SPB Git

Repository Public

Service.swift 10.9 KB 271 lines swift

1//2//  Fabri-Ka iOS v23//  File: FabriKa/Core/Models/Service.swift4//  Description: ce que le service dit de lui-même — identité et règles (`/api/version`), règle « public » et ce5//               qu'elle écarte (`/api/public`), état de la collecte (`/api/sources`), inscription d'une boutique.6//7//  Author: Simon-Pierre Boucher8//  Contact: contact@spboucher.ai9//1011import Foundation1213struct ServiceInfo: Codable, Sendable, Equatable {14    var api: Int15    var version: String?16    var ready: Bool17    var rules: [String]18    var products: Int?19    var stores: Int?20    var generatedAt: Double?21    var lastCollectAt: Double?2223    enum CodingKeys: String, CodingKey {24        case api, version, ready, rules, products, stores, generatedAt = "generated_at", lastCollectAt = "last_collect_at"25    }2627    init(from decoder: Decoder) throws {28        let c = try decoder.container(keyedBy: CodingKeys.self)29        api = c.int(.api) ?? 030        version = c.text(.version)31        ready = c.bool(.ready) ?? true32        rules = c.strings(.rules)33        products = c.int(.products)34        stores = c.int(.stores)35        generatedAt = c.dbl(.generatedAt)36        lastCollectAt = c.dbl(.lastCollectAt)37    }3839    private static let key = "service.info"4041    /// Dernière identité connue du service (chiffres de l'accueil et de « À propos » hors ligne).42    static var cached: ServiceInfo? {43        UserDefaults.standard.data(forKey: key).flatMap { try? JSONDecoder().decode(ServiceInfo.self, from: $0) }44    }4546    static func store(_ v: ServiceInfo) {47        if let d = try? JSONEncoder().encode(v) { UserDefaults.standard.set(d, forKey: key) }48    }49}5051/// Règle « public » publiée par le service, avec ce qu'elle écarte, mesuré.52struct PublicRules: Decodable, Sendable {53    struct Exclusion: Decodable, Hashable, Sendable, Identifiable {54        var reason: String55        var label: String56        var n: Int57        var id: String { reason }58        enum CodingKeys: String, CodingKey { case reason, label, n }59        init(from decoder: Decoder) throws {60            let c = try decoder.container(keyedBy: CodingKeys.self)61            reason = c.text(.reason) ?? ""62            label = c.text(.label) ?? reason63            n = c.int(.n) ?? 064        }65    }6667    var rules: [String]68    var inDatabase: Int?69    var active: Int?70    var publicProducts: Int?71    var excludedProducts: Int?72    var excluded: [Exclusion]73    var registry: Int?74    var publicStores: Int?75    var directoryOnly: Int?76    var withoutRegion: Int?77    var withoutPosition: Int?78    var meaning: String?7980    enum CodingKeys: String, CodingKey { case rules, products, excluded, stores, madeInQuebec = "made_in_quebec" }81    enum ProductKeys: String, CodingKey { case inDatabase = "in_database", active, isPublic = "public", excluded }82    enum StoreKeys: String, CodingKey {83        case registry, isPublic = "public", directoryOnly = "directory_only", withoutRegion = "without_region"84        case withoutPosition = "without_position"85    }86    enum MeaningKeys: String, CodingKey { case meaning }8788    init(from decoder: Decoder) throws {89        let c = try decoder.container(keyedBy: CodingKeys.self)90        rules = c.strings(.rules)91        excluded = c.list(.excluded)92        if let p = try? c.nestedContainer(keyedBy: ProductKeys.self, forKey: .products) {93            inDatabase = p.int(.inDatabase); active = p.int(.active); publicProducts = p.int(.isPublic); excludedProducts = p.int(.excluded)94        }95        if let s = try? c.nestedContainer(keyedBy: StoreKeys.self, forKey: .stores) {96            registry = s.int(.registry); publicStores = s.int(.isPublic); directoryOnly = s.int(.directoryOnly)97            withoutRegion = s.int(.withoutRegion); withoutPosition = s.int(.withoutPosition)98        }99        if let m = try? c.nestedContainer(keyedBy: MeaningKeys.self, forKey: .madeInQuebec) { meaning = m.text(.meaning) }100    }101}102103/// État de la collecte (`/api/sources`).104struct Sources: Decodable, Sendable {105    struct Platform: Decodable, Hashable, Sendable, Identifiable {106        var platform: String107        var followed: Int108        var failing: Int109        var publicStores: Int110        var publicProducts: Int111        var id: String { platform }112        enum CodingKeys: String, CodingKey {113            case platform, followed, failing, publicStores = "public_stores", publicProducts = "public_products"114        }115        init(from decoder: Decoder) throws {116            let c = try decoder.container(keyedBy: CodingKeys.self)117            platform = c.text(.platform) ?? "autre"118            followed = c.int(.followed) ?? 0; failing = c.int(.failing) ?? 0119            publicStores = c.int(.publicStores) ?? 0; publicProducts = c.int(.publicProducts) ?? 0120        }121        /// Nom d'affichage de la plateforme.122        var name: String {123            switch platform {124            case "shopify": "Shopify"125            case "woocommerce": "WooCommerce"126            case "wix": "Wix"127            case "square": "Square"128            case "squarespace": "Squarespace"129            default: platform.prefix(1).uppercased() + platform.dropFirst()130            }131        }132    }133134    var platforms: [Platform]135    var followed: Int?136    var failing: Int?137    var cadenceHours: Double?138    var lastCollectAt: Double?139    var syncs24h: Int?140    var added24h: Int?141    var removed24h: Int?142    var method: String?143    var listedBy: [String]144145    enum CodingKeys: String, CodingKey {146        case platforms, followed, failing, method, cadenceHours = "cadence_hours", lastCollectAt = "last_collect_at"147        case last24h = "last_24h", listedBy = "listed_by"148    }149    enum DayKeys: String, CodingKey { case syncs, added = "products_added", removed = "products_removed" }150151    init(from decoder: Decoder) throws {152        let c = try decoder.container(keyedBy: CodingKeys.self)153        platforms = c.list(.platforms)154        followed = c.int(.followed); failing = c.int(.failing)155        cadenceHours = c.dbl(.cadenceHours); lastCollectAt = c.dbl(.lastCollectAt)156        method = c.text(.method)157        listedBy = c.strings(.listedBy)158        if let d = try? c.nestedContainer(keyedBy: DayKeys.self, forKey: .last24h) {159            syncs24h = d.int(.syncs); added24h = d.int(.added); removed24h = d.int(.removed)160        }161    }162}163164/// Formulaire public d'inscription d'une boutique (`GET /api/inscriptions/form`).165struct InscriptionForm: Decodable, Sendable {166    struct Option: Decodable, Hashable, Sendable, Identifiable {167        var key: String168        var label: String169        var id: String { key }170    }171172    struct Field: Decodable, Sendable {173        var name: String174        var label: String175        var min: Int?176        var max: Int?177        var options: [Option]178        enum CodingKeys: String, CodingKey { case name, label, min, max, options }179        init(from decoder: Decoder) throws {180            let c = try decoder.container(keyedBy: CodingKeys.self)181            name = c.text(.name) ?? ""182            label = c.text(.label) ?? name183            min = c.int(.min); max = c.int(.max)184            options = c.list(.options)185        }186    }187188    var fields: [Field]189    var honeypot: String190    var stored: [String]191    var moderation: String?192    var perDay: Int?193194    enum CodingKeys: String, CodingKey { case fields, honeypot, stored, moderation, limits }195    enum LimitKeys: String, CodingKey { case perDay = "per_ip_24h" }196197    init(from decoder: Decoder) throws {198        let c = try decoder.container(keyedBy: CodingKeys.self)199        fields = c.list(.fields)200        honeypot = c.text(.honeypot) ?? "company_url"201        stored = c.strings(.stored)202        moderation = c.text(.moderation)203        if let l = try? c.nestedContainer(keyedBy: LimitKeys.self, forKey: .limits) { perDay = l.int(.perDay) }204    }205206    func field(_ name: String) -> Field? { fields.first { $0.name == name } }207    var categories: [Option] { field("category")?.options ?? [] }208    var consentLabel: String? { field("consent")?.label }209}210211/// Demande d'inscription saisie dans l'app. Rien n'est gardé sur l'appareil après l'envoi.212struct InscriptionRequest: Sendable, Equatable {213    var name = ""214    var category = ""215    var website = ""216    var description = ""217    var address = ""218    var email = ""219    var phone = ""220    var social = ""221    var consent = false222223    static let descriptionMin = 40224    static let descriptionMax = 2000225226    private func trimmed(_ s: String) -> String { s.trimmingCharacters(in: .whitespacesAndNewlines) }227228    /// Premier manque, dit en clair ; nil si la demande peut partir. Le service revalide tout.229    var problem: String? {230        if trimmed(name).count < 2 { return "Écrivez le nom de la boutique." }231        if category.isEmpty { return "Choisissez la spécialité de la boutique." }232        let site = trimmed(website)233        if site.count < 4 || !site.contains(".") || site.contains(" ") { return "Écrivez l'adresse de la boutique en ligne, par exemple atelierdulac.ca." }234        let d = trimmed(description).count235        if d < InscriptionRequest.descriptionMin { return "Décrivez ce que la boutique fabrique ou vend en au moins \(InscriptionRequest.descriptionMin) caractères (il en manque \(InscriptionRequest.descriptionMin - d))." }236        if d > InscriptionRequest.descriptionMax { return "La description dépasse \(Fmt.group(InscriptionRequest.descriptionMax)) caractères." }237        let mail = trimmed(email), tel = trimmed(phone)238        if mail.isEmpty && tel.isEmpty { return "Laissez un courriel ou un téléphone pour qu'on puisse vous répondre." }239        if !mail.isEmpty, !(mail.contains("@") && mail.contains(".")) { return "Le courriel semble incomplet." }240        if !consent { return "Cochez l'attestation pour envoyer la demande." }241        return nil242    }243244    /// Corps JSON de `POST /api/inscriptions`. Le pot de miel (`company_url`) existe et reste vide.245    func body(honeypot: String = "company_url") -> Data {246        let socials = trimmed(social).isEmpty ? [String]() : [trimmed(social)]247        let obj: [String: Any] = [248            "name": trimmed(name), "category": category, "website": trimmed(website), "description": trimmed(description),249            "address": trimmed(address), "email": trimmed(email), "phone": trimmed(phone), "socials": socials,250            "consent": consent, honeypot: "",251        ]252        return (try? JSONSerialization.data(withJSONObject: obj, options: [.sortedKeys])) ?? Data()253    }254}255256struct InscriptionResponse: Decodable, Sendable {257    var status: String?258    var id: Int?259    var alreadyListed: Bool260    var duplicate: Bool261    var message: String?262263    enum CodingKeys: String, CodingKey { case status, id, message, duplicate, alreadyListed = "already_listed" }264    init(from decoder: Decoder) throws {265        let c = try decoder.container(keyedBy: CodingKeys.self)266        status = c.text(.status); id = c.int(.id); message = c.text(.message)267        duplicate = c.bool(.duplicate) ?? false268        alreadyListed = c.bool(.alreadyListed) ?? false269    }270}271
Files main
Menu

Theme