SPB Git

Repository Public

CalculateurVue.swift 23.7 KB 491 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : Valo-Plex iOS9// File             : ValoPlex/Features/CalculateurVue.swift10// Description      : pro forma de l'investisseur. La saisie est envoyée à POST11//                    /api/v1/proforma après une courte pause (le service est12//                    limité à 60 calculs par minute) ; mêmes champs, libellés13//                    et valeurs de départ que le site.14// Module           : ValoPlex15// Repository       : https://git.spboucher.ai/valo-plex-ios16// Project Website  : https://www.valo-plex.com17// Created          : 2026-12-0118// Last Modified    : 2026-12-0119//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 Observation93import SwiftUI9495enum Champ: String, CaseIterable, Sendable {96    case prix, logements, loyersMensuels, autresRevenusAnnuels, inoccupationPct97    case taxesMunicipales, taxesScolaires, assurances, energie, entretienParLogement, gestionPct, conciergerieParLogement98    case miseDeFondsPct, tauxPct, amortissementAns99    case croissanceLoyersPct, appreciationPct, horizonAns100101    var libelle: String {102        switch self {103        case .prix: "Prix payé ($)"104        case .logements: "Logements"105        case .loyersMensuels: "Loyers, total par mois ($)"106        case .autresRevenusAnnuels: "Autres revenus par an ($)"107        case .inoccupationPct: "Inoccupation (%)"108        case .taxesMunicipales: "Taxes municipales ($)"109        case .taxesScolaires: "Taxes scolaires ($)"110        case .assurances: "Assurances ($)"111        case .energie: "Énergie à votre charge ($)"112        case .entretienParLogement: "Entretien par logement ($)"113        case .gestionPct: "Gestion (% du revenu)"114        case .conciergerieParLogement: "Conciergerie par logement ($)"115        case .miseDeFondsPct: "Mise de fonds (%)"116        case .tauxPct: "Taux d'intérêt (%)"117        case .amortissementAns: "Amortissement (ans)"118        case .croissanceLoyersPct: "Hausse des loyers par an (%)"119        case .appreciationPct: "Plus-value par an (%)"120        case .horizonAns: "Horizon (ans)"121        }122    }123124    var entier: Bool { self == .logements || self == .amortissementAns || self == .horizonAns }125}126127@MainActor128@Observable129final class CalculModele {130    let depart: Depart131    var saisie: [Champ: String]132    var financement: Financement133    private(set) var resultat: ProForma?134    private(set) var message: String?135    private(set) var enCours = false136137    @ObservationIgnored private var tache: Task<Void, Never>?138    @ObservationIgnored private var derniere: EntreeProForma?139    /// Pause de saisie avant l'envoi : le service accepte 60 calculs par minute.140    static let pause: Duration = .milliseconds(600)141142    init(depart: Depart) {143        self.depart = depart144        let n = depart.logements145        financement = n >= 5 ? .schl : .residentiel146        saisie = Self.depart(depart)147    }148149    /// Valeurs de départ, identiques à celles du calculateur du site.150    static func depart(_ d: Depart) -> [Champ: String] {151        let n = d.logements152        return [153            .prix: String(Int(d.prix.rounded())), .logements: String(n), .loyersMensuels: String(Int(d.loyersMensuels.rounded())),154            .autresRevenusAnnuels: "0", .inoccupationPct: "3",155            .taxesMunicipales: String(Int(d.taxesMunicipales.rounded())), .taxesScolaires: String(Int(d.taxesScolaires.rounded())),156            .assurances: String(600 * n), .energie: "0", .entretienParLogement: "700",157            .gestionPct: n >= 12 ? "5" : "4,5", .conciergerieParLogement: n >= 12 ? "400" : "250",158            .miseDeFondsPct: n >= 5 ? "15" : "20", .tauxPct: "4,5", .amortissementAns: n >= 5 ? "40" : "25",159            .croissanceLoyersPct: "3,1", .appreciationPct: "3", .horizonAns: "10",160        ]161    }162163    func nombre(_ c: Champ) -> Double { Fmt.lire(saisie[c] ?? "") ?? 0 }164165    /// Corps de la requête ; nil tant que la saisie est hors des bornes du service.166    var entree: EntreeProForma? {167        let prix = nombre(.prix), logements = nombre(.logements).rounded()168        guard prix >= 10_000, prix <= 1e10, logements >= 1, logements <= 2000 else { return nil }169        return EntreeProForma(170            prix: prix, logements: logements, loyersMensuels: nombre(.loyersMensuels), taxesMunicipales: nombre(.taxesMunicipales),171            taxesScolaires: nombre(.taxesScolaires), assurances: nombre(.assurances), energie: nombre(.energie),172            autresRevenusAnnuels: nombre(.autresRevenusAnnuels), inoccupationPct: nombre(.inoccupationPct),173            entretienParLogement: nombre(.entretienParLogement), gestionPct: nombre(.gestionPct),174            conciergerieParLogement: nombre(.conciergerieParLogement), financement: financement,175            miseDeFondsPct: min(100, nombre(.miseDeFondsPct)), tauxPct: nombre(.tauxPct), amortissementAns: max(1, nombre(.amortissementAns)),176            croissanceLoyersPct: nombre(.croissanceLoyersPct), appreciationPct: nombre(.appreciationPct), horizonAns: max(1, nombre(.horizonAns)),177            tgaMarche: depart.tgaMarche, ville: depart.ville178        )179    }180181    func changerFinancement(_ f: Financement) {182        financement = f183        saisie[.miseDeFondsPct] = f.miseDeFonds184        saisie[.amortissementAns] = f.amortissement185        planifier()186    }187188    func reinitialiser() {189        saisie = Self.depart(depart)190        financement = depart.logements >= 5 ? .schl : .residentiel191        planifier(immediat: true)192    }193194    func planifier(immediat: Bool = false) {195        tache?.cancel()196        guard let e = entree else {197            message = "Entrez un prix d'au moins 10 000 $ et un nombre de logements."198            enCours = false199            return200        }201        guard e != derniere || resultat == nil else {202            enCours = false203            return204        }205        enCours = true206        tache = Task { [weak self] in207            if !immediat { try? await Task.sleep(for: Self.pause) }208            guard !Task.isCancelled else { return }209            await self?.calculer(e)210        }211    }212213    private func calculer(_ e: EntreeProForma) async {214        do {215            let r = try await API.proForma(e)216            guard !Task.isCancelled else { return }217            resultat = r218            derniere = e219            message = nil220        } catch is CancellationError {221            return222        } catch let err as ErreurAPI {223            guard !Task.isCancelled else { return }224            message = err.statut == 429 ? "Trop de calculs en une minute : le prochain repartira dans un instant." : err.message225        } catch {226            message = ErreurAPI.reseau.message227        }228        enCours = false229    }230}231232/// Champ de saisie numérique : libellé à gauche, valeur en chasse fixe dans une case à filet.233struct ChampNombre: View {234    let champ: Champ235    @Bindable var modele: CalculModele236    var aide: String? = nil237238    var body: some View {239        VStack(alignment: .leading, spacing: 4) {240            HStack(spacing: 10) {241                Text(champ.libelle).font(.sans(15, style: .subheadline)).foregroundStyle(VX.encre).fixedSize(horizontal: false, vertical: true)242                Spacer(minLength: 6)243                TextField("0", text: Binding(get: { modele.saisie[champ] ?? "" }, set: { modele.saisie[champ] = $0; modele.planifier() }))244                    .font(.mono(15))245                    .foregroundStyle(VX.encre)246                    .multilineTextAlignment(.trailing)247                    .keyboardType(champ.entier ? .numberPad : .decimalPad)248                    .padding(.horizontal, 9)249                    .padding(.vertical, 8)250                    .frame(width: 128)251                    .background(VX.carton)252                    .overlay(Rectangle().strokeBorder(VX.encre3, lineWidth: 1))253                    .accessibilityLabel(champ.libelle)254                    .accessibilityIdentifier("champ-\(champ.rawValue)")255            }256            if let aide {257                Text(aide).font(.sans(12.5, style: .caption)).foregroundStyle(VX.encre3).fixedSize(horizontal: false, vertical: true)258            }259        }260        .padding(.bottom, 8)261    }262}263264/// Six indicateurs en cases, comme la tête du résultat sur le site.265struct Indicateurs: View {266    let r: ProForma267268    var body: some View {269        let cases: [(String, String, Color)] = [270            (Fmt.pct(r.tga, 2), "Taux de capitalisation au prix payé", VX.encre),271            (Fmt.nombre(r.mrb, 1), "Multiplicateur de revenu brut", VX.encre),272            (Fmt.dollars(r.prixParPorte), "Prix par porte", VX.encre),273            (Fmt.dollars(r.fluxMensuel), "Flux de trésorerie par mois", VX.signe(r.fluxMensuel)),274            (r.rcd.map { Fmt.nombre($0, 2) } ?? Fmt.vide, "Couverture de la dette" + (r.rcdMinimal.map { " (minimum \(Fmt.nombre($0, 2)))" } ?? ""), VX.encre),275            (r.tri.map { Fmt.pct($0, 1) } ?? Fmt.vide, "Rendement annuel sur \(Int(r.hypotheses.horizonAns)) ans, avant impôt", VX.encre),276        ]277        VStack(spacing: 0) {278            ForEach(0..<3, id: \.self) { i in279                if i > 0 { Filet(couleur: VX.papier3) }280                HStack(alignment: .top, spacing: 0) {281                    ForEach(0..<2, id: \.self) { j in282                        let c = cases[i * 2 + j]283                        VStack(alignment: .leading, spacing: 3) {284                            Text(c.0).font(.serif(22, style: .title3)).foregroundStyle(c.2).lineLimit(1).minimumScaleFactor(0.7)285                            Text(c.1).font(.sans(12.5, style: .caption)).foregroundStyle(VX.encre2).fixedSize(horizontal: false, vertical: true)286                        }287                        .padding(.horizontal, 14)288                        .padding(.vertical, 12)289                        .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)290                        .overlay(alignment: .leading) { if j > 0 { Rectangle().fill(VX.papier3).frame(width: 1) } }291                        .accessibilityElement(children: .combine)292                    }293                }294                .fixedSize(horizontal: false, vertical: true)295            }296        }297        .background(VX.carton)298        .overlay(Rectangle().strokeBorder(VX.encre, lineWidth: 1))299    }300}301302/// Le calculateur. `abrege` : quatre champs et les indicateurs, pour la fiche d'un immeuble.303struct CalculateurVue: View {304    @State private var modele: CalculModele305    var abrege = false306307    init(depart: Depart, abrege: Bool = false) {308        _modele = State(initialValue: CalculModele(depart: depart))309        self.abrege = abrege310    }311312    var body: some View {313        VStack(alignment: .leading, spacing: 0) {314            saisie315            resultat316        }317        .task { modele.planifier(immediat: true) }318    }319320    private func groupe<C: View>(_ titre: String, @ViewBuilder _ contenu: () -> C) -> some View {321        VStack(alignment: .leading, spacing: 0) {322            Etiquette(titre, couleur: VX.brique).padding(.bottom, 10)323            contenu()324        }325        .padding(.bottom, 10)326    }327328    private var saisie: some View {329        VStack(alignment: .leading, spacing: 0) {330            if abrege {331                groupe("Vos chiffres") {332                    ChampNombre(champ: .prix, modele: modele)333                    ChampNombre(champ: .loyersMensuels, modele: modele, aide: modele.depart.origineLoyers)334                    ChampNombre(champ: .miseDeFondsPct, modele: modele)335                    ChampNombre(champ: .tauxPct, modele: modele, aide: "Hypothèse : inscrivez le taux offert par votre prêteur.")336                }337            } else {338                groupe("Achat et revenus") {339                    ChampNombre(champ: .prix, modele: modele)340                    ChampNombre(champ: .logements, modele: modele)341                    ChampNombre(champ: .loyersMensuels, modele: modele, aide: modele.depart.origineLoyers ?? "Remplacez par la somme des loyers réels des baux.")342                    ChampNombre(champ: .autresRevenusAnnuels, modele: modele)343                    ChampNombre(champ: .inoccupationPct, modele: modele)344                }345                groupe("Dépenses par an") {346                    ChampNombre(champ: .taxesMunicipales, modele: modele)347                    ChampNombre(champ: .taxesScolaires, modele: modele)348                    ChampNombre(champ: .assurances, modele: modele, aide: "Hypothèse de 600 $ par logement : mettez la prime réelle.")349                    ChampNombre(champ: .energie, modele: modele)350                    ChampNombre(champ: .entretienParLogement, modele: modele)351                    ChampNombre(champ: .gestionPct, modele: modele)352                    ChampNombre(champ: .conciergerieParLogement, modele: modele)353                }354                groupe("Financement") {355                    HStack(spacing: 10) {356                        Text("Type de prêt").font(.sans(15, style: .subheadline)).foregroundStyle(VX.encre)357                        Spacer(minLength: 6)358                        Menu {359                            ForEach(Financement.allCases) { f in Button(f.libelle) { modele.changerFinancement(f) } }360                        } label: {361                            HStack(spacing: 6) {362                                Text(modele.financement.libelle).font(.sans(14.5, style: .subheadline)).foregroundStyle(VX.encre).lineLimit(1)363                                Fleche().rotation(.degrees(-90)).stroke(VX.encre, lineWidth: 1.2).frame(width: 6, height: 10)364                            }365                            .padding(.horizontal, 9)366                            .padding(.vertical, 9)367                            .background(VX.carton)368                            .overlay(Rectangle().strokeBorder(VX.encre3, lineWidth: 1))369                        }370                        .accessibilityLabel("Type de prêt : \(modele.financement.libelle)")371                    }372                    .padding(.bottom, 8)373                    ChampNombre(champ: .miseDeFondsPct, modele: modele)374                    ChampNombre(champ: .tauxPct, modele: modele, aide: "Hypothèse : inscrivez le taux offert par votre prêteur.")375                    ChampNombre(champ: .amortissementAns, modele: modele)376                }377                groupe("Projection") {378                    ChampNombre(champ: .croissanceLoyersPct, modele: modele, aide: "3,1 % : pourcentage de base du TAL pour 2026.")379                    ChampNombre(champ: .appreciationPct, modele: modele)380                    ChampNombre(champ: .horizonAns, modele: modele)381                }382                Button("Revenir aux valeurs de départ") { modele.reinitialiser() }383                    .buttonStyle(.plain)384                    .font(.sans(13.5, style: .footnote))385                    .foregroundStyle(VX.encre2)386                    .underline(true, color: VX.trait)387            }388        }389        .padding(18)390        .frame(maxWidth: .infinity, alignment: .leading)391        .background(VX.papier)392        .overlay(Rectangle().strokeBorder(VX.encre, lineWidth: 1))393    }394395    @ViewBuilder396    private var resultat: some View {397        VStack(alignment: .leading, spacing: 0) {398            HStack {399                Etiquette(modele.enCours ? "Calcul en cours" : "Résultat", couleur: modele.enCours ? VX.brique : VX.encre2)400                Spacer()401            }402            .padding(.bottom, 12)403            if let m = modele.message { Avis(m).padding(.bottom, 12) }404            if let r = modele.resultat {405                Indicateurs(r: r)406                if !abrege { detail(r) }407            } else if modele.message == nil {408                Attente(libelle: "Calcul du pro forma")409            }410        }411        .padding(18)412        .frame(maxWidth: .infinity, alignment: .leading)413        .background(VX.carton)414        .overlay(Rectangle().strokeBorder(VX.encre, lineWidth: 1))415        .padding(.top, -1)416        .opacity(modele.enCours && modele.resultat != nil ? 0.72 : 1)417        .accessibilityIdentifier("resultat-proforma")418        .id("resultat")419    }420421    @ViewBuilder422    private func detail(_ r: ProForma) -> some View {423        let d = r.depenses424        VStack(alignment: .leading, spacing: 0) {425            Ligne("Revenu brut potentiel", Fmt.dollars(r.revenuBrutPotentiel), premiere: true)426            Ligne("Inoccupation (\(Fmt.nombre(r.hypotheses.inoccupationPct, 1)) %)", "−" + Fmt.dollars(r.inoccupation))427            Ligne("Taxes municipales et scolaires", "−" + Fmt.dollars(d.taxes))428            Ligne("Assurances", "−" + Fmt.dollars(d.assurances))429            if d.energie > 0 { Ligne("Énergie", "−" + Fmt.dollars(d.energie)) }430            Ligne("Entretien et réparations", "−" + Fmt.dollars(d.entretien))431            Ligne("Gestion, conciergerie, autres", "−" + Fmt.dollars(d.gestion + d.conciergerie + d.autres))432            Ligne("Revenu net d'exploitation", Fmt.dollars(r.revenuNet), total: true)433            Ligne("Service de la dette (\(Fmt.dollars(r.paiementMensuel)) par mois)", "−" + Fmt.dollars(r.serviceDette))434            Ligne("Flux de trésorerie annuel", Fmt.dollars(r.fluxAnnuel), total: true, couleur: VX.signe(r.fluxAnnuel))435        }436        .padding(.top, 14)437438        Text("Ce que dit le revenu").font(.serif(19, style: .headline)).foregroundStyle(VX.encre).padding(.top, 24).padding(.bottom, 6).id("revenu")439        VStack(alignment: .leading, spacing: 0) {440            if let ve = r.valeurEconomique {441                Ligne("Valeur économique (revenu net ÷ taux du marché de \(Fmt.pct(modele.depart.tgaMarche, 2)))", Fmt.dollars(ve), premiere: true)442            }443            if let vm = modele.depart.valeurMarche {444                Ligne("Valeur de marché Valo-Plex", Fmt.dollars(vm), premiere: r.valeurEconomique == nil)445            }446            Ligne("Loyer moyen par logement pour un flux nul", Fmt.dollars(r.loyerEquilibre) + " / mois", premiere: r.valeurEconomique == nil && modele.depart.valeurMarche == nil)447            Ligne("Mise initiale (mise de fonds + droits de mutation de \(Fmt.dollars(r.droitsDeMutation)))", Fmt.dollars(r.miseInitiale))448            if r.primeSchl > 0 { Ligne("Prime SCHL ajoutée au prêt", Fmt.dollars(r.primeSchl)) }449            if let pm = r.pretMaximal { Ligne("Prêt maximal selon la couverture de la dette", Fmt.dollars(pm)) }450            Ligne("Capital remboursé la première année", Fmt.dollars(r.capitalRembourseAn1))451            Ligne("Rendement encaissé sur la mise initiale", Fmt.pct(r.rendementEncaisse, 1), couleur: VX.signe(r.rendementEncaisse))452            Ligne("Avec le capital remboursé", Fmt.pct(r.rendementAvecCapitalisation, 1))453            if let fin = r.projection.last {454                Ligne("Avoir net après \(fin.annee) ans (valeur \(Fmt.dollars(fin.valeur)), solde \(Fmt.dollars(fin.solde)))", Fmt.dollars(fin.avoir))455            }456        }457        ForEach(r.avertissements, id: \.self) { a in Avis(Fmt.virgules(a)).padding(.top, 10) }458        if r.projection.count > 1 {459            Text("Projection").font(.serif(19, style: .headline)).foregroundStyle(VX.encre).padding(.top, 24).padding(.bottom, 10)460            Tableau(461                entetes: ["An", "Revenu net", "Flux", "Solde du prêt", "Valeur", "Avoir net"],462                lignes: r.projection.map { a in463                    [String(a.annee), Fmt.dollars(a.revenuNet), Fmt.dollars(a.flux), Fmt.dollars(a.solde), Fmt.dollars(a.valeur), Fmt.dollars(a.avoir)]464                }465            )466        }467        Note("Calcul avant impôt, sans frais de vente ni travaux majeurs. Droits de mutation au barème de base de 2026 (barème propre à Montréal appliqué à Montréal) : votre municipalité peut exiger davantage au-delà de 500 000 $. Barème de dépenses de la SCHL en vigueur le 8 juin 2026 ; le prêteur retient le plus élevé du réel et de la norme.")468            .padding(.top, 18)469    }470}471472/// Écran du calculateur : onglet « Calcul » (exemple neutre) ou calcul ouvert depuis une fiche (prérempli).473struct CalculateurEcran: View {474    let depart: Depart475    let racine: Bool476    @Environment(Navigation.self) private var navigation477478    var body: some View {479        Ecran(racine: racine, titre: depart.adresse, ancre: navigation.ancre) {480            if let adresse = depart.adresse {481                TitreEcran(etiquette: "Pro forma de l'investisseur", titre: adresse,482                           chapeau: "Prérempli avec la valeur estimée, les loyers estimés et les taxes au taux de la municipalité. Tout se modifie.")483            } else {484                TitreEcran(etiquette: "Calculateur · pro forma", titre: "Un plex, ses loyers, son prêt.",485                           chapeau: "Entrez le prix, les loyers et le financement. Les dépenses partent du barème de la SCHL ; chaque hypothèse se remplace par votre chiffre réel. Pour partir d'un immeuble précis, cherchez son adresse : sa fiche préremplit tout.")486            }487            CalculateurVue(depart: depart).padding(.top, 24)488        }489    }490}491
Files main
Menu

Theme