Repository Public
1//2// Auto-Ka iOS v23// File: AutoKa/Core/Models/Responses.swift4// Description: réponses de l'API v2 — recherche, facettes, concessionnaires, marques, villes, marché, NIV, rappels.5// Décodées avec `API.decoder()` (clés snake_case → camelCase).6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9//1011import CoreLocation12import Foundation1314// MARK: - Version et règle du verdict1516struct APIVersion: Decodable, Sendable {17 var api: Int18 var version: String?19 var publicListings: Int?20 var kinds: [String: Int]?21 var verdict: VerdictRules?22 var sorts: [String]?23 var refreshSeconds: Double?24}2526/// La règle du verdict telle que le service la publie. L'app l'affiche (page « Méthode ») ; elle ne s'en sert27/// jamais pour calculer un verdict.28struct VerdictRules: Codable, Sendable, Equatable {29 var formule: String?30 var comparables: String?31 var ajustement: String?32 var tauxKmPar10000: Double?33 var tauxParAnnee: Double?34 var prixDeMarche: String?35 var intervalle: String?36 var comparablesMin: Int?37 var seuilsPct: [String: Double]?38 var ecartMinPct: Double?39 var ecartMaxPct: Double?40 var dispersionMax: Double?41 var libelles: [String: String]42 var nullSi: [String]?43 // révision 2 du contrat44 var regle: String?45 var bandePct: Double?46 var netPct: Double?47 var justification: String?48 var fourchette: String?49 var margeErreur: String?50 /// code → position (`sous`, `dans`, `dessus`, `nettement_dessus`)51 var positions: [String: String]?52 var positionLibelles: [String: String]?53 var noteInhabituel: String?5455 private static let key = "verdict.rules"5657 static func store(_ r: VerdictRules) {58 if let d = try? JSONEncoder().encode(r) { UserDefaults.standard.set(d, forKey: key) }59 }6061 /// Dernière règle reçue du service (gardée pour le hors ligne) ; nil tant qu'aucune version n'a répondu.62 static var current: VerdictRules? {63 UserDefaults.standard.data(forKey: key).flatMap { try? JSONDecoder().decode(VerdictRules.self, from: $0) }64 }6566 /// Positions dans l'ordre de l'échelle (froid → chaud), puis « aucun ».67 static let order = ["sous", "dans", "dessus", "nettement_dessus", "aucun"]6869 /// Position d'un code. Le service publie la correspondance ; la table de repli est celle du contrat.70 static func position(forCode code: String) -> PriceVerdict.Position {71 if let p = PriceVerdict.Position(rawValue: code), p != .unknown { return p }72 if let raw = current?.positions?[code] ?? current?.positions?[code.replacingOccurrences(of: "_", with: "")],73 let p = PriceVerdict.Position(rawValue: raw) { return p }74 switch code {75 case "excellent", "bon": return .below76 case "marche": return .within77 case "eleve": return .above78 case "tres_eleve", "tresEleve": return .farAbove79 default: return .unknown80 }81 }8283 /// Libellé d'une position ou d'un code, tel que publié par le service.84 static func label(for value: String) -> String {85 if value == "aucun" { return "Sans verdict" }86 let c = current87 if let l = c?.positionLibelles?[value] ?? c?.positionLibelles?[camel(value)] { return l }88 if let l = c?.libelles[value] ?? c?.libelles[camel(value)] { return l }89 let p = position(forCode: value)90 if p != .unknown, let l = c?.positionLibelles?[p.rawValue] ?? c?.positionLibelles?[camel(p.rawValue)] { return l }91 return value.replacingOccurrences(of: "_", with: " ").capitalized92 }9394 /// Regroupe des comptes par code (réponses des pages marque, modèle, ville, commerce) en comptes par position.95 static func byPosition(_ counts: [String: Int]) -> [String: Int] {96 var out: [String: Int] = [:]97 for (code, n) in counts {98 let p = position(forCode: code)99 out[p == .unknown ? "aucun" : p.rawValue, default: 0] += n100 }101 return out102 }103104 /// Les clés d'un dictionnaire décodé avec `convertFromSnakeCase` sont converties elles aussi.105 private static func camel(_ s: String) -> String {106 let parts = s.split(separator: "_")107 return parts.enumerated().map { $0.offset == 0 ? String($0.element) : $0.element.capitalized }.joined()108 }109}110111// MARK: - Recherche112113/// Un point de carte : une position, pas un véhicule. Les véhicules d'un même commerce partagent ses coordonnées.114struct MapPoint: Decodable, Sendable, Hashable {115 var lat: Double116 var lng: Double117 var n: Int118 var priceMin: Double?119 var priceMedian: Double?120 var city: String?121 /// renseigné quand la position ne compte qu'un commerce122 var dealerID: String?123 /// renseigné quand la position ne compte qu'un véhicule124 var uid: String?125126 init(lat: Double, lng: Double, n: Int, priceMin: Double? = nil, priceMedian: Double? = nil, city: String? = nil,127 dealerID: String? = nil, uid: String? = nil) {128 self.lat = lat; self.lng = lng; self.n = n; self.priceMin = priceMin; self.priceMedian = priceMedian129 self.city = city; self.dealerID = dealerID; self.uid = uid130 }131132 /// Format compact : `[lat, lng, n, price_min, price_median, city, dealer_id, uid]`.133 init(from decoder: Decoder) throws {134 var c = try decoder.unkeyedContainer()135 lat = try c.decode(Double.self)136 lng = try c.decode(Double.self)137 n = (try? c.decode(Int.self)) ?? Int((try? c.decode(Double.self)) ?? 1)138 func next<T: Decodable>(_ t: T.Type) -> T? {139 guard !c.isAtEnd else { return nil }140 if let v = try? c.decode(T.self) { return v }141 _ = try? c.decodeNil()142 return nil143 }144 priceMin = next(Double.self)145 priceMedian = next(Double.self)146 city = next(String.self)147 dealerID = next(String.self)148 uid = next(String.self)149 }150151 var coordinate: CLLocationCoordinate2D { .init(latitude: lat, longitude: lng) }152}153154struct SearchResponse: Decodable, Sendable {155 var total: Int156 var page: Int?157 var pageSize: Int?158 var pages: Int?159 var sort: String?160 var unpositioned: Int?161 var generatedAt: Double?162 var listings: [Vehicle]163 var points: [MapPoint]?164}165166struct CountResponse: Decodable, Sendable { var total: Int }167168/// Valeur d'une facette. `value` est une chaîne, même pour les années.169struct FacetValue: Decodable, Sendable, Hashable, Identifiable {170 var value: String171 var n: Int172 var slug: String?173 var name: String?174 var label: String?175 var id: String { value }176 /// libellé à l'écran : nom du commerce ou de la source, libellé du verdict, sinon la valeur177 var title: String { name ?? label ?? value }178179 private enum K: String, CodingKey { case value, n, slug, name, label }180 init(value: String, n: Int, slug: String? = nil, name: String? = nil, label: String? = nil) {181 self.value = value; self.n = n; self.slug = slug; self.name = name; self.label = label182 }183 init(from decoder: Decoder) throws {184 let c = try decoder.container(keyedBy: K.self)185 value = c.str(.value) ?? ""186 n = c.int(.n) ?? 0187 slug = c.text(.slug); name = c.text(.name); label = c.text(.label)188 }189}190191struct NumRange: Decodable, Sendable, Hashable {192 var min: Double?193 var max: Double?194 var median: Double?195}196197struct Facets: Decodable, Sendable {198 struct Ranges: Decodable, Sendable { var price: NumRange?; var mileageKm: NumRange?; var year: NumRange? }199 var total: Int200 var makes: [FacetValue]?201 var models: [FacetValue]?202 var bodyTypes: [FacetValue]?203 var fuels: [FacetValue]?204 var transmissions: [FacetValue]?205 var drivetrains: [FacetValue]?206 var colors: [FacetValue]?207 var years: [FacetValue]?208 var regions: [FacetValue]?209 var cities: [FacetValue]?210 var dealers: [FacetValue]?211 var sources: [FacetValue]?212 var statuses: [FacetValue]?213 var kinds: [FacetValue]?214 var verdicts: [FacetValue]?215 /// comptes regroupés par position (`sous`, `dans`, `dessus`, `nettement_dessus`)216 var positions: [FacetValue]?217 /// résultats dont le champ est vide : un filtre sur ce champ les écarte (clés du service : `body_type`, `fuel`…)218 var unknown: [String: Int]?219 var ranges: Ranges?220}221222// MARK: - Concessionnaires223224struct MakeCount: Decodable, Sendable, Hashable, Identifiable {225 var make: String226 var n: Int227 var id: String { make }228}229230struct Dealer: Decodable, Sendable, Hashable, Identifiable {231 var id: String232 var name: String233 var city: String?234 var region: String?235 /// nombre de villes où le commerce a des véhicules236 var cities: Int?237 var address: String?238 var phone: String?239 var website: String?240 var lat: Double?241 var lng: Double?242 /// `adresse` : coordonnées du commerce ; `ville` : centre de la ville (une zone, pas une épingle exacte)243 var position: String?244 var listings: Int?245 var medianPrice: Double?246 var makes: [MakeCount]?247 var nHere: Int?248249 private enum K: String, CodingKey { case id, name, city, region, cities, address, phone, website, lat, lng, position, listings, medianPrice, makes, nHere }250 init(from decoder: Decoder) throws {251 let c = try decoder.container(keyedBy: K.self)252 id = c.text(.id) ?? ""253 name = c.text(.name) ?? id254 city = c.text(.city); region = c.text(.region); cities = c.int(.cities)255 address = c.text(.address); phone = c.text(.phone); website = c.text(.website)256 lat = c.dbl(.lat); lng = c.dbl(.lng); position = c.text(.position)257 // `listings` est un nombre dans l'annuaire et la liste des annonces dans la page du commerce258 listings = c.int(.listings)259 medianPrice = c.dbl(.medianPrice)260 makes = c.opt(.makes)261 nHere = c.int(.nHere)262 }263264 var coordinate: CLLocationCoordinate2D? {265 guard let lat, let lng, abs(lat) > 0.01 else { return nil }266 return .init(latitude: lat, longitude: lng)267 }268 var hasExactPosition: Bool { position == "adresse" }269 /// « Sherbrooke · Estrie » ; « Saint-Léonard et 19 autres villes »270 var placeLine: String {271 if let c = cities, c > 1, let city { return "\(city) et \(c - 1) autre\(c > 2 ? "s" : "") ville\(c > 2 ? "s" : "")" }272 return [city, region].compactMap { $0 }.filter { !$0.isEmpty }.joined(separator: " · ")273 }274 var makesLine: String { (makes ?? []).prefix(3).map(\.make).joined(separator: ", ") }275}276277struct DealersResponse: Decodable, Sendable {278 var total: Int279 var listingsTotal: Int?280 var privateListings: Int?281 var dealers: [Dealer]282}283284struct SourceRef: Decodable, Sendable, Hashable, Identifiable {285 var id: String286 var name: String?287 var url: String?288}289290/// Page d'un commerce : sa fiche, son inventaire paginé, ses répartitions.291struct DealerPage: Decodable, Sendable {292 var dealer: Dealer293 var total: Int294 var pages: Int?295 var price: NumRange?296 var bodyTypes: [FacetValue]297 var verdicts: [String: Int]298 var sourceNames: [SourceRef]299 var vehicles: [Vehicle]300301 private enum K: String, CodingKey { case total, pages, price, bodyTypes, verdicts, sourceNames, listings }302 init(from decoder: Decoder) throws {303 dealer = try Dealer(from: decoder)304 let c = try decoder.container(keyedBy: K.self)305 total = c.int(.total) ?? 0306 pages = c.int(.pages)307 price = c.opt(.price)308 bodyTypes = c.list(.bodyTypes)309 verdicts = c.opt(.verdicts) ?? [:]310 sourceNames = c.list(.sourceNames)311 vehicles = c.list(.listings)312 dealer.listings = total313 }314}315316// MARK: - Marques et modèles317318/// Résumé chiffré commun aux marques, modèles, villes, régions et années.319struct MarketSummary: Decodable, Sendable, Hashable {320 var n: Int321 var priceMedian: Double?322 var priceMin: Double?323 var priceMax: Double?324 var kmMedian: Double?325 var yearMin: Int?326 var yearMax: Int?327}328329struct MakeSummary: Decodable, Sendable, Hashable, Identifiable {330 var make: String331 var slug: String332 var n: Int333 var priceMedian: Double?334 var priceMin: Double?335 var priceMax: Double?336 var kmMedian: Double?337 var yearMin: Int?338 var yearMax: Int?339 /// nombre de modèles340 var models: Int?341 var id: String { slug }342}343344struct MakesResponse: Decodable, Sendable {345 var total: Int346 var listingsTotal: Int?347 var makes: [MakeSummary]348}349350struct ModelSummary: Decodable, Sendable, Hashable, Identifiable {351 var model: String352 var slug: String353 var n: Int354 var priceMedian: Double?355 var priceMin: Double?356 var priceMax: Double?357 var kmMedian: Double?358 var yearMin: Int?359 var yearMax: Int?360 var id: String { slug }361}362363struct MakePage: Decodable, Sendable {364 var make: String365 var slug: String366 var n: Int367 var priceMedian: Double?368 var priceMin: Double?369 var priceMax: Double?370 var kmMedian: Double?371 var yearMin: Int?372 var yearMax: Int?373 var models: [ModelSummary]374 var years: [FacetValue]?375 var bodyTypes: [FacetValue]?376 var fuels: [FacetValue]?377 var regions: [FacetValue]?378 var verdicts: [String: Int]?379 var listings: [Vehicle]380}381382struct YearSummary: Decodable, Sendable, Hashable, Identifiable {383 var year: Int384 var n: Int385 var priceMedian: Double?386 var priceMin: Double?387 var priceMax: Double?388 var kmMedian: Double?389 var id: Int { year }390}391392struct Depreciation: Decodable, Sendable {393 struct Point: Decodable, Sendable, Hashable, Identifiable {394 var age: Int395 var year: Int?396 var n: Int397 var priceMedian: Double?398 var kmMedian: Double?399 var id: Int { age }400 }401 var listings: Int?402 var annualRatePct: Double?403 var method: String?404 var curve: [Point]405}406407struct ModelPage: Decodable, Sendable {408 var make: String409 var makeSlug: String?410 var model: String411 var slug: String412 var n: Int413 var priceMedian: Double?414 var priceMin: Double?415 var priceMax: Double?416 var kmMedian: Double?417 var yearMin: Int?418 var yearMax: Int?419 var byYear: [YearSummary]420 var trims: [FacetValue]?421 var fuels: [FacetValue]?422 var regions: [FacetValue]?423 var verdicts: [String: Int]?424 var depreciation: Depreciation?425 var listings: [Vehicle]426}427428// MARK: - Villes et régions429430struct CitySummary: Decodable, Sendable, Hashable, Identifiable {431 var city: String432 var slug: String433 var region: String?434 var lat: Double?435 var lng: Double?436 var n: Int437 var priceMedian: Double?438 var kmMedian: Double?439 var dealers: Int?440 var distanceKm: Double?441 var id: String { slug }442}443444struct CitiesResponse: Decodable, Sendable {445 var total: Int446 var listingsTotal: Int?447 var noCity: Int?448 var cities: [CitySummary]449}450451struct CityPage: Decodable, Sendable {452 var city: String453 var slug: String454 var region: String?455 var lat: Double?456 var lng: Double?457 var n: Int458 var priceMedian: Double?459 var priceMin: Double?460 var priceMax: Double?461 var kmMedian: Double?462 var dealers: Int?463 var makes: [FacetValue]?464 var bodyTypes: [FacetValue]?465 var verdicts: [String: Int]?466 var topDealers: [Dealer]?467 var nearby: [CitySummary]?468 var listings: [Vehicle]469}470471struct RegionSummary: Decodable, Sendable, Hashable, Identifiable {472 var region: String473 var slug: String474 var n: Int475 var priceMedian: Double?476 var kmMedian: Double?477 var cities: Int?478 var id: String { slug }479}480481struct RegionsResponse: Decodable, Sendable {482 var total: Int483 var listingsTotal: Int?484 var noRegion: Int?485 var regions: [RegionSummary]486}487488// MARK: - Marché489490struct Stats: Decodable, Sendable {491 struct Auto: Decodable, Sendable {492 var n: Int493 var priceMedian: Double?494 var priceMean: Double?495 var kmMedian: Double?496 var yearMedian: Double?497 var new7d: Int?498 var new24h: Int?499 var priceDrops: Int?500 var electric: Int?501 var hybrid: Int?502 var privateSellers: Int?503504 // `convertFromSnakeCase` rend « new_7d » en « new7D » (majuscule après chaque soulignement)505 private enum CodingKeys: String, CodingKey {506 case n, priceMedian, priceMean, kmMedian, yearMedian, new7d = "new7D", new24h = "new24H", priceDrops, electric, hybrid, privateSellers507 }508 }509 struct RegionRow: Decodable, Sendable, Hashable, Identifiable { var region: String; var slug: String?; var n: Int; var priceMedian: Double?; var id: String { region } }510 struct MakeRow: Decodable, Sendable, Hashable, Identifiable { var make: String; var slug: String?; var n: Int; var priceMedian: Double?; var id: String { make } }511 struct BodyRow: Decodable, Sendable, Hashable, Identifiable { var bodyType: String; var n: Int; var priceMedian: Double?; var id: String { bodyType } }512 struct FuelRow: Decodable, Sendable, Hashable, Identifiable { var fuel: String; var n: Int; var id: String { fuel } }513 struct YearRow: Decodable, Sendable, Hashable, Identifiable { var year: Int; var n: Int; var id: Int { year } }514 /// `to` est nul pour la dernière tranche (« et plus »)515 struct Bin: Decodable, Sendable, Hashable, Identifiable { var from: Double; var to: Double?; var n: Int; var id: Double { from } }516517 var generatedAt: Double?518 var publicListings: Int519 var kinds: [String: Int]?520 var auto: Auto521 var dealers: Int?522 var sources: Int?523 var cities: Int?524 var verdicts: [FacetValue]?525 var byRegion: [RegionRow]?526 var byMake: [MakeRow]?527 var byBody: [BodyRow]?528 var byFuel: [FuelRow]?529 var byYear: [YearRow]?530 var priceHistogram: [Bin]?531 var kmHistogram: [Bin]?532}533534/// `GET /api/stats/marche` : prix médian par marque, modèle et année.535struct MarketTable: Decodable, Sendable {536 struct Row: Decodable, Sendable, Hashable, Identifiable {537 var make: String538 var model: String539 var year: Int540 var n: Int541 var priceMedian: Double?542 var priceP25: Double?543 var priceP75: Double?544 var kmMedian: Double?545 var id: String { "\(make)|\(model)|\(year)" }546 }547 struct ModelRow: Decodable, Sendable, Hashable, Identifiable {548 var make: String549 var model: String550 var n: Int551 var priceMedian: Double?552 var id: String { "\(make)|\(model)" }553 }554 var listings: Int?555 var models: [ModelRow]?556 var rows: [Row]557}558559struct PriceDrops: Decodable, Sendable {560 var days: Int?561 var count: Int562 var sharePct: Double?563 var medianDropPct: Double?564 var medianDrop: Double?565 var byMake: [MakeCount]?566 var listings: [Vehicle]567}568569struct Electrics: Decodable, Sendable {570 struct TopModel: Decodable, Sendable, Hashable, Identifiable {571 var make: String572 var model: String573 var n: Int574 var priceMedian: Double?575 var id: String { make + "|" + model }576 }577 struct RegionCount: Decodable, Sendable, Hashable, Identifiable { var region: String; var n: Int; var id: String { region } }578 struct Segment: Decodable, Sendable, Identifiable {579 var fuel: String580 var n: Int581 var sharePct: Double?582 var priceMedian: Double?583 var kmMedian: Double?584 var yearMedian: Double?585 var topModels: [TopModel]?586 var byRegion: [RegionCount]?587 var id: String { fuel }588 }589 var autoTotal: Int?590 var segments: [Segment]591 var fuelUnknown: Int?592 var note: String?593}594595struct SaleDelays: Decodable, Sendable {596 struct Row: Decodable, Sendable, Hashable, Identifiable { var value: String; var n: Int; var medianDays: Double?; var id: String { value } }597 var days: Int?598 var withdrawn: Int?599 var medianDays: Double?600 var p25Days: Double?601 var p75Days: Double?602 var method: String?603 var byMake: [Row]?604 var byBody: [Row]?605 var byPrice: [Row]?606}607608/// Tableau de bord par période : seuls les indicateurs et les séries servent à l'app.609struct Dashboard: Decodable, Sendable {610 struct Period: Decodable, Sendable { var from: String?; var to: String?; var label: String? }611 struct TimePoint: Decodable, Sendable, Hashable, Identifiable {612 var t: String613 var v: Double614 var id: String { t }615 var date: Date { Fmt.isoDate(t) ?? .distantPast }616 }617 struct KPI: Decodable, Sendable, Identifiable {618 var id: String619 var label: String620 var value: Double?621 var unit: String?622 var deltaPct: Double?623 var spark: [TimePoint]?624625 private enum K: String, CodingKey { case id, label, value, unit, deltaPct, spark }626 /// `value` est un nombre ou une chaîne (« 2020,7 ») selon l'indicateur : décodage tolérant.627 init(from decoder: Decoder) throws {628 let c = try decoder.container(keyedBy: K.self)629 id = c.text(.id) ?? ""630 label = c.text(.label) ?? ""631 value = c.dbl(.value)632 unit = c.text(.unit)633 deltaPct = c.dbl(.deltaPct)634 spark = c.opt(.spark)635 }636 }637 struct Series: Decodable, Sendable, Identifiable {638 var id: String639 var title: String640 var unit: String?641 var points: [TimePoint]642 }643 var period: Period?644 var kpis: [KPI]?645 var series: [Series]?646}647648// MARK: - NIV et rappels649650struct VINResponse: Decodable, Sendable {651 var vin: String652 var decoded: Bool653 var info: [KeyValue]654 var listings: [Vehicle]655656 private enum K: String, CodingKey { case vin, decoded, info, listings }657 init(from decoder: Decoder) throws {658 let c = try decoder.container(keyedBy: K.self)659 vin = c.text(.vin) ?? ""660 decoded = c.bool(.decoded) ?? false661 if let v = try? c.nestedContainer(keyedBy: AnyKey.self, forKey: .info) {662 info = KeyValue.ordered(v.allKeys.compactMap { key in v.text(key).map { KeyValue(key: key.stringValue, value: $0) } })663 } else {664 info = []665 }666 listings = c.list(.listings)667 }668}669670struct RecallsResponse: Decodable, Sendable {671 var make: String?672 var model: String?673 var year: Int?674 var count: Int675 var recalls: [Recall]676 var source: String?677}678