SPB Git

Repository Public

CompareView.swift 11.9 KB 240 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : Immo-Ka iOS9// File             : ImmoKa/Features/Favorites/CompareView.swift10// Description      : comparateur côte à côte (jusqu'à 4 logements) — la11//                    meilleure valeur de chaque ligne est mise en évidence.12// Module           : ImmoKa13// Repository       : https://git.spboucher.ai/immo-ka-ios-v314// Project Website  : https://www.immo-ka.com15// Created          : 2026-11-2516// Last Modified    : 2026-11-2817//18// =============================================================================19// AUTHOR & PROFESSIONAL AFFILIATION20// =============================================================================21//22// Author           : Simon-Pierre Boucher23// Position         : Professor of Finance24// Institution      : Université du Québec en Outaouais (UQO)25// Department       : Département des sciences administratives26// Organization     : SP Boucher27//28// Website          : https://spboucher.ai29// Git              : https://git.spboucher.ai30//31// =============================================================================32// OFFICIAL CONTACT DIRECTORY33// =============================================================================34//35// General          : info@spboucher.ai36// Professional     : contact@spboucher.ai37// Direct           : simon@spboucher.ai38// Research         : research@spboucher.ai39// Development      : dev@spboucher.ai40// Support          : support@spboucher.ai41// Security/Admin   : admin@spboucher.ai42// Notifications    : notifications@spboucher.ai43//44// Preferred Contact: support@spboucher.ai45//46// =============================================================================47// COPYRIGHT & INTELLECTUAL PROPERTY48// =============================================================================49//50// Copyright (c) 202651// Simon-Pierre Boucher52//53// All rights reserved where applicable.54//55// This file is governed by the applicable project license,56// copyright notices, institutional agreements and relevant law.57//58// Unless expressly authorized by the applicable license or59// rights holder, copying, redistribution, sublicensing,60// publication and commercial exploitation are not permitted.61//62// Existing third-party rights and notices remain unaffected.63//64// =============================================================================65// CONFIDENTIALITY & SECURITY66// =============================================================================67//68// Classification   : Public69// Distribution     : Public repository; use is governed by the project license70// Security Contact : admin@spboucher.ai71//72// Access to this source does not independently grant permission73// to redistribute or disclose confidential materials.74//75// Do not embed credentials, private keys, access tokens,76// certificates or confidential personal information.77//78// =============================================================================79// LICENSE & MAINTENANCE80// =============================================================================81//82// License          : None specified (no license file in this repository)83// Maintainer       : Simon-Pierre Boucher84// Technical Contact: dev@spboucher.ai85//86// =============================================================================87// END OF SP BOUCHER SOURCE HEADER88// =============================================================================8990import SwiftUI9192struct CompareView: View {93    @Environment(Library.self) private var library94    @Environment(AppModel.self) private var app95    @State private var listings: [String: Listing] = [:]96    @State private var loading = true97    @State private var report: ExternalLink?98    /// meilleur taux fixe 5 ans du jour (repli : 5 %)99    @State private var rate = 5.0100101    private var items: [Listing] { library.compareIDs.compactMap { listings[$0] } }102    private let labelWidth: CGFloat = 104103    private let colWidth: CGFloat = 168104105    var body: some View {106        Group {107            if library.compareIDs.isEmpty {108                EmptyStateView(door: .many, title: "Le comparateur est vide",109                               message: "Ajoutez jusqu'à \(Library.compareMax) propriétés depuis une fiche (bouton « Comparer ») ou depuis vos favoris.",110                               actionTitle: "Explorer la carte") { app.tab = .explore }111            } else if loading, items.isEmpty {112                BrandLoader().frame(maxWidth: .infinity, maxHeight: .infinity)113            } else {114                ScrollView([.vertical]) {115                    ScrollView(.horizontal, showsIndicators: false) {116                        table.padding(16)117                    }118                }119            }120        }121        .background(Theme.bg)122        .navigationTitle("Comparateur")123        .navigationBarTitleDisplayMode(.inline)124        .toolbar {125            if !library.compareIDs.isEmpty {126                ToolbarItemGroup(placement: .topBarTrailing) {127                    if library.compareIDs.count >= 2, ServiceGeneration.current >= 3 {128                        Button {129                            let ids = library.compareIDs130                            Task { if let u = await APIClient.shared.comparisonReportURL(ids) { report = ExternalLink(url: u) } }131                        } label: { Image(systemName: "doc.richtext") }132                            .accessibilityLabel("Rapport PDF de comparaison")133                    }134                    Button("Vider") { library.clearCompare() }135                }136            }137        }138        .safariSheet($report)139        .task(id: library.compareIDs) {140            loading = true141            for uid in library.compareIDs where listings[uid] == nil {142                if let l = try? await APIClient.shared.fullListing(uid) { listings[uid] = l }143            }144            loading = false145            if let b = try? await APIClient.shared.mortgageBest() { rate = b.best.rate }146        }147    }148149    private var table: some View {150        let ls = items151        return VStack(alignment: .leading, spacing: 0) {152            HStack(alignment: .top, spacing: 10) {153                Color.clear.frame(width: labelWidth, height: 1)154                ForEach(ls) { l in155                    VStack(alignment: .leading, spacing: 8) {156                        NavigationLink(value: Route.listing(l.uid)) {157                            RemoteImage(source: l.images.first).frame(width: colWidth, height: 112)158                                .clipShape(RoundedRectangle(cornerRadius: Theme.radius, style: .continuous))159                        }160                        .buttonStyle(.plain)161                        Text(l.displayTitle).font(.footnote.weight(.semibold)).foregroundStyle(Theme.ink).lineLimit(2)162                        Text(l.place).font(.caption2).foregroundStyle(Theme.ink3).lineLimit(1)163                        Button { library.toggleCompare(l.uid) } label: { Label("Retirer", systemImage: "xmark").font(.caption) }164                            .buttonStyle(.plain).foregroundStyle(Theme.ink3)165                    }166                    .frame(width: colWidth, alignment: .leading)167                }168            }169            .padding(.bottom, 12)170171            row("Prix demandé", ls, best: bestMin(ls.map(\.plausiblePrice))) { $0.plausiblePrice.map { Fmt.money($0) } ?? "sur demande" }172            // la position n'est pas un classement : aucune colonne n'est mise en avant173            row("Position du prix", ls, best: nil) { l in174                guard let v = l.verdict else { return l.isV3 ? "Incertaine" : "—" }175                guard v != .marche, let d = l.deviation else { return v.label }176                return "\(v.label) \(Fmt.pct(d))"177            }178            row("Prix de vente attendu", ls, best: nil) { $0.expected.map { Fmt.money($0.value) } ?? "—" }179            row("Intervalle (8 ventes sur 10)", ls, best: nil) { l in180                guard let e = l.expected, let lo = e.low, let hi = e.high else { return "—" }181                return "\(Fmt.compactMoney(lo)) à \(Fmt.compactMoney(hi))"182            }183            row("Type", ls, best: nil) { $0.kind.isEmpty ? "—" : $0.kind }184            row("Chambres", ls, best: bestMax(ls.map { $0.bedrooms.map(Double.init) })) { $0.bedrooms.map(String.init) ?? "—" }185            row("Salles de bain", ls, best: bestMax(ls.map { $0.bathrooms.map(Double.init) })) { l in186                l.bathrooms.map { "\($0)" + (l.powderRooms.flatMap { $0 > 0 ? " + \($0)" : nil } ?? "") } ?? "—"187            }188            row("Superficie", ls, best: bestMax(ls.map(\.areaSqft))) { $0.areaSqft.map { "\(Fmt.int($0)) pi²" } ?? "—" }189            row("Prix au pi²", ls, best: bestMin(ls.map(\.pricePerSqft))) { $0.pricePerSqft.map { "\(Fmt.int($0)) $" } ?? "—" }190            row("Terrain", ls, best: bestMax(ls.map(\.lotSqft))) { Fmt.area($0.lotSqft) ?? "—" }191            row("Construction", ls, best: bestMax(ls.map { $0.yearBuilt.map(Double.init) })) { $0.yearBuilt.map(String.init) ?? "—" }192            row("Taxes annuelles", ls, best: bestMin(ls.map(\.taxTotal))) { l in193                l.taxTotal.map { Fmt.money($0) } ?? l.details.value(matching: "taxes", "municip") ?? "—"194            }195            row("Frais de copropriété", ls, best: nil) { $0.condoFee.map { "\(Fmt.money($0)) / mois" } ?? "—" }196            row("Stationnement", ls, best: nil) { $0.details.value(matching: "stationnement") ?? $0.details.value(matching: "garage") ?? "—" }197            row("Versement estimé", ls, best: bestMin(ls.map { monthly($0) })) { l in monthly(l).map { "\(Fmt.money($0)) / mois" } ?? "—" }198            row("En ligne depuis", ls, best: nil) { $0.daysOnMarket.map { Fmt.plural($0, "jour", "jours") } ?? "—" }199            row("Ville", ls, best: nil) { $0.cleanCity.isEmpty ? "—" : $0.cleanCity }200            row("Source", ls, best: nil) { app.sourceName($0.source) }201            Text("Versement estimé : mise de fonds de 20 %, amortissement de 25 ans, taux fixe de \(Fmt.rate(rate)).")202                .font(.caption).num().foregroundStyle(Theme.ink3).padding(.top, 12)203        }204    }205206    /// Versement mensuel indicatif, aux mêmes hypothèses pour toutes les colonnes.207    private func monthly(_ l: Listing) -> Double? {208        guard let p = l.plausiblePrice, !l.isLand else { return nil }209        return Mortgage.compute(.init(price: p, downPayment: p * 0.2, annualPct: rate, years: 25, city: l.cleanCity)).monthly210    }211212    private func bestMin(_ v: [Double?]) -> Int? {213        let c = v.enumerated().compactMap { i, x in x.map { (i, $0) } }214        guard c.count > 1, let m = c.min(by: { $0.1 < $1.1 }) else { return nil }215        return m.0216    }217218    private func bestMax(_ v: [Double?]) -> Int? {219        let c = v.enumerated().compactMap { i, x in x.map { (i, $0) } }220        guard c.count > 1, let m = c.max(by: { $0.1 < $1.1 }) else { return nil }221        return m.0222    }223224    private func row(_ label: String, _ ls: [Listing], best: Int?, value: @escaping (Listing) -> String) -> some View {225        VStack(spacing: 0) {226            Divider().overlay(Theme.line)227            HStack(alignment: .top, spacing: 10) {228                Text(label).font(.caption.weight(.semibold)).foregroundStyle(Theme.ink3).frame(width: labelWidth, alignment: .leading)229                ForEach(Array(ls.enumerated()), id: \.element.uid) { i, l in230                    Text(value(l)).font(.footnote.weight(i == best ? .bold : .regular)).num()231                        .foregroundStyle(i == best ? Theme.good : Theme.ink)232                        .frame(width: colWidth, alignment: .leading)233                        .accessibilityLabel("\(label), \(l.displayTitle) : \(value(l))\(i == best ? ", meilleure valeur" : "")")234                }235            }236            .padding(.vertical, 10)237        }238    }239}240
Files main
Menu

Theme