SPB Git

Repository Public

Intents.swift 10.5 KB 223 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : Lou-Ka iOS9// File             : LouKa/Core/System/Intents.swift10// Description      : App Intents et raccourcis Siri — chercher un logement par11//                    une phrase, connaître le loyer médian d'un lieu, compter12//                    les nouvelles annonces, ouvrir le marché. Les réponses13//                    viennent de l'API ; la phrase est interprétée par le14//                    serveur de Lou-Ka, sans service externe.15// Module           : LouKa16// Repository       : https://git.spboucher.ai/lou-ka-ios-v317// Project Website  : https://www.lou-ka.com18// Created          : 2026-11-2819// Last Modified    : 2026-11-2820//21// =============================================================================22// AUTHOR & PROFESSIONAL AFFILIATION23// =============================================================================24//25// Author           : Simon-Pierre Boucher26// Position         : Professor of Finance27// Institution      : Université du Québec en Outaouais (UQO)28// Department       : Département des sciences administratives29// Organization     : SP Boucher30//31// Website          : https://spboucher.ai32// Git              : https://git.spboucher.ai33//34// =============================================================================35// OFFICIAL CONTACT DIRECTORY36// =============================================================================37//38// General          : info@spboucher.ai39// Professional     : contact@spboucher.ai40// Direct           : simon@spboucher.ai41// Research         : research@spboucher.ai42// Development      : dev@spboucher.ai43// Support          : support@spboucher.ai44// Security/Admin   : admin@spboucher.ai45// Notifications    : notifications@spboucher.ai46//47// Preferred Contact: support@spboucher.ai48//49// =============================================================================50// COPYRIGHT & INTELLECTUAL PROPERTY51// =============================================================================52//53// Copyright (c) 202654// Simon-Pierre Boucher55//56// All rights reserved where applicable.57//58// This file is governed by the applicable project license,59// copyright notices, institutional agreements and relevant law.60//61// Unless expressly authorized by the applicable license or62// rights holder, copying, redistribution, sublicensing,63// publication and commercial exploitation are not permitted.64//65// Existing third-party rights and notices remain unaffected.66//67// =============================================================================68// CONFIDENTIALITY & SECURITY69// =============================================================================70//71// Classification   : Public72// Distribution     : Public repository; use is governed by the project license73// Security Contact : admin@spboucher.ai74//75// Access to this source does not independently grant permission76// to redistribute or disclose confidential materials.77//78// Do not embed credentials, private keys, access tokens,79// certificates or confidential personal information.80//81// =============================================================================82// LICENSE & MAINTENANCE83// =============================================================================84//85// License          : None specified (no license file in this repository)86// Maintainer       : Simon-Pierre Boucher87// Technical Contact: dev@spboucher.ai88//89// =============================================================================90// END OF SP BOUCHER SOURCE HEADER91// =============================================================================9293import AppIntents94import Foundation9596/// Destination demandée par un raccourci, remise à l'app à son ouverture.97@MainActor98final class IntentRouter {99    static let shared = IntentRouter()100    private(set) var pending: URL?101    var onURL: ((URL) -> Void)?102103    func route(_ url: URL) {104        if let onURL { onURL(url) } else { pending = url }105    }106107    func attach(_ handler: @escaping (URL) -> Void) {108        onURL = handler109        if let p = pending { pending = nil; handler(p) }110    }111112    /// `louka://recherche?nl=…` pour une phrase libre (logique pure, testée).113    nonisolated static func searchURL(phrase: String) -> URL {114        var c = URLComponents(string: "louka://recherche")!115        c.queryItems = [URLQueryItem(name: "nl", value: phrase)]116        return c.url ?? URL(string: "louka://recherche")!117    }118119    nonisolated static func searchURL(place: SharedAPI.PlaceRef?, rooms: Int?, newDays: Int? = nil) -> URL {120        var c = URLComponents(string: "louka://recherche")!121        var q = SharedAPI.searchParams(place).compactMap { k, v in v.map { URLQueryItem(name: k, value: $0) } }.sorted { $0.name < $1.name }122        if let rooms { q.append(URLQueryItem(name: "rooms", value: String(rooms))) }123        if let newDays { q += [URLQueryItem(name: "new_days", value: String(newDays)), URLQueryItem(name: "sort", value: "recent")] }124        c.queryItems = q.isEmpty ? nil : q125        return c.url ?? URL(string: "louka://recherche")!126    }127}128129struct SearchListingsIntent: AppIntent {130    static let title: LocalizedStringResource = "Chercher un logement"131    static let description = IntentDescription("Ouvre la carte de Lou-Ka sur une recherche décrite en une phrase, par exemple « 4½ à Rosemont sous 1 800 $ avec balcon ».")132    static let openAppWhenRun = true133134    @Parameter(title: "Recherche", requestValueDialog: "Quel logement cherchez-vous ?")135    var phrase: String136137    static var parameterSummary: some ParameterSummary { Summary("Chercher \(\.$phrase) dans Lou-Ka") }138139    @MainActor140    func perform() async throws -> some IntentResult {141        IntentRouter.shared.route(IntentRouter.searchURL(phrase: phrase))142        return .result()143    }144}145146struct MedianRentIntent: AppIntent {147    static let title: LocalizedStringResource = "Loyer médian d'un lieu"148    static let description = IntentDescription("Donne le loyer affiché médian d'une ville ou d'un quartier, et sa variation d'un mois à l'autre à sources constantes.")149150    @Parameter(title: "Lieu") var place: PlaceEntity?151152    static var parameterSummary: some ParameterSummary { Summary("Loyer médian à \(\.$place)") }153154    func perform() async throws -> some IntentResult & ProvidesDialog & ReturnsValue<Double?> {155        let m = try await SharedAPI.market(place: place?.ref)156        guard let median = m.median else {157            return .result(value: nil, dialog: "Lou-Ka n'a pas assez d'annonces à \(m.placeName) pour publier un loyer médian.")158        }159        var text = "À \(m.placeName), le loyer affiché médian est de \(SharedFmt.money(median))"160        if let a = m.active { text += ", sur \(SharedFmt.int(a)) annonces" }161        if let c = m.changePct, let a = m.previousMonth, let b = m.currentMonth {162            text += abs(c) < 0.05 ? ". Stable de \(a) à \(b), à sources constantes" : ". \(c > 0 ? "En hausse" : "En baisse") de \(SharedFmt.points(abs(c)).replacingOccurrences(of: "+", with: "")) de \(a) à \(b), à sources constantes"163        }164        return .result(value: median, dialog: "\(text). Ce sont des loyers demandés, pas des loyers signés.")165    }166}167168struct NewListingsCountIntent: AppIntent {169    static let title: LocalizedStringResource = "Nouvelles annonces"170    static let description = IntentDescription("Compte les logements vus pour la première fois depuis trois jours dans un lieu, et peut les ouvrir sur la carte.")171172    @Parameter(title: "Lieu") var place: PlaceEntity?173    @Parameter(title: "Grandeur") var rooms: RoomsOption?174    @Parameter(title: "Ouvrir la carte", default: false) var open: Bool175176    static var parameterSummary: some ParameterSummary {177        Summary("Nouvelles annonces à \(\.$place)") { \.$rooms; \.$open }178    }179180    func perform() async throws -> some IntentResult & ProvidesDialog & ReturnsValue<Int> {181        let r = try await SharedAPI.newListings(place: place?.ref, rooms: rooms?.rooms, limit: 3)182        let whereText = place.map { "à \($0.name)" } ?? "au Québec"183        let what = rooms.map { " de grandeur \($0.label)" } ?? ""184        var text = r.total == 0 ? "Aucun logement\(what) vu pour la première fois \(whereText) depuis trois jours"185            : "\(SharedFmt.int(r.total)) \(r.total > 1 ? "logements" : "logement")\(what) \(r.total > 1 ? "vus" : "vu") pour la première fois \(whereText) depuis trois jours"186        if let f = r.items.first, let p = f.price { text += ". Le plus récent : \(SharedFmt.money(p)), \(f.unit), \(f.place)" }187        if open {188            let url = IntentRouter.searchURL(place: place?.ref, rooms: rooms?.rooms, newDays: 3)189            await MainActor.run { IntentRouter.shared.route(url) }190        }191        return .result(value: r.total, dialog: "\(text).")192    }193}194195struct OpenMarketIntent: AppIntent {196    static let title: LocalizedStringResource = "Ouvrir le marché locatif"197    static let description = IntentDescription("Ouvre le portrait du marché locatif affiché dans Lou-Ka.")198    static let openAppWhenRun = true199200    @MainActor201    func perform() async throws -> some IntentResult {202        IntentRouter.shared.route(URL(string: "louka://marche")!)203        return .result()204    }205}206207struct LouKaShortcuts: AppShortcutsProvider {208    static var appShortcuts: [AppShortcut] {209        AppShortcut(intent: SearchListingsIntent(),210                    phrases: ["Chercher un logement avec \(.applicationName)", "Chercher un logement dans \(.applicationName)", "Trouver un logement avec \(.applicationName)"],211                    shortTitle: "Chercher un logement", systemImageName: "magnifyingglass")212        AppShortcut(intent: NewListingsCountIntent(),213                    phrases: ["Nouvelles annonces dans \(.applicationName)", "Quoi de neuf dans \(.applicationName)"],214                    shortTitle: "Nouvelles annonces", systemImageName: "sparkle")215        AppShortcut(intent: MedianRentIntent(),216                    phrases: ["Loyer médian avec \(.applicationName)", "Combien coûtent les loyers selon \(.applicationName)"],217                    shortTitle: "Loyer médian", systemImageName: "chart.bar")218        AppShortcut(intent: OpenMarketIntent(),219                    phrases: ["Ouvrir le marché dans \(.applicationName)"],220                    shortTitle: "Marché locatif", systemImageName: "chart.line.uptrend.xyaxis")221    }222}223
Files main
Menu

Theme