SPB Git

Repository Public

Library.swift 19.1 KB 485 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : Lou-Ka iOS9// File             : LouKa/Core/Store/Library.swift10// Description      : mémoire locale (SwiftData) — favoris, logements vus,11//                    comparateur, recherches enregistrées. Sans compte, rien ne12//                    quitte l'appareil. Avec un compte (facultatif), favoris,13//                    notes et recherches sont synchronisés par `SyncEngine`,14//                    qui écoute `Library.onChange`.15// Module           : LouKa16// Repository       : https://git.spboucher.ai/lou-ka-ios-v317// Project Website  : https://www.lou-ka.com18// Created          : 2026-11-2519// Last Modified    : 2026-11-3020//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 Foundation94import Observation95import SwiftData9697@Model98final class FavoriteItem {99    @Attribute(.unique) var uid: String100    var title: String101    var address: String102    var city: String103    var sector: String104    var unitType: String105    var price: Double?106    var image: String?107    var source: String108    var savedAt: Date109    var note: String110    /// dernier état connu (rafraîchi en arrière-plan)111    var lastPrice: Double?112    var offline: Bool113    // --- 3.1.0 (facultatifs : la base de la 3.0.0 se relit sans migration) ---114    /// dernière modification du favori (ajout, note) ; nil : jamais modifié depuis `savedAt`115    var updatedAt: Date?116    var areaSqft: Double?117    var lat: Double?118    var lng: Double?119120    /// Favori venu d'un autre appareil : affiché à partir de son aperçu, avant que la fiche ne soit chargée.121    init(remote r: RemoteFavorite) {122        let s = r.snapshot ?? FavoriteSnapshot()123        uid = r.uid124        title = s.title ?? ""125        address = s.address ?? ""126        city = s.city ?? ""127        sector = s.sector ?? ""128        unitType = s.unitType ?? ""129        price = s.price130        image = s.image131        source = s.source ?? String(r.uid.split(separator: ":").first ?? "")132        savedAt = Ms.date(r.savedAt)133        note = r.note ?? ""134        lastPrice = s.price135        offline = false136        updatedAt = r.updatedAt.map(Ms.date)137        areaSqft = s.areaSqft138        lat = s.lat139        lng = s.lng140    }141142    init(listing l: Listing) {143        uid = l.uid144        title = l.displayTitle145        address = l.address146        city = l.cleanCity147        sector = l.sector148        unitType = l.unitType149        price = l.plausiblePrice150        image = l.images.first151        source = l.source152        savedAt = Date()153        note = ""154        lastPrice = l.plausiblePrice155        offline = false156        updatedAt = savedAt157        areaSqft = l.areaSqft158        lat = l.coordinate?.latitude159        lng = l.coordinate?.longitude160    }161162    /// Titre à afficher, même pour un favori reçu sans aperçu.163    var displayTitle: String { !title.isEmpty ? title : !address.isEmpty ? address : "Logement à louer" }164165    /// Aperçu envoyé au compte avec le favori (champs partagés par le site et les applications).166    var snapshot: FavoriteSnapshot {167        func t(_ s: String) -> String? { s.isEmpty ? nil : String(s.prefix(300)) }168        return FavoriteSnapshot(title: t(title), address: t(address), city: t(city), sector: t(sector), unitType: t(unitType),169                                price: lastPrice ?? price, image: image.flatMap(t), source: t(source), areaSqft: areaSqft, lat: lat, lng: lng)170    }171172    /// Forme synchronisée (dates en millisecondes).173    var remote: RemoteFavorite {174        RemoteFavorite(uid: uid, savedAt: Ms.from(savedAt), note: note, snapshot: snapshot, updatedAt: Ms.from(updatedAt ?? savedAt))175    }176177    /// Complète un aperçu incomplet (favori venu d'un autre appareil) à partir de la fiche.178    func fill(from l: Listing) {179        if title.isEmpty { title = l.displayTitle }180        if address.isEmpty { address = l.address }181        if city.isEmpty { city = l.cleanCity }182        if sector.isEmpty { sector = l.sector }183        if unitType.isEmpty { unitType = l.unitType }184        if price == nil { price = l.plausiblePrice }185        if image == nil { image = l.images.first }186        if source.isEmpty { source = l.source }187        if areaSqft == nil { areaSqft = l.areaSqft }188        if lat == nil { lat = l.coordinate?.latitude; lng = l.coordinate?.longitude }189    }190191    var place: String {192        [sector.isEmpty || sector == city ? nil : sector, city.isEmpty ? nil : city].compactMap { $0 }.joined(separator: " · ")193    }194}195196@Model197final class SeenItem {198    @Attribute(.unique) var uid: String199    var at: Date200    init(uid: String) { self.uid = uid; at = Date() }201}202203@Model204final class CompareItem {205    @Attribute(.unique) var uid: String206    var addedAt: Date207    init(uid: String) { self.uid = uid; addedAt = Date() }208}209210@Model211final class SavedSearchItem {212    @Attribute(.unique) var id: UUID213    var label: String214    var filtersData: Data215    var sortRaw: String216    var savedAt: Date217    var lastTotal: Int?218    // --- 3.1.0 (facultatifs) ---219    /// identifiant de la recherche dans le compte ; nil : `id.uuidString`220    var remoteID: String?221    /// qui l'a créée : « ios », « web », « android » ; nil : cet appareil222    var origin: String?223    /// phrase libre d'une recherche du site (`nl=…`), interprétée par le serveur à l'ouverture224    var phrase: String?225    var updatedAt: Date?226227    init(label: String, filters: SearchFilters, sort: SearchSort, lastTotal: Int?) {228        id = UUID()229        self.label = label230        filtersData = (try? JSONEncoder().encode(filters)) ?? Data()231        sortRaw = sort.rawValue232        savedAt = Date()233        self.lastTotal = lastTotal234        updatedAt = savedAt235    }236237    /// Recherche venue du compte, déjà relue (`SearchQuery.read`).238    init(remote r: RemoteSearch, read q: SearchQuery.Read) {239        id = UUID(uuidString: r.id) ?? UUID()240        remoteID = r.id241        label = r.label.isEmpty ? (q.phrase.map { "« \($0) »" } ?? q.filters.summary) : r.label242        filtersData = (try? JSONEncoder().encode(q.filters)) ?? Data()243        sortRaw = q.sort.rawValue244        savedAt = Ms.date(r.savedAt)245        lastTotal = r.lastTotal246        origin = r.origin247        phrase = q.phrase248        updatedAt = r.updatedAt.map(Ms.date)249    }250251    /// Identifiant dans le compte (`[A-Za-z0-9_.:-]{1,64}`).252    var syncID: String { remoteID ?? id.uuidString }253254    /// Forme synchronisée : `query` est la chaîne de requête de la recherche, `origin` vaut « ios » pour255    /// une recherche créée ici.256    var remote: RemoteSearch {257        RemoteSearch(id: syncID, label: label, query: SearchQuery.string(filters, sort: sort, phrase: phrase), origin: origin ?? "ios",258                     savedAt: Ms.from(savedAt), lastTotal: lastTotal, updatedAt: Ms.from(updatedAt ?? savedAt))259    }260261    var filters: SearchFilters { (try? JSONDecoder().decode(SearchFilters.self, from: filtersData)) ?? SearchFilters() }262    var sort: SearchSort { SearchSort(rawValue: sortRaw) ?? .recent }263}264265/// Accès unique à la mémoire locale, avec des ensembles en mémoire pour les cartes et la carte.266@MainActor267@Observable268final class Library {269    static let compareMax = 8270    static let seenMax = 800271272    let container: ModelContainer273    private var context: ModelContext { container.mainContext }274    private let inMemory: Bool275276    /// Changement de la mémoire synchronisable ; écouté par `SyncEngine` quand un compte est connecté.277    enum Change: Sendable, Equatable {278        case favoriteSaved(String)279        case favoriteRemoved(String, at: Date)280        case searchSaved(String)281        case searchRemoved(String, at: Date)282    }283    @ObservationIgnored var onChange: ((Change) -> Void)?284285    private(set) var favoriteIDs: Set<String> = []286    private(set) var seenIDs: Set<String> = []287    private(set) var compareIDs: [String] = []288289    init(inMemory: Bool = false) {290        self.inMemory = inMemory291        let schema = Schema([FavoriteItem.self, SeenItem.self, CompareItem.self, SavedSearchItem.self])292        let config = ModelConfiguration("LouKa", schema: schema, isStoredInMemoryOnly: inMemory)293        do {294            container = try ModelContainer(for: schema, configurations: [config])295        } catch {296            // base illisible (jamais vu) : on repart d'une base en mémoire plutôt que de planter297            container = try! ModelContainer(for: schema, configurations: [ModelConfiguration(isStoredInMemoryOnly: true)])298        }299        reload()300    }301302    private func reload() {303        favoriteIDs = Set(((try? context.fetch(FetchDescriptor<FavoriteItem>())) ?? []).map(\.uid))304        seenIDs = Set(((try? context.fetch(FetchDescriptor<SeenItem>())) ?? []).map(\.uid))305        compareIDs = ((try? context.fetch(FetchDescriptor<CompareItem>(sortBy: [SortDescriptor(\.addedAt)]))) ?? []).map(\.uid)306    }307308    private func save() { try? context.save() }309310    // MARK: Favoris311312    func isFavorite(_ uid: String) -> Bool { favoriteIDs.contains(uid) }313314    /// Ajoute ou retire ; renvoie vrai si le logement est maintenant en favori.315    @discardableResult316    func toggleFavorite(_ l: Listing) -> Bool {317        if favoriteIDs.contains(l.uid) {318            removeFavorite(l.uid)319            return false320        }321        context.insert(FavoriteItem(listing: l))322        favoriteIDs.insert(l.uid)323        save()324        if !inMemory { SpotlightIndex.index(l, favorite: true) }325        onChange?(.favoriteSaved(l.uid))326        return true327    }328329    func removeFavorite(_ uid: String) {330        let d = FetchDescriptor<FavoriteItem>(predicate: #Predicate { $0.uid == uid })331        for f in (try? context.fetch(d)) ?? [] { context.delete(f) }332        favoriteIDs.remove(uid)333        save()334        if !inMemory { SpotlightIndex.remove(uid: uid) }335        onChange?(.favoriteRemoved(uid, at: Date()))336    }337338    func favorite(_ uid: String) -> FavoriteItem? {339        let d = FetchDescriptor<FavoriteItem>(predicate: #Predicate { $0.uid == uid })340        return (try? context.fetch(d))?.first341    }342343    func allFavorites() -> [FavoriteItem] {344        (try? context.fetch(FetchDescriptor<FavoriteItem>(sortBy: [SortDescriptor(\.savedAt, order: .reverse)]))) ?? []345    }346347    /// La note d'un favori vient d'être modifiée (éditeur de note) : datée, enregistrée, envoyée au compte.348    func noteChanged(_ uid: String) {349        guard let f = favorite(uid) else { return }350        f.note = String(f.note.prefix(2000))351        f.updatedAt = Date()352        save()353        onChange?(.favoriteSaved(uid))354    }355356    /// Enregistre des modifications faites directement sur les objets (aperçu complété, état en ligne).357    func persist() { save() }358359    /// Remplace les favoris par la liste fusionnée du compte. Les favoris de `keep` (modifiés pendant la360    /// synchronisation) sont gardés tels quels. Spotlight suit : ajouts indexés, retraits désindexés.361    func replaceFavorites(with remote: [RemoteFavorite], keep: Set<String> = []) {362        let local = Dictionary(allFavorites().map { ($0.uid, $0) }, uniquingKeysWith: { a, _ in a })363        let wanted = Set(remote.map(\.uid))364        for (uid, f) in local where !wanted.contains(uid) && !keep.contains(uid) {365            context.delete(f)366            if !inMemory { SpotlightIndex.remove(uid: uid) }367        }368        for r in remote where !keep.contains(r.uid) {369            if let f = local[r.uid] {370                f.note = r.note ?? ""371                if r.savedAt > 0 { f.savedAt = Ms.date(r.savedAt) }372                f.updatedAt = r.updatedAt.map(Ms.date) ?? f.updatedAt373                // l'aperçu local fait foi ; celui du compte ne comble que les champs vides374                if let s = r.snapshot {375                    if f.title.isEmpty { f.title = s.title ?? "" }376                    if f.address.isEmpty { f.address = s.address ?? "" }377                    if f.city.isEmpty { f.city = s.city ?? "" }378                    if f.sector.isEmpty { f.sector = s.sector ?? "" }379                    if f.unitType.isEmpty { f.unitType = s.unitType ?? "" }380                    if f.price == nil { f.price = s.price; f.lastPrice = f.lastPrice ?? s.price }381                    if f.image == nil { f.image = s.image }382                    if f.areaSqft == nil { f.areaSqft = s.areaSqft }383                    if f.lat == nil { f.lat = s.lat; f.lng = s.lng }384                }385            } else {386                let f = FavoriteItem(remote: r)387                context.insert(f)388                if !inMemory { SpotlightIndex.index(favorite: f) }389            }390        }391        save()392        favoriteIDs = Set(allFavorites().map(\.uid))393    }394395    // MARK: Vus396397    func markSeen(_ uid: String) {398        guard !seenIDs.contains(uid) else { return }399        context.insert(SeenItem(uid: uid))400        seenIDs.insert(uid)401        if seenIDs.count > Library.seenMax {402            var d = FetchDescriptor<SeenItem>(sortBy: [SortDescriptor(\.at)])403            d.fetchLimit = seenIDs.count - Library.seenMax404            for s in (try? context.fetch(d)) ?? [] { seenIDs.remove(s.uid); context.delete(s) }405        }406        save()407    }408409    // MARK: Comparateur410411    enum CompareResult { case added, removed, full }412413    @discardableResult414    func toggleCompare(_ uid: String) -> CompareResult {415        if compareIDs.contains(uid) {416            let d = FetchDescriptor<CompareItem>(predicate: #Predicate { $0.uid == uid })417            for c in (try? context.fetch(d)) ?? [] { context.delete(c) }418            compareIDs.removeAll { $0 == uid }419            save()420            return .removed421        }422        guard compareIDs.count < Library.compareMax else { return .full }423        context.insert(CompareItem(uid: uid))424        compareIDs.append(uid)425        save()426        return .added427    }428429    func clearCompare() {430        for c in (try? context.fetch(FetchDescriptor<CompareItem>())) ?? [] { context.delete(c) }431        compareIDs = []432        save()433    }434435    // MARK: Recherches436437    func saveSearch(_ filters: SearchFilters, sort: SearchSort, total: Int?) {438        let s = SavedSearchItem(label: filters.summary, filters: filters, sort: sort, lastTotal: total)439        context.insert(s)440        save()441        onChange?(.searchSaved(s.syncID))442    }443444    func delete(_ search: SavedSearchItem) {445        let id = search.syncID446        context.delete(search)447        save()448        onChange?(.searchRemoved(id, at: Date()))449    }450451    func allSearches() -> [SavedSearchItem] {452        (try? context.fetch(FetchDescriptor<SavedSearchItem>(sortBy: [SortDescriptor(\.savedAt, order: .reverse)]))) ?? []453    }454455    /// Remplace les recherches par la liste fusionnée du compte. Seules celles dont l'app sait relire la456    /// requête sont gardées sur l'appareil ; les autres restent dans le compte, intactes.457    func replaceSearches(with remote: [RemoteSearch], keep: Set<String> = []) {458        let local = Dictionary(allSearches().map { ($0.syncID, $0) }, uniquingKeysWith: { a, _ in a })459        let wanted = Set(remote.map(\.id))460        for (id, s) in local where !wanted.contains(id) && !keep.contains(id) { context.delete(s) }461        for r in remote where !keep.contains(r.id) {462            if let s = local[r.id] {463                // la recherche locale garde ses filtres (forme la plus riche) ; libellé et compte suivent le compte464                if !r.label.isEmpty { s.label = r.label }465                s.lastTotal = r.lastTotal ?? s.lastTotal466                s.updatedAt = r.updatedAt.map(Ms.date) ?? s.updatedAt467            } else if let q = SearchQuery.read(r.query) {468                context.insert(SavedSearchItem(remote: r, read: q))469            }470        }471        save()472    }473474    /// Efface toute la mémoire locale (Réglages).475    func eraseAll() {476        for f in (try? context.fetch(FetchDescriptor<FavoriteItem>())) ?? [] { context.delete(f) }477        for f in (try? context.fetch(FetchDescriptor<SeenItem>())) ?? [] { context.delete(f) }478        for f in (try? context.fetch(FetchDescriptor<CompareItem>())) ?? [] { context.delete(f) }479        for f in (try? context.fetch(FetchDescriptor<SavedSearchItem>())) ?? [] { context.delete(f) }480        save()481        reload()482        if !inMemory { SpotlightIndex.removeAll() }483    }484}485
Files main
Menu

Theme