SPB Git

Repository Public

TasksModel.swift 9.7 KB 246 lines swift

1// SP Notes Core2// File: Sources/SPNotesFeatures/Work/Tasks/TasksModel.swift3// Description: View model of the tasks screen over `TasksRepository`: the local list (works offline), grouping by due day4//              (overdue / today / upcoming / no date; a bare day is noon UTC, so the day shown is the UTC date part),5//              offline-first create / edit / delete, and the outbox operations the server refused (retry or discard).6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9import Foundation10import Observation11import SPNotesAPI12import SPNotesStore13import SPNotesSync1415@Observable @MainActor16public final class TasksModel {17    public enum Group: String, Sendable, CaseIterable, Identifiable {18        case overdue, today, upcoming, noDate, done19        public var id: String { rawValue }2021        public var title: String {22            switch self {23            case .overdue: return L("En retard")24            case .today: return L("Aujourd'hui")25            case .upcoming: return L("À venir")26            case .noDate: return L("Sans échéance")27            case .done: return L("Terminées")28            }29        }30    }3132    public struct Section: Identifiable, Equatable, Sendable {33        public var group: Group34        public var tasks: [TaskItem]35        public var id: String { group.rawValue }36    }3738    // MARK: state3940    public private(set) var tasks: [TaskItem] = []41    public private(set) var pendingIds: Set<String> = []42    /// Operations refused by the server (or unsupported by this build): surfaced until retried or discarded.43    public private(set) var problems: [PendingTaskOperation] = []44    /// Operations simply waiting for the next sync.45    public private(set) var waitingCount = 046    public private(set) var phase: LoadPhase = .idle47    /// Tasks are read from the device: there is no cached read model, hence no freshness.48    public let freshness: Freshness? = nil49    public var actionFailure: FeatureFailure?50    /// True when the server is a 2.x one: the list is readable, writes are refused.51    public private(set) var isReadOnly = false52    public var filter: TaskFilter = .open53    public var selectedTaskId: String?54    public var draftTitle = ""55    public var draftPriority: TaskPriority = .medium56    /// `YYYY-MM-DD` or nil.57    public var draftDueDay: String?5859    /// Restricts the screen to the tasks of one page (nil = all).60    public let pageId: String?61    private let repo: TasksRepository62    private let repositories: NotesRepositories63    private weak var router: (any FeatureRouter)?64    private let now: @Sendable () -> Date65    private let calendar: Calendar6667    public init(repositories: NotesRepositories, router: (any FeatureRouter)? = nil, pageId: String? = nil, calendar: Calendar = .current,68                now: @escaping @Sendable () -> Date = { Date() }) {69        self.repositories = repositories70        repo = repositories.tasks71        self.router = router72        self.pageId = pageId73        self.calendar = calendar74        self.now = now75    }7677    // MARK: derived7879    /// The user's "today" as `YYYY-MM-DD` (their calendar and time zone).80    public var todayDay: String { WorkDay.string(now(), timeZone: calendar.timeZone) }8182    /// The day a task is due: the UTC date part of `dueAt` (a bare day is stored at 12:00 UTC).83    public nonisolated static func dueDay(_ task: TaskItem) -> String? { task.dueAt.map { WorkDay.string($0, timeZone: WorkDay.utc) } }8485    public nonisolated static func group(of task: TaskItem, today: String) -> Group {86        if task.isDone { return .done }87        guard let day = dueDay(task) else { return .noDate }88        if day < today { return .overdue }89        return day == today ? .today : .upcoming90    }9192    public nonisolated static func sections(_ tasks: [TaskItem], today: String) -> [Section] {93        var buckets: [Group: [TaskItem]] = [:]94        for task in tasks { buckets[group(of: task, today: today), default: []].append(task) }95        return Group.allCases.compactMap { group in buckets[group].map { Section(group: group, tasks: $0) } }96    }9798    public var sections: [Section] { Self.sections(tasks, today: todayDay) }99    public var selectedTask: TaskItem? { tasks.first { $0.id == selectedTaskId } }100    public var openCount: Int { tasks.filter { !$0.isDone }.count }101    public var canAdd: Bool { !isReadOnly && !draftTitle.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty }102103    /// « 21 nov. » — the due day formatted as a date (UTC date part).104    public nonisolated static func dueLabel(_ task: TaskItem) -> String? {105        task.dueAt.map { FeatureFormat.day($0, timeZone: WorkDay.utc) }106    }107108    public nonisolated static func priorityLabel(_ priority: String?) -> String {109        switch priority {110        case TaskPriority.high.rawValue: return L("Haute")111        case TaskPriority.low.rawValue: return L("Basse")112        default: return L("Moyenne")113        }114    }115116    public nonisolated static func statusLabel(_ status: String) -> String {117        switch status {118        case TaskStatus.doing.rawValue: return L("En cours")119        case TaskStatus.done.rawValue: return L("Terminée")120        default: return L("À faire")121        }122    }123124    // MARK: loading125126    public func load() async {127        if tasks.isEmpty { phase = .loading }128        if let meta = await repositories.features() { isReadOnly = !meta.has(ServerFeature.tasksV2) }129        await reload()130    }131132    /// Reloads the list whenever the local copy changes (a sync, another screen). Runs until cancelled.133    public func observe() async {134        let changes = await repo.changes()135        // A change that landed between the first load and this subscription would be missed: read once more now.136        await reload()137        for await _ in changes { await reload() }138    }139140    public func setFilter(_ filter: TaskFilter) async {141        self.filter = filter142        await reload()143    }144145    private func reload() async {146        do {147            let list = try await repo.list(filter, pageId: pageId)148            let operations = try await repo.pendingOperations()149            tasks = list150            pendingIds = Set(operations.map(\.taskId))151            problems = operations.filter { $0.state != .pending }152            waitingCount = operations.count - problems.count153            if let selectedTaskId, !list.contains(where: { $0.id == selectedTaskId }) { self.selectedTaskId = nil }154            phase = .loaded155        } catch {156            phase = .failed(FeatureFailure(error))157        }158    }159160    // MARK: actions (offline-first)161162    @discardableResult163    public func add() async -> Bool {164        let title = draftTitle165        let done = await perform { [self] in _ = try await repo.create(title: title, dueDay: draftDueDay, priority: draftPriority, pageId: pageId) }166        if done { draftTitle = ""; draftDueDay = nil; draftPriority = .medium }167        return done168    }169170    public func toggle(_ task: TaskItem) async {171        await perform { [self] in _ = try await repo.setDone(id: task.id, !task.isDone) }172    }173174    public func setStatus(_ status: TaskStatus, id: String) async {175        await perform { [self] in _ = try await repo.update(id: id, TaskEdit(status: status)) }176    }177178    public func rename(_ title: String, id: String) async {179        guard title.trimmingCharacters(in: .whitespacesAndNewlines) != tasks.first(where: { $0.id == id })?.title else { return }180        await perform { [self] in _ = try await repo.update(id: id, TaskEdit(title: title)) }181    }182183    public func setPriority(_ priority: TaskPriority, id: String) async {184        await perform { [self] in _ = try await repo.update(id: id, TaskEdit(priority: priority)) }185    }186187    /// Sets (a bare day, stored at noon UTC) or clears the due date.188    public func setDue(day: String?, id: String) async {189        await perform { [self] in190            if let day {191                guard let date = WorkDay.date(day, hour: 12, timeZone: WorkDay.utc) else { throw RepositoryError.invalid(L("Date invalide.")) }192                _ = try await repo.update(id: id, TaskEdit(dueAt: .value(date)))193            } else {194                _ = try await repo.update(id: id, TaskEdit(dueAt: .null))195            }196        }197    }198199    public func delete(id: String) async {200        if selectedTaskId == id { selectedTaskId = nil }201        await perform { [self] in try await repo.delete(id: id) }202    }203204    public func retry(_ operation: PendingTaskOperation) async {205        await perform { [self] in try await repo.retry(operation: operation.id) }206    }207208    public func discard(_ operation: PendingTaskOperation) async {209        await perform { [self] in try await repo.discard(operation: operation.id) }210    }211212    /// Opens the page a task belongs to, at its block when it is anchored to one.213    public func openPage(of task: TaskItem) {214        guard let pageId = task.pageId else { return }215        router?.openPage(id: pageId, blockId: task.blockId)216    }217218    /// What a refused operation was, in words.219    public func describe(_ operation: PendingTaskOperation) -> String {220        let title = tasks.first { $0.id == operation.taskId }?.title221        let verb: String222        switch operation.verb {223        case "create": verb = L("Création")224        case "delete": verb = L("Suppression")225        default: verb = L("Modification")226        }227        return title.map { LF("%@ de « %@ »", verb, $0) } ?? verb228    }229230    @discardableResult231    private func perform(_ work: @escaping () async throws -> Void) async -> Bool {232        do {233            try await work()234            actionFailure = nil235            await reload()236            return true237        } catch {238            let failure = FeatureFailure(error)239            if failure.kind == .unsupported { isReadOnly = true }240            actionFailure = failure241            await reload()242            return false243        }244    }245}246
Files main
Menu

Theme