SPB Git

Repository Public

ListingView.swift 20.3 KB 407 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : Vrai-Prix iOS9// File             : VraiPrix/Features/Listings/ListingView.swift10// Description      : fiche d'une propriété à vendre — la photo prend place, le11//                    fil à plomb désigne la valeur estimée, le prix demandé est12//                    le losange, l'écart est coté. Puis faits, description,13//                    lectures de la valeur, comparables, historique du prix,14//                    emplacement, propriétés voisines.15// Module           : VraiPrix16// Repository       : https://git.spboucher.ai/vrai-prix-ios-v317// Project Website  : https://www.vrai-prix.com18// Created          : 2026-11-2619// Last Modified    : 2026-11-2620//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 MapKit95import SwiftUI9697struct ListingView: View {98    let uid: String99100    @Environment(AppModel.self) private var model101    @Environment(Library.self) private var library102    @Environment(MotionCenter.self) private var motion103    @Environment(\.accessibilityReduceMotion) private var reduceMotion104    @Environment(\.dynamicTypeSize) private var typeSize105106    @State private var state: Loadable<ListingDetail> = .loading107    @State private var photo: UIImage?108    @State private var ready = false109    @State private var level: PlumbLevel = .none110    @State private var revealed = false111    @State private var comps: [Comparable]?112    @State private var link: ExternalLink?113    @State private var gallery = false114    @State private var expanded = false115116    var body: some View {117        ScrollView {118            Group {119                switch state {120                case .loading: LoadingState(label: "Mesure en cours").padding(.top, 60)121                case .failed(let e): ErrorState(error: e, subject: "Cette propriété à vendre") { Task { await load() } }.padding(.top, 40)122                case .loaded(let d, let stale):123                    if ready { content(d, stale: stale) } else { LoadingState(label: "Mesure en cours").padding(.top, 60) }124                }125            }126            .pageColumn()127            .padding(.bottom, 40)128        }129        .background(Theme.bg)130        .navigationBarTitleDisplayMode(.inline)131        .toolbar { toolbar }132        .task { await load() }133        .safariSheet($link)134        .sheet(isPresented: $gallery) { if let d = state.value { PhotoGallery(images: d.images) } }135    }136137    private func load() async {138        if state.value != nil { return }139        state = .loading140        let trigger = motion.consume("listing:" + uid)141        do {142            let f = try await APIClient.shared.listing(uid)143            level = motion.level(for: trigger, reduceMotion: reduceMotion)144            if let first = f.value.images.first {145                photo = await ImageLoader.shared.image(for: first, maxPixel: 1100)146            }147            state = .loaded(f.value, stale: f.stale)148            ready = true149            library.visit(SavedProperty(listing: f.value))150            comps = try? await APIClient.shared.listingComps(uid)151        } catch is CancellationError {152        } catch { state = .failed(apiError(error)) }153    }154155    @ToolbarContentBuilder156    private var toolbar: some ToolbarContent {157        if let d = state.value {158            let saved = SavedProperty(listing: d)159            ToolbarItemGroup(placement: .topBarTrailing) {160                ShareLink(item: APIClient.site.appending(path: "a-vendre").appending(path: d.listing.uid), subject: Text(saved.title)) {161                    Image(systemName: "square.and.arrow.up")162                }163                .accessibilityLabel("Partager")164                Button {165                    let on = library.toggleFavorite(saved)166                    Haptics.tap()167                    model.showToast(on ? "Ajoutée aux favoris" : "Retirée des favoris")168                } label: { Image(systemName: library.isFavorite(saved.id) ? "heart.fill" : "heart") }169                    .accessibilityLabel(library.isFavorite(saved.id) ? "Retirer des favoris" : "Ajouter aux favoris")170            }171        }172    }173174    @ViewBuilder175    private func content(_ d: ListingDetail, stale: Bool) -> some View {176        let l = d.listing177        VStack(alignment: .leading, spacing: 0) {178            if stale { StaleNotice().padding(.top, 8) }179            VStack(alignment: .leading, spacing: 5) {180                Text(["À vendre", l.propertyType, l.city].compactMap { $0 }.joined(separator: " · ")).eyebrowStyle()181                Text(Fmt.address(l.address)).font(.editorial(27)).foregroundStyle(Theme.ink).fixedSize(horizontal: false, vertical: true)182                    .accessibilityAddTraits(.isHeader).accessibilityIdentifier("listing-title")183            }184            .padding(.top, 10)185186            if d.hasEstimate, let e = d.eval, let est = e.est, let low = e.low, let high = e.high {187                let data = PlumbData(value: est, low: low, high: high, price: l.price, priceLabel: "Prix demandé", reading: d.reading)188                PlumbScene(data: data, photo: photo, level: level) {189                    withAnimation(motion.allowed(reduceMotion: reduceMotion) ? .timingCurve(0.2, 0.7, 0.2, 1, duration: 0.24) : nil) { revealed = true }190                }191                .padding(.top, 14)192                VStack(spacing: 0) {193                    Hairline()194                    FactRow("Prix demandé", Fmt.money(l.price))195                    if let r = d.reading, let p = l.price {196                        FactRow("Écart avec la valeur estimée", "\(Fmt.signedMoney(p - est)) · \(Fmt.pct(r.gapPct))")197                        FactRow(label: "Lecture") { VerdictTag(verdict: r.verdict, gapPct: nil, short: false) }198                        if let inside = r.inRange {199                            Text(inside ? "Le prix demandé est dans la fourchette de l'estimation." : "Le prix demandé est hors de la fourchette de l'estimation.")200                                .font(.footnote).foregroundStyle(Theme.ink3).frame(maxWidth: .infinity, alignment: .leading).padding(.top, 10)201                        }202                    }203                }204                .padding(.top, 18)205                .opacity(revealed ? 1 : 0).offset(y: revealed ? 0 : 6)206            } else {207                if let photo {208                    Image(uiImage: photo).resizable().aspectRatio(contentMode: .fill)209                        .frame(maxWidth: .infinity).frame(height: 240).clipped()210                        .clipShape(RoundedRectangle(cornerRadius: Theme.radius, style: .continuous)).padding(.top, 14)211                        .accessibilityHidden(true)212                }213                VStack(spacing: 0) {214                    Hairline()215                    FactRow("Prix demandé", Fmt.money(l.price))216                }217                .padding(.top, 18)218                // sans jumelage sûr à une unité du rôle : ni valeur ni verdict, mais la raison219                VStack(alignment: .leading, spacing: 6) {220                    Text("Pas d'estimation pour cette inscription").font(.subheadline.weight(.semibold)).foregroundStyle(Theme.ink)221                    Text(d.jumelage?.explanation ?? "Cette inscription n'a pas pu être rattachée sûrement à une unité du rôle d'évaluation.")222                        .font(.footnote).foregroundStyle(Theme.ink2).fixedSize(horizontal: false, vertical: true)223                    Text("Une valeur n'est donnée que lorsque l'inscription désigne sûrement une propriété du rôle.")224                        .font(.footnote).foregroundStyle(Theme.ink3).fixedSize(horizontal: false, vertical: true)225                }226                .frame(maxWidth: .infinity, alignment: .leading)227                .padding(12)228                .background(Theme.surface2, in: RoundedRectangle(cornerRadius: 8, style: .continuous))229                .padding(.top, 14)230                .accessibilityElement(children: .combine)231                .accessibilityIdentifier("no-estimate")232            }233234            let layout = typeSize.isAccessibilitySize ? AnyLayout(VStackLayout(spacing: 10)) : AnyLayout(HStackLayout(spacing: 10))235            layout {236                if d.images.count > 1 {237                    Button { gallery = true } label: { Label("\(d.images.count) photos", systemImage: "photo.on.rectangle") }238                        .buttonStyle(SecondaryButtonStyle())239                }240                let saved = SavedProperty(listing: d)241                Button {242                    switch library.toggleCompare(saved) {243                    case .added: model.showToast("Ajoutée au comparateur")244                    case .removed: model.showToast("Retirée du comparateur")245                    case .full: model.showToast("Le comparateur contient déjà \(Library.compareLimit) propriétés")246                    }247                } label: { Label(library.isCompared(saved.id) ? "Comparée" : "Comparer", systemImage: library.isCompared(saved.id) ? "checkmark" : "rectangle.split.2x1") }248                    .buttonStyle(SecondaryButtonStyle())249            }250            .padding(.top, 18)251252            section("Caractéristiques", note: "Telles que publiées dans l'annonce.") {253                VStack(spacing: 0) {254                    Hairline()255                    if let t = l.propertyType { FactRow("Type", t) }256                    if let b = l.bedrooms, b > 0 { FactRow("Chambres", String(b)) }257                    if let b = l.bathrooms, b > 0 { FactRow("Salles de bain", String(b) + (l.powderRooms.map { $0 > 0 ? " + \($0) salle d'eau" : "" } ?? "")) }258                    if let a = l.areaSqft, a > 0 { FactRow("Superficie habitable", Fmt.area(sqft: a)) }259                    if let a = l.lotSqft, a > 0 { FactRow("Terrain", Fmt.area(sqft: a)) }260                    if let y = l.yearBuilt, y > 1600 { FactRow("Année de construction", String(y)) }261                    if let s = l.sector { FactRow("Secteur", s) }262                    if let f = l.firstSeen { FactRow("En ligne depuis le", Fmt.day(epoch: f)) }263                    if let a = l.agency ?? l.brokerName { FactRow("Publiée par", a) }264                    if let m = l.mls { FactRow("Numéro d'inscription", m) }265                }266            }267268            if let desc = l.description, desc.count > 20 {269                section("Description") {270                    Text(desc).font(.body).foregroundStyle(Theme.ink2).lineSpacing(3)271                        .lineLimit(expanded ? nil : 7).fixedSize(horizontal: false, vertical: true)272                    if desc.count > 420 {273                        Button(expanded ? "Réduire" : "Lire la suite") { withAnimation(.easeOut(duration: 0.2)) { expanded.toggle() } }274                            .font(.subheadline.weight(.medium)).foregroundStyle(Theme.brand).frame(minHeight: 44)275                    }276                }277            }278279            if d.hasEstimate, let e = d.eval {280                section("Les lectures de la valeur", note: "La valeur estimée combine plusieurs méthodes ; les voici une à une.") {281                    HStack(spacing: 10) {282                        ConfidenceBadge(level: e.confidence)283                        if let p = e.confidencePct { Text("indice \(Fmt.decimal(p, digits: 0)) sur 100").font(.subheadline).num().foregroundStyle(Theme.ink3) }284                    }285                    Text(Confidence.explanation(e.confidence)).font(.subheadline).foregroundStyle(Theme.ink2).fixedSize(horizontal: false, vertical: true)286                    VStack(spacing: 0) {287                        Hairline()288                        if let v = e.modelEst { FactRow("Modèle statistique", Fmt.money(v)) }289                        if let v = e.compsEst { FactRow("Ventes comparables ajustées" + (e.nComps.map { " (\($0))" } ?? ""), Fmt.money(v)) }290                        if let v = e.costEst { FactRow("Méthode du coût", Fmt.money(v)) }291                        if let v = e.roleEst { FactRow("Rôle indexé au marché", Fmt.money(v)) }292                        if let v = e.valeurRole { FactRow("Rôle d'évaluation", Fmt.money(v)) }293                        if let j = d.jumelage, j.isSure { FactRow("Jumelage au rôle", "sûr") }294                        if let a = e.evaluatedAt { FactRow("Estimée le", Fmt.day(a)) }295                    }296                    if let j = d.jumelage, j.isSure { Text(j.explanation).font(.footnote).foregroundStyle(Theme.ink3).fixedSize(horizontal: false, vertical: true) }297                    if let u = d.unit, d.jumelage?.isSure != false {298                        NavRow(icon: .roleEvaluation, title: "Fiche de la propriété au rôle", detail: Fmt.address(u.adresse), divider: false) { model.openProperty(u.id) }299                    }300                }301            }302303            if let comps, !comps.isEmpty {304                section("Ventes comparables", note: "Ventes conclues à proximité, ramenées à la propriété.") {305                    ComparablesSection(comps: comps, subject: l.coordinate, subjectTitle: Fmt.address(l.address))306                }307            }308309            if d.priceLog.count > 1 {310                section("Historique du prix demandé") {311                    VStack(spacing: 0) {312                        Hairline()313                        ForEach(d.priceLog.sorted { $0.ts > $1.ts }) { p in FactRow(Fmt.day(p.date), Fmt.money(p.price)) }314                    }315                }316            }317318            if let c = l.coordinate {319                section("Emplacement") {320                    Map(initialPosition: .region(MKCoordinateRegion(center: c, latitudinalMeters: 700, longitudinalMeters: 700)), interactionModes: []) {321                        Annotation(Fmt.address(l.address), coordinate: c, anchor: .bottom) { PriceMarker(text: Fmt.compact(l.price), selected: true) }322                            .annotationTitles(.hidden)323                    }324                    .mapStyle(.standard(pointsOfInterest: .excludingAll))325                    .frame(height: 200)326                    .clipShape(RoundedRectangle(cornerRadius: Theme.radius, style: .continuous))327                    .overlay(RoundedRectangle(cornerRadius: Theme.radius, style: .continuous).strokeBorder(Theme.line, lineWidth: 1))328                    .accessibilityLabel("Carte de l'emplacement")329                    Button { model.showOnMap(lat: c.latitude, lng: c.longitude, layer: .sales) } label: { Label("Voir les ventes autour sur la carte", systemImage: "map") }330                        .buttonStyle(SecondaryButtonStyle())331                }332            }333334            if !d.voisines.isEmpty {335                section("À vendre à proximité") {336                    VStack(spacing: 0) {337                        Hairline()338                        ForEach(d.voisines.prefix(5)) { v in339                            Button { model.openListing(v.uid) } label: { ListingRow(listing: v) }.buttonStyle(.plain)340                            Hairline()341                        }342                    }343                }344            }345346            if let ext = ExternalLink(l.url) {347                Button { link = ext } label: { Label("Voir l'annonce d'origine", systemImage: "arrow.up.right.square") }348                    .buttonStyle(SecondaryButtonStyle()).padding(.top, 30)349            }350            Text("Les photos et la description appartiennent à l'annonce d'origine. Estimation statistique à titre indicatif.")351                .font(.footnote).foregroundStyle(Theme.ink3).fixedSize(horizontal: false, vertical: true).padding(.top, 16)352        }353    }354355    private func section<C: View>(_ title: String, note: String? = nil, @ViewBuilder _ content: () -> C) -> some View {356        VStack(alignment: .leading, spacing: 12) {357            SectionHeader(title, note: note)358            content()359        }360        .padding(.top, 36)361    }362}363364/// Galerie des photos d'une annonce : défilement par pages, compteur.365struct PhotoGallery: View {366    let images: [String]367    @State private var index = 0368    @Environment(\.dismiss) private var dismiss369370    var body: some View {371        NavigationStack {372            TabView(selection: $index) {373                ForEach(Array(images.enumerated()), id: \.offset) { i, src in374                    GalleryPhoto(source: src).tag(i)375                }376            }377            .tabViewStyle(.page(indexDisplayMode: .never))378            .background(Color.black)379            .navigationTitle("\(index + 1) sur \(images.count)")380            .navigationBarTitleDisplayMode(.inline)381            .toolbarColorScheme(.dark, for: .navigationBar)382            .toolbarBackground(Color.black, for: .navigationBar)383            .toolbarBackground(.visible, for: .navigationBar)384            .toolbar { ToolbarItem(placement: .confirmationAction) { Button("Fermer") { dismiss() } } }385        }386    }387}388389private struct GalleryPhoto: View {390    let source: String391    @State private var image: UIImage?392    @State private var failed = false393    var body: some View {394        ZStack {395            Color.black396            if let image { Image(uiImage: image).resizable().scaledToFit() }397            else if failed { Text("Photo indisponible").font(.subheadline).foregroundStyle(.white.opacity(0.7)) }398            else { ProgressView().tint(.white) }399        }400        .task {401            image = await ImageLoader.shared.image(for: source, maxPixel: 1600)402            failed = image == nil403        }404        .accessibilityLabel("Photo de la propriété")405    }406}407
Files main
Menu

Theme