Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : Vrai-Prix iOS9// File : VraiPrix/Features/V3/SalesV3.swift10// Description : registre des ventes sous l'API v3 : ventes publiées,11// qualifiées par le moteur (de marché ou non, et pourquoi),12// filtre « ventes de marché », tris stables, pagination par13// curseur ; détail d'une vente.14// Module : VraiPrix15// Repository : https://git.spboucher.ai/vrai-prix-ios-v316// Project Website : https://www.vrai-prix.com17// Created : 2026-11-2818// Last Modified : 2026-11-2819//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 SwiftUI9394struct SaleQuery: Sendable, Hashable {95 enum Period: String, CaseIterable, Identifiable, Sendable {96 case d30 = "30", d90 = "90", d365 = "365", all97 var id: String { rawValue }98 var label: String {99 switch self {100 case .d30: "30 j"101 case .d90: "90 j"102 case .d365: "12 mois"103 case .all: "Tout"104 }105 }106 var long: String {107 switch self {108 case .d30: "30 derniers jours"109 case .d90: "90 derniers jours"110 case .d365: "12 derniers mois"111 case .all: "depuis 2021"112 }113 }114 }115 enum Sort: String, CaseIterable, Identifiable, Sendable {116 case recentes, anciennes, prixCroissant = "prix_croissant", prixDecroissant = "prix_decroissant"117 var id: String { rawValue }118 var label: String {119 switch self {120 case .recentes: "Les plus récentes"121 case .anciennes: "Les plus anciennes"122 case .prixCroissant: "Prix croissant"123 case .prixDecroissant: "Prix décroissant"124 }125 }126 }127 static let types: [(key: String, label: String)] = [("", "Tous"), ("unifamilial", "Unifamiliale"), ("condo", "Copropriété"), ("plex", "Plex")]128129 var place = ""130 var type = ""131 var min: Double?132 var max: Double?133 var period: Period = .d90134 var marketOnly = false135 var sort: Sort = .recentes136137 var query: [String: String?] {138 ["q": place.isEmpty ? nil : place, "type": type.isEmpty ? nil : type,139 "prix_min": min.map { String(Int($0)) }, "prix_max": max.map { String(Int($0)) },140 "periode": period.rawValue, "marche": marketOnly ? "1" : nil, "tri": sort == .recentes ? nil : sort.rawValue]141 }142 var extraCount: Int { (type.isEmpty ? 0 : 1) + (min == nil && max == nil ? 0 : 1) + (sort == .recentes ? 0 : 1) }143}144145struct SalesV3View: View {146 @State var query: SaleQuery147 let root: Bool148149 @Environment(AppModel.self) private var model150 @State private var rows: [SaleV3] = []151 @State private var cursor: String?152 @State private var total: Int?153 @State private var totalAll: Int?154 @State private var updatedTo: String?155 @State private var stale = false156 @State private var loading = false157 @State private var error: APIError?158 @State private var showFilters = false159 @State private var placeDraft = ""160161 var body: some View {162 ScrollView {163 LazyVStack(alignment: .leading, spacing: 0) {164 controls165 if stale { StaleNotice().padding(.top, 10) }166 summary.padding(.top, 14).padding(.bottom, 4)167 Hairline()168 list169 }170 .pageColumn()171 .padding(.bottom, 32)172 }173 .background(Theme.bg)174 .navigationTitle(root ? "Ventes" : (query.place.isEmpty ? "Registre des ventes" : query.place))175 .navigationBarTitleDisplayMode(root ? .large : .inline)176 .sheet(isPresented: $showFilters) { SaleQuerySheet(query: $query).presentationDetents([.medium, .large]) }177 .task(id: query) { await reload() }178 .task {179 placeDraft = query.place180 if model.launchSheet == "salefilters" { showFilters = true }181 }182 .refreshable { await reload() }183 }184185 private var controls: some View {186 VStack(alignment: .leading, spacing: 10) {187 HStack(spacing: 8) {188 HStack(spacing: 8) {189 Image(systemName: "magnifyingglass").foregroundStyle(Theme.ink3)190 TextField("Ville", text: $placeDraft)191 .textInputAutocapitalization(.words).autocorrectionDisabled().submitLabel(.search)192 .onSubmit { query.place = placeDraft.trimmingCharacters(in: .whitespaces) }193 .accessibilityIdentifier("sales-place")194 if !placeDraft.isEmpty {195 Button { placeDraft = ""; query.place = "" } label: {196 Image(systemName: "xmark.circle.fill").foregroundStyle(Theme.ink3).frame(width: 30, height: 44)197 }198 .buttonStyle(.plain).accessibilityLabel("Effacer le lieu")199 }200 }201 .padding(.horizontal, 12).frame(minHeight: 48)202 .background(Theme.surface, in: RoundedRectangle(cornerRadius: Theme.radiusSmall, style: .continuous))203 .overlay(RoundedRectangle(cornerRadius: Theme.radiusSmall, style: .continuous).strokeBorder(Theme.lineControl, lineWidth: 1))204 Button { showFilters = true } label: {205 HStack(spacing: 5) {206 Image(systemName: "slider.horizontal.3")207 if query.extraCount > 0 { Text(String(query.extraCount)).font(.footnote.weight(.bold)).monospacedDigit() }208 }209 .foregroundStyle(Theme.ink).frame(minWidth: 48, minHeight: 48)210 .background(Theme.surface, in: RoundedRectangle(cornerRadius: Theme.radiusSmall, style: .continuous))211 .overlay(RoundedRectangle(cornerRadius: Theme.radiusSmall, style: .continuous).strokeBorder(Theme.lineControl, lineWidth: 1))212 }213 .buttonStyle(.plain)214 .accessibilityLabel("Filtres : type, prix et tri")215 .accessibilityIdentifier("sales-filters")216 }217 SlidingSegmented(selection: $query.period, options: SaleQuery.Period.allCases.map { ($0, $0.label) }, label: "Période")218 Toggle(isOn: $query.marketOnly) {219 VStack(alignment: .leading, spacing: 1) {220 Text("Ventes de marché seulement").font(.subheadline).foregroundStyle(Theme.ink)221 Text("Écarte les ventes que le moteur qualifie hors marché.").font(.caption).foregroundStyle(Theme.ink3)222 }223 }224 .tint(Theme.brand)225 .accessibilityIdentifier("sales-market-only")226 }227 }228229 private var summary: some View {230 VStack(alignment: .leading, spacing: 3) {231 Text(loading && rows.isEmpty ? "Recherche…" : headline)232 .font(.subheadline.weight(.medium)).num().foregroundStyle(Theme.ink)233 .fixedSize(horizontal: false, vertical: true)234 .accessibilityIdentifier("sales-count")235 if let u = updatedTo {236 Text("Transactions publiées jusqu'au \(Fmt.day(u)). Prix de vente réels.").font(.footnote).num().foregroundStyle(Theme.ink3)237 }238 }239 }240241 private var headline: String {242 var s = "\(Fmt.int(total ?? rows.count)) \((total ?? rows.count) == 1 ? "vente" : "ventes")"243 if query.marketOnly { s += " de marché" + (totalAll.map { " sur \(Fmt.int($0))" } ?? "") }244 return s + " · " + query.period.long245 }246247 @ViewBuilder248 private var list: some View {249 if let error, rows.isEmpty {250 ErrorState(error: error, subject: "Le registre des ventes") { Task { await reload() } }251 } else if rows.isEmpty, !loading {252 EmptyState(title: "Aucune vente pour ces critères",253 message: "Élargissez la période, retirez un filtre ou vérifiez l'orthographe de la ville.",254 actionLabel: "Retirer les filtres") { placeDraft = ""; query = SaleQuery(period: query.period) }255 } else if rows.isEmpty {256 LoadingState(label: "Chargement du registre")257 } else {258 ForEach(Array(rows.enumerated()), id: \.element.id) { i, s in259 SaleV3Row(sale: s) { model.open(.sale(s.id)) }260 .accessibilityIdentifier("sale-row-\(i)")261 .onAppear { if i >= rows.count - 6 { Task { await loadMore() } } }262 }263 if cursor != nil { HStack { Spacer(); ProgressView(); Spacer() }.padding(.vertical, 18) }264 }265 }266267 private func reload() async {268 loading = true; error = nil269 do {270 let f = try await APIClient.shared.v3Sales(query.query)271 if Task.isCancelled { return }272 rows = f.value.items; cursor = f.value.nextCursor; total = f.value.total; totalAll = f.value.totalAll273 updatedTo = f.value.updatedTo; stale = f.stale274 } catch is CancellationError {275 return276 } catch {277 rows = []; total = 0; self.error = apiError(error)278 }279 loading = false280 }281282 private func loadMore() async {283 guard !loading, let c = cursor else { return }284 loading = true285 defer { loading = false }286 let current = query287 if let f = try? await APIClient.shared.v3Sales(current.query, cursor: c), current == query {288 let known = Set(rows.map(\.id))289 rows += f.value.items.filter { !known.contains($0.id) }290 cursor = f.value.nextCursor291 }292 }293}294295private struct SaleQuerySheet: View {296 @Binding var query: SaleQuery297 @Environment(\.dismiss) private var dismiss298299 var body: some View {300 NavigationStack {301 ScrollView {302 VStack(alignment: .leading, spacing: 22) {303 VStack(alignment: .leading, spacing: 10) {304 Text("Type de vente").eyebrowStyle()305 FlowChips(options: SaleQuery.types, selection: $query.type)306 }307 VStack(alignment: .leading, spacing: 10) {308 Text("Prix de vente").eyebrowStyle()309 PriceRangeFields(min: $query.min, max: $query.max)310 }311 VStack(alignment: .leading, spacing: 10) {312 Text("Tri").eyebrowStyle()313 Picker("Tri", selection: $query.sort) {314 ForEach(SaleQuery.Sort.allCases) { Text($0.label).tag($0) }315 }316 .pickerStyle(.inline).labelsHidden()317 }318 }319 .padding(Theme.margin)320 }321 .background(Theme.bg)322 .navigationTitle("Filtres")323 .navigationBarTitleDisplayMode(.inline)324 .toolbar {325 ToolbarItem(placement: .topBarLeading) {326 Button("Réinitialiser") { query.type = ""; query.min = nil; query.max = nil; query.sort = .recentes }.disabled(query.extraCount == 0)327 }328 ToolbarItem(placement: .confirmationAction) { Button("Terminé") { dismiss() }.fontWeight(.semibold) }329 }330 }331 }332}333334/// Une vente du registre : prix payé, adresse, date, et sa qualification (jamais cachée).335struct SaleV3Row: View {336 let sale: SaleV3337 var showPlace = true338 let action: () -> Void339 @Environment(\.dynamicTypeSize) private var typeSize340341 var body: some View {342 Button(action: action) {343 VStack(spacing: 0) {344 HStack(spacing: 8) {345 VStack(alignment: .leading, spacing: 4) {346 HStack(alignment: .firstTextBaseline) {347 Text(Fmt.money(sale.prix)).font(.body.weight(.semibold)).num().foregroundStyle(Theme.ink)348 Spacer(minLength: 8)349 Text(Fmt.day(sale.date, short: true)).font(.footnote).num().foregroundStyle(Theme.ink3)350 }351 Text(sale.title).font(.subheadline).foregroundStyle(Theme.ink).lineLimit(2).multilineTextAlignment(.leading)352 Text(detail).font(.footnote).num().foregroundStyle(Theme.ink3).lineLimit(2).multilineTextAlignment(.leading)353 if sale.deMarche == false {354 HStack(spacing: 6) {355 PlainTag(text: "Hors marché", tone: Theme.high, dashed: true)356 if let m = sale.marques.first {357 Text(m.libelle).font(.caption).foregroundStyle(Theme.ink3).lineLimit(1)358 }359 }360 } else if sale.deMarche == nil {361 PlainTag(text: "Pas encore qualifiée", dashed: true)362 }363 }364 Image(systemName: "chevron.right").font(.caption.weight(.semibold)).foregroundStyle(Theme.ink3)365 }366 .padding(.vertical, 11)367 Hairline()368 }369 .contentShape(Rectangle())370 }371 .buttonStyle(.plain)372 .accessibilityElement(children: .ignore)373 .accessibilityAddTraits(.isButton)374 .accessibilityLabel("Vendue \(Fmt.money(sale.prix)) le \(Fmt.day(sale.date)). \(sale.title). \(detail)." + (sale.deMarche == false ? " Vente hors marché." : ""))375 }376377 private var detail: String {378 var p: [String] = []379 if showPlace, let c = sale.ville { p.append(c) }380 if let t = sale.typeLabel { p.append(t) }381 if let y = sale.annee, y > 1700 { p.append(String(y)) }382 if let r = sale.ratioRole { p.append("\(Fmt.decimal(r, digits: 2)) × le rôle") }383 return p.joined(separator: " · ")384 }385}386387// MARK: - Détail d'une vente388389struct SaleV3View: View {390 let id: String391 @Environment(AppModel.self) private var model392 @State private var state: Loadable<SaleDetailV3> = .loading393394 var body: some View {395 ScrollView {396 Group {397 switch state {398 case .loading: LoadingState(label: "Chargement de la vente").padding(.top, 40)399 case .failed(let e): ErrorState(error: e, subject: "Cette vente") { Task { await load() } }.padding(.top, 40)400 case .loaded(let d, let stale): content(d, stale: stale)401 }402 }403 .pageColumn()404 .padding(.bottom, 40)405 }406 .background(Theme.bg)407 .navigationTitle("Vente")408 .navigationBarTitleDisplayMode(.inline)409 .toolbar {410 ToolbarItem(placement: .topBarTrailing) {411 ShareLink(item: APIClient.site.appending(path: "ventes").appending(path: id)) { Image(systemName: "square.and.arrow.up") }412 .accessibilityLabel("Partager")413 }414 }415 .task { await load() }416 }417418 private func load() async {419 if state.value != nil { return }420 do { let f = try await APIClient.shared.v3Sale(id); state = .loaded(f.value, stale: f.stale) }421 catch is CancellationError {}422 catch { state = .failed(apiError(error)) }423 }424425 @ViewBuilder426 private func content(_ d: SaleDetailV3, stale: Bool) -> some View {427 let s = d.vente428 VStack(alignment: .leading, spacing: 0) {429 if stale { StaleNotice().padding(.top, 8) }430 VStack(alignment: .leading, spacing: 5) {431 Text([s.typeLabel, s.ville].compactMap { $0 }.joined(separator: " · ")).eyebrowStyle()432 Text(s.title).font(.editorial(26)).foregroundStyle(Theme.ink).fixedSize(horizontal: false, vertical: true)433 .accessibilityAddTraits(.isHeader).accessibilityIdentifier("sale-title")434 }435 .padding(.top, 10)436437 VStack(alignment: .leading, spacing: 4) {438 Text("Prix de vente").eyebrowStyle()439 Text(Fmt.money(s.prix)).font(.display(36)).num().foregroundStyle(Theme.ink).accessibilityIdentifier("sale-price")440 Text("Vendue le \(Fmt.day(s.date))").font(.subheadline).num().foregroundStyle(Theme.ink2)441 }442 .padding(.top, 18)443444 // qualification445 VStack(alignment: .leading, spacing: 0) {446 SectionHeader("Qualification", note: "Ce que le moteur retient de cette vente pour mesurer le marché.")447 if !d.connue {448 NoteBlock(text: "Cette vente est arrivée depuis la dernière passe du moteur : elle n'est pas encore qualifiée.", dashed: true).padding(.top, 12)449 } else {450 HStack(spacing: 8) {451 PlainTag(text: d.deMarche == true ? "Vente de marché" : "Hors marché", tone: d.deMarche == true ? Theme.ink : Theme.high, dashed: d.deMarche != true)452 Spacer()453 }454 .padding(.top, 12)455 ForEach(d.marques, id: \.code) { m in456 NoteBlock(text: Fmt.capitalized(m.libelle), dashed: true).padding(.top, 10)457 }458 VStack(spacing: 0) {459 if let r = d.roleALaVente {460 FactRow("Valeur au rôle en vigueur à la vente" + (d.roleAnnee.map { " (référence \($0))" } ?? ""), Fmt.money(r))461 }462 if let r = d.ratio { FactRow("Prix payé sur le rôle", Fmt.decimal(r, digits: 2) + " ×") }463 if let r = d.ratioAttendu { FactRow("Rapport attendu dans ce marché", Fmt.decimal(r, digits: 2) + " ×") }464 if let a = d.bandeBas, let b = d.bandeHaut {465 FactRow("Bande d'un prix de marché", "\(Fmt.decimal(a, digits: 2)) à \(Fmt.decimal(b, digits: 2)) ×")466 }467 }468 .padding(.top, 8)469 }470 }471 .padding(.top, 28)472473 // rattachement et propriété474 VStack(alignment: .leading, spacing: 0) {475 SectionHeader("Propriété vendue")476 if let l = d.rattachementLibelle {477 Text(Fmt.capitalized(l) + ".").font(.subheadline).foregroundStyle(Theme.ink2).fixedSize(horizontal: false, vertical: true).padding(.top, 10)478 }479 if let pid = d.proprieteId {480 Button { model.openProperty(pid) } label: {481 VStack(spacing: 0) {482 HStack(alignment: .center, spacing: 12) {483 VStack(alignment: .leading, spacing: 3) {484 Text(d.proprieteTitre ?? "Propriété").font(.subheadline.weight(.medium)).foregroundStyle(Theme.ink)485 if let g = d.proprieteGenre { Text(Fmt.capitalized(g)).font(.footnote).foregroundStyle(Theme.ink3) }486 }487 Spacer(minLength: 8)488 ValueView(value: d.proprieteValeur, size: .line)489 Image(systemName: "chevron.right").font(.caption.weight(.semibold)).foregroundStyle(Theme.ink3)490 }491 .padding(.vertical, 12)492 Hairline()493 }494 .contentShape(Rectangle())495 }496 .buttonStyle(.plain)497 .accessibilityIdentifier("sale-property")498 if let w = d.avertissementValeur {499 Text(Fmt.capitalized(w) + ".").font(.footnote).foregroundStyle(Theme.ink3).fixedSize(horizontal: false, vertical: true).padding(.top, 10)500 }501 } else {502 Text("Aucune unité du rôle n'est désignée par cette vente : la valeur d'une propriété ne peut pas lui être associée.")503 .font(.footnote).foregroundStyle(Theme.ink3).fixedSize(horizontal: false, vertical: true).padding(.top, 10)504 }505 VStack(spacing: 0) {506 if let y = s.annee, y > 1700 { FactRow("Année de construction", String(y)) }507 if let a = s.aireM2 { FactRow("Aire d'étages", Fmt.area(m2: a)) }508 if let t = s.terrainM2 { FactRow("Terrain", Fmt.area(m2: t)) }509 }510 .padding(.top, 6)511 }512 .padding(.top, 28)513514 if !d.autresUnite.isEmpty || !d.autresImmeuble.isEmpty {515 VStack(alignment: .leading, spacing: 0) {516 SectionHeader("Autres ventes")517 ForEach(d.autresUnite) { o in SaleV3Row(sale: o, showPlace: false) { model.open(.sale(o.id)) } }518 if !d.autresImmeuble.isEmpty {519 Text("Dans l'immeuble").eyebrowStyle().padding(.top, 18).padding(.bottom, 2)520 ForEach(d.autresImmeuble.prefix(12)) { o in SaleV3Row(sale: o, showPlace: false) { model.open(.sale(o.id)) } }521 }522 }523 .padding(.top, 28)524 }525526 if let c = s.coordinate {527 Button { model.showOnMap(lat: c.latitude, lng: c.longitude, layer: .sales, span: 0.008) } label: { Label("Voir sur la carte", systemImage: "map") }528 .buttonStyle(SecondaryButtonStyle()).padding(.top, 24)529 }530 }531 }532}533