Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : Immo-Ka iOS9// File : ImmoKa/Core/Account/SyncEngine.swift10// Description : synchronisation des favoris (avec leurs notes) et des11// recherches enregistrées avec le compte. À la connexion :12// toute la mémoire locale est envoyée, la liste fusionnée du13// serveur la remplace. Ensuite chaque ajout, note ou retrait14// part aussitôt ; les retraits qui n'ont pas pu partir sont15// gardés avec leur date et rejoués. Nouvelle synchronisation16// au retour au premier plan et au retour du réseau. Sans17// compte, rien n'est envoyé.18// Module : ImmoKa19// Repository : https://git.spboucher.ai/immo-ka-ios-v320// Project Website : https://www.immo-ka.com21// Created : 2026-11-3022// Last Modified : 2026-11-3023//24// =============================================================================25// AUTHOR & PROFESSIONAL AFFILIATION26// =============================================================================27//28// Author : Simon-Pierre Boucher29// Position : Professor of Finance30// Institution : Université du Québec en Outaouais (UQO)31// Department : Département des sciences administratives32// Organization : SP Boucher33//34// Website : https://spboucher.ai35// Git : https://git.spboucher.ai36//37// =============================================================================38// OFFICIAL CONTACT DIRECTORY39// =============================================================================40//41// General : info@spboucher.ai42// Professional : contact@spboucher.ai43// Direct : simon@spboucher.ai44// Research : research@spboucher.ai45// Development : dev@spboucher.ai46// Support : support@spboucher.ai47// Security/Admin : admin@spboucher.ai48// Notifications : notifications@spboucher.ai49//50// Preferred Contact: support@spboucher.ai51//52// =============================================================================53// COPYRIGHT & INTELLECTUAL PROPERTY54// =============================================================================55//56// Copyright (c) 202657// Simon-Pierre Boucher58//59// All rights reserved where applicable.60//61// This file is governed by the applicable project license,62// copyright notices, institutional agreements and relevant law.63//64// Unless expressly authorized by the applicable license or65// rights holder, copying, redistribution, sublicensing,66// publication and commercial exploitation are not permitted.67//68// Existing third-party rights and notices remain unaffected.69//70// =============================================================================71// CONFIDENTIALITY & SECURITY72// =============================================================================73//74// Classification : Public75// Distribution : Public repository; use is governed by the project license76// Security Contact : admin@spboucher.ai77//78// Access to this source does not independently grant permission79// to redistribute or disclose confidential materials.80//81// Do not embed credentials, private keys, access tokens,82// certificates or confidential personal information.83//84// =============================================================================85// LICENSE & MAINTENANCE86// =============================================================================87//88// License : None specified (no license file in this repository)89// Maintainer : Simon-Pierre Boucher90// Technical Contact: dev@spboucher.ai91//92// =============================================================================93// END OF SP BOUCHER SOURCE HEADER94// =============================================================================9596import Foundation97import Network98import Observation99100/// Chaîne de requête d'une recherche enregistrée : mêmes paramètres que `/api/v3/search` et que l'adresse101/// `/recherche?…` du site (plus `sort`). Une phrase libre voyage dans `nl`, comme dans les filtres de l'app.102enum SearchQuery {103 struct Read: Equatable, Sendable {104 var filters: SearchFilters105 var sort: SearchSort106 }107108 static func string(_ filters: SearchFilters, sort: SearchSort) -> String {109 var comps = URLComponents()110 var items = filters.queryV3.compactMap { k, v -> URLQueryItem? in111 guard let v, !v.isEmpty else { return nil }112 return URLQueryItem(name: k, value: v)113 }114 if sort != .pertinence { items.append(URLQueryItem(name: "sort", value: sort.v3)) }115 comps.queryItems = items.sorted { $0.name < $1.name }116 return (comps.percentEncodedQuery ?? "").replacingOccurrences(of: "+", with: "%2B")117 }118119 /// Relit une requête ; nil si un paramètre n'est pas représentable par l'app (la recherche n'est alors120 /// pas affichée : mieux vaut l'omettre que l'ouvrir autrement que son auteur ne l'a enregistrée).121 static func read(_ query: String) -> Read? {122 let q = query.hasPrefix("?") ? String(query.dropFirst()) : query123 var comps = URLComponents()124 comps.percentEncodedQuery = q.replacingOccurrences(of: "+", with: "%20")125 var params: [String: String] = [:]126 for item in comps.queryItems ?? [] {127 guard let v = item.value, !v.isEmpty else { continue }128 if params[item.name] != nil { return nil } // paramètre répété : forme inconnue de l'app129 params[item.name] = v130 }131 var sort = SearchSort.pertinence132 if let s = params.removeValue(forKey: "sort") {133 guard let known = SearchSort.allCases.first(where: { $0.v3 == s }) else { return nil }134 sort = known135 }136 var f = SearchFilters()137 for (k, v) in params {138 switch k {139 case "city": f.city = v140 case "area": f.sector = v141 case "region": f.region = v142 case "type": f.propertyType = v143 case "source": f.source = v144 case "agency": f.agency = v145 case "broker": f.broker = v146 case "q": f.text = v147 case "nl": f.nl = v148 case "price_min": guard let n = Int(v) else { return nil }; f.priceMin = n149 case "price_max": guard let n = Int(v) else { return nil }; f.priceMax = n150 case "bedrooms_min": guard let n = Int(v) else { return nil }; f.bedroomsMin = n151 case "bathrooms_min": guard let n = Int(v) else { return nil }; f.bathroomsMin = n152 case "area_min": guard let n = Int(v) else { return nil }; f.areaMin = n153 case "lot_min": guard let n = Int(v) else { return nil }; f.lotMin = n154 case "year_min": guard let n = Int(v) else { return nil }; f.yearMin = n155 case "year_max": guard let n = Int(v) else { return nil }; f.yearMax = n156 case "new_days": guard let n = Int(v) else { return nil }; f.newDays = n157 case "tax_max": guard let n = Int(v) else { return nil }; f.taxMax = n158 case "condo_fee_max": guard let n = Int(v) else { return nil }; f.condoFeeMax = n159 case "price_drop": guard v == "1" || v == "true" else { return nil }; f.priceDrop = true160 case "position":161 switch v { case "sous": f.deal = .sous; case "dans": f.deal = .marche; case "sur": f.deal = .sur; default: return nil }162 case "with":163 let keys = v.split(separator: ",").map(String.init)164 guard keys.allSatisfy({ k in SearchFilters.attributes.contains { $0.key == k } }) else { return nil }165 f.with = keys.sorted()166 default: return nil167 }168 }169 return Read(filters: f, sort: sort)170 }171}172173/// Retraits faits pendant qu'un compte est connecté et pas encore confirmés par le serveur.174struct PendingRemovals: Codable, Equatable, Sendable {175 /// uid du favori → moment du retrait (ms)176 var favorites: [String: Int64] = [:]177 /// identifiant de la recherche → moment du retrait (ms)178 var searches: [String: Int64] = [:]179 var isEmpty: Bool { favorites.isEmpty && searches.isEmpty }180181 static let storeKey = "compte.retraits"182 static func load(_ defaults: UserDefaults?) -> PendingRemovals {183 guard let d = defaults?.data(forKey: storeKey) else { return PendingRemovals() }184 return (try? JSONDecoder().decode(PendingRemovals.self, from: d)) ?? PendingRemovals()185 }186 func save(_ defaults: UserDefaults?) {187 guard let defaults else { return }188 if isEmpty { defaults.removeObject(forKey: PendingRemovals.storeKey) } else { defaults.set(try? JSONEncoder().encode(self), forKey: PendingRemovals.storeKey) }189 }190}191192/// Règles de fusion côté appareil (pures, testées). Le serveur arbitre (la version la plus récente193/// l'emporte) ; l'appareil ne protège que ce qui a changé pendant l'aller-retour.194enum SyncLogic {195 static func favoriteRequest(local: [RemoteFavorite], pending: PendingRemovals) -> FavoriteSyncRequest {196 let present = Set(local.map(\.uid))197 return FavoriteSyncRequest(items: local,198 removed: pending.favorites.filter { !present.contains($0.key) }199 .map { RemovedFavorite(uid: $0.key, at: $0.value) }.sorted { $0.uid < $1.uid })200 }201202 static func searchRequest(local: [RemoteSearch], pending: PendingRemovals) -> SearchSyncRequest {203 let present = Set(local.map(\.id))204 return SearchSyncRequest(items: local,205 removed: pending.searches.filter { !present.contains($0.key) }206 .map { RemovedSearch(id: $0.key, at: $0.value) }.sorted { $0.id < $1.id })207 }208209 /// Éléments envoyés que le serveur a refusé de prendre (`skipped` : limite du compte atteinte, identifiant210 /// refusé). Rien ne dit lesquels : tant que `skipped` n'est pas nul, aucun élément local absent de la211 /// réponse n'est supprimé de l'appareil. Ils restent locaux, comme sans compte.212 static func refused(sent: [String], server: [String], skipped: Int?) -> Set<String> {213 guard (skipped ?? 0) > 0 else { return [] }214 return Set(sent).subtracting(server)215 }216217 /// Ce que l'appareil garde de la réponse : la liste du serveur, moins ce qui a été retiré ici pendant218 /// l'aller-retour ; `keep` = éléments modifiés ici pendant l'aller-retour (ils ne sont pas écrasés, et219 /// ne sont pas supprimés si le serveur ne les connaît pas encore). `again` : une nouvelle220 /// synchronisation doit suivre.221 static func settle<T>(server: [T], id: (T) -> String, changed: Set<String>, removed: Set<String>) -> (apply: [T], keep: Set<String>, again: Bool) {222 (server.filter { !removed.contains(id($0)) }, changed.subtracting(removed), !changed.isEmpty || !removed.isEmpty)223 }224}225226@MainActor227@Observable228final class SyncEngine {229 private let library: Library230 private let api: AccountAPI231 @ObservationIgnored private let defaults: UserDefaults?232 @ObservationIgnored var isSignedIn: () -> Bool = { false }233 @ObservationIgnored var onUnauthenticated: () -> Void = {}234235 private(set) var syncing = false236 private(set) var lastSync: Date?237 /// Dernier échec, en clair (nil : la dernière synchronisation a réussi).238 private(set) var lastError: String?239 private(set) var pending: PendingRemovals240241 @ObservationIgnored private var needsSync = false242 @ObservationIgnored private var again = false243 @ObservationIgnored private var monitor: NWPathMonitor?244 /// Changements faits ici pendant une synchronisation en cours (identifiants de favoris et de recherches).245 @ObservationIgnored private var flightChanged: Set<String> = []246 @ObservationIgnored private var flightRemoved: Set<String> = []247 /// Envois immédiats en cours (attendus par les tests).248 @ObservationIgnored private var pushes: [Task<Void, Never>] = []249250 /// `defaults` nil : les retraits en attente ne survivent pas au lancement (tests, base jetable).251 init(library: Library, api: AccountAPI, defaults: UserDefaults?) {252 self.library = library253 self.api = api254 self.defaults = defaults255 pending = PendingRemovals.load(defaults)256 library.onChange = { [weak self] change in self?.handle(change) }257 }258259 /// Relance une synchronisation quand le réseau revient après un envoi manqué.260 func watchNetwork() {261 guard monitor == nil else { return }262 let m = NWPathMonitor()263 m.pathUpdateHandler = { [weak self] path in264 guard path.status == .satisfied else { return }265 Task { @MainActor in266 guard let self, self.needsSync || !self.pending.isEmpty else { return }267 await self.sync()268 }269 }270 m.start(queue: .global(qos: .utility))271 monitor = m272 }273274 /// Déconnexion : plus rien n'est envoyé ; la mémoire locale reste telle quelle.275 func reset() {276 pending = PendingRemovals()277 pending.save(defaults)278 needsSync = false279 lastSync = nil280 lastError = nil281 }282283 /// Attend la fin des envois immédiats en cours.284 func settle() async {285 while !pushes.isEmpty {286 let t = pushes.removeFirst()287 await t.value288 }289 }290291 // MARK: Envois immédiats292293 private func handle(_ change: Library.Change) {294 guard isSignedIn() else { return }295 if syncing {296 switch change {297 case .favoriteSaved(let k), .searchSaved(let k): flightChanged.insert(k); flightRemoved.remove(k)298 case .favoriteRemoved(let k, _), .searchRemoved(let k, _): flightRemoved.insert(k); flightChanged.remove(k)299 }300 }301 switch change {302 case .favoriteSaved(let uid):303 if pending.favorites.removeValue(forKey: uid) != nil { pending.save(defaults) }304 guard let f = library.favorite(uid)?.remote else { return }305 push { try await $0.putFavorite(f) }306 case .favoriteRemoved(let uid, let at):307 let ms = Ms.from(at)308 pending.favorites[uid] = ms309 pending.save(defaults)310 push({ try await $0.deleteFavorite(uid) }, done: { me in311 if me.pending.favorites[uid] == ms { me.pending.favorites[uid] = nil; me.pending.save(me.defaults) }312 })313 case .searchSaved(let id):314 if pending.searches.removeValue(forKey: id) != nil { pending.save(defaults) }315 guard let s = library.allSearches().first(where: { $0.syncID == id })?.remote else { return }316 push { try await $0.putSearch(s) }317 case .searchRemoved(let id, let at):318 let ms = Ms.from(at)319 pending.searches[id] = ms320 pending.save(defaults)321 push({ try await $0.deleteSearch(id) }, done: { me in322 if me.pending.searches[id] == ms { me.pending.searches[id] = nil; me.pending.save(me.defaults) }323 })324 }325 }326327 private func push(_ call: @escaping @Sendable (AccountAPI) async throws -> Void, done: (@MainActor (SyncEngine) -> Void)? = nil) {328 let api = self.api329 let t = Task { @MainActor [weak self] in330 do {331 try await call(api)332 if let self { done?(self) }333 } catch {334 self?.failed(error)335 }336 }337 pushes.append(t)338 if pushes.count > 24 { pushes.removeFirst(pushes.count - 24) }339 }340341 private func failed(_ error: Error) {342 guard let e = error as? AccountError else { return }343 if e.isUnauthenticated { onUnauthenticated(); return }344 // tout autre échec (hors ligne, serveur) : la prochaine synchronisation rattrapera345 needsSync = true346 }347348 // MARK: Synchronisation complète349350 /// Synchronise si la dernière réussite date de plus de `minInterval` secondes (retour au premier plan).351 func syncIfStale(minInterval: TimeInterval = 20) async {352 if syncing { return }353 if let last = lastSync, Date().timeIntervalSince(last) < minInterval, !needsSync, pending.isEmpty { return }354 await sync()355 }356357 /// Envoie toute la mémoire locale et les retraits en attente ; la liste fusionnée devient la mémoire locale.358 func sync() async {359 guard isSignedIn() else { return }360 if syncing { again = true; return }361 syncing = true362 defer { syncing = false }363 var rounds = 0364 repeat {365 again = false366 rounds += 1367 do {368 try await round()369 lastSync = Date()370 lastError = nil371 needsSync = false372 } catch let e as AccountError {373 if e.isUnauthenticated { onUnauthenticated(); return }374 needsSync = true375 lastError = e.errorDescription376 return377 } catch {378 needsSync = true379 return380 }381 } while again && rounds < 3 && isSignedIn()382 }383384 private func round() async throws {385 flightChanged = []; flightRemoved = []386 let sent = pending387388 // favoris389 let favItems = library.allFavorites().map(\.remote)390 let favs = try await api.syncFavorites(items: favItems, removed: SyncLogic.favoriteRequest(local: favItems, pending: sent).removed)391 guard isSignedIn() else { return }392 let f = SyncLogic.settle(server: favs.items, id: \.uid, changed: flightChanged, removed: flightRemoved)393 library.replaceFavorites(with: f.apply, keep: f.keep.union(SyncLogic.refused(sent: favItems.map(\.uid), server: favs.items.map(\.uid), skipped: favs.skipped)))394 for (uid, at) in sent.favorites where pending.favorites[uid] == at { pending.favorites[uid] = nil }395 pending.save(defaults)396397 // recherches enregistrées398 let searchItems = library.allSearches().map(\.remote)399 let searches = try await api.syncSearches(items: searchItems, removed: SyncLogic.searchRequest(local: searchItems, pending: sent).removed)400 guard isSignedIn() else { return }401 let s = SyncLogic.settle(server: searches.items, id: \.id, changed: flightChanged, removed: flightRemoved)402 library.replaceSearches(with: s.apply, keep: s.keep.union(SyncLogic.refused(sent: searchItems.map(\.id), server: searches.items.map(\.id), skipped: searches.skipped)))403 for (id, at) in sent.searches where pending.searches[id] == at { pending.searches[id] = nil }404 pending.save(defaults)405406 if f.again || s.again { again = true }407 }408}409