SPB Git

Repository Public

ExploreModel.swift 16.5 KB 429 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/ExploreModel.swift10// Description      : état de la recherche — filtres, points de carte,11//                    regroupement, liste de la zone visible.12// Module           : ImmoKa13// Repository       : https://git.spboucher.ai/immo-ka-ios-v314// Project Website  : https://www.immo-ka.com15// Created          : 2026-11-2516// Last Modified    : 2026-11-2817//18// =============================================================================19// AUTHOR & PROFESSIONAL AFFILIATION20// =============================================================================21//22// Author           : Simon-Pierre Boucher23// Position         : Professor of Finance24// Institution      : Université du Québec en Outaouais (UQO)25// Department       : Département des sciences administratives26// Organization     : SP Boucher27//28// Website          : https://spboucher.ai29// Git              : https://git.spboucher.ai30//31// =============================================================================32// OFFICIAL CONTACT DIRECTORY33// =============================================================================34//35// General          : info@spboucher.ai36// Professional     : contact@spboucher.ai37// Direct           : simon@spboucher.ai38// Research         : research@spboucher.ai39// Development      : dev@spboucher.ai40// Support          : support@spboucher.ai41// Security/Admin   : admin@spboucher.ai42// Notifications    : notifications@spboucher.ai43//44// Preferred Contact: support@spboucher.ai45//46// =============================================================================47// COPYRIGHT & INTELLECTUAL PROPERTY48// =============================================================================49//50// Copyright (c) 202651// Simon-Pierre Boucher52//53// All rights reserved where applicable.54//55// This file is governed by the applicable project license,56// copyright notices, institutional agreements and relevant law.57//58// Unless expressly authorized by the applicable license or59// rights holder, copying, redistribution, sublicensing,60// publication and commercial exploitation are not permitted.61//62// Existing third-party rights and notices remain unaffected.63//64// =============================================================================65// CONFIDENTIALITY & SECURITY66// =============================================================================67//68// Classification   : Public69// Distribution     : Public repository; use is governed by the project license70// Security Contact : admin@spboucher.ai71//72// Access to this source does not independently grant permission73// to redistribute or disclose confidential materials.74//75// Do not embed credentials, private keys, access tokens,76// certificates or confidential personal information.77//78// =============================================================================79// LICENSE & MAINTENANCE80// =============================================================================81//82// License          : None specified (no license file in this repository)83// Maintainer       : Simon-Pierre Boucher84// Technical Contact: dev@spboucher.ai85//86// =============================================================================87// END OF SP BOUCHER SOURCE HEADER88// =============================================================================8990import CoreLocation91import Foundation92import Observation9394@MainActor95@Observable96final class ExploreModel {97    var filters = SearchFilters() { didSet { if filters != oldValue { filtersChanged() } } }98    /// nom de la bannière ou de l'agence dont on liste les propriétés (affiché à la place de la liste de sources)99    var placeTitle: String?100    var sort: SearchSort = .recent { didSet { if sort != oldValue { reloadList() } } }101102    // carte103    private(set) var points: [MapPoint] = []104    private(set) var total: Int?105    private(set) var unpositioned = 0106    private(set) var items: [MapItem] = []107    private(set) var loadingPoints = false108    private(set) var pointsError: Error?109    var command: MapCommand?110    var selectedUID: String? { didSet { if selectedUID != oldValue { loadSelected(); recluster() } } }111    private(set) var selected: Listing?112113    // liste (zone visible)114    private(set) var listings: [Listing] = []115    private(set) var inView: Int?116    private(set) var loadingList = false117    private(set) var listError: Error?118    private var page = 1119    private var hasMore = false120    /// v3 : curseur opaque de la page suivante, et ce que le service a compris de la recherche121    private var cursor: String?122    private(set) var interpreted: [V3Parse.Fragment] = []123    private(set) var notes: [String] = []124    /// v3 : la carte est servie par emprise (points sous 4 000 inscriptions, regroupements du serveur au-delà)125    private(set) var usesV3 = false126    private var serverClusters: [ServerCluster] = []127    private var mapTask: Task<Void, Never>?128    private var parseTask: Task<Void, Never>?129130    private var bounds: MapBounds?131    private var mapSize = CGSize(width: 390, height: 700)132    private var pointsTask: Task<Void, Never>?133    private var listTask: Task<Void, Never>?134    private var clusterTask: Task<Void, Never>?135    private var selectedTask: Task<Void, Never>?136    private var started = false137138    func start() {139        guard !started else { return }140        started = true141        usesV3 = ServiceGeneration.current >= 3142        loadPoints(fit: filters.hasPlace)143        // propriété présélectionnée par argument de lancement (tests, captures) : carte centrée, aperçu ouvert144        if let uid = UserDefaults.standard.string(forKey: "IKSelect") {145            Task {146                guard let l = try? await APIClient.shared.fullListing(uid), let c = l.coordinate else { return }147                command = MapCommand(kind: .center(lat: c.latitude, lng: c.longitude, spanDegrees: 0.012))148                try? await Task.sleep(for: .seconds(1.5))149                selectedUID = uid150            }151        }152    }153154    /// Applique une recherche venue d'ailleurs (accueil, ville, recherche enregistrée).155    func apply(_ filters: SearchFilters, sort: SearchSort, title: String? = nil) {156        started = true157        placeTitle = title158        selectedUID = nil159        self.sort = sort160        if self.filters == filters { loadPoints(fit: filters.hasPlace) } else { self.filters = filters }161    }162163    private func filtersChanged() {164        selectedUID = nil165        loadPoints(fit: filters.hasPlace)166    }167168    func retry() {169        loadPoints(fit: false)170        reloadList()171    }172173    // MARK: Points174175    private func loadPoints(fit: Bool) {176        pointsTask?.cancel()177        loadingPoints = true178        pointsError = nil179        let f = filters180        loadInterpretation(f)181        pointsTask = Task {182            usesV3 = await APIClient.shared.isV3()183            if usesV3 {184                // v3 : un appel sans emprise donne le total et, pour une recherche de lieu, la zone à cadrer ;185                // les marqueurs viennent ensuite par emprise (`fetchMap`)186                do {187                    let r = try await APIClient.shared.mapV3(f, bbox: nil, zoom: 8)188                    if Task.isCancelled { return }189                    total = r.total190                    unpositioned = 0191                    loadingPoints = false192                    if fit, let b = Clusterer.robustBounds(points: r.points, clusters: r.clusters) { command = MapCommand(kind: .fit(b)) }193                    refreshMap(debounce: false)194                    reloadList()195                } catch is CancellationError {196                } catch {197                    if Task.isCancelled { return }198                    loadingPoints = false199                    pointsError = error200                }201                return202            }203            do {204                let r = try await APIClient.shared.mapPoints(f)205                if Task.isCancelled { return }206                points = r.points207                total = r.total208                unpositioned = r.unpositioned209                loadingPoints = false210                if fit, let b = Clusterer.robustBounds(points) { command = MapCommand(kind: .fit(b)) }211                recluster()212                reloadList()213            } catch is CancellationError {214            } catch {215                if Task.isCancelled { return }216                loadingPoints = false217                pointsError = error218            }219        }220    }221222    // MARK: Zone visible223224    func regionChanged(_ b: MapBounds, size: CGSize) {225        let first = bounds == nil226        guard first || bounds != b else { return }227        bounds = b228        mapSize = size229        if usesV3 { refreshMap(debounce: !first) } else { recluster() }230        listTask?.cancel()231        listTask = Task {232            // la liste suit la carte une fois le geste terminé233            try? await Task.sleep(for: .milliseconds(first ? 0 : 320))234            if Task.isCancelled { return }235            await fetchList(reset: true)236        }237    }238239    /// Niveau de zoom de la carte (tuiles de 256 points) déduit de l'emprise et de la largeur de la vue.240    static func zoom(for b: MapBounds, width: CGFloat) -> Double {241        let span = max(b.east - b.west, 1e-6)242        return min(20, max(2, log2(360 * Double(max(width, 100)) / (256 * span))))243    }244245    /// v3 : marqueurs de l'emprise visible. Le service rend des points ou des regroupements selon la densité.246    private func refreshMap(debounce: Bool) {247        guard usesV3, let b = bounds else { return }248        mapTask?.cancel()249        let f = filters250        let size = mapSize251        mapTask = Task {252            if debounce { try? await Task.sleep(for: .milliseconds(180)) }253            if Task.isCancelled { return }254            do {255                let r = try await APIClient.shared.mapV3(f, bbox: b.padded(0.12).bbox, zoom: ExploreModel.zoom(for: b, width: size.width))256                if Task.isCancelled { return }257                points = r.isClustered ? [] : r.points258                serverClusters = r.isClustered ? r.clusters : []259                pointsError = nil260                recluster()261            } catch is CancellationError {262            } catch {263                if Task.isCancelled { return }264                // les marqueurs déjà affichés restent ; l'erreur n'est montrée que si la carte est vide265                if items.isEmpty { pointsError = error }266            }267        }268    }269270    /// v3 : ce que le service comprend de la phrase libre, affiché sous la barre de recherche.271    private func loadInterpretation(_ f: SearchFilters) {272        parseTask?.cancel()273        guard let nl = f.nl, !nl.isEmpty else { interpreted = []; return }274        parseTask = Task {275            guard let p = try? await APIClient.shared.parse(nl), !Task.isCancelled else { return }276            interpreted = p.interpreted277        }278    }279280    private func recluster() {281        guard let b = bounds else { return }282        clusterTask?.cancel()283        if usesV3, !serverClusters.isEmpty {284            let cl = serverClusters285            let cols = max(4, Int(mapSize.width / 74))286            let aspect = Double(mapSize.height / max(mapSize.width, 1))287            clusterTask = Task {288                let out = await Task.detached(priority: .userInitiated) {289                    Clusterer.merge(cl, in: b, columns: cols, aspect: aspect)290                }.value291                if Task.isCancelled { return }292                items = out293            }294            return295        }296        let pts = points297        let cols = max(4, Int(mapSize.width / 74))298        let aspect = Double(mapSize.height / max(mapSize.width, 1))299        let pinned = selectedUID300        clusterTask = Task {301            let out = await Task.detached(priority: .userInitiated) {302                Clusterer.cluster(pts, in: b, columns: cols, aspect: aspect, pinned: pinned)303            }.value304            if Task.isCancelled { return }305            items = out306        }307    }308309    // MARK: Liste310311    private func reloadList() {312        listTask?.cancel()313        listTask = Task { await fetchList(reset: true) }314    }315316    func loadMoreIfNeeded(_ l: Listing) {317        guard hasMore, !loadingList, l.uid == listings.last?.uid else { return }318        listTask = Task { await fetchList(reset: false) }319    }320321    private func fetchList(reset: Bool) async {322        guard let b = bounds else { return }323        loadingList = true324        listError = nil325        let next = reset ? 1 : page + 1326        if usesV3 {327            do {328                let r = try await APIClient.shared.searchV3(filters, sort: sort, bbox: b.bbox, cursor: reset ? nil : cursor)329                if Task.isCancelled { return }330                listings = reset ? r.items : listings + r.items.filter { n in !listings.contains { $0.uid == n.uid } }331                inView = r.total332                cursor = r.nextCursor333                hasMore = r.nextCursor != nil && !r.items.isEmpty334                notes = r.notes335                loadingList = false336            } catch is CancellationError {337            } catch {338                if Task.isCancelled { return }339                loadingList = false340                listError = error341                if reset { listings = []; inView = nil }342            }343            return344        }345        do {346            let r = try await APIClient.shared.search(filters, sort: sort, bbox: b.bbox, page: next, pageSize: 24)347            if Task.isCancelled { return }348            page = r.page349            listings = reset ? r.listings : listings + r.listings.filter { n in !listings.contains { $0.uid == n.uid } }350            inView = r.total351            hasMore = r.page * r.pageSize < r.total352            loadingList = false353        } catch is CancellationError {354        } catch {355            if Task.isCancelled { return }356            loadingList = false357            listError = error358            if reset { listings = []; inView = nil }359        }360    }361362    // MARK: Sélection363364    private func loadSelected() {365        selectedTask?.cancel()366        guard let uid = selectedUID else { selected = nil; return }367        if let known = listings.first(where: { $0.uid == uid }) { selected = known } else { selected = nil }368        selectedTask = Task {369            if let l = try? await APIClient.shared.fullListing(uid), !Task.isCancelled, selectedUID == uid { selected = l }370        }371    }372373    func center(on coordinate: CLLocationCoordinate2D) {374        command = MapCommand(kind: .center(lat: coordinate.latitude, lng: coordinate.longitude, spanDegrees: 0.035))375    }376}377378/// Position de l'utilisateur, demandée seulement au moment de l'usage.379@MainActor380@Observable381final class LocationProvider: NSObject, CLLocationManagerDelegate {382    private let manager = CLLocationManager()383    private(set) var authorized = false384    private(set) var denied = false385    private var pending: ((CLLocationCoordinate2D) -> Void)?386387    override init() {388        super.init()389        manager.delegate = self390        manager.desiredAccuracy = kCLLocationAccuracyHundredMeters391        refresh()392    }393394    private func refresh() {395        let s = manager.authorizationStatus396        authorized = s == .authorizedWhenInUse || s == .authorizedAlways397        denied = s == .denied || s == .restricted398    }399400    /// Demande la position (et l'autorisation si nécessaire), puis appelle `then` une fois.401    func locate(_ then: @escaping (CLLocationCoordinate2D) -> Void) {402        pending = then403        switch manager.authorizationStatus {404        case .notDetermined: manager.requestWhenInUseAuthorization()405        case .authorizedWhenInUse, .authorizedAlways: manager.requestLocation()406        default: denied = true; pending = nil407        }408    }409410    nonisolated func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) {411        Task { @MainActor in412            self.refresh()413            if self.authorized, self.pending != nil { self.manager.requestLocation() }414        }415    }416417    nonisolated func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {418        guard let c = locations.last?.coordinate else { return }419        Task { @MainActor in420            self.pending?(c)421            self.pending = nil422        }423    }424425    nonisolated func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {426        Task { @MainActor in self.pending = nil }427    }428}429
Files main
Menu

Theme