Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : Vrai-Prix iOS9// File : VraiPrix/Features/V3/ListingsV3.swift10// Description : propriétés à vendre sous l'API v3 : prix demandés,11// rattachés par le moteur à une unité du rôle quand c'est12// possible, avec la valeur de l'unité et la position du prix13// demandé. Une inscription que rien ne rattache n'a ni14// valeur ni position, et l'écran dit pourquoi.15// Module : VraiPrix16// Repository : https://git.spboucher.ai/vrai-prix-ios-v317// Project Website : https://www.vrai-prix.com18// Created : 2026-11-2819// Last Modified : 2026-11-2820//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 SwiftUI9495struct ListingQuery: Sendable, Hashable {96 enum Sort: String, CaseIterable, Identifiable, Sendable {97 case defaut, recentes, prixCroissant = "prix_croissant", prixDecroissant = "prix_decroissant"98 case ecartCroissant = "ecart_croissant", ecartDecroissant = "ecart_decroissant"99 var id: String { rawValue }100 var label: String {101 switch self {102 case .defaut: "Rattachées d'abord"103 case .recentes: "Les plus récentes"104 case .prixCroissant: "Prix croissant"105 case .prixDecroissant: "Prix décroissant"106 case .ecartCroissant: "Écart à la valeur, croissant"107 case .ecartDecroissant: "Écart à la valeur, décroissant"108 }109 }110 }111 static let groups: [(key: String, label: String)] = [("", "Tous"), ("maison", "Maison"), ("condo", "Copropriété"), ("plex", "Plex"),112 ("chalet", "Chalet"), ("terrain", "Terrain"), ("commercial", "Commercial")]113 static let positions: [(key: String, label: String)] = [("", "Toutes"), ("sous", "Sous l'intervalle"), ("dans", "Dans l'intervalle"),114 ("au-dessus", "Au-dessus"), ("aucune", "Sans position")]115 static let bedrooms: [(key: String, label: String)] = [("", "Toutes"), ("1", "1 +"), ("2", "2 +"), ("3", "3 +"), ("4", "4 +")]116117 var place = ""118 var municipality = ""119 var group = ""120 var position = ""121 var bedrooms = ""122 var min: Double?123 var max: Double?124 var linkedOnly = false125 var sort: Sort = .defaut126127 var query: [String: String?] {128 ["q": place.isEmpty ? nil : place, "municipalite": municipality.isEmpty ? nil : municipality, "groupe": group.isEmpty ? nil : group,129 "position": position.isEmpty ? nil : position, "chambres_min": bedrooms.isEmpty ? nil : bedrooms,130 "prix_min": min.map { String(Int($0)) }, "prix_max": max.map { String(Int($0)) },131 "rattachee": linkedOnly ? "1" : nil, "tri": sort == .defaut ? nil : sort.rawValue]132 }133 var activeCount: Int {134 [!group.isEmpty, !position.isEmpty, !bedrooms.isEmpty, min != nil || max != nil, linkedOnly, sort != .defaut, !municipality.isEmpty].filter { $0 }.count135 }136}137138struct ListingsV3View: View {139 @State var query: ListingQuery140141 @Environment(AppModel.self) private var model142 @State private var rows: [ListingV3] = []143 @State private var cursor: String?144 @State private var page: ListingsPageV3?145 @State private var stale = false146 @State private var loading = false147 @State private var error: APIError?148 @State private var showFilters = false149 @State private var placeDraft = ""150151 var body: some View {152 ScrollView {153 LazyVStack(alignment: .leading, spacing: 0) {154 controls155 if stale { StaleNotice().padding(.top, 10) }156 summary.padding(.top, 14).padding(.bottom, 4)157 Hairline()158 list159 }160 .pageColumn()161 .padding(.bottom, 32)162 }163 .background(Theme.bg)164 .navigationTitle(query.municipality.isEmpty ? "À vendre" : "À vendre, \(query.municipality)")165 .navigationBarTitleDisplayMode(.inline)166 .sheet(isPresented: $showFilters) {167 ListingQuerySheet(query: $query, municipalities: page?.municipalites ?? []).presentationDetents([.large])168 }169 .task(id: query) { await reload() }170 .task {171 placeDraft = query.place172 if model.launchSheet == "listingfilters" { showFilters = true }173 }174 .refreshable { await reload() }175 }176177 private var controls: some View {178 VStack(alignment: .leading, spacing: 10) {179 HStack(spacing: 8) {180 HStack(spacing: 8) {181 Image(systemName: "magnifyingglass").foregroundStyle(Theme.ink3)182 TextField("Adresse, ville ou secteur", text: $placeDraft)183 .textInputAutocapitalization(.words).autocorrectionDisabled().submitLabel(.search)184 .onSubmit { query.place = placeDraft.trimmingCharacters(in: .whitespaces) }185 .accessibilityIdentifier("listings-place")186 if !placeDraft.isEmpty {187 Button { placeDraft = ""; query.place = "" } label: {188 Image(systemName: "xmark.circle.fill").foregroundStyle(Theme.ink3).frame(width: 30, height: 44)189 }190 .buttonStyle(.plain).accessibilityLabel("Effacer")191 }192 }193 .padding(.horizontal, 12).frame(minHeight: 48)194 .background(Theme.surface, in: RoundedRectangle(cornerRadius: Theme.radiusSmall, style: .continuous))195 .overlay(RoundedRectangle(cornerRadius: Theme.radiusSmall, style: .continuous).strokeBorder(Theme.lineControl, lineWidth: 1))196 Button { showFilters = true } label: {197 HStack(spacing: 5) {198 Image(systemName: "slider.horizontal.3")199 if query.activeCount > 0 { Text(String(query.activeCount)).font(.footnote.weight(.bold)).monospacedDigit() }200 }201 .foregroundStyle(Theme.ink).frame(minWidth: 48, minHeight: 48)202 .background(Theme.surface, in: RoundedRectangle(cornerRadius: Theme.radiusSmall, style: .continuous))203 .overlay(RoundedRectangle(cornerRadius: Theme.radiusSmall, style: .continuous).strokeBorder(Theme.lineControl, lineWidth: 1))204 }205 .buttonStyle(.plain)206 .accessibilityLabel("Filtres et tri")207 .accessibilityIdentifier("listings-filters")208 }209 ScrollView(.horizontal, showsIndicators: false) {210 HStack(spacing: 8) {211 ForEach(ListingQuery.positions, id: \.key) { p in212 FilterChip(label: p.label + (count(p.key).map { " · " + Fmt.int($0) } ?? ""), active: query.position == p.key) { query.position = p.key }213 }214 }215 }216 }217 }218219 /// Effectif d'une position dans la sélection courante (avant le filtre de position), rendu par le service.220 private func count(_ key: String) -> Int? {221 guard !key.isEmpty, let p = page?.positions, !p.isEmpty else { return nil }222 return p[key] ?? p[key.replacingOccurrences(of: "-", with: "_")]223 }224225 private var summary: some View {226 VStack(alignment: .leading, spacing: 3) {227 Text(loading && rows.isEmpty ? "Recherche…" : "\(Fmt.int(page?.total ?? rows.count)) \((page?.total ?? rows.count) == 1 ? "inscription" : "inscriptions") · \(query.sort.label.lowercased())")228 .font(.subheadline.weight(.medium)).num().foregroundStyle(Theme.ink)229 .fixedSize(horizontal: false, vertical: true)230 .accessibilityIdentifier("listings-count")231 Text("Prix demandés" + (page?.releveLe.map { ", relevés le \(Fmt.day(String($0.prefix(10))))" } ?? "") + ". Un prix demandé n'est pas un prix de vente.")232 .font(.footnote).num().foregroundStyle(Theme.ink3).fixedSize(horizontal: false, vertical: true)233 if page?.linked == false {234 NoteBlock(text: "Le rattachement des inscriptions au rôle se rafraîchit : valeurs et positions reviendront dans un instant.", dashed: true).padding(.top, 6)235 }236 }237 }238239 @ViewBuilder240 private var list: some View {241 if let error, rows.isEmpty {242 ErrorState(error: error, subject: "La liste des propriétés à vendre") { Task { await reload() } }243 } else if rows.isEmpty, !loading {244 EmptyState(title: "Aucune inscription pour ces critères", message: "Retirez un filtre ou élargissez le lieu.",245 actionLabel: "Retirer les filtres") { placeDraft = ""; query = ListingQuery() }246 } else if rows.isEmpty {247 LoadingState(label: "Chargement des inscriptions")248 } else {249 ForEach(Array(rows.enumerated()), id: \.element.id) { i, l in250 Button { model.openListing(l.id) } label: { ListingV3Row(listing: l) }251 .buttonStyle(.plain)252 .accessibilityIdentifier("listing-row-\(i)")253 .onAppear { if i >= rows.count - 6 { Task { await loadMore() } } }254 Hairline()255 }256 if cursor != nil { HStack { Spacer(); ProgressView(); Spacer() }.padding(.vertical, 18) }257 }258 }259260 private func reload() async {261 loading = true; error = nil262 do {263 let f = try await APIClient.shared.v3Listings(query.query)264 if Task.isCancelled { return }265 rows = f.value.items; cursor = f.value.nextCursor; page = f.value; stale = f.stale266 } catch is CancellationError {267 return268 } catch {269 rows = []; page = nil; self.error = apiError(error)270 }271 loading = false272 }273274 private func loadMore() async {275 guard !loading, let c = cursor else { return }276 loading = true277 defer { loading = false }278 let current = query279 if let f = try? await APIClient.shared.v3Listings(current.query, cursor: c), current == query {280 let known = Set(rows.map(\.id))281 rows += f.value.items.filter { !known.contains($0.id) }282 cursor = f.value.nextCursor283 }284 }285}286287private struct ListingQuerySheet: View {288 @Binding var query: ListingQuery289 let municipalities: [ListingsPageV3.Facet]290 @Environment(\.dismiss) private var dismiss291292 var body: some View {293 NavigationStack {294 ScrollView {295 VStack(alignment: .leading, spacing: 22) {296 group("Genre") { FlowChips(options: ListingQuery.groups, selection: $query.group) }297 group("Prix demandé") { PriceRangeFields(min: $query.min, max: $query.max) }298 group("Chambres") { FlowChips(options: ListingQuery.bedrooms, selection: $query.bedrooms) }299 group("Position du prix demandé") { FlowChips(options: ListingQuery.positions, selection: $query.position) }300 Toggle(isOn: $query.linkedOnly) {301 VStack(alignment: .leading, spacing: 1) {302 Text("Rattachées au rôle seulement").font(.subheadline).foregroundStyle(Theme.ink)303 Text("Les inscriptions qui désignent une propriété du rôle : elles seules ont une valeur.").font(.caption).foregroundStyle(Theme.ink3)304 }305 }306 .tint(Theme.brand)307 if !municipalities.isEmpty {308 group("Municipalité") {309 FlowChips(options: [("", "Toutes")] + municipalities.prefix(14).map { ($0.key, "\($0.key) · \(Fmt.int($0.n))") }, selection: $query.municipality)310 }311 }312 group("Tri") {313 Picker("Tri", selection: $query.sort) { ForEach(ListingQuery.Sort.allCases) { Text($0.label).tag($0) } }314 .pickerStyle(.inline).labelsHidden()315 }316 }317 .padding(Theme.margin)318 }319 .background(Theme.bg)320 .navigationTitle("Filtres")321 .navigationBarTitleDisplayMode(.inline)322 .toolbar {323 ToolbarItem(placement: .topBarLeading) {324 Button("Réinitialiser") { query = ListingQuery(place: query.place) }.disabled(query.activeCount == 0)325 }326 ToolbarItem(placement: .confirmationAction) { Button("Terminé") { dismiss() }.fontWeight(.semibold) }327 }328 }329 }330331 private func group<C: View>(_ title: String, @ViewBuilder _ content: () -> C) -> some View {332 VStack(alignment: .leading, spacing: 10) { Text(title).eyebrowStyle(); content() }333 }334}335336/// Une inscription : photo, prix demandé, adresse ; puis la valeur de l'unité désignée et la position du prix, ou la337/// raison pour laquelle il n'y en a pas.338struct ListingV3Row: View {339 let listing: ListingV3340341 var body: some View {342 HStack(alignment: .top, spacing: 12) {343 RemoteImage(source: listing.image, maxPixel: 360)344 .frame(width: 104, height: 78)345 .clipShape(RoundedRectangle(cornerRadius: 8, style: .continuous))346 VStack(alignment: .leading, spacing: 4) {347 Text(Fmt.money(listing.prixDemande)).font(.body.weight(.semibold)).num().foregroundStyle(Theme.ink)348 Text(listing.title).font(.subheadline).foregroundStyle(Theme.ink).lineLimit(1)349 Text(([listing.place] + facts).filter { !$0.isEmpty }.joined(separator: " · "))350 .font(.footnote).num().foregroundStyle(Theme.ink3).lineLimit(1)351 if let v = listing.valeur, let a = v.amounts {352 IntervalBar(value: a.value, low: a.low, high: a.high, approximate: v.status == .ordre,353 price: listing.position?.prixCompare ?? (v.isFirm ? listing.prixDemande.map { $0 * 0.978 } : nil))354 .padding(.top, 2)355 ViewThatFits(in: .horizontal) {356 HStack(spacing: 8) {357 PositionPlate(position: listing.position?.position, gapPct: listing.position?.ecartPct, size: .compact).fixedSize()358 Text("valeur " + (ValueFmt.amount(v) ?? "")).font(.caption).num().foregroundStyle(Theme.ink3).lineLimit(1).fixedSize()359 }360 VStack(alignment: .leading, spacing: 3) {361 PositionPlate(position: listing.position?.position, gapPct: listing.position?.ecartPct, size: .compact)362 Text("valeur " + (ValueFmt.amount(v) ?? "")).font(.caption).num().foregroundStyle(Theme.ink3).lineLimit(1)363 }364 }365 } else {366 Text(noValueNote).font(.caption).foregroundStyle(Theme.ink3).lineLimit(2).fixedSize(horizontal: false, vertical: true)367 }368 }369 .frame(maxWidth: .infinity, alignment: .leading)370 }371 .padding(.vertical, 12)372 .contentShape(Rectangle())373 .accessibilityElement(children: .ignore)374 .accessibilityLabel(a11y)375 }376377 private var facts: [String] {378 var p: [String] = []379 if let g = listing.groupe { p.append(ListingV3.groupLabel(g)) }380 if let c = listing.chambres, c > 0 { p.append("\(c) ch.") }381 return p382 }383384 /// Pourquoi aucune valeur : le motif de rattachement, ou celui de la valeur, tels que le moteur les écrit.385 private var noValueNote: String {386 if listing.niveau != nil, listing.niveau != "unite", let r = listing.rattachementLibelle { return "Sans valeur : " + r }387 if let m = listing.valeur?.motif { return "Aucune valeur : " + ([m.familyTitle?.lowercased(), m.libelle].compactMap { $0 }.joined(separator: ", ")) }388 if listing.niveau == nil { return "Inscription parue depuis la dernière passe du moteur : pas encore rattachée." }389 return "Aucune valeur pour cette inscription."390 }391392 private var a11y: String {393 var s = "\(listing.title), \(listing.place). Prix demandé \(Fmt.money(listing.prixDemande))."394 if let v = listing.valeur, v.amounts != nil {395 s += " " + ValueFmt.sentence(v)396 if let p = listing.position?.position { s += " \(p.label)" + (listing.position?.ecartPct.map { ", écart de \(Fmt.pct($0))" } ?? "") + "." }397 else { s += " Sans verdict." }398 } else { s += " " + noValueNote + "." }399 return s400 }401}402403// MARK: - Fiche d'une inscription404405struct ListingV3View: View {406 let uid: String407408 @Environment(AppModel.self) private var model409 @Environment(Library.self) private var library410 @Environment(MotionCenter.self) private var motion411 @Environment(\.accessibilityReduceMotion) private var reduceMotion412413 @State private var state: Loadable<ListingV3> = .loading414 @State private var photo: UIImage?415 @State private var level: PlumbLevel = .none416 @State private var revealed = false417 @State private var link: ExternalLink?418 @State private var gallery = false419 @State private var expanded = false420421 var body: some View {422 ScrollView {423 Group {424 switch state {425 case .loading: LoadingState(label: "Mesure en cours").padding(.top, 60)426 case .failed(let e):427 if e == .gone || e == .notFound {428 EmptyState(title: "Inscription introuvable", message: "Cette inscription n'existe pas, n'a jamais été publiée ou a été retirée comme doublon.")429 .padding(.top, 40).accessibilityIdentifier("listing-gone")430 } else {431 ErrorState(error: e, subject: "Cette inscription") { Task { await load(force: true) } }.padding(.top, 40)432 }433 case .loaded(let l, let stale): content(l, stale: stale)434 }435 }436 .pageColumn()437 .padding(.bottom, 40)438 }439 .background(Theme.bg)440 .navigationBarTitleDisplayMode(.inline)441 .toolbar { toolbar }442 .task { await load(force: false) }443 .safariSheet($link)444 .sheet(isPresented: $gallery) { if let l = state.value { PhotoGallery(images: l.images) } }445 .userActivity(Handoff.listingActivity, isActive: state.value != nil) { a in446 guard let l = state.value else { return }447 Handoff.fill(a, title: l.title, path: "a-vendre/" + l.id)448 }449 }450451 private func load(force: Bool) async {452 if state.value != nil, !force { return }453 state = .loading454 let trigger = motion.consume("listing:" + uid)455 do {456 let f = try await APIClient.shared.v3Listing(uid)457 level = motion.level(for: trigger, reduceMotion: reduceMotion)458 if let src = f.value.image, f.value.valeur?.amounts != nil, UserDefaults.standard.string(forKey: "VPHero") != "gable" {459 photo = await ImageLoader.shared.image(for: src, maxPixel: 1100)460 }461 state = .loaded(f.value, stale: f.stale)462 let saved = SavedProperty(v3: f.value)463 library.visit(saved)464 SpotlightIndex.index(saved)465 } catch is CancellationError {466 } catch {467 state = .failed(apiError(error))468 }469 }470471 @ToolbarContentBuilder472 private var toolbar: some ToolbarContent {473 if let l = state.value {474 let saved = SavedProperty(v3: l)475 ToolbarItemGroup(placement: .topBarTrailing) {476 ShareLink(item: APIClient.site.appending(path: "a-vendre").appending(path: l.id), subject: Text(l.title),477 message: Text("\(l.title), \(l.place) : prix demandé \(Fmt.money(l.prixDemande)).")) { Image(systemName: "square.and.arrow.up") }478 .accessibilityLabel("Partager")479 Button {480 let on = library.toggleFavorite(saved)481 Haptics.tap()482 model.showToast(on ? "Ajoutée aux favoris" : "Retirée des favoris")483 } label: { Image(systemName: library.isFavorite(saved.id) ? "heart.fill" : "heart") }484 .accessibilityLabel(library.isFavorite(saved.id) ? "Retirer des favoris" : "Ajouter aux favoris")485 .accessibilityIdentifier("favorite-button")486 }487 }488 }489490 @ViewBuilder491 private func content(_ l: ListingV3, stale: Bool) -> some View {492 let pos = l.position493 VStack(alignment: .leading, spacing: 0) {494 if stale { StaleNotice().padding(.top, 8) }495 if let s = l.stateLabel {496 NoteBlock(text: s + ". Elle reste lisible, sans photos ni courtier, et sans valeur : le moteur ne rattache que les inscriptions en ligne.", dashed: true)497 .padding(.top, 10).accessibilityIdentifier("listing-state")498 }499 VStack(alignment: .leading, spacing: 5) {500 Text([l.typeAnnonce ?? ListingV3.groupLabel(l.groupe), l.place].filter { !$0.isEmpty }.joined(separator: " · ")).eyebrowStyle()501 Text(l.title).font(.editorial(27)).foregroundStyle(Theme.ink).fixedSize(horizontal: false, vertical: true)502 .accessibilityAddTraits(.isHeader).accessibilityIdentifier("listing-title")503 }504 .padding(.top, 10)505506 if let v = l.valeur, let a = v.amounts {507 PlumbScene(data: PlumbData(v3: a.value, low: a.low, high: a.high, approximate: v.status == .ordre,508 price: v.isFirm ? pos?.prixCompare : nil, priceLabel: "Prix demandé, ramené",509 gap: pos?.ecartPct, position: pos?.position),510 photo: photo, level: level) {511 withAnimation(motion.allowed(reduceMotion: reduceMotion) ? .timingCurve(0.2, 0.7, 0.2, 1, duration: 0.24) : nil) { revealed = true }512 }513 .padding(.top, 14)514 VStack(alignment: .leading, spacing: 0) {515 Hairline()516 FactRow("Prix demandé", Fmt.money(l.prixDemande))517 if let c = pos?.prixCompare, let r = pos?.rapport {518 FactRow("Ramené au prix de vente attendu (× \(Fmt.decimal(r, digits: 3)))", Fmt.money(c))519 }520 PositionPlate(position: pos?.position, gapPct: pos?.ecartPct, size: .block,521 reason: pos?.motifLibelle ?? (v.status == .ordre ? "la valeur n'est qu'un ordre de grandeur : aucun prix n'est situé" : nil))522 .padding(.vertical, 12).accessibilityIdentifier("position-plate")523 Hairline()524 Text(v.status == .ordre ? "Ordre de grandeur : l'intervalle est trop large pour situer un prix."525 : "8 ventes semblables sur 10 se concluent dans cet intervalle. Une position dit où se situe le prix, pas si la propriété le vaut.")526 .font(.footnote).foregroundStyle(Theme.ink3).fixedSize(horizontal: false, vertical: true).padding(.top, 10)527 }528 .padding(.top, 18)529 .opacity(revealed ? 1 : 0)530 .offset(y: revealed ? 0 : 6)531 } else {532 if let src = l.image {533 RemoteImage(source: src, maxPixel: 1100).aspectRatio(1.5, contentMode: .fit)534 .clipShape(RoundedRectangle(cornerRadius: Theme.radius, style: .continuous)).padding(.top, 14)535 }536 VStack(alignment: .leading, spacing: 4) {537 Text("Prix demandé").eyebrowStyle()538 Text(Fmt.money(l.prixDemande)).font(.display(34)).num().foregroundStyle(Theme.ink).accessibilityIdentifier("asked-price")539 }540 .padding(.top, 16)541 noValue(l).padding(.top, 14)542 }543544 actions(l).padding(.top, 18)545546 if let pid = l.proprieteId {547 VStack(alignment: .leading, spacing: 0) {548 SectionHeader("Propriété au rôle", note: l.rattachementLibelle.map { Fmt.capitalized($0) + "." })549 NavRow(icon: .roleEvaluation, title: "Fiche de la propriété", detail: "Valeur, ventes enregistrées, comparables, repères du rôle") {550 model.openProperty(pid)551 }552 .accessibilityIdentifier("listing-property")553 }554 .padding(.top, 28)555 }556557 VStack(alignment: .leading, spacing: 0) {558 SectionHeader("L'inscription", note: "Ce que l'annonce publie. Vrai-Prix ne vérifie pas ces renseignements.")559 if let c = l.chambres, c > 0 { FactRow("Chambres", String(c)) }560 if let b = l.sallesDeBain, b > 0 { FactRow("Salles de bain", String(b)) }561 if let a = l.superficiePi2, a > 0 { FactRow("Superficie habitable", Fmt.area(sqft: a)) }562 if let t = l.terrainPi2, t > 0 { FactRow("Terrain", Fmt.area(sqft: t)) }563 if let y = l.annee, y > 1700 { FactRow("Année de construction", String(y)) }564 if let n = l.numero { FactRow("Numéro d'inscription", n) }565 if let a = l.agence { FactRow("Agence", a) }566 if let c = l.courtier { FactRow("Courtier", c) }567 if let d = l.premiereVueLe { FactRow("Vue pour la première fois", Fmt.day(String(d.prefix(10)))) }568 if let d = l.vueLe { FactRow("Relevée la dernière fois", Fmt.day(String(d.prefix(10)))) }569 if let n = l.regroupement, n > 1 { FactRow("Inscrite chez", "\(n) sources") }570 }571 .padding(.top, 28)572573 if l.historique.count > 1 {574 VStack(alignment: .leading, spacing: 0) {575 SectionHeader("Prix demandés successifs")576 ForEach(l.historique) { h in FactRow(Fmt.day(String(h.date.prefix(10))), Fmt.money(h.prix)) }577 }578 .padding(.top, 28)579 }580581 if let d = l.description {582 VStack(alignment: .leading, spacing: 8) {583 SectionHeader("Description de l'annonce")584 Text(d).font(.subheadline).foregroundStyle(Theme.ink2).lineLimit(expanded ? nil : 6).fixedSize(horizontal: false, vertical: true)585 if d.count > 320 { MoreLink(label: expanded ? "Réduire" : "Lire la suite") { expanded.toggle() } }586 }587 .padding(.top, 28)588 }589 if !l.caracteristiques.isEmpty {590 VStack(alignment: .leading, spacing: 8) {591 SectionHeader("Caractéristiques publiées")592 ForEach(l.caracteristiques.prefix(24), id: \.self) { c in593 Text(c).font(.footnote).foregroundStyle(Theme.ink2).frame(maxWidth: .infinity, alignment: .leading)594 }595 }596 .padding(.top, 28)597 }598 }599 }600601 private func noValue(_ l: ListingV3) -> some View {602 let linked = l.niveau == "unite"603 let title = linked ? (l.valeur?.motif?.familyTitle ?? "Aucune valeur") : "Propriété non rattachée au rôle"604 let reason = linked ? l.valeur?.motif?.libelle : (l.rattachementLibelle ?? (l.isOnline ? "inscription parue depuis la dernière passe du moteur" : nil))605 return VStack(alignment: .leading, spacing: 8) {606 NoteBlock(text: [title, reason.map { Fmt.capitalized($0) + "." },607 "Sans valeur, le prix demandé n'est situé nulle part : aucun verdict n'est rendu."].compactMap { $0 }.joined(separator: " : ").replacingOccurrences(of: ". : ", with: ". "),608 dashed: true)609 }610 .accessibilityIdentifier("listing-no-value")611 }612613 @ViewBuilder614 private func actions(_ l: ListingV3) -> some View {615 HStack(spacing: 10) {616 if let u = l.url.flatMap(URL.init(string:)), l.isOnline {617 Button { link = ExternalLink(url: u) } label: { Label("Voir l'annonce", systemImage: "arrow.up.right") }618 .buttonStyle(PrimaryButtonStyle())619 .accessibilityIdentifier("open-source")620 }621 if l.images.count > 1 {622 Button { gallery = true } label: { Label("\(l.images.count) photos", systemImage: "photo.on.rectangle") }623 .buttonStyle(SecondaryButtonStyle())624 }625 }626 if let c = l.coordinate {627 Button { model.showOnMap(lat: c.latitude, lng: c.longitude, layer: .listings, span: 0.01) } label: { Label("Voir sur la carte", systemImage: "map") }628 .buttonStyle(SecondaryButtonStyle()).padding(.top, 10)629 }630 }631}632633extension SavedProperty {634 init(v3 l: ListingV3) {635 let a = l.valeur?.amounts636 self.init(kind: .listing, ref: l.id, title: l.title, subtitle: [l.place, ListingV3.groupLabel(l.groupe)].filter { !$0.isEmpty }.joined(separator: " · "),637 value: a?.value, low: a?.low, high: a?.high, price: l.position?.prixCompare ?? l.prixDemande, priceLabel: "Demandé",638 confidence: l.valeur?.confidence, year: l.annee, areaM2: l.superficiePi2.map { $0 / 10.7639 }, landM2: l.terrainPi2.map { $0 / 10.7639 },639 roll: nil, image: l.image, verdictKey: nil, ecartPct: l.position?.ecartPct, dansFourchette: nil,640 regime: l.valeur?.status?.rawValue ?? (l.niveau == "unite" ? nil : "abstention"),641 motifCode: l.valeur?.motif?.code ?? (l.niveau == "unite" ? nil : "non-rattachee"),642 motifLibelle: l.valeur?.motif?.libelle ?? l.rattachementLibelle, positionKey: l.position?.position?.rawValue)643 }644}645