SPB Git

Repository Public

AnnoncesVue.swift 13.4 KB 303 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : Valo-Plex iOS9// File             : ValoPlex/Features/AnnoncesVue.swift10// Description      : plex à vendre, chacun comparé à sa valeur : filtres11//                    (région, type, prix maximal, revenus, tri), chargement à12//                    l'infini, carte menant à la fiche de l'immeuble.13// Module           : ValoPlex14// Repository       : https://git.spboucher.ai/valo-plex-ios15// Project Website  : https://www.valo-plex.com16// Created          : 2026-12-0117// Last Modified    : 2026-12-0118//19// =============================================================================20// AUTHOR & PROFESSIONAL AFFILIATION21// =============================================================================22//23// Author           : Simon-Pierre Boucher24// Position         : Professor of Finance25// Institution      : Université du Québec en Outaouais (UQO)26// Department       : Département des sciences administratives27// Organization     : SP Boucher28//29// Website          : https://spboucher.ai30// Git              : https://git.spboucher.ai31//32// =============================================================================33// OFFICIAL CONTACT DIRECTORY34// =============================================================================35//36// General          : info@spboucher.ai37// Professional     : contact@spboucher.ai38// Direct           : simon@spboucher.ai39// Research         : research@spboucher.ai40// Development      : dev@spboucher.ai41// Support          : support@spboucher.ai42// Security/Admin   : admin@spboucher.ai43// Notifications    : notifications@spboucher.ai44//45// Preferred Contact: support@spboucher.ai46//47// =============================================================================48// COPYRIGHT & INTELLECTUAL PROPERTY49// =============================================================================50//51// Copyright (c) 202652// Simon-Pierre Boucher53//54// All rights reserved where applicable.55//56// This file is governed by the applicable project license,57// copyright notices, institutional agreements and relevant law.58//59// Unless expressly authorized by the applicable license or60// rights holder, copying, redistribution, sublicensing,61// publication and commercial exploitation are not permitted.62//63// Existing third-party rights and notices remain unaffected.64//65// =============================================================================66// CONFIDENTIALITY & SECURITY67// =============================================================================68//69// Classification   : Public70// Distribution     : Public repository; use is governed by the project license71// Security Contact : admin@spboucher.ai72//73// Access to this source does not independently grant permission74// to redistribute or disclose confidential materials.75//76// Do not embed credentials, private keys, access tokens,77// certificates or confidential personal information.78//79// =============================================================================80// LICENSE & MAINTENANCE81// =============================================================================82//83// License          : None specified (no license file in this repository)84// Maintainer       : Simon-Pierre Boucher85// Technical Contact: dev@spboucher.ai86//87// =============================================================================88// END OF SP BOUCHER SOURCE HEADER89// =============================================================================9091import SwiftUI9293struct CarteAnnonce: View {94    let annonce: Annonce95    var image = true9697    var body: some View {98        let o = annonce99        VStack(alignment: .leading, spacing: 0) {100            if image {101                Color.clear102                    .aspectRatio(16.0 / 10.0, contentMode: .fit)103                    .overlay {104                        if let url = o.imageURL {105                            AsyncImage(url: url) { phase in106                                if let img = phase.image {107                                    img.resizable().scaledToFill()108                                } else {109                                    vignette110                                }111                            }112                        } else {113                            vignette114                        }115                    }116                    .background(VX.papier2)117                    .clipped()118                    .accessibilityHidden(true)119                Filet(couleur: VX.encre)120            }121            VStack(alignment: .leading, spacing: 8) {122                Pastille(Position.libelle(o.position), VX.position(o.position))123                Text(Fmt.dollars(o.prix)).font(.serif(25, style: .title2)).foregroundStyle(VX.encre)124                VStack(alignment: .leading, spacing: 2) {125                    Text(Fmt.adresse(o.iAdresse ?? o.adresse)).font(.sans(16)).foregroundStyle(VX.encre).multilineTextAlignment(.leading)126                    Text([o.municipalite, o.iLogements.map { Fmt.logements($0) }, o.annee.map(String.init)].compactMap { $0 }.joined(separator: " · "))127                        .font(.sans(13.5, style: .footnote)).foregroundStyle(VX.encre2)128                }129                Filet(couleur: VX.papier3).padding(.top, 4)130                HStack(alignment: .top, spacing: 6) {131                    mesure(Fmt.pct(o.ecart, 0, signe: true), "face à \(Fmt.grand(o.valeur))")132                    mesure(Fmt.nombre(o.mrbDemande, 1), "fois le revenu \(o.revenuDeclare ? "déclaré" : "estimé")")133                    mesure(Fmt.grand(o.parPorte), "par porte")134                }135            }136            .padding(16)137        }138        .background(VX.carton)139        .overlay(Rectangle().strokeBorder(VX.encre, lineWidth: 1))140        .contentShape(Rectangle())141        .accessibilityElement(children: .combine)142    }143144    private var vignette: some View {145        Facade(logements: annonce.iLogements ?? 2, cote: false).padding(.horizontal, 70).padding(.top, 16)146    }147148    private func mesure(_ valeur: String, _ legende: String) -> some View {149        VStack(alignment: .leading, spacing: 2) {150            Text(valeur).font(.mono(14.5, .moyen)).foregroundStyle(VX.encre)151            Text(legende).font(.sans(12.5, style: .caption)).foregroundStyle(VX.encre2).fixedSize(horizontal: false, vertical: true)152        }153        .frame(maxWidth: .infinity, alignment: .leading)154    }155}156157struct AnnoncesVue: View {158    @Environment(Navigation.self) private var navigation159160    @State private var annonces: [Annonce] = []161    @State private var total: Int?162    @State private var page = 0163    @State private var enCours = false164    @State private var panne: ErreurAPI?165    @State private var regions: [Territoire] = []166167    static let tris: [(String, String)] = [168        ("ecart", "Écart à la valeur"), ("rendement", "Revenu le plus élevé pour le prix"), ("porte", "Prix par porte"),169        ("recent", "Plus récents"), ("prix", "Prix croissant"), ("prix-desc", "Prix décroissant"),170    ]171    static let plafonds = [400_000, 600_000, 800_000, 1_000_000, 1_500_000, 2_500_000]172    static let parPage = 24173174    private var fini: Bool { total.map { annonces.count >= $0 } ?? false }175176    var body: some View {177        @Bindable var navigation = navigation178        let f = navigation.filtre179        Ecran(racine: true, largeur: 1100, ancre: annonces.isEmpty ? nil : navigation.ancre) {180            TitreEcran(181                etiquette: "Plex à vendre" + (total.map { " · \(Fmt.nombre($0)) inscription\($0 > 1 ? "s" : "") analysée\($0 > 1 ? "s" : "")" } ?? ""),182                titre: "Chaque prix demandé, face à la valeur.",183                chapeau: "Seules les inscriptions rattachées avec certitude à un immeuble du rôle sont analysées. La valeur vient des ventes réelles ; le prix demandé n'y entre pas."184            )185            filtres(f).padding(.top, 22)186187            if let panne, annonces.isEmpty {188                Panne(message: panne.message) { Task { await recharger() } }189            } else if total == 0 {190                Text("Aucune inscription ne correspond à ces critères.").font(.sans(16)).foregroundStyle(VX.encre2).padding(.vertical, 28)191            }192            LazyVGrid(columns: [GridItem(.adaptive(minimum: 300, maximum: 520), spacing: 20, alignment: .top)], spacing: 20) {193                ForEach(annonces) { o in194                    if let id = o.id {195                        NavigationLink(value: Route.immeuble(id)) { CarteAnnonce(annonce: o) }196                            .buttonStyle(.plain)197                            .onAppear { if o.uid == annonces.last?.uid { Task { await suite() } } }198                    }199                }200            }201            .padding(.top, 22)202            .id("cartes")203            if enCours {204                Attente(libelle: annonces.isEmpty ? "Lecture des inscriptions" : "Inscriptions suivantes")205            } else if panne != nil, !annonces.isEmpty {206                Panne(message: "La suite n'a pas pu être chargée.") { Task { await suite() } }207            } else if fini, annonces.count > 6 {208                Etiquette("Fin de la liste · \(Fmt.nombre(annonces.count)) inscriptions").padding(.top, 28)209            }210        }211        .task(id: f) { await recharger() }212        .task {213            if regions.isEmpty { regions = (try? await API.marche().regions) ?? [] }214        }215    }216217    @ViewBuilder218    private func filtres(_ f: API.FiltreAnnonces) -> some View {219        let colonnes = [GridItem(.adaptive(minimum: 150), spacing: 10, alignment: .top)]220        LazyVGrid(columns: colonnes, alignment: .leading, spacing: 10) {221            choix("Région", f.region.isEmpty ? "Tout le Québec" : (regions.first { $0.code == f.region }?.nom ?? "Région \(f.region)")) {222                Button("Tout le Québec") { navigation.filtre.region = "" }223                ForEach(regions) { r in Button(r.nom) { navigation.filtre.region = r.code } }224            }225            choix("Type", f.classe.isEmpty ? "Tous" : Fmt.libelleClasse(f.classe)) {226                Button("Tous") { navigation.filtre.classe = "" }227                ForEach(Fmt.classes, id: \.cle) { c in Button(c.nom) { navigation.filtre.classe = c.cle } }228            }229            choix("Prix maximal", f.prixMax > 0 ? Fmt.grand(Double(f.prixMax)) : "Aucun") {230                Button("Aucun") { navigation.filtre.prixMax = 0 }231                ForEach(Self.plafonds, id: \.self) { p in Button(Fmt.grand(Double(p))) { navigation.filtre.prixMax = p } }232            }233            choix("Revenus", f.revenuDeclare ? "Déclarés par le vendeur" : "Tous") {234                Button("Tous") { navigation.filtre.revenuDeclare = false }235                Button("Déclarés par le vendeur") { navigation.filtre.revenuDeclare = true }236            }237            choix("Tri", Self.tris.first { $0.0 == f.tri }?.1 ?? "Écart à la valeur") {238                ForEach(Self.tris, id: \.0) { t in Button(t.1) { navigation.filtre.tri = t.0 } }239            }240        }241        if f.actifs > 0 {242            Button("Retirer les filtres") { navigation.filtre = API.FiltreAnnonces(tri: f.tri) }243                .buttonStyle(.plain)244                .font(.sans(13.5, style: .footnote))245                .foregroundStyle(VX.encre2)246                .underline(true, color: VX.trait)247                .padding(.top, 10)248        }249    }250251    private func choix<M: View>(_ libelle: String, _ valeur: String, @ViewBuilder menu: () -> M) -> some View {252        VStack(alignment: .leading, spacing: 4) {253            Etiquette(libelle)254            Menu {255                menu()256            } label: {257                HStack(spacing: 6) {258                    Text(valeur).font(.sans(15, style: .subheadline)).foregroundStyle(VX.encre).lineLimit(1)259                    Spacer(minLength: 4)260                    Fleche().rotation(.degrees(-90)).stroke(VX.encre, lineWidth: 1.2).frame(width: 6, height: 10)261                }262                .padding(.horizontal, 10)263                .padding(.vertical, 10)264                .background(VX.carton)265                .overlay(Rectangle().strokeBorder(VX.encre, lineWidth: 1))266                .contentShape(Rectangle())267            }268            .accessibilityLabel("\(libelle) : \(valeur)")269        }270    }271272    private func recharger() async {273        annonces = []274        total = nil275        page = 0276        panne = nil277        enCours = false278        await suite()279    }280281    private func suite() async {282        guard !enCours, !fini else { return }283        enCours = true284        defer { enCours = false }285        let filtre = navigation.filtre286        do {287            let r = try await API.annonces(filtre, page: page + 1, parPage: Self.parPage)288            guard !Task.isCancelled, filtre == navigation.filtre else { return }289            let connues = Set(annonces.map(\.uid))290            annonces += r.annonces.filter { !connues.contains($0.uid) }291            page = r.page292            // une page vide avant le total annoncé arrête la pagination plutôt que de boucler293            total = r.annonces.isEmpty ? annonces.count : r.total294            panne = nil295        } catch is CancellationError {296        } catch let e as ErreurAPI {297            panne = e298        } catch {299            panne = .reseau300        }301    }302}303
Files main
Menu

Theme