SPB Git

Repository Public

FinanceCalculator.swift 20.6 KB 414 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : Immo-Ka iOS9// File             : ImmoKa/Features/Finance/FinanceCalculator.swift10// Description      : calculateur de financement natif — mise de fonds, taux11//                    (branché sur les vrais taux du jour), amortissement,12//                    versement, assurance prêt, droits de mutation, somme à13//                    prévoir à la clôture, courbe du solde. Utilisé dans la14//                    fiche d'une propriété et dans l'onglet Marché.15// Module           : ImmoKa16// Repository       : https://git.spboucher.ai/immo-ka-ios-v317// Project Website  : https://www.immo-ka.com18// Created          : 2026-11-2519// Last Modified    : 2026-11-2520//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 Charts94import SwiftUI9596@MainActor97@Observable98final class FinanceModel {99    var price: Double100    var city: String101    /// mise de fonds en fraction du prix (0,05 … 0,60)102    var downPct: Double = 0.20103    /// taux annuel en pourcentage104    var rate: Double = 5.0105    var years: Int = 25106    var fixed = true107    var term = 60108109    private(set) var intelligence: MortgageIntelligence?110    private(set) var rateSource: String?111    /// vrai tant que le taux affiché est celui du marché (et non une valeur choisie à la main)112    private(set) var followsMarket = true113    private(set) var loadingRates = false114115    init(price: Double, city: String = "") {116        self.price = price117        self.city = city118        // mise de fonds de départ : 20 %, ou le minimum légal s'il est plus élevé (1,5 M$ et plus)119        downPct = 0.20120    }121122    var downPayment: Double { (price * downPct).rounded() }123    var scenario: Mortgage.Scenario {124        Mortgage.Scenario(price: price, downPayment: downPayment, annualPct: rate, years: years, fixed: fixed, city: city)125    }126    var result: Mortgage.Result { Mortgage.compute(scenario) }127    var minDownPct: Double { price > 0 ? Mortgage.minDownPayment(price: price) / price : 0.05 }128129    func setRateManually(_ r: Double) {130        rate = (r * 100).rounded() / 100131        followsMarket = false132        rateSource = nil133    }134135    /// Reprend le meilleur taux observé pour le produit choisi (type et terme).136    func applyMarketRate() {137        guard let p = intelligence?.product(fixed: fixed, term: term) ?? intelligence?.products.first(where: { $0.isFixed == fixed }) else { return }138        rate = p.best139        term = p.termMonths140        rateSource = "Meilleur taux \(p.label.lowercased()) observé : \(p.bestInstitution)"141        followsMarket = true142    }143144    func loadRates() async {145        guard intelligence == nil, !loadingRates else { return }146        loadingRates = true147        if let i = try? await APIClient.shared.mortgageIntelligence(), !i.products.isEmpty {148            intelligence = i149            if followsMarket { applyMarketRate() }150        }151        loadingRates = false152    }153}154155/// Le calculateur : réglages, versement, détail des coûts. `showsPrice` ajoute le champ de prix (onglet Marché).156struct FinanceCalculator: View {157    @Bindable var model: FinanceModel158    var showsPrice = false159    @State private var priceText = ""160    @State private var draw: Double = 0161    @FocusState private var priceFocused: Bool162163    private static let amortizations = [15, 20, 25, 30]164165    var body: some View {166        let r = model.result167        VStack(alignment: .leading, spacing: 22) {168            if showsPrice { priceField }169            payment(r)170            controls(r)171            costs(r)172            if model.price > 0, r.principal > 0 { balanceChart(r) }173            Text("Estimations à titre indicatif, calculées sur votre appareil selon les règles en vigueur au Québec en 2026 (capitalisation semestrielle pour un taux fixe, barème d'assurance prêt, droits de mutation de la municipalité). Elles ne tiennent pas compte de votre dossier de crédit, des frais de notaire, d'inspection ni des taxes foncières. Confirmez toujours auprès d'un prêteur et d'un notaire.")174                .font(.caption).foregroundStyle(Theme.ink3).fixedSize(horizontal: false, vertical: true)175        }176        .task { await model.loadRates() }177        .animation(.snappy(duration: 0.25), value: r.insurance.required)178    }179180    // MARK: Prix181182    private var priceField: some View {183        VStack(alignment: .leading, spacing: 8) {184            Text("Prix d'achat").font(.subheadline.weight(.semibold)).foregroundStyle(Theme.ink)185            HStack(spacing: 6) {186                TextField("500 000", text: $priceText)187                    .keyboardType(.numberPad)188                    .font(.display(24, weight: .semibold)).monospacedDigit()189                    .focused($priceFocused)190                    .accessibilityLabel("Prix d'achat en dollars")191                    .accessibilityIdentifier("calculator.price")192                Text("$").font(.title3).foregroundStyle(Theme.ink3)193                if priceFocused {194                    Button("OK") { priceFocused = false }.font(.subheadline.weight(.semibold))195                }196            }197            .padding(.horizontal, 14).frame(height: 54)198            .background(Theme.surface, in: RoundedRectangle(cornerRadius: Theme.radiusSmall, style: .continuous))199            .overlay(RoundedRectangle(cornerRadius: Theme.radiusSmall, style: .continuous).strokeBorder(priceFocused ? Theme.brand : Theme.line2, lineWidth: 1))200            ScrollView(.horizontal, showsIndicators: false) {201                HStack(spacing: 8) {202                    ForEach([300_000, 400_000, 500_000, 650_000, 800_000, 1_000_000], id: \.self) { p in203                        Chip(label: Fmt.compactMoney(Double(p)), active: Int(model.price) == p) {204                            model.price = Double(p); priceText = Fmt.int(p)205                        }206                    }207                }208            }209            .scrollClipDisabled()210        }211        .onAppear { priceText = model.price > 0 ? Fmt.int(model.price) : "" }212        .onChange(of: priceText) { _, v in213            let digits = String(v.filter(\.isNumber).prefix(9))214            let n = Double(digits) ?? 0215            if n != model.price { model.price = n }216            let pretty = n > 0 ? Fmt.int(n) : ""217            if pretty != v { priceText = pretty }218        }219    }220221    // MARK: Versement222223    private func payment(_ r: Mortgage.Result) -> some View {224        VStack(alignment: .leading, spacing: 6) {225            Text("Versement mensuel estimé").font(.caption.weight(.medium)).foregroundStyle(Theme.ink3)226            HStack(alignment: .firstTextBaseline, spacing: 6) {227                Text(model.price > 0 ? Fmt.money(r.monthly) : "—")228                    .font(.display(40, weight: .semibold)).tracking(-1).num().foregroundStyle(Theme.ink)229                    .contentTransition(.numericText(value: r.monthly))230                    .animation(.snappy(duration: 0.3), value: Int(r.monthly))231                    .accessibilityIdentifier("finance.monthly")232                Text("/ mois").font(.subheadline).foregroundStyle(Theme.ink3)233            }234            if model.price > 0 {235                Text("Prêt de \(Fmt.money(r.principal))\(r.insurance.premium > 0 ? ", prime d'assurance comprise" : "") · \(Fmt.rate(model.rate)) · \(model.years) ans")236                    .font(.footnote).num().foregroundStyle(Theme.ink2).fixedSize(horizontal: false, vertical: true)237            }238        }239        .accessibilityElement(children: .combine)240    }241242    // MARK: Réglages243244    private func controls(_ r: Mortgage.Result) -> some View {245        VStack(alignment: .leading, spacing: 18) {246            // mise de fonds247            VStack(alignment: .leading, spacing: 6) {248                HStack(alignment: .firstTextBaseline) {249                    Text("Mise de fonds").font(.subheadline.weight(.semibold)).foregroundStyle(Theme.ink)250                    Spacer()251                    Text("\(Fmt.money(model.downPayment)) · \(Int((model.downPct * 100).rounded())) %").font(.subheadline.weight(.semibold)).num().foregroundStyle(Theme.ink)252                }253                Slider(value: $model.downPct, in: 0.05...0.60, step: 0.01) { Text("Mise de fonds") }254                    .tint(Theme.brand)255                    .accessibilityValue("\(Int((model.downPct * 100).rounded())) pour cent, \(Fmt.money(model.downPayment))")256                    .accessibilityIdentifier("finance.down")257                if model.price > 0 {258                    Text("Minimum légal : \(Fmt.money(r.minDown)) (\(Fmt.decimal(model.minDownPct * 100)) %).")259                        .font(.caption).num().foregroundStyle(model.downPayment + 0.5 < r.minDown ? Theme.bad : Theme.ink3)260                }261            }262            // taux263            VStack(alignment: .leading, spacing: 8) {264                HStack(alignment: .firstTextBaseline) {265                    Text("Taux d'intérêt").font(.subheadline.weight(.semibold)).foregroundStyle(Theme.ink)266                    Spacer()267                    Stepper(value: Binding(get: { model.rate }, set: { model.setRateManually(min(15, max(0.5, $0))) }), in: 0.5...15, step: 0.05) {268                        Text(Fmt.rate(model.rate)).font(.subheadline.weight(.semibold)).num().foregroundStyle(Theme.ink)269                            .frame(maxWidth: .infinity, alignment: .trailing)270                    }271                    .fixedSize()272                    .accessibilityLabel("Taux d'intérêt")273                    .accessibilityValue(Fmt.rate(model.rate))274                }275                SlidingSegmented(selection: Binding(get: { model.fixed }, set: { model.fixed = $0; model.applyMarketRate() }),276                                 options: [(true, "Fixe"), (false, "Variable")], label: "Type de taux")277                if let src = model.rateSource {278                    Text(src).font(.caption).foregroundStyle(Theme.ink3).fixedSize(horizontal: false, vertical: true)279                } else if model.intelligence != nil {280                    Button("Reprendre le meilleur taux du jour") { model.applyMarketRate() }.font(.caption.weight(.semibold))281                } else if !model.loadingRates {282                    Text("Taux du jour indisponibles : taux indicatif, à ajuster.").font(.caption).foregroundStyle(Theme.ink3)283                }284            }285            // amortissement286            VStack(alignment: .leading, spacing: 8) {287                Text("Amortissement").font(.subheadline.weight(.semibold)).foregroundStyle(Theme.ink)288                SlidingSegmented(selection: $model.years, options: Self.amortizations.map { (value: $0, label: "\($0) ans") }, label: "Amortissement")289            }290        }291    }292293    // MARK: Détail des coûts294295    private func costs(_ r: Mortgage.Result) -> some View {296        VStack(alignment: .leading, spacing: 0) {297            Divider().overlay(Theme.line)298            if r.insurance.required {299                if r.insurance.eligible {300                    KeyValueRow(label: "Assurance prêt (\(Fmt.decimal(r.insurance.premiumRate * 100)) %, ajoutée au prêt)", value: Fmt.money(r.insurance.premium))301                    Divider().overlay(Theme.line)302                    KeyValueRow(label: "Taxe sur la prime (comptant)", value: Fmt.money(r.insurance.tax))303                    Divider().overlay(Theme.line)304                }305                if let issue = r.insurance.issue {306                    Label(issue, systemImage: r.insurance.eligible ? "info.circle" : "exclamationmark.triangle")307                        .font(.footnote).foregroundStyle(r.insurance.eligible ? Theme.ink2 : Theme.bad)308                        .padding(.vertical, 9).fixedSize(horizontal: false, vertical: true)309                    Divider().overlay(Theme.line)310                }311            } else if model.price > 0 {312                KeyValueRow(label: "Assurance prêt", value: "Non requise")313                Divider().overlay(Theme.line)314            }315            KeyValueRow(label: "Droits de mutation\(model.city.isEmpty ? "" : " (\(model.city))")", value: model.price > 0 ? Fmt.money(r.transferTax.total) : "—")316            if model.price > 0, !r.transferTax.slices.isEmpty {317                Text(r.transferTax.slices.map { "\(Fmt.decimal($0.rate * 100)) % sur \(Fmt.compactMoney($0.to - $0.from))" }.joined(separator: " + ")318                     + (r.transferTax.municipalScale ? "" : " — barème de base du Québec"))319                    .font(.caption).num().foregroundStyle(Theme.ink3).fixedSize(horizontal: false, vertical: true).padding(.bottom, 9)320            }321            Divider().overlay(Theme.line)322            KeyValueRow(label: "À prévoir à la clôture", value: model.price > 0 ? Fmt.money(r.cashAtClosing) : "—")323            Text("Mise de fonds, droits de mutation\(r.insurance.tax > 0 ? " et taxe sur la prime" : ""). Notaire et inspection en sus.")324                .font(.caption).foregroundStyle(Theme.ink3).padding(.bottom, 9)325            Divider().overlay(Theme.line)326            KeyValueRow(label: "Intérêts sur \(model.years) ans, à taux constant", value: model.price > 0 ? Fmt.money(r.totalInterest) : "—")327            Divider().overlay(Theme.line)328            KeyValueRow(label: "Test de résistance (\(Fmt.rate(r.qualifyingRate)))", value: model.price > 0 ? "\(Fmt.money(r.qualifyingMonthly)) / mois" : "—")329            Divider().overlay(Theme.line)330        }331    }332333    // MARK: Solde du prêt334335    private func balanceChart(_ r: Mortgage.Result) -> some View {336        let balances = Mortgage.yearlyBalances(principal: r.principal, annualPct: model.rate, years: model.years, fixed: model.fixed)337        return VStack(alignment: .leading, spacing: 8) {338            Text("Solde du prêt").font(.subheadline.weight(.semibold)).foregroundStyle(Theme.ink)339            Chart {340                ForEach(Array(balances.enumerated()), id: \.offset) { year, b in341                    AreaMark(x: .value("Année", year), y: .value("Solde", b * draw))342                        .foregroundStyle(Theme.brand.opacity(0.12))343                    LineMark(x: .value("Année", year), y: .value("Solde", b * draw))344                        .foregroundStyle(Theme.brand)345                        .lineStyle(StrokeStyle(lineWidth: 2))346                }347                if model.term / 12 < model.years {348                    RuleMark(x: .value("Fin du terme", model.term / 12))349                        .foregroundStyle(Theme.ink3.opacity(0.6)).lineStyle(StrokeStyle(lineWidth: 1, dash: [3, 3]))350                        .annotation(position: .top, alignment: .leading) {351                            Text("fin du terme").font(.caption2).foregroundStyle(Theme.ink3)352                        }353                }354            }355            .chartXAxis {356                AxisMarks(values: .stride(by: 5)) { v in357                    AxisGridLine().foregroundStyle(Theme.line)358                    AxisValueLabel { if let y = v.as(Int.self) { Text("\(y) ans").font(.caption2) } }359                }360            }361            .chartYAxis {362                AxisMarks(position: .leading, values: .automatic(desiredCount: 4)) { v in363                    AxisGridLine().foregroundStyle(Theme.line)364                    AxisValueLabel { if let d = v.as(Double.self) { Text(Fmt.compactMoney(d)).font(.caption2).monospacedDigit() } }365                }366            }367            .chartYScale(domain: 0...(max(1, r.principal) * 1.05))368            .frame(height: 170)369            .drawOnAppear($draw, duration: 0.9)370            .accessibilityLabel("Solde du prêt de \(Fmt.money(r.principal)) à zéro en \(model.years) ans")371        }372    }373}374375/// Écran « Calculateur d'achat » (onglet Marché).376struct CalculatorView: View {377    @State private var model = FinanceModel(price: 500_000)378    @State private var cityText = ""379    @State private var cities: [String] = []380381    var body: some View {382        ScrollView {383            VStack(alignment: .leading, spacing: 22) {384                VStack(alignment: .leading, spacing: 8) {385                    Text("Calculateur d'achat").font(.editorial(28)).foregroundStyle(Theme.ink)386                    Text("Ce qu'une propriété coûte vraiment : le versement, l'assurance prêt, les droits de mutation et la somme à réunir pour la clôture.")387                        .font(.subheadline).foregroundStyle(Theme.ink2).fixedSize(horizontal: false, vertical: true)388                }389                FinanceCalculator(model: model, showsPrice: true)390                VStack(alignment: .leading, spacing: 8) {391                    Text("Municipalité").font(.subheadline.weight(.semibold)).foregroundStyle(Theme.ink)392                    Text("Les droits de mutation dépendent de la ville : Montréal, Québec, Laval, Gatineau, Longueuil et plusieurs autres ont leurs propres tranches.")393                        .font(.footnote).foregroundStyle(Theme.ink3).fixedSize(horizontal: false, vertical: true)394                    ScrollView(.horizontal, showsIndicators: false) {395                        HStack(spacing: 8) {396                            ForEach(["Montréal", "Québec", "Laval", "Gatineau", "Longueuil", "Sherbrooke", "Lévis", "Trois-Rivières", "Saguenay", "Terrebonne"], id: \.self) { c in397                                Chip(label: c, active: model.city == c) { model.city = model.city == c ? "" : c }398                            }399                        }400                    }401                    .scrollClipDisabled()402                }403            }404            .padding(20)405            .frame(maxWidth: 640, alignment: .leading)406            .frame(maxWidth: .infinity)407        }408        .scrollDismissesKeyboard(.interactively)409        .background(Theme.bg)410        .navigationTitle("Calculateur")411        .navigationBarTitleDisplayMode(.inline)412    }413}414
Files main
Menu

Theme