SPB Git

Repository Public

MarketV3.swift 37.7 KB 774 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : Immo-Ka iOS9// File             : ImmoKa/Features/Market/MarketV3.swift10// Description      : marché d'un lieu d'après l'API v3 — prix demandés (coupe11//                    courante), flux de la semaine, ventes réelles, indice des12//                    prix de vente avec son intervalle, séries. Prix demandés13//                    et prix de vente ne sont jamais confondus ; une série14//                    refusée par le service dit pourquoi.15// Module           : ImmoKa16// Repository       : https://git.spboucher.ai/immo-ka-ios-v317// Project Website  : https://www.immo-ka.com18// Created          : 2026-11-2819// Last Modified    : 2026-11-3020//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/// Lieu dont on regarde le marché ; nil : la province.97struct MarketPlace: Hashable, Sendable {98    var slug: String99    var kind: String100    var name: String101}102103/// Courbe d'une série, avec sa bande d'incertitude quand elle existe. Les périodes partielles sont en pointillé.104struct SeriesChart: View {105    let points: [SeriesPoint]106    var band = false107    var money = true108    var tint: Color = Theme.brand109    @State private var draw: Double = 0110111    var body: some View {112        let pts = points.compactMap { p -> (Date, Double, Double?, Double?, Bool)? in113            guard let d = p.date, let v = p.value else { return nil }114            return (d, v, p.low, p.high, p.partial)115        }116        if pts.count >= 2 {117            let base = pts.first?.1 ?? 0118            Chart {119                ForEach(Array(pts.enumerated()), id: \.offset) { _, p in120                    if band, let lo = p.2, let hi = p.3 {121                        AreaMark(x: .value("Période", p.0), yStart: .value("Bas", lo), yEnd: .value("Haut", hi))122                            .foregroundStyle(tint.opacity(0.14 * draw))123                    }124                    LineMark(x: .value("Période", p.0), y: .value("Valeur", base + (p.1 - base) * draw))125                        .foregroundStyle(tint)126                        .lineStyle(StrokeStyle(lineWidth: 2))127                        .interpolationMethod(.monotone)128                    if p.4 {129                        // période partielle : un point creux (sans annotation : elle relançait la mise en page du graphique)130                        PointMark(x: .value("Période", p.0), y: .value("Valeur", base + (p.1 - base) * draw))131                            .symbol { Circle().strokeBorder(tint, lineWidth: 1.5).background(Circle().fill(Theme.bg)).frame(width: 8, height: 8) }132                    }133                }134            }135            .chartYScale(domain: .automatic(includesZero: false))136            .chartYAxis {137                AxisMarks(position: .leading, values: .automatic(desiredCount: 3)) { v in138                    AxisGridLine().foregroundStyle(Theme.line)139                    AxisValueLabel {140                        if let d = v.as(Double.self) { Text(money ? Fmt.compactMoney(d) : Fmt.int(d)).font(.caption2).monospacedDigit() }141                    }142                }143            }144            .chartXAxis {145                AxisMarks(values: .automatic(desiredCount: 4)) { _ in146                    AxisGridLine().foregroundStyle(Theme.line)147                    AxisValueLabel(format: .dateTime.month(.abbreviated).year(.twoDigits).locale(Fmt.locale))148                }149            }150            .frame(height: 170)151            .drawOnAppear($draw)152            .accessibilityElement(children: .ignore)153            .accessibilityLabel(summary(pts.map { ($0.0, $0.1) }))154        }155    }156157    private func summary(_ pts: [(Date, Double)]) -> String {158        guard let a = pts.first, let b = pts.last else { return "" }159        let f: (Double) -> String = { money ? Fmt.money($0) : Fmt.decimal($0) }160        return "De \(f(a.1)) à \(f(b.1)), \(pts.count) périodes"161    }162}163164@MainActor165@Observable166final class MarketV3Model {167    var place: MarketPlace?168    var portrait: MarketPortrait?169    var asked: MarketSeries?170    var sales: MarketSeries?171    var index: MarketSeries?172    var error: Error?173    var loading = false174175    func load(force: Bool = false) async {176        if portrait != nil, !force { return }177        loading = true178        error = nil179        let (slug, kind) = (place?.slug, place?.kind)180        do {181            portrait = try await APIClient.shared.market(place: slug, kind: kind)182        } catch is CancellationError {183        } catch { self.error = error }184        loading = false185        async let a = try? APIClient.shared.marketSeries(indicator: "price_median", place: slug, kind: kind)186        async let s = try? APIClient.shared.marketSales(place: slug, kind: kind)187        async let i = try? APIClient.shared.priceIndex(place: slug, kind: kind)188        (asked, sales, index) = await (a, s, i)189    }190191    func select(_ p: MarketPlace?) {192        guard p != place else { return }193        place = p194        portrait = nil; asked = nil; sales = nil; index = nil195        Task { await load(force: true) }196    }197}198199/// Portrait de marché d'un lieu : blocs séparés pour les prix demandés et pour les ventes réelles.200struct MarketPortraitView: View {201    @Bindable var model: MarketV3Model202    @State private var report: ExternalLink?203204    var body: some View {205        VStack(alignment: .leading, spacing: 30) {206            if let p = model.portrait {207                asked(p)208                flows(p)209                salesBlock(p)210                indexBlock(p)211                Button {212                    Task { if let u = await APIClient.shared.marketReportURL(place: model.place?.slug, kind: model.place?.kind) { report = ExternalLink(url: u) } }213                } label: { Label("Rapport PDF du marché", systemImage: "doc.richtext") }214                    .buttonStyle(SoftButtonStyle())215            } else if let e = model.error {216                ErrorStateView(error: e) { Task { await model.load(force: true) } }217            } else {218                Skeleton(height: 130, radius: Theme.radius)219                Skeleton(height: 200, radius: Theme.radius)220            }221        }222        .safariSheet($report)223    }224225    private func grid<C: View>(@ViewBuilder _ content: () -> C) -> some View {226        LazyVGrid(columns: [GridItem(.flexible(), spacing: 16, alignment: .topLeading), GridItem(.flexible(), spacing: 16, alignment: .topLeading)], spacing: 20) { content() }227            .padding(.vertical, 16)228            .overlay(alignment: .top) { Larmier() }229            .overlay(alignment: .bottom) { Divider().overlay(Theme.line) }230    }231232    private func asked(_ p: MarketPortrait) -> some View {233        VStack(alignment: .leading, spacing: 14) {234            VStack(alignment: .leading, spacing: 5) {235                Text("Prix demandés").font(.editorial(23)).foregroundStyle(Theme.ink)236                Text("Propriétés distinctes à vendre\(p.asOf.map { " le \(Fmt.day($0))" } ?? ""). Ce ne sont pas des prix de vente.")237                    .font(.subheadline).num().foregroundStyle(Theme.ink2).fixedSize(horizontal: false, vertical: true)238            }239            grid {240                if let v = p.askMedian { StatTile(value: Fmt.money(v), label: "Prix demandé médian") }241                if let v = p.inventory { StatTile(value: Fmt.int(v), label: "Propriétés à vendre") }242                if let v = p.askPsfMedian { StatTile(value: "\(Fmt.int(v)) $", label: "Prix demandé médian au pi²") }243                if let v = p.new30d { StatTile(value: Fmt.int(v), label: "Nouvelles depuis 30 jours") }244                if let v = p.sharePriceReduced {245                    StatTile(value: "\(Fmt.int(v * 100)) %", label: "Avec une baisse de prix",246                             hint: p.reductionMedianPct.map { "baisse médiane de \(Fmt.decimal(abs($0))) %" })247                }248                if let lo = p.askP25, let hi = p.askP75 {249                    StatTile(value: "\(Fmt.compactMoney(lo)) à \(Fmt.compactMoney(hi))", label: "La moitié des prix demandés")250                }251            }252            .accessibilityIdentifier("market.asked")253            if let s = model.asked, s.points.count >= 2 {254                VStack(alignment: .leading, spacing: 8) {255                    Text(s.label ?? "Prix demandé médian, par semaine").font(.caption.weight(.semibold)).foregroundStyle(Theme.ink3)256                    SeriesChart(points: s.points)257                }258            }259        }260    }261262    @ViewBuilder263    private func flows(_ p: MarketPortrait) -> some View {264        if p.flowNew.current != nil || p.flowWithdrawn.current != nil {265            VStack(alignment: .leading, spacing: 12) {266                SectionHeader(title: "La dernière semaine",267                              subtitle: "\(p.flowPeriodStart.map { "Du \(Fmt.day($0)) au \(Fmt.day(p.flowPeriodEnd))" } ?? "Semaine complète la plus récente"), à sources constantes.")268                VStack(spacing: 0) {269                    flowRow("Nouvelles inscriptions", p.flowNew)270                    Divider().overlay(Theme.line)271                    flowRow("Retraits observés", p.flowWithdrawn)272                    Divider().overlay(Theme.line)273                    flowRow("Inscriptions présentes", p.flowActive)274                }275                Text(p.definitions["n_withdrawn"] ?? "Un retrait n'est pas une vente : la propriété peut avoir été vendue, retirée, ou avoir expiré.")276                    .font(.caption).foregroundStyle(Theme.ink3).fixedSize(horizontal: false, vertical: true)277            }278        }279    }280281    private func flowRow(_ label: String, _ f: MarketPortrait.Flow) -> some View {282        HStack(alignment: .firstTextBaseline) {283            Text(label).font(.subheadline).foregroundStyle(Theme.ink)284            Spacer()285            VStack(alignment: .trailing, spacing: 2) {286                Text(f.current.map { Fmt.int($0) } ?? "Inconnu").font(.subheadline.weight(.semibold)).num().foregroundStyle(f.current == nil ? Theme.ink3 : Theme.ink)287                if let c = f.current, let prev = f.previous {288                    let d = c - prev289                    HStack(spacing: 3) {290                        Image(systemName: d == 0 ? "equal" : d > 0 ? "arrow.up" : "arrow.down").font(.system(size: 9, weight: .bold))291                        Text("\(Fmt.int(prev)) la semaine d'avant")292                    }293                    .font(.caption).num().foregroundStyle(Theme.ink3)294                }295            }296        }297        .padding(.vertical, 10)298        .accessibilityElement(children: .combine)299    }300301    @ViewBuilder302    private func salesBlock(_ p: MarketPortrait) -> some View {303        if !p.sales.isEmpty {304            VStack(alignment: .leading, spacing: 12) {305                SectionHeader(title: "Ventes réelles",306                              subtitle: p.salesStatement ?? "Prix de vente tirés des actes publiés.")307                VStack(spacing: 0) {308                    ForEach(p.sales) { s in309                        HStack(alignment: .firstTextBaseline) {310                            VStack(alignment: .leading, spacing: 2) {311                                Text(s.label).font(.subheadline).foregroundStyle(Theme.ink)312                                Text("\(Fmt.plural(s.n, "vente", "ventes"))\(s.from.map { ", du \(Fmt.day($0)) au \(Fmt.day(s.to))" } ?? "")")313                                    .font(.caption).num().foregroundStyle(Theme.ink3)314                            }315                            Spacer()316                            Text(s.median.map { Fmt.money($0) } ?? "Inconnu").font(.subheadline.weight(.semibold)).num()317                                .foregroundStyle(s.median == nil ? Theme.ink3 : Theme.ink)318                        }319                        .padding(.vertical, 10)320                        .accessibilityElement(children: .combine)321                        Divider().overlay(Theme.line)322                    }323                }324                .accessibilityIdentifier("market.sales")325                if let s = model.sales, s.points.count >= 2 {326                    Text("Prix de vente médian, par trimestre").font(.caption.weight(.semibold)).foregroundStyle(Theme.ink3)327                    SeriesChart(points: s.points, tint: Theme.brassStrong)328                }329                if let w = p.askVsSale.first(where: { $0.ratio != nil }), let a = w.askMedian, let s = w.saleMedian {330                    Text("Prix demandé médian aujourd'hui : \(Fmt.money(a)). Prix de vente médian des douze derniers mois connus : \(Fmt.money(s)). \(w.warning ?? "Les deux médianes ne portent ni sur les mêmes propriétés ni sur les mêmes dates.")")331                        .font(.footnote).num().foregroundStyle(Theme.ink2).fixedSize(horizontal: false, vertical: true)332                }333            }334        }335    }336337    @ViewBuilder338    private func indexBlock(_ p: MarketPortrait) -> some View {339        if let s = model.index {340            VStack(alignment: .leading, spacing: 12) {341                SectionHeader(title: "Indice des prix de vente",342                              subtitle: "Unifamiliale. \(s.baseLabel.map { $0.prefix(1).uppercased() + $0.dropFirst() } ?? "Base 100 au premier trimestre de 2021"), intervalle à 95 %.")343                if s.published, s.points.count >= 2 {344                    if let last = p.index.first(where: { $0.family == "unifamiliale" }), let v = last.value {345                        HStack(alignment: .firstTextBaseline, spacing: 10) {346                            Text(Fmt.decimal(v)).font(.display(28, weight: .semibold)).num().foregroundStyle(Theme.ink)347                            if let y = last.yoyPct {348                                HStack(spacing: 3) {349                                    Image(systemName: y >= 0 ? "arrow.up" : "arrow.down").font(.system(size: 10, weight: .bold))350                                    Text("\(Fmt.decimal(abs(y))) % sur un an")351                                }352                                .font(.footnote.weight(.medium)).num().foregroundStyle(Theme.ink2)353                            }354                        }355                    }356                    SeriesChart(points: s.points, band: true, money: false)357                    if let n = s.notes.first {358                        Text(n).font(.caption).foregroundStyle(Theme.ink3).fixedSize(horizontal: false, vertical: true)359                    }360                } else {361                    // série refusée : le service dit pourquoi, l'app le répète362                    let why = s.reason ?? p.index.first { $0.family == "unifamiliale" }?.reason363                    Label("Indice non publié pour ce lieu\(why.map { " : \($0)" } ?? "").", systemImage: "minus.circle")364                        .font(.subheadline).foregroundStyle(Theme.ink2).fixedSize(horizontal: false, vertical: true)365                }366            }367            .accessibilityIdentifier("market.index")368        }369    }370}371372/// Choix du lieu du marché : la province, ou une ville cherchée par son nom.373struct MarketPlacePicker: View {374    let current: MarketPlace?375    let pick: (MarketPlace?) -> Void376    @Environment(\.dismiss) private var dismiss377    @State private var query = ""378    @State private var hits: [PlaceSuggestion] = []379380    var body: some View {381        NavigationStack {382            List {383                Button {384                    pick(nil); dismiss()385                } label: {386                    HStack {387                        Label("Tout le Québec", systemImage: "map").foregroundStyle(Theme.ink)388                        Spacer()389                        if current == nil { Image(systemName: "checkmark").foregroundStyle(Theme.brand) }390                    }391                }392                ForEach(hits) { h in393                    Button {394                        pick(MarketPlace(slug: h.slug, kind: h.kind, name: h.name)); dismiss()395                    } label: {396                        VStack(alignment: .leading, spacing: 2) {397                            Text(h.name).foregroundStyle(Theme.ink)398                            Text("\(h.kindLabel)\(h.parent.map { " · \($0)" } ?? "") · \(Fmt.plural(h.count, "propriété", "propriétés"))")399                                .font(.caption).num().foregroundStyle(Theme.ink3)400                        }401                    }402                }403            }404            .scrollContentBackground(.hidden)405            .background(Theme.bg)406            .searchable(text: $query, placement: .navigationBarDrawer(displayMode: .always), prompt: "Ville ou région")407            .navigationTitle("Marché de")408            .navigationBarTitleDisplayMode(.inline)409            .toolbar { ToolbarItem(placement: .topBarTrailing) { Button("Fermer") { dismiss() } } }410            .task(id: query) {411                let t = query.trimmingCharacters(in: .whitespaces)412                guard t.count >= 2 else { hits = []; return }413                try? await Task.sleep(for: .milliseconds(240))414                if Task.isCancelled { return }415                hits = ((try? await APIClient.shared.suggestPlaces(t)) ?? []).filter { $0.kind == "municipalite" || $0.kind == "region" }416            }417        }418        .presentationDetents([.medium, .large])419    }420}421422// MARK: - Quartiers423424/// Villes ayant un portrait, ou arrondissements, quartiers et secteurs d'une ville.425struct NeighborhoodsView: View {426    var city: String?427    var cityName: String?428    @State private var items: [NeighborhoodEntry]?429    @State private var error: Error?430    @State private var query = ""431432    var body: some View {433        let shown = (items ?? []).filter { query.isEmpty || Fmt.slug($0.name).contains(Fmt.slug(query)) }434        List {435            if let error, items == nil {436                ErrorStateView(error: error) { Task { await load() } }.listRowBackground(Color.clear).listRowSeparator(.hidden)437            } else if items == nil {438                ForEach(0..<8, id: \.self) { _ in Skeleton(height: 40) }.listRowBackground(Color.clear).listRowSeparator(.hidden)439            } else if shown.isEmpty {440                EmptyStateView(door: .closed, title: city == nil ? "Aucun lieu à ce nom" : "Aucun quartier décrit pour cette ville",441                               message: "Un portrait n'est publié qu'à partir de dix propriétés à vendre.")442                    .listRowBackground(Color.clear).listRowSeparator(.hidden)443            }444            ForEach(shown) { n in445                NavigationLink(value: Route.neighborhood(slug: n.slug, city: n.kind == "municipalite" ? nil : (n.parentSlug ?? city))) {446                    VStack(alignment: .leading, spacing: 3) {447                        Text(n.name).font(.subheadline.weight(.medium)).foregroundStyle(Theme.ink)448                        Text([Fmt.plural(n.count, "propriété à vendre", "propriétés à vendre"),449                              n.askMedian.map { "demandé médian \(Fmt.compactMoney($0))" },450                              n.saleMedian.map { "vendu médian \(Fmt.compactMoney($0))" }].compactMap { $0 }.joined(separator: " · "))451                            .font(.caption).num().foregroundStyle(Theme.ink3)452                    }453                }454                .listRowBackground(Theme.bg)455            }456        }457        .listStyle(.plain)458        .scrollContentBackground(.hidden)459        .background(Theme.bg)460        .searchable(text: $query, prompt: city == nil ? "Ville" : "Quartier")461        .navigationTitle(cityName.map { "Quartiers de \($0)" } ?? "Quartiers")462        .navigationBarTitleDisplayMode(.inline)463        .task { if items == nil { await load() } }464        .accessibilityIdentifier("neighborhoods.list")465    }466467    private func load() async {468        error = nil469        do { items = try await APIClient.shared.neighborhoods(city: city, limit: city == nil ? 1000 : 200) }470        catch is CancellationError {} catch { self.error = error }471    }472}473474/// Portrait d'un lieu : marché, ventes réelles, parc immobilier, taxes, services, transport, voisins.475struct NeighborhoodView: View {476    let slug: String477    var city: String?478    @Environment(AppModel.self) private var app479    @State private var p: NeighborhoodPortrait?480    @State private var error: Error?481    @State private var draw: Double = 0482483    var body: some View {484        ScrollView {485            LazyVStack(alignment: .leading, spacing: 30) {486                if let p {487                    header(p)488                    market(p)489                    sales(p)490                    stock(p)491                    services(p)492                    transit(p)493                    neighbors(p)494                    Text(p.notes["excluded"] ?? "Aucun indicateur de revenu, de défavorisation, de criminalité ni de composition de la population. Ni score ni classement.")495                        .font(.caption).foregroundStyle(Theme.ink3).fixedSize(horizontal: false, vertical: true)496                } else if let error {497                    ErrorStateView(error: error) { Task { await load() } }498                } else {499                    Skeleton(height: 120, radius: Theme.radius)500                    Skeleton(height: 200, radius: Theme.radius)501                }502            }503            .padding(.horizontal, 20).padding(.vertical, 20)504            .frame(maxWidth: 760, alignment: .leading)505            .frame(maxWidth: .infinity)506        }507        .background(Theme.bg)508        .navigationTitle(p?.place.name ?? "Quartier")509        .navigationBarTitleDisplayMode(.inline)510        .task { if p == nil { await load() } }511        .accessibilityIdentifier("neighborhood.portrait")512    }513514    private func load() async {515        error = nil516        do { p = try await APIClient.shared.neighborhood(slug: slug, city: city) }517        catch is CancellationError {} catch { self.error = error }518    }519520    private func header(_ p: NeighborhoodPortrait) -> some View {521        VStack(alignment: .leading, spacing: 12) {522            Text(p.place.name).font(.editorial(30)).foregroundStyle(Theme.ink).fixedSize(horizontal: false, vertical: true)523            Text([PlaceSuggestionKind.label(p.place.kind), p.place.parentName].compactMap { $0 }.joined(separator: " · "))524                .font(.subheadline).foregroundStyle(Theme.ink2)525            Button {526                var f = SearchFilters()527                if p.place.kind == "municipalite" { f.city = p.place.name }528                else if p.place.kind == "region" { f.region = p.place.name }529                else { f.city = city; f.sector = p.place.name }530                app.explore(f)531            } label: { Label("Voir les propriétés sur la carte", systemImage: "map") }532                .buttonStyle(PrimaryButtonStyle())533        }534    }535536    @ViewBuilder537    private func market(_ p: NeighborhoodPortrait) -> some View {538        if let a = p.ask {539            VStack(alignment: .leading, spacing: 12) {540                SectionHeader(title: "Prix demandés", subtitle: p.notes["asking"] ?? "Propriétés actuellement à vendre : ce ne sont pas des prix de vente.")541                LazyVGrid(columns: [GridItem(.flexible(), spacing: 16, alignment: .topLeading), GridItem(.flexible(), spacing: 16, alignment: .topLeading)], spacing: 20) {542                    if let v = a.p50 { StatTile(value: Fmt.money(v), label: "Prix demandé médian") }543                    StatTile(value: Fmt.int(a.n), label: "Propriétés résidentielles à vendre")544                    if let lo = a.p25, let hi = a.p75 { StatTile(value: "\(Fmt.compactMoney(lo)) à \(Fmt.compactMoney(hi))", label: "La moitié des prix demandés") }545                    if let g = p.askGapMedianPct { StatTile(value: Fmt.pct(g / 100), label: "Écart médian au prix de vente attendu") }546                    if let d = p.daysListedMedian { StatTile(value: "\(Fmt.int(d)) j", label: "Affichées depuis (médiane, en cours)") }547                }548            }549        }550    }551552    @ViewBuilder553    private func sales(_ p: NeighborhoodPortrait) -> some View {554        if !p.sales.isEmpty {555            VStack(alignment: .leading, spacing: 12) {556                SectionHeader(title: "Ventes réelles", subtitle: p.salesStatement)557                RowList(rows: p.sales.map { ("\($0.label) · \(Fmt.plural($0.n, "vente", "ventes"))", $0.median.map { Fmt.money($0) } ?? "Inconnu") })558            }559        }560    }561562    @ViewBuilder563    private func stock(_ p: NeighborhoodPortrait) -> some View {564        if !p.ageBands.isEmpty || p.rollValueMedian != nil {565            VStack(alignment: .leading, spacing: 12) {566                SectionHeader(title: "Parc immobilier", subtitle: "D'après le rôle d'évaluation foncière.")567                var rows: [(String, String)] {568                    var r: [(String, String)] = []569                    if let y = p.medianYear { r.append(("Année de construction médiane", String(y))) }570                    if let v = p.rollValueMedian { r.append(("Valeur au rôle médiane, résidentiel", Fmt.money(v))) }571                    if let t = p.taxPer100k { r.append(("Taxes municipales par 100 000 $ de valeur\(p.taxStatus.map { " (\($0))" } ?? "")", Fmt.money(t))) }572                    if let s = p.floodShare, let n = p.floodChecked, n > 0 { r.append(("Propriétés à vendre en zone inondable", "\(Fmt.decimal(s * 100)) % de \(Fmt.int(n))")) }573                    return r574                }575                RowList(rows: rows)576                if !p.ageBands.isEmpty {577                    Chart(p.ageBands) { b in578                        BarMark(x: .value("Part", b.share * 100 * draw), y: .value("Époque", b.label))579                            .foregroundStyle(Theme.brand)580                            .annotation(position: .trailing) { Text("\(Fmt.int(b.share * 100)) %").font(.caption2).monospacedDigit().foregroundStyle(Theme.ink3) }581                    }582                    .chartXAxis(.hidden)583                    .chartYAxis { AxisMarks { _ in AxisValueLabel().font(.caption) } }584                    .frame(height: CGFloat(p.ageBands.count) * 30)585                    .drawOnAppear($draw)586                    .accessibilityLabel("Répartition du parc par époque de construction")587                }588            }589        }590    }591592    @ViewBuilder593    private func services(_ p: NeighborhoodPortrait) -> some View {594        if !p.services.isEmpty {595            VStack(alignment: .leading, spacing: 12) {596                SectionHeader(title: "Proximité des services",597                              subtitle: "Centile médian des propriétés du lieu parmi celles du Québec : 50 est la médiane provinciale.")598                VStack(spacing: 10) {599                    ForEach(p.services) { s in600                        HStack(spacing: 10) {601                            Text(s.label).font(.footnote).foregroundStyle(Theme.ink).frame(width: 132, alignment: .leading)602                            GeometryReader { g in603                                ZStack(alignment: .leading) {604                                    Capsule().fill(Theme.surface3)605                                    Capsule().fill(Theme.brand).frame(width: g.size.width * CGFloat(min(100, max(0, s.percentile)) / 100))606                                    Rectangle().fill(Theme.ink3).frame(width: 1).offset(x: g.size.width / 2)607                                }608                            }609                            .frame(height: 7)610                            Text(Fmt.int(s.percentile)).font(.footnote).num().foregroundStyle(Theme.ink2).frame(width: 28, alignment: .trailing)611                        }612                        .accessibilityElement(children: .ignore)613                        .accessibilityLabel("\(s.label) : centile \(Fmt.int(s.percentile))")614                    }615                }616                if let n = p.schoolCount { Text("\(Fmt.plural(n, "école", "écoles")) dans le lieu.").font(.footnote).num().foregroundStyle(Theme.ink2) }617            }618        }619    }620621    @ViewBuilder622    private func transit(_ p: NeighborhoodPortrait) -> some View {623        if !p.transit.isEmpty {624            VStack(alignment: .leading, spacing: 10) {625                SectionHeader(title: "Transport collectif")626                FlowLayout(spacing: 8) {627                    ForEach(p.transit) { t in628                        Text(t.text).font(.footnote.weight(.medium)).num().foregroundStyle(Theme.ink)629                            .padding(.horizontal, 11).padding(.vertical, 7)630                            .background(Theme.surface2, in: RoundedRectangle(cornerRadius: Theme.radiusTag, style: .continuous))631                    }632                }633                // les stations de l'O-Train sont à Ottawa, pas au Québec : la précision du service est répétée634                if p.transit.contains(where: { $0.key == "otrain" }), let n = p.transitNote {635                    Text(n).font(.caption).foregroundStyle(Theme.ink3).fixedSize(horizontal: false, vertical: true)636                }637            }638        }639    }640641    @ViewBuilder642    private func neighbors(_ p: NeighborhoodPortrait) -> some View {643        if !p.neighbors.isEmpty {644            VStack(alignment: .leading, spacing: 10) {645                SectionHeader(title: "Lieux voisins")646                VStack(spacing: 0) {647                    ForEach(p.neighbors.prefix(8)) { n in648                        NavigationLink(value: Route.neighborhood(slug: n.slug, city: n.kind == "municipalite" ? nil : (n.parentSlug ?? city))) {649                            HStack {650                                VStack(alignment: .leading, spacing: 2) {651                                    Text(n.name).font(.subheadline.weight(.medium)).foregroundStyle(Theme.ink)652                                    Text([n.distanceKm.map { "à \(Fmt.decimal($0)) km" }, Fmt.plural(n.count, "propriété", "propriétés")].compactMap { $0 }.joined(separator: " · "))653                                        .font(.caption).num().foregroundStyle(Theme.ink3)654                                }655                                Spacer()656                                if let m = n.askMedian { Text(Fmt.compactMoney(m)).font(.subheadline).num().foregroundStyle(Theme.ink2) }657                                Image(systemName: "chevron.right").font(.caption.weight(.semibold)).foregroundStyle(Theme.ink3)658                            }659                            .padding(.vertical, 9)660                        }661                        .buttonStyle(.plain)662                        Divider().overlay(Theme.line)663                    }664                }665            }666        }667    }668}669670enum PlaceSuggestionKind {671    static func label(_ kind: String) -> String? {672        switch kind {673        case "region": "Région"674        case "municipalite": "Ville"675        case "arrondissement": "Arrondissement"676        case "quartier": "Quartier"677        case "secteur": "Secteur"678        default: nil679        }680    }681}682683// MARK: - Courtiers684685/// Recherche de courtiers par nom. Aucun téléphone ni courriel : ils restent chez la source.686struct BrokerSearchView: View {687    @Environment(AppModel.self) private var app688    @State private var query = ""689    @State private var hits: [BrokerEntry] = []690    @State private var total: Int?691    @State private var searching = false692    @State private var error: Error?693694    var body: some View {695        List {696            if query.trimmingCharacters(in: .whitespaces).count < 2 {697                VStack(spacing: 10) {698                    BrandIllustration(kind: .ajar, size: 60)699                    Text("Chercher un courtier").font(.editorial(20)).foregroundStyle(Theme.ink)700                    Text("Tapez au moins deux lettres de son nom. Les courtiers sont ceux que nomment les sources ; l'ordre est alphabétique, jamais selon le volume d'inscriptions.")701                        .font(.footnote).foregroundStyle(Theme.ink3).multilineTextAlignment(.center)702                }703                .frame(maxWidth: .infinity).padding(.vertical, 14)704                .listRowBackground(Color.clear).listRowSeparator(.hidden)705            } else if let error, hits.isEmpty {706                ErrorStateView(error: error, retry: nil).listRowBackground(Color.clear).listRowSeparator(.hidden)707            } else if hits.isEmpty, !searching {708                EmptyStateView(door: .closed, title: "Aucun courtier à ce nom").listRowBackground(Color.clear).listRowSeparator(.hidden)709            }710            ForEach(hits) { b in711                // page du courtier : sa fiche publiée s'il est vérifié, et ses propriétés712                NavigationLink(value: Route.broker(id: b.id, name: b.name)) {713                    HStack {714                        VStack(alignment: .leading, spacing: 3) {715                            Text(b.name).font(.subheadline.weight(.medium)).foregroundStyle(Theme.ink)716                            Text([b.agencyName, b.regions.prefix(2).joined(separator: ", ")].compactMap { $0 }.filter { !$0.isEmpty }.joined(separator: " · "))717                                .font(.caption).foregroundStyle(Theme.ink3)718                        }719                        Spacer()720                        Text(Fmt.plural(b.units, "propriété", "propriétés")).font(.caption).num().foregroundStyle(Theme.ink2)721                    }722                }723                .listRowBackground(Theme.bg)724            }725            if let total, total > hits.count {726                Text("\(Fmt.int(total)) courtiers correspondent ; précisez le nom pour en voir moins.")727                    .font(.caption).num().foregroundStyle(Theme.ink3).listRowBackground(Color.clear)728            }729        }730        .listStyle(.plain)731        .scrollContentBackground(.hidden)732        .background(Theme.bg)733        .searchable(text: $query, placement: .navigationBarDrawer(displayMode: .always), prompt: "Nom du courtier")734        .navigationTitle("Courtiers")735        .navigationBarTitleDisplayMode(.inline)736        .task(id: query) {737            let t = query.trimmingCharacters(in: .whitespaces)738            guard t.count >= 2 else { hits = []; total = nil; return }739            searching = true740            try? await Task.sleep(for: .milliseconds(260))741            if Task.isCancelled { return }742            do {743                let r = try await APIClient.shared.brokers(q: t)744                if Task.isCancelled { return }745                hits = r.items; total = r.total; error = nil746            } catch is CancellationError {747            } catch { self.error = error; hits = [] }748            searching = false749        }750        .accessibilityIdentifier("brokers.search")751    }752}753754/// Marché d'un lieu ouvert depuis une ville ou un lien.755struct PlaceMarketView: View {756    let place: MarketPlace757    @State private var model = MarketV3Model()758759    var body: some View {760        ScrollView {761            MarketPortraitView(model: model)762                .padding(.horizontal, 20).padding(.vertical, 20)763                .frame(maxWidth: 760, alignment: .leading)764                .frame(maxWidth: .infinity)765        }766        .background(Theme.bg)767        .navigationTitle("Marché de \(model.portrait?.place.name ?? place.name)")768        .navigationBarTitleDisplayMode(.inline)769        .task {770            if model.portrait == nil { model.place = place; await model.load() }771        }772    }773}774
Files main
Menu

Theme