Repository Public
1//2// Auto-Ka iOS v23// File: AutoKa/Core/Models/Vehicle.swift4// Description: un véhicule à vendre — la carte de résultat et la fiche complète, le verdict de prix du service.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8//910import CoreLocation11import Foundation1213/// Décodeur commun : les clés `snake_case` du service deviennent des propriétés `camelCase`.14enum API {15 static func decoder() -> JSONDecoder {16 let d = JSONDecoder()17 d.keyDecodingStrategy = .convertFromSnakeCase18 return d19 }20}2122/// Verdict de prix, calculé par le service (une seule règle, publiée dans `/api/version`).23/// L'app ne recalcule rien : elle lit la position, le libellé et l'écart, et situe le prix dans la fourchette fournie.24struct PriceVerdict: Codable, Sendable, Hashable {25 /// Position du prix demandé par rapport au marché, telle que le service la publie (`sous`, `dans`, `dessus`,26 /// `nettement_dessus`) : elle choisit la couleur et l'icône. L'échelle est descriptive, pas morale.27 enum Position: String, Sendable, Hashable, CaseIterable {28 case below = "sous", within = "dans", above = "dessus", farAbove = "nettement_dessus", unknown = ""29 }3031 /// code fin du service : `excellent` et `bon` (deux degrés de « sous le marché »), `marche`, `eleve`, `tres_eleve`32 var code: String33 var label: String34 var positionRaw: String?35 /// écart très bas : le service joint une note (« vérifier le kilométrage, le NIV et les rappels »)36 var unusual: Bool37 var note: String?38 /// écart en points de pourcentage, signé (−6.0)39 var deviationPct: Double40 /// médiane des prix ajustés des comparables41 var marketPrice: Double42 /// 1er et 3e quartiles des prix ajustés43 var marketLow: Double44 var marketHigh: Double45 /// 10e et 90e centiles des prix ajustés (absents d'une ancienne réponse gardée en cache)46 var marketP10: Double?47 var marketP90: Double?48 /// marge d'erreur à 95 % du prix de marché, en %, et bande « dans le marché » retenue pour ce véhicule49 var marketErrorPct: Double?50 var bandPct: Double?51 var comparables: Int52 /// ± années retenues pour les comparables53 var yearSpan: Int5455 enum CodingKeys: String, CodingKey {56 case code = "verdict", label, positionRaw = "position", unusual, note, deviationPct, marketPrice, marketLow, marketHigh57 case marketP10, marketP90, marketErrorPct, bandPct, comparables, yearSpan58 }5960 init(code: String, label: String, position: Position? = nil, unusual: Bool = false, note: String? = nil, deviationPct: Double,61 marketPrice: Double, marketLow: Double, marketHigh: Double, marketP10: Double? = nil, marketP90: Double? = nil,62 comparables: Int, yearSpan: Int) {63 self.code = code; self.label = label; self.positionRaw = position?.rawValue; self.unusual = unusual; self.note = note64 self.deviationPct = deviationPct; self.marketPrice = marketPrice; self.marketLow = marketLow; self.marketHigh = marketHigh65 self.marketP10 = marketP10; self.marketP90 = marketP90; self.comparables = comparables; self.yearSpan = yearSpan66 }6768 init(from decoder: Decoder) throws {69 let c = try decoder.container(keyedBy: CodingKeys.self)70 code = try c.decode(String.self, forKey: .code)71 label = (try? c.decode(String.self, forKey: .label)) ?? ""72 positionRaw = try? c.decode(String.self, forKey: .positionRaw)73 unusual = (try? c.decode(Bool.self, forKey: .unusual)) ?? false74 note = try? c.decode(String.self, forKey: .note)75 deviationPct = try c.decode(Double.self, forKey: .deviationPct)76 marketPrice = try c.decode(Double.self, forKey: .marketPrice)77 marketLow = (try? c.decode(Double.self, forKey: .marketLow)) ?? marketPrice78 marketHigh = (try? c.decode(Double.self, forKey: .marketHigh)) ?? marketPrice79 marketP10 = try? c.decode(Double.self, forKey: .marketP10)80 marketP90 = try? c.decode(Double.self, forKey: .marketP90)81 marketErrorPct = try? c.decode(Double.self, forKey: .marketErrorPct)82 bandPct = try? c.decode(Double.self, forKey: .bandPct)83 comparables = (try? c.decode(Int.self, forKey: .comparables)) ?? 084 yearSpan = (try? c.decode(Int.self, forKey: .yearSpan)) ?? 185 }8687 /// Position publiée par le service ; à défaut (réponse d'avant la révision 2), celle du code.88 var position: Position {89 if let p = positionRaw.flatMap(Position.init(rawValue:)), p != .unknown { return p }90 return VerdictRules.position(forCode: code)91 }9293 /// Libellé à afficher : celui du service ; à défaut, celui de `/api/version`.94 var displayLabel: String {95 if !label.isEmpty { return label }96 return VerdictRules.current?.libelles[code] ?? "Verdict"97 }9899 /// prix demandé − prix de marché, en dollars100 func gap(price: Double) -> Double { price - marketPrice }101}102103struct PriceChange: Codable, Sendable, Hashable {104 var ts: Double?105 var previous: Double?106 var delta: Double?107 var pct: Double?108 var isDrop: Bool { (delta ?? 0) < 0 }109}110111struct PricePoint: Codable, Sendable, Hashable, Identifiable {112 var ts: Double113 var price: Double114 var id: Double { ts }115 var date: Date { Date(timeIntervalSince1970: ts) }116}117118struct VehicleScore: Decodable, Sendable, Hashable {119 struct Part: Decodable, Sendable, Hashable, Identifiable {120 var key: String121 var label: String122 var score: Double123 var weight: Double124 var id: String { key }125 }126 var overall: Double127 var parts: [Part]128 var kmPerYearReference: Double?129}130131struct Offer: Decodable, Sendable, Hashable, Identifiable {132 var uid: String133 var source: String?134 var sourceName: String?135 var url: String?136 var price: Double?137 var dealerName: String?138 var city: String?139 var id: String { uid }140}141142struct Exclusion: Decodable, Sendable, Hashable {143 var code: String144 var label: String?145}146147struct Recall: Decodable, Sendable, Hashable, Identifiable {148 var recallNumber: String149 var make: String?150 var model: String?151 var year: Int?152 var date: String?153 var component: String?154 var description: String?155 var category: String?156 var unitsAffected: Int?157 var id: String { recallNumber + (date ?? "") }158159 /// Texte du rappel découpé en paragraphes titrés (« Problème : », « Risque pour la sécurité : », « Mesure corrective : »).160 var paragraphs: [(title: String?, text: String)] {161 let raw = (description ?? "").replacingOccurrences(of: "\r", with: "")162 var out: [(String?, String)] = []163 var title: String?164 var buf: [String] = []165 func flush() {166 let t = buf.joined(separator: " ").trimmingCharacters(in: .whitespacesAndNewlines)167 if !t.isEmpty { out.append((title, t)) }168 buf = []169 }170 for line in raw.split(separator: "\n").map({ $0.trimmingCharacters(in: .whitespaces) }) where !line.isEmpty {171 if line.hasSuffix(":"), line.count < 48 {172 flush()173 title = String(line.dropLast()).trimmingCharacters(in: .whitespaces)174 } else {175 buf.append(line)176 }177 }178 flush()179 return out180 }181}182183struct RecallCheck: Decodable, Sendable, Hashable {184 /// faux quand marque, modèle ou année manque : ne pas dire « aucun rappel »185 var checked: Bool186 var count: Int187 var items: [Recall]188}189190/// Un véhicule. Les champs de la carte sont toujours là ; ceux de la fiche (`description`, `images`, `dealer`…)191/// ne sont remplis que par `GET /api/listings/{uid}`.192struct Vehicle: Decodable, Identifiable, Hashable, Sendable {193 var uid: String194 var source: String195 var sourceName: String196 var url: String?197 var kind: String198 var title: String199 var make: String200 var model: String201 var trim: String202 var year: Int?203 var price: Double?204 var mileageKm: Double?205 var transmission: String206 var fuel: String207 var drivetrain: String208 var bodyType: String209 var exteriorColor: String210 var color: String211 var vin: String212 var stockNumber: String213 var dealerName: String214 var dealerID: String?215 var privateSeller: Bool216 var city: String217 var region: String218 var lat: Double?219 var lng: Double?220 var nImg: Int221 /// première VRAIE photo quand il y en a une ; sinon la première image (peut être un visuel d'attente)222 var img: String?223 /// l'annonce a des images mais aucune vraie photo (« Nouvel arrivage », « Photo à venir », logo)224 var photoPlaceholder: Bool225 /// nombre de vraies photos226 var photosReelles: Int227 var nFeat: Int228 var hasCarfax: Bool229 var status: String230 /// champs déduits du consensus du modèle (`body_type`, `fuel`) : à signaler discrètement231 var inferred: [String]232 var verdict: PriceVerdict?233 var priceChange: PriceChange?234 var offersCount: Int235 var firstSeen: Double?236 var lastSeen: Double?237 var daysListed: Int?238 var path: String?239 var makeSlug: String?240 var modelSlug: String?241 var citySlug: String?242 /// présent quand la recherche est faite autour d'un point243 var distanceKm: Double?244245 // --- fiche ---246 var isDetail = false247 var isPublic = true248 var active = true249 var exclusion: Exclusion?250 var description: String = ""251 var features: [String] = []252 var images: [String] = []253 var interiorColor: String = ""254 var engine: String = ""255 var doors: Int?256 var seats: Int?257 var carfaxURL: String?258 var details: [String: String] = [:]259 var priceHistory: [PricePoint] = []260 var score: VehicleScore?261 var offers: [Offer] = []262 var dealer: Dealer?263 var similar: [Vehicle] = []264 var recalls: RecallCheck?265 /// fiche constructeur décodée du NIV : libellé → valeur, dans l'ordre d'affichage266 var vinInfo: [KeyValue] = []267 var vinInfoPending = false268269 var id: String { uid }270271 static func == (a: Vehicle, b: Vehicle) -> Bool {272 a.uid == b.uid && a.price == b.price && a.isDetail == b.isDetail && a.lastSeen == b.lastSeen && a.active == b.active273 && a.vinInfo.count == b.vinInfo.count274 }275 func hash(into h: inout Hasher) { h.combine(uid) }276277 init(from decoder: Decoder) throws {278 let c = try decoder.container(keyedBy: AnyKey.self)279 func k(_ s: String) -> AnyKey { AnyKey(s) }280 guard let id = c.text(k("uid")) else {281 throw DecodingError.dataCorrupted(.init(codingPath: decoder.codingPath, debugDescription: "annonce sans uid"))282 }283 uid = id284 source = c.text(k("source")) ?? ""285 sourceName = c.text(k("sourceName")) ?? ""286 url = c.text(k("url"))287 kind = c.text(k("kind")) ?? "auto"288 title = c.text(k("title")) ?? ""289 make = c.text(k("make")) ?? ""290 model = c.text(k("model")) ?? ""291 trim = c.text(k("trim")) ?? ""292 year = c.int(k("year"))293 price = c.dbl(k("price")).flatMap { $0 > 0 ? $0 : nil }294 mileageKm = c.dbl(k("mileageKm")).flatMap { $0 >= 0 ? $0 : nil }295 transmission = c.text(k("transmission")) ?? ""296 fuel = c.text(k("fuel")) ?? ""297 drivetrain = c.text(k("drivetrain")) ?? ""298 bodyType = c.text(k("bodyType")) ?? ""299 exteriorColor = c.text(k("exteriorColor")) ?? ""300 color = c.text(k("color")) ?? ""301 vin = c.text(k("vin")) ?? ""302 stockNumber = c.text(k("stockNumber")) ?? ""303 dealerName = c.text(k("dealerName")) ?? ""304 dealerID = c.text(k("dealerId"))305 privateSeller = c.bool(k("privateSeller")) ?? false306 city = c.text(k("city")) ?? ""307 region = c.text(k("region")) ?? ""308 lat = c.dbl(k("lat"))309 lng = c.dbl(k("lng"))310 nImg = c.int(k("nImg")) ?? 0311 img = c.text(k("img"))312 photoPlaceholder = c.bool(k("photoPlaceholder")) ?? false313 photosReelles = c.int(k("photosReelles")) ?? nImg314 nFeat = c.int(k("nFeat")) ?? 0315 hasCarfax = c.bool(k("hasCarfax")) ?? false316 status = c.text(k("status")) ?? ""317 inferred = c.strings(k("inferred"))318 verdict = c.opt(k("priceVerdict"))319 priceChange = c.opt(k("priceChange"))320 offersCount = c.int(k("offersCount")) ?? 0321 firstSeen = c.dbl(k("firstSeen"))322 lastSeen = c.dbl(k("lastSeen"))323 daysListed = c.int(k("daysListed"))324 path = c.text(k("path"))325 makeSlug = c.text(k("makeSlug"))326 modelSlug = c.text(k("modelSlug"))327 citySlug = c.text(k("citySlug"))328 distanceKm = c.dbl(k("distanceKm"))329330 // la fiche se reconnaît à ses champs propres331 isDetail = c.contains(k("images")) || c.contains(k("priceHistory")) || c.contains(k("active"))332 isPublic = c.bool(k("public")) ?? true333 active = c.bool(k("active")) ?? true334 exclusion = c.opt(k("exclusion"))335 description = c.text(k("description")) ?? ""336 features = c.strings(k("features")).map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }.filter { !$0.isEmpty }337 // galerie : les vraies photos seulement ; un visuel d'attente n'est jamais montré comme une photo338 let real = c.strings(k("imagesReelles")).filter { $0.hasPrefix("http") }339 if c.contains(k("imagesReelles")) {340 images = real341 } else {342 images = photoPlaceholder ? [] : c.strings(k("images")).filter { $0.hasPrefix("http") }343 }344 if images.isEmpty, let photo { images = [photo] }345 interiorColor = c.text(k("interiorColor")) ?? ""346 engine = c.text(k("engine")) ?? ""347 doors = c.int(k("doors")).flatMap { (1...8).contains($0) ? $0 : nil }348 seats = c.int(k("seats")).flatMap { (1...16).contains($0) ? $0 : nil }349 carfaxURL = c.text(k("carfaxUrl"))350 if let d = try? c.nestedContainer(keyedBy: AnyKey.self, forKey: k("details")) {351 for key in d.allKeys {352 if let s = d.text(key) { details[key.stringValue] = s } else if let b = d.bool(key) { details[key.stringValue] = b ? "oui" : "non" }353 }354 }355 priceHistory = c.list(k("priceHistory"), PricePoint.self).sorted { $0.ts < $1.ts }356 score = c.opt(k("score"))357 offers = c.list(k("offers"))358 dealer = c.opt(k("dealer"))359 similar = c.list(k("similar"))360 recalls = c.opt(k("recalls"))361 if let v = try? c.nestedContainer(keyedBy: AnyKey.self, forKey: k("vinInfo")) {362 vinInfo = KeyValue.ordered(v.allKeys.compactMap { key in v.text(key).map { KeyValue(key: key.stringValue, value: $0) } })363 }364 vinInfoPending = c.bool(k("vinInfoPending")) ?? false365 }366}367368/// Paire libellé → valeur (fiche constructeur du NIV).369struct KeyValue: Sendable, Hashable, Identifiable {370 var key: String371 var value: String372 var id: String { key }373374 /// Ordre d'affichage stable : l'ordre d'un objet JSON n'est pas garanti au décodage.375 private static let order = ["Carrosserie (usine)", "Moteur", "Cylindres", "Cylindrée (L)", "Puissance (ch)", "Carburant (usine)",376 "Transmission (usine)", "Rouage (usine)", "Portes (usine)", "Places (usine)", "PNBV",377 "Constructeur", "Usine", "Pays d'assemblage", "Ville d'assemblage", "Freins ABS",378 "Coussins avant", "Coussins latéraux", "Coussins rideaux", "Surveillance pneus (TPMS)", "Caméra de recul"]379380 static func ordered(_ items: [KeyValue]) -> [KeyValue] {381 items.sorted { a, b in382 let ia = order.firstIndex(of: a.key) ?? Int.max, ib = order.firstIndex(of: b.key) ?? Int.max383 return ia == ib ? a.key.localizedCompare(b.key) == .orderedAscending : ia < ib384 }385 }386}387388// MARK: - Affichage389390extension Vehicle {391 /// « Toyota RAV4 »392 var name: String { [make, model].filter { !$0.isEmpty }.joined(separator: " ") }393394 /// Version nettoyée du texte de vente.395 var cleanTrim: String { Fmt.cleanTrim(trim) }396397 /// « Toyota RAV4 XLE AWD 2022 » : le titre d'une fiche et d'une carte.398 var fullTitle: String {399 let parts = [make, model, cleanTrim, year.map(String.init) ?? ""].filter { !$0.isEmpty }400 return parts.isEmpty ? title : parts.joined(separator: " ")401 }402403 var isCar: Bool { kind == "auto" }404405 /// Photo de vitrine : jamais un visuel d'attente.406 var photo: String? { photoPlaceholder ? nil : img }407 var coordinate: CLLocationCoordinate2D? {408 guard let lat, let lng, abs(lat) > 0.01 else { return nil }409 return .init(latitude: lat, longitude: lng)410 }411412 /// « Charlesbourg Toyota · Québec » ; « Particulier · Laval »413 var sellerLine: String {414 [privateSeller || dealerName.isEmpty ? (privateSeller ? "Particulier" : "") : dealerName, city].filter { !$0.isEmpty }.joined(separator: " · ")415 }416417 /// « 110 641 km · Charlesbourg Toyota · Québec »418 var cardLine: String {419 ([Fmt.mileageShort(mileageKm)].compactMap { $0 } + [sellerLine]).filter { !$0.isEmpty }.joined(separator: " · ")420 }421422 /// « Automatique · Intégrale / 4x4 · Essence »423 var specLine: String { [transmission, drivetrain, fuel].filter { !$0.isEmpty }.joined(separator: " · ") }424425 func isInferred(_ field: String) -> Bool { inferred.contains(field) }426427 var statusLabel: String? {428 switch status {429 case "certifie": "Certifié par le vendeur"430 case "demo": "Démonstrateur"431 default: nil432 }433 }434435 /// Icône de la marque pour la carrosserie (repli quand la photo manque, accès par carrosserie).436 var bodyIcon: String { BodyType.icon(for: bodyType, kind: kind) }437438 /// Phrase de la dernière variation de prix : « Prix baissé de 507 $ le 25 novembre ».439 var priceChangeLine: String? {440 guard let pc = priceChange, let d = pc.delta, d != 0 else { return nil }441 return "Prix \(d < 0 ? "baissé" : "augmenté") de \(Fmt.money(abs(d))) le \(Fmt.dayMonth(pc.ts))"442 }443444 /// Adresse publique de la fiche (partage).445 var shareURL: URL? {446 guard let path else { return nil }447 return URL(string: "https://www.auto-ka.com" + path)448 }449}450451enum BodyType {452 /// Les huit carrosseries du service, dans l'ordre de l'accueil, avec l'icône de la marque.453 static let all: [(value: String, label: String, icon: String)] = [454 ("VUS", "VUS", "ic-vus"), ("Berline", "Berlines", "ic-berline"), ("Camionnette", "Camionnettes", "ic-camion"),455 ("Hayon", "Hayons", "ic-familiale"), ("Fourgonnette", "Fourgonnettes", "ic-fourgonnette"), ("Coupé", "Coupés", "ic-coupe"),456 ("Cabriolet", "Cabriolets", "ic-coupe"), ("Familiale", "Familiales", "ic-familiale"),457 ]458459 static func icon(for body: String, kind: String = "auto") -> String {460 all.first { $0.value == body }?.icon ?? "ic-berline"461 }462}463464enum Fuel {465 static func icon(for fuel: String) -> String {466 switch fuel {467 case "Électrique": "ic-electrique"468 case "Hybride", "Hybride rechargeable": "ic-hybride"469 case "Diesel": "ic-diesel"470 default: "ic-essence"471 }472 }473}474