Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : Vrai-Prix iOS9// File : VraiPrix/Core/Models/Market.swift10// Description : registre des ventes, municipalités, indice de marché,11// statistiques — miroir de /api/ventes,12// /api/ventes/overview, /api/municipalites, /api/indice,13// /api/stats, /api/stats/marche.14// Module : VraiPrix15// Repository : https://git.spboucher.ai/vrai-prix-ios-v316// Project Website : https://www.vrai-prix.com17// Created : 2026-11-2618// Last Modified : 2026-11-2619//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 CoreLocation93import Foundation9495// MARK: - Ventes9697struct Sale: Decodable, Sendable, Identifiable, Hashable {98 var id: String99 var date: String?100 var amount: Double?101 var street: String?102 var city: String?103 var propertyType: String?104 var yearBuilt: Int?105 var floorArea: Double?106 var landArea: Double?107 var idProvinc: String?108 var valeurRole: Double?109 var lat: Double?110 var lng: Double?111 var vsRolePct: Double?112 /// `unite` : l'adresse publiée est celle d'une seule unité du rôle · `immeuble` · `absente` · `aucun`113 var rattachement: String?114 var unitesAdresse: Int?115 var unitGenre: String?116 /// valeur de la fiche de l'unité rattachée (jamais donnée sans rattachement vérifié)117 var valeurEstimee: Double?118 var low: Double?119 var high: Double?120 var verdict: String?121 var ecartPct: Double?122 var dansFourchette: Bool?123124 private struct UnitRef: Decodable { var genre: String?; var genreLibelle: String? }125126 enum CodingKeys: String, CodingKey {127 case id, date, amount, street, city, propertyType, yearBuilt, floorArea, landArea, idProvinc, valeurRole, lat, lng, vsRolePct128 case rattachement, unitesAdresse, unit, valeurEstimee, low, high, verdict, ecartPct, dansFourchette129 }130131 init(from decoder: Decoder) throws {132 let c = try decoder.container(keyedBy: CodingKeys.self)133 id = c.str(.id) ?? UUID().uuidString134 date = c.text(.date); amount = c.dbl(.amount); street = c.text(.street); city = c.text(.city)135 propertyType = c.text(.propertyType); yearBuilt = c.int(.yearBuilt); floorArea = c.dbl(.floorArea)136 landArea = c.dbl(.landArea); idProvinc = c.text(.idProvinc); valeurRole = c.dbl(.valeurRole)137 lat = c.dbl(.lat); lng = c.dbl(.lng); vsRolePct = c.dbl(.vsRolePct)138 rattachement = c.text(.rattachement); unitesAdresse = c.int(.unitesAdresse)139 unitGenre = c.opt(.unit, UnitRef.self)?.genre140 valeurEstimee = c.dbl(.valeurEstimee); low = c.dbl(.low); high = c.dbl(.high)141 verdict = c.text(.verdict); ecartPct = c.dbl(.ecartPct); dansFourchette = c.bool(.dansFourchette)142 }143144 var coordinate: CLLocationCoordinate2D? {145 guard let lat, let lng, lat != 0, lng != 0 else { return nil }146 return .init(latitude: lat, longitude: lng)147 }148149 var title: String { Fmt.address(street) }150 /// lecture du prix vendu contre la valeur de la fiche, calculée par le service151 var reading: Reading? { Reading(verdict: verdict, ecartPct: ecartPct, dansFourchette: dansFourchette) }152 /// pourquoi la vente n'ouvre aucune fiche, dit simplement153 var unattachedNote: String? {154 guard idProvinc == nil else { return nil }155 switch rattachement {156 case "immeuble": return unitesAdresse.map { "immeuble de \($0) unités, unité non précisée" } ?? "immeuble, unité non précisée"157 case "absente": return "adresse absente du rôle"158 default: return "non rattachée à une unité du rôle"159 }160 }161}162163struct SalesPage: Decodable, Sendable {164 var source: String?165 var updatedTo: String?166 var total: Int167 var page: Int168 var pages: Int169 var limit: Int?170 var since: String?171 var rows: [Sale]172173 enum CodingKeys: String, CodingKey { case source, updatedTo, total, page, pages, limit, since, rows }174 init(from decoder: Decoder) throws {175 let c = try decoder.container(keyedBy: CodingKeys.self)176 source = c.text(.source); updatedTo = c.text(.updatedTo); total = c.int(.total) ?? 0177 page = c.int(.page) ?? 1; pages = c.int(.pages) ?? 1; limit = c.int(.limit); since = c.text(.since)178 rows = c.list(.rows)179 }180}181182struct SalesOverview: Decodable, Sendable {183 var maxDate: String?184 var n30: Int?185 var n90: Int?186 var n365: Int?187 var median30: Double?188 var byType30: [TypeMedian]?189190 struct TypeMedian: Decodable, Sendable, Hashable, Identifiable {191 var type: String192 var n: Int?193 var median: Double?194 var id: String { type }195 }196}197198/// Filtres du registre des ventes (mêmes paramètres que /api/ventes).199struct SaleFilters: Sendable, Hashable {200 enum Period: String, CaseIterable, Identifiable, Sendable {201 case d30 = "30", d90 = "90", d365 = "365", all202 var id: String { rawValue }203 var label: String {204 switch self {205 case .d30: "30 jours"206 case .d90: "90 jours"207 case .d365: "12 mois"208 case .all: "Depuis 2021"209 }210 }211 var long: String {212 switch self {213 case .d30: "30 derniers jours"214 case .d90: "90 derniers jours"215 case .d365: "12 derniers mois"216 case .all: "depuis 2021"217 }218 }219 }220221 var place = ""222 /// "" (tous), unifamilial, condo, plex, indéterminé223 var type = ""224 var min: Double?225 var max: Double?226 var period: Period = .d90227228 static let types: [(key: String, label: String)] = [("", "Tous"), ("unifamilial", "Unifamiliale"), ("condo", "Condo"), ("plex", "Plex"), ("indéterminé", "Autre")]229230 var query: [String: String?] {231 ["q": place.trimmingCharacters(in: .whitespaces), "type": type, "min": min.map { String(Int($0)) },232 "max": max.map { String(Int($0)) }, "periode": period.rawValue]233 }234235 /// nombre de filtres actifs hors période236 var activeCount: Int { (place.trimmingCharacters(in: .whitespaces).isEmpty ? 0 : 1) + (type.isEmpty ? 0 : 1) + (min == nil ? 0 : 1) + (max == nil ? 0 : 1) }237}238239// MARK: - Municipalités240241struct MunicipalityList: Decodable, Sendable {242 var total: Int?243 var municipalites: [Municipality]244 enum CodingKeys: String, CodingKey { case total, municipalites }245 init(from decoder: Decoder) throws {246 let c = try decoder.container(keyedBy: CodingKeys.self)247 total = c.int(.total); municipalites = c.list(.municipalites)248 }249}250251struct Municipality: Decodable, Sendable, Identifiable, Hashable {252 var nom: String253 var slug: String254 var n: Int?255 var lat: Double?256 var lng: Double?257 var id: String { slug }258259 /// clé de recherche sans accents ni casse260 var searchKey: String { nom.folding(options: [.diacriticInsensitive, .caseInsensitive], locale: Locale(identifier: "fr_CA")).lowercased() }261}262263struct MunicipalityDetail: Decodable, Sendable {264 var nom: String265 var slug: String266 var lat: Double?267 var lng: Double?268 var millesime: Int?269 var n: Int?270 var total2026: Double?271 var total2021: Double?272 var mediane2026: Double?273 var croissancePct: Double?274 var parType: [TypeRow]275 /// répartition par genre lu au rôle (à préférer à `parType`)276 var parGenre: [TypeRow]277 var ventes: Ventes?278 var voisines: [Municipality]279 var echantillon: [Sample]280 var links: Links?281282 struct TypeRow: Decodable, Sendable, Identifiable, Hashable {283 var type: String284 var slug: String?285 enum CodingKeys: String, CodingKey { case type, genre, slug, libelle, n, total2026, mediane2026 }286 init(from decoder: Decoder) throws {287 let c = try decoder.container(keyedBy: CodingKeys.self)288 type = c.text(.genre) ?? c.text(.type) ?? "autre"289 slug = c.text(.slug); libelle = c.text(.libelle); n = c.int(.n); total2026 = c.dbl(.total2026); mediane2026 = c.dbl(.mediane2026)290 }291 var libelle: String?292 var n: Int?293 var total2026: Double?294 var mediane2026: Double?295 var id: String { type }296 var label: String {297 guard let l = libelle, !l.isEmpty else { return PropType.label(type) }298 return l.prefix(1).uppercased() + l.dropFirst()299 }300 }301302 struct Ventes: Decodable, Sendable {303 var n365: Int?304 var median365: Double?305 var rows: [Sale]306 /// série mensuelle depuis 2021 (mois complets) : nombre de ventes et prix médian (nul sous 5 ventes)307 var parMois: [Month]308 struct Month: Decodable, Sendable, Hashable, Identifiable {309 var mois: String310 var n: Int?311 var mediane: Double?312 var id: String { mois }313 var date: Date { Fmt.monthDate(mois) ?? .distantPast }314 }315 enum CodingKeys: String, CodingKey { case n365, median365, rows, parMois }316 init(from decoder: Decoder) throws {317 let c = try decoder.container(keyedBy: CodingKeys.self)318 n365 = c.int(.n365); median365 = c.dbl(.median365); rows = c.list(.rows); parMois = c.list(.parMois)319 }320 }321322 struct Sample: Decodable, Sendable, Identifiable, Hashable {323 var id: String324 var adresse: String?325 var apt: String?326 var typeProp: String?327 var est2026: Double?328 var valeurEstimee: Double?329 var genre: String?330 var anneeConstruction: Int?331 var aireEtagesM2: Double?332 var value: Double? { valeurEstimee ?? est2026 }333 }334335 struct Links: Decodable, Sendable { var page: String? }336337 enum CodingKeys: String, CodingKey {338 case nom, slug, lat, lng, millesime, n, total2026, total2021, mediane2026, croissancePct, parType, parGenre, ventes, voisines, echantillon, links339 }340341 init(from decoder: Decoder) throws {342 let c = try decoder.container(keyedBy: CodingKeys.self)343 nom = c.text(.nom) ?? "Municipalité"; slug = c.text(.slug) ?? ""344 lat = c.dbl(.lat); lng = c.dbl(.lng); millesime = c.int(.millesime); n = c.int(.n)345 total2026 = c.dbl(.total2026); total2021 = c.dbl(.total2021); mediane2026 = c.dbl(.mediane2026)346 croissancePct = c.dbl(.croissancePct); parType = c.list(.parType); parGenre = c.list(.parGenre); ventes = c.opt(.ventes)347 voisines = c.list(.voisines); echantillon = c.list(.echantillon); links = c.opt(.links)348 }349}350351// MARK: - Indice de marché352353struct IndexResponse: Decodable, Sendable {354 var base: String?355 var types: [Summary]356 var series: [String: [IndexPoint]]357358 struct Summary: Decodable, Sendable, Identifiable, Hashable {359 var type: String360 var from: String?361 var to: String?362 var variation12mPct: Double?363 var variationDepuisDebutPct: Double?364 var ppm2: Double?365 var id: String { type }366 }367368 enum CodingKeys: String, CodingKey { case base, types, series }369 init(from decoder: Decoder) throws {370 let c = try decoder.container(keyedBy: CodingKeys.self)371 base = c.text(.base); types = c.list(.types)372 var out: [String: [IndexPoint]] = [:]373 if let s = try? c.nestedContainer(keyedBy: AnyKey.self, forKey: .series) {374 for k in s.allKeys { out[k.stringValue] = s.list(k) }375 }376 series = out377 }378379 /// ordre d'affichage : unifamiliale, condo, plex, autre380 static let order = ["unifamilial", "condo", "plex", "indéterminé"]381 var orderedTypes: [Summary] {382 types.sorted { (IndexResponse.order.firstIndex(of: $0.type) ?? 9) < (IndexResponse.order.firstIndex(of: $1.type) ?? 9) }383 }384}385386// MARK: - Statistiques387388/// GET /api/stats : chiffres de tête du parc.389struct ParkStats: Decodable, Sendable {390 var units_total: Int?391 var value_total_2026: Double?392 var value_median_2026: Double?393 var growth_2021_2026_pct: Double?394 var dwellings: Int?395 var municipalities: Int?396 var transactions: Int?397 /// nombre de ventes au registre, en direct (les autres chiffres sont figés au dernier calcul provincial)398 var transactions_total: Int?399 var model_version: String?400 var updated: String?401402 var sales: Int? { transactions_total ?? transactions }403}404405/// GET /api/stats/marche : le moteur confronté aux propriétés réellement à vendre.406struct MarketTest: Decodable, Sendable {407 var generated: String?408 var source: Source?409 var global: Row?410 var methods: [Method]411 var byConfidence: [Row]412 var byType: [Row]413 var byRegion: [Row]414 var byCity: [Row]415 var byBracket: [Row]416 var histogram: Histogram?417418 struct Source: Decodable, Sendable {419 var totalListings: Int?420 var geolocated: Int?421 var evaluated: Int?422 var valid: Int?423 var matchMedianM: Double?424 var copiedAt: String?425 }426427 struct Row: Decodable, Sendable, Identifiable, Hashable {428 var key: String?429 var n: Int?430 var medianRatio: Double?431 var mdape: Double?432 var within10: Double?433 var within20: Double?434 var askAbove: Double?435 var inP10P90: Double?436 var medianAsk: Double?437 var medianEst: Double?438 var medianDiff: Double?439 var medianDiffPct: Double?440 var id: String { key ?? "global" }441 }442443 struct Method: Decodable, Sendable, Identifiable, Hashable {444 var key: String445 var main: Bool?446 var n: Int?447 var coverage: Double?448 var medianRatio: Double?449 var mdape: Double?450 var within10: Double?451 var within20: Double?452 var medianDiff: Double?453 var id: String { key }454 var label: String {455 switch key {456 case "hybride": "Estimation Vrai-Prix"457 case "hedonique": "Modèle statistique"458 case "comparables": "Ventes comparables"459 case "cout": "Méthode du coût"460 case "role_indexe": "Rôle indexé"461 case "ensemble": "Ensemble"462 default: key.prefix(1).uppercased() + key.dropFirst()463 }464 }465 }466467 struct Histogram: Decodable, Sendable {468 var below: Int?469 var above: Int?470 var bins: [Bin]471 struct Bin: Decodable, Sendable, Hashable, Identifiable {472 var lo: Double473 var hi: Double474 var n: Int475 var id: Double { lo }476 }477 enum CodingKeys: String, CodingKey { case below, above, bins }478 init(from decoder: Decoder) throws {479 let c = try decoder.container(keyedBy: CodingKeys.self)480 below = c.int(.below); above = c.int(.above); bins = c.list(.bins)481 }482 }483484 enum CodingKeys: String, CodingKey { case generated, source, global, methods, byConfidence, byType, byRegion, byCity, byBracket, histogram }485 init(from decoder: Decoder) throws {486 let c = try decoder.container(keyedBy: CodingKeys.self)487 generated = c.text(.generated); source = c.opt(.source); global = c.opt(.global); methods = c.list(.methods)488 byConfidence = c.list(.byConfidence); byType = c.list(.byType); byRegion = c.list(.byRegion)489 byCity = c.list(.byCity); byBracket = c.list(.byBracket); histogram = c.opt(.histogram)490 }491}492