Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : Immo-Ka iOS9// File : ImmoKa/Features/Market/RatesView.swift10// Description : taux hypothécaires — meilleurs taux par produit,11// classement des institutions pour le produit choisi,12// historique tracé (Swift Charts), taux préférentiels, accès13// au calculateur.14// Module : ImmoKa15// Repository : https://git.spboucher.ai/immo-ka-ios-v316// Project Website : https://www.immo-ka.com17// Created : 2026-11-2518// Last Modified : 2026-11-2519//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 RatesView: View {96 @State private var intel: MortgageIntelligence?97 @State private var best: MortgageBest?98 @State private var history: [MortgageRate] = []99 @State private var error: Error?100 @State private var fixed = true101 @State private var term = 60102 @State private var draw: Double = 0103 @State private var external: ExternalLink?104105 private var product: MortgageIntelligence.Product? { intel?.product(fixed: fixed, term: term) }106 private var terms: [Int] { (intel?.products ?? []).filter { $0.isFixed == fixed }.map(\.termMonths) }107108 var body: some View {109 ScrollViewReader { proxy in110 ScrollView {111 LazyVStack(alignment: .leading, spacing: 30) {112 VStack(alignment: .leading, spacing: 8) {113 Text("Taux hypothécaires").font(.editorial(28)).foregroundStyle(Theme.ink)114 Text("Relevés chaque jour sur les sites des banques et des prêteurs. Le meilleur taux affiché n'est pas une offre : le vôtre dépend de votre dossier.")115 .font(.subheadline).foregroundStyle(Theme.ink2).fixedSize(horizontal: false, vertical: true)116 }117 if let intel {118 selector119 if let p = product { headline(p) }120 institutions.id("institutions")121 historyChart.id("history")122 allProducts(intel).id("products")123 primes(intel)124 } else if let error {125 ErrorStateView(error: error) { Task { await load() } }126 } else {127 Skeleton(height: 120, radius: Theme.radius)128 Skeleton(height: 220, radius: Theme.radius)129 }130 NavigationLink(value: Route.calculator) {131 Label("Calculer un versement", systemImage: "function").frame(maxWidth: .infinity)132 }133 .buttonStyle(PrimaryButtonStyle())134 }135 .padding(20)136 .frame(maxWidth: 720, alignment: .leading)137 .frame(maxWidth: .infinity)138 }139 .background(Theme.bg)140 .navigationTitle("Taux")141 .navigationBarTitleDisplayMode(.inline)142 .refreshable { await load() }143 .task { if intel == nil { await load() } }144 .task(id: "\(fixed)-\(term)") {145 await loadProduct()146 guard let anchor = UserDefaults.standard.string(forKey: "IKAnchor") else { return }147 try? await Task.sleep(for: .seconds(1.0))148 proxy.scrollTo(anchor, anchor: .top)149 }150 .safariSheet($external)151 }152 }153154 private func load() async {155 error = nil156 do {157 let i = try await APIClient.shared.mortgageIntelligence()158 intel = i159 if i.product(fixed: fixed, term: term) == nil, let first = i.products.first { fixed = first.isFixed; term = first.termMonths }160 } catch is CancellationError {} catch { self.error = error }161 }162163 private func loadProduct() async {164 async let b = try? APIClient.shared.mortgageBest(fixed: fixed, term: term)165 async let h = try? APIClient.shared.get("api/mortgage/rates/history",166 query: ["rate_type": fixed ? "fixed" : "variable", "term_months": String(term), "days": "365"],167 as: MortgageRates.self)168 let (bv, hv) = await (b, h)169 if Task.isCancelled { return }170 withAnimation(.snappy) { best = bv }171 history = hv?.rates ?? []172 draw = 0173 withAnimation(.timingCurve(0.2, 0.8, 0.2, 1, duration: 0.9)) { draw = 1 }174 }175176 // MARK: Produit177178 private var selector: some View {179 VStack(alignment: .leading, spacing: 10) {180 SlidingSegmented(selection: Binding(get: { fixed }, set: { v in181 fixed = v182 let t = (intel?.products ?? []).filter { $0.isFixed == v }.map(\.termMonths)183 if !t.contains(term) { term = t.contains(60) ? 60 : (t.first ?? 60) }184 }), options: [(true, "Taux fixe"), (false, "Taux variable")], label: "Type de taux")185 if terms.count > 1 {186 SlidingSegmented(selection: $term, options: terms.map { (value: $0, label: Fmt.term($0)) }, label: "Terme")187 }188 }189 }190191 private func headline(_ p: MortgageIntelligence.Product) -> some View {192 VStack(alignment: .leading, spacing: 12) {193 HStack(alignment: .firstTextBaseline) {194 VStack(alignment: .leading, spacing: 2) {195 Text("Meilleur taux \(p.label.lowercased())").font(.caption.weight(.medium)).foregroundStyle(Theme.ink3)196 Text(Fmt.rate(p.best)).font(.display(44, weight: .semibold)).tracking(-1).num().foregroundStyle(Theme.ink)197 .contentTransition(.numericText(value: p.best))198 .accessibilityIdentifier("rates.best")199 Text(p.bestInstitution).font(.subheadline.weight(.medium)).foregroundStyle(Theme.ink2)200 }201 Spacer()202 }203 let rows: [(String, String)] = [204 p.median.map { ("Médiane des institutions", Fmt.rate($0)) },205 p.var30d.map { ("Variation sur 30 jours", variation($0)) },206 p.var90d.map { ("Variation sur 90 jours", variation($0)) },207 p.lowest6m.map { ("Plus bas des 6 derniers mois", Fmt.rate($0)) },208 ].compactMap { $0 }209 if !rows.isEmpty { RowList(rows: rows) }210 }211 .animation(.snappy, value: p.id)212 }213214 private func variation(_ v: Double) -> String {215 if abs(v) < 0.005 { return "stable" }216 return "\(v > 0 ? "+" : "−")\(String(format: "%.2f", abs(v)).replacingOccurrences(of: ".", with: ",")) pt"217 }218219 @ViewBuilder220 private var institutions: some View {221 if let rows = best?.perInstitution, !rows.isEmpty {222 let top = rows.map(\.rate).max() ?? 1, low = rows.map(\.rate).min() ?? 0223 VStack(alignment: .leading, spacing: 4) {224 SectionHeader(title: "Par institution").padding(.bottom, 6)225 ForEach(Array(rows.enumerated()), id: \.element.id) { i, r in226 Button { if let l = ExternalLink(r.sourceURL) { external = l } } label: {227 VStack(alignment: .leading, spacing: 6) {228 HStack(alignment: .firstTextBaseline) {229 VStack(alignment: .leading, spacing: 1) {230 Text(r.institution).font(.subheadline.weight(.medium)).foregroundStyle(Theme.ink)231 Text([r.productName, r.kindLabel].filter { !$0.isEmpty }.joined(separator: " · ")).font(.caption).foregroundStyle(Theme.ink3).lineLimit(1)232 }233 Spacer(minLength: 8)234 Text(Fmt.rate(r.rate)).font(.subheadline.weight(.semibold)).num().foregroundStyle(i == 0 ? Theme.good : Theme.ink)235 }236 GeometryReader { geo in237 // barre relative : du meilleur taux au plus élevé238 let span = max(0.01, top - low)239 Capsule().fill(i == 0 ? Theme.good : Theme.brand.opacity(0.55))240 .frame(width: max(6, geo.size.width * (0.25 + 0.75 * (r.rate - low) / span) * draw))241 }242 .frame(height: 4)243 }244 .padding(.vertical, 9)245 .contentShape(Rectangle())246 }247 .buttonStyle(.plain)248 .staggered(i)249 .accessibilityLabel("\(r.institution), \(Fmt.rate(r.rate))\(i == 0 ? ", meilleur taux" : "")")250 .accessibilityHint("Ouvre la page des taux de l'institution")251 Divider().overlay(Theme.line)252 }253 }254 }255 }256257 // MARK: Historique258259 private struct HistPoint: Identifiable {260 let date: Date261 let rate: Double262 let series: String263 var id: String { "\(series)-\(date.timeIntervalSince1970)" }264 }265266 /// Deux séries lisibles : le meilleur taux observé et la médiane, par jour de relevé.267 private var historyPoints: [HistPoint] {268 var byDay: [Date: [Double]] = [:]269 let cal = Calendar(identifier: .gregorian)270 for r in history {271 guard let ts = r.validFrom else { continue }272 byDay[cal.startOfDay(for: Date(timeIntervalSince1970: ts)), default: []].append(r.rate)273 }274 guard byDay.count >= 3 else { return [] }275 var out: [HistPoint] = []276 for (day, rates) in byDay.sorted(by: { $0.key < $1.key }) {277 let s = rates.sorted()278 out.append(HistPoint(date: day, rate: s[0], series: "Meilleur taux"))279 out.append(HistPoint(date: day, rate: s[s.count / 2], series: "Médiane"))280 }281 return out282 }283284 @ViewBuilder285 private var historyChart: some View {286 let pts = historyPoints287 if !pts.isEmpty {288 let rates = pts.map(\.rate)289 let mid = rates.reduce(0, +) / Double(rates.count)290 VStack(alignment: .leading, spacing: 14) {291 SectionHeader(title: "Historique", subtitle: "Changements de taux relevés depuis un an, pour ce produit.")292 Chart(pts) { p in293 LineMark(x: .value("Date", p.date), y: .value("Taux", mid + (p.rate - mid) * draw))294 .foregroundStyle(by: .value("Série", p.series))295 .interpolationMethod(.stepEnd)296 .lineStyle(StrokeStyle(lineWidth: 2))297 }298 .chartForegroundStyleScale(["Meilleur taux": Theme.good, "Médiane": Theme.ink3])299 .chartYScale(domain: ((rates.min() ?? 0) - 0.15)...((rates.max() ?? 1) + 0.15))300 .chartYAxis {301 AxisMarks(position: .leading, values: .automatic(desiredCount: 4)) { v in302 AxisGridLine().foregroundStyle(Theme.line)303 AxisValueLabel { if let x = v.as(Double.self) { Text(Fmt.rate(x)).font(.caption2).monospacedDigit() } }304 }305 }306 .chartXAxis {307 AxisMarks(values: .automatic(desiredCount: 4)) { _ in308 AxisGridLine().foregroundStyle(Theme.line)309 AxisValueLabel(format: .dateTime.month(.abbreviated).year(.twoDigits).locale(Fmt.locale)).font(.caption2)310 }311 }312 .chartLegend(position: .bottom, alignment: .leading)313 .frame(height: 210)314 .accessibilityLabel("Historique du meilleur taux et de la médiane")315 }316 }317 }318319 // MARK: Tous les produits, taux préférentiels320321 private func allProducts(_ i: MortgageIntelligence) -> some View {322 VStack(alignment: .leading, spacing: 4) {323 SectionHeader(title: "Tous les produits").padding(.bottom, 6)324 ForEach(i.products) { p in325 Button { withAnimation(.snappy) { fixed = p.isFixed; term = p.termMonths } } label: {326 HStack(alignment: .firstTextBaseline) {327 VStack(alignment: .leading, spacing: 1) {328 Text(p.label).font(.subheadline.weight(.medium)).foregroundStyle(Theme.ink)329 Text(p.bestInstitution).font(.caption).foregroundStyle(Theme.ink3)330 }331 Spacer()332 if let m = p.median { Text("médiane \(Fmt.rate(m))").font(.caption).num().foregroundStyle(Theme.ink3) }333 Text(Fmt.rate(p.best)).font(.subheadline.weight(.semibold)).num().foregroundStyle(Theme.ink).frame(minWidth: 64, alignment: .trailing)334 }335 .padding(.vertical, 10)336 .contentShape(Rectangle())337 }338 .buttonStyle(.plain)339 .accessibilityAddTraits(p.id == product?.id ? .isSelected : [])340 Divider().overlay(Theme.line)341 }342 }343 }344345 @ViewBuilder346 private func primes(_ i: MortgageIntelligence) -> some View {347 if !i.primeRates.isEmpty {348 let common = Dictionary(grouping: i.primeRates, by: \.rate).max { $0.value.count < $1.value.count }?.key349 VStack(alignment: .leading, spacing: 8) {350 SectionHeader(title: "Taux préférentiel",351 subtitle: common.map { "\(Fmt.rate($0)) dans la plupart des institutions. Les taux variables s'expriment par rapport à lui." })352 let others = i.primeRates.filter { $0.rate != common }353 if !others.isEmpty { RowList(rows: others.map { ($0.institution, Fmt.rate($0.rate)) }) }354 }355 }356 }357}358