SPB Git

Repository Public

Catalog.swift 18.6 KB 528 lines swift

1//2//  Fabri-Ka iOS v23//  File: FabriKa/Core/Models/Catalog.swift4//  Description: recherche unifiée — filtres, tris, page de résultats, facettes, points de carte, suggestions,5//               arbre des catégories, annuaire des boutiques.6//7//  Author: Simon-Pierre Boucher8//  Contact: contact@spboucher.ai9//1011import CoreLocation12import Foundation1314enum SortOrder: String, CaseIterable, Identifiable, Sendable, Hashable {15    case relevance = "pertinence", recent, priceAsc = "price_asc", priceDesc = "price_desc", discount, title, random1617    var id: String { rawValue }18    var label: String {19        switch self {20        case .relevance: "Pertinence"21        case .recent: "Vus récemment pour la première fois"22        case .priceAsc: "Prix croissant"23        case .priceDesc: "Prix décroissant"24        case .discount: "Plus fort rabais"25        case .title: "Nom, de A à Z"26        case .random: "Au hasard"27        }28    }29    var short: String {30        switch self {31        case .relevance: "Pertinence"32        case .recent: "Récents"33        case .priceAsc: "Prix croissant"34        case .priceDesc: "Prix décroissant"35        case .discount: "Rabais"36        case .title: "Nom"37        case .random: "Au hasard"38        }39    }40}4142/// Filtres d'une recherche de produits. Valeur de navigation (`Route.search`).43struct SearchFilters: Hashable, Sendable {44    var q = ""45    var category: String?46    var categoryName: String?47    var subcategory: String?48    var subcategoryName: String?49    var region: String?50    var regionName: String?51    var city: String?52    var cityName: String?53    var store: String?54    var storeName: String?55    var priceMin: Double?56    var priceMax: Double?57    var inStock = false58    var new = false59    var daysMax: Int?60    var onSale = false61    var madeInQuebec = false62    /// nil : le tri par défaut du service (pertinence avec un texte, récents sinon)63    var sort: SortOrder?64    var seed: Int?6566    var trimmedQuery: String { q.trimmingCharacters(in: .whitespacesAndNewlines) }6768    /// Tri effectif, pour l'affichage.69    var effectiveSort: SortOrder { sort ?? (trimmedQuery.isEmpty ? .recent : .relevance) }7071    /// Paramètres de `/api/search`, `/api/count` et `/api/facets`.72    func query(page: Int = 1, pageSize: Int = 24, facets: Bool = false, points: Bool = false) -> [String: String?] {73        var p: [String: String?] = [74            "q": trimmedQuery, "category": category, "subcategory": subcategory, "region": region, "city": city, "store": store,75            "price_min": priceMin.map(SearchFilters.number), "price_max": priceMax.map(SearchFilters.number),76            "in_stock": inStock ? "1" : nil, "new": new ? "1" : nil, "days_max": daysMax.map(String.init),77            "on_sale": onSale ? "1" : nil, "made_in_quebec": madeInQuebec ? "1" : nil,78            "sort": sort?.rawValue, "seed": seed.map(String.init),79        ]80        if page > 1 { p["page"] = String(page) }81        p["page_size"] = String(pageSize)82        if facets { p["facets"] = "1" }83        if points { p["points"] = "1" }84        return p85    }8687    private static func number(_ v: Double) -> String {88        v == v.rounded() ? String(Int(v)) : String(format: "%.2f", v)89    }9091    /// Nombre de filtres actifs hors texte, catégorie d'entrée et tri (pastille du bouton « Filtres »).92    var activeCount: Int {93        [subcategory != nil, region != nil, city != nil, store != nil, priceMin != nil || priceMax != nil, inStock, new || daysMax != nil,94         onSale, madeInQuebec].filter { $0 }.count95    }9697    var isEmpty: Bool { trimmedQuery.isEmpty && category == nil && activeCount == 0 }9899    /// Titre de la page de résultats.100    var title: String {101        if !trimmedQuery.isEmpty { return "« \(trimmedQuery) »" }102        if let s = subcategoryName { return s }103        if let c = categoryName { return c }104        if let s = storeName { return s }105        if let c = cityName { return c }106        if let r = regionName { return r }107        if new || daysMax != nil { return "Nouveautés" }108        if onSale { return "Prix réduits" }109        return "Tous les produits"110    }111112    /// Libellé de la fourchette de prix : « 25 $ à 50 $ », « 1 000 $ et plus ».113    var priceLabel: String? {114        switch (priceMin, priceMax) {115        case let (a?, b?): Fmt.shortPrice(a) + " à " + Fmt.shortPrice(b)116        case let (a?, nil): Fmt.shortPrice(a) + " et plus"117        case let (nil, b?): "moins de " + Fmt.shortPrice(b)118        default: nil119        }120    }121}122123/// Entrée d'une facette : catégorie (`key`), sous-catégorie ou lieu (`slug`), boutique (`id`).124struct FacetItem: Decodable, Hashable, Sendable, Identifiable {125    var key: String126    var slug: String127    var label: String128    var n: Int129    var stores: Int?130    var category: String?131    var sharePct: Double?132    var vsQuebec: Double?133134    var id: String { key }135136    enum CodingKeys: String, CodingKey {137        case key, slug, id, label, name, n, stores, category, products, sharePct = "share_pct", vsQuebec = "vs_quebec"138    }139140    init(from decoder: Decoder) throws {141        let c = try decoder.container(keyedBy: CodingKeys.self)142        guard let k = c.text(.key) ?? c.text(.id) ?? c.text(.slug) ?? c.text(.name) else {143            throw DecodingError.dataCorruptedError(forKey: .key, in: c, debugDescription: "facette sans clé")144        }145        key = k146        slug = c.text(.slug) ?? k147        label = c.text(.label) ?? c.text(.name) ?? k148        n = c.int(.n) ?? c.int(.products) ?? 0149        stores = c.int(.stores)150        category = c.text(.category)151        sharePct = c.dbl(.sharePct)152        vsQuebec = c.dbl(.vsQuebec)153    }154}155156struct PriceBucket: Decodable, Hashable, Sendable, Identifiable {157    var min: Double158    var max: Double?159    var n: Int160    var id: Double { min }161162    enum CodingKeys: String, CodingKey { case min, max, n }163    init(from decoder: Decoder) throws {164        let c = try decoder.container(keyedBy: CodingKeys.self)165        min = c.dbl(.min) ?? 0166        max = c.dbl(.max)167        n = c.int(.n) ?? 0168    }169170    var label: String {171        guard let max else { return Fmt.shortPrice(min) + " et plus" }172        return min <= 0 ? "moins de " + Fmt.shortPrice(max) : Fmt.shortPrice(min) + " à " + Fmt.shortPrice(max)173    }174}175176/// Comptes par dimension ; chaque dimension est comptée sans son propre filtre.177struct Facets: Decodable, Sendable {178    var categories: [FacetItem]179    var subcategories: [FacetItem]180    var regions: [FacetItem]181    var regionUnknown: Int?182    var cities: [FacetItem]183    var stores: [FacetItem]184    var storesTotal: Int?185    var priceMin: Double?186    var priceMax: Double?187    var priceMedian: Double?188    var buckets: [PriceBucket]189    var origins: [FacetItem]190    var madeInQuebec: Int?191    var inStock: Int?192    var new: Int?193    var onSale: Int?194    var total: Int?195196    enum CodingKeys: String, CodingKey {197        case categories, subcategories, regions, cities, stores, price, origins, new, total198        case regionUnknown = "region_unknown", storesTotal = "stores_total", madeInQuebec = "made_in_quebec"199        case inStock = "in_stock", onSale = "on_sale"200    }201    enum PriceKeys: String, CodingKey { case min, max, median, buckets }202203    init(from decoder: Decoder) throws {204        let c = try decoder.container(keyedBy: CodingKeys.self)205        categories = c.list(.categories)206        subcategories = c.list(.subcategories)207        regions = c.list(.regions)208        regionUnknown = c.int(.regionUnknown)209        cities = c.list(.cities)210        stores = c.list(.stores)211        storesTotal = c.int(.storesTotal)212        if let p = try? c.nestedContainer(keyedBy: PriceKeys.self, forKey: .price) {213            priceMin = p.dbl(.min); priceMax = p.dbl(.max); priceMedian = p.dbl(.median); buckets = p.list(.buckets)214        } else {215            buckets = []216        }217        origins = c.list(.origins)218        madeInQuebec = c.int(.madeInQuebec)219        inStock = c.int(.inStock)220        new = c.int(.new)221        onSale = c.int(.onSale)222        total = c.int(.total)223    }224}225226/// Point de carte : une boutique. Format du service : `[store_id, lat, lng, n, name, city]`.227struct MapPoint: Decodable, Hashable, Sendable, Identifiable {228    var storeId: String229    var lat: Double230    var lng: Double231    var n: Int232    var name: String233    var city: String?234235    var id: String { storeId }236    var coordinate: CLLocationCoordinate2D { CLLocationCoordinate2D(latitude: lat, longitude: lng) }237238    init(storeId: String, lat: Double, lng: Double, n: Int, name: String, city: String? = nil) {239        self.storeId = storeId; self.lat = lat; self.lng = lng; self.n = n; self.name = name; self.city = city240    }241242    init(from decoder: Decoder) throws {243        var c = try decoder.unkeyedContainer()244        storeId = try c.decode(String.self)245        lat = try c.decode(Double.self)246        lng = try c.decode(Double.self)247        n = (try? c.decode(Int.self)) ?? 0248        name = (try? c.decode(String.self)) ?? storeId249        city = c.isAtEnd ? nil : (try? c.decodeIfPresent(String.self)) ?? nil250    }251}252253/// Page de résultats de `/api/search` (aussi le catalogue d'une boutique).254struct SearchPage: Decodable, Sendable {255    struct Correction: Decodable, Hashable, Sendable {256        var typed: String257        var understood: [String]258        enum CodingKeys: String, CodingKey { case typed, understood }259        init(from decoder: Decoder) throws {260            let c = try decoder.container(keyedBy: CodingKeys.self)261            typed = c.text(.typed) ?? ""262            understood = c.strings(.understood)263        }264    }265266    var total: Int267    var page: Int268    var pages: Int269    var sort: String?270    var diversity: Int?271    var storesTotal: Int?272    var products: [Product]273    var corrections: [Correction]274    var relaxed: Bool275    var points: [MapPoint]276    var unpositioned: Int?277    var facets: Facets?278279    enum CodingKeys: String, CodingKey {280        case total, page, pages, sort, diversity, products, search, points, unpositioned, facets, storesTotal = "stores_total"281    }282    enum SearchKeys: String, CodingKey { case corrections, relaxed }283284    init(from decoder: Decoder) throws {285        let c = try decoder.container(keyedBy: CodingKeys.self)286        products = c.list(.products)287        total = c.int(.total) ?? products.count288        page = c.int(.page) ?? 1289        pages = c.int(.pages) ?? 1290        sort = c.text(.sort)291        diversity = c.int(.diversity)292        storesTotal = c.int(.storesTotal)293        if let s = try? c.nestedContainer(keyedBy: SearchKeys.self, forKey: .search) {294            corrections = s.list(.corrections, Correction.self).filter { !$0.understood.isEmpty }295            relaxed = s.bool(.relaxed) ?? false296        } else {297            corrections = []; relaxed = false298        }299        points = c.list(.points)300        unpositioned = c.int(.unpositioned)301        facets = c.opt(.facets)302    }303304    /// « Compris : bracelet » — ce que le service a lu d'un mot mal tapé.305    var understood: String? {306        guard !corrections.isEmpty else { return nil }307        return corrections.compactMap { $0.understood.first }.joined(separator: ", ")308    }309}310311struct CountResult: Decodable, Sendable {312    var total: Int313    var stores: Int?314}315316/// Autocomplétion (`/api/suggest`).317struct Suggestions: Decodable, Sendable {318    struct Place: Decodable, Hashable, Sendable, Identifiable {319        var name: String320        var slug: String321        var n: Int?322        var id: String { slug }323        enum CodingKeys: String, CodingKey { case name, slug, n, stores, label }324        init(from decoder: Decoder) throws {325            let c = try decoder.container(keyedBy: CodingKeys.self)326            guard let s = c.text(.slug), let nm = c.text(.name) ?? c.text(.label) else {327                throw DecodingError.dataCorruptedError(forKey: .slug, in: c, debugDescription: "lieu incomplet")328            }329            slug = s; name = nm; n = c.int(.n) ?? c.int(.stores)330        }331    }332333    var q: String334    var categories: [FacetItem]335    var subcategories: [FacetItem]336    var stores: [Store]337    var cities: [Place]338    var regions: [Place]339    var terms: [String]340    var products: [Product]341    var productsTotal: Int?342343    enum CodingKeys: String, CodingKey {344        case q, categories, subcategories, stores, cities, regions, terms, products, productsTotal = "products_total"345    }346347    init(from decoder: Decoder) throws {348        let c = try decoder.container(keyedBy: CodingKeys.self)349        q = c.text(.q) ?? ""350        categories = c.list(.categories)351        subcategories = c.list(.subcategories)352        stores = c.list(.stores)353        cities = c.list(.cities)354        regions = c.list(.regions)355        terms = c.strings(.terms)356        products = c.list(.products)357        productsTotal = c.int(.productsTotal)358    }359360    var isEmpty: Bool {361        categories.isEmpty && subcategories.isEmpty && stores.isEmpty && cities.isEmpty && regions.isEmpty && terms.isEmpty && products.isEmpty362    }363}364365/// Catégorie et ses sous-catégories (`/api/categories`, `/api/discover`).366struct CategoryNode: Decodable, Hashable, Sendable, Identifiable {367    var key: String368    var label: String369    var slug: String370    var n: Int371    var stores: Int?372    var new: Int?373    var images: [String]374    var subcategories: [FacetItem]375376    var id: String { key }377    var icon: String { CategoryIcon.name(for: key) }378379    enum CodingKeys: String, CodingKey { case key, label, slug, n, stores, new, images, subcategories }380381    init(from decoder: Decoder) throws {382        let c = try decoder.container(keyedBy: CodingKeys.self)383        guard let k = c.text(.key) else {384            throw DecodingError.dataCorruptedError(forKey: .key, in: c, debugDescription: "catégorie sans clé")385        }386        key = k387        label = c.text(.label) ?? k388        slug = c.text(.slug) ?? k389        n = c.int(.n) ?? 0390        stores = c.int(.stores)391        new = c.int(.new)392        images = c.strings(.images)393        subcategories = c.list(.subcategories)394    }395}396397struct Categories: Decodable, Sendable {398    var total: Int?399    var categories: [CategoryNode]400    enum CodingKeys: String, CodingKey { case total, categories }401    init(from decoder: Decoder) throws {402        let c = try decoder.container(keyedBy: CodingKeys.self)403        total = c.int(.total)404        categories = c.list(.categories)405    }406}407408/// Filtres de l'annuaire des boutiques (`/api/boutiques`).409struct StoreFilters: Hashable, Sendable {410    enum Sort: String, CaseIterable, Identifiable, Sendable {411        case size, name, new, recent412        var id: String { rawValue }413        var label: String {414            switch self {415            case .size: "Plus grands catalogues"416            case .name: "Nom"417            case .new: "Plus de nouveautés"418            case .recent: "Arrivées récemment"419            }420        }421    }422423    var q = ""424    var region: String?425    var regionName: String?426    var category: String?427    var categoryName: String?428    var sort: Sort = .size429430    var trimmedQuery: String { q.trimmingCharacters(in: .whitespacesAndNewlines) }431    var hasFilter: Bool { region != nil || category != nil }432433    func query(page: Int = 1, pageSize: Int = 30, points: Bool = false) -> [String: String?] {434        var p: [String: String?] = ["q": trimmedQuery, "region": region, "category": category,435                                    "sort": sort == .size ? nil : sort.rawValue, "page_size": String(pageSize)]436        if page > 1 { p["page"] = String(page) }437        if points { p["points"] = "1" }438        // fiches « annuaire » : seulement quand on cherche un nom439        if !trimmedQuery.isEmpty, page == 1 { p["directory"] = "1" }440        return p441    }442}443444/// Fiche « annuaire » : boutique répertoriée, sans catalogue suivi.445struct DirectoryEntry: Decodable, Hashable, Sendable, Identifiable {446    var id: String447    var name: String448    var url: String?449    var region: String?450    var city: String?451452    enum CodingKeys: String, CodingKey { case id, name, url, region, city }453    init(from decoder: Decoder) throws {454        let c = try decoder.container(keyedBy: CodingKeys.self)455        guard let i = c.text(.id) else {456            throw DecodingError.dataCorruptedError(forKey: .id, in: c, debugDescription: "fiche sans identifiant")457        }458        id = i; name = c.text(.name) ?? i; url = c.text(.url); region = c.text(.region); city = c.text(.city)459    }460}461462struct StoresPage: Decodable, Sendable {463    var total: Int464    var page: Int465    var pages: Int466    var productsTotal: Int?467    var stores: [Store]468    var points: [MapPoint]469    var unpositioned: Int?470    var directory: [DirectoryEntry]471    var directoryTotal: Int?472473    enum CodingKeys: String, CodingKey {474        case total, page, pages, stores, points, unpositioned, directory475        case productsTotal = "products_total", directoryTotal = "directory_total"476    }477478    init(from decoder: Decoder) throws {479        let c = try decoder.container(keyedBy: CodingKeys.self)480        stores = c.list(.stores)481        total = c.int(.total) ?? stores.count482        page = c.int(.page) ?? 1483        pages = c.int(.pages) ?? 1484        productsTotal = c.int(.productsTotal)485        points = c.list(.points)486        unpositioned = c.int(.unpositioned)487        directory = c.list(.directory)488        directoryTotal = c.int(.directoryTotal)489    }490}491492/// Lecture par lot (`GET /api/products?ids=`), pour les favoris de l'appareil.493struct ProductBatch: Decodable, Sendable {494    struct Unavailable: Decodable, Hashable, Sendable {495        var uid: String496        /// `gone` (retiré par la boutique), `unlisted` (écarté des listes), `unknown`497        var status: String498        enum CodingKeys: String, CodingKey { case uid, status }499        init(from decoder: Decoder) throws {500            let c = try decoder.container(keyedBy: CodingKeys.self)501            uid = c.text(.uid) ?? ""502            status = c.text(.status) ?? "unknown"503        }504    }505506    /// Carte rendue pour un identifiant demandé (un produit regroupé rend son représentant avec `requested_uid`).507    struct Entry: Decodable, Sendable {508        var product: Product509        var requestedUID: String510        enum CodingKeys: String, CodingKey { case requestedUID = "requested_uid" }511        init(from decoder: Decoder) throws {512            product = try Product(from: decoder)513            let c = try decoder.container(keyedBy: CodingKeys.self)514            requestedUID = c.text(.requestedUID) ?? product.uid515        }516    }517518    var entries: [Entry]519    var unavailable: [Unavailable]520521    enum CodingKeys: String, CodingKey { case products, unavailable }522    init(from decoder: Decoder) throws {523        let c = try decoder.container(keyedBy: CodingKeys.self)524        entries = c.list(.products)525        unavailable = c.list(.unavailable, Unavailable.self).filter { !$0.uid.isEmpty }526    }527}528
Files main
Menu

Theme