Repository Public
1// SP Notes Core2// File: Tests/SPNotesFeaturesTests/WorkTasksTests.swift3// Description: The tasks view model against the fake backend: grouping by due day (bare-day rule), offline-first4// create / edit / delete, the outbox problems (retry, discard), live refresh, a 2.x server, empty and5// failing states.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9import Foundation10import SPNotesAPI11import SPNotesSync12import Testing13@testable import SPNotesFeatures14@testable import SPNotesFeaturesCatalog1516@Suite("Work · tasks")17@MainActor18struct WorkTasksTests {19 private func model(_ world: FeatureWorld, router: FeatureRouterRecorder? = nil, pageId: String? = nil) -> TasksModel {20 var calendar = Calendar(identifier: .gregorian)21 calendar.timeZone = TimeZone(identifier: "America/Toronto")!22 return TasksModel(repositories: world.repositories, router: router, pageId: pageId, calendar: calendar, now: { FeatureSamples.now })23 }2425 @Test("happy path: the open tasks are grouped overdue / today / upcoming / no date")26 func grouping() async throws {27 let world = try await FeatureWorld()28 let model = model(world)29 await model.load()30 #expect(model.phase == .loaded)31 #expect(model.sections.map(\.group) == [.overdue, .today, .upcoming, .noDate])32 #expect(model.sections[0].tasks.map(\.title) == ["Envoyer les documents à la banque"])33 #expect(model.sections[1].tasks.count == 2)34 #expect(model.sections[2].tasks.count == 2)35 #expect(model.openCount == 6)36 await model.setFilter(.done)37 #expect(model.sections.map(\.group) == [.done])38 await model.setFilter(.all)39 #expect(model.tasks.count == 7)40 }4142 @Test("a bare day is noon UTC: the day shown and grouped is the UTC date part, whatever the user's time zone")43 func bareDay() throws {44 let noon = try #require(APIDate.parse("2026-11-21T12:00:00.000Z"))45 let task = try APIJSON.decoder().decode(TaskItem.self, from: Data("""46 {"id":"t","title":"x","status":"todo","priority":"medium","dueAt":"2026-11-21T12:00:00.000Z","createdAt":"2026-11-01T00:00:00.000Z","updatedAt":"2026-11-01T00:00:00.000Z"}47 """.utf8))48 #expect(task.dueAt == noon)49 #expect(TasksModel.dueDay(task) == "2026-11-21")50 #expect(TasksModel.group(of: task, today: "2026-11-21") == .today)51 #expect(TasksModel.group(of: task, today: "2026-11-22") == .overdue)52 #expect(TasksModel.group(of: task, today: "2026-11-20") == .upcoming)53 // 23:30 in Tokyo on the 21st is still the 21st for a bare day.54 #expect(WorkDay.string(noon, timeZone: TimeZone(identifier: "Asia/Tokyo")!) == "2026-11-21")55 #expect(WorkDay.date("2026-11-21", hour: 12, timeZone: WorkDay.utc) == noon)56 #expect(WorkDay.date("pas une date", timeZone: WorkDay.utc) == nil)57 }5859 @Test("offline: the list is readable, a task is created, edited and completed locally, then reaches the server")60 func offlineFirst() async throws {61 let world = try await FeatureWorld()62 let model = model(world)63 await model.load()64 world.setOffline(true)65 model.draftTitle = "Écrire au notaire"66 model.draftDueDay = "2026-11-19"67 model.draftPriority = .high68 #expect(await model.add())69 #expect(model.actionFailure == nil)70 #expect(model.draftTitle.isEmpty)71 let created = try #require(model.tasks.first { $0.title == "Écrire au notaire" })72 #expect(TasksModel.group(of: created, today: model.todayDay) == .today)73 #expect(model.pendingIds.contains(created.id))74 #expect(model.waitingCount == 1)75 await model.setDue(day: "2026-12-01", id: created.id)76 await model.setStatus(.doing, id: created.id)77 await model.rename("Écrire au notaire (acte)", id: created.id)78 let edited = try #require(model.tasks.first { $0.id == created.id })79 #expect(edited.title == "Écrire au notaire (acte)")80 #expect(edited.status == "doing")81 #expect(TasksModel.dueDay(edited) == "2026-12-01")82 await model.setDue(day: nil, id: created.id)83 #expect(model.tasks.first { $0.id == created.id }?.dueAt == nil)84 world.setOffline(false)85 await world.sync()86 await model.load()87 #expect(model.pendingIds.isEmpty)88 #expect(world.fake.taskTitle(created.id) == "Écrire au notaire (acte)")89 }9091 @Test("toggle, delete and the page link through the router")92 func actions() async throws {93 let world = try await FeatureWorld()94 let router = FeatureRouterRecorder()95 let model = model(world, router: router)96 await model.load()97 let linked = try #require(model.tasks.first { $0.pageId == FeatureSamples.workProjectPageId })98 model.openPage(of: linked)99 #expect(router.calls == [.page(id: FeatureSamples.workProjectPageId, blockId: nil)])100 await model.toggle(linked)101 #expect(model.tasks.first { $0.id == linked.id } == nil) // done: leaves the open list102 let other = try #require(model.tasks.first)103 model.selectedTaskId = other.id104 await model.delete(id: other.id)105 #expect(model.selectedTaskId == nil)106 #expect(model.tasks.contains { $0.id == other.id } == false)107 await world.sync()108 #expect(world.fake.taskTitle(other.id) == nil)109 }110111 @Test("an empty title is refused calmly and nothing is created")112 func invalid() async throws {113 let world = try await FeatureWorld(samples: false)114 let model = model(world)115 await model.load()116 #expect(model.tasks.isEmpty)117 #expect(model.phase == .loaded)118 model.draftTitle = " "119 #expect(!model.canAdd)120 #expect(await model.add() == false)121 #expect(model.actionFailure?.kind == .other)122 #expect(model.tasks.isEmpty)123 }124125 @Test("a refused operation is surfaced with its error; discard gives the server's state back")126 func rejected() async throws {127 let world = try await FeatureWorld()128 let model = model(world)129 await model.load()130 let task = try #require(model.tasks.first)131 world.fake.inject(.status(422), method: "PATCH", path: "^/api/tasks/", count: 5)132 await model.rename("Titre refusé", id: task.id)133 await world.sync()134 await model.load()135 #expect(model.problems.count == 1)136 let problem = try #require(model.problems.first)137 #expect(problem.state == .rejected)138 #expect(model.describe(problem).contains("Modification"))139 await model.discard(problem)140 #expect(model.problems.isEmpty)141 #expect(model.tasks.first { $0.id == task.id }?.title == task.title)142 }143144 @Test("a refused operation can be retried and then goes through")145 func retry() async throws {146 let world = try await FeatureWorld()147 let model = model(world)148 await model.load()149 let task = try #require(model.tasks.first)150 world.fake.inject(.status(422), method: "PATCH", path: "^/api/tasks/", count: 1)151 await model.rename("Deuxième essai", id: task.id)152 await world.sync()153 await model.load()154 let problem = try #require(model.problems.first)155 await model.retry(problem)156 await world.sync()157 await model.load()158 #expect(model.problems.isEmpty)159 #expect(world.fake.taskTitle(task.id) == "Deuxième essai")160 }161162 @Test("a change made elsewhere arrives through the change stream")163 func liveRefresh() async throws {164 let world = try await FeatureWorld()165 let model = model(world)166 await model.load()167 let observer = Task { await model.observe() }168 let id = world.fake.webCreateTask(title: "Créée sur le Web")169 await world.sync()170 // Up to 30 s: the whole target runs in parallel with the hosted renders, a fixed second is not enough under load.171 let deadline = Date().addingTimeInterval(30)172 while !model.tasks.contains(where: { $0.id == id }), Date() < deadline { try await Task.sleep(for: .milliseconds(20)) }173 observer.cancel()174 #expect(model.tasks.contains { $0.id == id })175 }176177 @Test("a 2.x server: the screen is read-only and says so instead of failing")178 func legacyServer() async throws {179 let world = try await FeatureWorld(samples: false, apiLevel: 2)180 await world.sync()181 let model = model(world)182 await model.load()183 model.draftTitle = "Impossible ici"184 let added = await model.add()185 if !added {186 #expect(model.actionFailure?.kind == .unsupported)187 #expect(model.isReadOnly)188 #expect(!model.canAdd)189 } else {190 // The features of this server are not known yet: the repository lets the write through (documented behaviour).191 #expect(await world.repositories.features() == nil)192 }193 }194195 @Test("the tasks of one page only")196 func pageScope() async throws {197 let world = try await FeatureWorld()198 let model = model(world, pageId: FeatureSamples.workProjectPageId)199 await model.load()200 #expect(model.tasks.map(\.title) == ["Envoyer les documents à la banque"])201 model.draftTitle = "Rappeler le courtier"202 await model.add()203 #expect(model.tasks.count == 2)204 #expect(model.tasks.allSatisfy { $0.pageId == FeatureSamples.workProjectPageId })205 }206}207