Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : Lou-Ka iOS9// File : LouKa/Features/Explore/FiltersSheet.swift10// Description : filtres de la recherche v3 (grandeurs, genres, budget avec11// distribution réelle, attributs à trois états avec leurs12// compteurs) et recherche d'un lieu ou d'une phrase libre.13// Module : LouKa14// Repository : https://git.spboucher.ai/lou-ka-ios-v315// Project Website : https://www.lou-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 Charts92import SwiftUI9394struct FiltersSheet: View {95 @Bindable var model: ExploreModel96 @Environment(\.dismiss) private var dismiss97 @State private var minText = ""98 @State private var maxText = ""99100 private static let kinds: [(String, String)] = [("appartement", "Appartement"), ("condo", "Condo"), ("loft", "Loft"),101 ("maison", "Maison"), ("studio", "Studio"), ("chambre", "Chambre")]102103 var body: some View {104 NavigationStack {105 ScrollView {106 VStack(alignment: .leading, spacing: 26) {107 group("Grandeur") {108 FlowLayout(spacing: 8) {109 ForEach(Rooms.all, id: \.self) { r in110 Chip(label: Rooms.label(r), count: model.facets?.rooms[r], active: model.filters.effectiveRooms.contains(r)) {111 model.filters.toggle(rooms: r)112 }113 .accessibilityIdentifier("filters.rooms.\(r)")114 }115 }116 }117 group("Genre de logement") {118 FlowLayout(spacing: 8) {119 ForEach(Self.kinds, id: \.0) { key, label in120 Chip(label: label, active: model.filters.effectiveKinds.contains(key)) { model.filters.toggle(kind: key) }121 }122 }123 }124 group("Loyer mensuel") {125 if let f = model.facets, f.histogram.count > 3 { priceHistogram(f) }126 HStack(spacing: 12) {127 priceField("Minimum", text: $minText) { model.filters.priceMin = $0 }128 priceField("Maximum", text: $maxText) { model.filters.priceMax = $0 }129 }130 ScrollView(.horizontal, showsIndicators: false) {131 HStack(spacing: 8) {132 ForEach([1000, 1200, 1500, 1800, 2200, 3000], id: \.self) { p in133 Chip(label: "≤ \(Fmt.int(p)) $", active: model.filters.priceMax == p) {134 model.filters.priceMax = model.filters.priceMax == p ? nil : p135 maxText = model.filters.priceMax.map(String.init) ?? ""136 }137 }138 }139 }140 .scrollClipDisabled()141 }142 group("Loyer par rapport à l'estimation", note: "Position du loyer affiché dans la fourchette estimée. Environ un logement sur trois n'a pas de verdict : l'incertitude y est trop grande.") {143 FlowLayout(spacing: 8) {144 ForEach(Verdict.allCases, id: \.self) { v in145 Chip(label: v.label, active: model.filters.deal == v, tint: Theme.color(for: v)) {146 model.filters.deal = model.filters.deal == v ? nil : v147 }148 }149 }150 }151 group("Disponibilité") {152 FlowLayout(spacing: 8) {153 ForEach([(0, "Maintenant"), (30, "D'ici 30 jours"), (60, "D'ici 60 jours")], id: \.0) { d, label in154 Chip(label: label, count: d == 0 ? model.facets?.availableNow?.yes : nil, active: model.filters.availableWithinDays == d) {155 model.filters.availableWithinDays = model.filters.availableWithinDays == d ? nil : d156 }157 }158 }159 }160 group("Chambres et salles de bain") {161 stepper("Chambres, au moins", value: Binding(get: { model.filters.bedroomsMin ?? 0 }, set: { model.filters.bedroomsMin = $0 == 0 ? nil : $0 }), range: 0...5)162 stepper("Salles de bain, au moins", value: Binding(get: { model.filters.bathroomsMin ?? 0 }, set: { model.filters.bathroomsMin = $0 == 0 ? nil : $0 }), range: 0...3)163 }164 group("Inclus dans le loyer", note: Self.threeStateNote) { features(Feature.included) }165 group("Le logement") { features(Feature.unit) }166 group("L'immeuble") { features(Feature.building) }167 group("Mode de vie") {168 FlowLayout(spacing: 8) {169 Chip(label: "Animaux acceptés", icon: "pawprint", count: model.facets?.pets?.yes, active: model.filters.pets) { model.filters.pets.toggle() }170 Chip(label: "Meublé", icon: "sofa", count: model.facets?.furnished?.yes, active: model.filters.furnished == true) {171 model.filters.furnished = model.filters.furnished == true ? nil : true172 }173 }174 }175 group("Annonces") {176 FlowLayout(spacing: 8) {177 Chip(label: "Baisse de prix", icon: "arrow.down", count: model.facets?.priceDrop, active: model.filters.priceDrop == true) {178 model.filters.priceDrop = model.filters.priceDrop == true ? nil : true179 }180 ForEach([(1, "Vues depuis 24 h"), (3, "Depuis 3 jours"), (7, "Depuis 7 jours")], id: \.0) { d, label in181 Chip(label: label, active: model.filters.newDays == d) { model.filters.newDays = model.filters.newDays == d ? nil : d }182 }183 }184 }185 group("Score de quartier minimal") {186 FlowLayout(spacing: 8) {187 ForEach([60, 70, 80], id: \.self) { s in188 Chip(label: "\(s) et plus", active: model.filters.scoreMin == s) {189 model.filters.scoreMin = model.filters.scoreMin == s ? nil : s190 }191 }192 }193 }194 group("Superficie minimale") {195 FlowLayout(spacing: 8) {196 ForEach([500, 700, 900, 1200], id: \.self) { a in197 Chip(label: "\(Fmt.int(a)) pi²", active: model.filters.areaMin == a) {198 model.filters.areaMin = model.filters.areaMin == a ? nil : a199 }200 }201 }202 }203 group("Année de construction") {204 FlowLayout(spacing: 8) {205 ForEach([2000, 2010, 2020], id: \.self) { y in206 Chip(label: "Après \(y)", active: model.filters.builtAfter == y) {207 model.filters.builtAfter = model.filters.builtAfter == y ? nil : y208 }209 }210 }211 }212 }213 .padding(20)214 }215 .background(Theme.bg)216 .navigationTitle("Filtres")217 .navigationBarTitleDisplayMode(.inline)218 .toolbar {219 ToolbarItem(placement: .topBarLeading) {220 Button("Tout effacer") {221 model.filters = model.filters.placeOnly222 minText = ""; maxText = ""223 }224 .disabled(model.filters.activeCount == 0)225 }226 ToolbarItem(placement: .topBarTrailing) {227 Button("Fermer") { dismiss() }228 }229 }230 .safeAreaInset(edge: .bottom) {231 Button { dismiss() } label: {232 Text(model.facets.map { "Voir \(Fmt.plural($0.total, "logement", "logements"))" } ?? "Voir les logements")233 .num().frame(maxWidth: .infinity)234 }235 .buttonStyle(PrimaryButtonStyle())236 .padding(.horizontal, 20).padding(.vertical, 10)237 .background(Theme.bg)238 .overlay(alignment: .top) { Rectangle().fill(Theme.line).frame(height: 1) }239 .accessibilityIdentifier("filters.apply")240 }241 .task {242 minText = model.filters.priceMin.map(String.init) ?? ""243 maxText = model.filters.priceMax.map(String.init) ?? ""244 }245 }246 .presentationDetents([.large])247 .presentationDragIndicator(.visible)248 }249250 private static let threeStateNote = "Le compteur indique les annonces qui le mentionnent. Une annonce qui n'en dit rien n'est pas un « non » : exiger un attribut écarte aussi les annonces muettes."251252 private func features(_ list: [Feature]) -> some View {253 FlowLayout(spacing: 8) {254 ForEach(list) { f in255 Chip(label: f.label, icon: f.icon, count: model.facets?.features[f.rawValue]?.yes, active: model.filters.has(f)) { model.filters.toggle(f) }256 }257 }258 }259260 /// Distribution réelle des loyers des résultats courants (compteurs du serveur), avec la médiane.261 private func priceHistogram(_ f: SearchFacets) -> some View {262 let lo = Double(model.filters.priceMin ?? 0), hi = Double(model.filters.priceMax ?? .max)263 let bins = f.histogram.filter { $0.from <= (f.p90 ?? 4000) * 1.6 }264 return VStack(alignment: .leading, spacing: 4) {265 Chart(bins) { b in266 RectangleMark(xStart: .value("De", b.from + f.step * 0.08), xEnd: .value("À", b.from + f.step * 0.92),267 yStart: .value("Base", 0), yEnd: .value("Annonces", b.n))268 .foregroundStyle(b.from >= lo && b.from < hi ? Theme.brand : Theme.surface3)269 }270 .chartXAxis {271 AxisMarks(values: .automatic(desiredCount: 5)) { v in272 AxisValueLabel { if let d = v.as(Double.self) { Text(Fmt.money(d)).font(.caption2).monospacedDigit() } }273 }274 }275 .chartYAxis(.hidden)276 .frame(height: 84)277 .accessibilityLabel("Distribution des loyers affichés")278 if let m = f.p50 {279 Text("Médiane \(Fmt.money(m)) · 8 loyers sur 10 entre \(Fmt.money(f.p10)) et \(Fmt.money(f.p90))")280 .font(.caption).num().foregroundStyle(Theme.ink3)281 }282 }283 }284285 private func group<C: View>(_ title: String, note: String? = nil, @ViewBuilder _ content: () -> C) -> some View {286 VStack(alignment: .leading, spacing: 12) {287 Text(title).font(.headline).foregroundStyle(Theme.ink)288 content()289 if let note { Text(note).font(.caption).foregroundStyle(Theme.ink3).fixedSize(horizontal: false, vertical: true) }290 }291 }292293 private func stepper(_ label: String, value: Binding<Int>, range: ClosedRange<Int>) -> some View {294 Stepper(value: value, in: range) {295 HStack {296 Text(label).font(.subheadline).foregroundStyle(Theme.ink)297 Spacer()298 Text(value.wrappedValue == 0 ? "Indifférent" : "\(value.wrappedValue)").font(.subheadline.weight(.semibold)).num()299 .foregroundStyle(value.wrappedValue == 0 ? Theme.ink3 : Theme.ink)300 }301 }302 }303304 private func priceField(_ placeholder: String, text: Binding<String>, commit: @escaping (Int?) -> Void) -> some View {305 TextField(placeholder, text: text)306 .keyboardType(.numberPad)307 .font(.body.monospacedDigit())308 .padding(.horizontal, 14)309 .frame(height: 48)310 .background(Theme.surface, in: RoundedRectangle(cornerRadius: Theme.radiusSmall, style: .continuous))311 .overlay(RoundedRectangle(cornerRadius: Theme.radiusSmall, style: .continuous).strokeBorder(Theme.lineControl, lineWidth: 1))312 .onChange(of: text.wrappedValue) { _, v in313 let digits = v.filter(\.isNumber)314 if digits != v { text.wrappedValue = digits }315 commit(Int(digits))316 }317 .accessibilityLabel("Loyer \(placeholder.lowercased())")318 }319}320321/// Recherche : une phrase libre (interprétée par le serveur), un lieu canonique ou un gestionnaire.322struct PlaceSearchSheet: View {323 @Bindable var model: ExploreModel324 var location: LocationProvider?325 @Environment(AppModel.self) private var app326 @Environment(\.dismiss) private var dismiss327 @State private var query = ""328 @State private var places: [Place] = []329 @State private var top: [Place] = []330 @State private var managers: [ManagerEntry] = []331 @State private var preview: ParsedPhrase?332 @State private var suggestTask: Task<Void, Never>?333334 private static let examples = ["4½ à Rosemont sous 1 800 $ avec balcon", "Studio meublé à Québec, animaux acceptés",335 "5½ à Gatineau avec stationnement, disponible maintenant"]336337 private var trimmed: String { query.trimmingCharacters(in: .whitespacesAndNewlines) }338 private var managerHits: [ManagerEntry] {339 let q = Fmt.slug(trimmed)340 return q.count < 2 ? [] : Array(managers.filter { Fmt.slug($0.name).contains(q) }.prefix(6))341 }342343 var body: some View {344 NavigationStack {345 List {346 if !trimmed.isEmpty {347 Section {348 Button { submit(trimmed) } label: {349 VStack(alignment: .leading, spacing: 6) {350 Label("Chercher « \(trimmed) »", systemImage: "magnifyingglass").foregroundStyle(Theme.ink)351 if let p = preview, !p.interpreted.isEmpty {352 FlowLayout(spacing: 6) {353 ForEach(p.interpreted) { c in354 Text(c.label).font(.caption.weight(.medium)).foregroundStyle(Theme.brandStrong)355 .padding(.horizontal, 8).padding(.vertical, 4)356 .background(Theme.brandSoft, in: RoundedRectangle(cornerRadius: Theme.radiusTag, style: .continuous))357 }358 if !p.rest.isEmpty {359 Text("mots : \(p.rest)").font(.caption).foregroundStyle(Theme.ink3).padding(.vertical, 4)360 }361 }362 .accessibilityElement(children: .combine)363 .accessibilityLabel("Compris : " + p.interpreted.map(\.label).joined(separator: ", "))364 }365 }366 }367 .accessibilityIdentifier("search.submit")368 } footer: {369 Text("La phrase est interprétée par le serveur de Lou-Ka, sans service externe.")370 }371 }372 if trimmed.isEmpty {373 VStack(spacing: 10) {374 DoorIllustration(kind: .ajar, size: 56)375 Text("Où voulez-vous habiter ?").font(.editorial(20)).foregroundStyle(Theme.ink)376 Text("Écrivez une ville, un quartier, ou décrivez le logement en une phrase.")377 .font(.footnote).foregroundStyle(Theme.ink3).multilineTextAlignment(.center)378 }379 .frame(maxWidth: .infinity)380 .padding(.vertical, 14)381 .listRowBackground(Color.clear)382 .listRowSeparator(.hidden)383 Section("Exemples") {384 ForEach(Self.examples, id: \.self) { e in385 Button { query = e } label: { Label(e, systemImage: "text.cursor").foregroundStyle(Theme.ink) }386 }387 }388 if let location {389 Section {390 Button {391 location.locate { c in model.searchNear(c) }392 if location.denied { app.showToast("Autorisez la localisation dans Réglages pour chercher autour de vous") }393 dismiss()394 } label: {395 Label("Autour de moi, dans un rayon de 2 km", systemImage: "location").foregroundStyle(Theme.ink)396 }397 } footer: {398 Text("Votre position n'est demandée que si vous touchez ce bouton. Un point arrondi à une centaine de mètres est envoyé au serveur pour cette recherche, sans identifiant.")399 }400 }401 }402 let rows = trimmed.isEmpty ? top : places403 if !rows.isEmpty {404 Section(trimmed.isEmpty ? "Villes les plus actives" : "Lieux") {405 ForEach(rows) { p in406 Button {407 model.clearPhrase()408 model.filters = p.filters409 dismiss()410 } label: {411 HStack {412 Image(systemName: p.kind == "municipalite" || p.kind == "region" ? "mappin.circle" : "mappin").foregroundStyle(Theme.brand)413 VStack(alignment: .leading, spacing: 2) {414 Text(p.name).foregroundStyle(Theme.ink)415 Text([p.kindLabel, p.kind == "municipalite" || p.kind == "region" ? nil : p.parent,416 p.listings.map { Fmt.plural($0, "logement", "logements") }].compactMap { $0 }.joined(separator: " · "))417 .font(.caption).num().foregroundStyle(Theme.ink3)418 }419 }420 }421 }422 }423 }424 if !managerHits.isEmpty {425 Section("Gestionnaires") {426 ForEach(managerHits) { m in427 Button {428 dismiss()429 app.open(.manager(m.id))430 } label: {431 HStack {432 Image(systemName: "building.2").foregroundStyle(Theme.ink2)433 VStack(alignment: .leading, spacing: 2) {434 Text(m.name).foregroundStyle(Theme.ink)435 Text(m.activeListings > 0 ? Fmt.plural(m.activeListings, "logement à louer", "logements à louer") : m.region)436 .font(.caption).num().foregroundStyle(Theme.ink3)437 }438 }439 }440 }441 }442 }443 }444 .scrollContentBackground(.hidden)445 .background(Theme.bg)446 .searchable(text: $query, placement: .navigationBarDrawer(displayMode: .always), prompt: "Ville, quartier ou phrase")447 .onSubmit(of: .search) { if !trimmed.isEmpty { submit(trimmed) } }448 .navigationTitle("Chercher")449 .navigationBarTitleDisplayMode(.inline)450 .toolbar { ToolbarItem(placement: .topBarTrailing) { Button("Fermer") { dismiss() } } }451 .onChange(of: query) { _, _ in suggest() }452 .task {453 async let t = try? APIClient.shared.places(minListings: 150)454 async let m = try? APIClient.shared.managers()455 top = Array(((await t) ?? []).sorted { ($0.listings ?? 0) > ($1.listings ?? 0) }.prefix(12))456 managers = (await m)?.managers ?? []457 #if DEBUG458 if let q = UserDefaults.standard.string(forKey: "LKQuery") { query = q }459 #endif460 }461 }462 .presentationDetents([.large])463 }464465 /// Suggestions de lieux et aperçu de l'interprétation, après une courte pause de frappe.466 private func suggest() {467 suggestTask?.cancel()468 let q = trimmed469 guard q.count >= 2 else { places = []; preview = nil; return }470 suggestTask = Task {471 try? await Task.sleep(for: .milliseconds(220))472 if Task.isCancelled { return }473 async let s = try? APIClient.shared.suggestPlaces(q)474 async let p = try? APIClient.shared.parse(phrase: q)475 let (sv, pv) = (await s, await p)476 if Task.isCancelled { return }477 places = sv ?? []478 preview = pv479 }480 }481482 private func submit(_ text: String) {483 Task { await model.search(phrase: text) }484 dismiss()485 }486}487