Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : Immo-Ka iOS9// File : ImmoKa/Features/Pros/CitiesView.swift10// Description : villes — index typographique (propriétés en ligne, prix11// médian) et page d'une ville avec ses propriétés récentes12// et l'accès à la carte.13// Module : ImmoKa14// Repository : https://git.spboucher.ai/immo-ka-ios-v315// Project Website : https://www.immo-ka.com16// Created : 2026-11-2517// Last Modified : 2026-11-2818//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 CitiesView: View {94 @Environment(AppModel.self) private var app95 @Environment(\.horizontalSizeClass) private var hSize96 @State private var cities: [CityEntry]?97 @State private var names: [String] = []98 @State private var error: Error?99 @State private var query = ""100 @State private var byName = false101102 /// Villes affichées : l'index (avec chiffres) ; en recherche, s'y ajoutent les autres municipalités connues.103 private var rows: [CityEntry] {104 guard let cities else { return [] }105 let q = Fmt.slug(query)106 var out = q.isEmpty ? cities : cities.filter { Fmt.slug($0.name).contains(q) }107 if !q.isEmpty {108 let seen = Set(out.map { Fmt.slug($0.name) })109 out += names.filter { let s = Fmt.slug($0); return s.contains(q) && !seen.contains(s) }.prefix(40)110 .map { CityEntry(name: $0, count: 0, medianPrice: nil) }111 }112 if byName { out.sort { $0.name.localizedCaseInsensitiveCompare($1.name) == .orderedAscending } }113 return out114 }115116 var body: some View {117 ScrollView {118 LazyVStack(alignment: .leading, spacing: 0) {119 if cities != nil {120 HStack {121 Text("Propriétés à vendre et prix médian demandé.").font(.subheadline).foregroundStyle(Theme.ink2)122 Spacer()123 SlidingSegmented(selection: $byName, options: [(false, "Offre"), (true, "Nom")], label: "Tri des villes")124 }125 .padding(.bottom, 10)126 Divider().overlay(Theme.line)127 let list = rows128 LazyVGrid(columns: Array(repeating: GridItem(.flexible(), spacing: 28), count: hSize == .regular ? 2 : 1), spacing: 0) {129 ForEach(Array(list.enumerated()), id: \.element.id) { i, c in130 NavigationLink(value: Route.city(c.name)) {131 VStack(spacing: 0) {132 HStack(alignment: .firstTextBaseline) {133 Text(c.name).font(.editorial(19)).foregroundStyle(Theme.ink).lineLimit(1)134 Spacer()135 if c.count > 0 { Text(Fmt.int(c.count)).font(.footnote).num().foregroundStyle(Theme.ink3) }136 Text(c.medianPrice.map { Fmt.compactMoney($0) } ?? "").font(.subheadline.weight(.semibold)).num().foregroundStyle(Theme.ink)137 .frame(minWidth: 70, alignment: .trailing)138 }139 .padding(.vertical, 13)140 Divider().overlay(Theme.line)141 }142 .contentShape(Rectangle())143 }144 .buttonStyle(.plain)145 .staggered(i)146 .accessibilityElement(children: .ignore)147 .accessibilityLabel(c.count > 0 ? "\(c.name), \(c.count) propriétés, prix médian \(c.medianPrice.map { Fmt.money($0) } ?? "inconnu")" : c.name)148 .accessibilityAddTraits(.isButton)149 }150 }151 if list.isEmpty {152 EmptyStateView(door: .closed, title: "Aucune ville à ce nom", message: "Vérifiez l'orthographe, ou cherchez directement sur la carte.",153 actionTitle: "Explorer la carte") { app.tab = .explore }154 }155 } else if let error {156 ErrorStateView(error: error) { Task { await load() } }157 } else {158 ForEach(0..<10, id: \.self) { _ in Skeleton(height: 44, radius: 8).padding(.vertical, 5) }159 }160 }161 .padding(.horizontal, 20).padding(.vertical, 12)162 .frame(maxWidth: 900)163 .frame(maxWidth: .infinity)164 .animation(.snappy, value: byName)165 }166 .background(Theme.bg)167 .navigationTitle("Villes")168 .searchable(text: $query, prompt: "Nom de la ville")169 .task { if cities == nil { await load() } }170 }171172 private func load() async {173 error = nil174 do {175 cities = try await APIClient.shared.cities()176 names = (try? await APIClient.shared.facets().cityNames) ?? []177 } catch is CancellationError {} catch { self.error = error }178 }179}180181struct CityView: View {182 let name: String183 @Environment(AppModel.self) private var app184 @Environment(\.horizontalSizeClass) private var hSize185 @State private var entry: CityEntry?186 @State private var page: CityPage?187 @State private var drawTypes: Double = 0188 @State private var listings: [Listing]?189 @State private var total: Int?190 @State private var error: Error?191 @State private var kind: String?192 @State private var sort: SearchSort = .recent193194 private var filters: SearchFilters {195 var f = SearchFilters(); f.city = name; f.propertyType = kind196 return f197 }198199 var body: some View {200 ScrollView {201 LazyVStack(alignment: .leading, spacing: 24) {202 VStack(alignment: .leading, spacing: 10) {203 Text("Propriétés à vendre à \(name)").font(.editorial(28)).foregroundStyle(Theme.ink).fixedSize(horizontal: false, vertical: true)204 if let total {205 Text("\(Fmt.plural(total, "propriété en ligne", "propriétés en ligne"))\(kind == nil ? (entry?.medianPrice.map { " · prix médian demandé \(Fmt.money($0))" } ?? "") : "")")206 .font(.subheadline).num().foregroundStyle(Theme.ink2).contentTransition(.numericText())207 .accessibilityIdentifier("city.count")208 }209 }210 Button { app.explore(filters, sort: sort) } label: { Label("Voir sur la carte", systemImage: "map") }211 .buttonStyle(PrimaryButtonStyle())212 ScrollView(.horizontal, showsIndicators: false) {213 HStack(spacing: 8) {214 Chip(label: "Tous les types", active: kind == nil) { kind = nil }215 ForEach(["Maison", "Condo", "Duplex", "Triplex", "Terrain"], id: \.self) { k in216 Chip(label: k, icon: PropertyKind.icon(k), active: kind == k) { kind = kind == k ? nil : k }217 }218 }219 .padding(.horizontal, 20)220 }221 .padding(.horizontal, -20)222 typesSection223 VStack(alignment: .leading, spacing: 14) {224 SectionHeader(title: "Inscriptions") {225 Menu {226 Picker("Trier", selection: $sort) { ForEach(SearchSort.allCases) { Text($0.label).tag($0) } }227 } label: {228 Label(sort.label, systemImage: "arrow.up.arrow.down").font(.subheadline.weight(.semibold))229 }230 }231 if let listings {232 if listings.isEmpty {233 EmptyStateView(door: .closed, title: "Aucune propriété pour ces critères",234 message: "Essayez un autre type de propriété ou explorez les villes voisines sur la carte.")235 } else {236 LazyVGrid(columns: Array(repeating: GridItem(.flexible(), spacing: 14), count: hSize == .regular ? 2 : 1), spacing: 14) {237 ForEach(Array(listings.enumerated()), id: \.element.id) { i, l in ListingLink(listing: l).staggered(i) }238 }239 }240 } else if let error {241 ErrorStateView(error: error) { Task { await load() } }242 } else {243 ForEach(0..<2, id: \.self) { _ in ListingCardSkeleton() }244 }245 }246 if ServiceGeneration.current >= 3 {247 VStack(spacing: 0) {248 placeLink(.market(slug: Fmt.slug(name), kind: "municipalite", name: name), "Marché de \(name)",249 "Prix demandés, ventes réelles, indice", "chart.xyaxis.line")250 placeLink(.neighborhood(slug: Fmt.slug(name), city: nil), "Portrait de \(name)",251 "Parc immobilier, taxes, services, transport", "building.2")252 placeLink(.neighborhoods(city: Fmt.slug(name), name: name), "Quartiers de \(name)",253 "Arrondissements, quartiers et secteurs", "square.grid.2x2")254 }255 }256 neighborsSection257 }258 .padding(20)259 .frame(maxWidth: 760, alignment: .leading)260 .frame(maxWidth: .infinity)261 }262 .background(Theme.bg)263 .navigationTitle(name)264 .navigationBarTitleDisplayMode(.inline)265 .refreshable { await load() }266 .task(id: "\(kind ?? "")|\(sort.rawValue)") { await load() }267 }268269 private func placeLink(_ route: Route, _ title: String, _ text: String, _ icon: String) -> some View {270 NavigationLink(value: route) {271 VStack(spacing: 0) {272 HStack(spacing: 14) {273 Image(systemName: icon).font(.system(size: 16)).foregroundStyle(Theme.brand).frame(width: 26)274 VStack(alignment: .leading, spacing: 2) {275 Text(title).font(.subheadline.weight(.semibold)).foregroundStyle(Theme.ink)276 Text(text).font(.footnote).foregroundStyle(Theme.ink3)277 }278 Spacer()279 Image(systemName: "chevron.right").font(.caption.weight(.semibold)).foregroundStyle(Theme.ink3)280 }281 .padding(.vertical, 12)282 Divider().overlay(Theme.line)283 }284 .contentShape(Rectangle())285 }286 .buttonStyle(.plain)287 }288289 /// Prix médian par type de propriété (page de ville de la v2) : barres qui se déploient.290 @ViewBuilder291 private var typesSection: some View {292 if let rows = page?.types.filter({ $0.medianPrice != nil && $0.n >= 3 }).prefix(6), rows.count >= 2 {293 let top = rows.compactMap(\.medianPrice).max() ?? 1294 VStack(alignment: .leading, spacing: 10) {295 SectionHeader(title: "Prix médian par type")296 ForEach(Array(rows)) { r in297 Button { withAnimation(.snappy) { kind = PropertyKind.normalize(r.propertyType) } } label: {298 HStack(spacing: 12) {299 Text(r.propertyType).font(.footnote.weight(.medium)).foregroundStyle(Theme.ink).frame(width: 104, alignment: .leading).lineLimit(1)300 GeometryReader { geo in301 RoundedRectangle(cornerRadius: 2).fill(Theme.brand)302 .frame(width: max(3, geo.size.width * (r.medianPrice ?? 0) / top * drawTypes))303 }304 .frame(height: 8)305 Text(Fmt.compactMoney(r.medianPrice)).font(.footnote.weight(.semibold)).num().foregroundStyle(Theme.ink).frame(width: 62, alignment: .trailing)306 Text(Fmt.int(r.n)).font(.caption).num().foregroundStyle(Theme.ink3).frame(width: 40, alignment: .trailing)307 }308 .contentShape(Rectangle())309 }310 .buttonStyle(.plain)311 .accessibilityLabel("\(r.propertyType) : prix médian \(Fmt.money(r.medianPrice)), \(r.n) propriétés")312 }313 }314 .drawOnAppear($drawTypes, duration: 0.8)315 }316 }317318 @ViewBuilder319 private var neighborsSection: some View {320 if let n = page?.neighbors, !n.isEmpty {321 VStack(alignment: .leading, spacing: 0) {322 SectionHeader(title: "Autour de \(name)").padding(.bottom, 6)323 ForEach(n.prefix(8)) { c in324 NavigationLink(value: Route.city(c.name)) {325 VStack(spacing: 0) {326 HStack(alignment: .firstTextBaseline) {327 Text(c.name).font(.editorial(18)).foregroundStyle(Theme.ink).lineLimit(1)328 Spacer()329 Text(Fmt.int(c.count)).font(.footnote).num().foregroundStyle(Theme.ink3)330 Text(c.medianPrice.map { Fmt.compactMoney($0) } ?? "").font(.subheadline.weight(.semibold)).num().foregroundStyle(Theme.ink)331 .frame(minWidth: 70, alignment: .trailing)332 }333 .padding(.vertical, 12)334 Divider().overlay(Theme.line)335 }336 .contentShape(Rectangle())337 }338 .buttonStyle(.plain)339 }340 }341 }342 }343344 private func load() async {345 error = nil346 if page == nil { page = await APIClient.shared.cityPage(name) }347 do {348 let r = try await APIClient.shared.search(filters, sort: sort, pageSize: 30)349 if Task.isCancelled { return }350 withAnimation(.snappy) {351 total = r.total352 listings = r.listings353 }354 if entry == nil { entry = try? await APIClient.shared.cities().first { Fmt.slug($0.name) == Fmt.slug(name) } }355 } catch is CancellationError {} catch { self.error = error; if listings == nil { listings = nil } }356 }357}358