SPB Git

Repository Public

Samples+Work.swift 34.9 KB 468 lines swift

1// SP Notes Core2// File: Sources/SPNotesFeaturesCatalog/Samples+Work.swift3// Description: Sample data of the « Work » area (tasks, inbox, a database, search) for the catalogue and the tests:4//              tasks and pages in the fake backend, and three small stateful fakes scripted with `stub` — the inbox with5//              its Smart Inbox, one database with its six views (shapes of API-NEXT: info, properties, views, rows,6//              query, writes) and the server search. Nothing here is linked in an app.7//8// Author: Simon-Pierre Boucher9// Contact: contact@spboucher.ai10import Foundation11import SPNotesAPI12import SPNotesDocument13import SPNotesSync14import SPNotesTestSupport1516extension FeatureSamples {17    // Stable ids of the samples (tests and catalogue entries refer to them).18    public static let workDatabaseId = "6a1f0c5e-1a11-4b6e-9a10-000000000d01"19    public static let workDatabasePageId = "6a1f0c5e-1a11-4b6e-9a10-000000000d02"20    public static let workProjectPageId = "6a1f0c5e-1a11-4b6e-9a10-0000000000a1"21    public static let workNotePageId = "6a1f0c5e-1a11-4b6e-9a10-0000000000a2"22    public static let workJournalPageId = "6a1f0c5e-1a11-4b6e-9a10-0000000000a3"23    public static let workInboxSuggestedId = "6a1f0c5e-1a11-4b6e-9a10-0000000001b1"24    public static let workInboxPlainId = "6a1f0c5e-1a11-4b6e-9a10-0000000001b2"2526    static func installWork(on world: FeatureWorld) {27        installWorkPages(on: world.fake)28        installWorkTasks(on: world.fake)29        SampleInboxServer().install(on: world.fake)30        SampleDatabaseServer().install(on: world.fake)31        installWorkSearch(on: world.fake)32    }3334    /// An instant `offset` days from the sample "now" (UTC day), at `hour` UTC.35    static func workDay(_ offset: Int, hour: Int = 12) -> Date {36        var calendar = Calendar(identifier: .gregorian)37        calendar.timeZone = TimeZone(identifier: "UTC")!38        let start = calendar.startOfDay(for: now)39        return calendar.date(byAdding: .hour, value: hour, to: calendar.date(byAdding: .day, value: offset, to: start)!)!40    }4142    static func workDocument(_ blocks: [(id: String, type: String, text: String)]) -> Data {43        let content: [[String: Any]] = blocks.map { block in44            var attrs: [String: Any] = ["id": block.id]45            if block.type == "heading" { attrs["level"] = 2 }46            return ["type": block.type, "attrs": attrs, "content": [["type": "text", "text": block.text]]]47        }48        return try! JSONSerialization.data(withJSONObject: ["type": "doc", "content": content], options: [.sortedKeys])49    }5051    private static func installWorkPages(on fake: FakeBackend) {52        fake.webCreatePage(id: workProjectPageId, title: "Refinancement du triplex", content: workDocument([53            ("h-contexte", "heading", "Contexte"),54            ("p-contexte", "paragraph", "Le triplex de la rue Laurel arrive à échéance en mars. La banque propose un taux fixe de cinq ans."),55            ("h-decision", "heading", "Décision"),56            ("p-decision", "paragraph", "Nous retenons le taux fixe ; la garantie de taux doit être prolongée de 90 jours."),57        ]), section: "projects", tags: ["refinancement", "triplex"])58        fake.webCreatePage(id: workNotePageId, title: "Notes de lecture — volatilité conditionnelle", content: workDocument([59            ("h-garch", "heading", "Modèles GARCH"),60            ("p-garch", "paragraph", "La volatilité conditionnelle se regroupe : un choc de taux se propage sur plusieurs séances."),61        ]), section: "research", tags: ["finance"])62        fake.webCreatePage(id: workJournalPageId, title: "Journal du 18 novembre", content: workDocument([63            ("p-journal", "paragraph", "Appel avec la banque : le taux garanti tient jusqu'en février. Prochaine étape, l'évaluation du triplex."),64        ]), section: "notes")65    }6667    private static func installWorkTasks(on fake: FakeBackend) {68        fake.webCreateTask(title: "Envoyer les documents à la banque", pageId: workProjectPageId, dueAt: workDay(-2), priority: "high")69        fake.webCreateTask(title: "Relire le chapitre sur la volatilité", pageId: workNotePageId, dueAt: workDay(0), status: "doing")70        fake.webCreateTask(title: "Confirmer la visite de l'évaluateur", dueAt: workDay(0), priority: "high")71        fake.webCreateTask(title: "Préparer le plan de cours de janvier", dueAt: workDay(4))72        fake.webCreateTask(title: "Mettre à jour le budget des travaux", dueAt: workDay(11), priority: "low")73        fake.webCreateTask(title: "Classer les reçus du trimestre")74        fake.webCreateTask(title: "Signer l'offre de financement", pageId: workProjectPageId, dueAt: workDay(-6), status: "done")75    }7677    private static func installWorkSearch(on fake: FakeBackend) {78        struct Passage { var pageId: String; var title: String; var section: String; var heading: String?; var blockId: String?; var text: String }79        let passages = [80            Passage(pageId: workProjectPageId, title: "Refinancement du triplex", section: "projects", heading: "Décision", blockId: "p-decision",81                    text: "Nous retenons le taux fixe ; la garantie de taux doit être prolongée de 90 jours."),82            Passage(pageId: workNotePageId, title: "Notes de lecture — volatilité conditionnelle", section: "research", heading: "Modèles GARCH", blockId: "p-garch",83                    text: "La volatilité conditionnelle se regroupe : un choc de taux se propage sur plusieurs séances."),84            Passage(pageId: "6a1f0c5e-1a11-4b6e-9a10-0000000000a9", title: "Offre de la banque (archive web)", section: "documents", heading: nil, blockId: "p-offre",85                    text: "Taux fixe 5 ans à 4,89 %, garantie de taux de 90 jours, pénalité de trois mois d'intérêts."),86        ]87        fake.stub("GET", path: "^/api/search$") { request in88            let query = (request.query["q"] ?? "").lowercased()89            let tokens = query.split(separator: " ").map(String.init).filter { $0.count > 1 }90            var hits: [JSONValue] = []91            for passage in passages {92                let lower = passage.text.lowercased()93                guard let token = tokens.first(where: { lower.contains($0) || passage.title.lowercased().contains($0) }) else { continue }94                var snippet = passage.text95                if let range = snippet.range(of: token, options: .caseInsensitive) {96                    snippet = snippet.replacingCharacters(in: range, with: "\u{1}" + snippet[range] + "\u{2}")97                }98                hits.append(.object([99                    "chunkId": .string("page:" + passage.pageId), "pageId": .string(passage.pageId), "sourceType": "page", "sourceId": .string(passage.pageId),100                    "title": .string(passage.title), "icon": .null, "section": .string(passage.section), "heading": passage.heading.map { .string($0) } ?? .null,101                    "blockId": passage.blockId.map { .string($0) } ?? .null, "content": .string(passage.text), "snippet": .string(snippet),102                    "score": 0.5, "semantic": request.query["semantic"] == "0" ? 0 : 0.42, "keyword": 1, "kind": "page",103                ]))104            }105            return .json(JSONValue.array(hits).canonicalString())106        }107    }108}109110// MARK: - Inbox111112/// A small stateful inbox: list, capture, triage, undo, Smart Inbox suggestions (cached for one capture, generated on113/// demand for the others) and apply.114final class SampleInboxServer: @unchecked Sendable {115    private struct Item { var id: String; var title: String; var kind: String; var excerpt: String; var minutesAgo: Int; var tags: [String]; var url: String?; var openTasks: Int }116    private let lock = NSLock()117    private var items: [Item]118    private var journal: [String: Item] = [:]119    private var generated: Set<String> = [FeatureSamples.workInboxSuggestedId]120121    init() {122        items = [123            Item(id: FeatureSamples.workInboxSuggestedId, title: "rappeler la banque triplex", kind: "note",124                 excerpt: "Demander si la garantie de taux de 90 jours peut être prolongée.", minutesAgo: 25, tags: [], url: nil, openTasks: 0),125            Item(id: FeatureSamples.workInboxPlainId, title: "Idée de cours : méthode du revenu", kind: "note",126                 excerpt: "Partir d'un triplex réel, loyers observés, taux global d'actualisation.", minutesAgo: 190, tags: ["cours"], url: nil, openTasks: 0),127            Item(id: "6a1f0c5e-1a11-4b6e-9a10-0000000001b3", title: "À faire · 19 nov. 2026", kind: "tasks",128                 excerpt: "Appeler l'évaluateur\nRéserver la salle du séminaire", minutesAgo: 320, tags: [], url: nil, openTasks: 2),129            Item(id: "6a1f0c5e-1a11-4b6e-9a10-0000000001b4", title: "Four Decades of Conditional Volatility Modeling", kind: "link",130                 excerpt: "https://example.org/garch-survey\nSynthèse des variantes GARCH", minutesAgo: 1500, tags: [], url: "https://example.org/garch-survey", openTasks: 0),131            Item(id: "6a1f0c5e-1a11-4b6e-9a10-0000000001b5", title: "Mémo vocal · 18 nov. 2026", kind: "audio", excerpt: "", minutesAgo: 1700, tags: [], url: nil, openTasks: 0),132        ]133    }134135    private func json(_ item: Item) -> JSONValue {136        let at = APIDate.string(from: FeatureSamples.now.addingTimeInterval(-Double(item.minutesAgo) * 60))137        return .object(["id": .string(item.id), "title": .string(item.title), "icon": .null, "kind": .string(item.kind), "inboxAt": .string(at), "updatedAt": .string(at),138                        "wordCount": .int(Int64(item.excerpt.split(separator: " ").count)), "excerpt": .string(item.excerpt), "tags": .array(item.tags.map { .string($0) }),139                        "url": item.url.map { .string($0) } ?? .null, "image": .null, "openTasks": .int(Int64(item.openTasks))])140    }141142    private func suggestions(_ item: Item, cached: Bool) -> String {143        let set: JSONValue = [144            "title": ["value": "Rappeler la banque — garantie de taux du triplex", "current": .string(item.title)],145            "tags": [["name": "refinancement", "existing": true], ["name": "triplex", "existing": true], ["name": "banque", "existing": false]],146            "destination": ["section": "projects", "parentId": .string(FeatureSamples.workProjectPageId), "parentTitle": "Refinancement du triplex"],147            "relations": [["pageId": .string(FeatureSamples.workJournalPageId), "title": "Journal du 18 novembre", "icon": .null,148                           "reason": "L'appel avec la banque y est consigné, avec la date de fin de la garantie."]],149            "summary": "Rappeler la banque pour demander si la garantie de taux de 90 jours peut être prolongée dans le cadre du refinancement du triplex.",150        ]151        let answer: JSONValue = ["pageId": .string(item.id), "contentHash": "c0218f0950c5aad9b1170269bc6f4f2c", "status": "ready", "ai": true, "model": "claude-haiku-5-5",152                                 "provider": "anthropic", "generatedAt": "2026-11-19T14:24:12.565Z", "cached": .bool(cached), "costUsd": 0.00010823, "suggestions": set]153        return answer.canonicalString()154    }155156    func install(on fake: FakeBackend) {157        fake.stub("GET", path: "^/api/inbox$") { [self] request in158            lock.withLock {159                if request.query["count"] != nil { return .json("{\"count\":\(items.count)}") }160                return .json(JSONValue.array(items.map(json)).canonicalString())161            }162        }163        fake.stub("POST", path: "^/api/capture$") { [self] request in164            guard let body = try? JSONValue(data: request.body), let kind = body["kind"]?.stringValue else { return .error(400, message: "Validation: kind") }165            let text = body["text"]?.stringValue ?? body["url"]?.stringValue ?? ""166            guard !text.isEmpty else { return .error(400, message: "Nothing to capture") }167            let item = Item(id: UUID().uuidString.lowercased(), title: String(text.split(separator: "\n").first ?? ""), kind: kind, excerpt: text, minutesAgo: 0, tags: [],168                            url: body["url"]?.stringValue, openTasks: kind == "tasks" ? text.split(separator: "\n").count : 0)169            lock.withLock { items.insert(item, at: 0) }170            let answer: JSONValue = ["id": .string(item.id), "title": .string(item.title), "kind": .string(kind), "inboxAt": .string(APIDate.string(from: FeatureSamples.now))]171            return .json(answer.canonicalString(), status: 201)172        }173        fake.stub("POST", path: "^/api/inbox/undo$") { [self] request in174            guard let id = (try? JSONValue(data: request.body))?["actionId"]?.stringValue else { return .error(400, message: "Validation") }175            return lock.withLock {176                guard let item = journal.removeValue(forKey: id) else { return .json("{\"ok\":true,\"already\":true}") }177                if let index = items.firstIndex(where: { $0.id == item.id }) { items[index] = item } else { items.insert(item, at: 0) }178                return .json("{\"ok\":true,\"already\":false}")179            }180        }181        fake.stub("GET", path: "^/api/inbox/[^/]+/suggestions$") { [self] request in182            let id = String(request.path.split(separator: "/")[2])183            return lock.withLock {184                guard let item = items.first(where: { $0.id == id }) else { return .error(409, code: "not_in_inbox", message: "This item is no longer in the inbox") }185                let cached = generated.contains(item.id)186                if request.query["cachedOnly"] != nil, !cached { return .error(404, code: "not_generated", message: "No suggestions generated yet") }187                generated.insert(item.id)188                return .json(suggestions(item, cached: cached))189            }190        }191        fake.stub("POST", path: "^/api/inbox/[^/]+/apply$") { [self] request in192            let id = String(request.path.split(separator: "/")[2])193            guard let body = (try? JSONValue(data: request.body))?.objectValue, !body.isEmpty else { return .error(400, code: "nothing_to_apply", message: "Nothing chosen to apply") }194            return lock.withLock {195                guard let index = items.firstIndex(where: { $0.id == id }) else { return .error(409, code: "not_in_inbox", message: "This item is no longer in the inbox") }196                let actionId = UUID().uuidString.lowercased()197                journal[actionId] = items[index]198                if let title = body["title"]?.stringValue { items[index].title = title }199                if let tags = body["tags"]?.arrayValue { items[index].tags += tags.compactMap(\.stringValue) }200                let filed = body["destination"] != nil201                if filed { items.remove(at: index) }202                let answer: JSONValue = ["actionId": .string(actionId), "summary": .string("\(body.count) suggestions applied"), "applied": .array(body.keys.sorted().map { .string($0) }),203                                         "filed": .bool(filed), "created": [:]]204                return .json(answer.canonicalString())205            }206        }207        fake.stub("POST", path: "^/api/inbox/[0-9a-f-]{36}$") { [self] request in208            let id = String(request.path.split(separator: "/")[2])209            let action = (try? JSONValue(data: request.body))?["action"]?.stringValue ?? ""210            return lock.withLock {211                guard let index = items.firstIndex(where: { $0.id == id }) else { return .error(409, code: "not_in_inbox", message: "This item is no longer in the inbox") }212                let item = items.remove(at: index)213                let actionId = UUID().uuidString.lowercased()214                journal[actionId] = item215                let created: JSONValue = action == "task" ? ["taskIds": .array((0..<max(1, item.openTasks)).map { _ in .string(UUID().uuidString.lowercased()) })] : [:]216                let answer: JSONValue = ["actionId": .string(actionId), "summary": .string(action), "created": created]217                return .json(answer.canonicalString())218            }219        }220    }221}222223// MARK: - Database224225/// One database served like the real backend: definition, hydrated rows (relation, rollup, formula, AI computed), the226/// query route with the view's or an ad hoc filter / sort / search, and the row / view / property writes. The feed227/// rows (`database_row`) carry the stored values only, as API-NEXT §3.1 says.228final class SampleDatabaseServer: @unchecked Sendable {229    static let stamp = "2026-11-02T14:00:00.000Z"230    private struct Meta { var pageId: String; var position: Double; var created: String; var deleted = false }231    private let lock = NSLock()232    private let id = FeatureSamples.workDatabaseId233    private let pageId = FeatureSamples.workDatabasePageId234    private var properties: [JSONValue]235    private var views: [JSONValue]236    /// Stored values of each row (what the feed carries).237    private var rows: [String: [String: JSONValue]] = [:]238    private var meta: [String: Meta] = [:]239    private var order: [String] = []240241    init() {242        func property(_ id: String, _ name: String, _ type: String, _ config: JSONValue = [:], _ position: Double, width: Int) -> JSONValue {243            .object(["id": .string(id), "databaseId": .string(FeatureSamples.workDatabaseId), "name": .string(name), "type": .string(type), "config": config,244                     "position": .double(position), "width": .int(Int64(width)), "createdAt": .string(Self.stamp), "rev": .int(Int64(100 + position))])245        }246        func options(_ items: [(String, String, String)]) -> JSONValue {247            .object(["options": .array(items.map { .object(["id": .string($0.0), "name": .string($0.1), "color": .string($0.2)]) })])248        }249        properties = [250            property("p-title", "Projet", "title", [:], 0, width: 280),251            property("p-status", "Statut", "status", options([("s-todo", "À lancer", "gray"), ("s-doing", "En cours", "blue"), ("s-review", "En révision", "orange"), ("s-done", "Publié", "green")]), 1, width: 140),252            property("p-prio", "Priorité", "select", options([("o-high", "Haute", "red"), ("o-mid", "Moyenne", "yellow"), ("o-low", "Basse", "gray")]), 2, width: 120),253            property("p-start", "Début", "date", [:], 3, width: 130),254            property("p-due", "Échéance", "date", [:], 4, width: 130),255            property("p-budget", "Budget", "number", ["format": "currency"], 5, width: 130),256            property("p-ready", "Données prêtes", "checkbox", [:], 6, width: 130),257            property("p-tags", "Thèmes", "multi_select", options([("t-fin", "finance", "blue"), ("t-immo", "immobilier", "green"), ("t-ia", "IA", "purple"), ("t-meth", "méthodes", "brown")]), 7, width: 200),258            property("p-link", "Dépôt", "url", [:], 8, width: 220),259            property("p-lead", "Responsable", "text", [:], 9, width: 150),260            property("p-refs", "Références", "relation", ["targetDatabaseId": "6a1f0c5e-1a11-4b6e-9a10-000000000d09", "twoWay": false], 10, width: 260),261            property("p-refcount", "Nb références", "rollup", ["aggregate": "count", "relationPropertyId": "p-refs"], 11, width: 130),262            property("p-monthly", "Budget / mois", "formula", ["expression": "prop(\"Budget\") / 12", "format": "currency"], 12, width: 140),263            property("p-ai", "Résumé IA", "ai", ["prompt": "Résume le projet en une phrase."], 13, width: 320),264            property("p-created", "Créé", "created_time", [:], 14, width: 170),265        ]266        func view(_ id: String, _ name: String, _ type: String, _ config: JSONValue, _ position: Double, isDefault: Bool = false) -> JSONValue {267            .object(["id": .string(id), "databaseId": .string(FeatureSamples.workDatabaseId), "name": .string(name), "type": .string(type), "config": config,268                     "position": .double(position), "isDefault": .bool(isDefault), "createdAt": .string(Self.stamp), "rev": .int(Int64(200 + position))])269        }270        views = [271            view("v-table", "Table", "table", ["sorts": [["property": "p-due", "dir": "asc"]], "hidden": ["p-created"]], 0, isDefault: true),272            view("v-board", "Par statut", "board", ["groupBy": "p-status"], 1),273            view("v-list", "Liste par priorité", "list", ["groupBy": "p-prio", "sorts": [["property": "p-prio", "dir": "asc"]]], 2),274            view("v-gallery", "Galerie", "gallery", [:], 3),275            view("v-calendar", "Calendrier", "calendar", ["dateProperty": "p-due"], 4),276            view("v-timeline", "Chronologie", "timeline", ["startProperty": "p-start", "endProperty": "p-due"], 5),277            view("v-funded", "Bien financés", "table", ["filter": ["and": [["property": "p-monthly", "op": "gt", "value": 3000]]], "sorts": [["property": "p-monthly", "dir": "desc"]]], 6),278        ]279        struct Seed { var id: String; var title: String; var status: String; var priority: String; var start: String?; var due: String?; var budget: Double?; var ready: Bool; var tags: [String]; var link: String?; var lead: String }280        let seed = [281            Seed(id: "r-01", title: "Volatilité conditionnelle : quarante ans de GARCH", status: "s-review", priority: "o-high", start: "2026-09-01", due: "2026-11-24", budget: 48_000, ready: true, tags: ["t-fin", "t-meth"], link: "https://git.example.org/wp46", lead: "S.-P. Boucher"),282            Seed(id: "r-02", title: "Courbe des taux à la minute", status: "s-doing", priority: "o-high", start: "2026-10-05", due: "2026-12-12", budget: 36_000, ready: true, tags: ["t-fin"], link: "https://git.example.org/wp47", lead: "G. Manseau"),283            Seed(id: "r-03", title: "Atlas des ajustements immobiliers", status: "s-done", priority: "o-mid", start: "2026-08-10", due: "2026-11-11", budget: 22_500, ready: true, tags: ["t-immo"], link: nil, lead: "S.-P. Boucher"),284            Seed(id: "r-04", title: "Greffe d'organes neuronaux", status: "s-doing", priority: "o-mid", start: "2026-10-20", due: "2026-11-30", budget: 64_000, ready: false, tags: ["t-ia"], link: "https://git.example.org/wpai1", lead: "S.-P. Boucher"),285            Seed(id: "r-05", title: "Géographie économique de la production numérique", status: "s-todo", priority: "o-low", start: "2026-11-25", due: "2027-01-20", budget: 18_000, ready: false, tags: ["t-meth"], link: nil, lead: "M. Lebel-Allaire"),286            Seed(id: "r-06", title: "Architecture cachée des prix d'épicerie", status: "s-review", priority: "o-mid", start: "2026-09-15", due: "2026-11-19", budget: 27_000, ready: true, tags: ["t-fin", "t-meth"], link: nil, lead: "S.-P. Boucher"),287            Seed(id: "r-07", title: "Dynamique du marché des voitures d'occasion", status: "s-todo", priority: "o-low", start: nil, due: nil, budget: nil, ready: false, tags: [], link: nil, lead: ""),288            Seed(id: "r-08", title: "Reconstruction du texte humain", status: "s-done", priority: "o-high", start: "2026-09-28", due: "2026-11-09", budget: 81_000, ready: true, tags: ["t-ia", "t-meth"], link: "https://git.example.org/wpai2", lead: "S.-P. Boucher"),289        ]290        for (index, item) in seed.enumerated() {291            var values: [String: JSONValue] = ["p-title": .string(item.title), "p-status": .string(item.status), "p-prio": .string(item.priority), "p-ready": .bool(item.ready),292                                               "p-tags": .array(item.tags.map { .string($0) })]293            if let start = item.start { values["p-start"] = .string(start) }294            if let due = item.due { values["p-due"] = .string(due) }295            if let budget = item.budget { values["p-budget"] = .double(budget) }296            if let link = item.link { values["p-link"] = .string(link) }297            if !item.lead.isEmpty { values["p-lead"] = .string(item.lead) }298            rows[item.id] = values299            meta[item.id] = Meta(pageId: "6a1f0c5e-1a11-4b6e-9a10-0000000002" + String(format: "%02d", index + 1), position: Double(index + 1),300                                 created: "2026-11-\(String(format: "%02d", index + 1))T15:00:00.000Z")301            order.append(item.id)302        }303    }304305    private static let references: [String: [String]] = ["r-01": ["Bollerslev (1986)", "Engle (1982)", "Hansen & Lunde (2005)"], "r-02": ["Nelson & Siegel (1987)"],306                                                         "r-03": ["Rosen (1974)"], "r-08": ["Vaswani et al. (2017)", "Raffel et al. (2020)"]]307    private static let summaries: [String: JSONValue] = [308        "r-01": "Synthèse de 64 architectures GARCH comparées sur 42 instruments.",309        "r-02": "Estimation Nelson–Siegel intrajournalière à partir des contrats à terme du Trésor.",310        "r-04": ["pending": true, "at": "2026-11-19T14:58:00.000Z"],311        "r-06": ["error": "Le modèle n'a pas répondu"],312    ]313314    /// The values the server computes on top of the stored ones.315    private func hydratedValues(_ rowId: String) -> [String: JSONValue] {316        var values = rows[rowId] ?? [:]317        let refs = Self.references[rowId] ?? []318        values["p-refs"] = .array(refs.enumerated().map { index, title in319            .object(["rowId": .string("ref-\(rowId)-\(index)"), "pageId": .string("ref-page-\(rowId)-\(index)"), "title": .string(title), "icon": .null])320        })321        values["p-refcount"] = .int(Int64(refs.count))322        values["p-monthly"] = values["p-budget"]?.doubleValue.map { .double(($0 / 12).rounded()) } ?? .null323        values["p-ai"] = Self.summaries[rowId] ?? .null324        values["p-created"] = .string(meta[rowId]?.created ?? Self.stamp)325        return values326    }327328    /// The row as the database routes return it.329    private func hydrated(_ rowId: String) -> JSONValue {330        let values = hydratedValues(rowId)331        let info = meta[rowId] ?? Meta(pageId: "", position: 0, created: Self.stamp)332        return .object(["id": .string(rowId), "pageId": .string(info.pageId), "databaseId": .string(id), "title": values["p-title"] ?? "", "icon": .null, "values": .object(values),333                        "position": .double(info.position), "createdAt": .string(info.created), "updatedAt": .string(info.created)])334    }335336    private func stored(_ rowId: String) -> JSONValue {337        let info = meta[rowId] ?? Meta(pageId: "", position: 0, created: Self.stamp)338        return .object(["id": .string(rowId), "pageId": .string(info.pageId), "databaseId": .string(id), "title": rows[rowId]?["p-title"] ?? "", "values": .object(rows[rowId] ?? [:]),339                        "position": .double(info.position), "createdAt": .string(info.created), "updatedAt": .string(info.created), "deletedAt": .null])340    }341342    private func info(full: Bool) -> JSONValue {343        var object: [String: JSONValue] = ["id": .string(id), "pageId": .string(pageId), "name": "Projets de recherche", "description": "Suivi des working papers", "icon": "🧪",344                                           "isTemplate": false, "templateOf": .null, "createdAt": .string(Self.stamp), "updatedAt": .string(Self.stamp), "rev": 90]345        if full { object["properties"] = .array(properties); object["views"] = .array(views) }346        return .object(object)347    }348349    /// The server evaluates everything, computed properties included: they are given to the evaluator as plain types.350    private func evaluate(_ body: JSONValue?) -> JSONValue {351        let infos = properties.compactMap { json -> DatabasePropertyInfo? in352            guard var info = DatabasePropertyInfo(json: json) else { return nil }353            if info.type == "formula" || info.type == "rollup" { info.type = "number" }354            if info.type == "relation" || info.type == "ai" { info.type = "text" }355            return info356        }357        var config: JSONValue?358        if let viewId = body?["viewId"]?.stringValue {359            config = views.first { $0["id"]?.stringValue == viewId }?["config"]360        } else if body?["filter"] == nil, body?["sorts"] == nil {361            config = views.first { $0["isDefault"]?.boolValue == true }?["config"]362        }363        var query = DatabaseViewQuery(viewConfig: config)364        if let filter = body?["filter"] { query.filter = DatabaseViewFilter(json: filter) }365        if let sorts = body?["sorts"] { query.sorts = DatabaseViewSort.list(json: sorts) }366        query.search = body?["search"]?.stringValue367        query.groupBy = nil368        query.limit = body?["limit"]?.intValue ?? 200369        query.offset = body?["offset"]?.intValue ?? 0370        let candidates = order.filter { meta[$0]?.deleted == false }.map { rowId -> DatabaseRowValues in371            var values = hydratedValues(rowId)372            values["p-refs"] = .string((Self.references[rowId] ?? []).joined(separator: ", "))373            return DatabaseRowValues(id: rowId, pageId: meta[rowId]?.pageId, title: values["p-title"]?.stringValue ?? "", values: values, position: meta[rowId]?.position ?? 0,374                                     createdAt: APIDate.parse(meta[rowId]?.created ?? ""))375        }376        let result = DatabaseEvaluator.evaluate(properties: infos, rows: candidates, query: query, now: FeatureSamples.now)377        return .object(["rows": .array(result.rows.map { hydrated($0.id) }), "total": .int(Int64(result.total)), "limit": .int(Int64(query.limit ?? 200)), "offset": .int(Int64(query.offset))])378    }379380    func install(on fake: FakeBackend) {381        // The feed (what a device has offline): definition and stored values.382        fake.webPutEntity(kind: "database", id: id, json: info(full: false).canonicalString())383        for property in properties { fake.webPutEntity(kind: "database_property", id: property["id"]?.stringValue ?? "", json: property.canonicalString()) }384        for view in views { fake.webPutEntity(kind: "database_view", id: view["id"]?.stringValue ?? "", json: view.canonicalString()) }385        for rowId in order { fake.webPutEntity(kind: "database_row", id: rowId, json: stored(rowId).canonicalString()) }386387        let base = "^/api/databases/(\(id)|\(pageId))"388        fake.stub("GET", path: base + "$") { [self] _ in lock.withLock { .json(info(full: true).canonicalString()) } }389        fake.stub("POST", path: base + "/query$") { [self] request in lock.withLock { .json(evaluate(try? JSONValue(data: request.body)).canonicalString()) } }390        fake.stub("POST", path: base + "/rows$") { [self] request in391            guard let body = try? JSONValue(data: request.body), let rowId = body["id"]?.stringValue else { return .error(400, message: "Validation: id") }392            return lock.withLock {393                if rows[rowId] == nil {394                    var values = body["values"]?.objectValue ?? [:]395                    values["p-title"] = .string(body["title"]?.stringValue ?? "Untitled")396                    rows[rowId] = values397                    meta[rowId] = Meta(pageId: body["pageId"]?.stringValue ?? UUID().uuidString.lowercased(), position: Double(order.count + 1), created: APIDate.string(from: FeatureSamples.now))398                    order.append(rowId)399                }400                return .json(hydrated(rowId).canonicalString(), status: 201)401            }402        }403        fake.stub("PATCH", path: base + "/rows$") { [self] request in404            guard let body = try? JSONValue(data: request.body), let rowId = body["id"]?.stringValue, let values = body["values"]?.objectValue else { return .error(400, message: "Validation") }405            return lock.withLock {406                guard rows[rowId] != nil, meta[rowId]?.deleted == false else { return .error(404, message: "Row not found") }407                for (key, value) in values {408                    let empty = value.isNull || value.stringValue == "" || value.arrayValue?.isEmpty == true409                    if empty { rows[rowId]?.removeValue(forKey: key) } else { rows[rowId]?[key] = value }410                }411                return .json(hydrated(rowId).canonicalString())412            }413        }414        fake.stub("DELETE", path: base + "/rows$") { [self] request in415            let ids = (request.query["ids"] ?? request.query["id"] ?? "").split(separator: ",").map(String.init)416            return lock.withLock {417                var deleted = 0418                for rowId in ids where meta[rowId]?.deleted == false { meta[rowId]?.deleted = true; deleted += 1 }419                return .json("{\"ok\":true,\"deleted\":\(deleted)}")420            }421        }422        fake.stub("POST", path: base + "/rows/restore$") { [self] request in423            let ids = ((try? JSONValue(data: request.body))?["ids"]?.arrayValue ?? []).compactMap(\.stringValue)424            return lock.withLock {425                var restored = 0426                for rowId in ids where meta[rowId]?.deleted == true { meta[rowId]?.deleted = false; restored += 1 }427                return .json("{\"ok\":true,\"restored\":\(restored)}")428            }429        }430        fake.stub("POST", path: base + "/views$") { [self] request in431            guard let body = (try? JSONValue(data: request.body))?.objectValue, let viewId = body["id"]?.stringValue else { return .error(400, message: "Validation") }432            return lock.withLock {433                let view = JSONValue.object(["id": .string(viewId), "databaseId": .string(id), "name": body["name"] ?? "Vue", "type": body["type"] ?? "table", "config": body["config"] ?? [:],434                                             "position": .double(Double(views.count)), "isDefault": false, "createdAt": .string(Self.stamp), "rev": .int(Int64(300 + views.count))])435                views.append(view)436                return .json(view.canonicalString(), status: 201)437            }438        }439        fake.stub("PATCH", path: base + "/views$") { [self] request in440            guard let body = (try? JSONValue(data: request.body))?.objectValue, let viewId = body["id"]?.stringValue else { return .error(400, message: "Validation") }441            return lock.withLock {442                guard let index = views.firstIndex(where: { $0["id"]?.stringValue == viewId }), var view = views[index].objectValue else { return .error(404, message: "View not found") }443                for key in ["name", "type", "config", "position", "isDefault"] { if let value = body[key] { view[key] = value } }444                view["rev"] = .int(Int64((view["rev"]?.intValue ?? 300) + 1))445                views[index] = .object(view)446                return .json(views[index].canonicalString())447            }448        }449        fake.stub("DELETE", path: base + "/views$") { [self] request in450            lock.withLock {451                guard views.count > 1 else { return .error(400, message: "A database keeps at least one view") }452                views.removeAll { $0["id"]?.stringValue == request.query["id"] }453                return .json("{\"ok\":true}")454            }455        }456        fake.stub("POST", path: base + "/properties$") { [self] request in457            guard let body = (try? JSONValue(data: request.body))?.objectValue, let propertyId = body["id"]?.stringValue else { return .error(400, message: "Validation") }458            return lock.withLock {459                let property = JSONValue.object(["id": .string(propertyId), "databaseId": .string(id), "name": body["name"] ?? "Propriété", "type": body["type"] ?? "text",460                                                 "config": body["config"] ?? [:], "position": .double(Double(properties.count)), "width": .null, "createdAt": .string(Self.stamp),461                                                 "rev": .int(Int64(400 + properties.count))])462                properties.append(property)463                return .json(property.canonicalString(), status: 201)464            }465        }466    }467}468
Files main
Menu

Theme