Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : Immo-Ka iOS9// File : ImmoKa/Core/Store/Library.swift10// Description : mémoire locale (SwiftData) — favoris, propriétés11// consultées, comparateur, recherches enregistrées. Sans12// compte, rien ne quitte l'appareil. Avec un compte13// (facultatif), favoris, notes et recherches sont14// synchronisés par `SyncEngine`, qui écoute15// `Library.onChange`.16// Module : ImmoKa17// Repository : https://git.spboucher.ai/immo-ka-ios-v318// Project Website : https://www.immo-ka.com19// Created : 2026-11-2520// Last Modified : 2026-11-3021//22// =============================================================================23// AUTHOR & PROFESSIONAL AFFILIATION24// =============================================================================25//26// Author : Simon-Pierre Boucher27// Position : Professor of Finance28// Institution : Université du Québec en Outaouais (UQO)29// Department : Département des sciences administratives30// Organization : SP Boucher31//32// Website : https://spboucher.ai33// Git : https://git.spboucher.ai34//35// =============================================================================36// OFFICIAL CONTACT DIRECTORY37// =============================================================================38//39// General : info@spboucher.ai40// Professional : contact@spboucher.ai41// Direct : simon@spboucher.ai42// Research : research@spboucher.ai43// Development : dev@spboucher.ai44// Support : support@spboucher.ai45// Security/Admin : admin@spboucher.ai46// Notifications : notifications@spboucher.ai47//48// Preferred Contact: support@spboucher.ai49//50// =============================================================================51// COPYRIGHT & INTELLECTUAL PROPERTY52// =============================================================================53//54// Copyright (c) 202655// Simon-Pierre Boucher56//57// All rights reserved where applicable.58//59// This file is governed by the applicable project license,60// copyright notices, institutional agreements and relevant law.61//62// Unless expressly authorized by the applicable license or63// rights holder, copying, redistribution, sublicensing,64// publication and commercial exploitation are not permitted.65//66// Existing third-party rights and notices remain unaffected.67//68// =============================================================================69// CONFIDENTIALITY & SECURITY70// =============================================================================71//72// Classification : Public73// Distribution : Public repository; use is governed by the project license74// Security Contact : admin@spboucher.ai75//76// Access to this source does not independently grant permission77// to redistribute or disclose confidential materials.78//79// Do not embed credentials, private keys, access tokens,80// certificates or confidential personal information.81//82// =============================================================================83// LICENSE & MAINTENANCE84// =============================================================================85//86// License : None specified (no license file in this repository)87// Maintainer : Simon-Pierre Boucher88// Technical Contact: dev@spboucher.ai89//90// =============================================================================91// END OF SP BOUCHER SOURCE HEADER92// =============================================================================9394import Foundation95import Observation96import SwiftData9798/// Instantané d'une propriété gardé sur l'appareil (favori ou fiche consultée) : assez pour l'afficher hors ligne.99protocol ListingSnapshot {100 var uid: String { get }101 var title: String { get }102 var city: String { get }103 var sector: String { get }104 var propertyType: String { get }105 var price: Double? { get }106 var image: String? { get }107 var bedrooms: Int? { get }108 var bathrooms: Int? { get }109 var areaSqft: Double? { get }110}111112extension ListingSnapshot {113 var place: String {114 [sector.isEmpty || sector == city ? nil : sector, city.isEmpty ? nil : city].compactMap { $0 }.joined(separator: " · ")115 }116 /// « Maison · 3 ch. · 2 sdb · 1 450 pi² »117 var facts: String {118 [propertyType.isEmpty ? nil : propertyType, bedrooms.map { "\($0) ch." }, bathrooms.map { "\($0) sdb" },119 areaSqft.map { "\(Fmt.int($0)) pi²" }].compactMap { $0 }.joined(separator: " · ")120 }121}122123@Model124final class FavoriteItem: ListingSnapshot {125 @Attribute(.unique) var uid: String126 var title: String127 var city: String128 var sector: String129 var propertyType: String130 var price: Double?131 var image: String?132 var source: String133 var bedrooms: Int?134 var bathrooms: Int?135 var areaSqft: Double?136 var savedAt: Date137 var note: String138 /// prix au moment de l'enregistrement : la fiche signale une baisse ou une hausse depuis139 var savedPrice: Double?140 // --- 3.1.0 (facultatifs : la base de la 3.0.0 se relit sans migration) ---141 /// dernière modification du favori (ajout, note) ; nil : jamais modifié depuis `savedAt`142 var updatedAt: Date?143 var address: String?144 var lat: Double?145 var lng: Double?146147 init(listing l: Listing) {148 uid = l.uid149 title = l.displayTitle150 city = l.cleanCity151 sector = l.sector152 propertyType = l.kind153 price = l.plausiblePrice154 image = l.images.first155 source = l.source156 bedrooms = l.bedrooms157 bathrooms = l.bathrooms158 areaSqft = l.areaSqft159 savedAt = Date()160 note = ""161 savedPrice = l.plausiblePrice162 updatedAt = savedAt163 address = l.address.isEmpty ? nil : l.address164 lat = l.coordinate?.latitude165 lng = l.coordinate?.longitude166 }167168 /// Favori venu d'un autre appareil : affiché à partir de son aperçu, avant que la fiche ne soit chargée.169 init(remote r: RemoteFavorite) {170 let s = r.snapshot ?? FavoriteSnapshot()171 uid = r.uid172 title = s.title ?? s.address ?? ""173 city = s.city ?? ""174 sector = s.sector ?? ""175 propertyType = s.propertyType ?? ""176 price = s.price177 image = s.image178 source = s.source ?? String(r.uid.split(separator: ":").first ?? "")179 areaSqft = s.areaSqft180 savedAt = Ms.date(r.savedAt)181 note = r.note ?? ""182 savedPrice = s.price183 updatedAt = r.updatedAt.map(Ms.date)184 address = s.address185 lat = s.lat186 lng = s.lng187 }188189 /// Titre à afficher, même pour un favori reçu sans aperçu.190 var displayTitle: String { !title.isEmpty ? title : !(address ?? "").isEmpty ? (address ?? "") : "Propriété à vendre" }191192 /// Aperçu envoyé au compte avec le favori (champs partagés par le site et les applications).193 var snapshot: FavoriteSnapshot {194 func t(_ s: String?) -> String? { (s ?? "").isEmpty ? nil : String((s ?? "").prefix(300)) }195 return FavoriteSnapshot(title: t(title), address: t(address), city: t(city), sector: t(sector), propertyType: t(propertyType),196 price: price, image: t(image), source: t(source), areaSqft: areaSqft, lat: lat, lng: lng)197 }198199 /// Forme synchronisée (dates en millisecondes).200 var remote: RemoteFavorite {201 RemoteFavorite(uid: uid, savedAt: Ms.from(savedAt), note: note, snapshot: snapshot, updatedAt: Ms.from(updatedAt ?? savedAt))202 }203204 /// Complète un aperçu incomplet (favori venu d'un autre appareil) à partir de la fiche.205 func fill(from l: Listing) {206 if title.isEmpty { title = l.displayTitle }207 if (address ?? "").isEmpty, !l.address.isEmpty { address = l.address }208 if city.isEmpty { city = l.cleanCity }209 if sector.isEmpty { sector = l.sector }210 if propertyType.isEmpty { propertyType = l.kind }211 if price == nil { price = l.plausiblePrice }212 if savedPrice == nil { savedPrice = l.plausiblePrice }213 if image == nil { image = l.images.first }214 if source.isEmpty { source = l.source }215 if bedrooms == nil { bedrooms = l.bedrooms }216 if bathrooms == nil { bathrooms = l.bathrooms }217 if areaSqft == nil { areaSqft = l.areaSqft }218 if lat == nil { lat = l.coordinate?.latitude; lng = l.coordinate?.longitude }219 }220221 /// L'aperçu est-il incomplet au point de mériter d'être complété par la fiche ?222 var needsFill: Bool { title.isEmpty || image == nil || propertyType.isEmpty }223}224225@Model226final class SeenItem: ListingSnapshot {227 @Attribute(.unique) var uid: String228 var at: Date229 var title: String230 var city: String231 var sector: String232 var propertyType: String233 var price: Double?234 var image: String?235 var bedrooms: Int?236 var bathrooms: Int?237 var areaSqft: Double?238239 init(listing l: Listing) {240 uid = l.uid241 at = Date()242 title = l.displayTitle243 city = l.cleanCity244 sector = l.sector245 propertyType = l.kind246 price = l.plausiblePrice247 image = l.images.first248 bedrooms = l.bedrooms249 bathrooms = l.bathrooms250 areaSqft = l.areaSqft251 }252}253254@Model255final class CompareItem {256 @Attribute(.unique) var uid: String257 var addedAt: Date258 init(uid: String) { self.uid = uid; addedAt = Date() }259}260261@Model262final class SavedSearchItem {263 @Attribute(.unique) var id: UUID264 var label: String265 var filtersData: Data266 var sortRaw: String267 var savedAt: Date268 var lastTotal: Int?269 // --- 3.1.0 (facultatifs) ---270 /// identifiant de la recherche dans le compte ; nil : `id.uuidString`271 var remoteID: String?272 /// qui l'a créée : « ios », « web », « android » ; nil : cet appareil273 var origin: String?274 var updatedAt: Date?275276 init(label: String, filters: SearchFilters, sort: SearchSort, lastTotal: Int?) {277 id = UUID()278 self.label = label279 filtersData = (try? JSONEncoder().encode(filters)) ?? Data()280 sortRaw = sort.rawValue281 savedAt = Date()282 self.lastTotal = lastTotal283 updatedAt = savedAt284 }285286 /// Recherche venue du compte, déjà relue (`SearchQuery.read`).287 init(remote r: RemoteSearch, read q: SearchQuery.Read) {288 id = UUID(uuidString: r.id) ?? UUID()289 remoteID = r.id290 label = r.label.isEmpty ? q.filters.summary : r.label291 filtersData = (try? JSONEncoder().encode(q.filters)) ?? Data()292 sortRaw = q.sort.rawValue293 savedAt = Ms.date(r.savedAt)294 lastTotal = r.lastTotal295 origin = r.origin296 updatedAt = r.updatedAt.map(Ms.date)297 }298299 /// Identifiant dans le compte (`[A-Za-z0-9_.:-]{1,64}`).300 var syncID: String { remoteID ?? id.uuidString }301302 /// Forme synchronisée : `query` est la chaîne de requête de la recherche (paramètres de `/api/v3/search`),303 /// `origin` vaut « ios » pour une recherche créée ici.304 var remote: RemoteSearch {305 RemoteSearch(id: syncID, label: label, query: SearchQuery.string(filters, sort: sort), origin: origin ?? "ios",306 savedAt: Ms.from(savedAt), lastTotal: lastTotal, updatedAt: Ms.from(updatedAt ?? savedAt))307 }308309 var filters: SearchFilters { (try? JSONDecoder().decode(SearchFilters.self, from: filtersData)) ?? SearchFilters() }310 var sort: SearchSort { SearchSort(rawValue: sortRaw) ?? .recent }311}312313/// Accès unique à la mémoire locale, avec des ensembles en mémoire pour les cartes et la carte.314@MainActor315@Observable316final class Library {317 /// huit en v3 (comme le site et le rapport de comparaison), quatre auparavant318 static let compareMax = 8319 static let seenMax = 400320321 let container: ModelContainer322 private var context: ModelContext { container.mainContext }323324 /// Changement de la mémoire synchronisable ; écouté par `SyncEngine` quand un compte est connecté.325 enum Change: Sendable, Equatable {326 case favoriteSaved(String)327 case favoriteRemoved(String, at: Date)328 case searchSaved(String)329 case searchRemoved(String, at: Date)330 }331 @ObservationIgnored var onChange: ((Change) -> Void)?332333 private(set) var favoriteIDs: Set<String> = []334 private(set) var seenIDs: Set<String> = []335 private(set) var compareIDs: [String] = []336337 /// Spotlight : favoris et fiches consultées (pas pour une base jetable de test ou de capture)338 private let indexes: Bool339340 private func spotlight(_ s: any ListingSnapshot, domain: String) {341 guard indexes else { return }342 Spotlight.index(uid: s.uid, domain: domain, title: s.title, city: s.city, sector: s.sector, kind: s.propertyType, price: s.price, facts: s.facts)343 }344345 init(inMemory: Bool = false) {346 indexes = !inMemory347 let schema = Schema([FavoriteItem.self, SeenItem.self, CompareItem.self, SavedSearchItem.self])348 let config = ModelConfiguration("ImmoKa-v2", schema: schema, isStoredInMemoryOnly: inMemory)349 do {350 container = try ModelContainer(for: schema, configurations: [config])351 } catch {352 // base illisible (jamais vu) : on repart d'une base en mémoire plutôt que de planter353 container = try! ModelContainer(for: schema, configurations: [ModelConfiguration(isStoredInMemoryOnly: true)])354 }355 reload()356 }357358 private func reload() {359 favoriteIDs = Set(((try? context.fetch(FetchDescriptor<FavoriteItem>())) ?? []).map(\.uid))360 seenIDs = Set(((try? context.fetch(FetchDescriptor<SeenItem>())) ?? []).map(\.uid))361 compareIDs = ((try? context.fetch(FetchDescriptor<CompareItem>(sortBy: [SortDescriptor(\.addedAt)]))) ?? []).map(\.uid)362 }363364 private func save() { try? context.save() }365366 // MARK: Favoris367368 func isFavorite(_ uid: String) -> Bool { favoriteIDs.contains(uid) }369370 /// Ajoute ou retire ; renvoie vrai si la propriété est maintenant en favori.371 @discardableResult372 func toggleFavorite(_ l: Listing) -> Bool {373 if favoriteIDs.contains(l.uid) {374 removeFavorite(l.uid)375 return false376 }377 let item = FavoriteItem(listing: l)378 context.insert(item)379 favoriteIDs.insert(l.uid)380 save()381 spotlight(item, domain: Spotlight.favoritesDomain)382 onChange?(.favoriteSaved(l.uid))383 return true384 }385386 func removeFavorite(_ uid: String) {387 let d = FetchDescriptor<FavoriteItem>(predicate: #Predicate { $0.uid == uid })388 for f in (try? context.fetch(d)) ?? [] { context.delete(f) }389 favoriteIDs.remove(uid)390 save()391 if indexes { Spotlight.remove(uid: uid, domain: Spotlight.favoritesDomain) }392 onChange?(.favoriteRemoved(uid, at: Date()))393 }394395 func favorite(_ uid: String) -> FavoriteItem? {396 let d = FetchDescriptor<FavoriteItem>(predicate: #Predicate { $0.uid == uid })397 return (try? context.fetch(d))?.first398 }399400 func allFavorites() -> [FavoriteItem] {401 (try? context.fetch(FetchDescriptor<FavoriteItem>(sortBy: [SortDescriptor(\.savedAt, order: .reverse)]))) ?? []402 }403404 /// La note d'un favori vient d'être modifiée (éditeur de note) : datée, enregistrée, envoyée au compte.405 func noteChanged(_ uid: String) {406 guard let f = favorite(uid) else { return }407 f.note = String(f.note.prefix(2000))408 f.updatedAt = Date()409 save()410 onChange?(.favoriteSaved(uid))411 }412413 /// Enregistre des modifications faites directement sur les objets (aperçu complété).414 func persist() { save() }415416 /// Remplace les favoris par la liste fusionnée du compte. Les favoris de `keep` (modifiés pendant la417 /// synchronisation) sont gardés tels quels. Spotlight suit : ajouts indexés, retraits désindexés.418 func replaceFavorites(with remote: [RemoteFavorite], keep: Set<String> = []) {419 let local = Dictionary(allFavorites().map { ($0.uid, $0) }, uniquingKeysWith: { a, _ in a })420 let wanted = Set(remote.map(\.uid))421 for (uid, f) in local where !wanted.contains(uid) && !keep.contains(uid) {422 context.delete(f)423 if indexes { Spotlight.remove(uid: uid, domain: Spotlight.favoritesDomain) }424 }425 for r in remote where !keep.contains(r.uid) {426 if let f = local[r.uid] {427 f.note = r.note ?? ""428 if r.savedAt > 0 { f.savedAt = Ms.date(r.savedAt) }429 f.updatedAt = r.updatedAt.map(Ms.date) ?? f.updatedAt430 // l'aperçu local fait foi ; celui du compte ne comble que les champs vides431 if let s = r.snapshot {432 if f.title.isEmpty { f.title = s.title ?? "" }433 if (f.address ?? "").isEmpty { f.address = s.address }434 if f.city.isEmpty { f.city = s.city ?? "" }435 if f.sector.isEmpty { f.sector = s.sector ?? "" }436 if f.propertyType.isEmpty { f.propertyType = s.propertyType ?? "" }437 if f.price == nil { f.price = s.price; f.savedPrice = f.savedPrice ?? s.price }438 if f.image == nil { f.image = s.image }439 if f.areaSqft == nil { f.areaSqft = s.areaSqft }440 if f.lat == nil { f.lat = s.lat; f.lng = s.lng }441 }442 } else {443 let f = FavoriteItem(remote: r)444 context.insert(f)445 if indexes {446 Spotlight.index(uid: f.uid, domain: Spotlight.favoritesDomain, title: f.displayTitle, city: f.city, sector: f.sector,447 kind: f.propertyType, price: f.price, facts: f.facts)448 }449 }450 }451 save()452 favoriteIDs = Set(allFavorites().map(\.uid))453 }454455 // MARK: Vus456457 /// Note la consultation d'une fiche (instantané gardé pour « Récemment consultées »).458 func markSeen(_ l: Listing) {459 let uid = l.uid460 let d = FetchDescriptor<SeenItem>(predicate: #Predicate { $0.uid == uid })461 if let known = (try? context.fetch(d))?.first {462 known.at = Date()463 known.price = l.plausiblePrice464 if known.image == nil { known.image = l.images.first }465 } else {466 let item = SeenItem(listing: l)467 context.insert(item)468 seenIDs.insert(uid)469 spotlight(item, domain: Spotlight.seenDomain)470 }471 if seenIDs.count > Library.seenMax {472 var old = FetchDescriptor<SeenItem>(sortBy: [SortDescriptor(\.at)])473 old.fetchLimit = seenIDs.count - Library.seenMax474 for s in (try? context.fetch(old)) ?? [] { seenIDs.remove(s.uid); context.delete(s) }475 }476 save()477 }478479 /// Met à jour le prix connu d'un favori (appelé quand sa fiche est rechargée).480 func refreshFavorite(_ l: Listing) {481 let uid = l.uid482 guard favoriteIDs.contains(uid) else { return }483 let d = FetchDescriptor<FavoriteItem>(predicate: #Predicate { $0.uid == uid })484 guard let f = (try? context.fetch(d))?.first else { return }485 // favori venu d'un autre appareil avec un aperçu incomplet : complété par la fiche486 let incomplete = f.needsFill487 guard incomplete || f.price != l.plausiblePrice else { return }488 if incomplete { f.fill(from: l) }489 f.price = l.plausiblePrice490 save()491 }492493 func clearSeen() {494 for f in (try? context.fetch(FetchDescriptor<SeenItem>())) ?? [] { context.delete(f) }495 seenIDs = []496 save()497 if indexes { Spotlight.removeAll(domain: Spotlight.seenDomain) }498 }499500 // MARK: Comparateur501502 enum CompareResult { case added, removed, full }503504 @discardableResult505 func toggleCompare(_ uid: String) -> CompareResult {506 if compareIDs.contains(uid) {507 let d = FetchDescriptor<CompareItem>(predicate: #Predicate { $0.uid == uid })508 for c in (try? context.fetch(d)) ?? [] { context.delete(c) }509 compareIDs.removeAll { $0 == uid }510 save()511 return .removed512 }513 guard compareIDs.count < Library.compareMax else { return .full }514 context.insert(CompareItem(uid: uid))515 compareIDs.append(uid)516 save()517 return .added518 }519520 func clearCompare() {521 for c in (try? context.fetch(FetchDescriptor<CompareItem>())) ?? [] { context.delete(c) }522 compareIDs = []523 save()524 }525526 // MARK: Recherches527528 func saveSearch(_ filters: SearchFilters, sort: SearchSort, total: Int?) {529 let s = SavedSearchItem(label: filters.summary, filters: filters, sort: sort, lastTotal: total)530 context.insert(s)531 save()532 onChange?(.searchSaved(s.syncID))533 }534535 func delete(_ search: SavedSearchItem) {536 let id = search.syncID537 context.delete(search)538 save()539 onChange?(.searchRemoved(id, at: Date()))540 }541542 func allSearches() -> [SavedSearchItem] {543 (try? context.fetch(FetchDescriptor<SavedSearchItem>(sortBy: [SortDescriptor(\.savedAt, order: .reverse)]))) ?? []544 }545546 /// Remplace les recherches par la liste fusionnée du compte. Seules celles dont l'app sait relire la547 /// requête sont gardées sur l'appareil ; les autres restent dans le compte, intactes.548 func replaceSearches(with remote: [RemoteSearch], keep: Set<String> = []) {549 let local = Dictionary(allSearches().map { ($0.syncID, $0) }, uniquingKeysWith: { a, _ in a })550 let wanted = Set(remote.map(\.id))551 for (id, s) in local where !wanted.contains(id) && !keep.contains(id) { context.delete(s) }552 for r in remote where !keep.contains(r.id) {553 if let s = local[r.id] {554 // la recherche locale garde ses filtres (forme la plus riche) ; libellé et compte suivent le compte555 if !r.label.isEmpty { s.label = r.label }556 s.lastTotal = r.lastTotal ?? s.lastTotal557 s.updatedAt = r.updatedAt.map(Ms.date) ?? s.updatedAt558 } else if let q = SearchQuery.read(r.query) {559 context.insert(SavedSearchItem(remote: r, read: q))560 }561 }562 save()563 }564565 /// Efface toute la mémoire locale (Réglages).566 func eraseAll() {567 for f in (try? context.fetch(FetchDescriptor<FavoriteItem>())) ?? [] { context.delete(f) }568 for f in (try? context.fetch(FetchDescriptor<SeenItem>())) ?? [] { context.delete(f) }569 for f in (try? context.fetch(FetchDescriptor<CompareItem>())) ?? [] { context.delete(f) }570 for f in (try? context.fetch(FetchDescriptor<SavedSearchItem>())) ?? [] { context.delete(f) }571 save()572 reload()573 if indexes { Spotlight.removeAll(domain: Spotlight.favoritesDomain); Spotlight.removeAll(domain: Spotlight.seenDomain) }574 }575576 /// Réindexe les favoris déjà enregistrés (une fois, au premier lancement de la 3.0.0).577 func indexExistingFavorites() {578 guard indexes, !UserDefaults.standard.bool(forKey: "spotlight.v3") else { return }579 for f in (try? context.fetch(FetchDescriptor<FavoriteItem>())) ?? [] { spotlight(f, domain: Spotlight.favoritesDomain) }580 UserDefaults.standard.set(true, forKey: "spotlight.v3")581 }582}583