SPB Git

Repository Public

FiltersSheet.swift 27.6 KB 530 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : Immo-Ka iOS9// File             : ImmoKa/Features/Explore/FiltersSheet.swift10// Description      : feuille de filtres (type de propriété, prix, chambres,11//                    salles de bain, superficie, terrain, année, verdict du12//                    vrai prix, source, quartier) et recherche d'un lieu13//                    (villes, agences).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 SwiftUI9394struct FiltersSheet: View {95    @Bindable var model: ExploreModel96    @Environment(AppModel.self) private var app97    @Environment(\.dismiss) private var dismiss98    @State private var sectors: [FacetValue] = []99    @State private var sources: [Facets.SourceCount] = []100    @State private var minText = ""101    @State private var maxText = ""102    @State private var allSources = false103104    private static let priceCaps = [300_000, 400_000, 500_000, 650_000, 800_000, 1_000_000, 1_500_000]105    private static let areas = [800, 1000, 1200, 1500, 2000, 3000]106    private static let lots = [5_000, 10_000, 20_000, 43_560, 217_800]107    private static let years = [1980, 2000, 2010, 2020]108    private static let taxes = [3000, 5000, 8000]109    private static let fees = [300, 500]110111    var body: some View {112        NavigationStack {113            ScrollView {114                VStack(alignment: .leading, spacing: 26) {115                    group("Type de propriété") {116                        FlowLayout(spacing: 8) {117                            ForEach(PropertyKind.all, id: \.self) { k in118                                Chip(label: k, icon: PropertyKind.icon(k), active: model.filters.propertyType == k) {119                                    model.filters.propertyType = model.filters.propertyType == k ? nil : k120                                }121                            }122                        }123                    }124                    group("Prix demandé") {125                        HStack(spacing: 12) {126                            priceField("Minimum", text: $minText) { model.filters.priceMin = $0 }127                            priceField("Maximum", text: $maxText) { model.filters.priceMax = $0 }128                        }129                        ScrollView(.horizontal, showsIndicators: false) {130                            HStack(spacing: 8) {131                                ForEach(Self.priceCaps, id: \.self) { p in132                                    Chip(label: "≤ \(Fmt.compactMoney(Double(p)))", active: model.filters.priceMax == p) {133                                        model.filters.priceMax = model.filters.priceMax == p ? nil : p134                                        maxText = model.filters.priceMax.map(String.init) ?? ""135                                    }136                                }137                            }138                        }139                        .scrollClipDisabled()140                    }141                    group("Chambres") {142                        stepChips([1, 2, 3, 4, 5], value: model.filters.bedroomsMin) { model.filters.bedroomsMin = $0 }143                    }144                    group("Salles de bain") {145                        stepChips([1, 2, 3], value: model.filters.bathroomsMin) { model.filters.bathroomsMin = $0 }146                    }147                    group("Position du prix demandé", note: "Face au prix de vente attendu d'après les ventes réelles. Les propriétés dont l'estimation est trop incertaine n'ont pas de position.") {148                        FlowLayout(spacing: 8) {149                            ForEach(Verdict.allCases, id: \.self) { v in150                                Chip(label: v.label, icon: VerdictPill.icon(v), active: model.filters.deal == v, tint: Theme.color(for: v)) {151                                    model.filters.deal = model.filters.deal == v ? nil : v152                                }153                            }154                        }155                    }156                    if model.usesV3 {157                        group("Activité") {158                            FlowLayout(spacing: 8) {159                                Chip(label: "Nouvelles depuis 7 jours", icon: "sparkle", active: model.filters.newDays == 7) {160                                    model.filters.newDays = model.filters.newDays == 7 ? nil : 7161                                }162                                Chip(label: "Depuis 30 jours", active: model.filters.newDays == 30) {163                                    model.filters.newDays = model.filters.newDays == 30 ? nil : 30164                                }165                                Chip(label: "Prix en baisse", icon: "arrow.down", active: model.filters.priceDrop == true) {166                                    model.filters.priceDrop = model.filters.priceDrop == true ? nil : true167                                }168                            }169                        }170                        group("Caractéristiques", note: "Seulement les propriétés où la source le déclare. Une caractéristique non déclarée est inconnue, pas absente.") {171                            FlowLayout(spacing: 8) {172                                ForEach(SearchFilters.attributes, id: \.key) { a in173                                    let on = (model.filters.with ?? []).contains(a.key)174                                    Chip(label: a.label, icon: a.icon, active: on) {175                                        var w = model.filters.with ?? []176                                        if on { w.removeAll { $0 == a.key } } else { w.append(a.key) }177                                        model.filters.with = w.isEmpty ? nil : w178                                    }179                                }180                            }181                        }182                        group("Charges annuelles et mensuelles") {183                            FlowLayout(spacing: 8) {184                                ForEach(Self.taxes, id: \.self) { t in185                                    Chip(label: "Taxes ≤ \(Fmt.int(t)) $ par an", active: model.filters.taxMax == t) {186                                        model.filters.taxMax = model.filters.taxMax == t ? nil : t187                                    }188                                }189                                ForEach(Self.fees, id: \.self) { t in190                                    Chip(label: "Copropriété ≤ \(Fmt.int(t)) $ par mois", active: model.filters.condoFeeMax == t) {191                                        model.filters.condoFeeMax = model.filters.condoFeeMax == t ? nil : t192                                    }193                                }194                            }195                        }196                    }197                    group("Superficie habitable minimale") {198                        FlowLayout(spacing: 8) {199                            ForEach(Self.areas, id: \.self) { a in200                                Chip(label: "\(Fmt.int(a)) pi²", active: model.filters.areaMin == a) {201                                    model.filters.areaMin = model.filters.areaMin == a ? nil : a202                                }203                            }204                        }205                    }206                    group("Terrain minimal") {207                        FlowLayout(spacing: 8) {208                            ForEach(Self.lots, id: \.self) { a in209                                Chip(label: a >= 43_560 ? "\(a / 43_560) acre\(a > 43_560 ? "s" : "")" : "\(Fmt.int(a)) pi²", active: model.filters.lotMin == a) {210                                    model.filters.lotMin = model.filters.lotMin == a ? nil : a211                                }212                            }213                        }214                    }215                    group("Année de construction") {216                        FlowLayout(spacing: 8) {217                            ForEach(Self.years, id: \.self) { y in218                                Chip(label: "\(y) et après", active: model.filters.yearMin == y) {219                                    model.filters.yearMin = model.filters.yearMin == y ? nil : y220                                }221                            }222                        }223                    }224                    if let city = model.filters.city, sectors.count > 1 {225                        group("Quartier — \(city)") {226                            FlowLayout(spacing: 8) {227                                ForEach(sectors.prefix(48)) { s in228                                    Chip(label: s.n > 0 ? "\(s.value) · \(s.n)" : s.value, active: model.filters.sector == s.value) {229                                        model.filters.sector = model.filters.sector == s.value ? nil : s.value230                                    }231                                }232                            }233                        }234                    }235                    if !sources.isEmpty {236                        group("Source", note: "Bannière, courtier ou portail qui publie l'inscription.") {237                            FlowLayout(spacing: 8) {238                                ForEach(allSources ? sources : Array(sources.prefix(10))) { s in239                                    Chip(label: s.name ?? app.sourceName(s.value), active: model.filters.source == s.value) {240                                        model.placeTitle = nil241                                        model.filters.source = model.filters.source == s.value ? nil : s.value242                                    }243                                }244                                if !allSources, sources.count > 10 {245                                    Chip(label: "Toutes les sources (\(sources.count))", icon: "plus") {246                                        withAnimation(.snappy) { allSources = true }247                                    }248                                }249                            }250                        }251                    }252                }253                .padding(20)254            }255            .background(Theme.bg)256            .navigationTitle("Filtres")257            .navigationBarTitleDisplayMode(.inline)258            .toolbar {259                ToolbarItem(placement: .topBarLeading) {260                    Button("Tout effacer") {261                        let place = (model.filters.city, model.filters.text, model.filters.nl, model.filters.region)262                        var f = SearchFilters(); f.city = place.0; f.text = place.1; f.nl = place.2; f.region = place.3263                        model.filters = f264                        minText = ""; maxText = ""265                    }266                    .disabled(model.filters.activeCount == 0)267                }268                ToolbarItem(placement: .topBarTrailing) {269                    Button("Fermer") { dismiss() }270                }271            }272            .safeAreaInset(edge: .bottom) {273                Button { dismiss() } label: {274                    Text(model.total.map { "Voir \(Fmt.plural($0, "propriété", "propriétés"))" } ?? "Voir les propriétés")275                        .num().contentTransition(.numericText()).frame(maxWidth: .infinity)276                }277                .buttonStyle(PrimaryButtonStyle())278                .padding(.horizontal, 20).padding(.vertical, 10)279                .background(Theme.bg)280                .overlay(alignment: .top) { Divider().overlay(Theme.line) }281                .animation(.snappy, value: model.total)282                .accessibilityIdentifier("filters.apply")283            }284            .task(id: model.filters.city) {285                minText = model.filters.priceMin.map(String.init) ?? ""286                maxText = model.filters.priceMax.map(String.init) ?? ""287                let f = try? await APIClient.shared.facets(city: model.filters.city)288                sectors = model.filters.city == nil ? [] : (f?.sectors ?? [])289                if sources.isEmpty { sources = f?.sources ?? [] }290            }291        }292        .presentationDetents([.large])293        .presentationDragIndicator(.visible)294    }295296    private func group<C: View>(_ title: String, note: String? = nil, @ViewBuilder _ content: () -> C) -> some View {297        VStack(alignment: .leading, spacing: 12) {298            VStack(alignment: .leading, spacing: 3) {299                Text(title).font(.headline).foregroundStyle(Theme.ink)300                if let note { Text(note).font(.footnote).foregroundStyle(Theme.ink3) }301            }302            content()303        }304    }305306    private func stepChips(_ values: [Int], value: Int?, set: @escaping (Int?) -> Void) -> some View {307        FlowLayout(spacing: 8) {308            ForEach(values, id: \.self) { n in309                Chip(label: "\(n) et plus", active: value == n) { set(value == n ? nil : n) }310            }311        }312    }313314    private func priceField(_ placeholder: String, text: Binding<String>, commit: @escaping (Int?) -> Void) -> some View {315        HStack(spacing: 6) {316            TextField(placeholder, text: text)317                .keyboardType(.numberPad)318                .font(.body.monospacedDigit())319            Text("$").foregroundStyle(Theme.ink3)320        }321        .padding(.horizontal, 14)322        .frame(height: 48)323        .background(Theme.surface, in: RoundedRectangle(cornerRadius: Theme.radiusSmall, style: .continuous))324        .overlay(RoundedRectangle(cornerRadius: Theme.radiusSmall, style: .continuous).strokeBorder(Theme.line2, lineWidth: 1))325        .onChange(of: text.wrappedValue) { _, v in326            let digits = String(v.filter(\.isNumber).prefix(9))327            if digits != v { text.wrappedValue = digits }328            commit(Int(digits))329        }330        .accessibilityLabel("Prix \(placeholder.lowercased())")331    }332}333334/// Recherche d'un lieu : villes (avec leur offre) et agences.335struct PlaceSearchSheet: View {336    @Bindable var model: ExploreModel337    @Environment(AppModel.self) private var app338    @Environment(\.dismiss) private var dismiss339    @State private var query = ""340    @State private var top: [CityEntry] = []341    @State private var names: [String] = []342    @State private var franchises: [AgencyEntry] = []343    @State private var loaded = false344    /// v3 : lieux canoniques suggérés et ce que le service comprend de la phrase345    @State private var places: [PlaceSuggestion] = []346    @State private var understood: [V3Parse.Fragment] = []347348    private var q: String { Fmt.slug(query) }349350    private func pick(_ p: PlaceSuggestion) {351        var f = model.filters352        f.city = nil; f.sector = nil; f.region = nil; f.text = nil; f.nl = nil; f.source = nil; f.agency = nil353        switch p.kind {354        case "region": f.region = p.name355        case "municipalite": f.city = p.name356        default: f.city = p.parent; f.sector = p.name357        }358        model.placeTitle = nil359        model.filters = f360        dismiss()361    }362363    /// Villes correspondantes : celles de l'index d'abord (avec leur nombre de propriétés), puis les autres.364    private var cityHits: [CityEntry] {365        if q.isEmpty { return Array(top.prefix(12)) }366        let known = top.filter { Fmt.slug($0.name).contains(q) }367        let seen = Set(known.map { Fmt.slug($0.name) })368        let others = names.lazy.filter { let s = Fmt.slug($0); return s.contains(q) && !seen.contains(s) }369            .sorted { (Fmt.slug($0).hasPrefix(q) ? 0 : 1, $0.count) < (Fmt.slug($1).hasPrefix(q) ? 0 : 1, $1.count) }370            .prefix(20 - min(20, known.count)).map { CityEntry(name: $0, count: 0, medianPrice: nil) }371        return known + others372    }373374    private var agencyHits: [AgencyEntry] {375        q.isEmpty ? [] : Array(franchises.filter { Fmt.slug($0.name).contains(q) }.prefix(8))376    }377378    var body: some View {379        NavigationStack {380            List {381                let free = query.trimmingCharacters(in: .whitespaces)382                if !free.isEmpty {383                    if model.usesV3, !understood.isEmpty {384                        // phrase libre : le service dit ce qu'il comprend avant qu'on lance la recherche385                        Section("Ce que la recherche comprend") {386                            Button {387                                var f = SearchFilters(); f.nl = free388                                model.placeTitle = nil389                                model.filters = f390                                dismiss()391                            } label: {392                                VStack(alignment: .leading, spacing: 8) {393                                    FlowLayout(spacing: 6) {394                                        ForEach(understood) { u in395                                            Text(u.label)396                                                .font(.footnote.weight(.medium))397                                                .strikethrough(u.ignored)398                                                .foregroundStyle(u.ignored ? Theme.ink3 : Theme.ink)399                                                .padding(.horizontal, 9).padding(.vertical, 5)400                                                .background(Theme.surface2, in: RoundedRectangle(cornerRadius: Theme.radiusTag, style: .continuous))401                                        }402                                    }403                                    Label("Lancer cette recherche", systemImage: "arrow.right").font(.subheadline.weight(.semibold))404                                    if understood.contains(where: \.ignored) {405                                        Text("Les critères barrés ne peuvent pas être filtrés.").font(.caption).foregroundStyle(Theme.ink3)406                                    }407                                }408                            }409                            .accessibilityIdentifier("search.natural")410                        }411                    }412                    Button {413                        var f = model.filters; f.city = nil; f.sector = nil; f.source = nil; f.agency = nil; f.nl = nil; f.text = free414                        model.filters = f415                        dismiss()416                    } label: {417                        Label("Chercher « \(free) » dans les adresses", systemImage: "magnifyingglass")418                    }419                }420                if !places.isEmpty, !q.isEmpty {421                    Section("Lieux") {422                        ForEach(places) { p in423                            Button { pick(p) } label: {424                                HStack(spacing: 12) {425                                    Image(systemName: p.kind == "region" ? "map" : "mappin").foregroundStyle(Theme.brand).frame(width: 22)426                                    VStack(alignment: .leading, spacing: 2) {427                                        Text(p.name).foregroundStyle(Theme.ink)428                                        Text("\(p.kindLabel)\(p.parent.map { " · \($0)" } ?? "") · \(Fmt.plural(p.count, "propriété", "propriétés"))")429                                            .font(.caption).num().foregroundStyle(Theme.ink3)430                                    }431                                }432                            }433                        }434                    }435                }436                if q.isEmpty {437                    // invitation : la maison, porte entrouverte438                    VStack(spacing: 10) {439                        BrandIllustration(kind: .ajar, size: 60)440                        Text("Où voulez-vous habiter ?").font(.editorial(20)).foregroundStyle(Theme.ink)441                        Text("Tapez une ville, une adresse, un numéro d'inscription ou le nom d'une agence.")442                            .font(.footnote).foregroundStyle(Theme.ink3).multilineTextAlignment(.center)443                    }444                    .frame(maxWidth: .infinity)445                    .padding(.vertical, 14)446                    .listRowBackground(Color.clear)447                    .listRowSeparator(.hidden)448                } else if cityHits.isEmpty, agencyHits.isEmpty, places.isEmpty, understood.isEmpty, loaded {449                    EmptyStateView(door: .closed, title: "Aucune ville ni agence à ce nom",450                                   message: "La recherche libre ci-dessus cherche aussi dans les titres, les adresses et les numéros d'inscription.")451                        .listRowBackground(Color.clear)452                        .listRowSeparator(.hidden)453                }454                if !cityHits.isEmpty, places.isEmpty || q.isEmpty {455                    Section(q.isEmpty ? "Villes les plus actives" : "Villes") {456                        ForEach(cityHits) { v in457                            Button {458                                var f = model.filters; f.city = v.name; f.sector = nil; f.text = nil; f.nl = nil; f.region = nil; f.source = nil; f.agency = nil459                                model.filters = f460                                dismiss()461                            } label: {462                                HStack(spacing: 12) {463                                    Image(systemName: "mappin").foregroundStyle(Theme.brand).frame(width: 22)464                                    VStack(alignment: .leading, spacing: 2) {465                                        Text(v.name).foregroundStyle(Theme.ink)466                                        if v.count > 0 {467                                            Text("\(Fmt.plural(v.count, "propriété", "propriétés"))\(v.medianPrice.map { " · médiane \(Fmt.compactMoney($0))" } ?? "")")468                                                .font(.caption).num().foregroundStyle(Theme.ink3)469                                        }470                                    }471                                }472                            }473                        }474                    }475                }476                if !agencyHits.isEmpty {477                    Section("Bannières et agences") {478                        ForEach(agencyHits) { m in479                            Button {480                                dismiss()481                                app.open(.agency(m.name))482                            } label: {483                                HStack(spacing: 12) {484                                    Image(systemName: "person.2").foregroundStyle(Theme.ink2).frame(width: 22)485                                    VStack(alignment: .leading, spacing: 2) {486                                        Text(m.name).foregroundStyle(Theme.ink)487                                        Text(Fmt.plural(m.activeListings, "propriété à vendre", "propriétés à vendre"))488                                            .font(.caption).num().foregroundStyle(Theme.ink3)489                                    }490                                }491                            }492                        }493                    }494                }495            }496            .scrollContentBackground(.hidden)497            .background(Theme.bg)498            .searchable(text: $query, placement: .navigationBarDrawer(displayMode: .always), prompt: model.usesV3 ? "Ville, quartier, ou « maison 3 chambres à Gatineau »" : "Ville, adresse, agence")499            .task(id: query) {500                // suggestions et interprétation du service, après une courte pause de frappe501                let text = query.trimmingCharacters(in: .whitespaces)502                guard model.usesV3, text.count >= 2 else { places = []; understood = []; return }503                try? await Task.sleep(for: .milliseconds(260))504                if Task.isCancelled { return }505                async let s = try? APIClient.shared.suggestPlaces(text)506                async let p = try? APIClient.shared.parse(text)507                let (sv, pv) = await (s, p)508                if Task.isCancelled { return }509                places = sv ?? []510                // une phrase qui n'est qu'un nom de lieu n'a pas besoin d'être « comprise »511                let frags = pv?.interpreted ?? []512                understood = frags.count >= 2 || frags.contains { $0.kind != "lieu" && $0.kind != "ville" } ? frags : []513            }514            .navigationTitle("Chercher un lieu")515            .navigationBarTitleDisplayMode(.inline)516            .toolbar { ToolbarItem(placement: .topBarTrailing) { Button("Fermer") { dismiss() } } }517            .task {518                async let c = try? APIClient.shared.cities()519                async let f = try? APIClient.shared.facets()520                async let a = try? APIClient.shared.agencyDirectory()521                top = (await c) ?? []522                names = (await f)?.cityNames ?? []523                franchises = ((await a)?.all ?? []).filter { $0.activeListings > 0 }524                loaded = true525            }526        }527        .presentationDetents([.large])528    }529}530
Files main
Menu

Theme