SPB Git

Repository Public

ListingView.swift 19.9 KB 430 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : Immo-Ka iOS9// File             : ImmoKa/Features/Listing/ListingView.swift10// Description      : fiche d'une propriété — galerie, prix et verdict du vrai11//                    prix, faits clés, actions, puis les blocs dans l'ordre12//                    standard ; les blocs secondaires se chargent à leur13//                    apparition et se masquent sans données.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 ListingModel {97    let uid: String98    var listing: Listing?99    var error: Error?100    var loading = false101102    init(uid: String) { self.uid = uid }103104    func load(force: Bool = false) async {105        if listing != nil, !force { return }106        loading = true107        error = nil108        do {109            // fiche demandée au geste par la porte : on la reprend au lieu de la redemander110            if !force, let ready = try await ListingPrefetch.shared.take(uid) { listing = ready }111            else { listing = try await APIClient.shared.fullListing(uid) }112        } catch is CancellationError {113        } catch {114            self.error = error115        }116        loading = false117    }118}119120struct ListingView: View {121    let uid: String122    @Environment(AppModel.self) private var app123    @Environment(Library.self) private var library124    @Environment(\.horizontalSizeClass) private var hSize125    @Environment(DoorCenter.self) private var door126    @Environment(\.dynamicTypeSize) private var typeSize127    @State private var model: ListingModel128    @State private var photo = 0129    @State private var showGallery = false130    @State private var external: ExternalLink?131    @Namespace private var galleryNS132133    init(uid: String) {134        self.uid = uid135        _model = State(initialValue: ListingModel(uid: uid))136    }137138    var body: some View {139        Group {140            if let l = model.listing {141                content(l)142            } else if let error = model.error {143                if case APIError.goneListing(let g) = error {144                    GoneListingView(gone: g)145                } else if case APIError.notFound = error {146                    EmptyStateView(door: .closed, title: "Propriété introuvable",147                                   message: "L'inscription a peut-être été retirée par la source.",148                                   actionTitle: "Explorer la carte") { app.tab = .explore }149                } else {150                    ErrorStateView(error: error) { Task { await model.load(force: true) } }151                }152            } else {153                loadingView154            }155        }156        // le fond couvre tout l'écran, aussi quand l'état (erreur, introuvable) n'occupe que sa hauteur157        .frame(maxWidth: .infinity, maxHeight: .infinity)158        .background(Theme.bg.ignoresSafeArea())159        .navigationBarTitleDisplayMode(.inline)160        .toolbar {161            if let l = model.listing {162                ToolbarItemGroup(placement: .topBarTrailing) {163                    if let url = URL(string: "https://www.immo-ka.com/propriete/\(l.uid.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? l.uid)") {164                        ShareLink(item: url, subject: Text(l.displayTitle),165                                  message: Text("\(l.displayTitle), \(l.cleanCity) — \(l.plausiblePrice.map { Fmt.money($0) } ?? "prix sur demande")")) {166                            Image(systemName: "square.and.arrow.up")167                        }168                        .accessibilityLabel("Partager")169                    }170                    Button {171                        let added = library.toggleFavorite(l)172                        if added { Haptics.success() } else { Haptics.tap() }173                        app.showToast(added ? "Ajoutée à vos favoris" : "Retirée des favoris")174                    } label: {175                        Image(systemName: library.isFavorite(l.uid) ? "heart.fill" : "heart")176                            .foregroundStyle(library.isFavorite(l.uid) ? Theme.heart : Theme.ink)177                            .heartBurst(library.isFavorite(l.uid))178                    }179                    .accessibilityLabel(library.isFavorite(l.uid) ? "Retirer des favoris" : "Ajouter aux favoris")180                    .accessibilityIdentifier("listing.favorite")181                }182            }183        }184        .task {185            await model.load()186            if let l = model.listing { library.markSeen(l); library.refreshFavorite(l) }187        }188        .fullScreenCover(isPresented: $showGallery) {189            GalleryViewer(images: model.listing?.images ?? [], captions: model.listing?.details.photoCaptions ?? [], index: $photo)190                .navigationTransition(.zoom(sourceID: "galerie", in: galleryNS))191        }192        .safariSheet($external)193    }194195    private var loadingView: some View {196        ScrollView {197            VStack(alignment: .leading, spacing: 16) {198                Skeleton(height: 320, radius: 0)199                VStack(alignment: .leading, spacing: 12) {200                    Skeleton(height: 34).frame(width: 170)201                    Skeleton(height: 18).frame(maxWidth: 280)202                    Skeleton(height: 14).frame(width: 200)203                    Skeleton(height: 120, radius: Theme.radius)204                }205                .padding(.horizontal, 20)206            }207        }208        .accessibilityLabel("Chargement de la fiche")209    }210211    private func content(_ l: Listing) -> some View {212        ScrollViewReader { proxy in213        ScrollView {214            VStack(alignment: .leading, spacing: 0) {215                // 1. galerie216                GalleryCarousel(images: l.images, title: l.displayTitle, index: $photo) { showGallery = true }217                    .frame(height: hSize == .regular ? 460 : 320)218                    .frame(maxWidth: .infinity)219                    .clipped()220                    // cible du passage du seuil : l'embrasure de la porte de la maison vient exactement sur cette photo221                    .onGeometryChange(for: CGRect.self) { $0.frame(in: .global) } action: { door.heroRect = $0 }222                    // transition partagée vers la visionneuse plein écran : la photo s'agrandit depuis la galerie223                    .matchedTransitionSource(id: "galerie", in: galleryNS)224225                // chaque bloc porte son propre espacement : un bloc sans données ne laisse aucun vide,226                // et les blocs sous la ligne de flottaison ne se chargent qu'à leur apparition227                LazyVStack(alignment: .leading, spacing: 0) {228                    if !l.active { inactiveBanner.padding(.bottom, 30) }229                    // 2. prix, verdict, adresse, faits clés, actions230                    SummarySection(listing: l, external: $external).padding(.bottom, l.isV3 ? 18 : 30).id("summary")231                    if l.isV3 { MarketStatusSection(listing: l) }232                    // 3. description233                    DescriptionSection(listing: l).id("description")234                    // 4. caractéristiques235                    FeaturesSection(listing: l)236                    if l.isV3 { FlagsSection(listing: l) }237                    // 5. bâtiment et terrain238                    BuildingSection(listing: l).id("building")239                    // 6. analyses : vrai prix, historique du prix, financement240                    // v3 : prix de vente attendu, coût de possession poste par poste ; le calculateur reste pour simuler241                    if l.isV3 {242                        ValuationSection(listing: l).id("analyses")243                        PriceHistorySection(listing: l)244                        OwnershipSection(listing: l).id("ownership")245                    } else {246                        VraiPrixSection(listing: l, external: $external).id("analyses")247                        PriceHistorySection(listing: l)248                    }249                    FinancingSection(listing: l).id("financing")250                    // 7. carte et à proximité251                    LocationSection(listing: l).id("location")252                    // 8 et 9. quartier et risques253                    NeighbourhoodSection(listing: l).id("quartier")254                    RisksSection(listing: l).id("risks")255                    // courtier et agence256                    BrokerSection(listing: l, external: $external).padding(.bottom, 30).id("broker")257                    // comparables258                    if l.isV3 {259                        SamePropertySection(listing: l, external: $external).id("links")260                        ComparablesV3Section(listing: l).id("comparables")261                    } else {262                        ComparablesSection(listing: l).id("comparables")263                    }264                }265                .padding(.horizontal, 20)266                .padding(.top, 22)267                .padding(.bottom, 30)268                .frame(maxWidth: 760, alignment: .leading)269                .frame(maxWidth: .infinity)270            }271        }272        .safeAreaInset(edge: .bottom) { actionBar(l) }273        .refreshable { await model.load(force: true) }274        .task {275            // ancre de départ imposée par argument de lancement (captures d'écran des sections basses)276            guard let anchor = UserDefaults.standard.string(forKey: "IKAnchor") else { return }277            try? await Task.sleep(for: .seconds(1.2))278            proxy.scrollTo(anchor, anchor: .top)279            try? await Task.sleep(for: .seconds(1.5))280            proxy.scrollTo(anchor, anchor: .top)281        }282        }283    }284285    private var inactiveBanner: some View {286        Label("Cette inscription n'est plus en ligne. La fiche reste consultable.", systemImage: "clock.badge.xmark")287            .font(.subheadline.weight(.medium))288            .foregroundStyle(Theme.high)289            .padding(14)290            .frame(maxWidth: .infinity, alignment: .leading)291            .background(Theme.highSoft, in: RoundedRectangle(cornerRadius: 16, style: .continuous))292    }293294    private func actionBar(_ l: Listing) -> some View {295        HStack(spacing: 12) {296            // aux très grandes tailles de texte, la barre ne garde que l'action : le prix est en tête de fiche297            if !typeSize.isAccessibilitySize {298                VStack(alignment: .leading, spacing: 1) {299                    PriceText(price: l.price, size: 21)300                    if let v = l.verdict {301                        Text(v.label)302                            .font(.caption.weight(.medium)).foregroundStyle(Theme.color(for: v)).lineLimit(1).minimumScaleFactor(0.8)303                    }304                }305                Spacer(minLength: 8)306            }307            if let link = ExternalLink(l.url) {308                Button {309                    Haptics.tap()310                    external = link311                } label: {312                    HStack(spacing: 8) {313                        Text("Voir l'inscription").lineLimit(1).minimumScaleFactor(0.7)314                        Image(systemName: "arrow.up.right").font(.system(size: 13, weight: .bold))315                    }316                    .frame(maxWidth: typeSize.isAccessibilitySize ? .infinity : nil)317                }318                .buttonStyle(PrimaryButtonStyle())319                .accessibilityHint("Ouvre l'inscription originale sur \(app.sourceName(l.source))")320                .accessibilityIdentifier("listing.open")321            }322        }323        .padding(.horizontal, 18)324        .padding(.vertical, 10)325        .background(Theme.bg)326        .overlay(alignment: .top) { Rectangle().fill(Theme.line).frame(height: 1) }327    }328}329330// MARK: - 2. Résumé331332struct SummarySection: View {333    let listing: Listing334    @Binding var external: ExternalLink?335    @Environment(Library.self) private var library336    @Environment(AppModel.self) private var app337    @State private var pdf: ExternalLink?338    /// largeur minimale d'un fait clé : grandit avec la taille du texte (trois colonnes, puis deux, puis une)339    @ScaledMetric(relativeTo: .title3) private var factWidth: CGFloat = 100340341    var body: some View {342        let l = listing343        VStack(alignment: .leading, spacing: 16) {344            HStack(alignment: .top) {345                VStack(alignment: .leading, spacing: 4) {346                    PriceText(price: l.price, size: 36)347                    if let p = l.pricePerSqft {348                        Text("\(Fmt.int(p)) $ le pi²").font(.caption).num().foregroundStyle(Theme.ink3)349                    }350                }351                Spacer()352                VerdictPill(verdict: l.verdict, deviation: l.deviation, large: true)353            }354            VStack(alignment: .leading, spacing: 5) {355                Text(l.displayTitle).font(.editorial(22)).foregroundStyle(Theme.ink)356                    .fixedSize(horizontal: false, vertical: true)357                Text([l.kind.isEmpty ? nil : l.kind, l.place.isEmpty ? nil : l.place, l.details.postalCode].compactMap { $0 }.joined(separator: " · "))358                    .font(.subheadline).foregroundStyle(Theme.ink2)359                    .fixedSize(horizontal: false, vertical: true)360            }361            let facts = keyFacts(l)362            if !facts.isEmpty {363                // faits clés : une grille à filets, sans boîtes364                LazyVGrid(columns: [GridItem(.adaptive(minimum: factWidth), spacing: 10, alignment: .topLeading)], alignment: .leading, spacing: 14) {365                    ForEach(facts, id: \.label) { f in366                        VStack(alignment: .leading, spacing: 3) {367                            Text(f.value).font(.display(19, weight: .semibold)).num().foregroundStyle(Theme.ink).lineLimit(1).minimumScaleFactor(0.7)368                            Text(f.label).font(.caption).foregroundStyle(Theme.ink3).fixedSize(horizontal: false, vertical: true)369                        }370                        .frame(maxWidth: .infinity, alignment: .leading)371                        .accessibilityElement(children: .ignore)372                        .accessibilityLabel("\(f.label) : \(f.value)")373                    }374                }375                .padding(.vertical, 14)376                .overlay(alignment: .top) { Divider().overlay(Theme.line) }377                .overlay(alignment: .bottom) { Divider().overlay(Theme.line) }378            }379            HStack(spacing: 10) {380                let inCompare = library.compareIDs.contains(l.uid)381                Button {382                    switch library.toggleCompare(l.uid) {383                    case .added: Haptics.success(); app.showToast("Ajoutée au comparateur")384                    case .removed: Haptics.tap(); app.showToast("Retirée du comparateur")385                    case .full: Haptics.warning(); app.showToast("Le comparateur contient déjà \(Library.compareMax) propriétés")386                    }387                } label: {388                    Label(inCompare ? "Dans le comparateur" : "Comparer", systemImage: inCompare ? "checkmark" : "rectangle.split.2x1")389                }390                .buttonStyle(SoftButtonStyle())391                Button {392                    Task { if let u = await APIClient.shared.reportURL(l.uid) { pdf = ExternalLink(url: u) } }393                } label: {394                    Label(l.isV3 ? "Rapport PDF" : "Fiche PDF", systemImage: "doc.richtext")395                }396                .buttonStyle(SoftButtonStyle())397            }398            statusLine(l)399        }400        .safariSheet($pdf)401    }402403    /// Jours sur le marché, numéro d'inscription.404    @ViewBuilder405    private func statusLine(_ l: Listing) -> some View {406        let parts: [String] = [407            l.marketCensored ? nil : l.daysOnMarket.map { $0 == 0 ? "Repérée aujourd'hui" : "Observée depuis \(Fmt.plural($0, "jour", "jours"))" },408            l.mls.map { "N° d'inscription \($0)" },409        ].compactMap { $0 }410        if !parts.isEmpty {411            Text(parts.joined(separator: " · ")).font(.caption).num().foregroundStyle(Theme.ink3)412        }413    }414415    private struct Fact { let value: String; let label: String }416417    private func keyFacts(_ l: Listing) -> [Fact] {418        var out: [Fact] = []419        if let b = l.bedrooms, b > 0 { out.append(Fact(value: String(b), label: b > 1 ? "chambres" : "chambre")) }420        if let b = l.bathrooms, b > 0 {421            out.append(Fact(value: String(b) + (l.powderRooms.flatMap { $0 > 0 ? " + \($0)" : nil } ?? ""),422                            label: (l.powderRooms ?? 0) > 0 ? "sdb + salle d'eau" : (b > 1 ? "salles de bain" : "salle de bain")))423        }424        if let a = l.areaSqft { out.append(Fact(value: "\(Fmt.int(a)) pi²", label: "habitables")) }425        if let lot = Fmt.area(l.lotSqft) { out.append(Fact(value: lot, label: "de terrain")) }426        if let y = l.yearBuilt { out.append(Fact(value: String(y), label: "construction")) }427        return out428    }429}430
Files main
Menu

Theme