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/FreeEstimateView.swift10// Description : estimation sans adresse sous l'API v3 : un ordre de11// grandeur pour un bien décrit à la main, fondé sur les12// seules ventes de marché du voisinage. Jamais une valeur13// ferme, jamais une position de prix ; le service s'abstient14// quand les comparables manquent ou sont trop loin.15// Module : VraiPrix16// Repository : https://git.spboucher.ai/vrai-prix-ios-v317// Project Website : https://www.vrai-prix.com18// Created : 2026-11-2819// Last Modified : 2026-11-2820//21// =============================================================================22// AUTHOR & PROFESSIONAL AFFILIATION23// =============================================================================24//25// Author : Simon-Pierre Boucher26// Position : Professor of Finance27// Institution : Université du Québec en Outaouais (UQO)28// Department : Département des sciences administratives29// Organization : SP Boucher30//31// Website : https://spboucher.ai32// Git : https://git.spboucher.ai33//34// =============================================================================35// OFFICIAL CONTACT DIRECTORY36// =============================================================================37//38// General : info@spboucher.ai39// Professional : contact@spboucher.ai40// Direct : simon@spboucher.ai41// Research : research@spboucher.ai42// Development : dev@spboucher.ai43// Support : support@spboucher.ai44// Security/Admin : admin@spboucher.ai45// Notifications : notifications@spboucher.ai46//47// Preferred Contact: support@spboucher.ai48//49// =============================================================================50// COPYRIGHT & INTELLECTUAL PROPERTY51// =============================================================================52//53// Copyright (c) 202654// Simon-Pierre Boucher55//56// All rights reserved where applicable.57//58// This file is governed by the applicable project license,59// copyright notices, institutional agreements and relevant law.60//61// Unless expressly authorized by the applicable license or62// rights holder, copying, redistribution, sublicensing,63// publication and commercial exploitation are not permitted.64//65// Existing third-party rights and notices remain unaffected.66//67// =============================================================================68// CONFIDENTIALITY & SECURITY69// =============================================================================70//71// Classification : Public72// Distribution : Public repository; use is governed by the project license73// Security Contact : admin@spboucher.ai74//75// Access to this source does not independently grant permission76// to redistribute or disclose confidential materials.77//78// Do not embed credentials, private keys, access tokens,79// certificates or confidential personal information.80//81// =============================================================================82// LICENSE & MAINTENANCE83// =============================================================================84//85// License : None specified (no license file in this repository)86// Maintainer : Simon-Pierre Boucher87// Technical Contact: dev@spboucher.ai88//89// =============================================================================90// END OF SP BOUCHER SOURCE HEADER91// =============================================================================9293import SwiftUI9495struct FreeEstimateView: View {96 @Environment(AppModel.self) private var model97 @State private var place: TerritoryRef?98 @State private var genre = "maison"99 @State private var area: Double?100 @State private var year: Int?101 @State private var pick = false102 @State private var result: Loadable<FreeEstimateV3>?103104 static let genres: [(key: String, label: String)] = [("maison", "Maison"), ("condo", "Copropriété"), ("plex", "Plex"), ("chalet", "Chalet"), ("maison-mobile", "Maison mobile")]105106 var body: some View {107 ScrollViewReader { proxy in108 ScrollView {109 VStack(alignment: .leading, spacing: 0) {110 Text("Sans adresse, Vrai-Prix ne rend qu'un ordre de grandeur : la médiane des ventes de marché du voisinage, pas le modèle de valeur. Pour une valeur et son intervalle, cherchez l'adresse.")111 .font(.body).foregroundStyle(Theme.ink2).fixedSize(horizontal: false, vertical: true)112113 Text("Municipalité").eyebrowStyle().padding(.top, 22).padding(.bottom, 8)114 Button { pick = true } label: {115 HStack {116 Text(place?.title ?? "Choisir une municipalité").foregroundStyle(place == nil ? Theme.ink3 : Theme.ink)117 Spacer()118 Image(systemName: "chevron.right").font(.footnote.weight(.semibold)).foregroundStyle(Theme.ink3)119 }120 .padding(.horizontal, 12).frame(minHeight: 48)121 .background(Theme.surface, in: RoundedRectangle(cornerRadius: Theme.radiusSmall, style: .continuous))122 .overlay(RoundedRectangle(cornerRadius: Theme.radiusSmall, style: .continuous).strokeBorder(Theme.lineControl, lineWidth: 1))123 .contentShape(Rectangle())124 }125 .buttonStyle(.plain)126 .accessibilityIdentifier("free-municipality")127128 Text("Genre de propriété").eyebrowStyle().padding(.top, 20).padding(.bottom, 8)129 FlowChips(options: FreeEstimateView.genres, selection: $genre)130131 HStack(alignment: .top, spacing: 12) {132 field("Aire d'étages (m²)", value: $area, id: "free-area")133 field("Année de construction", value: Binding(get: { year.map(Double.init) }, set: { year = $0.map { Int($0) } }), id: "free-year")134 }135 .padding(.top, 20)136137 Button { Task { await run(); withAnimation { proxy.scrollTo("result", anchor: .top) } } } label: {138 if result?.isLoading == true { ProgressView().tint(Theme.actionInk) } else { Text("Estimer l'ordre de grandeur") }139 }140 .buttonStyle(PrimaryButtonStyle())141 .disabled(place == nil || result?.isLoading == true)142 .padding(.top, 24)143 .accessibilityIdentifier("free-submit")144145 if let result { resultView(result).padding(.top, 28).id("result") }146 }147 .pageColumn()148 .padding(.top, 6).padding(.bottom, 40)149 }150 }151 .scrollDismissesKeyboard(.interactively)152 .background(Theme.bg)153 .navigationTitle("Estimer sans adresse")154 .navigationBarTitleDisplayMode(.inline)155 .sheet(isPresented: $pick) { MunicipalityPicker { place = $0 } }156 .task {157 // captures et tests : -VPFree <slug de municipalité>158 if place == nil, let slug = UserDefaults.standard.string(forKey: "VPFree"),159 let t = try? await APIClient.shared.v3Territory(slug).value.ref {160 place = t; area = 110; year = 1985161 await run()162 }163 }164 }165166 private func field(_ label: String, value: Binding<Double?>, id: String) -> some View {167 VStack(alignment: .leading, spacing: 8) {168 Text(label).eyebrowStyle()169 TextField("Facultatif", value: value, format: .number.grouping(.never))170 .keyboardType(.numberPad)171 .font(.body.monospacedDigit())172 .padding(.horizontal, 12).frame(minHeight: 48)173 .background(Theme.surface, in: RoundedRectangle(cornerRadius: Theme.radiusSmall, style: .continuous))174 .overlay(RoundedRectangle(cornerRadius: Theme.radiusSmall, style: .continuous).strokeBorder(Theme.lineControl, lineWidth: 1))175 .accessibilityIdentifier(id)176 }177 .frame(maxWidth: .infinity, alignment: .leading)178 }179180 private func run() async {181 guard let place else { return }182 result = .loading183 do {184 result = .loaded(try await APIClient.shared.v3FreeEstimate(genre: genre, municipality: place.slug ?? place.id, lat: nil, lng: nil,185 areaM2: area.flatMap { $0 >= 10 && $0 <= 5000 ? $0 : nil },186 year: year.flatMap { $0 > 1700 && $0 <= 2100 ? $0 : nil }), stale: false)187 } catch is CancellationError {188 } catch { result = .failed(apiError(error)) }189 }190191 @ViewBuilder192 private func resultView(_ r: Loadable<FreeEstimateV3>) -> some View {193 switch r {194 case .loading: ProgressView().frame(maxWidth: .infinity)195 case .failed(let e): ErrorState(error: e, subject: "L'estimation") { Task { await run() } }196 case .loaded(let e, _):197 VStack(alignment: .leading, spacing: 0) {198 Hairline(color: Theme.line2)199 if e.status == .ordre, let v = e.value, let lo = e.low, let hi = e.high {200 Text("Ordre de grandeur").eyebrowStyle().padding(.top, 16)201 Text(ValueFmt.approx(v)).font(.display(36, weight: .regular)).num().foregroundStyle(Theme.ink)202 .accessibilityIdentifier("free-value")203 Text("La moitié centrale des prix payés : \(ValueFmt.interval(lo, hi))").font(.footnote).num().foregroundStyle(Theme.ink3)204 .fixedSize(horizontal: false, vertical: true).padding(.top, 2)205 IntervalBar(value: v, low: lo, high: hi, approximate: true).padding(.top, 14)206 NoteBlock(text: "Ce n'est pas l'intervalle du modèle : environ \(e.dansIntervallePct.map { Fmt.decimal($0, digits: 0) } ?? "quatre") prix payés sur cent seulement tombent dans cette moitié centrale. Aucun prix n'est situé face à un ordre de grandeur.", dashed: true)207 .padding(.top, 14)208 } else {209 Text("Aucune estimation").font(.editorial(24)).foregroundStyle(Theme.ink).padding(.top, 16).accessibilityIdentifier("free-abstention")210 Text((e.motif.map { Fmt.capitalized($0.libelle) + "." } ?? "Les ventes comparables manquent.") + " Le service s'abstient plutôt que d'écrire un chiffre.")211 .font(.subheadline).foregroundStyle(Theme.ink2).fixedSize(horizontal: false, vertical: true).padding(.top, 6)212 }213 VStack(spacing: 0) {214 if let n = e.nVentes { FactRow("Ventes de marché lues", Fmt.int(n)) }215 if let k = e.rayonKm { FactRow("Rayon de recherche", Fmt.decimal(k, digits: 1) + " km") }216 if let a = e.depuis, let b = e.jusqua { FactRow("Période", "\(Fmt.day(a, short: true)) au \(Fmt.day(b, short: true))") }217 if let p = e.precision { FactRow("Point de départ", Fmt.capitalized(p)) }218 if let m = e.erreurMedianePct { FactRow("Erreur médiane mesurée de cette méthode", Fmt.decimal(m, digits: 1) + Fmt.nbsp + "%") }219 }220 .padding(.top, 14)221 if !e.comparables.isEmpty {222 SectionHeader("Les ventes lues").padding(.top, 26)223 ForEach(Array(e.comparables.enumerated()), id: \.element.id) { i, c in224 ComparableRow(index: i + 1, item: c) {225 if let pid = c.proprieteId { model.openProperty(pid) } else { model.open(.sale(c.venteId)) }226 }227 }228 }229 }230 }231 }232}233234extension Loadable {235 var isLoading: Bool { if case .loading = self { return true } else { return false } }236}237238/// Choix d'une municipalité, par le début de son nom.239struct MunicipalityPicker: View {240 let pick: (TerritoryRef) -> Void241 @Environment(\.dismiss) private var dismiss242 @State private var text = ""243 @State private var rows: [TerritoryItemV3] = []244245 var body: some View {246 NavigationStack {247 List(rows) { t in248 Button { pick(t.ref); dismiss() } label: {249 VStack(alignment: .leading, spacing: 2) {250 Text(t.ref.title).foregroundStyle(Theme.ink)251 if let n = t.nbUnites { Text("\(Fmt.int(n)) propriétés").font(.footnote).monospacedDigit().foregroundStyle(Theme.ink3) }252 }253 }254 .accessibilityIdentifier("municipality-" + (t.ref.slug ?? t.ref.id))255 }256 .listStyle(.plain)257 .searchable(text: $text, placement: .navigationBarDrawer(displayMode: .always), prompt: "Nom de la municipalité")258 .navigationTitle("Municipalité")259 .navigationBarTitleDisplayMode(.inline)260 .toolbar { ToolbarItem(placement: .cancellationAction) { Button("Fermer") { dismiss() } } }261 .task(id: text) {262 let q = text.trimmingCharacters(in: .whitespaces)263 if !q.isEmpty { try? await Task.sleep(for: .milliseconds(250)) }264 if Task.isCancelled { return }265 if let r = try? await APIClient.shared.v3Territories(level: "municipalite", q: q.count >= 2 ? q : nil, limit: 60), !Task.isCancelled { rows = r.items }266 }267 }268 }269}270