SPB Git

Repository Public

Intents.swift 9.9 KB 213 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : Vrai-Prix iOS9// File             : VraiPrix/Core/System/Intents.swift10// Description      : raccourcis (App Intents, Siri, Spotlight) : estimer une11//                    adresse, le marché d'une municipalité, les ventes12//                    récentes, ouvrir le marché. Les réponses parlées citent13//                    des chiffres du service et leur nature.14// Module           : VraiPrix15// Repository       : https://git.spboucher.ai/vrai-prix-ios-v316// Project Website  : https://www.vrai-prix.com17// Created          : 2026-11-2818// Last Modified    : 2026-11-2819//20// =============================================================================21// AUTHOR & PROFESSIONAL AFFILIATION22// =============================================================================23//24// Author           : Simon-Pierre Boucher25// Position         : Professor of Finance26// Institution      : Université du Québec en Outaouais (UQO)27// Department       : Département des sciences administratives28// Organization     : SP Boucher29//30// Website          : https://spboucher.ai31// Git              : https://git.spboucher.ai32//33// =============================================================================34// OFFICIAL CONTACT DIRECTORY35// =============================================================================36//37// General          : info@spboucher.ai38// Professional     : contact@spboucher.ai39// Direct           : simon@spboucher.ai40// Research         : research@spboucher.ai41// Development      : dev@spboucher.ai42// Support          : support@spboucher.ai43// Security/Admin   : admin@spboucher.ai44// Notifications    : notifications@spboucher.ai45//46// Preferred Contact: support@spboucher.ai47//48// =============================================================================49// COPYRIGHT & INTELLECTUAL PROPERTY50// =============================================================================51//52// Copyright (c) 202653// Simon-Pierre Boucher54//55// All rights reserved where applicable.56//57// This file is governed by the applicable project license,58// copyright notices, institutional agreements and relevant law.59//60// Unless expressly authorized by the applicable license or61// rights holder, copying, redistribution, sublicensing,62// publication and commercial exploitation are not permitted.63//64// Existing third-party rights and notices remain unaffected.65//66// =============================================================================67// CONFIDENTIALITY & SECURITY68// =============================================================================69//70// Classification   : Public71// Distribution     : Public repository; use is governed by the project license72// Security Contact : admin@spboucher.ai73//74// Access to this source does not independently grant permission75// to redistribute or disclose confidential materials.76//77// Do not embed credentials, private keys, access tokens,78// certificates or confidential personal information.79//80// =============================================================================81// LICENSE & MAINTENANCE82// =============================================================================83//84// License          : None specified (no license file in this repository)85// Maintainer       : Simon-Pierre Boucher86// Technical Contact: dev@spboucher.ai87//88// =============================================================================89// END OF SP BOUCHER SOURCE HEADER90// =============================================================================9192import AppIntents93import Foundation9495/// Passe une adresse `vraiprix://…` du raccourci à l'app (qui peut ne pas être encore lancée).96@MainActor97final class IntentRouter {98    static let shared = IntentRouter()99    private(set) var pending: URL?100    var onURL: ((URL) -> Void)?101102    func route(_ url: URL) {103        if let onURL { onURL(url) } else { pending = url }104    }105106    func attach(_ handler: @escaping (URL) -> Void) {107        onURL = handler108        if let p = pending { pending = nil; handler(p) }109    }110111    nonisolated static func searchURL(_ phrase: String) -> URL {112        var c = URLComponents(string: "vraiprix://recherche")!113        c.queryItems = [URLQueryItem(name: "q", value: phrase)]114        return c.url ?? URL(string: "vraiprix://recherche")!115    }116}117118struct EstimateAddressIntent: AppIntent {119    static let title: LocalizedStringResource = "Estimer une adresse"120    static let description = IntentDescription("Ouvre Vrai-Prix sur la recherche d'une adresse du rôle d'évaluation, par exemple « 13435 rue Marianne, Québec ».")121    static let openAppWhenRun = true122123    @Parameter(title: "Adresse", requestValueDialog: "Quelle adresse voulez-vous estimer ?")124    var address: String125126    static var parameterSummary: some ParameterSummary { Summary("Estimer \(\.$address) dans Vrai-Prix") }127128    @MainActor129    func perform() async throws -> some IntentResult {130        IntentRouter.shared.route(IntentRouter.searchURL(address))131        return .result()132    }133}134135struct LocalMarketIntent: AppIntent {136    static let title: LocalizedStringResource = "Marché d'une municipalité"137    static let description = IntentDescription("Donne le prix payé médian des douze derniers mois dans une municipalité et, quand elle est publiée, la variation de l'indice des prix de vente.")138139    @Parameter(title: "Municipalité") var place: PlaceEntity?140141    static var parameterSummary: some ParameterSummary { Summary("Marché de \(\.$place)") }142143    func perform() async throws -> some IntentResult & ProvidesDialog & ReturnsValue<Double?> {144        let m = try await SharedAPI.market(place: place?.ref)145        guard let median = m.medianPaid else {146            return .result(value: nil, dialog: "Vrai-Prix n'a pas assez de ventes à \(m.placeName) pour publier un prix payé médian.")147        }148        var text = "\(m.placeName == "Québec" && place == nil ? "Au Québec" : "À \(m.placeName)"), le prix payé médian \(m.windowLong) est de \(SharedFmt.money(median))"149        if let n = m.sales { text += ", sur \(SharedFmt.int(n)) ventes" }150        if let c = m.indexChangePct {151            let whose = m.indexPlace.map { " (indice de \($0))" } ?? ""152            text += abs(c) < 0.05 ? ". L'indice des prix de vente des maisons est stable sur un an\(whose)"153                : ". L'indice des prix de vente des maisons \(c > 0 ? "a monté" : "a baissé") de \(SharedFmt.points(abs(c)).replacingOccurrences(of: "+", with: "")) sur un an\(whose)"154        }155        return .result(value: median, dialog: "\(text). Ce sont des prix de vente réels, pas des prix demandés.")156    }157}158159struct RecentSalesIntent: AppIntent {160    static let title: LocalizedStringResource = "Ventes récentes"161    static let description = IntentDescription("Lit les dernières ventes publiées au registre dans une municipalité, et peut ouvrir le registre.")162163    @Parameter(title: "Municipalité") var place: PlaceEntity?164    @Parameter(title: "Ouvrir le registre", default: false) var open: Bool165166    static var parameterSummary: some ParameterSummary { Summary("Ventes récentes à \(\.$place)") { \.$open } }167168    func perform() async throws -> some IntentResult & ProvidesDialog & ReturnsValue<Int> {169        let r = try await SharedAPI.recentSales(place: place?.ref, limit: 3)170        let whereText = place.map { "à \($0.name)" } ?? "au Québec"171        var text: String172        if let f = r.items.first {173            text = "Dernière vente publiée \(whereText) : \(SharedFmt.money(f.price)), \(f.street)" + (SharedFmt.day(iso: f.date).map { ", le \($0)" } ?? "")174            if r.items.count > 1 {175                text += ". Avant elle : " + r.items.dropFirst().map { "\(SharedFmt.money($0.price)), \($0.street)" }.joined(separator: " ; ")176            }177        } else {178            text = "Aucune vente publiée \(whereText) depuis 90 jours"179        }180        if open { await MainActor.run { IntentRouter.shared.route(URL(string: "vraiprix://ventes")!) } }181        return .result(value: r.items.count, dialog: "\(text). Ce sont des prix de vente réels.")182    }183}184185struct OpenMarketIntent: AppIntent {186    static let title: LocalizedStringResource = "Ouvrir le marché"187    static let description = IntentDescription("Ouvre l'onglet Marché de Vrai-Prix : ventes réelles, prix demandés, indice des prix de vente.")188    static let openAppWhenRun = true189190    @MainActor191    func perform() async throws -> some IntentResult {192        IntentRouter.shared.route(URL(string: "vraiprix://marche")!)193        return .result()194    }195}196197struct VraiPrixShortcuts: AppShortcutsProvider {198    static var appShortcuts: [AppShortcut] {199        AppShortcut(intent: EstimateAddressIntent(),200                    phrases: ["Estimer une adresse avec \(.applicationName)", "Estimer une propriété avec \(.applicationName)", "Chercher une adresse dans \(.applicationName)"],201                    shortTitle: "Estimer une adresse", systemImageName: "magnifyingglass")202        AppShortcut(intent: RecentSalesIntent(),203                    phrases: ["Ventes récentes dans \(.applicationName)", "Dernières ventes selon \(.applicationName)"],204                    shortTitle: "Ventes récentes", systemImageName: "list.bullet.rectangle")205        AppShortcut(intent: LocalMarketIntent(),206                    phrases: ["Marché d'une municipalité avec \(.applicationName)", "Prix médian selon \(.applicationName)"],207                    shortTitle: "Marché d'une municipalité", systemImageName: "chart.bar")208        AppShortcut(intent: OpenMarketIntent(),209                    phrases: ["Ouvrir le marché dans \(.applicationName)"],210                    shortTitle: "Marché", systemImageName: "chart.xyaxis.line")211    }212}213
Files main
Menu

Theme