SPB Git

Repository Public

HomeV3View.swift 18.5 KB 376 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : Vrai-Prix iOS9// File             : VraiPrix/Features/V3/HomeV3View.swift10// Description      : l'onglet Estimer sous l'API v3. Une recherche unique11//                    (adresses du rôle et lieux, fautes tolérées), puis des12//                    chiffres qui viennent du modèle et du registre : ce que le13//                    modèle couvre, sa mesure hors échantillon, les dernières14//                    ventes de marché.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 HomeV3View: View {96    @Environment(AppModel.self) private var model97    @Environment(Library.self) private var library98    @State private var query = ""99    @State private var results: SearchV3?100    @State private var searching = false101    @State private var searchError: APIError?102    @State private var searchedQuery = ""103    @State private var modelInfo: ModelV3?104    @State private var sales: Loadable<[SaleV3]> = .loading105    @State private var units: SearchV3.Address?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é, et ce qu'on en sait vraiment.")117                        .font(.editorial(30)).foregroundStyle(Theme.ink)118                        .fixedSize(horizontal: false, vertical: true)119                        .padding(.top, 22)120                        .accessibilityAddTraits(.isHeader)121                    Text("Une valeur et son intervalle pour les propriétés du rôle d'évaluation du Québec, mesurées contre les ventes réellement conclues. Quand le modèle ne peut pas défendre un chiffre, il ne l'écrit pas.")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 { searchResults.padding(.top, 6) } else { content }128            }129            .pageColumn()130            .padding(.bottom, 32)131            .animation(.easeOut(duration: 0.2), value: isSearching)132        }133        .scrollDismissesKeyboard(.interactively)134        .background(Theme.bg)135        .toolbar(.hidden, for: .navigationBar)136        .task(id: trimmed) { await runSearch() }137        .task { await load() }138        .refreshable { await load(force: true) }139        .onAppear { if let q = model.launchQuery, query.isEmpty { query = q } }140        .onChange(of: model.pendingQuery, initial: true) {141            if let q = model.pendingQuery { query = q; model.pendingQuery = nil }142        }143        .confirmationDialog(units.map { "\($0.title) : \($0.nbUnites) unités" } ?? "", isPresented: Binding(get: { units != nil }, set: { if !$0 { units = nil } }), titleVisibility: .visible) {144            if let a = units {145                ForEach(a.unites.prefix(12)) { u in146                    Button(u.appartement.map { "Appartement \($0)" } ?? "Unité") { open(u.id, title: a.title + (u.appartement.map { ", app. \($0)" } ?? ""), subtitle: a.subtitle) }147                }148            }149        }150    }151152    // MARK: Recherche153154    private var searchField: some View {155        HStack(spacing: 10) {156            HStack(spacing: 10) {157                Image(systemName: "magnifyingglass").font(.body.weight(.medium)).foregroundStyle(Theme.ink3)158                TextField("Adresse, rue ou municipalité", text: $query)159                    .focused($focused)160                    .textInputAutocapitalization(.words)161                    .autocorrectionDisabled()162                    .submitLabel(.search)163                    .font(.body)164                    .foregroundStyle(Theme.ink)165                    .accessibilityIdentifier("address-search")166                if searching {167                    ProgressView().controlSize(.small)168                } else if !query.isEmpty {169                    Button { query = ""; results = nil } label: {170                        Image(systemName: "xmark.circle.fill").foregroundStyle(Theme.ink3).frame(width: 32, height: 44)171                    }172                    .buttonStyle(.plain)173                    .accessibilityLabel("Effacer")174                }175            }176            .padding(.horizontal, 14)177            .frame(minHeight: 54)178            .background(Theme.surface, in: RoundedRectangle(cornerRadius: Theme.radiusSmall, style: .continuous))179            .overlay(RoundedRectangle(cornerRadius: Theme.radiusSmall, style: .continuous).strokeBorder(focused ? Theme.brand : Theme.lineControl, lineWidth: focused ? 1.5 : 1))180            if isSearching {181                Button("Annuler") { query = ""; results = nil; focused = false }182                    .font(.body).foregroundStyle(Theme.brand).frame(minHeight: 44)183            }184        }185    }186187    private func open(_ id: String, title: String, subtitle: String) {188        library.remember(searchID: id, title: title, subtitle: subtitle)189        focused = false190        model.openProperty(id, trigger: .reveal)191    }192193    @ViewBuilder194    private var searchResults: some View {195        if trimmed.count < 2 {196            if library.searches.isEmpty {197                Text("Tapez le numéro puis le nom de la rue, le nom d'une rue ou celui d'une municipalité.")198                    .font(.subheadline).foregroundStyle(Theme.ink3).padding(.top, 14)199            } else {200                recents(all: true).padding(.top, 14)201            }202        } else if let searchError, results == nil {203            EmptyState(title: searchError.isOffline ? "Hors ligne" : "Recherche impossible",204                       message: searchError.isOffline ? "La recherche demande une connexion. Vos favoris et les fiches déjà consultées restent lisibles."205                           : "Le service n'a pas répondu. Réessayez dans un instant.")206        } else if let r = results, r.isEmpty, !searching, searchedQuery == trimmed {207            EmptyState(title: "Rien à cette adresse",208                       message: "Aucune propriété du rôle ni aucun lieu ne correspond à « \(trimmed) ». Vérifiez le numéro et le nom de la rue, ou estimez sans adresse.",209                       actionLabel: "Estimer sans adresse") { model.open(.manual) }210        } else if let r = results {211            LazyVStack(alignment: .leading, spacing: 0) {212                if !r.corrections.isEmpty {213                    Text("Recherche corrigée : " + r.corrections.joined(separator: ", ")).font(.footnote).foregroundStyle(Theme.ink3).padding(.vertical, 8)214                }215                ForEach(Array(r.adresses.enumerated()), id: \.element.id) { i, a in216                    Button {217                        if let id = a.uniteId ?? (a.unites.count == 1 ? a.unites.first?.id : nil) { open(id, title: a.title, subtitle: a.subtitle) }218                        else if !a.unites.isEmpty { focused = false; units = a }219                    } label: {220                        HStack(alignment: .firstTextBaseline, spacing: 12) {221                            VStack(alignment: .leading, spacing: 2) {222                                Text(a.title).font(.body).foregroundStyle(Theme.ink).multilineTextAlignment(.leading)223                                Text(a.subtitle).font(.footnote).num().foregroundStyle(Theme.ink3)224                            }225                            Spacer(minLength: 8)226                            Image(systemName: a.uniteId == nil && a.unites.count > 1 ? "list.bullet" : "chevron.right").font(.footnote.weight(.semibold)).foregroundStyle(Theme.ink3)227                        }228                        .padding(.vertical, 12).frame(minHeight: 56).contentShape(Rectangle())229                    }230                    .buttonStyle(.plain)231                    .accessibilityIdentifier("search-result-\(i)")232                    Hairline()233                }234                ForEach(r.lieux.prefix(6)) { p in235                    Button { focused = false; openPlace(p) } label: {236                        HStack(spacing: 12) {237                            if p.type == "rue" { Image(systemName: "road.lanes").font(.body).foregroundStyle(Theme.ink2).frame(width: 22) }238                            else { BrandIconView(icon: .municipalite, size: 22, color: Theme.ink2) }239                            VStack(alignment: .leading, spacing: 2) {240                                Text(p.title).font(.body).foregroundStyle(Theme.ink)241                                Text(p.subtitle).font(.footnote).num().foregroundStyle(Theme.ink3)242                            }243                            Spacer(minLength: 8)244                            Image(systemName: "chevron.right").font(.footnote.weight(.semibold)).foregroundStyle(Theme.ink3)245                        }246                        .padding(.vertical, 10).frame(minHeight: 56).contentShape(Rectangle())247                    }248                    .buttonStyle(.plain)249                    .accessibilityIdentifier(p.type == "rue" ? "search-street" : "search-municipality")250                    Hairline()251                }252            }253        }254    }255256    /// Une municipalité s'ouvre par son slug ; une rue se résout par la liste des rues de sa municipalité.257    private func openPlace(_ p: SearchV3.Place) {258        if let t = p.territory { model.open(.territory(t)); return }259        guard let muni = p.municipaliteSlug else { return }260        Task {261            let found = try? await APIClient.shared.v3Territories(level: "rue", q: p.nom, parent: muni, limit: 10)262            let key = { (s: String) in s.folding(options: [.diacriticInsensitive, .caseInsensitive], locale: nil) }263            if let hit = found?.items.first(where: { key($0.ref.nom) == key(p.nom) }) ?? found?.items.first {264                model.open(.territory(hit.ref.id))265            } else {266                model.showToast("Cette rue n'a pas de portrait")267            }268        }269    }270271    private func recents(all: Bool) -> some View {272        VStack(alignment: .leading, spacing: 0) {273            HStack {274                Text(all ? "Recherches récentes" : "Dernières adresses").eyebrowStyle()275                Spacer()276                if all { Button("Effacer") { library.clearSearches() }.font(.footnote).foregroundStyle(Theme.brand).frame(minHeight: 44) }277            }278            ForEach(library.searches.prefix(all ? 8 : 3)) { s in279                Button { model.openProperty(s.id, trigger: .reveal) } label: {280                    HStack(spacing: 12) {281                        VStack(alignment: .leading, spacing: 2) {282                            Text(s.title).font(.subheadline.weight(.medium)).foregroundStyle(Theme.ink)283                            Text(s.subtitle).font(.footnote).foregroundStyle(Theme.ink3)284                        }285                        Spacer()286                        Image(systemName: "chevron.right").font(.footnote.weight(.semibold)).foregroundStyle(Theme.ink3)287                    }288                    .padding(.vertical, 10).frame(minHeight: 48).contentShape(Rectangle())289                }290                .buttonStyle(.plain)291                Hairline()292            }293        }294    }295296    private func runSearch() async {297        let q = trimmed298        guard q.count >= 2 else { results = nil; searching = false; searchError = nil; return }299        searching = true300        try? await Task.sleep(for: .milliseconds(220))301        if Task.isCancelled { return }302        do {303            let r = try await APIClient.shared.v3Search(q)304            if Task.isCancelled { return }305            results = r; searchError = nil306        } catch is CancellationError {307            return308        } catch {309            results = nil; searchError = apiError(error)310        }311        searchedQuery = q312        searching = false313    }314315    // MARK: Contenu316317    @ViewBuilder318    private var content: some View {319        if !library.searches.isEmpty { recents(all: false).padding(.top, 26) }320321        if let m = modelInfo {322            VStack(alignment: .leading, spacing: 0) {323                SectionHeader("Ce que le modèle sait, et ce qu'il ne sait pas",324                              note: m.dateValeur.map { "Valeurs au \(Fmt.day($0))" + (m.derniereVenteApprise.map { ", ventes apprises jusqu'au \(Fmt.day($0))." } ?? ".") }) {325                    MoreLink(label: "Méthode") { model.open(.methodology) }326                }327                ForEach(m.regimes, id: \.label) { r in328                    FactRow(label: r.label) {329                        Text("\(Fmt.int(r.n))" + (m.parcUnites.map { " · " + Fmt.share(Double(r.n) / Double(max($0, 1))) } ?? ""))330                            .font(.subheadline.weight(.semibold)).num().foregroundStyle(Theme.ink)331                    }332                }333                FigureGrid {334                    if let e = m.erreurMedianeMarche { Figure(label: "Erreur médiane, ventes de marché", value: Fmt.decimal(e, digits: 1) + Fmt.nbsp + "%", note: "mesurée sur des ventes jamais vues") }335                    if let c = m.couverture { Figure(label: "Prix payés dans l'intervalle", value: Fmt.decimal(c, digits: 1) + Fmt.nbsp + "%", note: "pour 80 % annoncés") }336                }337                .padding(.top, 16)338            }339            .padding(.top, 30)340            .accessibilityIdentifier("home-model")341        }342343        VStack(alignment: .leading, spacing: 0) {344            SectionHeader("Dernières ventes de marché", note: "Prix de vente réels, publiés au registre.") {345                MoreLink { model.tab = .sales }346            }347            switch sales {348            case .loading: ProgressView().frame(maxWidth: .infinity).padding(.vertical, 26)349            case .failed: Text("Les ventes n'ont pas pu être chargées.").font(.subheadline).foregroundStyle(Theme.ink3).padding(.top, 10)350            case .loaded(let rows, _):351                ForEach(rows.prefix(5)) { s in SaleV3Row(sale: s) { model.open(.sale(s.id)) } }352            }353        }354        .padding(.top, 30)355356        VStack(spacing: 0) {357            SectionHeader("Explorer").padding(.top, 30)358            Hairline().padding(.top, 8)359            NavRow(icon: .comparables, title: "Propriétés à vendre", detail: "Le prix demandé face à l'intervalle") { model.open(.listingsV3(ListingQuery())) }360            NavRow(icon: .indice, title: "Marché et indice", detail: "Ventes réelles, prix demandés, valeurs, par territoire") { model.tab = .market }361            NavRow(icon: .fourchette, title: "Estimer sans adresse", detail: "Un ordre de grandeur, par les ventes du voisinage", divider: false) { model.open(.manual) }362        }363    }364365    private func load(force: Bool = false) async {366        if !force, modelInfo != nil, sales.value != nil { return }367        async let mi = try? APIClient.shared.v3Model()368        do {369            let f = try await APIClient.shared.v3Sales(SaleQuery(period: .d30, marketOnly: true).query, limit: 6)370            sales = .loaded(f.value.items, stale: f.stale)371        } catch is CancellationError {372        } catch { if sales.value == nil { sales = .failed(apiError(error)) } }373        if let m = await mi { modelInfo = m.value }374    }375}376
Files main
Menu

Theme