SPB Git

Repository Public

DiscoverView.swift 24.2 KB 485 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : Immo-Ka iOS9// File             : ImmoKa/Features/Discover/DiscoverView.swift10// Description      : accueil éditorial — accroche, chiffres réels, nouvelles11//                    inscriptions, bonnes occasions (vrai prix), villes en12//                    index typographique, accès aux courtiers et aux taux13//                    hypothécaires.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-2819//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 SwiftUI9394@MainActor95@Observable96final class DiscoverModel {97    var stats: GlobalStats?98    /// v3 : propriétés distinctes à vendre99    var inventory: Int?100    var cities: [CityEntry]?101    var deals: [Listing]?102    var recent: [Listing]?103    var bestRate: MortgageRate?104    var agencies: AgencyDirectory?105    var shares: VerdictShares?106    var error: Error?107108    private var loading = false109110    /// Chaque bloc s'affiche dès que sa réponse arrive : une réponse lente (le tableau de bord peut prendre111    /// plusieurs secondes à froid) ne retient pas les autres.112    func load(force: Bool = false) async {113        if (stats != nil && !force) || loading { return }114        loading = true115        error = nil116        // tâches héritant de l'acteur principal : chacune pose son résultat dès qu'il arrive117        let tasks: [Task<Void, Never>] = [118            Task { if let v = try? await APIClient.shared.stats() { self.stats = v } },119            // v3 : propriétés distinctes à vendre (une propriété publiée par plusieurs sources compte une fois)120            Task { if await APIClient.shared.isV3(), let m = try? await APIClient.shared.market() { self.inventory = m.inventory } },121            Task { if let v = try? await APIClient.shared.cities() { self.cities = v } },122            Task { if let v = try? await APIClient.shared.mortgageBest() { self.bestRate = v.best } },123            Task { if let v = try? await APIClient.shared.agencyDirectory() { self.agencies = v } },124            Task { if let v = try? await APIClient.shared.verdictShares() { self.shares = v } },125            Task {126                // nouvelles inscriptions : avec photo, prix plausible et type reconnu ; Marketplace n'est pas mis127                // en avant (ses photos expirent)128                guard let r = try? await APIClient.shared.search(SearchFilters(), sort: .recent, pageSize: 40) else { return }129                self.recent = Array(r.listings.filter { !$0.images.isEmpty && $0.plausiblePrice != nil && !$0.kind.isEmpty && $0.source != "fb_marketplace" }.prefix(10))130            },131            Task {132                // bonnes occasions : sous la valeur estimée, avec photo ; les écarts extrêmes sont presque toujours133                // de mauvais appariements134                var f = SearchFilters(); f.deal = .sous; f.priceMin = 150_000135                guard let r = try? await APIClient.shared.search(f, sort: .recent, pageSize: 60) else { return }136                self.deals = Array(r.listings.filter { l in137                    // le verdict est celui du service ; au-delà de 35 % d'écart, la vitrine s'abstient138                    guard !l.images.isEmpty, !l.isLand, l.source != "fb_marketplace", l.verdict == .sous, let d = l.deviation else { return false }139                    return d > -0.35140                }.prefix(10))141            },142        ]143        for t in tasks { await t.value }144        if stats == nil, recent == nil, deals == nil { error = APIError.offline }145        loading = false146    }147}148149/// Bouton principal de l'accueil : la porte de la petite maison est entrebâillée (34°) ; à l'appui elle s'ouvre150/// à 84° en 260 ms et l'intérieur s'éclaire.151struct ExploreDoorButtonStyle: ButtonStyle {152    func makeBody(configuration: Configuration) -> some View {153        HStack(spacing: 12) {154            BrandMark(angle: configuration.isPressed ? BrandGeometry.transitionAngle : BrandGeometry.exploreAngle, onDark: true, showsThreshold: false) {155                Theme.doorInterior.opacity(configuration.isPressed ? 1 : 0)156            }157            .frame(width: 26, height: 26)158            .animation(.timingCurve(DoorCurve.x1, DoorCurve.y1, DoorCurve.x2, DoorCurve.y2, duration: 0.26), value: configuration.isPressed)159            configuration.label.font(.body.weight(.semibold)).foregroundStyle(.white)160        }161        .padding(.leading, 14).padding(.trailing, 20)162        .frame(minHeight: 52)163        .background(configuration.isPressed ? Theme.deepSlate : Theme.slate, in: RoundedRectangle(cornerRadius: Theme.radiusSmall, style: .continuous))164        .animation(.easeOut(duration: 0.1), value: configuration.isPressed)165    }166}167168struct DiscoverView: View {169    @Environment(AppModel.self) private var app170    @Environment(\.horizontalSizeClass) private var hSize171    @Environment(DoorCenter.self) private var door172    @State private var model = DiscoverModel()173174    var body: some View {175        ScrollView {176            VStack(alignment: .leading, spacing: 40) {177                intro178                if let error = model.error, model.stats == nil {179                    ErrorStateView(error: error) { Task { await model.load(force: true) } }180                } else {181                    recentSection182                    dealsSection183                    cities184                    vraiPrix185                    services186                    closing187                }188            }189            .padding(.top, 8)190            .padding(.bottom, 40)191            .frame(maxWidth: 900, alignment: .leading)192            .frame(maxWidth: .infinity)193        }194        .background(Theme.bg)195        .toolbar(.hidden, for: .navigationBar)196        .refreshable { await model.load(force: true) }197        .task {198            await model.load()199            #if DEBUG200            // -IKDoorLive YES : joue réellement la transition sur la première propriété, sans naviguer (diagnostic)201            if UserDefaults.standard.bool(forKey: "IKDoorLive"), let l = model.recent?.first ?? model.deals?.first {202                try? await Task.sleep(for: .seconds(2))203                door.open(uid: l.uid, image: l.images.first, from: CGRect(x: 20, y: 560, width: 286, height: 214), reduceMotion: false) {}204            }205            // -IKDoorDemo <secondes> : fige la signature à cet instant (captures)206            if let v = UserDefaults.standard.string(forKey: "IKDoorDemo"), let time = Double(v) {207                let l = model.recent?.first ?? model.deals?.first208                let level = DoorLevel(rawValue: UserDefaults.standard.string(forKey: "IKDoorLevel") ?? "") ?? .signature209                door.debugFreeze(uid: l?.uid ?? "demo", image: l?.images.first, source: CGRect(x: 20, y: 560, width: 286, height: 214), at: time, level: level)210            }211            #endif212        }213    }214215    // MARK: Accroche216217    private var intro: some View {218        VStack(alignment: .leading, spacing: 22) {219            HStack {220                BrandLogo(height: 32)221                Spacer()222                Button { app.open(.settings) } label: {223                    Image(systemName: "gearshape").font(.system(size: 17, weight: .regular)).foregroundStyle(Theme.ink2)224                        .frame(width: 44, height: 44)225                }226                .accessibilityLabel("Réglages")227            }228            VStack(alignment: .leading, spacing: 12) {229                Text("Ouvrez la porte de votre prochaine maison.")230                    .font(.editorial(hSize == .regular ? 38 : 31)).tracking(-0.2)231                    .foregroundStyle(Theme.ink)232                    .fixedSize(horizontal: false, vertical: true)233                    .accessibilityAddTraits(.isHeader)234                Text("Les propriétés à vendre au Québec, réunies sur une seule carte. Pour chacune : le prix demandé, le prix de vente attendu d'après les ventes réelles, le coût de possession et le quartier.")235                    .font(.body).foregroundStyle(Theme.ink2).lineSpacing(2)236                    .fixedSize(horizontal: false, vertical: true)237            }238            Button {239                Haptics.tap()240                app.explore(SearchFilters())241            } label: {242                Text("Explorer la carte")243            }244            .buttonStyle(ExploreDoorButtonStyle())245            .accessibilityIdentifier("discover.explore")246            if let n = model.inventory, n > 0 {247                Text("\(Fmt.int(n)) propriétés distinctes à vendre aujourd'hui\((model.stats?.sources).map { ", tirées de \(Fmt.int($0)) sources" } ?? "")\((V3Version.current?.municipalities).map { ", dans \(Fmt.int($0)) municipalités" } ?? "").")248                    .font(.footnote).num().foregroundStyle(Theme.ink3)249                    .fixedSize(horizontal: false, vertical: true)250                    .accessibilityIdentifier("discover.count")251            } else if ServiceGeneration.current < 3, let st = model.stats, st.total > 0 {252                Text("\(Fmt.int(st.total)) propriétés en ligne aujourd'hui\(st.sources.map { ", tirées de \(Fmt.int($0)) sources" } ?? "")\(st.cities.map { ", dans \(Fmt.int($0)) municipalités" } ?? "").")253                    .font(.footnote).num().foregroundStyle(Theme.ink3)254                    .fixedSize(horizontal: false, vertical: true)255                    .accessibilityIdentifier("discover.count")256            }257            VStack(alignment: .leading, spacing: 0) {258                Divider().overlay(Theme.line)259                shortcut("Sous le prix attendu", "arrow.down.to.line") { var f = SearchFilters(); f.deal = .sous; app.explore(f, sort: .deal) }260                shortcut("Maisons", "house") { var f = SearchFilters(); f.propertyType = "Maison"; app.explore(f) }261                shortcut("Condos", "building") { var f = SearchFilters(); f.propertyType = "Condo"; app.explore(f) }262                shortcut("Plex et immeubles à revenus", "building.2") { var f = SearchFilters(); f.propertyType = "Duplex"; app.explore(f) }263            }264        }265        .padding(.horizontal, 20)266    }267268    private func shortcut(_ label: String, _ icon: String, action: @escaping () -> Void) -> some View {269        Button(action: action) {270            VStack(spacing: 0) {271                HStack(spacing: 12) {272                    Image(systemName: icon).font(.system(size: 15)).foregroundStyle(Theme.brand).frame(width: 24)273                    Text(label).font(.subheadline.weight(.medium)).foregroundStyle(Theme.ink)274                    Spacer()275                    Image(systemName: "chevron.right").font(.caption.weight(.semibold)).foregroundStyle(Theme.ink3)276                }277                .padding(.vertical, 13)278                Divider().overlay(Theme.line)279            }280            .contentShape(Rectangle())281        }282        .buttonStyle(.plain)283    }284285    // MARK: Sections286287    private var recentSection: some View {288        VStack(alignment: .leading, spacing: 16) {289            SectionHeader(title: "Nouvelles inscriptions",290                          subtitle: "Les dernières propriétés repérées par Immo-Ka.") {291                Button("Carte") { app.explore(SearchFilters()) }.font(.subheadline.weight(.semibold))292            }293            .padding(.horizontal, 20)294            rail(model.recent)295        }296    }297298    private var dealsSection: some View {299        VStack(alignment: .leading, spacing: 16) {300            SectionHeader(title: "Sous le prix attendu",301                          subtitle: "Des prix demandés sous l'intervalle du prix de vente attendu. Un repère, pas une promesse.") {302                Button("Tout voir") { var f = SearchFilters(); f.deal = .sous; app.explore(f, sort: .deal) }.font(.subheadline.weight(.semibold))303            }304            .padding(.horizontal, 20)305            if let d = model.deals, d.isEmpty {306                Text("Aucune parmi les dernières inscriptions. La carte les signale toutes par un liseré vert.")307                    .font(.footnote).foregroundStyle(Theme.ink3).padding(.horizontal, 20)308            } else {309                rail(model.deals)310            }311        }312    }313314    private func rail(_ listings: [Listing]?) -> some View {315        ScrollView(.horizontal, showsIndicators: false) {316            LazyHStack(alignment: .top, spacing: 14) {317                if let listings {318                    ForEach(Array(listings.enumerated()), id: \.element.id) { i, l in ListingLink(listing: l).frame(width: 286).staggered(i) }319                } else {320                    ForEach(0..<3, id: \.self) { _ in ListingCardSkeleton().frame(width: 286) }321                }322            }323            .scrollTargetLayout()324            .padding(.horizontal, 20)325        }326        .scrollTargetBehavior(.viewAligned)327    }328329    /// Villes : index typographique (nom en serif, nombre de propriétés, prix médian).330    @ViewBuilder331    private var cities: some View {332        let top = Array((model.cities ?? []).prefix(hSize == .regular ? 12 : 8))333        if !top.isEmpty {334            VStack(alignment: .leading, spacing: 12) {335                SectionHeader(title: "Villes", subtitle: "Propriétés à vendre et prix médian demandé.") {336                    Button("Toutes les villes") { app.open(.cities) }.font(.subheadline.weight(.semibold))337                }338                LazyVGrid(columns: Array(repeating: GridItem(.flexible(), spacing: 24), count: hSize == .regular ? 2 : 1), spacing: 0) {339                    ForEach(Array(top.enumerated()), id: \.element.id) { i, c in340                        Button { app.open(.city(c.name)) } label: {341                            VStack(spacing: 0) {342                                HStack(alignment: .firstTextBaseline) {343                                    Text(c.name).font(.editorial(19)).foregroundStyle(Theme.ink).lineLimit(1)344                                    Spacer()345                                    Text(Fmt.int(c.count)).font(.footnote).num().foregroundStyle(Theme.ink3)346                                    Text(c.medianPrice.map { Fmt.compactMoney($0) } ?? "—").font(.subheadline.weight(.semibold)).num().foregroundStyle(Theme.ink)347                                        .frame(minWidth: 70, alignment: .trailing)348                                }349                                .padding(.vertical, 13)350                                Divider().overlay(Theme.line)351                            }352                            .contentShape(Rectangle())353                        }354                        .buttonStyle(.plain)355                        .staggered(i)356                        .accessibilityElement(children: .ignore)357                        .accessibilityLabel("\(c.name), \(c.count) propriétés, prix médian \(c.medianPrice.map { Fmt.money($0) } ?? "inconnu")")358                        .accessibilityAddTraits(.isButton)359                    }360                }361            }362            .padding(.horizontal, 20)363        }364    }365366    /// Le vrai prix, en une phrase et un vrai chiffre du marché.367    @ViewBuilder368    private var vraiPrix: some View {369        VStack(alignment: .leading, spacing: 16) {370            SectionHeader(title: "Le vrai prix",371                          subtitle: "Chaque prix demandé est situé face au prix de vente attendu d'après les ventes réelles : sous l'intervalle, dans l'intervalle ou au-dessus.")372            if let v = model.shares {373                VStack(alignment: .leading, spacing: 12) {374                    VerdictShareBar(shares: v)375                    Text(v.sentence).font(.footnote).num().foregroundStyle(Theme.ink2).fixedSize(horizontal: false, vertical: true)376                }377            }378            NavigationLink(value: Route.vraiPrixGuide) {379                HStack {380                    Text("Comprendre la méthode").font(.subheadline.weight(.semibold)).foregroundStyle(Theme.brand)381                    Image(systemName: "arrow.right").font(.caption.weight(.semibold)).foregroundStyle(Theme.brand)382                }383            }384        }385        .padding(.horizontal, 20)386    }387388    /// Accès aux courtiers et aux taux : lignes à filet, chiffres réels.389    private var services: some View {390        VStack(alignment: .leading, spacing: 12) {391            SectionHeader(title: "Acheter, bien accompagné")392            VStack(spacing: 0) {393                serviceRow("Courtiers et agences", model.agencies.map { $0.agencies.isEmpty ? "\(Fmt.int($0.franchises.count)) bannières et agences" : "\(Fmt.int($0.total)) agences\($0.brokersTotal.map { ", \(Fmt.int($0)) courtiers" } ?? "")" } ?? "Bannières, agences et leurs propriétés",394                           "person.2") { app.tab = .pros }395                Divider().overlay(Theme.line)396                serviceRow("Taux hypothécaires", model.bestRate.map { "Meilleur fixe 5 ans : \(Fmt.rate($0.rate)) (\($0.institution))" } ?? "Meilleurs taux du jour et historique",397                           "percent") { app.tab = .market; app.open(.rates) }398                Divider().overlay(Theme.line)399                serviceRow("Calculateur d'achat", "Versement, mise de fonds, assurance prêt, droits de mutation", "function") { app.tab = .market; app.open(.calculator) }400                Divider().overlay(Theme.line)401                serviceRow("Inspecteurs en bâtiment", "Par région, avec leurs avis", "checklist") { app.tab = .pros; app.open(.inspectors) }402            }403        }404        .padding(.horizontal, 20)405    }406407    private func serviceRow(_ title: String, _ text: String, _ icon: String, action: @escaping () -> Void) -> some View {408        Button(action: action) {409            HStack(alignment: .center, spacing: 14) {410                Image(systemName: icon).font(.system(size: 16)).foregroundStyle(Theme.brand).frame(width: 26)411                VStack(alignment: .leading, spacing: 3) {412                    Text(title).font(.subheadline.weight(.semibold)).foregroundStyle(Theme.ink)413                    Text(text).font(.footnote).num().foregroundStyle(Theme.ink2).fixedSize(horizontal: false, vertical: true).multilineTextAlignment(.leading)414                }415                Spacer(minLength: 8)416                Image(systemName: "chevron.right").font(.caption.weight(.semibold)).foregroundStyle(Theme.ink3)417            }418            .padding(.vertical, 13)419            .contentShape(Rectangle())420        }421        .buttonStyle(.plain)422    }423424    private var closing: some View {425        VStack(spacing: 8) {426            BrandMark(angle: BrandGeometry.ajarAngle).frame(width: 44, height: 44).accessibilityHidden(true)427            Text("Sans compte, sans publicité.").font(.editorial(18)).foregroundStyle(Theme.ink)428            Text("Vos favoris et vos recherches restent sur votre appareil.").font(.footnote).foregroundStyle(Theme.ink3)429        }430        .multilineTextAlignment(.center)431        .frame(maxWidth: .infinity)432        .padding(.horizontal, 30)433    }434}435436/// Répartition des verdicts du vrai prix : une barre en trois aplats qui se déploie, avec ses légendes.437struct VerdictShareBar: View {438    let shares: VerdictShares439    @State private var progress: Double = 0440441    var body: some View {442        let total = max(1, shares.n)443        let sous = shares.sous / total * 100, juste = shares.juste / total * 100, sur = shares.sur / total * 100444        VStack(alignment: .leading, spacing: 8) {445            GeometryReader { geo in446                HStack(spacing: 2) {447                    Rectangle().fill(Theme.good).frame(width: max(2, geo.size.width * sous / 100 * progress))448                    Rectangle().fill(Theme.fair.opacity(0.55)).frame(width: max(2, geo.size.width * juste / 100 * progress))449                    Rectangle().fill(Theme.high).frame(width: max(2, (geo.size.width - 4) * sur / 100 * progress))450                    Spacer(minLength: 0)451                }452                .clipShape(RoundedRectangle(cornerRadius: 3, style: .continuous))453            }454            .frame(height: 10)455            HStack(spacing: 14) {456                legend(Theme.good, "Sous l'intervalle", sous)457                legend(Theme.fair.opacity(0.55), "Dans l'intervalle", juste)458                legend(Theme.high, "Élevé", sur)459            }460        }461        .drawOnAppear($progress, duration: 0.8)462        .accessibilityElement(children: .ignore)463        .accessibilityLabel("Sous l'intervalle \(Fmt.int(shares.sous / total * 100)) %, dans l'intervalle \(Fmt.int(shares.juste / total * 100)) %, élevé \(Fmt.int(shares.sur / total * 100)) %")464    }465466    private func legend(_ color: Color, _ label: String, _ value: Double) -> some View {467        HStack(spacing: 5) {468            RoundedRectangle(cornerRadius: 2).fill(color).frame(width: 9, height: 9)469            Text("\(label) \(Fmt.int(value)) %").font(.caption).num().foregroundStyle(Theme.ink2)470        }471    }472}473474extension VerdictShares {475    /// « Sur 43 139 propriétés évaluées, le prix demandé dépasse la valeur estimée de 8,5 % (médiane). »476    var sentence: String {477        var t = "Sur \(Fmt.int(n)) propriétés évaluées"478        if let m = median {479            t += abs(m) < 0.05 ? ", le prix demandé égale le prix de vente attendu (médiane)"480                : ", le prix demandé \(m > 0 ? "dépasse" : "est sous") le prix de vente attendu de \(Fmt.decimal(abs(m))) % (médiane)"481        }482        return t + "."483    }484}485
Files main
Menu

Theme