Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : Vrai-Prix iOS9// File : Shared/VraiPrixShared.swift10// Description : ce que l'app, ses raccourcis et ses widgets partagent :11// lecture directe du service (API v3 quand elle est servie,12// sinon les mêmes chiffres par l'API 2), entité «13// municipalité », formats. Aucun stockage partagé : widgets14// et raccourcis lisent le service public, rien de15// l'appareil.16// Module : Shared17// Repository : https://git.spboucher.ai/vrai-prix-ios-v318// Project Website : https://www.vrai-prix.com19// Created : 2026-11-2820// Last Modified : 2026-11-2821//22// =============================================================================23// AUTHOR & PROFESSIONAL AFFILIATION24// =============================================================================25//26// Author : Simon-Pierre Boucher27// Position : Professor of Finance28// Institution : Université du Québec en Outaouais (UQO)29// Department : Département des sciences administratives30// Organization : SP Boucher31//32// Website : https://spboucher.ai33// Git : https://git.spboucher.ai34//35// =============================================================================36// OFFICIAL CONTACT DIRECTORY37// =============================================================================38//39// General : info@spboucher.ai40// Professional : contact@spboucher.ai41// Direct : simon@spboucher.ai42// Research : research@spboucher.ai43// Development : dev@spboucher.ai44// Support : support@spboucher.ai45// Security/Admin : admin@spboucher.ai46// Notifications : notifications@spboucher.ai47//48// Preferred Contact: support@spboucher.ai49//50// =============================================================================51// COPYRIGHT & INTELLECTUAL PROPERTY52// =============================================================================53//54// Copyright (c) 202655// Simon-Pierre Boucher56//57// All rights reserved where applicable.58//59// This file is governed by the applicable project license,60// copyright notices, institutional agreements and relevant law.61//62// Unless expressly authorized by the applicable license or63// rights holder, copying, redistribution, sublicensing,64// publication and commercial exploitation are not permitted.65//66// Existing third-party rights and notices remain unaffected.67//68// =============================================================================69// CONFIDENTIALITY & SECURITY70// =============================================================================71//72// Classification : Public73// Distribution : Public repository; use is governed by the project license74// Security Contact : admin@spboucher.ai75//76// Access to this source does not independently grant permission77// to redistribute or disclose confidential materials.78//79// Do not embed credentials, private keys, access tokens,80// certificates or confidential personal information.81//82// =============================================================================83// LICENSE & MAINTENANCE84// =============================================================================85//86// License : None specified (no license file in this repository)87// Maintainer : Simon-Pierre Boucher88// Technical Contact: dev@spboucher.ai89//90// =============================================================================91// END OF SP BOUCHER SOURCE HEADER92// =============================================================================9394import AppIntents95import Foundation9697enum SharedFmt {98 static let locale = Locale(identifier: "fr_CA")99 static func int(_ n: Int) -> String { n.formatted(.number.locale(locale).grouping(.automatic)) }100 static func money(_ d: Double?) -> String { d.map { "\(int(Int($0.rounded()))) $" } ?? "—" }101 /// « 450 k$ », « 1,25 M$ »102 static func compact(_ d: Double?) -> String {103 guard let d else { return "—" }104 if d >= 1_000_000 { return (d / 1_000_000).formatted(.number.precision(.fractionLength(0...2)).locale(locale)) + " M$" }105 return int(Int((d / 1000).rounded())) + " k$"106 }107 static func points(_ x: Double) -> String {108 let v = abs(x).formatted(.number.precision(.fractionLength(1)).locale(locale))109 return "\(abs(x) < 0.05 ? "" : x > 0 ? "+" : "−")\(v) %"110 }111 static func day(iso: String?) -> String? {112 guard let p = iso?.prefix(10).split(separator: "-").compactMap({ Int($0) }), p.count == 3 else { return nil }113 var c = DateComponents(); c.year = p[0]; c.month = p[1]; c.day = p[2]114 return Calendar(identifier: .gregorian).date(from: c)?.formatted(.dateTime.day().month(.abbreviated).locale(locale))115 }116}117118enum SharedAPI {119 static let site = URL(string: "https://www.vrai-prix.com")!120121 struct PlaceRef: Sendable, Hashable {122 var slug: String123 var name: String124 var units: Int?125 }126127 struct RecentSale: Sendable, Hashable, Identifiable {128 var id: String129 var price: Double?130 var street: String131 var city: String132 var date: String?133 var propertyID: String?134 /// la fiche de la propriété vendue si le registre la désigne ; sinon l'onglet Ventes135 var url: URL {136 if let p = propertyID { return URL(string: "vraiprix://propriete/" + p) ?? URL(string: "vraiprix://ventes")! }137 return URL(string: "vraiprix://ventes")!138 }139 }140141 struct RecentSales: Sendable {142 var items: [RecentSale]143 /// vrai : seules les ventes que le moteur qualifie de marché (API v3)144 var marketOnly: Bool145 var updatedTo: String?146 }147148 struct MarketBrief: Sendable {149 var placeName: String150 /// ventes des douze derniers mois et leur prix payé médian (nul sous le seuil de publication)151 var sales: Int?152 var medianPaid: Double?153 /// valeur estimée médiane des propriétés154 var medianValue: Double?155 /// variation sur un an de l'indice des prix de vente des maisons, et le territoire qui porte la série156 var indexChangePct: Double?157 var indexPlace: String?158 var indexPeriod: String?159 /// fenêtre des ventes comptées : « 12 mois », ou « 30 jours » quand le service ne publie que celle-là160 var window = "12 mois"161 var windowLong: String { window == "12 mois" ? "des douze derniers mois" : "des trente derniers jours" }162 }163164 static func json(_ path: String, _ query: [String: String?] = [:]) async throws -> [String: Any] {165 var comps = URLComponents(url: site.appending(path: path), resolvingAgainstBaseURL: false)!166 let items = query.compactMap { k, v in v.map { URLQueryItem(name: k, value: $0) } }.sorted { $0.name < $1.name }167 if !items.isEmpty { comps.queryItems = items }168 var req = URLRequest(url: comps.url!)169 req.timeoutInterval = 15170 req.setValue("application/json", forHTTPHeaderField: "Accept")171 let (data, resp) = try await URLSession.shared.data(for: req)172 guard (resp as? HTTPURLResponse)?.statusCode == 200, let o = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else {173 throw URLError(.badServerResponse)174 }175 return o176 }177178 /// Le service sert-il l'API v3 avec un moteur lisible ? (la page HTML du site tant qu'elle n'existe pas : non)179 static func servesV3() async -> Bool {180 guard let o = try? await json("api/v3/version"), (o["api"] as? Int) == 3 else { return false }181 return ((o["engine"] as? [String: Any])?["routes_available"] as? Bool) ?? false182 }183184 static func num(_ v: Any?) -> Double? { (v as? Double) ?? (v as? Int).map(Double.init) }185186 // MARK: Municipalités187188 static func municipalities(matching q: String?) async throws -> [PlaceRef] {189 let o = try await json("api/municipalites")190 let all = ((o["municipalites"] as? [[String: Any]]) ?? []).compactMap { m -> PlaceRef? in191 guard let slug = m["slug"] as? String, let nom = m["nom"] as? String else { return nil }192 return PlaceRef(slug: slug, name: nom, units: m["n"] as? Int)193 }194 guard let q, !q.trimmingCharacters(in: .whitespaces).isEmpty else { return all }195 let key = { (s: String) in s.folding(options: [.diacriticInsensitive, .caseInsensitive], locale: locale).lowercased() }196 let k = key(q.trimmingCharacters(in: .whitespaces))197 return all.filter { let n = key($0.name); return n.hasPrefix(k) || n.contains(" " + k) || n.contains("-" + k) }198 }199 private static let locale = Locale(identifier: "fr_CA")200201 // MARK: Ventes récentes202203 static func recentSales(place: PlaceRef?, limit: Int = 6) async throws -> RecentSales {204 if await servesV3() {205 let o = try await json("api/v3/ventes", ["q": place?.name, "periode": "90", "marche": "1", "limit": String(limit)])206 let items = ((o["items"] as? [[String: Any]]) ?? []).compactMap { s -> RecentSale? in207 guard let id = s["id"] as? String else { return nil }208 return RecentSale(id: id, price: num(s["prix_vente"]), street: (s["rue"] as? String) ?? "", city: (s["ville"] as? String) ?? "",209 date: s["date"] as? String, propertyID: s["propriete_id"] as? String)210 }211 return RecentSales(items: items, marketOnly: true, updatedTo: o["updated_to"] as? String)212 }213 let rows: [[String: Any]]214 var updated: String?215 if let place {216 let o = try await json("api/municipalites/" + place.slug, ["ventes": String(limit), "echantillon": "1"])217 rows = ((o["ventes"] as? [String: Any])?["rows"] as? [[String: Any]]) ?? []218 } else {219 let o = try await json("api/ventes", ["periode": "90", "limit": String(limit)])220 rows = (o["rows"] as? [[String: Any]]) ?? []221 updated = o["updatedTo"] as? String222 }223 let items = rows.prefix(limit).compactMap { s -> RecentSale? in224 guard let id = s["id"] as? String else { return nil }225 return RecentSale(id: id, price: num(s["amount"]), street: (s["street"] as? String) ?? "", city: (s["city"] as? String) ?? "",226 date: s["date"] as? String, propertyID: s["idProvinc"] as? String)227 }228 return RecentSales(items: items, marketOnly: false, updatedTo: updated ?? items.first?.date)229 }230231 // MARK: Marché d'un lieu232233 static func market(place: PlaceRef?) async throws -> MarketBrief {234 if await servesV3() {235 let o = try await json("api/v3/territoires/" + (place?.slug ?? "qc"))236 let t = (o["territoire"] as? [String: Any]) ?? [:]237 let v = (o["ventes_12_mois"] as? [String: Any]) ?? [:]238 let idx = ((o["indice"] as? [String: Any])?["maison"] as? [String: Any]) ?? [:]239 let propre = (idx["propre"] as? Bool) ?? true240 return MarketBrief(placeName: (t["nom"] as? String) ?? place?.name ?? "Québec", sales: v["n"] as? Int, medianPaid: num(v["prix_median"]),241 medianValue: num((o["valeurs"] as? [String: Any])?["mediane"]), indexChangePct: num(idx["var_an_pct"]),242 indexPlace: propre ? nil : (idx["territoire"] as? [String: Any])?["nom"] as? String, indexPeriod: idx["periode"] as? String)243 }244 if let place {245 let o = try await json("api/municipalites/" + place.slug, ["ventes": "1", "echantillon": "1"])246 let v = (o["ventes"] as? [String: Any]) ?? [:]247 return MarketBrief(placeName: (o["nom"] as? String) ?? place.name, sales: v["n365"] as? Int, medianPaid: num(v["median365"]),248 medianValue: num(o["mediane2026"]), indexChangePct: nil, indexPlace: nil, indexPeriod: nil)249 }250 let o = try await json("api/ventes/overview")251 // l'API 2 ne publie le prix payé médian de la province que sur trente jours252 return MarketBrief(placeName: "Québec", sales: o["n30"] as? Int, medianPaid: num(o["median30"]), medianValue: nil,253 indexChangePct: nil, indexPlace: nil, indexPeriod: nil, window: "30 jours")254 }255}256257// MARK: - Entité : municipalité258259/// Municipalité choisie dans un widget ou un raccourci. L'identifiant porte le slug et le nom : il se résout sans réseau.260struct PlaceEntity: AppEntity, Hashable {261 static let typeDisplayRepresentation = TypeDisplayRepresentation(name: "Municipalité")262 static let defaultQuery = PlaceQuery()263264 var id: String265 var name: String266 var slug: String267268 init(_ p: SharedAPI.PlaceRef) { name = p.name; slug = p.slug; id = p.slug + "|" + p.name }269270 init?(id: String) {271 let parts = id.split(separator: "|", maxSplits: 1, omittingEmptySubsequences: false).map(String.init)272 guard parts.count == 2, !parts[0].isEmpty else { return nil }273 self.id = id; slug = parts[0]; name = parts[1]274 }275276 var ref: SharedAPI.PlaceRef { .init(slug: slug, name: name, units: nil) }277 var displayRepresentation: DisplayRepresentation { DisplayRepresentation(title: "\(name)") }278}279280struct PlaceQuery: EntityStringQuery {281 func entities(for identifiers: [String]) async throws -> [PlaceEntity] { identifiers.compactMap(PlaceEntity.init(id:)) }282 func entities(matching string: String) async throws -> [PlaceEntity] { try await SharedAPI.municipalities(matching: string).prefix(20).map(PlaceEntity.init) }283 /// les municipalités les plus peuplées d'abord (ordre du service)284 func suggestedEntities() async throws -> [PlaceEntity] { try await SharedAPI.municipalities(matching: nil).prefix(20).map(PlaceEntity.init) }285}286287// MARK: - Configuration des widgets288289struct RecentSalesConfiguration: WidgetConfigurationIntent {290 static let title: LocalizedStringResource = "Ventes récentes"291 static let description = IntentDescription("Les dernières ventes publiées au registre, dans la municipalité de votre choix. Des prix de vente réels.")292 @Parameter(title: "Municipalité") var place: PlaceEntity?293}294295struct LocalMarketConfiguration: WidgetConfigurationIntent {296 static let title: LocalizedStringResource = "Marché local"297 static let description = IntentDescription("Le prix payé médian des douze derniers mois dans une municipalité, et la variation de l'indice des prix de vente.")298 @Parameter(title: "Municipalité") var place: PlaceEntity?299}300