@open-mercato/scheduler 0.6.4-develop.4371.1.8f3030407e → 0.6.4

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 (52) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/dist/modules/scheduler/__integration__/TC-SCHED-002.spec.js +49 -0
  3. package/dist/modules/scheduler/__integration__/TC-SCHED-002.spec.js.map +7 -0
  4. package/dist/modules/scheduler/__integration__/TC-SCHED-003.spec.js +38 -0
  5. package/dist/modules/scheduler/__integration__/TC-SCHED-003.spec.js.map +7 -0
  6. package/dist/modules/scheduler/__integration__/TC-SCHED-004.spec.js +36 -0
  7. package/dist/modules/scheduler/__integration__/TC-SCHED-004.spec.js.map +7 -0
  8. package/dist/modules/scheduler/__integration__/TC-SCHED-005.spec.js +41 -0
  9. package/dist/modules/scheduler/__integration__/TC-SCHED-005.spec.js.map +7 -0
  10. package/dist/modules/scheduler/__integration__/TC-SCHED-006.spec.js +61 -0
  11. package/dist/modules/scheduler/__integration__/TC-SCHED-006.spec.js.map +7 -0
  12. package/dist/modules/scheduler/__integration__/TC-SCHED-007.spec.js +36 -0
  13. package/dist/modules/scheduler/__integration__/TC-SCHED-007.spec.js.map +7 -0
  14. package/dist/modules/scheduler/__integration__/TC-SCHED-CRUDFORM-001.spec.js +105 -0
  15. package/dist/modules/scheduler/__integration__/TC-SCHED-CRUDFORM-001.spec.js.map +7 -0
  16. package/dist/modules/scheduler/__integration__/TC-UNDO-001-scheduler-jobs.spec.js +124 -0
  17. package/dist/modules/scheduler/__integration__/TC-UNDO-001-scheduler-jobs.spec.js.map +7 -0
  18. package/dist/modules/scheduler/__integration__/helpers/scheduler.js +59 -0
  19. package/dist/modules/scheduler/__integration__/helpers/scheduler.js.map +7 -0
  20. package/dist/modules/scheduler/backend/config/scheduled-jobs/[id]/edit/page.js +1 -1
  21. package/dist/modules/scheduler/backend/config/scheduled-jobs/[id]/edit/page.js.map +2 -2
  22. package/dist/modules/scheduler/backend/config/scheduled-jobs/page.js +10 -1
  23. package/dist/modules/scheduler/backend/config/scheduled-jobs/page.js.map +2 -2
  24. package/dist/modules/scheduler/commands/jobs.js +56 -13
  25. package/dist/modules/scheduler/commands/jobs.js.map +2 -2
  26. package/dist/modules/scheduler/i18n/de.json +2 -0
  27. package/dist/modules/scheduler/i18n/en.json +2 -0
  28. package/dist/modules/scheduler/i18n/es.json +2 -0
  29. package/dist/modules/scheduler/i18n/pl.json +2 -0
  30. package/dist/modules/scheduler/lib/scheduledJobFormConfig.js +8 -1
  31. package/dist/modules/scheduler/lib/scheduledJobFormConfig.js.map +2 -2
  32. package/package.json +7 -8
  33. package/src/modules/scheduler/__integration__/TC-SCHED-002.spec.ts +63 -0
  34. package/src/modules/scheduler/__integration__/TC-SCHED-003.spec.ts +48 -0
  35. package/src/modules/scheduler/__integration__/TC-SCHED-004.spec.ts +52 -0
  36. package/src/modules/scheduler/__integration__/TC-SCHED-005.spec.ts +51 -0
  37. package/src/modules/scheduler/__integration__/TC-SCHED-006.spec.ts +84 -0
  38. package/src/modules/scheduler/__integration__/TC-SCHED-007.spec.ts +50 -0
  39. package/src/modules/scheduler/__integration__/TC-SCHED-CRUDFORM-001.spec.ts +144 -0
  40. package/src/modules/scheduler/__integration__/TC-UNDO-001-scheduler-jobs.spec.ts +179 -0
  41. package/src/modules/scheduler/__integration__/helpers/scheduler.ts +110 -0
  42. package/src/modules/scheduler/backend/config/scheduled-jobs/[id]/edit/page.tsx +1 -1
  43. package/src/modules/scheduler/backend/config/scheduled-jobs/page.tsx +9 -1
  44. package/src/modules/scheduler/commands/__tests__/jobs.undo.test.ts +181 -0
  45. package/src/modules/scheduler/commands/jobs.ts +76 -13
  46. package/src/modules/scheduler/data/__tests__/validators.test.ts +17 -0
  47. package/src/modules/scheduler/i18n/de.json +2 -0
  48. package/src/modules/scheduler/i18n/en.json +2 -0
  49. package/src/modules/scheduler/i18n/es.json +2 -0
  50. package/src/modules/scheduler/i18n/pl.json +2 -0
  51. package/src/modules/scheduler/lib/__tests__/scheduledJobFormConfig.test.ts +24 -0
  52. package/src/modules/scheduler/lib/scheduledJobFormConfig.tsx +11 -1
@@ -1,5 +1,7 @@
1
1
  import { registerCommand } from '@open-mercato/shared/lib/commands'
2
2
  import type { CommandHandler, CommandRuntimeContext } from '@open-mercato/shared/lib/commands'
3
+ import { extractUndoPayload, type UndoPayload } from '@open-mercato/shared/lib/commands/undo'
4
+ import { makeCreateRedo } from '@open-mercato/shared/lib/commands/redo'
3
5
  import { ensureOrganizationScope } from '@open-mercato/shared/lib/commands/scope'
4
6
  import { CrudHttpError } from '@open-mercato/shared/lib/crud/errors'
5
7
  import type { EntityManager } from '@mikro-orm/core'
@@ -70,6 +72,57 @@ async function loadScheduleSnapshot(
70
72
  }
71
73
  }
72
74
 
75
+ /**
76
+ * Snapshots are persisted as JSON (in the action log's command payload), so Date
77
+ * fields come back as ISO strings on undo. Coerce them to Date before writing
78
+ * them onto the entity, otherwise MikroORM throws while flushing a Date column.
79
+ */
80
+ function toDate(value: Date | string | null | undefined): Date | null {
81
+ if (!value) return null
82
+ return value instanceof Date ? value : new Date(value)
83
+ }
84
+
85
+ /**
86
+ * Build a full create seed (including the original id and Date-coerced timestamps)
87
+ * from a snapshot. Shared by `materializeScheduleFromSnapshot` (delete-undo) and the
88
+ * create command's id-preserving `redo`.
89
+ */
90
+ function scheduleSeedFromSnapshot(snapshot: ScheduleSnapshot): Record<string, unknown> {
91
+ const now = new Date()
92
+ return {
93
+ id: snapshot.id,
94
+ name: snapshot.name,
95
+ description: snapshot.description,
96
+ scopeType: snapshot.scopeType,
97
+ organizationId: snapshot.organizationId,
98
+ tenantId: snapshot.tenantId,
99
+ scheduleType: snapshot.scheduleType,
100
+ scheduleValue: snapshot.scheduleValue,
101
+ timezone: snapshot.timezone,
102
+ targetType: snapshot.targetType,
103
+ targetQueue: snapshot.targetQueue,
104
+ targetCommand: snapshot.targetCommand,
105
+ targetPayload: snapshot.targetPayload,
106
+ requireFeature: snapshot.requireFeature,
107
+ isEnabled: snapshot.isEnabled,
108
+ sourceType: snapshot.sourceType,
109
+ sourceModule: snapshot.sourceModule,
110
+ nextRunAt: toDate(snapshot.nextRunAt),
111
+ lastRunAt: toDate(snapshot.lastRunAt),
112
+ deletedAt: null,
113
+ createdAt: now,
114
+ updatedAt: now,
115
+ }
116
+ }
117
+
118
+ /**
119
+ * Re-create a ScheduledJob entity from a snapshot, preserving its original id.
120
+ * Used by delete-undo when the row was hard-removed rather than soft-deleted.
121
+ */
122
+ function materializeScheduleFromSnapshot(em: EntityManager, snapshot: ScheduleSnapshot): ScheduledJob {
123
+ return em.create(ScheduledJob, scheduleSeedFromSnapshot(snapshot) as never)
124
+ }
125
+
73
126
  /**
74
127
  * Trigger BullMQ sync after undo operations.
75
128
  * Best-effort: if BullMQ service is unavailable (e.g. local strategy), this is a no-op.
@@ -197,8 +250,7 @@ const createScheduleCommand: CommandHandler<ScheduleCreateInput, { id: string }>
197
250
  },
198
251
 
199
252
  async undo({ logEntry, ctx }) {
200
- const undoPayload = logEntry.payload as { undo?: { after?: ScheduleSnapshot } }
201
- const after = undoPayload?.undo?.after
253
+ const after = extractUndoPayload<UndoPayload<ScheduleSnapshot>>(logEntry)?.after
202
254
  if (!after) return
203
255
 
204
256
  const em = ctx.container.resolve<EntityManager>('em').fork()
@@ -209,6 +261,16 @@ const createScheduleCommand: CommandHandler<ScheduleCreateInput, { id: string }>
209
261
  await syncBullMQAfterUndo(ctx, schedule)
210
262
  }
211
263
  },
264
+
265
+ redo: makeCreateRedo<ScheduledJob, ScheduleSnapshot, ScheduleCreateInput, { id: string }>({
266
+ entityClass: ScheduledJob,
267
+ getSnapshotId: (snapshot) => snapshot.id,
268
+ seedFromSnapshot: scheduleSeedFromSnapshot,
269
+ buildResult: (entity) => ({ id: entity.id }),
270
+ afterRestore: async ({ ctx, entity }) => {
271
+ await syncBullMQAfterUndo(ctx, entity)
272
+ },
273
+ }),
212
274
  }
213
275
 
214
276
  /**
@@ -307,8 +369,7 @@ const updateScheduleCommand: CommandHandler<ScheduleUpdateInput, { ok: boolean }
307
369
  },
308
370
 
309
371
  async undo({ logEntry, ctx }) {
310
- const undoPayload = logEntry.payload as { undo?: { before?: ScheduleSnapshot; after?: ScheduleSnapshot } }
311
- const before = undoPayload?.undo?.before
372
+ const before = extractUndoPayload<UndoPayload<ScheduleSnapshot>>(logEntry)?.before
312
373
  if (!before) return
313
374
 
314
375
  const em = ctx.container.resolve<EntityManager>('em').fork()
@@ -332,8 +393,8 @@ const updateScheduleCommand: CommandHandler<ScheduleUpdateInput, { ok: boolean }
332
393
  schedule.isEnabled = before.isEnabled
333
394
  schedule.sourceType = before.sourceType
334
395
  schedule.sourceModule = before.sourceModule
335
- schedule.nextRunAt = before.nextRunAt
336
- schedule.lastRunAt = before.lastRunAt
396
+ schedule.nextRunAt = toDate(before.nextRunAt)
397
+ schedule.lastRunAt = toDate(before.lastRunAt)
337
398
  schedule.updatedAt = new Date()
338
399
 
339
400
  await em.flush()
@@ -392,20 +453,22 @@ const deleteScheduleCommand: CommandHandler<{ id: string }, { ok: boolean }> = {
392
453
  },
393
454
 
394
455
  async undo({ logEntry, ctx }) {
395
- const undoPayload = logEntry.payload as { undo?: { before?: ScheduleSnapshot } }
396
- const before = undoPayload?.undo?.before
456
+ const before = extractUndoPayload<UndoPayload<ScheduleSnapshot>>(logEntry)?.before
397
457
  if (!before) return
398
458
 
399
459
  const em = ctx.container.resolve<EntityManager>('em').fork()
400
- const schedule = await em.findOne(ScheduledJob, { id: before.id })
460
+ const existing = await em.findOne(ScheduledJob, { id: before.id })
401
461
 
402
- if (schedule) {
403
- // Restore by clearing deletedAt
462
+ // Soft-deleted rows are restored by clearing `deletedAt`. A hard-removed row
463
+ // (no surviving record) is re-materialized from the snapshot so undo is
464
+ // robust to either deletion strategy — mirroring the sales reference undo.
465
+ const schedule = existing ?? materializeScheduleFromSnapshot(em, before)
466
+ if (existing) {
404
467
  schedule.deletedAt = null
405
468
  schedule.updatedAt = new Date()
406
- await em.flush()
407
- await syncBullMQAfterUndo(ctx, schedule)
408
469
  }
470
+ await em.flush()
471
+ await syncBullMQAfterUndo(ctx, schedule)
409
472
  },
410
473
  }
411
474
 
@@ -506,6 +506,23 @@ describe('scheduleUpdateSchema', () => {
506
506
 
507
507
  expect(result.targetPayload).toBeNull()
508
508
  })
509
+
510
+ it('should strip scope fields so scope stays immutable after creation', () => {
511
+ const result = scheduleUpdateSchema.parse({
512
+ id: scheduleId,
513
+ name: 'Updated name',
514
+ scopeType: 'organization',
515
+ organizationId,
516
+ tenantId,
517
+ })
518
+
519
+ // Scope is derived from the creator's auth context at create time and must
520
+ // not be mutable via update. The edit form locks the Scope field to mirror
521
+ // this contract (see scheduledJobFormConfig lockScope).
522
+ expect((result as Record<string, unknown>).scopeType).toBeUndefined()
523
+ expect((result as Record<string, unknown>).organizationId).toBeUndefined()
524
+ expect((result as Record<string, unknown>).tenantId).toBeUndefined()
525
+ })
509
526
  })
510
527
 
511
528
  describe('scheduleDeleteSchema', () => {
@@ -99,6 +99,7 @@
99
99
  "scheduler.form.schedule_value.description": "Für Cron: verwenden Sie Cron-Ausdruck (z.B. \"0 0 * * *\"). Für Intervall: verwenden Sie Format wie \"15m\", \"2h\", \"1d\" (s=Sekunden, m=Minuten, h=Stunden, d=Tage)",
100
100
  "scheduler.form.schedule_value.placeholder": "z.B. 0 */6 * * * oder 15m",
101
101
  "scheduler.form.scope_type": "Bereich",
102
+ "scheduler.form.scope_type.locked_description": "Der Bereich wird bei der Erstellung des Zeitplans festgelegt und kann danach nicht mehr geändert werden.",
102
103
  "scheduler.form.submit": "Zeitplan erstellen",
103
104
  "scheduler.form.target_command": "Zielbefehl",
104
105
  "scheduler.form.target_command.placeholder": "Befehle suchen...",
@@ -131,6 +132,7 @@
131
132
  "scheduler.loading": "Zeitplan wird geladen...",
132
133
  "scheduler.module.description": "Verwalten Sie automatisierte geplante Aufgaben mit Cron-Ausdrücken oder einfachen Intervallen.",
133
134
  "scheduler.module.title": "Geplante Aufgaben",
135
+ "scheduler.nav.backToList": "Zurück zu geplanten Aufgaben",
134
136
  "scheduler.scope.organization": "Organisation",
135
137
  "scheduler.scope.system": "System",
136
138
  "scheduler.scope.tenant": "Mandant",
@@ -99,6 +99,7 @@
99
99
  "scheduler.form.schedule_value.description": "For cron: use cron expression (e.g., \"0 0 * * *\"). For interval: use format like \"15m\", \"2h\", \"1d\" (s=seconds, m=minutes, h=hours, d=days)",
100
100
  "scheduler.form.schedule_value.placeholder": "e.g. 0 */6 * * * or 15m",
101
101
  "scheduler.form.scope_type": "Scope",
102
+ "scheduler.form.scope_type.locked_description": "Scope is set when the schedule is created and cannot be changed afterwards.",
102
103
  "scheduler.form.submit": "Create Schedule",
103
104
  "scheduler.form.target_command": "Target Command",
104
105
  "scheduler.form.target_command.placeholder": "Search commands...",
@@ -131,6 +132,7 @@
131
132
  "scheduler.loading": "Loading schedule...",
132
133
  "scheduler.module.description": "Manage automated scheduled jobs with cron expressions or simple intervals.",
133
134
  "scheduler.module.title": "Scheduled Jobs",
135
+ "scheduler.nav.backToList": "Back to scheduled jobs",
134
136
  "scheduler.scope.organization": "Organization",
135
137
  "scheduler.scope.system": "System",
136
138
  "scheduler.scope.tenant": "Tenant",
@@ -99,6 +99,7 @@
99
99
  "scheduler.form.schedule_value.description": "Para cron: use expresión cron (ej. \"0 0 * * *\"). Para intervalo: use formato como \"15m\", \"2h\", \"1d\" (s=segundos, m=minutos, h=horas, d=días)",
100
100
  "scheduler.form.schedule_value.placeholder": "ej. 0 */6 * * * o 15m",
101
101
  "scheduler.form.scope_type": "Ámbito",
102
+ "scheduler.form.scope_type.locked_description": "El ámbito se establece al crear la programación y no se puede cambiar posteriormente.",
102
103
  "scheduler.form.submit": "Crear programación",
103
104
  "scheduler.form.target_command": "Comando de destino",
104
105
  "scheduler.form.target_command.placeholder": "Buscar comandos...",
@@ -131,6 +132,7 @@
131
132
  "scheduler.loading": "Cargando programación...",
132
133
  "scheduler.module.description": "Administre tareas programadas automáticas con expresiones cron o intervalos simples.",
133
134
  "scheduler.module.title": "Tareas programadas",
135
+ "scheduler.nav.backToList": "Volver a tareas programadas",
134
136
  "scheduler.scope.organization": "Organización",
135
137
  "scheduler.scope.system": "Sistema",
136
138
  "scheduler.scope.tenant": "Inquilino",
@@ -99,6 +99,7 @@
99
99
  "scheduler.form.schedule_value.description": "Dla cron: użyj wyrażenia cron (np. \"0 0 * * *\"). Dla interwału: użyj formatu jak \"15m\", \"2h\", \"1d\" (s=sekundy, m=minuty, h=godziny, d=dni)",
100
100
  "scheduler.form.schedule_value.placeholder": "np. 0 */6 * * * lub 15m",
101
101
  "scheduler.form.scope_type": "Zakres",
102
+ "scheduler.form.scope_type.locked_description": "Zakres jest ustalany podczas tworzenia harmonogramu i nie można go później zmienić.",
102
103
  "scheduler.form.submit": "Utwórz harmonogram",
103
104
  "scheduler.form.target_command": "Polecenie docelowe",
104
105
  "scheduler.form.target_command.placeholder": "Szukaj poleceń...",
@@ -131,6 +132,7 @@
131
132
  "scheduler.loading": "Ładowanie harmonogramu...",
132
133
  "scheduler.module.description": "Zarządzaj automatycznymi zaplanowanymi zadaniami z wyrażeniami cron lub prostymi interwałami.",
133
134
  "scheduler.module.title": "Zaplanowane zadania",
135
+ "scheduler.nav.backToList": "Wróć do zaplanowanych zadań",
134
136
  "scheduler.scope.organization": "Organizacja",
135
137
  "scheduler.scope.system": "System",
136
138
  "scheduler.scope.tenant": "Najemca",
@@ -83,6 +83,30 @@ describe('scheduledJobFormConfig target fields', () => {
83
83
  })
84
84
  })
85
85
 
86
+ describe('scheduledJobFormConfig scope field', () => {
87
+ const t = (_key: string, fallback: string) => fallback
88
+ const loaders = {
89
+ loadQueueOptions: async () => [],
90
+ loadCommandOptions: async () => [],
91
+ loadTimezoneOptions: async () => [],
92
+ }
93
+
94
+ it('keeps the scope field editable on create (no lockScope)', () => {
95
+ const fields = scheduledJobFields(t, loaders)
96
+ const scope = fields.find((f) => f.id === 'scopeType')
97
+ expect(scope).toBeDefined()
98
+ expect(scope?.disabled).toBeFalsy()
99
+ })
100
+
101
+ it('locks the scope field on edit so the value cannot be deceptively changed then silently dropped', () => {
102
+ const fields = scheduledJobFields(t, loaders, { lockScope: true })
103
+ const scope = fields.find((f) => f.id === 'scopeType')
104
+ expect(scope).toBeDefined()
105
+ expect(scope?.disabled).toBe(true)
106
+ expect(scope?.description).toBeTruthy()
107
+ })
108
+ })
109
+
86
110
  describe('loadTimezoneOptions', () => {
87
111
  it('includes UTC even when Intl.supportedValuesOf does not list it', async () => {
88
112
  const options = await loadTimezoneOptions('utc')
@@ -149,8 +149,10 @@ export function scheduledJobFields(
149
149
  loadQueueOptions: (query?: string) => Promise<ComboboxOption[]>
150
150
  loadCommandOptions: (query?: string) => Promise<ComboboxOption[]>
151
151
  loadTimezoneOptions: (query?: string) => Promise<ComboboxOption[]>
152
- }
152
+ },
153
+ options?: { lockScope?: boolean }
153
154
  ): CrudField[] {
155
+ const lockScope = options?.lockScope ?? false
154
156
  return [
155
157
  {
156
158
  id: 'name',
@@ -168,6 +170,14 @@ export function scheduledJobFields(
168
170
  type: 'select',
169
171
  label: t('scheduler.form.scope_type', 'Scope'),
170
172
  required: true,
173
+ // Scope is derived from the creator's auth context at create time and is
174
+ // immutable afterwards (the update schema/command never persist it). Lock
175
+ // the field on edit so it does not deceptively accept input that is then
176
+ // silently dropped on save.
177
+ disabled: lockScope,
178
+ description: lockScope
179
+ ? t('scheduler.form.scope_type.locked_description', 'Scope is set when the schedule is created and cannot be changed afterwards.')
180
+ : undefined,
171
181
  options: [
172
182
  { value: 'system', label: t('scheduler.scope.system', 'System') },
173
183
  { value: 'organization', label: t('scheduler.scope.organization', 'Organization') },