Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : Vrai-Prix iOS9// File : VraiPrix/Features/Cost/CostView.swift10// Description : méthode du coût d'une propriété du rôle — coût de11// remplacement à neuf, dépréciation, valeur du terrain,12// répartition par corps d'ouvrage (Swift Charts), hypothèses13// dites clairement.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 Charts93import SwiftUI9495struct CostView: View {96 let id: String97 let title: String9899 private struct Loaded: Sendable { var prefill: CostPrefill; var estimate: CostEstimate }100 @State private var state: Loadable<Loaded> = .loading101 @State private var drawn = 0.0102103 var body: some View {104 ScrollView {105 Group {106 switch state {107 case .loading: LoadingState(label: "Calcul du coût").padding(.top, 40)108 case .failed(let e):109 if e == .notFound {110 EmptyState(title: "Méthode du coût non applicable", message: "Cette unité du rôle n'a pas de bâtiment à reconstruire, ou ses caractéristiques manquent.")111 } else {112 ErrorState(error: e, subject: "La méthode du coût") { Task { await load() } }113 }114 case .loaded(let l, _): content(l)115 }116 }117 .pageColumn()118 .padding(.top, 10).padding(.bottom, 36)119 }120 .background(Theme.bg)121 .navigationTitle("Méthode du coût")122 .navigationBarTitleDisplayMode(.inline)123 .task { await load() }124 }125126 private func load() async {127 if state.value != nil { return }128 state = .loading129 do {130 let p = try await APIClient.shared.costPrefill(id)131 let e = try await APIClient.shared.costEstimate(p)132 state = .loaded(Loaded(prefill: p, estimate: e), stale: false)133 } catch is CancellationError {134 } catch { state = .failed(apiError(error)) }135 }136137 @ViewBuilder138 private func content(_ l: Loaded) -> some View {139 let e = l.estimate140 VStack(alignment: .leading, spacing: 0) {141 Text(title).eyebrowStyle()142 Text("Ce qu'il en coûterait de rebâtir, moins l'usure, plus le terrain.")143 .font(.editorial(24)).foregroundStyle(Theme.ink).fixedSize(horizontal: false, vertical: true).padding(.top, 4)144145 VStack(spacing: 4) {146 Text("Valeur par la méthode du coût").eyebrowStyle()147 Text(Fmt.money(e.costApproachValue)).font(.display(34)).num().foregroundStyle(Theme.ink).lineLimit(1).minimumScaleFactor(0.6)148 .accessibilityIdentifier("cost-value")149 }150 .frame(maxWidth: .infinity).padding(.top, 26)151152 VStack(spacing: 0) {153 Hairline()154 FactRow("Coût de remplacement à neuf", Fmt.money(e.replacementCostNew))155 if let r = e.range, let lo = r.low, let hi = r.high { FactRow("Fourchette du coût à neuf", "\(Fmt.money(lo)) à \(Fmt.money(hi))") }156 if let d = e.depreciation {157 FactRow("Dépréciation physique" + (d.physicalPct.map { " (\(Fmt.decimal($0, digits: 0))" + Fmt.nbsp + "%)" } ?? ""), d.total.map { Fmt.signedMoney(-$0) } ?? Fmt.dash)158 FactRow("Bâtiment déprécié", Fmt.money(d.depreciatedImprovementValue))159 }160 FactRow("Terrain, valeur au rôle", Fmt.money(e.landValue))161 FactRow("Valeur par la méthode du coût", Fmt.money(e.costApproachValue))162 }163 .padding(.top, 22)164 if let d = e.depreciation, let age = d.effectiveAge, let life = d.economicLife {165 Text("Âge retenu : \(Fmt.decimal(age, digits: 0)) ans, pour une vie économique de \(Fmt.decimal(life, digits: 0)) ans. Un bâtiment ancien bien entretenu vaut souvent plus que ce calcul : la méthode du coût est la moins fiable pour les constructions âgées.")166 .font(.footnote).foregroundStyle(Theme.ink3).fixedSize(horizontal: false, vertical: true).padding(.top, 10)167 }168169 if let r = l.prefill.readings {170 SectionHeader("Face aux autres lectures").padding(.top, 36)171 VStack(spacing: 0) {172 Hairline().padding(.top, 10)173 if let v = r.hybrid { FactRow("Valeur estimée Vrai-Prix", Fmt.money(v)) }174 if let v = r.hedonic { FactRow("Modèle statistique", Fmt.money(v)) }175 if let v = r.comparables { FactRow("Ventes comparables", Fmt.money(v)) }176 if let v = r.rollValue { FactRow("Rôle d'évaluation", Fmt.money(v)) }177 if let v = r.hybrid, let c = e.costApproachValue, v > 0 { FactRow("Coût par rapport à la valeur estimée", Fmt.pct((c / v - 1) * 100)) }178 }179 }180181 let cats = e.categories.filter { ($0.adjusted ?? 0) > 0 }.sorted { ($0.adjusted ?? 0) > ($1.adjusted ?? 0) }182 if !cats.isEmpty {183 SectionHeader("Coûts directs par corps d'ouvrage", note: "Matériaux, main-d'œuvre et équipement : \(Fmt.money(e.directCost)).").padding(.top, 36)184 Chart(cats.prefix(10)) { c in185 BarMark(x: .value("Coût", (c.adjusted ?? 0) * drawn), y: .value("Corps", c.labelFr ?? c.category), height: .fixed(13))186 .foregroundStyle(Theme.ink)187 .annotation(position: .trailing, spacing: 6) {188 Text(Fmt.compact(c.adjusted)).font(.chartAxis).monospacedDigit().foregroundStyle(Theme.ink3)189 }190 }191 .chartXAxis(.hidden)192 .chartXScale(domain: 0...((cats.first?.adjusted ?? 1) * 1.3))193 .chartYAxis { AxisMarks(position: .leading) { _ in AxisValueLabel().font(.chartAxis).foregroundStyle(Theme.ink2) } }194 .frame(height: CGFloat(min(cats.count, 10)) * 32 + 8)195 .padding(.top, 12)196 .drawOnAppear($drawn)197 .accessibilityElement(children: .ignore)198 .accessibilityLabel("Coûts directs par corps d'ouvrage : " + cats.prefix(10).map { "\($0.labelFr ?? $0.category) \(Fmt.money($0.adjusted))" }.joined(separator: ", "))199200 VStack(spacing: 0) {201 Hairline()202 FactRow("Coûts directs", Fmt.money(e.directCost))203 FactRow("Frais indirects", Fmt.money(e.indirectCost))204 FactRow("Frais généraux de l'entrepreneur", Fmt.money(e.contractorOverhead))205 FactRow("Profit de l'entrepreneur", Fmt.money(e.contractorProfit))206 FactRow("Imprévus", Fmt.money(e.contingency))207 if let s = e.perSqft, let m = e.perM2 { FactRow("Coût à neuf par surface", "\(Fmt.money(s)) le pi² · \(Fmt.money(m)) le m²") }208 }209 .padding(.top, 14)210 }211212 SectionHeader("Hypothèses et fiabilité").padding(.top, 36)213 if let c = e.confidence {214 HStack(spacing: 10) {215 ConfidenceBadge(level: c.letter)216 if let t = c.total { Text("indice \(Fmt.decimal(t, digits: 0)) sur 100").font(.subheadline).num().foregroundStyle(Theme.ink3) }217 }218 .padding(.top, 10)219 }220 if !l.prefill.missing.isEmpty {221 Text("Le rôle ne dit pas tout d'un bâtiment. Ces caractéristiques sont supposées de qualité courante : \(l.prefill.missing.map(CostLabels.missing).joined(separator: ", ")).")222 .font(.subheadline).foregroundStyle(Theme.ink2).fixedSize(horizontal: false, vertical: true).padding(.top, 10)223 }224 ForEach(e.confidence?.notesFr ?? [], id: \.self) { n in225 Text(n).font(.footnote).foregroundStyle(Theme.ink3).fixedSize(horizontal: false, vertical: true).padding(.top, 8)226 }227 Text([l.prefill.locationName.map { "Prix ajustés pour \($0)" }, e.priceDate.map { "en date du \(Fmt.day($0))" }, e.methodVersion.map { "méthode \($0)" }]228 .compactMap { $0 }.joined(separator: ", ") + ". Ce calcul n'est pas enregistré.")229 .font(.footnote).foregroundStyle(Theme.ink3).fixedSize(horizontal: false, vertical: true).padding(.top, 12)230 }231 }232}233