Repository Public
1// SP Notes Core2// File: Sources/SPNotesSync/Repositories/TasksRepository.swift3// Description: Tasks for the apps: read from the local copy fed by the entity feed, written offline-first (local row +4// outbox entry in one transaction, client-chosen id, sent by the engine in order). See docs/REPOSITORIES.md.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Foundation9import SPNotesAPI10import SPNotesStore1112/// What the user changes in a task. `nil` = untouched; a nullable field is cleared with `.null`.13public struct TaskEdit: Sendable, Equatable {14 public var title: String?15 public var status: TaskStatus?16 public var priority: TaskPriority?17 public var dueAt: PatchValue<Date>?18 public var project: PatchValue<String>?19 public var pageId: PatchValue<String>?20 public var blockId: PatchValue<String>?2122 public init(title: String? = nil, status: TaskStatus? = nil, priority: TaskPriority? = nil, dueAt: PatchValue<Date>? = nil,23 project: PatchValue<String>? = nil, pageId: PatchValue<String>? = nil, blockId: PatchValue<String>? = nil) {24 self.title = title; self.status = status; self.priority = priority; self.dueAt = dueAt25 self.project = project; self.pageId = pageId; self.blockId = blockId26 }2728 public var isEmpty: Bool { title == nil && status == nil && priority == nil && dueAt == nil && project == nil && pageId == nil && blockId == nil }29}3031/// Which tasks a list shows.32public enum TaskFilter: Sendable, Equatable {33 /// Not done (`todo`, `doing`).34 case open35 case done36 case all37}3839/// A task operation waiting in the outbox, or refused by the server.40public struct PendingTaskOperation: Sendable, Equatable, Identifiable {41 public var id: Int6442 public var taskId: String43 /// `create`, `update` or `delete`.44 public var verb: String45 public var state: EntityOp.State46 public var attempts: Int47 public var lastError: String?48}4950public struct TasksRepository: Sendable {51 let context: RepositoryContext52 public init(context: RepositoryContext) { self.context = context }5354 // MARK: reading (local, works offline)5556 /// The tasks of the local copy, in the server's order: open first, then by due date (no date last), then newest.57 public func list(_ filter: TaskFilter = .open, pageId: String? = nil) async throws -> [TaskItem] {58 do {59 let all = context.decodeEntities(TaskItem.self, try await context.store.tasks(pageId: pageId))60 let kept = all.filter { task in61 switch filter {62 case .open: return !task.isDone63 case .done: return task.isDone64 case .all: return true65 }66 }67 return kept.sorted(by: Self.serverOrder)68 } catch { throw RepositoryError.from(error) }69 }7071 public func task(id: String) async throws -> TaskItem? {72 do {73 guard let record = try await context.store.entity(kind: .task, id: id), !record.deleted else { return nil }74 return try? APIJSON.decoder().decode(TaskItem.self, from: record.json)75 } catch { throw RepositoryError.from(error) }76 }7778 /// Whether the task has local changes the server has not acknowledged yet.79 public func isPending(id: String) async throws -> Bool {80 do { return try await context.store.entity(kind: .task, id: id)?.dirty ?? false } catch { throw RepositoryError.from(error) }81 }8283 static func serverOrder(_ a: TaskItem, _ b: TaskItem) -> Bool {84 if a.isDone != b.isDone { return !a.isDone }85 switch (a.dueAt, b.dueAt) {86 case (let x?, let y?) where x != y: return x < y87 case (.some, nil): return true88 case (nil, .some): return false89 default: break90 }91 if a.createdAt != b.createdAt { return a.createdAt > b.createdAt }92 return a.id < b.id93 }9495 // MARK: writing (offline-first)9697 /// Creates a task under a client-chosen id. Works offline: the task exists at once in the local copy and reaches98 /// the server at the next cycle (idempotent on its id).99 /// - Parameter dueDay: a bare calendar day `YYYY-MM-DD` (the server stores it at 12:00 UTC); `dueAt` wins when both are given.100 @discardableResult101 public func create(title: String, dueAt: Date? = nil, dueDay: String? = nil, priority: TaskPriority = .medium, status: TaskStatus = .todo,102 project: String? = nil, pageId: String? = nil, blockId: String? = nil, id: String = NotesAPI.newID()) async throws -> TaskItem {103 let trimmed = title.trimmingCharacters(in: .whitespacesAndNewlines)104 guard !trimmed.isEmpty, trimmed.count <= 500 else { throw RepositoryError.invalid("Le titre d'une tâche compte de 1 à 500 caractères.") }105 if let dueDay, APIDate.parse(dueDay) == nil { throw RepositoryError.invalid("Date invalide : \(dueDay)") }106 try await requireTasks()107 let now = Date()108 let due = dueAt ?? dueDay.flatMap { APIDate.parse($0 + "T12:00:00.000Z") }109 var row: [String: Any] = ["id": id, "title": trimmed, "status": status.rawValue, "priority": priority.rawValue,110 "createdAt": APIDate.string(from: now), "updatedAt": APIDate.string(from: now)]111 if let due { row["dueAt"] = APIDate.string(from: due) }112 if status == .done { row["completedAt"] = APIDate.string(from: now) }113 if let project { row["project"] = project }114 if let pageId { row["pageId"] = pageId }115 if let blockId { row["blockId"] = blockId }116 let draft = QueuedTaskDraft(title: trimmed, status: status.rawValue, priority: priority.rawValue, dueAt: dueAt, due: dueAt == nil ? dueDay : nil,117 project: project, pageId: pageId, blockId: blockId)118 do {119 let json = try JSONSerialization.data(withJSONObject: row, options: [.sortedKeys])120 try await context.store.saveLocalEntity(kind: .task, id: id, json: json, op: EntityOpVerb.create, payload: try APIJSON.encoder().encode(draft))121 await context.scheduleSync()122 return try APIJSON.decoder().decode(TaskItem.self, from: json)123 } catch { throw RepositoryError.from(error) }124 }125126 /// Changes a task. Works offline; only the changed fields are sent, so two devices editing different fields of the127 /// same task both win (the same field: the last one to reach the server).128 @discardableResult129 public func update(id: String, _ edit: TaskEdit) async throws -> TaskItem {130 if let title = edit.title {131 let trimmed = title.trimmingCharacters(in: .whitespacesAndNewlines)132 guard !trimmed.isEmpty, trimmed.count <= 500 else { throw RepositoryError.invalid("Le titre d'une tâche compte de 1 à 500 caractères.") }133 }134 try await requireTasks()135 do {136 guard let record = try await context.store.entity(kind: .task, id: id), !record.deleted,137 var row = try JSONSerialization.jsonObject(with: record.json) as? [String: Any] else { throw RepositoryError.notFound("task \(id)") }138 guard !edit.isEmpty else { return try APIJSON.decoder().decode(TaskItem.self, from: record.json) }139 let now = Date()140 var queued = QueuedTaskChanges()141 var clear: [String] = []142 if let title = edit.title { let t = title.trimmingCharacters(in: .whitespacesAndNewlines); row["title"] = t; queued.title = t }143 if let status = edit.status {144 if (row["status"] as? String) != status.rawValue { row["completedAt"] = status == .done ? APIDate.string(from: now) : NSNull() }145 row["status"] = status.rawValue; queued.status = status.rawValue146 }147 if let priority = edit.priority { row["priority"] = priority.rawValue; queued.priority = priority.rawValue }148 switch edit.dueAt {149 case .value(let date)?: row["dueAt"] = APIDate.string(from: date); queued.dueAt = date150 case .null?: row["dueAt"] = NSNull(); clear.append("dueAt")151 case nil: break152 }153 switch edit.project {154 case .value(let project)?: row["project"] = project; queued.project = project155 case .null?: row["project"] = NSNull(); clear.append("project")156 case nil: break157 }158 switch edit.pageId {159 case .value(let pageId)?: row["pageId"] = pageId; queued.pageId = pageId160 case .null?:161 row["pageId"] = NSNull(); clear.append("pageId")162 if edit.blockId == nil { row["blockId"] = NSNull() } // the server clears the anchor with the page163 case nil: break164 }165 switch edit.blockId {166 case .value(let blockId)?: row["blockId"] = blockId; queued.blockId = blockId167 case .null?: row["blockId"] = NSNull(); clear.append("blockId")168 case nil: break169 }170 if !clear.isEmpty { queued.clear = clear }171 row["updatedAt"] = APIDate.string(from: now)172 let json = try JSONSerialization.data(withJSONObject: row, options: [.sortedKeys])173 try await context.store.saveLocalEntity(kind: .task, id: id, json: json, op: EntityOpVerb.update, payload: try APIJSON.encoder().encode(queued))174 await context.scheduleSync()175 return try APIJSON.decoder().decode(TaskItem.self, from: json)176 } catch { throw RepositoryError.from(error) }177 }178179 @discardableResult180 public func setDone(id: String, _ done: Bool) async throws -> TaskItem { try await update(id: id, TaskEdit(status: done ? .done : .todo)) }181182 /// Deletes a task (works offline; a deletion wins over an edit made elsewhere).183 public func delete(id: String) async throws {184 try await requireTasks()185 do {186 guard try await context.store.entity(kind: .task, id: id) != nil else { return }187 try await context.store.saveLocalEntity(kind: .task, id: id, json: nil, op: EntityOpVerb.delete)188 await context.scheduleSync()189 } catch { throw RepositoryError.from(error) }190 }191192 // MARK: outbox193194 /// Operations waiting or refused (`state == .rejected`: the server said no for good — show `lastError`, then195 /// `retry` or `discard`).196 public func pendingOperations() async throws -> [PendingTaskOperation] {197 do {198 return try await context.store.entityOps().filter { $0.kind == .task }199 .map { PendingTaskOperation(id: $0.id, taskId: $0.entityId, verb: $0.op, state: $0.state, attempts: $0.attempts, lastError: $0.lastError) }200 } catch { throw RepositoryError.from(error) }201 }202203 /// Puts a refused operation back in line, or ends the wait of one in backoff ("retry now").204 public func retry(operation id: Int64) async throws {205 do {206 try await context.store.retryEntityOps(id: id)207 try await context.store.expediteEntityOps(id: id)208 await context.scheduleSync()209 } catch { throw RepositoryError.from(error) }210 }211212 /// Abandons an operation on the user's decision, with the later operations of the same task (they were built on213 /// it). The local task then shows the server's state again: a task whose creation is abandoned disappears;214 /// otherwise the server copy is used (the one the feed already brought, or a fresh read — `.offline` when that215 /// read is needed and impossible; nothing is discarded in that case).216 public func discard(operation id: Int64) async throws {217 do {218 guard let target = try await context.store.entityOps().first(where: { $0.id == id }), target.kind == .task else { return }219 let taskId = target.entityId220 let ops = try await context.store.entityOps(kind: .task, entityId: taskId).filter { $0.id >= id }221 let record = try await context.store.entity(kind: .task, id: taskId)222 var replacement = record?.remoteJSON223 var gone = ops.contains { $0.op == EntityOpVerb.create }224 if !gone, replacement == nil {225 let fresh = try await context.online { try await context.api.task(id: taskId) }226 if fresh.deletedAt != nil { gone = true } else { replacement = try APIJSON.encoder().encode(fresh) }227 }228 for op in ops { _ = try await context.store.discardEntityOp(id: op.id) }229 guard try await context.store.entityOps(kind: .task, entityId: taskId).isEmpty else { return }230 _ = try await context.store.markEntitySynced(kind: .task, id: taskId)231 if gone {232 await context.uncacheEntity(kind: .task, id: taskId)233 } else if let replacement {234 // Revision 0: the row always applies, and any later row of the feed replaces it.235 _ = try await context.store.applyRemoteEntities([RemoteEntity(kind: .task, id: taskId, rev: 0, json: replacement)])236 }237 await context.scheduleSync()238 } catch { throw RepositoryError.from(error) }239 }240241 /// Changes of the local task list (to reload a view).242 public func changes() async -> AsyncStream<Void> {243 let upstream = await context.store.changes()244 return AsyncStream { continuation in245 let task = Task {246 for await change in upstream {247 if case .entities(let kind, _) = change, kind == EntityKind.task.rawValue { continuation.yield() }248 }249 continuation.finish()250 }251 continuation.onTermination = { _ in task.cancel() }252 }253 }254255 private func requireTasks() async throws {256 if let meta = await context.knownFeatures(), !meta.has(ServerFeature.tasksV2) { throw RepositoryError.unsupported(feature: ServerFeature.tasksV2) }257 }258}259