SPB Git

Repository Public

Unit.swift 15.9 KB 431 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : Vrai-Prix iOS9// File             : VraiPrix/Core/Models/Unit.swift10// Description      : unité d'évaluation du rôle, son estimation, ses11//                    comparables, son contexte — miroir de GET /api/units/{id},12//                    GET /api/search, POST /api/estimate.13// Module           : VraiPrix14// Repository       : https://git.spboucher.ai/vrai-prix-ios-v315// Project Website  : https://www.vrai-prix.com16// Created          : 2026-11-2617// Last Modified    : 2026-11-2618//19// =============================================================================20// AUTHOR & PROFESSIONAL AFFILIATION21// =============================================================================22//23// Author           : Simon-Pierre Boucher24// Position         : Professor of Finance25// Institution      : Université du Québec en Outaouais (UQO)26// Department       : Département des sciences administratives27// Organization     : SP Boucher28//29// Website          : https://spboucher.ai30// Git              : https://git.spboucher.ai31//32// =============================================================================33// OFFICIAL CONTACT DIRECTORY34// =============================================================================35//36// General          : info@spboucher.ai37// Professional     : contact@spboucher.ai38// Direct           : simon@spboucher.ai39// Research         : research@spboucher.ai40// Development      : dev@spboucher.ai41// Support          : support@spboucher.ai42// Security/Admin   : admin@spboucher.ai43// Notifications    : notifications@spboucher.ai44//45// Preferred Contact: support@spboucher.ai46//47// =============================================================================48// COPYRIGHT & INTELLECTUAL PROPERTY49// =============================================================================50//51// Copyright (c) 202652// Simon-Pierre Boucher53//54// All rights reserved where applicable.55//56// This file is governed by the applicable project license,57// copyright notices, institutional agreements and relevant law.58//59// Unless expressly authorized by the applicable license or60// rights holder, copying, redistribution, sublicensing,61// publication and commercial exploitation are not permitted.62//63// Existing third-party rights and notices remain unaffected.64//65// =============================================================================66// CONFIDENTIALITY & SECURITY67// =============================================================================68//69// Classification   : Public70// Distribution     : Public repository; use is governed by the project license71// Security Contact : admin@spboucher.ai72//73// Access to this source does not independently grant permission74// to redistribute or disclose confidential materials.75//76// Do not embed credentials, private keys, access tokens,77// certificates or confidential personal information.78//79// =============================================================================80// LICENSE & MAINTENANCE81// =============================================================================82//83// License          : None specified (no license file in this repository)84// Maintainer       : Simon-Pierre Boucher85// Technical Contact: dev@spboucher.ai86//87// =============================================================================88// END OF SP BOUCHER SOURCE HEADER89// =============================================================================9091import CoreLocation92import Foundation9394// MARK: - Recherche d'adresse9596struct SearchResponse: Decodable, Sendable {97    var results: [SearchHit]98    var municipalites: [Municipality]99    var rues: [Street]100101    /// Rue trouvée (adresses regroupées par voie et municipalité).102    struct Street: Decodable, Sendable, Hashable, Identifiable {103        var nom: String104        var municipalite: String?105        var n: Int?106        var id: String { nom + "|" + (municipalite ?? "") }107        var title: String { Fmt.address(nom) }108    }109110    enum CodingKeys: String, CodingKey { case results, municipalites, rues }111    init(from decoder: Decoder) throws {112        let c = try decoder.container(keyedBy: CodingKeys.self)113        results = c.list(.results); municipalites = c.list(.municipalites); rues = c.list(.rues)114    }115116    var isEmpty: Bool { results.isEmpty && municipalites.isEmpty && rues.isEmpty }117}118119struct SearchHit: Decodable, Sendable, Hashable, Identifiable {120    var id: String121    var adresse: String?122    var apt: String?123    var municipalite: String?124    var typeProp: String?125    var lat: Double?126    var lng: Double?127    var est2026: Double?128    var genre: String?129    var genreLibelle: String?130    /// la valeur de la fiche (une propriété n'a qu'une valeur) ; `est2026` la répète131    var valeurEstimee: Double?132133    var value: Double? { valeurEstimee ?? est2026 }134135    /// « 5681 Rue Campanules, app. 3 »136    var title: String {137        let a = Fmt.address(adresse)138        if let apt, !apt.trimmingCharacters(in: .whitespaces).isEmpty { return a + ", app. " + apt }139        return a140    }141142    var subtitle: String {143        [municipalite, genreLibelle.map(Fmt.capitalized) ?? PropType.label(typeProp)].compactMap { $0 }.filter { !$0.isEmpty }.joined(separator: " · ")144    }145146    var coordinate: CLLocationCoordinate2D? {147        guard let lat, let lng, lat != 0, lng != 0 else { return nil }148        return .init(latitude: lat, longitude: lng)149    }150}151152// MARK: - Fiche d'unité153154struct UnitDetail: Decodable, Sendable {155    var unit: PropertyUnit?156    var result: EstimateResult157    var context: MarketContext?158    var sales: [UnitSale]159    var links: UnitLinks?160    /// l'inscription à vendre de l'unité (jumelage sûr), avec la lecture de son prix161    var inscription: Inscription?162163    struct Inscription: Decodable, Sendable, Hashable {164        var uid: String165        var prix: Double?166        var image: String?167        var verdict: String?168        var ecartPct: Double?169        var dansFourchette: Bool?170    }171172    enum CodingKeys: String, CodingKey { case unit, result, context, sales, links, inscription }173    init(from decoder: Decoder) throws {174        let c = try decoder.container(keyedBy: CodingKeys.self)175        unit = c.opt(.unit)176        result = try c.decode(EstimateResult.self, forKey: .result)177        context = c.opt(.context)178        sales = c.list(.sales)179        links = c.opt(.links)180        inscription = c.opt(.inscription)181    }182}183184struct UnitLinks: Decodable, Sendable {185    var page: String?186    var pdf: String?187    var pdfPro: String?188    var cout: String?189}190191struct PropertyUnit: Decodable, Sendable {192    var id: String193    var adresse: String?194    var municipalite: String?195    var typeProp: String?196    var cubfLibelle: String?197    var anneeConstruction: Int?198    var aireEtagesM2: Double?199    var superficieTerrainM2: Double?200    var nbLogements: Int?201    var valeurRole: Double?202    var lat: Double?203    var lng: Double?204    var history: [HistoryPoint]205    var specs: UnitSpecs?206    var typeLabel: String?207    var municipaliteSlug: String?208    /// genre lu au rôle (clé stable) et son libellé ; `typeProp` est le classement brut de la base, mal nommé209    var genre: String?210    var genreLibelle: String?211212    enum CodingKeys: String, CodingKey {213        case id, adresse, municipalite, typeProp, cubfLibelle, anneeConstruction, aireEtagesM2, superficieTerrainM2214        case nbLogements, valeurRole, lat, lng, history, specs, typeLabel, municipaliteSlug, genre, genreLibelle215    }216217    init(from decoder: Decoder) throws {218        let c = try decoder.container(keyedBy: CodingKeys.self)219        guard let i = c.str(.id) else { throw DecodingError.dataCorruptedError(forKey: .id, in: c, debugDescription: "id absent") }220        id = i221        adresse = c.text(.adresse)222        municipalite = c.text(.municipalite)223        typeProp = c.text(.typeProp)224        cubfLibelle = c.text(.cubfLibelle)225        anneeConstruction = c.int(.anneeConstruction)226        aireEtagesM2 = c.dbl(.aireEtagesM2)227        superficieTerrainM2 = c.dbl(.superficieTerrainM2)228        nbLogements = c.int(.nbLogements)229        valeurRole = c.dbl(.valeurRole)230        lat = c.dbl(.lat)231        lng = c.dbl(.lng)232        history = c.list(.history)233        specs = c.opt(.specs)234        typeLabel = c.text(.typeLabel)235        municipaliteSlug = c.text(.municipaliteSlug)236        genre = c.text(.genre); genreLibelle = c.text(.genreLibelle)237    }238239    var title: String {240        let a = Fmt.address(adresse)241        if let apt = specs?.apt?.trimmingCharacters(in: .whitespaces), !apt.isEmpty { return a + ", app. " + apt }242        return a243    }244245    var typeDisplay: String {246        if let t = genreLibelle ?? typeLabel, !t.isEmpty { return Fmt.capitalized(t) }247        return PropType.label(typeProp, short: false)248    }249250    /// Libellé court du genre, pour les sous-titres.251    var typeShort: String { PropType.label(genre ?? typeProp) }252    var isNonResidential: Bool { (genre ?? typeProp) == "autre" }253254    var coordinate: CLLocationCoordinate2D? {255        guard let lat, let lng, lat != 0, lng != 0 else { return nil }256        return .init(latitude: lat, longitude: lng)257    }258}259260struct HistoryPoint: Decodable, Sendable, Identifiable, Hashable {261    var year: Int262    var value: Double?263    var id: Int { year }264}265266struct UnitSpecs: Decodable, Sendable {267    var cubf: Int?268    var cubfLibelle: String?269    var anneeEstimee: String?270    var frontTerrainM: Double?271    var nbEtages: Int?272    var nbLocauxNonResid: Int?273    var nbChambresLocatives: Int?274    var lienPhysique: String?275    var genreConstruction: String?276    var matricule: String?277    var uniteVoisinage: String?278    var nAdresses: Int?279    var datCondMarche: String?280    var valeurTerrain: Double?281    var valeurBatiment: Double?282    var valeurAnterieure: Double?283    var arrond: String?284    var apt: String?285286    enum CodingKeys: String, CodingKey {287        case cubf, cubfLibelle, anneeEstimee, frontTerrainM, nbEtages, nbLocauxNonResid, nbChambresLocatives, lienPhysique288        case genreConstruction, matricule, uniteVoisinage, nAdresses, datCondMarche, valeurTerrain, valeurBatiment289        case valeurAnterieure, arrond, apt290    }291292    init(from decoder: Decoder) throws {293        let c = try decoder.container(keyedBy: CodingKeys.self)294        cubf = c.int(.cubf); cubfLibelle = c.text(.cubfLibelle); anneeEstimee = c.text(.anneeEstimee)295        frontTerrainM = c.dbl(.frontTerrainM); nbEtages = c.int(.nbEtages); nbLocauxNonResid = c.int(.nbLocauxNonResid)296        nbChambresLocatives = c.int(.nbChambresLocatives); lienPhysique = c.text(.lienPhysique)297        genreConstruction = c.text(.genreConstruction); matricule = c.text(.matricule); uniteVoisinage = c.text(.uniteVoisinage)298        nAdresses = c.int(.nAdresses); datCondMarche = c.text(.datCondMarche); valeurTerrain = c.dbl(.valeurTerrain)299        valeurBatiment = c.dbl(.valeurBatiment); valeurAnterieure = c.dbl(.valeurAnterieure); arrond = c.text(.arrond)300        apt = c.text(.apt)301    }302}303304struct EstimateResult: Decodable, Sendable {305    /// nil : marché sans modèle ni comparables (le service sert `null`)306    var estimate: Double?307    var low: Double?308    var high: Double?309    var confidencePct: Double?310    var confidenceLevel: String?311    var modelEstimate: Double?312    var compsEstimate: Double?313    var modelWeight: Double?314    var comps: [Comparable]315    var nCompsUsed: Int?316    var compsDispersionPct: Double?317318    enum CodingKeys: String, CodingKey {319        case estimate, low, high, confidencePct, confidenceLevel, modelEstimate, compsEstimate, modelWeight, comps320        case nCompsUsed, compsDispersionPct321    }322323    init(from decoder: Decoder) throws {324        let c = try decoder.container(keyedBy: CodingKeys.self)325        estimate = c.dbl(.estimate); low = c.dbl(.low); high = c.dbl(.high)326        confidencePct = c.dbl(.confidencePct); confidenceLevel = c.text(.confidenceLevel)327        modelEstimate = c.dbl(.modelEstimate); compsEstimate = c.dbl(.compsEstimate); modelWeight = c.dbl(.modelWeight)328        comps = c.list(.comps); nCompsUsed = c.int(.nCompsUsed); compsDispersionPct = c.dbl(.compsDispersionPct)329    }330331    /// Une estimation n'est affichable que si la valeur et sa fourchette existent et sont cohérentes.332    var isUsable: Bool {333        guard let e = estimate, let l = low, let h = high else { return false }334        return e > 0 && l > 0 && h >= e && l <= e335    }336}337338/// Vente comparable ajustée (conditions de marché, superficie, âge).339struct Comparable: Decodable, Sendable, Identifiable, Hashable {340    var id: String341    var kind: String?342    var date: String?343    var amount: Double?344    var lat: Double?345    var lng: Double?346    var propertyType: String?347    var yearBuilt: Int?348    var floorArea: Double?349    var street: String?350    var city: String?351    var distanceM: Double?352    var monthsAgo: Double?353    var adjTime: Double?354    var adjArea: Double?355    var adjAge: Double?356    var adjustedPrice: Double?357    var weight: Double?358    var engineUsed: Bool?359    var idProvinc: String?360    /// ce comparable est une vente de la propriété elle-même361    var venteDuSujet: Bool?362363    enum CodingKeys: String, CodingKey {364        case id, kind, date, amount, lat, lng, propertyType, yearBuilt, floorArea, street, city, distanceM, monthsAgo365        case adjTime, adjArea, adjAge, adjustedPrice, weight, engineUsed, idProvinc, venteDuSujet366    }367368    init(from decoder: Decoder) throws {369        let c = try decoder.container(keyedBy: CodingKeys.self)370        id = c.str(.id) ?? UUID().uuidString371        kind = c.text(.kind); date = c.text(.date); amount = c.dbl(.amount); lat = c.dbl(.lat); lng = c.dbl(.lng)372        propertyType = c.text(.propertyType); yearBuilt = c.int(.yearBuilt); floorArea = c.dbl(.floorArea)373        street = c.text(.street); city = c.text(.city); distanceM = c.dbl(.distanceM); monthsAgo = c.dbl(.monthsAgo)374        adjTime = c.dbl(.adjTime); adjArea = c.dbl(.adjArea); adjAge = c.dbl(.adjAge)375        adjustedPrice = c.dbl(.adjustedPrice); weight = c.dbl(.weight); engineUsed = c.bool(.engineUsed)376        idProvinc = c.text(.idProvinc); venteDuSujet = c.bool(.venteDuSujet)377    }378379    var coordinate: CLLocationCoordinate2D? {380        guard let lat, let lng else { return nil }381        return .init(latitude: lat, longitude: lng)382    }383}384385struct MarketContext: Decodable, Sendable {386    var typeProp: String?387    var index: [IndexPoint]388    var index12mPct: Double?389    var indexSince2021Pct: Double?390    var sector: Sector?391    var muniPercentile: Double?392    var muniTotal: Int?393394    struct Sector: Decodable, Sendable {395        var nSales12m: Int?396        var medianPrice: Double?397        var medianPpm2: Double?398        var radiusKm: Double?399    }400401    enum CodingKeys: String, CodingKey { case typeProp, index, index12mPct, indexSince2021Pct, sector, muniPercentile, muniTotal }402    init(from decoder: Decoder) throws {403        let c = try decoder.container(keyedBy: CodingKeys.self)404        typeProp = c.text(.typeProp); index = c.list(.index); index12mPct = c.dbl(.index12mPct)405        indexSince2021Pct = c.dbl(.indexSince2021Pct); sector = c.opt(.sector)406        muniPercentile = c.dbl(.muniPercentile); muniTotal = c.int(.muniTotal)407    }408}409410struct IndexPoint: Decodable, Sendable, Hashable, Identifiable {411    var month: String412    var idx: Double413    var ppm2: Double?414    var n: Int?415    var id: String { month }416    var date: Date { Fmt.monthDate(month) ?? .distantPast }417}418419/// Vente publiée à l'adresse de l'unité.420struct UnitSale: Decodable, Sendable, Identifiable, Hashable {421    var id: String422    var date: String?423    var amount: Double?424    var propertyType: String?425    var valeurRole: Double?426    var vsRolePct: Double?427    var verdict: String?428    var ecartPct: Double?429    var dansFourchette: Bool?430}431
Files main
Menu

Theme