Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : Vrai-Prix iOS9// File : VraiPrix/Features/Home/HomeView.swift10// Description : accueil — la recherche d'adresse avec autocomplétion (le11// point d'entrée : adresse → estimation), les ventes12// récentes réelles, les accès rapides.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-2818//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 SwiftUI9293struct HomeView: View {94 @Environment(AppModel.self) private var model95 @Environment(Library.self) private var library96 @State private var query = ""97 @State private var results: [SearchHit] = []98 @State private var places: [Municipality] = []99 @State private var streets: [SearchResponse.Street] = []100 @State private var searching = false101 @State private var searchError: APIError?102 @State private var searchedQuery = ""103 @State private var sales: Loadable<[Sale]> = .loading104 @State private var overview: SalesOverview?105 @State private var stats: ParkStats?106 @FocusState private var focused: Bool107108 private var trimmed: String { query.trimmingCharacters(in: .whitespaces) }109 private var isSearching: Bool { focused || !trimmed.isEmpty }110111 var body: some View {112 ScrollView {113 VStack(alignment: .leading, spacing: 0) {114 if !isSearching {115 Wordmark(size: 21).padding(.top, 8)116 Text("La valeur d'une propriété, mesurée.")117 .font(.editorial(30)).foregroundStyle(Theme.ink)118 .fixedSize(horizontal: false, vertical: true)119 .padding(.top, 22)120 .accessibilityAddTraits(.isHeader)121 Text("Une estimation pour chaque propriété du rôle d'évaluation du Québec, établie à partir des ventes réellement conclues.")122 .font(.body).foregroundStyle(Theme.ink2)123 .fixedSize(horizontal: false, vertical: true)124 .padding(.top, 8)125 }126 searchField.padding(.top, isSearching ? 8 : 20)127 if isSearching {128 searchResults.padding(.top, 6)129 } else {130 content131 }132 }133 .pageColumn()134 .padding(.bottom, 32)135 .animation(.easeOut(duration: 0.2), value: isSearching)136 }137 .scrollDismissesKeyboard(.interactively)138 .background(Theme.bg)139 .toolbar(.hidden, for: .navigationBar)140 .task(id: trimmed) { await runSearch() }141 .task { await load() }142 .refreshable { await load(force: true) }143 .onAppear {144 if let q = model.launchQuery, query.isEmpty { query = q }145 }146 .onChange(of: model.pendingQuery, initial: true) {147 if let q = model.pendingQuery { query = q; model.pendingQuery = nil }148 }149 }150151 // MARK: Recherche152153 private var searchField: some View {154 HStack(spacing: 10) {155 HStack(spacing: 10) {156 Image(systemName: "magnifyingglass").font(.body.weight(.medium)).foregroundStyle(Theme.ink3)157 TextField("Adresse : numéro et rue", text: $query)158 .focused($focused)159 .textInputAutocapitalization(.words)160 .autocorrectionDisabled()161 .submitLabel(.search)162 .font(.body)163 .foregroundStyle(Theme.ink)164 .accessibilityIdentifier("address-search")165 if searching {166 ProgressView().controlSize(.small)167 } else if !query.isEmpty {168 Button { query = ""; results = []; places = []; streets = [] } label: {169 Image(systemName: "xmark.circle.fill").foregroundStyle(Theme.ink3).frame(width: 32, height: 44)170 }171 .buttonStyle(.plain)172 .accessibilityLabel("Effacer")173 }174 }175 .padding(.horizontal, 14)176 .frame(minHeight: 54)177 .background(Theme.surface, in: RoundedRectangle(cornerRadius: Theme.radiusSmall, style: .continuous))178 .overlay(RoundedRectangle(cornerRadius: Theme.radiusSmall, style: .continuous).strokeBorder(focused ? Theme.brand : Theme.line2, lineWidth: focused ? 1.5 : 1))179 if isSearching {180 Button("Annuler") { query = ""; results = []; places = []; streets = []; focused = false }181 .font(.body).foregroundStyle(Theme.brand).frame(minHeight: 44)182 }183 }184 }185186 @ViewBuilder187 private var searchResults: some View {188 if trimmed.count < 2 {189 if library.searches.isEmpty {190 Text("Tapez le numéro puis le nom de la rue, ou le nom d'une municipalité.")191 .font(.subheadline).foregroundStyle(Theme.ink3).padding(.top, 14)192 } else {193 recentSearches.padding(.top, 14)194 }195 } else if let searchError, results.isEmpty, places.isEmpty {196 EmptyState(title: searchError.isOffline ? "Hors ligne" : "Recherche impossible",197 message: searchError.isOffline ? "La recherche d'adresse demande une connexion. Vos favoris et les fiches déjà consultées restent lisibles."198 : "Le service n'a pas répondu. Réessayez dans un instant.")199 } else if results.isEmpty, places.isEmpty, streets.isEmpty, !searching, searchedQuery == trimmed {200 EmptyState(title: "Adresse introuvable",201 message: "Aucune propriété du rôle ne correspond à « \(trimmed) ». Vérifiez le numéro et le nom de la rue, ou estimez sans adresse.",202 actionLabel: "Estimer sans adresse") { model.open(.manual) }203 } else {204 LazyVStack(alignment: .leading, spacing: 0) {205 // municipalités et rues qui portent ce nom, avant les adresses206 ForEach(places.prefix(3)) { m in207 Button { focused = false; model.open(.municipality(m.slug)) } label: {208 HStack(spacing: 12) {209 BrandIconView(icon: .municipalite, size: 22, color: Theme.ink2)210 VStack(alignment: .leading, spacing: 2) {211 Text(m.nom).font(.body).foregroundStyle(Theme.ink)212 Text("Municipalité · \(Fmt.int(m.n)) propriétés").font(.footnote).num().foregroundStyle(Theme.ink3)213 }214 Spacer(minLength: 8)215 Image(systemName: "chevron.right").font(.footnote.weight(.semibold)).foregroundStyle(Theme.ink3)216 }217 .padding(.vertical, 10).frame(minHeight: 56).contentShape(Rectangle())218 }219 .buttonStyle(.plain)220 .accessibilityIdentifier("search-municipality")221 Hairline()222 }223 ForEach(streets.prefix(3)) { r in224 Button { query = [r.title, r.municipalite].compactMap { $0 }.joined(separator: " ") } label: {225 HStack(spacing: 12) {226 Image(systemName: "road.lanes").font(.body).foregroundStyle(Theme.ink2).frame(width: 22)227 VStack(alignment: .leading, spacing: 2) {228 Text(r.title).font(.body).foregroundStyle(Theme.ink)229 Text(["Rue", r.municipalite].compactMap { $0 }.joined(separator: " · ")).font(.footnote).foregroundStyle(Theme.ink3)230 }231 Spacer(minLength: 8)232 Image(systemName: "arrow.up.left").font(.footnote.weight(.semibold)).foregroundStyle(Theme.ink3)233 }234 .padding(.vertical, 10).frame(minHeight: 56).contentShape(Rectangle())235 }236 .buttonStyle(.plain)237 .accessibilityLabel("Rue \(r.title), \(r.municipalite ?? ""). Lister ses adresses.")238 Hairline()239 }240 ForEach(Array(results.enumerated()), id: \.element.id) { i, hit in241 Button {242 library.remember(search: hit)243 focused = false244 model.openProperty(hit.id, trigger: .reveal)245 } label: {246 HStack(alignment: .firstTextBaseline, spacing: 12) {247 VStack(alignment: .leading, spacing: 2) {248 Text(hit.title).font(.body).foregroundStyle(Theme.ink).multilineTextAlignment(.leading)249 Text(hit.subtitle).font(.footnote).foregroundStyle(Theme.ink3)250 }251 Spacer(minLength: 8)252 if let e = hit.value, e > 0 {253 Text(Fmt.compact(e)).font(.subheadline.weight(.semibold)).num().foregroundStyle(Theme.ink2)254 }255 }256 .padding(.vertical, 12)257 .frame(minHeight: 56)258 .contentShape(Rectangle())259 }260 .buttonStyle(.plain)261 .accessibilityIdentifier("search-result-\(i)")262 Hairline()263 }264 }265 }266 }267268 private var recentSearches: some View {269 VStack(alignment: .leading, spacing: 0) {270 HStack {271 Text("Recherches récentes").eyebrowStyle()272 Spacer()273 Button("Effacer") { library.clearSearches() }.font(.footnote).foregroundStyle(Theme.brand).frame(minHeight: 44)274 }275 ForEach(library.searches) { s in276 Button { model.openProperty(s.id, trigger: .reveal) } label: {277 HStack(spacing: 12) {278 Image(systemName: "clock").font(.subheadline).foregroundStyle(Theme.ink3)279 VStack(alignment: .leading, spacing: 2) {280 Text(s.title).font(.body).foregroundStyle(Theme.ink)281 Text(s.subtitle).font(.footnote).foregroundStyle(Theme.ink3)282 }283 Spacer()284 }285 .padding(.vertical, 10).frame(minHeight: 52).contentShape(Rectangle())286 }287 .buttonStyle(.plain)288 Hairline()289 }290 }291 }292293 private func runSearch() async {294 let q = trimmed295 guard q.count >= 2 else { results = []; places = []; streets = []; searching = false; searchError = nil; return }296 searching = true297 // anti-rebond : la frappe suivante annule cette tâche298 try? await Task.sleep(for: .milliseconds(220))299 if Task.isCancelled { return }300 do {301 let r = try await APIClient.shared.search(q)302 if Task.isCancelled { return }303 results = r.results; places = r.municipalites; streets = r.rues; searchError = nil304 } catch is CancellationError {305 return306 } catch {307 results = []; places = []; streets = []; searchError = apiError(error)308 }309 searchedQuery = q310 searching = false311 }312313 // MARK: Contenu314315 @ViewBuilder316 private var content: some View {317 if !library.searches.isEmpty {318 VStack(alignment: .leading, spacing: 0) {319 Text("Dernières adresses").eyebrowStyle().padding(.bottom, 4)320 ForEach(library.searches.prefix(3)) { s in321 Button { model.openProperty(s.id, trigger: .reveal) } label: {322 HStack {323 VStack(alignment: .leading, spacing: 2) {324 Text(s.title).font(.subheadline.weight(.medium)).foregroundStyle(Theme.ink)325 Text(s.subtitle).font(.footnote).foregroundStyle(Theme.ink3)326 }327 Spacer()328 Image(systemName: "chevron.right").font(.footnote.weight(.semibold)).foregroundStyle(Theme.ink3)329 }330 .padding(.vertical, 10).frame(minHeight: 48).contentShape(Rectangle())331 }332 .buttonStyle(.plain)333 Hairline()334 }335 }336 .padding(.top, 22)337 }338339 // ventes récentes réelles340 SectionHeader("Ventes récentes", note: overview?.maxDate.map { "Transactions publiées jusqu'au \(Fmt.day($0))." }) {341 MoreLink(label: "Registre") { model.tab = .sales }342 }343 .padding(.top, 34)344 Group {345 switch sales {346 case .loading:347 LoadingState(label: "Chargement des ventes")348 case .failed(let e):349 ErrorState(error: e, subject: "La liste des ventes") { Task { await load(force: true) } }350 case .loaded(let rows, let stale):351 if stale { StaleNotice().padding(.top, 10) }352 if rows.isEmpty {353 EmptyState(title: "Aucune vente publiée", message: "Le registre ne contient aucune transaction pour le moment.")354 } else {355 LazyVStack(spacing: 0) {356 ForEach(Array(rows.enumerated()), id: \.element.id) { i, s in357 Button {358 if let id = s.idProvinc { model.openProperty(id) } else { model.tab = .sales }359 } label: { SaleRow(sale: s) }360 .buttonStyle(.plain)361 .staggered(i)362 Hairline()363 }364 }365 .padding(.top, 4)366 }367 }368 }369370 // accès rapides371 SectionHeader("Explorer").padding(.top, 34)372 VStack(spacing: 0) {373 NavRow(icon: .venteConclue, title: "Carte des ventes", detail: "Les transactions autour d'une adresse") { model.tab = .map }374 NavRow(icon: .roleEvaluation, title: "Registre des ventes", detail: overview?.n365.map { "\(Fmt.int($0)) ventes publiées en 12 mois" }) { model.tab = .sales }375 NavRow(icon: .ecart, title: "Propriétés à vendre", detail: "Le prix demandé face à la valeur estimée") { model.open(.listings(ListingFilters())) }376 NavRow(icon: .municipalite, title: "Municipalités", detail: stats?.municipalities.map { "\(Fmt.int($0)) municipalités du rôle" }) { model.open(.municipalities) }377 NavRow(icon: .indice, title: "Marché et indice", detail: "Évolution des prix depuis 2021") { model.tab = .market }378 NavRow(icon: .fourchette, title: "Estimer sans adresse", detail: "Municipalité, type et caractéristiques", divider: false) { model.open(.manual) }379 }380 .padding(.top, 4)381382 // le registre en bref : des faits, pas un bandeau de chiffres383 if let stats {384 SectionHeader("Ce que mesure Vrai-Prix").padding(.top, 34)385 FigureGrid {386 Figure(label: "Propriétés estimées", value: Fmt.int(stats.units_total), note: "rôle d'évaluation 2026")387 Figure(label: "Ventes au registre", value: Fmt.int(stats.sales), note: "depuis 2021")388 Figure(label: "Valeur médiane", value: Fmt.money(stats.value_median_2026), note: "estimation 2026")389 if let m = overview?.median30 {390 Figure(label: "Prix médian vendu", value: Fmt.money(m), note: "30 derniers jours")391 }392 }393 .padding(.top, 14)394 Button { model.open(.methodology) } label: {395 Text("Comment la valeur est calculée").font(.subheadline.weight(.medium)).foregroundStyle(Theme.brand)396 .frame(minHeight: 44)397 }398 .buttonStyle(.plain)399 .padding(.top, 10)400 }401402 Hairline().padding(.top, 28)403 Text("Estimations statistiques à titre indicatif. Elles ne remplacent pas le rapport d'un évaluateur agréé.")404 .font(.footnote).foregroundStyle(Theme.ink3).fixedSize(horizontal: false, vertical: true)405 .padding(.top, 14)406 }407408 private func load(force: Bool = false) async {409 if !force, sales.value != nil { return }410 async let page = APIClient.shared.sales(SaleFilters(period: .d30), limit: 8)411 async let ov = try? APIClient.shared.salesOverview()412 async let st = try? APIClient.shared.parkStats()413 do {414 let p = try await page415 sales = .loaded(p.value.rows, stale: p.stale)416 } catch is CancellationError {417 } catch {418 if sales.value == nil { sales = .failed(apiError(error)) }419 }420 if let o = await ov { overview = o }421 if let s = await st { stats = s }422 }423}424