Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : Lou-Ka iOS9// File : LouKa/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 : LouKa13// Repository : https://git.spboucher.ai/lou-ka-ios-v314// Project Website : https://www.lou-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 costs: [String: TrueCost] = [:]97 @State private var rankingChanges = false98 @State private var loading = true99 @State private var editing = false100 @State private var report: ExternalLink?101102 private var items: [Listing] { library.compareIDs.compactMap { listings[$0] } }103 private let labelWidth: CGFloat = 112104 private let colWidth: CGFloat = 168105106 var body: some View {107 Group {108 if library.compareIDs.isEmpty {109 EmptyStateView(door: .many, title: "Le comparateur est vide",110 message: "Ajoutez jusqu'à \(Library.compareMax) logements depuis une fiche (bouton « Comparer ») ou depuis vos favoris.",111 actionTitle: "Explorer la carte") { app.tab = .explore }112 } else if loading, items.isEmpty {113 DoorLoader().frame(maxWidth: .infinity, maxHeight: .infinity)114 } else {115 ScrollView([.vertical]) {116 ScrollView(.horizontal, showsIndicators: false) {117 table.padding(16)118 }119 }120 }121 }122 .background(Theme.bg)123 .navigationTitle("Comparateur")124 .navigationBarTitleDisplayMode(.inline)125 .toolbar {126 if !library.compareIDs.isEmpty {127 ToolbarItemGroup(placement: .topBarTrailing) {128 Menu {129 Button { editing = true } label: { Label("Mes hypothèses de coût", systemImage: "pencil") }130 if library.compareIDs.count >= 2 {131 Button {132 let ids = library.compareIDs, a = app.costAssumptions133 Task { if let u = await APIClient.shared.reportURL(comparison: ids, assumptions: a) { report = ExternalLink(url: u) } }134 } label: { Label("Rapport PDF de comparaison", systemImage: "doc.richtext") }135 }136 Button(role: .destructive) { library.clearCompare() } label: { Label("Vider le comparateur", systemImage: "trash") }137 } label: {138 Image(systemName: "ellipsis.circle")139 }140 .accessibilityLabel("Actions du comparateur")141 .accessibilityIdentifier("compare.menu")142 }143 }144 }145 .sheet(isPresented: $editing) { AssumptionsSheet() }146 .safariSheet($report)147 .task(id: library.compareIDs) {148 loading = true149 await withTaskGroup(of: (String, Listing?).self) { group in150 for uid in library.compareIDs where listings[uid] == nil {151 group.addTask { (uid, try? await APIClient.shared.listingV3(uid)) }152 }153 for await (uid, l) in group { if let l { listings[uid] = l } }154 }155 loading = false156 }157 // coûts réels calculés par le serveur aux mêmes hypothèses pour tous les logements158 .task(id: "\(library.compareIDs)-\(app.costAssumptions.hashValue)") {159 guard !library.compareIDs.isEmpty else { costs = [:]; return }160 guard let c = try? await APIClient.shared.trueCost(uids: library.compareIDs, assumptions: app.costAssumptions) else { return }161 costs = Dictionary(c.items.map { ($0.uid, $0) }, uniquingKeysWith: { a, _ in a })162 rankingChanges = c.rankingChanges163 }164 }165166 private var table: some View {167 let ls = items168 return VStack(alignment: .leading, spacing: 0) {169 HStack(alignment: .top, spacing: 10) {170 Color.clear.frame(width: labelWidth, height: 1)171 ForEach(ls) { l in172 VStack(alignment: .leading, spacing: 8) {173 NavigationLink(value: Route.listing(l.uid)) {174 RemoteImage(source: l.images.first).frame(width: colWidth, height: 112)175 .clipShape(RoundedRectangle(cornerRadius: Theme.radius, style: .continuous))176 }177 .buttonStyle(.plain)178 Text(l.displayTitle).font(.footnote.weight(.semibold)).foregroundStyle(Theme.ink).lineLimit(2)179 Text(l.place).font(.caption2).foregroundStyle(Theme.ink3).lineLimit(1)180 Button { library.toggleCompare(l.uid) } label: { Label("Retirer", systemImage: "xmark").font(.caption) }181 .buttonStyle(.plain).foregroundStyle(Theme.ink3)182 }183 .frame(width: colWidth, alignment: .leading)184 }185 }186 .padding(.bottom, 12)187188 row("Loyer", ls, best: bestMin(ls.map(\.plausiblePrice))) { $0.plausiblePrice.map { Fmt.money($0) } ?? "sur demande" }189 row("Verdict", ls, best: nil) { l in190 guard let v = l.fvVerdict else { return "sans verdict" }191 guard v != .marche, let d = l.fvDeviation else { return v.label }192 return "\(v.label) \(Fmt.pct(d))"193 }194 row("Loyer estimé", ls, best: nil) { l in195 guard let fv = l.fv else { return "inconnu" }196 guard let lo = l.fvLow, let hi = l.fvHigh else { return "≈ \(Fmt.money(fv))" }197 return "≈ \(Fmt.money(fv))\n\(Fmt.int(lo)) à \(Fmt.money(hi))"198 }199 row("Coût réel", ls, best: bestMin(ls.map { costs[$0.uid]?.monthly?.amount })) { l in200 guard let c = costs[l.uid], let m = c.monthly?.amount else { return costs.isEmpty ? "…" : "inconnu" }201 return (c.complete ? "" : "au moins ") + Fmt.money(m) + (c.unknown.isEmpty ? "" : "\nnon chiffré : " + c.unknown.joined(separator: ", ").lowercased())202 }203 row("Grandeur", ls, best: nil) { $0.unitType.isEmpty ? "—" : $0.unitType }204 row("Superficie", ls, best: bestMax(ls.map(\.areaSqft))) { $0.areaSqft.map { "\(Fmt.int($0)) pi²" } ?? "—" }205 row("Prix au pi²", ls, best: bestMin(ls.map(\.pricePerSqft))) { $0.pricePerSqft.map { String(format: "%.2f $", $0).replacingOccurrences(of: ".", with: ",") } ?? "—" }206 row("Disponible", ls, best: nil) { Fmt.availability($0.availabilityDate) ?? "—" }207 row("Animaux", ls, best: nil) { $0.pets == nil ? "inconnu" : ($0.petsAllowed ? "Acceptés" : "Non") }208 row("Meublé", ls, best: nil) { $0.furnished.map { $0 ? "Oui" : "Non" } ?? "inconnu" }209 row("Inclus", ls, best: nil) { l in210 let inc = Feature.included.filter { l.features[$0.rawValue] == true }.map { $0.label.replacingOccurrences(of: " inclus", with: "").replacingOccurrences(of: " incluse", with: "") }211 return inc.isEmpty ? "non mentionné" : inc.joined(separator: ", ")212 }213 row("Attributs", ls, best: nil) { l in214 let f = (Feature.unit + Feature.building).filter { l.features[$0.rawValue] == true }.map(\.label)215 return f.isEmpty ? "non mentionné" : f.joined(separator: ", ")216 }217 row("Score global", ls, best: bestMax(ls.map { $0.scores.weighted(app.scoreWeights) ?? $0.scores.global })) {218 ($0.scores.weighted(app.scoreWeights) ?? $0.scores.global).map { Fmt.int($0) } ?? "—"219 }220 ForEach(ScoreAxis.all) { ax in221 row(ax.label, ls, best: bestMax(ls.map { $0.scores.value(ax.key) })) { $0.scores.value(ax.key).map { Fmt.int($0) } ?? "—" }222 }223 row("Source", ls, best: nil) { app.sourceName($0.source) }224 Divider().overlay(Theme.line)225 Text((rankingChanges ? "Le classement par coût réel diffère du classement par loyer affiché. " : "")226 + "« Inconnu » et « non mentionné » ne veulent pas dire « non » : l'annonce n'en dit rien. La meilleure valeur de chaque ligne est en gras.")227 .font(.caption).foregroundStyle(Theme.ink3).frame(maxWidth: 560, alignment: .leading).padding(.top, 10)228 .fixedSize(horizontal: false, vertical: true)229 }230 }231232 private func bestMin(_ v: [Double?]) -> Int? {233 let c = v.enumerated().compactMap { i, x in x.map { (i, $0) } }234 guard c.count > 1, let m = c.min(by: { $0.1 < $1.1 }) else { return nil }235 return m.0236 }237238 private func bestMax(_ v: [Double?]) -> Int? {239 let c = v.enumerated().compactMap { i, x in x.map { (i, $0) } }240 guard c.count > 1, let m = c.max(by: { $0.1 < $1.1 }) else { return nil }241 return m.0242 }243244 private func row(_ label: String, _ ls: [Listing], best: Int?, value: @escaping (Listing) -> String) -> some View {245 VStack(spacing: 0) {246 Divider().overlay(Theme.line)247 HStack(alignment: .top, spacing: 10) {248 Text(label).font(.caption.weight(.semibold)).foregroundStyle(Theme.ink3).frame(width: labelWidth, alignment: .leading)249 ForEach(Array(ls.enumerated()), id: \.element.uid) { i, l in250 Text(value(l)).font(.footnote.weight(i == best ? .bold : .regular)).num().fixedSize(horizontal: false, vertical: true)251 .foregroundStyle(i == best ? Theme.good : Theme.ink)252 .frame(width: colWidth, alignment: .leading)253 .accessibilityLabel("\(label), \(l.displayTitle) : \(value(l))\(i == best ? ", meilleure valeur" : "")")254 }255 }256 .padding(.vertical, 10)257 }258 }259}260