SPB Git

Repository Public

Library.swift 10.7 KB 265 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : Vrai-Prix iOS9// File             : VraiPrix/Core/Store/Library.swift10// Description      : ce qui reste sur l'appareil — favoris, comparateur, fiches11//                    récentes, recherches récentes. Aucun compte, aucune12//                    synchronisation : un fichier JSON dans Application13//                    Support.14// Module           : VraiPrix15// Repository       : https://git.spboucher.ai/vrai-prix-ios-v316// Project Website  : https://www.vrai-prix.com17// Created          : 2026-11-2618// 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 Foundation93import Observation9495/// Propriété mémorisée (unité du rôle ou annonce à vendre) avec ce qu'il faut pour l'afficher hors ligne.96struct SavedProperty: Codable, Sendable, Hashable, Identifiable {97    enum Kind: String, Codable, Sendable { case unit, listing }98    var kind: Kind99    /// identifiant de l'unité (id_provinc) ou uid de l'annonce100    var ref: String101    var title: String102    var subtitle: String103    var value: Double?104    var low: Double?105    var high: Double?106    /// prix demandé (annonce) ou dernier prix vendu (unité)107    var price: Double?108    var priceLabel: String?109    var confidence: String?110    var year: Int?111    var areaM2: Double?112    var landM2: Double?113    var roll: Double?114    var image: String?115    /// lecture du prix calculée par le service au moment de la consultation116    var verdictKey: String?117    var ecartPct: Double?118    var dansFourchette: Bool?119    // --- API v3 (absents des propriétés mémorisées par la version 2 : elles se lisent comme avant) ---120    /// régime de la valeur (`valeur`, `ordre`, `abstention`, `hors_champ`)121    var regime: String?122    /// motif d'un ordre de grandeur ou d'une absence de valeur123    var motifCode: String?124    var motifLibelle: String?125    /// position du prix face à l'intervalle, rendue par le moteur126    var positionKey: String?127    var savedAt: Date = .now128129    var id: String { kind.rawValue + ":" + ref }130    var route: Route { kind == .unit ? .property(ref) : .listing(ref) }131    /// lecture mémorisée du service, sinon la même règle appliquée aux nombres gardés132    var reading: Reading? {133        Reading.of(verdict: verdictKey, ecartPct: ecartPct, dansFourchette: dansFourchette, price: price, value: value, low: low, high: high)134    }135    var gapPct: Double? { reading?.gapPct }136137    /// La valeur telle que l'API v3 l'a rendue ; nil pour une propriété mémorisée sous l'API 2.138    var valueBlock: ValueBlock? {139        guard let regime, let status = ValueStatus(rawValue: regime) else { return nil }140        return ValueBlock(status: status, value: value, low: low, high: high,141                          motif: motifCode.map { Motif(code: $0, libelle: motifLibelle ?? "") })142    }143    var position: PricePosition? { positionKey.flatMap(PricePosition.init(rawValue:)) }144}145146@MainActor147@Observable148final class Library {149    private struct Disk: Codable {150        var favorites: [SavedProperty] = []151        var compare: [SavedProperty] = []152        var recents: [SavedProperty] = []153        var searches: [SearchHitRecord] = []154    }155156    struct SearchHitRecord: Codable, Hashable, Identifiable, Sendable {157        var id: String158        var title: String159        var subtitle: String160    }161162    /// 4 sous l'API 2 ; 8 sous l'API v3 (comparateur à axe commun)163    static var compareLimit: Int { ServiceLevel.current == .v3 ? 8 : 4 }164    static let recentLimit = 24165166    private(set) var favorites: [SavedProperty] = []167    private(set) var compare: [SavedProperty] = []168    private(set) var recents: [SavedProperty] = []169    private(set) var searches: [SearchHitRecord] = []170171    private let file: URL?172173    init(inMemory: Bool = false) {174        if inMemory {175            file = nil176        } else {177            let dir = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0]178            try? FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)179            file = dir.appending(path: "bibliotheque.json")180            if let f = file, let d = try? Data(contentsOf: f), let disk = try? Library.decoder.decode(Disk.self, from: d) {181                favorites = disk.favorites; compare = disk.compare; recents = disk.recents; searches = disk.searches182            }183        }184    }185186    private static let decoder: JSONDecoder = { let d = JSONDecoder(); d.dateDecodingStrategy = .iso8601; return d }()187    private static let encoder: JSONEncoder = { let e = JSONEncoder(); e.dateEncodingStrategy = .iso8601; return e }()188189    private func save() {190        guard let file else { return }191        let disk = Disk(favorites: favorites, compare: compare, recents: recents, searches: searches)192        if let d = try? Library.encoder.encode(disk) { try? d.write(to: file, options: .atomic) }193    }194195    // MARK: Favoris196197    func isFavorite(_ id: String) -> Bool { favorites.contains { $0.id == id } }198199    /// Ajoute ou retire ; renvoie vrai si la propriété est maintenant en favori.200    @discardableResult201    func toggleFavorite(_ p: SavedProperty) -> Bool {202        if let i = favorites.firstIndex(where: { $0.id == p.id }) {203            favorites.remove(at: i); save()204            if file != nil { SpotlightIndex.index(p, favorite: false) }   // redevient une fiche consultée (30 jours)205            return false206        }207        var q = p; q.savedAt = .now208        favorites.insert(q, at: 0); save()209        if file != nil { SpotlightIndex.index(q, favorite: true) }210        return true211    }212213    func removeFavorite(_ id: String) { favorites.removeAll { $0.id == id }; save() }214215    // MARK: Comparateur216217    func isCompared(_ id: String) -> Bool { compare.contains { $0.id == id } }218219    enum CompareResult { case added, removed, full }220221    @discardableResult222    func toggleCompare(_ p: SavedProperty) -> CompareResult {223        if let i = compare.firstIndex(where: { $0.id == p.id }) { compare.remove(at: i); save(); return .removed }224        guard compare.count < Library.compareLimit else { return .full }225        compare.append(p); save(); return .added226    }227228    func clearCompare() { compare = []; save() }229230    // MARK: Récents231232    /// Mémorise une fiche consultée et rafraîchit le favori ou la comparaison correspondants.233    func visit(_ p: SavedProperty) {234        recents.removeAll { $0.id == p.id }235        recents.insert(p, at: 0)236        if recents.count > Library.recentLimit { recents = Array(recents.prefix(Library.recentLimit)) }237        if let i = favorites.firstIndex(where: { $0.id == p.id }) { var q = p; q.savedAt = favorites[i].savedAt; favorites[i] = q }238        if let i = compare.firstIndex(where: { $0.id == p.id }) { compare[i] = p }239        save()240    }241242    func clearRecents() { recents = []; save() }243244    func remember(search hit: SearchHit) {245        searches.removeAll { $0.id == hit.id }246        searches.insert(SearchHitRecord(id: hit.id, title: hit.title, subtitle: hit.subtitle), at: 0)247        if searches.count > 8 { searches = Array(searches.prefix(8)) }248        save()249    }250251    func remember(searchID id: String, title: String, subtitle: String) {252        searches.removeAll { $0.id == id }253        searches.insert(SearchHitRecord(id: id, title: title, subtitle: subtitle), at: 0)254        if searches.count > 8 { searches = Array(searches.prefix(8)) }255        save()256    }257258    func clearSearches() { searches = []; save() }259260    func eraseAll() {261        favorites = []; compare = []; recents = []; searches = []; save()262        if file != nil { SpotlightIndex.removeAll() }263    }264}265
Files main
Menu

Theme