SPB Git

Repository Public

PropertyView.swift 20.7 KB 446 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : Vrai-Prix iOS9// File             : VraiPrix/Features/Property/PropertyView.swift10// Description      : fiche d'une propriété du rôle et de son estimation. En11//                    tête, le geste « d'aplomb » ; puis, dans l'ordre de12//                    lecture : valeur et lecture, caractéristiques, rôle,13//                    fiabilité, ventes de l'adresse, comparables (liste et14//                    carte), évolution, emplacement, secteur, méthodes.15// Module           : VraiPrix16// Repository       : https://git.spboucher.ai/vrai-prix-ios-v317// Project Website  : https://www.vrai-prix.com18// Created          : 2026-11-2619// Last Modified    : 2026-11-2620//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 MapKit94import QuickLook95import SwiftUI9697struct PropertyView: View {98    let id: String99100    @Environment(AppModel.self) private var model101    @Environment(Library.self) private var library102    @Environment(MotionCenter.self) private var motion103    @Environment(\.accessibilityReduceMotion) private var reduceMotion104    @AppStorage("streetPhoto") private var streetPhoto = true105    @Environment(\.dynamicTypeSize) private var typeSize106107    @State private var state: Loadable<UnitDetail> = .loading108    @State private var photo: UIImage?109    @State private var heroReady = false110    @State private var level: PlumbLevel = .none111    @State private var revealed = false112    @State private var report: ReportFile?113    @State private var reportLoading = false114115    var body: some View {116        ScrollViewReader { proxy in117            ScrollView {118                Group {119                    switch state {120                    case .loading:121                        LoadingState(label: "Mesure en cours").padding(.top, 60)122                    case .failed(let e):123                        ErrorState(error: e, subject: "Cette propriété") { Task { await load() } }.padding(.top, 40)124                    case .loaded(let d, let stale):125                        if heroReady {126                            content(d, stale: stale)127                                .onAppear { scrollToAnchor(proxy) }128                        } else {129                            LoadingState(label: "Mesure en cours").padding(.top, 60)130                        }131                    }132                }133                .pageColumn()134                .padding(.bottom, 40)135            }136        }137        .background(Theme.bg)138        .navigationBarTitleDisplayMode(.inline)139        .toolbar { toolbar }140        .task { await load() }141        .sheet(item: $report) { r in QuickLookSheet(url: r.url).ignoresSafeArea() }142    }143144    private func scrollToAnchor(_ proxy: ScrollViewProxy) {145        guard let a = model.launchAnchor else { return }146        Task { @MainActor in147            try? await Task.sleep(for: .milliseconds(500))148            proxy.scrollTo(a, anchor: .top)149        }150    }151152    // MARK: Chargement153154    private func load() async {155        if state.value != nil { return }156        state = .loading157        let trigger = motion.consume("unit:" + id)158        do {159            let f = try await APIClient.shared.unit(id)160            level = motion.level(for: trigger, reduceMotion: reduceMotion)161            // photo de la rue (Plans d'Apple) : attendue un court instant, sinon le pignon filaire162            let hero = UserDefaults.standard.string(forKey: "VPHero")163            if hero != "gable", streetPhoto, f.value.result.isUsable, let c = f.value.unit?.coordinate, !f.stale {164                photo = await StreetPhoto.fetch(c, timeout: hero == "photo" ? 6 : 1.4)165            }166            state = .loaded(f.value, stale: f.stale)167            heroReady = true168            if let s = SavedProperty(unit: f.value) { library.visit(s) }169        } catch is CancellationError {170        } catch {171            state = .failed(apiError(error))172        }173    }174175    // MARK: Barre d'outils176177    @ToolbarContentBuilder178    private var toolbar: some ToolbarContent {179        if let d = state.value, let saved = SavedProperty(unit: d) {180            ToolbarItemGroup(placement: .topBarTrailing) {181                if let page = shareURL(d) {182                    ShareLink(item: page, subject: Text(saved.title), message: Text(shareText(d))) {183                        Image(systemName: "square.and.arrow.up")184                    }185                    .accessibilityLabel("Partager")186                }187                Button {188                    let on = library.toggleFavorite(saved)189                    Haptics.tap()190                    model.showToast(on ? "Ajoutée aux favoris" : "Retirée des favoris")191                } label: {192                    Image(systemName: library.isFavorite(saved.id) ? "heart.fill" : "heart")193                }194                .accessibilityLabel(library.isFavorite(saved.id) ? "Retirer des favoris" : "Ajouter aux favoris")195                .accessibilityIdentifier("favorite-button")196            }197        }198    }199200    private func shareURL(_ d: UnitDetail) -> URL? {201        guard let u = d.unit else { return nil }202        return APIClient.site.appending(path: "estimation").appending(path: u.id)203    }204205    private func shareText(_ d: UnitDetail) -> String {206        guard let u = d.unit, d.result.isUsable else { return "" }207        return "\(u.title), \(u.municipalite ?? "") : valeur estimée \(Fmt.money(d.result.estimate)) (fourchette \(Fmt.money(d.result.low)) à \(Fmt.money(d.result.high)))."208    }209210    // MARK: Contenu211212    /// Vente de l'adresse assez récente pour être lue contre la valeur d'aujourd'hui (24 mois).213    private func recentSale(_ d: UnitDetail) -> UnitSale? {214        guard let s = d.sales.first(where: { ($0.amount ?? 0) > 0 }), let date = Fmt.date(iso: s.date) else { return nil }215        return date > Date().addingTimeInterval(-730 * 86400) ? s : nil216    }217218    @ViewBuilder219    private func content(_ d: UnitDetail, stale: Bool) -> some View {220        let u = d.unit221        VStack(alignment: .leading, spacing: 0) {222            if stale { StaleNotice().padding(.top, 8) }223224            // adresse225            VStack(alignment: .leading, spacing: 5) {226                Text([u?.typeDisplay, u?.municipalite].compactMap { $0 }.joined(separator: " · ")).eyebrowStyle()227                    .accessibilityIdentifier("property-kind")228                Text(u?.title ?? "Estimation").font(.editorial(27)).foregroundStyle(Theme.ink)229                    .fixedSize(horizontal: false, vertical: true)230                    .accessibilityAddTraits(.isHeader)231                    .accessibilityIdentifier("property-title")232            }233            .padding(.top, 10)234235            // le geste : la mesure. Le losange est le prix demandé si l'unité est à vendre, sinon sa vente récente.236            if d.result.isUsable, let est = d.result.estimate, let low = d.result.low, let high = d.result.high {237                let sale = recentSale(d)238                let ins = d.inscription239                let data: PlumbData = if let ins, let prix = ins.prix {240                    PlumbData(value: est, low: low, high: high, price: prix, priceLabel: "Prix demandé",241                              reading: Reading(verdict: ins.verdict, ecartPct: ins.ecartPct, dansFourchette: ins.dansFourchette))242                } else {243                    PlumbData(value: est, low: low, high: high, price: sale?.amount,244                              priceLabel: sale.map { "Vendue, " + Fmt.month(String(($0.date ?? "").prefix(7)), short: true) },245                              reading: sale.flatMap { Reading(verdict: $0.verdict, ecartPct: $0.ecartPct, dansFourchette: $0.dansFourchette) })246                }247                PlumbScene(data: data, photo: photo, level: level) {248                    withAnimation(motion.allowed(reduceMotion: reduceMotion) ? .timingCurve(0.2, 0.7, 0.2, 1, duration: 0.24) : nil) { revealed = true }249                }250                .padding(.top, 14)251                if photo != nil {252                    Text("Vue de la rue à cette adresse, Plans d'Apple. Elle peut montrer un bâtiment voisin.")253                        .font(.caption).foregroundStyle(Theme.ink3).frame(maxWidth: .infinity, alignment: .center)254                        .multilineTextAlignment(.center).padding(.top, 8)255                        .opacity(revealed ? 1 : 0)256                }257                readingRows(d, data: data, sale: ins == nil ? sale : nil)258                    .padding(.top, 18)259                    .opacity(revealed ? 1 : 0)260                    .offset(y: revealed ? 0 : 6)261            } else {262                noEstimate.padding(.top, 14)263            }264265            if let caution = caution(d) {266                HStack(alignment: .firstTextBaseline, spacing: 10) {267                    Image(systemName: "exclamationmark.triangle").font(.footnote.weight(.semibold)).foregroundStyle(Theme.high)268                    Text(caution).font(.footnote).foregroundStyle(Theme.ink2).fixedSize(horizontal: false, vertical: true)269                }270                .padding(12)271                .frame(maxWidth: .infinity, alignment: .leading)272                .background(Theme.highSoft, in: RoundedRectangle(cornerRadius: 8, style: .continuous))273                .padding(.top, 16)274                .accessibilityElement(children: .combine)275            }276277            actions(d).padding(.top, 18)278279            PropertySections(detail: d)280        }281    }282283    /// Mise en garde dite franchement : propriété non résidentielle, ou estimation sans rapport avec le rôle.284    private func caution(_ d: UnitDetail) -> String? {285        guard d.result.isUsable, let e = d.result.estimate else { return nil }286        if d.unit?.isNonResidential == true {287            return "Immeuble non résidentiel (\((d.unit?.cubfLibelle ?? "autre usage").lowercased())). Le modèle est entraîné sur des ventes résidentielles : cette estimation est peu fiable. Fiez-vous d'abord au rôle d'évaluation."288        }289        if let r = d.unit?.valeurRole, r > 0, e / r > 3 || e / r < 0.4 {290            return "L'estimation s'écarte fortement du rôle d'évaluation (\(Fmt.money(r))). Vérifiez les caractéristiques inscrites : l'une d'elles est peut-être erronée."291        }292        return nil293    }294295    private var noEstimate: some View {296        VStack(alignment: .leading, spacing: 10) {297            BrandSymbol(style: .mono(Theme.ink3), noFloor: true).frame(width: 44, height: 44)298            Text("Pas d'estimation pour cette propriété").font(.editorial(20)).foregroundStyle(Theme.ink)299            Text("Il n'y a pas assez de ventes comparables dans ce marché, et le modèle statistique ne couvre pas ce type de propriété. Les données du rôle d'évaluation restent affichées ci-dessous.")300                .font(.subheadline).foregroundStyle(Theme.ink2).fixedSize(horizontal: false, vertical: true)301        }302        .frame(maxWidth: .infinity, alignment: .leading)303        .cardStyle()304    }305306    @ViewBuilder307    private func readingRows(_ d: UnitDetail, data: PlumbData, sale: UnitSale?) -> some View {308        VStack(spacing: 0) {309            Hairline()310            if let ins = d.inscription, let prix = ins.prix {311                // l'unité est à vendre : son prix demandé, lu par le service312                FactRow("Prix demandé", Fmt.money(prix))313                readingLines(data, price: prix, noun: "prix demandé")314                Button { model.openListing(ins.uid) } label: {315                    HStack {316                        Text("Voir l'inscription à vendre").font(.subheadline.weight(.medium)).foregroundStyle(Theme.brand)317                        Spacer()318                        Image(systemName: "chevron.right").font(.footnote.weight(.semibold)).foregroundStyle(Theme.brand)319                    }320                    .frame(minHeight: 44).contentShape(Rectangle())321                }322                .buttonStyle(.plain)323                .accessibilityIdentifier("open-inscription")324            } else if let sale, let amount = sale.amount {325                FactRow("Vendue le \(Fmt.day(sale.date))", Fmt.money(amount))326                readingLines(data, price: amount, noun: "prix vendu")327            } else {328                if let r = d.unit?.valeurRole, r > 0 {329                    FactRow("Rôle d'évaluation 2026", Fmt.money(r))330                    FactRow("Valeur estimée par rapport au rôle", Fmt.pct((data.value / r - 1) * 100))331                }332                Text(d.sales.isEmpty ? "Aucune vente enregistrée à cette adresse depuis 2021." : "La dernière vente enregistrée à cette adresse date de plus de deux ans : elle figure plus bas, sans être comparée à la valeur d'aujourd'hui.")333                    .font(.footnote).foregroundStyle(Theme.ink3).frame(maxWidth: .infinity, alignment: .leading).padding(.top, 10)334            }335        }336    }337338    @ViewBuilder339    private func readingLines(_ data: PlumbData, price: Double, noun: String) -> some View {340        if let r = data.reading {341            FactRow("Écart avec la valeur estimée", "\(Fmt.signedMoney(price - data.value)) · \(Fmt.pct(r.gapPct))")342            FactRow(label: "Lecture") { VerdictTag(verdict: r.verdict, gapPct: nil, short: false) }343            if let inside = r.inRange {344                Text(inside ? "Le \(noun) est dans la fourchette de l'estimation." : "Le \(noun) est hors de la fourchette de l'estimation.")345                    .font(.footnote).foregroundStyle(Theme.ink3).frame(maxWidth: .infinity, alignment: .leading).padding(.top, 10)346            }347        } else {348            Text("L'écart entre ce prix et la valeur estimée est trop grand pour être une mesure : aucune lecture n'est donnée.")349                .font(.footnote).foregroundStyle(Theme.ink3).frame(maxWidth: .infinity, alignment: .leading).padding(.top, 10)350        }351    }352353    // MARK: Actions354355    private struct ReportFile: Identifiable { let url: URL; var id: String { url.path } }356357    @ViewBuilder358    private func actions(_ d: UnitDetail) -> some View {359        if let u = d.unit, let saved = SavedProperty(unit: d) {360            let layout = typeSize.isAccessibilitySize ? AnyLayout(VStackLayout(spacing: 10)) : AnyLayout(HStackLayout(spacing: 10))361            layout {362                Button {363                    switch library.toggleCompare(saved) {364                    case .added: model.showToast("Ajoutée au comparateur")365                    case .removed: model.showToast("Retirée du comparateur")366                    case .full: model.showToast("Le comparateur contient déjà \(Library.compareLimit) propriétés")367                    }368                } label: {369                    Label(library.isCompared(saved.id) ? "Comparée" : "Comparer", systemImage: library.isCompared(saved.id) ? "checkmark" : "rectangle.split.2x1")370                }371                .buttonStyle(SecondaryButtonStyle())372                .accessibilityIdentifier("compare-button")373374                Menu {375                    Button("Rapport d'estimation") { openReport(u, pro: false) }376                    Button("Rapport professionnel") { openReport(u, pro: true) }377                } label: {378                    HStack(spacing: 8) {379                        if reportLoading { ProgressView().controlSize(.small) } else { Image(systemName: "doc.text") }380                        Text("Rapport PDF")381                    }382                }383                .buttonStyle(SecondaryButtonStyle())384                .disabled(reportLoading || !d.result.isUsable)385                .accessibilityIdentifier("pdf-button")386            }387        }388    }389390    private func openReport(_ u: PropertyUnit, pro: Bool) {391        reportLoading = true392        Task {393            defer { reportLoading = false }394            do {395                report = ReportFile(url: try await APIClient.shared.report(id: u.id, pro: pro, name: u.title))396            } catch {397                model.showToast(apiError(error).isOffline ? "Hors ligne : le rapport demande une connexion" : "Le rapport n'a pas pu être produit")398            }399        }400    }401}402403/// Photo de la rue à une adresse (Look Around de Plans). Aucune donnée personnelle : seule la coordonnée de la404/// propriété consultée est transmise à Plans, comme pour la carte.405enum StreetPhoto {406    static func fetch(_ c: CLLocationCoordinate2D, timeout: Double) async -> UIImage? {407        await withTaskGroup(of: UIImage?.self) { group in408            group.addTask {409                guard let scene = try? await MKLookAroundSceneRequest(coordinate: c).scene else { return nil }410                let o = MKLookAroundSnapshotter.Options()411                o.size = CGSize(width: 900, height: 612)412                return try? await MKLookAroundSnapshotter(scene: scene, options: o).snapshot.image413            }414            group.addTask {415                try? await Task.sleep(for: .seconds(timeout))416                return nil417            }418            let first = await group.next() ?? nil419            group.cancelAll()420            return first421        }422    }423}424425/// Aperçu d'un PDF (Coup d'œil) avec partage et impression.426struct QuickLookSheet: UIViewControllerRepresentable {427    let url: URL428429    func makeCoordinator() -> Coordinator { Coordinator(url: url) }430431    func makeUIViewController(context: Context) -> UINavigationController {432        let c = QLPreviewController()433        c.dataSource = context.coordinator434        return UINavigationController(rootViewController: c)435    }436437    func updateUIViewController(_ vc: UINavigationController, context: Context) {}438439    final class Coordinator: NSObject, QLPreviewControllerDataSource {440        let url: URL441        init(url: URL) { self.url = url }442        func numberOfPreviewItems(in controller: QLPreviewController) -> Int { 1 }443        func previewController(_ controller: QLPreviewController, previewItemAt index: Int) -> QLPreviewItem { url as NSURL }444    }445}446
Files main
Menu

Theme