SPB Git

Repository Public

ManualEstimateView.swift 11.8 KB 248 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : Vrai-Prix iOS9// File             : VraiPrix/Features/Home/ManualEstimateView.swift10// Description      : estimation sans adresse — municipalité, type et11//                    caractéristiques facultatives ; le moteur s'appuie sur les12//                    ventes comparables de la municipalité. Le résultat se13//                    révèle par le geste d'aplomb.14// Module           : VraiPrix15// Repository       : https://git.spboucher.ai/vrai-prix-ios-v316// Project Website  : https://www.vrai-prix.com17// Created          : 2026-11-2618// Last Modified    : 2026-11-2619//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 ManualEstimateView: View {95    @Environment(MotionCenter.self) private var motion96    @Environment(\.accessibilityReduceMotion) private var reduceMotion97    @State private var municipality = ""98    @State private var all: [Municipality] = []99    @State private var type: PropType = .unifamilial100    @State private var floorArea: Double?101    @State private var yearBuilt: Int?102    @State private var landArea: Double?103    @State private var loading = false104    @State private var error: String?105    @State private var result: UnitDetail?106    @State private var resultID = 0107    @State private var revealed = false108    @FocusState private var muniFocused: Bool109110    private var suggestions: [Municipality] {111        let q = municipality.folding(options: [.diacriticInsensitive, .caseInsensitive], locale: Locale(identifier: "fr_CA")).lowercased().trimmingCharacters(in: .whitespaces)112        guard muniFocused, q.count >= 2, !all.contains(where: { $0.nom == municipality }) else { return [] }113        return Array(all.filter { $0.searchKey.hasPrefix(q) || $0.searchKey.contains(" " + q) || $0.searchKey.contains("-" + q) }.prefix(5))114    }115116    private var canSubmit: Bool { !municipality.trimmingCharacters(in: .whitespaces).isEmpty && !loading }117118    var body: some View {119        ScrollViewReader { proxy in120            ScrollView {121                VStack(alignment: .leading, spacing: 0) {122                    Text("Sans adresse précise, l'estimation repose sur les ventes comparables de la municipalité. Elle est moins précise qu'une estimation par adresse.")123                        .font(.body).foregroundStyle(Theme.ink2).fixedSize(horizontal: false, vertical: true)124125                    label("Municipalité").padding(.top, 22)126                    TextField("Québec, Lévis, Sherbrooke…", text: $municipality)127                        .focused($muniFocused).textInputAutocapitalization(.words).autocorrectionDisabled()128                        .fieldStyle()129                        .accessibilityIdentifier("manual-municipality")130                    if !suggestions.isEmpty {131                        VStack(spacing: 0) {132                            ForEach(suggestions) { m in133                                Button { municipality = m.nom; muniFocused = false } label: {134                                    HStack { Text(m.nom).foregroundStyle(Theme.ink); Spacer() }135                                        .padding(.horizontal, 12).frame(minHeight: 44).contentShape(Rectangle())136                                }137                                .buttonStyle(.plain)138                                Hairline()139                            }140                        }141                        .background(Theme.surface, in: RoundedRectangle(cornerRadius: 8, style: .continuous))142                        .padding(.top, 4)143                    }144145                    label("Type de propriété").padding(.top, 20)146                    FlowLayout(spacing: 8) {147                        ForEach(PropType.manual) { t in FilterChip(label: t.short, active: type == t) { type = t } }148                    }149150                    label("Aire des étages, en m² (facultatif)").padding(.top, 20)151                    TextField("150", value: $floorArea, format: .number).keyboardType(.decimalPad).fieldStyle()152                    label("Année de construction (facultatif)").padding(.top, 16)153                    TextField("1985", value: $yearBuilt, format: .number.grouping(.never)).keyboardType(.numberPad).fieldStyle()154                    label("Superficie du terrain, en m² (facultatif)").padding(.top, 16)155                    TextField("500", value: $landArea, format: .number).keyboardType(.decimalPad).fieldStyle()156157                    Button { submit(proxy) } label: {158                        HStack(spacing: 10) {159                            if loading { ProgressView().tint(Theme.brandInk) }160                            Text(loading ? "Mesure en cours" : "Estimer")161                        }162                    }163                    .buttonStyle(PrimaryButtonStyle())164                    .disabled(!canSubmit)165                    .padding(.top, 24)166                    .accessibilityIdentifier("manual-submit")167168                    if let error {169                        Text(error).font(.subheadline).foregroundStyle(Theme.bad).fixedSize(horizontal: false, vertical: true).padding(.top, 12)170                    }171172                    if let r = result {173                        resultView(r).id("resultat").padding(.top, 34)174                    }175                }176                .pageColumn()177                .padding(.top, 10).padding(.bottom, 40)178            }179            .scrollDismissesKeyboard(.interactively)180        }181        .background(Theme.bg)182        .navigationTitle("Estimer sans adresse")183        .navigationBarTitleDisplayMode(.inline)184        .task { if all.isEmpty { all = (try? await APIClient.shared.municipalities()) ?? [] } }185    }186187    private func label(_ s: String) -> some View { Text(s).eyebrowStyle().padding(.bottom, 8) }188189    @ViewBuilder190    private func resultView(_ r: UnitDetail) -> some View {191        VStack(alignment: .leading, spacing: 0) {192            Text("\(type.label) · \(municipality)").eyebrowStyle()193            Text("Estimation sans adresse").font(.editorial(24)).foregroundStyle(Theme.ink).padding(.top, 4)194            if r.result.isUsable, let e = r.result.estimate, let lo = r.result.low, let hi = r.result.high {195                PlumbScene(data: PlumbData(value: e, low: lo, high: hi), photo: nil, level: motion.level(for: .reveal, reduceMotion: reduceMotion)) {196                    withAnimation(.easeOut(duration: 0.24)) { revealed = true }197                }198                .id(resultID)199                .padding(.top, 16)200                Group {201                    SectionHeader("Fiabilité de l'estimation").padding(.top, 34)202                    ConfidenceSection(result: r.result).padding(.top, 12)203                    SectionHeader("Ventes comparables", note: "Ventes de la municipalité, ramenées à la propriété décrite.").padding(.top, 34)204                    ComparablesSection(comps: r.result.comps).padding(.top, 12)205                }206                .opacity(revealed ? 1 : 0)207            } else {208                EmptyState(title: "Pas d'estimation possible", message: "Il n'y a pas assez de ventes comparables de ce type dans cette municipalité.")209            }210        }211    }212213    private func submit(_ proxy: ScrollViewProxy) {214        guard canSubmit else { return }215        loading = true; error = nil; muniFocused = false216        Task {217            defer { loading = false }218            do {219                let r = try await APIClient.shared.estimateManual(municipality: municipality.trimmingCharacters(in: .whitespaces), typeProp: type.rawValue,220                                                                  floorArea: floorArea, yearBuilt: yearBuilt, landArea: landArea)221                revealed = false222                result = r223                resultID += 1224                try? await Task.sleep(for: .milliseconds(120))225                withAnimation(.easeInOut(duration: 0.35)) { proxy.scrollTo("resultat", anchor: .top) }226            } catch {227                let e = apiError(error)228                self.error = switch e {229                case .notFound: "Municipalité introuvable, ou marché insuffisant pour ce type de propriété. Choisissez un nom dans les suggestions."230                case .offline: "Hors ligne : l'estimation demande une connexion."231                default: e.errorDescription ?? "L'estimation n'a pas pu être calculée."232                }233            }234        }235    }236}237238extension View {239    /// Champ de formulaire : papier, filet, 50 pt.240    func fieldStyle() -> some View {241        self.font(.body)242            .padding(.horizontal, 12)243            .frame(minHeight: 50)244            .background(Theme.surface, in: RoundedRectangle(cornerRadius: Theme.radiusSmall, style: .continuous))245            .overlay(RoundedRectangle(cornerRadius: Theme.radiusSmall, style: .continuous).strokeBorder(Theme.line2, lineWidth: 1))246    }247}248
Files main
Menu

Theme