@imenam/mcp-organizer 1.0.19 → 1.0.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (106) hide show
  1. package/README.md +103 -29
  2. package/dist/shared/logic/attachments.d.ts +28 -0
  3. package/dist/shared/logic/attachments.js +52 -0
  4. package/dist/shared/logic/documents.d.ts +22 -0
  5. package/dist/shared/logic/documents.js +38 -0
  6. package/dist/shared/logic/line-diff.d.ts +13 -0
  7. package/dist/shared/logic/line-diff.js +66 -0
  8. package/dist/shared/logic/notes.d.ts +12 -0
  9. package/dist/shared/logic/notes.js +23 -0
  10. package/dist/shared/logic/timer.d.ts +69 -0
  11. package/dist/shared/logic/timer.js +87 -0
  12. package/dist/shared/schemas/agent-api.schema.d.ts +10 -29
  13. package/dist/shared/schemas/agent-api.schema.js +4 -15
  14. package/dist/shared/schemas/agent-tools.schema.d.ts +522 -2
  15. package/dist/shared/schemas/agent-tools.schema.js +111 -6
  16. package/dist/shared/schemas/api.schema.d.ts +7 -0
  17. package/dist/shared/schemas/api.schema.js +6 -0
  18. package/dist/shared/schemas/documents-api.schema.d.ts +49 -0
  19. package/dist/shared/schemas/documents-api.schema.js +38 -0
  20. package/dist/shared/schemas/entities.schema.d.ts +107 -54
  21. package/dist/shared/schemas/entities.schema.js +81 -10
  22. package/dist/shared/schemas/enums.schema.d.ts +19 -3
  23. package/dist/shared/schemas/enums.schema.js +8 -2
  24. package/dist/shared/schemas/gui-api.schema.d.ts +1 -0
  25. package/dist/shared/schemas/gui-api.schema.js +2 -0
  26. package/dist/shared/schemas/history-api.schema.d.ts +961 -0
  27. package/dist/shared/schemas/history-api.schema.js +104 -0
  28. package/dist/shared/schemas/notes-api.schema.d.ts +54 -0
  29. package/dist/shared/schemas/notes-api.schema.js +38 -0
  30. package/dist/shared/schemas/notifications-api.schema.d.ts +12 -0
  31. package/dist/shared/schemas/notifications-api.schema.js +4 -1
  32. package/dist/shared/schemas/tasks-api.schema.d.ts +39 -0
  33. package/dist/shared/schemas/tasks-api.schema.js +5 -0
  34. package/dist/shared/schemas/timers-api.schema.d.ts +119 -0
  35. package/dist/shared/schemas/timers-api.schema.js +44 -0
  36. package/dist/shared/schemas/views-api.schema.d.ts +16 -0
  37. package/dist/shared/schemas/views-api.schema.js +4 -2
  38. package/dist/src/agent-api/documents.d.ts +3 -0
  39. package/dist/src/agent-api/documents.js +66 -0
  40. package/dist/src/agent-api/history.d.ts +3 -0
  41. package/dist/src/agent-api/history.js +103 -0
  42. package/dist/src/agent-api/notes.d.ts +3 -0
  43. package/dist/src/agent-api/notes.js +39 -0
  44. package/dist/src/agent-api/requests.js +2 -1
  45. package/dist/src/agent-api/router.js +5 -1
  46. package/dist/src/agent-api/tasks.js +17 -6
  47. package/dist/src/agent-api/timers.d.ts +2 -0
  48. package/dist/src/agent-api/timers.js +170 -0
  49. package/dist/src/agent-api/types.d.ts +3 -0
  50. package/dist/src/agent-api/views.js +15 -30
  51. package/dist/src/cli/backup.js +3 -3
  52. package/dist/src/core/accounts.d.ts +12 -5
  53. package/dist/src/core/accounts.js +28 -10
  54. package/dist/src/core/agent.d.ts +27 -3
  55. package/dist/src/core/agent.js +118 -1
  56. package/dist/src/core/attachments.d.ts +6 -3
  57. package/dist/src/core/attachments.js +9 -4
  58. package/dist/src/core/board-views.js +4 -4
  59. package/dist/src/core/document-text.d.ts +17 -0
  60. package/dist/src/core/document-text.js +118 -0
  61. package/dist/src/core/documents.d.ts +22 -0
  62. package/dist/src/core/documents.js +168 -0
  63. package/dist/src/core/history-events.d.ts +34 -0
  64. package/dist/src/core/history-events.js +236 -0
  65. package/dist/src/core/history.js +33 -3
  66. package/dist/src/core/migrations.js +153 -0
  67. package/dist/src/core/notes.d.ts +23 -0
  68. package/dist/src/core/notes.js +78 -0
  69. package/dist/src/core/notifications.d.ts +48 -5
  70. package/dist/src/core/notifications.js +209 -33
  71. package/dist/src/core/password-reset.d.ts +37 -0
  72. package/dist/src/core/password-reset.js +56 -0
  73. package/dist/src/core/requests.d.ts +4 -3
  74. package/dist/src/core/requests.js +5 -4
  75. package/dist/src/core/snapshots.d.ts +3 -3
  76. package/dist/src/core/snapshots.js +3 -1
  77. package/dist/src/core/space-history.d.ts +18 -0
  78. package/dist/src/core/space-history.js +86 -0
  79. package/dist/src/core/spaces.d.ts +1 -1
  80. package/dist/src/core/spaces.js +4 -4
  81. package/dist/src/core/store.d.ts +154 -11
  82. package/dist/src/core/store.js +479 -52
  83. package/dist/src/core/task-history.d.ts +9 -5
  84. package/dist/src/core/task-history.js +17 -25
  85. package/dist/src/core/tasks.d.ts +2 -2
  86. package/dist/src/core/tasks.js +13 -2
  87. package/dist/src/core/timers.d.ts +33 -0
  88. package/dist/src/core/timers.js +101 -0
  89. package/dist/src/core/versions.d.ts +22 -0
  90. package/dist/src/core/versions.js +106 -0
  91. package/dist/src/gui-api.d.ts +4 -1
  92. package/dist/src/gui-api.js +85 -6
  93. package/dist/src/mcp/start.d.ts +1 -1
  94. package/dist/src/mcp/start.js +12 -7
  95. package/dist/src/mcp/tools.js +129 -3
  96. package/dist/src/server/app.d.ts +4 -2
  97. package/dist/src/server/app.js +21 -5
  98. package/dist/src/server/login-limiter.d.ts +27 -1
  99. package/dist/src/server/login-limiter.js +31 -1
  100. package/dist/src/server/start.js +1 -0
  101. package/gui/dist/assets/index-DbzcjyaW.js +104 -0
  102. package/gui/dist/assets/index-Dvf5Yo0e.css +1 -0
  103. package/gui/dist/index.html +2 -2
  104. package/package.json +1 -1
  105. package/gui/dist/assets/index-B-AB8nGt.css +0 -1
  106. package/gui/dist/assets/index-DU-RfoVk.js +0 -99
@@ -3,8 +3,9 @@ import { ForbiddenError, InvariantError, NotFoundError, OrganizerError } from ".
3
3
  import { positionBetween } from "../../shared/logic/positions.js";
4
4
  import { newId } from "./ids.js";
5
5
  import { WatcherRegistry } from "./watchers.js";
6
- import { MAX_TASK_DEPTH, TASK_PRIORITIES, TASK_STATUSES, } from "../../shared/schemas/enums.schema.js";
7
- import { AccessLinkSchema, AgentActionSchema, AgentInstructionsSchema, AgentTokenSchema, AgentRequestSchema, AttachmentSchema, BoardViewSchema, ChangeSchema, ChecklistItemSchema, CommentSchema, MAX_QUESTION_OPTIONS, QuestionOptionSchema, TaskQuestionSchema, EntityVersionSchema, FollowUpSchema, IdeaSchema, IdeaSnapshotSchema, InvitationSchema, MembershipSchema, NotificationSchema, SessionSchema, SpaceSchema, TagSchema, TaskSchema, TaskSnapshotSchema, TestCheckpointSchema, TestResultSchema, TestReviewSchema, UserSchema, UserSettingsSchema, SpaceNotificationSettingsSchema, } from "../../shared/schemas/entities.schema.js";
6
+ import { isVisibleVersion, VERSION_SNAPSHOT_SCHEMAS, versionSnapshot } from "./versions.js";
7
+ import { MAX_TASK_DEPTH, TASK_PRIORITIES, TASK_STATUSES, TASK_TYPES, VERSIONED_ENTITY_TYPES, } from "../../shared/schemas/enums.schema.js";
8
+ import { AccessLinkSchema, AgentActionSchema, AgentInstructionsSchema, AgentTokenSchema, AgentRequestSchema, AttachmentSchema, BoardViewSchema, ChangeSchema, ChecklistItemSchema, CommentSchema, MAX_QUESTION_OPTIONS, QuestionOptionSchema, TaskQuestionSchema, EntityVersionSchema, FollowUpSchema, IdeaSchema, InvitationSchema, NoteSchema, SpaceDocumentSchema, MembershipSchema, NotificationSchema, SessionSchema, SpaceSchema, TagSchema, TaskSchema, TaskSnapshotSchema, TestCheckpointSchema, TestResultSchema, TestReviewSchema, TimeSessionSchema, UserSchema, UserSettingsSchema, SpaceNotificationSettingsSchema, } from "../../shared/schemas/entities.schema.js";
8
9
  import { ClaudeConnectionSchema, RunnerSessionRecordSchema, RunnerSettingsSchema, } from "../../shared/schemas/admin-api.schema.js";
9
10
  /** Valide `value` avec `schema` ; une donnée invalide est une erreur métier qui liste les champs fautifs. */
10
11
  function validate(schema, value, what) {
@@ -76,6 +77,28 @@ function settingsFromRow(row) {
76
77
  notifyFollowUpApp: bool(row.notify_follow_up_app),
77
78
  notifyFollowUpEmail: bool(row.notify_follow_up_email),
78
79
  assistantHistory: row.assistant_history,
80
+ pomodoro: {
81
+ workMinutes: row.pomodoro_work_minutes,
82
+ shortBreakMinutes: row.pomodoro_short_break_minutes,
83
+ longBreakMinutes: row.pomodoro_long_break_minutes,
84
+ cycles: row.pomodoro_cycles,
85
+ },
86
+ });
87
+ }
88
+ function timeSessionFromRow(row) {
89
+ return TimeSessionSchema.parse({
90
+ id: row.id,
91
+ spaceId: row.space_id,
92
+ taskId: row.task_id,
93
+ userId: row.user_id,
94
+ mode: row.mode,
95
+ pomodoro: row.work_minutes === null
96
+ ? null
97
+ : { workMinutes: row.work_minutes, shortBreakMinutes: row.short_break_minutes, longBreakMinutes: row.long_break_minutes, cycles: row.cycles },
98
+ startedAt: row.started_at,
99
+ endedAt: row.ended_at,
100
+ runningSince: row.running_since,
101
+ elapsedMs: row.elapsed_ms,
79
102
  });
80
103
  }
81
104
  function sessionFromRow(row) {
@@ -169,6 +192,34 @@ function ideaFromRow(row) {
169
192
  createdAt: row.created_at,
170
193
  });
171
194
  }
195
+ function noteFromRow(row) {
196
+ return NoteSchema.parse({
197
+ id: row.id,
198
+ spaceId: row.space_id,
199
+ authorId: row.author_id,
200
+ title: row.title,
201
+ body: row.body,
202
+ updatedBy: row.updated_by,
203
+ createdAt: row.created_at,
204
+ updatedAt: row.updated_at,
205
+ });
206
+ }
207
+ function documentFromRow(row) {
208
+ return SpaceDocumentSchema.parse({
209
+ id: row.id,
210
+ spaceId: row.space_id,
211
+ uploaderId: row.uploader_id,
212
+ filename: row.filename,
213
+ description: row.description,
214
+ mime: row.mime,
215
+ size: row.size,
216
+ version: row.version,
217
+ storagePath: row.storage_path,
218
+ updatedBy: row.updated_by,
219
+ createdAt: row.created_at,
220
+ updatedAt: row.updated_at,
221
+ });
222
+ }
172
223
  function boardViewFromRow(row) {
173
224
  return BoardViewSchema.parse({
174
225
  id: row.id,
@@ -184,6 +235,7 @@ function boardViewFromRow(row) {
184
235
  assigneeIds: JSON.parse(row.assignee_ids),
185
236
  unassigned: bool(row.unassigned),
186
237
  tagIds: JSON.parse(row.tag_ids),
238
+ types: JSON.parse(row.types),
187
239
  position: row.position,
188
240
  createdAt: row.created_at,
189
241
  updatedAt: row.updated_at,
@@ -224,14 +276,43 @@ function followUpFromRow(row) {
224
276
  doneByRequestId: row.done_by_request_id,
225
277
  });
226
278
  }
279
+ function historyFilterClause(filters) {
280
+ const parts = [];
281
+ const params = [];
282
+ if (filters.actor?.type === "agent")
283
+ parts.push("v.actor_type = 'agent'");
284
+ if (filters.actor?.type === "user") {
285
+ parts.push("v.actor_type = 'user' AND v.actor_id = ?");
286
+ params.push(filters.actor.userId);
287
+ }
288
+ if (filters.entityTypes !== null) {
289
+ parts.push(filters.entityTypes.length === 0 ? "0" : `v.entity_type IN (${filters.entityTypes.map(() => "?").join(", ")})`);
290
+ params.push(...filters.entityTypes);
291
+ }
292
+ if (filters.since !== null) {
293
+ parts.push("v.created_at >= ?");
294
+ params.push(filters.since);
295
+ }
296
+ return { clause: parts.map((part) => `AND ${part}`).join(" "), params };
297
+ }
298
+ function historyRowFromRow(row) {
299
+ const version = versionFromRow(row);
300
+ const previousExists = row.previous_version !== null;
301
+ const previous = row.previous_snapshot === null ? null : VERSION_SNAPSHOT_SCHEMAS[version.entityType].parse(JSON.parse(row.previous_snapshot));
302
+ return { version, previousExists, previous };
303
+ }
227
304
  function versionFromRow(row) {
228
- const raw = row.snapshot === null ? null : JSON.parse(row.snapshot);
229
- const snapshot = raw === null ? null : row.entity_type === "task" ? TaskSnapshotSchema.parse(raw) : IdeaSnapshotSchema.parse(raw);
305
+ const entityType = row.entity_type;
306
+ const snapshot = row.snapshot === null ? null : VERSION_SNAPSHOT_SCHEMAS[entityType].parse(JSON.parse(row.snapshot));
230
307
  return EntityVersionSchema.parse({
231
- entityType: row.entity_type,
308
+ seq: row.seq,
309
+ entityType,
232
310
  entityId: row.entity_id,
233
311
  version: row.version,
312
+ spaceId: row.space_id,
313
+ taskId: row.task_id,
234
314
  snapshot,
315
+ visible: row.visible === 1,
235
316
  actorType: row.actor_type,
236
317
  actorId: row.actor_id,
237
318
  requestId: row.request_id,
@@ -760,6 +841,13 @@ export class Store {
760
841
  const rows = this.db.prepare("SELECT c.task_id, c.done FROM checklist_items c JOIN tasks t ON t.id = c.task_id WHERE t.space_id = ?").all(spaceId);
761
842
  return rows.map((row) => ({ taskId: row.task_id, done: bool(row.done) }));
762
843
  }
844
+ /** Questions des tâches d'un espace : répondue dès qu'une réponse est enregistrée. */
845
+ listQuestionsInSpace(spaceId) {
846
+ const rows = this.db
847
+ .prepare("SELECT q.task_id, q.answered_at IS NOT NULL AS answered FROM task_questions q JOIN tasks t ON t.id = q.task_id WHERE t.space_id = ?")
848
+ .all(spaceId);
849
+ return rows.map((row) => ({ taskId: row.task_id, answered: bool(row.answered) }));
850
+ }
763
851
  /** Résultats saisis sur les points des tâches d'un espace. */
764
852
  listTestResultsInSpace(spaceId) {
765
853
  const rows = this.db
@@ -835,6 +923,38 @@ export class Store {
835
923
  const rows = this.db.prepare("SELECT * FROM ideas WHERE space_id = ? ORDER BY created_at DESC, id").all(spaceId);
836
924
  return rows.map(ideaFromRow);
837
925
  }
926
+ // --- Notes ---
927
+ findNote(id) {
928
+ const row = this.db.prepare("SELECT * FROM notes WHERE id = ?").get(id);
929
+ return row ? noteFromRow(row) : null;
930
+ }
931
+ getNote(id) {
932
+ const note = this.findNote(id);
933
+ if (!note)
934
+ throw new NotFoundError(`Note ${id} not found.`);
935
+ return note;
936
+ }
937
+ /** Notes d'un espace, de la plus récemment modifiée à la plus ancienne. */
938
+ listNotes(spaceId) {
939
+ const rows = this.db.prepare("SELECT * FROM notes WHERE space_id = ? ORDER BY updated_at DESC, id").all(spaceId);
940
+ return rows.map(noteFromRow);
941
+ }
942
+ // --- Documents ---
943
+ findDocument(id) {
944
+ const row = this.db.prepare("SELECT * FROM documents WHERE id = ?").get(id);
945
+ return row ? documentFromRow(row) : null;
946
+ }
947
+ getDocument(id) {
948
+ const document = this.findDocument(id);
949
+ if (!document)
950
+ throw new NotFoundError(`Document ${id} not found.`);
951
+ return document;
952
+ }
953
+ /** Documents d'un espace, du plus récemment modifié au plus ancien. */
954
+ listDocuments(spaceId) {
955
+ const rows = this.db.prepare("SELECT * FROM documents WHERE space_id = ? ORDER BY updated_at DESC, id").all(spaceId);
956
+ return rows.map(documentFromRow);
957
+ }
838
958
  /** Demandes de promotion (`idea_promotion`) en attente ou en cours sur les idées d'un espace. */
839
959
  listOpenPromotionRequests(spaceId) {
840
960
  const rows = this.db
@@ -844,6 +964,36 @@ export class Store {
844
964
  return rows.map(requestFromRow);
845
965
  }
846
966
  // --- Vues du tableau de bord ---
967
+ findTimeSession(id) {
968
+ const row = this.db.prepare("SELECT * FROM time_sessions WHERE id = ?").get(id);
969
+ return row ? timeSessionFromRow(row) : null;
970
+ }
971
+ getTimeSession(id) {
972
+ const session = this.findTimeSession(id);
973
+ if (!session)
974
+ throw new NotFoundError(`Time session ${id} not found.`);
975
+ return session;
976
+ }
977
+ /** Sessions de chrono d'une tâche, de la plus ancienne à la plus récente. */
978
+ listTimeSessions(taskId) {
979
+ const rows = this.db.prepare("SELECT * FROM time_sessions WHERE task_id = ? ORDER BY started_at, id").all(taskId);
980
+ return rows.map(timeSessionFromRow);
981
+ }
982
+ /** Sessions actives (en marche ou en pause) d'un utilisateur, la plus récente d'abord. */
983
+ listActiveTimeSessionsOf(userId) {
984
+ const rows = this.db.prepare("SELECT * FROM time_sessions WHERE user_id = ? AND ended_at IS NULL ORDER BY started_at DESC, id").all(userId);
985
+ return rows.map(timeSessionFromRow);
986
+ }
987
+ /** Session active d'un utilisateur sur une tâche. */
988
+ findActiveTimeSession(taskId, userId) {
989
+ const row = this.db.prepare("SELECT * FROM time_sessions WHERE task_id = ? AND user_id = ? AND ended_at IS NULL").get(taskId, userId);
990
+ return row ? timeSessionFromRow(row) : null;
991
+ }
992
+ /** Session en marche d'un utilisateur, toutes tâches confondues. */
993
+ findRunningTimeSessionOf(userId) {
994
+ const row = this.db.prepare("SELECT * FROM time_sessions WHERE user_id = ? AND running_since IS NOT NULL").get(userId);
995
+ return row ? timeSessionFromRow(row) : null;
996
+ }
847
997
  findBoardView(id) {
848
998
  const row = this.db.prepare("SELECT * FROM board_views WHERE id = ?").get(id);
849
999
  return row ? boardViewFromRow(row) : null;
@@ -940,6 +1090,14 @@ export class Store {
940
1090
  const row = this.db.prepare("SELECT COUNT(*) AS n FROM agent_requests WHERE status = 'pending' AND target_space_id = ?").get(spaceId);
941
1091
  return row.n;
942
1092
  }
1093
+ /** Nombre de demandes d'un espace qui attendent l'utilisateur : traitées avec un point à régler ouvert, ou en échec. */
1094
+ countWaitingRequestsOfSpace(spaceId) {
1095
+ const row = this.db
1096
+ .prepare(`SELECT COUNT(*) AS n FROM agent_requests r WHERE r.target_space_id = ? AND (r.status = 'failed'
1097
+ OR (r.status = 'done' AND EXISTS (SELECT 1 FROM follow_ups f WHERE f.request_id = r.id AND f.done_at IS NULL)))`)
1098
+ .get(spaceId);
1099
+ return row.n;
1100
+ }
943
1101
  // --- Actions de l'agent ---
944
1102
  findAgentAction(id) {
945
1103
  const row = this.db.prepare("SELECT * FROM agent_actions WHERE id = ?").get(id);
@@ -996,6 +1154,11 @@ export class Store {
996
1154
  .all(userId, limit, offset);
997
1155
  return rows.map(notificationFromRow);
998
1156
  }
1157
+ /** Notifications dont l'e-mail attend d'être envoyé, les plus anciennes d'abord. */
1158
+ listEmailPendingNotifications() {
1159
+ const rows = this.db.prepare("SELECT * FROM notifications WHERE email_pending = 1 ORDER BY created_at, id").all();
1160
+ return rows.map(notificationFromRow);
1161
+ }
999
1162
  /** Nombre de notifications non lues affichées dans l'application d'un utilisateur. */
1000
1163
  countUnreadNotifications(userId) {
1001
1164
  const row = this.db
@@ -1017,6 +1180,67 @@ export class Store {
1017
1180
  .all(entityType, entityId);
1018
1181
  return rows.map(versionFromRow);
1019
1182
  }
1183
+ /** Dernière version d'une entité, ou null si elle n'en a aucune. */
1184
+ latestVersion(entityType, entityId) {
1185
+ const row = this.db
1186
+ .prepare("SELECT * FROM entity_versions WHERE entity_type = ? AND entity_id = ? ORDER BY version DESC LIMIT 1")
1187
+ .get(entityType, entityId);
1188
+ return row ? versionFromRow(row) : null;
1189
+ }
1190
+ /** Dernier instantané connu d'une entité, existante ou supprimée ; null si elle n'en a aucun. */
1191
+ lastSnapshot(entityType, entityId) {
1192
+ const row = this.db
1193
+ .prepare("SELECT snapshot FROM entity_versions WHERE entity_type = ? AND entity_id = ? AND snapshot IS NOT NULL ORDER BY version DESC LIMIT 1")
1194
+ .get(entityType, entityId);
1195
+ return row ? VERSION_SNAPSHOT_SCHEMAS[entityType].parse(JSON.parse(row.snapshot)) : null;
1196
+ }
1197
+ /** Dernier instantané connu d'une tâche, existante ou supprimée ; null si elle n'a aucune version. */
1198
+ lastTaskSnapshot(taskId) {
1199
+ const snapshot = this.lastSnapshot("task", taskId);
1200
+ return snapshot === null ? null : TaskSnapshotSchema.parse(snapshot);
1201
+ }
1202
+ /**
1203
+ * Versions visibles d'un espace, de la plus récente à la plus ancienne,
1204
+ * antérieures au numéro `before` quand il est donné, au plus `limit`.
1205
+ */
1206
+ listSpaceHistory(spaceId, filters, before, limit) {
1207
+ const { clause, params } = historyFilterClause(filters);
1208
+ const rows = this.db
1209
+ .prepare(`SELECT v.*, p.version AS previous_version, p.snapshot AS previous_snapshot FROM entity_versions v
1210
+ LEFT JOIN entity_versions p ON p.entity_type = v.entity_type AND p.entity_id = v.entity_id AND p.version = v.version - 1
1211
+ WHERE v.space_id = ? AND v.visible = 1 ${clause} ${before === null ? "" : "AND v.seq < ?"}
1212
+ ORDER BY v.seq DESC LIMIT ?`)
1213
+ .all(spaceId, ...params, ...(before === null ? [] : [before]), limit);
1214
+ return rows.map(historyRowFromRow);
1215
+ }
1216
+ /** Nombre de versions visibles d'un espace qui passent les filtres. */
1217
+ countSpaceHistory(spaceId, filters) {
1218
+ const { clause, params } = historyFilterClause(filters);
1219
+ const row = this.db.prepare(`SELECT COUNT(*) AS n FROM entity_versions v WHERE v.space_id = ? AND v.visible = 1 ${clause}`).get(spaceId, ...params);
1220
+ return row.n;
1221
+ }
1222
+ /** Versions visibles d'une tâche et des éléments qu'elle porte (checklist, points de vérification), de la plus récente à la plus ancienne. */
1223
+ listTaskHistory(taskId) {
1224
+ const rows = this.db
1225
+ .prepare(`SELECT v.*, p.version AS previous_version, p.snapshot AS previous_snapshot FROM entity_versions v
1226
+ LEFT JOIN entity_versions p ON p.entity_type = v.entity_type AND p.entity_id = v.entity_id AND p.version = v.version - 1
1227
+ WHERE v.task_id = ? AND v.visible = 1 ORDER BY v.seq DESC`)
1228
+ .all(taskId);
1229
+ return rows.map(historyRowFromRow);
1230
+ }
1231
+ /**
1232
+ * Entités d'un espace supprimées par la mutation horodatée `at` et toujours
1233
+ * supprimées : leur dernière version, sans instantané, porte cette date.
1234
+ */
1235
+ listDeletedAt(spaceId, at) {
1236
+ const rows = this.db
1237
+ .prepare(`SELECT v.* FROM entity_versions v
1238
+ WHERE v.space_id = ? AND v.created_at = ? AND v.snapshot IS NULL
1239
+ AND v.version = (SELECT MAX(o.version) FROM entity_versions o WHERE o.entity_type = v.entity_type AND o.entity_id = v.entity_id)
1240
+ ORDER BY v.seq`)
1241
+ .all(spaceId, at);
1242
+ return rows.map(versionFromRow);
1243
+ }
1020
1244
  /** Changements de numéro strictement supérieur à `since`, dans l'ordre. */
1021
1245
  listChangesSince(since) {
1022
1246
  const rows = this.db.prepare("SELECT * FROM changes WHERE seq > ? ORDER BY seq").all(since);
@@ -1040,9 +1264,10 @@ export class Store {
1040
1264
  }
1041
1265
  // --- Mutation ---
1042
1266
  /**
1043
- * Abonne `listener` aux notifications dont le destinataire veut un e-mail :
1044
- * il reçoit leurs identifiants après la validation de la mutation qui les a
1045
- * créées.
1267
+ * Abonne `listener` aux mutations qui peuvent rendre un e-mail de
1268
+ * notification prêt à partir : celles qui créent une notification à envoyer
1269
+ * par e-mail ou qui touchent une demande de l'agent. Il est appelé après la
1270
+ * validation de la mutation.
1046
1271
  */
1047
1272
  setEmailListener(listener) {
1048
1273
  this.emailListener = listener;
@@ -1070,7 +1295,7 @@ export class Store {
1070
1295
  mutate(actor, fn) {
1071
1296
  if (this.activeMutation)
1072
1297
  throw new Error("Store.mutate is not reentrant: use the Mutation passed to the running mutation.");
1073
- let emails = [];
1298
+ let emails = false;
1074
1299
  let pending = [];
1075
1300
  let allowed = [];
1076
1301
  const run = this.db.transaction(() => {
@@ -1079,7 +1304,7 @@ export class Store {
1079
1304
  try {
1080
1305
  const result = fn(tx);
1081
1306
  tx.finish();
1082
- emails = tx.emailNotificationIds;
1307
+ emails = tx.emailNotificationIds.length > 0 || tx.touchedRequestIds.size > 0;
1083
1308
  pending = tx.pendingRequestIds;
1084
1309
  allowed = tx.runnerAllowedSpaceIds;
1085
1310
  return result;
@@ -1089,8 +1314,8 @@ export class Store {
1089
1314
  }
1090
1315
  });
1091
1316
  const result = run.immediate();
1092
- if (emails.length > 0 && this.emailListener)
1093
- this.emailListener(emails);
1317
+ if (emails && this.emailListener)
1318
+ this.emailListener();
1094
1319
  if (pending.length > 0 && this.pendingRequestListeners.size > 0) {
1095
1320
  for (const id of pending) {
1096
1321
  const request = this.getAgentRequest(id);
@@ -1106,7 +1331,7 @@ export class Store {
1106
1331
  return result;
1107
1332
  }
1108
1333
  }
1109
- const VERSIONED = new Set(["task", "idea"]);
1334
+ const VERSIONED = new Set(VERSIONED_ENTITY_TYPES);
1110
1335
  /** Texte d'une demande `direct` dont le lot n'a aucune action. */
1111
1336
  const DIRECT_REQUEST_TEXT = "Action directe de l'agent";
1112
1337
  /** Texte d'une demande `direct` qui porte un compte rendu de l'agent et ses points à régler. */
@@ -1123,6 +1348,8 @@ export class Mutation {
1123
1348
  touched = new Map();
1124
1349
  /** Notifications créées par la mutation dont le destinataire veut un e-mail. */
1125
1350
  emailNotificationIds = [];
1351
+ /** Demandes de l'agent touchées par la mutation. */
1352
+ touchedRequestIds = new Set();
1126
1353
  /** Demandes passées en attente par la mutation : créées, ou libérées. */
1127
1354
  pendingRequestIds = [];
1128
1355
  /** Espaces où la mutation a autorisé le runner. */
@@ -1449,10 +1676,6 @@ export class Mutation {
1449
1676
  for (const membership of this.store.listMemberships(id)) {
1450
1677
  this.touch("membership", `${id}:${membership.userId}`, id, membership.userId);
1451
1678
  }
1452
- this.db
1453
- .prepare(`DELETE FROM entity_versions WHERE (entity_type = 'task' AND entity_id IN (SELECT id FROM tasks WHERE space_id = ?))
1454
- OR (entity_type = 'idea' AND entity_id IN (SELECT id FROM ideas WHERE space_id = ?))`)
1455
- .run(id, id);
1456
1679
  this.db.prepare("DELETE FROM spaces WHERE id = ?").run(id);
1457
1680
  this.touch("space", id, id, null);
1458
1681
  }
@@ -1571,7 +1794,8 @@ export class Mutation {
1571
1794
  }
1572
1795
  /**
1573
1796
  * Supprime une tâche et ses sous-tâches ; chacune reçoit une version de
1574
- * suppression. Les tâches de test qui vérifiaient une tâche supprimée
1797
+ * suppression, comme les éléments de checklist et points de vérification
1798
+ * qu'elles portent. Les tâches de test qui vérifiaient une tâche supprimée
1575
1799
  * perdent ce lien, avec une nouvelle version.
1576
1800
  */
1577
1801
  deleteTask(id) {
@@ -1584,11 +1808,45 @@ export class Mutation {
1584
1808
  this.db.prepare("UPDATE tasks SET tested_task_id = NULL, updated_at = ? WHERE id = ?").run(this.now, test.id);
1585
1809
  this.touch("task", test.id, test.spaceId, null);
1586
1810
  }
1811
+ for (const item of this.store.listChecklist(id))
1812
+ this.touch("checklist_item", item.id, task.spaceId, null, id);
1813
+ for (const checkpoint of this.store.listCheckpoints(id))
1814
+ this.touch("test_checkpoint", checkpoint.id, task.spaceId, null, id);
1587
1815
  this.db.prepare("DELETE FROM tasks WHERE id = ?").run(id);
1588
1816
  this.touch("task", id, task.spaceId, null);
1589
1817
  }
1590
- /** Remplace les assignés (ou testeurs) d'une tâche. */
1591
- setAssignees(taskId, userIds) {
1818
+ /**
1819
+ * Recrée une tâche supprimée d'après son dernier instantané, avec son
1820
+ * identifiant et son numéro, sous son parent d'alors (qui doit exister). Elle
1821
+ * reprend sa position si elle est libre dans sa colonne, sinon va en fin de
1822
+ * colonne ; sa tâche testée n'est reprise que si elle existe encore. Les
1823
+ * assignés et les tags ne sont pas posés ici.
1824
+ */
1825
+ restoreTask(snapshot) {
1826
+ if (this.store.findTask(snapshot.id))
1827
+ throw new InvariantError(`Task ${taskLabel(this.db, snapshot)} already exists.`);
1828
+ const space = this.store.getSpace(snapshot.spaceId);
1829
+ const parent = snapshot.parentId === null ? null : this.store.getTask(snapshot.parentId);
1830
+ const depth = parent === null ? 0 : this.childDepth(parent, space.id);
1831
+ const taken = this.store.listColumn(space.id, snapshot.parentId, snapshot.status).some((task) => task.position === snapshot.position);
1832
+ const testedTaskId = snapshot.testedTaskId !== null && this.store.findTask(snapshot.testedTaskId) ? snapshot.testedTaskId : null;
1833
+ const task = validate(TaskSchema, {
1834
+ ...snapshot,
1835
+ depth,
1836
+ position: taken ? this.endOfColumn(space.id, snapshot.parentId, snapshot.status, null) : snapshot.position,
1837
+ testedTaskId,
1838
+ updatedAt: this.now,
1839
+ }, "task");
1840
+ this.db
1841
+ .prepare(`INSERT INTO tasks (id, space_id, number, parent_id, depth, type, title, description, status, priority, position, tested_task_id,
1842
+ created_by, created_at, updated_at, version)
1843
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)
1844
+ .run(task.id, task.spaceId, task.number, task.parentId, task.depth, task.type, task.title, task.description, task.status, task.priority, task.position, task.testedTaskId, task.createdBy, task.createdAt, task.updatedAt, task.version);
1845
+ this.touch("task", task.id, task.spaceId, null);
1846
+ return task;
1847
+ }
1848
+ /** Remplace les assignés (ou testeurs) d'une tâche ; les nouveaux assignés sont notifiés, sauf avec `notify` faux. */
1849
+ setAssignees(taskId, userIds, notify = true) {
1592
1850
  const task = this.store.getTask(taskId);
1593
1851
  const unique = [...new Set(userIds)].sort();
1594
1852
  for (const userId of unique)
@@ -1600,7 +1858,7 @@ export class Mutation {
1600
1858
  insert.run(taskId, userId);
1601
1859
  this.db.prepare("UPDATE tasks SET updated_at = ? WHERE id = ?").run(this.now, taskId);
1602
1860
  this.touch("task", taskId, task.spaceId, null);
1603
- for (const userId of unique) {
1861
+ for (const userId of notify ? unique : []) {
1604
1862
  if (previous.has(userId) || this.isActingUser(userId))
1605
1863
  continue;
1606
1864
  this.notify("assigned", userId, taskId, null);
@@ -2204,6 +2462,70 @@ export class Mutation {
2204
2462
  this.db.prepare("DELETE FROM ideas WHERE id = ?").run(id);
2205
2463
  this.touch("idea", id, idea.spaceId, null);
2206
2464
  }
2465
+ // --- Notes ---
2466
+ createNote(input) {
2467
+ this.store.getSpace(input.spaceId);
2468
+ const note = validate(NoteSchema, {
2469
+ id: newId(),
2470
+ spaceId: input.spaceId,
2471
+ authorId: this.actingUserId,
2472
+ title: input.title,
2473
+ body: input.body,
2474
+ updatedBy: this.actingUserId,
2475
+ createdAt: this.now,
2476
+ updatedAt: this.now,
2477
+ }, "note");
2478
+ this.db
2479
+ .prepare("INSERT INTO notes (id, space_id, author_id, title, body, updated_by, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)")
2480
+ .run(note.id, note.spaceId, note.authorId, note.title, note.body, note.updatedBy, note.createdAt, note.updatedAt);
2481
+ this.touch("note", note.id, note.spaceId, null);
2482
+ return note;
2483
+ }
2484
+ updateNote(id, patch) {
2485
+ const current = this.store.getNote(id);
2486
+ const note = validate(NoteSchema, { ...current, ...definedFields(patch), updatedBy: this.actingUserId, updatedAt: this.now }, "note");
2487
+ this.db.prepare("UPDATE notes SET title = ?, body = ?, updated_by = ?, updated_at = ? WHERE id = ?").run(note.title, note.body, note.updatedBy, note.updatedAt, id);
2488
+ this.touch("note", id, note.spaceId, null);
2489
+ return note;
2490
+ }
2491
+ deleteNote(id) {
2492
+ const note = this.store.getNote(id);
2493
+ this.db.prepare("DELETE FROM notes WHERE id = ?").run(id);
2494
+ this.touch("note", id, note.spaceId, null);
2495
+ }
2496
+ // --- Documents ---
2497
+ createDocument(input) {
2498
+ this.store.getSpace(input.spaceId);
2499
+ const document = validate(SpaceDocumentSchema, { ...input, uploaderId: this.actingUserId, version: 1, updatedBy: this.actingUserId, createdAt: this.now, updatedAt: this.now }, "document");
2500
+ this.db
2501
+ .prepare(`INSERT INTO documents (id, space_id, uploader_id, filename, description, mime, size, version, storage_path, updated_by, created_at, updated_at)
2502
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)
2503
+ .run(document.id, document.spaceId, document.uploaderId, document.filename, document.description, document.mime, document.size, document.version, document.storagePath, document.updatedBy, document.createdAt, document.updatedAt);
2504
+ this.touch("document", document.id, document.spaceId, null);
2505
+ return document;
2506
+ }
2507
+ replaceDocumentFile(id, file) {
2508
+ const current = this.store.getDocument(id);
2509
+ const document = validate(SpaceDocumentSchema, { ...current, ...file, version: current.version + 1, updatedBy: this.actingUserId, updatedAt: this.now }, "document");
2510
+ this.db
2511
+ .prepare("UPDATE documents SET filename = ?, mime = ?, size = ?, version = ?, storage_path = ?, updated_by = ?, updated_at = ? WHERE id = ?")
2512
+ .run(document.filename, document.mime, document.size, document.version, document.storagePath, document.updatedBy, document.updatedAt, id);
2513
+ this.touch("document", id, document.spaceId, null);
2514
+ return document;
2515
+ }
2516
+ setDocumentDescription(id, description) {
2517
+ const current = this.store.getDocument(id);
2518
+ const document = validate(SpaceDocumentSchema, { ...current, description, updatedBy: this.actingUserId, updatedAt: this.now }, "document");
2519
+ this.db.prepare("UPDATE documents SET description = ?, updated_by = ?, updated_at = ? WHERE id = ?").run(document.description, document.updatedBy, document.updatedAt, id);
2520
+ this.touch("document", id, document.spaceId, null);
2521
+ return document;
2522
+ }
2523
+ deleteDocument(id) {
2524
+ const document = this.store.getDocument(id);
2525
+ this.db.prepare("DELETE FROM documents WHERE id = ?").run(id);
2526
+ this.touch("document", id, document.spaceId, null);
2527
+ return document;
2528
+ }
2207
2529
  // --- Vues du tableau de bord ---
2208
2530
  /** Ajoute une vue à celles d'un membre dans un espace, après la dernière. */
2209
2531
  createBoardView(spaceId, userId, settings) {
@@ -2232,18 +2554,18 @@ export class Mutation {
2232
2554
  }
2233
2555
  insertBoardView(view) {
2234
2556
  this.db
2235
- .prepare(`INSERT INTO board_views (id, space_id, user_id, name, layout, group_by, then_by, show_empty_groups, statuses, priorities, assignee_ids, unassigned, tag_ids, position, created_at, updated_at)
2236
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)
2237
- .run(view.id, view.spaceId, view.userId, view.name, view.layout, view.groupBy, view.thenBy, view.showEmptyGroups ? 1 : 0, JSON.stringify(view.statuses), JSON.stringify(view.priorities), JSON.stringify(view.assigneeIds), view.unassigned ? 1 : 0, JSON.stringify(view.tagIds), view.position, view.createdAt, view.updatedAt);
2557
+ .prepare(`INSERT INTO board_views (id, space_id, user_id, name, layout, group_by, then_by, show_empty_groups, statuses, priorities, assignee_ids, unassigned, tag_ids, types, position, created_at, updated_at)
2558
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)
2559
+ .run(view.id, view.spaceId, view.userId, view.name, view.layout, view.groupBy, view.thenBy, view.showEmptyGroups ? 1 : 0, JSON.stringify(view.statuses), JSON.stringify(view.priorities), JSON.stringify(view.assigneeIds), view.unassigned ? 1 : 0, JSON.stringify(view.tagIds), JSON.stringify(view.types), view.position, view.createdAt, view.updatedAt);
2238
2560
  this.touch("board_view", view.id, null, view.userId, null, view.spaceId);
2239
2561
  }
2240
2562
  updateBoardView(id, patch) {
2241
2563
  const current = this.store.getBoardView(id);
2242
2564
  const view = validate(BoardViewSchema, { ...current, ...normalizedSettings({ ...current, ...definedFields(patch) }), updatedAt: this.now }, "board view");
2243
2565
  this.db
2244
- .prepare(`UPDATE board_views SET name = ?, layout = ?, group_by = ?, then_by = ?, show_empty_groups = ?, statuses = ?, priorities = ?, assignee_ids = ?, unassigned = ?, tag_ids = ?, updated_at = ?
2566
+ .prepare(`UPDATE board_views SET name = ?, layout = ?, group_by = ?, then_by = ?, show_empty_groups = ?, statuses = ?, priorities = ?, assignee_ids = ?, unassigned = ?, tag_ids = ?, types = ?, updated_at = ?
2245
2567
  WHERE id = ?`)
2246
- .run(view.name, view.layout, view.groupBy, view.thenBy, view.showEmptyGroups ? 1 : 0, JSON.stringify(view.statuses), JSON.stringify(view.priorities), JSON.stringify(view.assigneeIds), view.unassigned ? 1 : 0, JSON.stringify(view.tagIds), view.updatedAt, id);
2568
+ .run(view.name, view.layout, view.groupBy, view.thenBy, view.showEmptyGroups ? 1 : 0, JSON.stringify(view.statuses), JSON.stringify(view.priorities), JSON.stringify(view.assigneeIds), view.unassigned ? 1 : 0, JSON.stringify(view.tagIds), JSON.stringify(view.types), view.updatedAt, id);
2247
2569
  this.touch("board_view", id, null, view.userId, null, view.spaceId);
2248
2570
  return view;
2249
2571
  }
@@ -2292,6 +2614,7 @@ export class Mutation {
2292
2614
  }
2293
2615
  /** Note la modification d'une demande, pour son espace. */
2294
2616
  touchRequest(request) {
2617
+ this.touchedRequestIds.add(request.id);
2295
2618
  this.touch("agent_request", request.id, request.targetSpaceId, request.authorId, request.contextTaskId);
2296
2619
  }
2297
2620
  /** Demande `pending` qu'un membre de son espace modifie ou annule. */
@@ -2571,6 +2894,101 @@ export class Mutation {
2571
2894
  this.touch("agent_action", id, this.store.getAgentRequest(action.requestId).targetSpaceId, null, taskId);
2572
2895
  return { ...action, undoneAt: this.now, undoneBy: this.actor.userId };
2573
2896
  }
2897
+ // --- Chrono ---
2898
+ /**
2899
+ * Démarre une session de chrono d'un membre sur une tâche, en marche dès
2900
+ * `at`. Le membre n'a qu'une session active par tâche, et une seule en
2901
+ * marche : l'appelant met d'abord en pause celle qui tourne ailleurs.
2902
+ */
2903
+ startTimeSession(input) {
2904
+ const task = this.store.getTask(input.taskId);
2905
+ if (!this.store.isMember(task.spaceId, input.userId))
2906
+ throw new NotFoundError(`User ${input.userId} is not a member of the space of task ${taskLabel(this.db, task)}.`);
2907
+ if (this.store.findActiveTimeSession(task.id, input.userId))
2908
+ throw new InvariantError(`A timer is already active on ${taskLabel(this.db, task)}: resume or stop it.`);
2909
+ if (this.store.findRunningTimeSessionOf(input.userId))
2910
+ throw new InvariantError("Another timer is running: pause it first.");
2911
+ const session = validate(TimeSessionSchema, {
2912
+ id: newId(),
2913
+ spaceId: task.spaceId,
2914
+ taskId: task.id,
2915
+ userId: input.userId,
2916
+ mode: input.mode,
2917
+ pomodoro: input.mode === "pomodoro" ? input.pomodoro : null,
2918
+ startedAt: input.at,
2919
+ endedAt: null,
2920
+ runningSince: input.at,
2921
+ elapsedMs: 0,
2922
+ }, "time session");
2923
+ this.insertTimeSession(session);
2924
+ return session;
2925
+ }
2926
+ /** Met en pause une session en marche : sa marche s'ajoute au temps cumulé. */
2927
+ pauseTimeSession(id, at) {
2928
+ const current = this.store.getTimeSession(id);
2929
+ if (current.runningSince === null)
2930
+ throw new InvariantError("This timer is not running.");
2931
+ return this.writeTimeSessionState(current, { runningSince: null, elapsedMs: current.elapsedMs + Math.max(0, Date.parse(at) - Date.parse(current.runningSince)), endedAt: null });
2932
+ }
2933
+ /** Reprend une session en pause ; aucune autre session du membre ne doit tourner. */
2934
+ resumeTimeSession(id, at) {
2935
+ const current = this.store.getTimeSession(id);
2936
+ if (current.endedAt !== null)
2937
+ throw new InvariantError("This timer is stopped.");
2938
+ if (current.runningSince !== null)
2939
+ throw new InvariantError("This timer is already running.");
2940
+ if (this.store.findRunningTimeSessionOf(current.userId))
2941
+ throw new InvariantError("Another timer is running: pause it first.");
2942
+ return this.writeTimeSessionState(current, { runningSince: at, elapsedMs: current.elapsedMs, endedAt: null });
2943
+ }
2944
+ /** Arrête une session active, en marche ou en pause. */
2945
+ stopTimeSession(id, at) {
2946
+ const current = this.store.getTimeSession(id);
2947
+ if (current.endedAt !== null)
2948
+ throw new InvariantError("This timer is already stopped.");
2949
+ const elapsedMs = current.runningSince === null ? current.elapsedMs : current.elapsedMs + Math.max(0, Date.parse(at) - Date.parse(current.runningSince));
2950
+ return this.writeTimeSessionState(current, { runningSince: null, elapsedMs, endedAt: at });
2951
+ }
2952
+ /**
2953
+ * Remet une session dans un état antérieur (annulation d'une action de
2954
+ * l'agent) ; refusé quand une autre session du membre occupe désormais la
2955
+ * tâche, ou tourne alors que l'état visé est en marche.
2956
+ */
2957
+ restoreTimeSessionState(id, state) {
2958
+ const current = this.store.getTimeSession(id);
2959
+ if (state.endedAt === null && current.endedAt !== null) {
2960
+ const other = this.store.findActiveTimeSession(current.taskId, current.userId);
2961
+ if (other && other.id !== id)
2962
+ throw new InvariantError("Un autre chrono a été démarré depuis sur cette tâche : annulation impossible.");
2963
+ }
2964
+ if (state.runningSince !== null) {
2965
+ const running = this.store.findRunningTimeSessionOf(current.userId);
2966
+ if (running && running.id !== id)
2967
+ throw new InvariantError("Un autre chrono tourne désormais : mettez-le en pause avant d'annuler.");
2968
+ }
2969
+ return this.writeTimeSessionState(current, state);
2970
+ }
2971
+ deleteTimeSession(id) {
2972
+ const session = this.store.getTimeSession(id);
2973
+ this.db.prepare("DELETE FROM time_sessions WHERE id = ?").run(id);
2974
+ this.touchTimeSession(session);
2975
+ }
2976
+ insertTimeSession(session) {
2977
+ this.db
2978
+ .prepare(`INSERT INTO time_sessions (id, space_id, task_id, user_id, mode, work_minutes, short_break_minutes, long_break_minutes, cycles, started_at, ended_at, running_since, elapsed_ms)
2979
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)
2980
+ .run(session.id, session.spaceId, session.taskId, session.userId, session.mode, session.pomodoro?.workMinutes ?? null, session.pomodoro?.shortBreakMinutes ?? null, session.pomodoro?.longBreakMinutes ?? null, session.pomodoro?.cycles ?? null, session.startedAt, session.endedAt, session.runningSince, session.elapsedMs);
2981
+ this.touchTimeSession(session);
2982
+ }
2983
+ writeTimeSessionState(current, state) {
2984
+ const session = validate(TimeSessionSchema, { ...current, ...state }, "time session");
2985
+ this.db.prepare("UPDATE time_sessions SET running_since = ?, elapsed_ms = ?, ended_at = ? WHERE id = ?").run(session.runningSince, session.elapsedMs, session.endedAt, session.id);
2986
+ this.touchTimeSession(session);
2987
+ return session;
2988
+ }
2989
+ touchTimeSession(session) {
2990
+ this.touch("time_session", session.id, session.spaceId, session.userId, session.taskId);
2991
+ }
2574
2992
  // --- Notifications ---
2575
2993
  /** Vrai si l'utilisateur est l'auteur humain de la mutation : on ne se notifie pas soi-même. */
2576
2994
  isActingUser(userId) {
@@ -2579,8 +2997,8 @@ export class Mutation {
2579
2997
  /**
2580
2998
  * Notifie un utilisateur selon ses préférences dans l'espace de la tâche
2581
2999
  * (celles de l'espace, sinon celles du compte) : la notification apparaît
2582
- * dans l'application si elle y est activée, et son identifiant est retenu
2583
- * pour l'envoi de l'e-mail si celui-ci est activé. Rien n'est créé quand les
3000
+ * dans l'application si elle y est activée, et son e-mail est marqué en
3001
+ * attente d'envoi si celui-ci est activé. Rien n'est créé quand les
2584
3002
  * deux sont désactivés.
2585
3003
  */
2586
3004
  notify(type, userId, taskId, commentId) {
@@ -2613,9 +3031,9 @@ export class Mutation {
2613
3031
  emailError: null,
2614
3032
  }, "notification");
2615
3033
  this.db
2616
- .prepare(`INSERT INTO notifications (id, user_id, type, task_id, actor_type, actor_id, request_id, comment_id, in_app, created_at)
2617
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)
2618
- .run(notification.id, notification.userId, notification.type, notification.taskId, notification.actorType, notification.actorId, notification.requestId, notification.commentId, inApp ? 1 : 0, notification.createdAt);
3034
+ .prepare(`INSERT INTO notifications (id, user_id, type, task_id, actor_type, actor_id, request_id, comment_id, in_app, email_pending, created_at)
3035
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)
3036
+ .run(notification.id, notification.userId, notification.type, notification.taskId, notification.actorType, notification.actorId, notification.requestId, notification.commentId, inApp ? 1 : 0, email ? 1 : 0, notification.createdAt);
2619
3037
  if (inApp)
2620
3038
  this.touch("notification", notification.id, null, userId, taskId);
2621
3039
  if (email)
@@ -2646,7 +3064,7 @@ export class Mutation {
2646
3064
  recordNotificationEmail(id, outcome) {
2647
3065
  const notification = this.store.getNotification(id);
2648
3066
  const recorded = validate(NotificationSchema, { ...notification, emailedAt: outcome.sent ? this.now : null, emailError: outcome.sent ? null : outcome.reason }, "notification");
2649
- this.db.prepare("UPDATE notifications SET emailed_at = ?, email_error = ? WHERE id = ?").run(recorded.emailedAt, recorded.emailError, id);
3067
+ this.db.prepare("UPDATE notifications SET emailed_at = ?, email_error = ?, email_pending = 0 WHERE id = ?").run(recorded.emailedAt, recorded.emailError, id);
2650
3068
  if (notification.inApp)
2651
3069
  this.touch("notification", id, null, notification.userId, notification.taskId);
2652
3070
  return recorded;
@@ -2656,8 +3074,9 @@ export class Mutation {
2656
3074
  const settings = validate(UserSettingsSchema, { ...this.store.getUserSettings(userId), ...definedFields(patch) }, "settings");
2657
3075
  this.db
2658
3076
  .prepare(`UPDATE user_settings SET notify_assign_app = ?, notify_assign_email = ?, notify_comment_app = ?, notify_comment_email = ?,
2659
- notify_follow_up_app = ?, notify_follow_up_email = ?, assistant_history = ? WHERE user_id = ?`)
2660
- .run(settings.notifyAssignApp ? 1 : 0, settings.notifyAssignEmail ? 1 : 0, settings.notifyCommentApp ? 1 : 0, settings.notifyCommentEmail ? 1 : 0, settings.notifyFollowUpApp ? 1 : 0, settings.notifyFollowUpEmail ? 1 : 0, settings.assistantHistory, userId);
3077
+ notify_follow_up_app = ?, notify_follow_up_email = ?, assistant_history = ?, pomodoro_work_minutes = ?,
3078
+ pomodoro_short_break_minutes = ?, pomodoro_long_break_minutes = ?, pomodoro_cycles = ? WHERE user_id = ?`)
3079
+ .run(settings.notifyAssignApp ? 1 : 0, settings.notifyAssignEmail ? 1 : 0, settings.notifyCommentApp ? 1 : 0, settings.notifyCommentEmail ? 1 : 0, settings.notifyFollowUpApp ? 1 : 0, settings.notifyFollowUpEmail ? 1 : 0, settings.assistantHistory, settings.pomodoro.workMinutes, settings.pomodoro.shortBreakMinutes, settings.pomodoro.longBreakMinutes, settings.pomodoro.cycles, userId);
2661
3080
  this.touch("user_settings", userId, null, userId);
2662
3081
  return settings;
2663
3082
  }
@@ -2878,30 +3297,37 @@ export class Mutation {
2878
3297
  throw new InvariantError("The promotion of this idea is already pending with the agent.");
2879
3298
  }
2880
3299
  }
2881
- /** Une version par entité versionnée modifiée ; une suppression a un instantané nul. */
3300
+ /**
3301
+ * Une version par entité versionnée modifiée, dans un espace qui existe
3302
+ * encore ; une suppression a un instantané nul. La version est visible dans
3303
+ * l'historique quand elle change quelque chose de lisible.
3304
+ */
2882
3305
  writeVersions() {
2883
3306
  const actorType = this.actor.type;
2884
3307
  const actorId = this.actingUserId;
2885
3308
  const requestId = this.request?.id ?? null;
2886
3309
  const tokenId = this.token?.id ?? null;
2887
- const insert = this.db.prepare(`INSERT INTO entity_versions (entity_type, entity_id, version, snapshot, actor_type, actor_id, request_id, created_at, token_id)
2888
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`);
3310
+ const insert = this.db.prepare(`INSERT INTO entity_versions (entity_type, entity_id, version, space_id, task_id, snapshot, visible, actor_type, actor_id, request_id, created_at, token_id)
3311
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);
3312
+ const restoredTaskIds = new Set();
3313
+ for (const entry of this.touched.values()) {
3314
+ if (entry.entityType === "task" && this.store.findTask(entry.entityId) && this.store.latestVersion("task", entry.entityId)?.snapshot === null)
3315
+ restoredTaskIds.add(entry.entityId);
3316
+ }
2889
3317
  for (const entry of this.touched.values()) {
2890
- if (!VERSIONED.has(entry.entityType))
3318
+ if (!VERSIONED.has(entry.entityType) || entry.spaceId === null || !this.store.findSpace(entry.spaceId))
2891
3319
  continue;
2892
- const previous = this.db
2893
- .prepare("SELECT MAX(version) AS v FROM entity_versions WHERE entity_type = ? AND entity_id = ?")
2894
- .get(entry.entityType, entry.entityId);
2895
- const version = (previous.v ?? 0) + 1;
2896
- let snapshot = null;
2897
- if (entry.entityType === "task" && this.store.findTask(entry.entityId)) {
3320
+ const entityType = entry.entityType;
3321
+ const latest = this.store.latestVersion(entityType, entry.entityId);
3322
+ const version = (latest?.version ?? 0) + 1;
3323
+ if (entityType === "task" && this.store.findTask(entry.entityId))
2898
3324
  this.db.prepare("UPDATE tasks SET version = ? WHERE id = ?").run(version, entry.entityId);
2899
- snapshot = this.store.taskSnapshot(entry.entityId);
2900
- }
2901
- else if (entry.entityType === "idea") {
2902
- snapshot = this.store.findIdea(entry.entityId);
2903
- }
2904
- insert.run(entry.entityType, entry.entityId, version, snapshot === null ? null : JSON.stringify(snapshot), actorType, actorId, requestId, this.now, tokenId);
3325
+ const snapshot = versionSnapshot(this.store, entityType, entry.entityId);
3326
+ if (latest === null && snapshot === null)
3327
+ continue;
3328
+ const taskLifecycle = entry.taskId === null ? null : !this.store.findTask(entry.taskId) ? "deleted" : restoredTaskIds.has(entry.taskId) ? "restored" : null;
3329
+ const visible = isVisibleVersion(entityType, latest, snapshot, taskLifecycle);
3330
+ insert.run(entityType, entry.entityId, version, entry.spaceId, entry.taskId, snapshot === null ? null : JSON.stringify(snapshot), visible ? 1 : 0, actorType, actorId, requestId, this.now, tokenId);
2905
3331
  }
2906
3332
  }
2907
3333
  /** Une ligne du journal par entité modifiée, avec l'auteur de la mutation. */
@@ -2915,9 +3341,9 @@ export class Mutation {
2915
3341
  }
2916
3342
  }
2917
3343
  }
2918
- /** Réglages d'une vue avec des filtres sans doublon, dans l'ordre des statuts et des priorités. */
3344
+ /** Réglages d'une vue avec des filtres sans doublon, dans l'ordre des statuts, des priorités et des types. */
2919
3345
  function normalizedSettings(settings) {
2920
- const { name, layout, groupBy, thenBy, showEmptyGroups, statuses, priorities, assigneeIds, unassigned, tagIds } = settings;
3346
+ const { name, layout, groupBy, thenBy, showEmptyGroups, statuses, priorities, assigneeIds, unassigned, tagIds, types } = settings;
2921
3347
  return {
2922
3348
  name,
2923
3349
  layout,
@@ -2929,6 +3355,7 @@ function normalizedSettings(settings) {
2929
3355
  assigneeIds: [...new Set(assigneeIds)],
2930
3356
  unassigned,
2931
3357
  tagIds: [...new Set(tagIds)],
3358
+ types: TASK_TYPES.filter((type) => types.includes(type)),
2932
3359
  };
2933
3360
  }
2934
3361
  /** Champs de `patch` dont la valeur n'est pas `undefined`. */