@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
@@ -0,0 +1,144 @@
1
+ import { expect, test, type APIRequestContext } from '@playwright/test';
2
+ import { apiRequest, getAuthToken } from '@open-mercato/core/helpers/integration/api';
3
+ import { readJsonSafe } from '@open-mercato/core/helpers/integration/generalFixtures';
4
+ import {
5
+ runCrudFormRoundTrip,
6
+ skipIfCrudFormExtensionTestsDisabled,
7
+ type CrudRecord,
8
+ } from '@open-mercato/core/helpers/integration/crudFormPersistence';
9
+
10
+ /**
11
+ * TC-SCHED-CRUDFORM-001: Scheduled Job CrudForm persists scope, target + payload JSON (#2466).
12
+ *
13
+ * The scheduler's scheduled-job is the Tier-B "JSON-bearing scalar" surface: scope
14
+ * (scopeType, server-derived org/tenant), schedule (scheduleType/scheduleValue/timezone),
15
+ * target (targetType/targetQueue), and a nested `targetPayload` JSON object. Proves create +
16
+ * update round-trip every value.
17
+ *
18
+ * Verified contract (differs from the makeCrud-default reference specs):
19
+ * - The list GET filters by `?id=` (single uuid), not the `?ids=` other sweep modules use; the
20
+ * explicit `readById` documents that contract and mirrors the sibling specs (the shared
21
+ * harness default reads back via `?id=` too).
22
+ * - Read-back is camelCase: the list `transformItem` maps every column to camelCase
23
+ * (`scopeType`, `scheduleType`, `targetPayload`, `isEnabled`, ...), so the scalar
24
+ * expectations use camelCase keys (not the snake_case of resources/staff).
25
+ * - The scheduled-job declares no custom entity (no `ce.ts`), so there are no `cf_*` fields —
26
+ * the surface is scalars + nested JSON only.
27
+ * - Scope is derived server-side from the caller's auth context and is immutable on update:
28
+ * `scopeType: 'organization'` fills org+tenant from the admin token and survives the edit.
29
+ * - Update is a partial PUT: omitted target fields are retained, so the update changes the
30
+ * payload JSON while proving `targetType`/`targetQueue` survive untouched.
31
+ * - Harness cleanup deletes via `?id=`; the scheduler delete resolves the id from the query
32
+ * string, so the default `finally` cleanup removes the fixture.
33
+ *
34
+ * Self-contained: the job needs no pre-created fixtures (queue target + inline JSON), and the
35
+ * harness deletes it in `finally`.
36
+ *
37
+ * Gated by `OM_INTEGRATION_CRUDFORM_EXTENSION_TESTS_DISABLED` (default off → runs).
38
+ */
39
+ const SCHEDULER_JOBS_PATH = '/api/scheduler/jobs';
40
+
41
+ async function readScheduledJobById(
42
+ request: APIRequestContext,
43
+ token: string,
44
+ id: string,
45
+ ): Promise<CrudRecord | null> {
46
+ const response = await apiRequest(
47
+ request,
48
+ 'GET',
49
+ `${SCHEDULER_JOBS_PATH}?id=${encodeURIComponent(id)}&page=1&pageSize=100`,
50
+ { token },
51
+ );
52
+ expect(response.status(), `read-back scheduler jobs failed: ${response.status()}`).toBe(200);
53
+ const body = await readJsonSafe<{ items?: CrudRecord[] }>(response);
54
+ return (body?.items ?? []).find((item) => item.id === id) ?? null;
55
+ }
56
+
57
+ test.describe('TC-SCHED-CRUDFORM-001: Scheduled Job CrudForm persists scope, target + payload JSON', () => {
58
+ test.beforeAll(() => {
59
+ skipIfCrudFormExtensionTestsDisabled();
60
+ });
61
+
62
+ test('round-trips scalars, scope, target + nested payload JSON on create and update', async ({ request }) => {
63
+ const token = await getAuthToken(request, 'admin');
64
+ const stamp = Date.now();
65
+
66
+ const createPayload = {
67
+ source: 'integration-test',
68
+ attempts: 3,
69
+ retries: { max: 5, backoff: 'exponential' },
70
+ tags: ['alpha', 'beta'],
71
+ };
72
+ const updatePayload = {
73
+ source: 'integration-test-edited',
74
+ attempts: 1,
75
+ retries: { max: 0, backoff: 'fixed' },
76
+ tags: ['gamma'],
77
+ };
78
+
79
+ await runCrudFormRoundTrip({
80
+ request,
81
+ token,
82
+ collectionPath: SCHEDULER_JOBS_PATH,
83
+ readById: (id) => readScheduledJobById(request, token, id),
84
+ create: {
85
+ payload: {
86
+ name: `QA CRUDFORM Scheduled Job ${stamp}`,
87
+ description: 'Original scheduled job description',
88
+ scopeType: 'organization',
89
+ scheduleType: 'interval',
90
+ scheduleValue: '15m',
91
+ timezone: 'UTC',
92
+ targetType: 'queue',
93
+ targetQueue: 'scheduler-execution',
94
+ targetPayload: createPayload,
95
+ isEnabled: true,
96
+ sourceType: 'user',
97
+ },
98
+ },
99
+ expectAfterCreate: {
100
+ scalars: {
101
+ name: `QA CRUDFORM Scheduled Job ${stamp}`,
102
+ description: 'Original scheduled job description',
103
+ scopeType: 'organization',
104
+ scheduleType: 'interval',
105
+ scheduleValue: '15m',
106
+ timezone: 'UTC',
107
+ targetType: 'queue',
108
+ targetQueue: 'scheduler-execution',
109
+ targetCommand: null,
110
+ targetPayload: createPayload,
111
+ isEnabled: true,
112
+ sourceType: 'user',
113
+ },
114
+ },
115
+ update: {
116
+ payload: (id) => ({
117
+ id,
118
+ name: `QA CRUDFORM Scheduled Job ${stamp} EDITED`,
119
+ description: 'Updated scheduled job description',
120
+ scheduleType: 'cron',
121
+ scheduleValue: '0 0 * * *',
122
+ timezone: 'Europe/Warsaw',
123
+ targetPayload: updatePayload,
124
+ isEnabled: false,
125
+ }),
126
+ },
127
+ expectAfterUpdate: {
128
+ scalars: {
129
+ name: `QA CRUDFORM Scheduled Job ${stamp} EDITED`,
130
+ description: 'Updated scheduled job description',
131
+ scopeType: 'organization',
132
+ scheduleType: 'cron',
133
+ scheduleValue: '0 0 * * *',
134
+ timezone: 'Europe/Warsaw',
135
+ targetType: 'queue',
136
+ targetQueue: 'scheduler-execution',
137
+ targetCommand: null,
138
+ targetPayload: updatePayload,
139
+ isEnabled: false,
140
+ },
141
+ },
142
+ });
143
+ });
144
+ });
@@ -0,0 +1,179 @@
1
+ import { expect, test, type APIRequestContext, type APIResponse } from '@playwright/test'
2
+ import { apiRequest, getAuthToken } from '@open-mercato/core/helpers/integration/api'
3
+ import { skipIfUndoTestsDisabled } from '@open-mercato/core/helpers/integration/undoHarness'
4
+
5
+ /**
6
+ * TC-UNDO-001: scheduler.jobs undo round-trip (regression for issue #2504).
7
+ *
8
+ * Before the fix, every scheduler.jobs undo handler read `logEntry.payload`
9
+ * (always undefined — the command bus persists the undo snapshot under
10
+ * `commandPayload`), so undo returned `{ ok: true }` while silently changing
11
+ * nothing. This spec exercises the real HTTP path end-to-end:
12
+ * - CREATE -> undo => job is soft-deleted (no longer listed)
13
+ * - UPDATE -> undo => renamed field is restored to its prior value
14
+ * - DELETE -> undo => soft-deleted job is re-materialized
15
+ *
16
+ * Endpoints covered:
17
+ * - POST /api/scheduler/jobs (create)
18
+ * - GET /api/scheduler/jobs?id= (read)
19
+ * - PUT /api/scheduler/jobs (update)
20
+ * - DELETE /api/scheduler/jobs (delete, cleanup)
21
+ * - POST /api/audit_logs/audit-logs/actions/undo (undo)
22
+ */
23
+
24
+ type ScheduleRow = {
25
+ id: string
26
+ name: string
27
+ description: string | null
28
+ scheduleValue: string
29
+ }
30
+
31
+ // The undo endpoint only honors the *latest* undoable log for a resource, and
32
+ // `latestUndoableForResource` orders by `created_at` alone. Audit `created_at` is
33
+ // millisecond-precision (`new Date()` at log time), so a create + a follow-up
34
+ // mutation issued within the same millisecond tie and the lookup may resolve to
35
+ // the wrong log. A short settle guarantees the operation under undo is strictly
36
+ // the most recent, keeping the round-trip deterministic.
37
+ async function settleAuditClock(): Promise<void> {
38
+ await new Promise((resolve) => setTimeout(resolve, 50))
39
+ }
40
+
41
+ function readUndoToken(res: APIResponse): string {
42
+ const header = res.headers()['x-om-operation'] ?? ''
43
+ const enc = header.startsWith('omop:') ? header.slice(5) : ''
44
+ expect(enc, 'x-om-operation header should carry an omop: payload').not.toBe('')
45
+ const payload = JSON.parse(decodeURIComponent(enc)) as { undoToken?: string }
46
+ expect(typeof payload.undoToken, 'undoToken present in operation payload').toBe('string')
47
+ return payload.undoToken as string
48
+ }
49
+
50
+ async function getById(
51
+ request: APIRequestContext,
52
+ token: string,
53
+ id: string,
54
+ ): Promise<ScheduleRow | undefined> {
55
+ const res = await apiRequest(request, 'GET', `/api/scheduler/jobs?id=${encodeURIComponent(id)}`, { token })
56
+ expect(res.status()).toBe(200)
57
+ const body = (await res.json()) as { items?: ScheduleRow[] }
58
+ return (body.items ?? [])[0]
59
+ }
60
+
61
+ async function createJob(request: APIRequestContext, token: string, name: string): Promise<{ id: string; res: APIResponse }> {
62
+ const res = await apiRequest(request, 'POST', '/api/scheduler/jobs', {
63
+ token,
64
+ data: {
65
+ name,
66
+ description: 'TC-UNDO-001 probe',
67
+ scopeType: 'tenant',
68
+ scheduleType: 'cron',
69
+ scheduleValue: '0 0 * * *',
70
+ timezone: 'UTC',
71
+ targetType: 'queue',
72
+ targetQueue: 'default',
73
+ isEnabled: true,
74
+ sourceType: 'user',
75
+ },
76
+ })
77
+ expect(res.status(), 'create returns 201').toBe(201)
78
+ const id = ((await res.json()) as { id: string }).id
79
+ expect(id, 'create returns an id').toBeTruthy()
80
+ return { id, res }
81
+ }
82
+
83
+ async function undo(request: APIRequestContext, token: string, undoToken: string): Promise<void> {
84
+ const res = await apiRequest(request, 'POST', '/api/audit_logs/audit-logs/actions/undo', {
85
+ token,
86
+ data: { undoToken },
87
+ })
88
+ const raw = await res.text()
89
+ expect(res.status(), `undo returns 200 (body: ${raw})`).toBe(200)
90
+ const body = JSON.parse(raw) as { ok?: boolean }
91
+ expect(body.ok, 'undo body is { ok: true }').toBe(true)
92
+ }
93
+
94
+ async function cleanup(request: APIRequestContext, token: string | null, id: string | null): Promise<void> {
95
+ if (!token || !id) return
96
+ try {
97
+ await apiRequest(request, 'DELETE', '/api/scheduler/jobs', { token, data: { id } })
98
+ } catch {
99
+ /* ignore */
100
+ }
101
+ }
102
+
103
+ test.describe('TC-UNDO-001: scheduler.jobs undo actually restores state (#2504)', () => {
104
+ test.beforeAll(() => {
105
+ skipIfUndoTestsDisabled()
106
+ })
107
+
108
+ test('UPDATE -> undo restores the prior name', async ({ request }) => {
109
+ let token: string | null = null
110
+ let id: string | null = null
111
+ try {
112
+ token = await getAuthToken(request, 'admin')
113
+ const originalName = `TC-UNDO-001 Update ${Date.now()}`
114
+ ;({ id } = await createJob(request, token, originalName))
115
+ await settleAuditClock()
116
+
117
+ const updateRes = await apiRequest(request, 'PUT', '/api/scheduler/jobs', {
118
+ token,
119
+ data: { id, name: `${originalName} RENAMED` },
120
+ })
121
+ expect(updateRes.status(), 'update returns 200').toBe(200)
122
+ expect((await getById(request, token, id))?.name).toBe(`${originalName} RENAMED`)
123
+
124
+ await undo(request, token, readUndoToken(updateRes))
125
+
126
+ const restored = await getById(request, token, id)
127
+ expect(restored, 'job still exists after update-undo').toBeTruthy()
128
+ expect(restored!.name, 'name restored to original by undo').toBe(originalName)
129
+ } finally {
130
+ await cleanup(request, token, id)
131
+ }
132
+ })
133
+
134
+ test('DELETE -> undo re-lists the soft-deleted job', async ({ request }) => {
135
+ let token: string | null = null
136
+ let id: string | null = null
137
+ try {
138
+ token = await getAuthToken(request, 'admin')
139
+ const name = `TC-UNDO-001 Delete ${Date.now()}`
140
+ ;({ id } = await createJob(request, token, name))
141
+ await settleAuditClock()
142
+
143
+ const deleteRes = await apiRequest(request, 'DELETE', '/api/scheduler/jobs', {
144
+ token,
145
+ data: { id },
146
+ })
147
+ expect(deleteRes.status(), 'delete returns 200').toBe(200)
148
+ expect(await getById(request, token, id), 'job is gone after delete').toBeFalsy()
149
+
150
+ await undo(request, token, readUndoToken(deleteRes))
151
+
152
+ const restored = await getById(request, token, id)
153
+ expect(restored, 'job re-materialized by delete-undo').toBeTruthy()
154
+ expect(restored!.name).toBe(name)
155
+ } finally {
156
+ await cleanup(request, token, id)
157
+ }
158
+ })
159
+
160
+ test('CREATE -> undo removes the created job', async ({ request }) => {
161
+ let token: string | null = null
162
+ let id: string | null = null
163
+ try {
164
+ token = await getAuthToken(request, 'admin')
165
+ const name = `TC-UNDO-001 Create ${Date.now()}`
166
+ const created = await createJob(request, token, name)
167
+ id = created.id
168
+
169
+ expect(await getById(request, token, id), 'job exists after create').toBeTruthy()
170
+
171
+ await undo(request, token, readUndoToken(created.res))
172
+
173
+ expect(await getById(request, token, id), 'job removed by create-undo').toBeFalsy()
174
+ id = null // already undone; nothing to clean up
175
+ } finally {
176
+ await cleanup(request, token, id)
177
+ }
178
+ })
179
+ })
@@ -0,0 +1,110 @@
1
+ import { expect, type APIRequestContext } from '@playwright/test'
2
+ import { apiRequest } from '@open-mercato/core/helpers/integration/api'
3
+ import { readJsonSafe } from '@open-mercato/core/helpers/integration/generalFixtures'
4
+
5
+ export const SCHEDULER_JOBS_PATH = '/api/scheduler/jobs'
6
+ export const SCHEDULER_TARGETS_PATH = '/api/scheduler/targets'
7
+ export const SCHEDULER_TRIGGER_PATH = '/api/scheduler/trigger'
8
+
9
+ /** Queue registered by the scheduler module's execute-schedule worker. */
10
+ export const SCHEDULER_EXECUTION_QUEUE = 'scheduler-execution'
11
+
12
+ export type SchedulerJob = {
13
+ id: string
14
+ name: string
15
+ description: string | null
16
+ scopeType: 'system' | 'organization' | 'tenant'
17
+ organizationId: string | null
18
+ tenantId: string | null
19
+ scheduleType: 'cron' | 'interval'
20
+ scheduleValue: string
21
+ timezone: string
22
+ targetType: 'queue' | 'command'
23
+ targetQueue: string | null
24
+ targetCommand: string | null
25
+ isEnabled: boolean
26
+ createdAt: string | null
27
+ updatedAt: string | null
28
+ }
29
+
30
+ export type CreateScheduleOverrides = {
31
+ name?: string
32
+ description?: string | null
33
+ scopeType?: 'system' | 'organization' | 'tenant'
34
+ scheduleType?: 'cron' | 'interval'
35
+ scheduleValue?: string
36
+ timezone?: string
37
+ targetType?: 'queue' | 'command'
38
+ targetQueue?: string
39
+ targetCommand?: string
40
+ targetPayload?: Record<string, unknown>
41
+ isEnabled?: boolean
42
+ sourceType?: 'user' | 'module'
43
+ }
44
+
45
+ let sequence = 0
46
+
47
+ /** Stable-ish unique label so concurrent fixtures never collide on name. */
48
+ export function uniqueScheduleName(prefix: string): string {
49
+ sequence += 1
50
+ return `${prefix} ${Date.now()}-${sequence}`
51
+ }
52
+
53
+ /**
54
+ * Create an organization-scoped queue-target schedule via the API and return its id.
55
+ * Org/tenant are derived server-side from the caller's auth context, so the caller
56
+ * only needs an admin (or otherwise scheduler.jobs.manage) token.
57
+ */
58
+ export async function createScheduleJob(
59
+ request: APIRequestContext,
60
+ token: string,
61
+ overrides: CreateScheduleOverrides = {},
62
+ ): Promise<string> {
63
+ const targetType = overrides.targetType ?? 'queue'
64
+ const data: Record<string, unknown> = {
65
+ name: overrides.name ?? uniqueScheduleName('Integration Scheduler'),
66
+ description: overrides.description ?? 'Created by scheduler integration tests',
67
+ scopeType: overrides.scopeType ?? 'organization',
68
+ scheduleType: overrides.scheduleType ?? 'interval',
69
+ scheduleValue: overrides.scheduleValue ?? '15m',
70
+ timezone: overrides.timezone ?? 'UTC',
71
+ targetType,
72
+ targetPayload: overrides.targetPayload ?? { source: 'integration-test' },
73
+ isEnabled: overrides.isEnabled ?? true,
74
+ sourceType: overrides.sourceType ?? 'user',
75
+ }
76
+ if (targetType === 'command') {
77
+ data.targetCommand = overrides.targetCommand
78
+ } else {
79
+ data.targetQueue = overrides.targetQueue ?? SCHEDULER_EXECUTION_QUEUE
80
+ }
81
+
82
+ const response = await apiRequest(request, 'POST', SCHEDULER_JOBS_PATH, { token, data })
83
+ const body = await readJsonSafe<{ id?: string }>(response)
84
+ expect(response.status(), 'POST /api/scheduler/jobs should return 201').toBe(201)
85
+ const id = body?.id
86
+ expect(typeof id === 'string' && /^[0-9a-f-]{36}$/i.test(id), 'create response should include a UUID id').toBe(true)
87
+ return String(id)
88
+ }
89
+
90
+ /** Fetch a single schedule by id from the list endpoint; null when absent (e.g. soft-deleted). */
91
+ export async function getScheduleJobById(
92
+ request: APIRequestContext,
93
+ token: string,
94
+ id: string,
95
+ ): Promise<SchedulerJob | null> {
96
+ const response = await apiRequest(request, 'GET', `${SCHEDULER_JOBS_PATH}?id=${encodeURIComponent(id)}`, { token })
97
+ expect(response.status(), 'GET /api/scheduler/jobs?id should return 200').toBe(200)
98
+ const body = await readJsonSafe<{ items?: SchedulerJob[] }>(response)
99
+ return (body?.items ?? []).find((item) => item.id === id) ?? null
100
+ }
101
+
102
+ /** Best-effort cleanup; swallows errors so teardown never masks the real assertion. */
103
+ export async function deleteScheduleJob(
104
+ request: APIRequestContext,
105
+ token: string,
106
+ id: string | null,
107
+ ): Promise<void> {
108
+ if (!id) return
109
+ await apiRequest(request, 'DELETE', SCHEDULER_JOBS_PATH, { token, data: { id } }).catch(() => null)
110
+ }
@@ -88,7 +88,7 @@ export default function EditSchedulePage({ params }: { params: { id: string } })
88
88
  const formSchema = React.useMemo(() => scheduledJobFormSchema(t), [t])
89
89
 
90
90
  const fields = React.useMemo(
91
- () => scheduledJobFields(t, { loadQueueOptions, loadCommandOptions, loadTimezoneOptions }),
91
+ () => scheduledJobFields(t, { loadQueueOptions, loadCommandOptions, loadTimezoneOptions }, { lockScope: true }),
92
92
  [t, loadQueueOptions, loadCommandOptions]
93
93
  )
94
94
 
@@ -14,6 +14,7 @@ import { useConfirmDialog } from '@open-mercato/ui/backend/confirm-dialog'
14
14
  import { useT } from '@open-mercato/shared/lib/i18n/context'
15
15
  import { useOrganizationScopeVersion } from '@open-mercato/shared/lib/frontend/useOrganizationScope'
16
16
  import { formatDateTime } from '@open-mercato/shared/lib/time'
17
+ import { ListEmptyState } from '@open-mercato/ui/backend/filters/ListEmptyState'
17
18
 
18
19
  type ScheduleRow = {
19
20
  id: string
@@ -196,7 +197,7 @@ export default function SchedulerPage() {
196
197
  : row.original.targetCommand
197
198
  return (
198
199
  <div className="flex flex-col">
199
- <span className="text-xs text-gray-500 capitalize">{row.original.targetType}</span>
200
+ <span className="text-xs text-muted-foreground capitalize">{row.original.targetType}</span>
200
201
  <span className="text-sm">{target || '-'}</span>
201
202
  </div>
202
203
  )
@@ -274,6 +275,13 @@ export default function SchedulerPage() {
274
275
  data={rows}
275
276
  onRowClick={(row) => router.push(`/backend/config/scheduled-jobs/${row.id}`)}
276
277
  rowActions={(row) => <RowActions items={rowActions(row)} />}
278
+ emptyState={(
279
+ <ListEmptyState
280
+ entityName={t('scheduler.title', 'Scheduled Jobs')}
281
+ createHref="/backend/config/scheduled-jobs/new"
282
+ createLabel={t('scheduler.action.create', 'New Schedule')}
283
+ />
284
+ )}
277
285
  pagination={{ page, pageSize, total, totalPages, onPageChange: setPage }}
278
286
  isLoading={isLoading}
279
287
  searchValue={search}
@@ -0,0 +1,181 @@
1
+ export {}
2
+
3
+ // Regression coverage for issue #2504: scheduler.jobs undo handlers were silent
4
+ // no-ops because they read `logEntry.payload` (always undefined) instead of the
5
+ // persisted `commandPayload`. These tests construct the logEntry exactly as the
6
+ // command bus persists it (redo-wrapped `commandPayload`, no top-level `payload`)
7
+ // and assert undo actually restores state.
8
+
9
+ const registerCommand = jest.fn()
10
+
11
+ jest.mock('@open-mercato/shared/lib/commands', () => ({
12
+ registerCommand,
13
+ }))
14
+
15
+ jest.mock('@open-mercato/shared/lib/i18n/server', () => ({
16
+ resolveTranslations: jest.fn().mockResolvedValue({
17
+ translate: (_key: string, fallback?: string) => fallback ?? _key,
18
+ }),
19
+ }))
20
+
21
+ function loadCommands() {
22
+ let create: any
23
+ let update: any
24
+ let del: any
25
+ jest.isolateModules(() => {
26
+ require('../jobs')
27
+ create = registerCommand.mock.calls.find(([cmd]) => cmd.id === 'scheduler.jobs.create')?.[0]
28
+ update = registerCommand.mock.calls.find(([cmd]) => cmd.id === 'scheduler.jobs.update')?.[0]
29
+ del = registerCommand.mock.calls.find(([cmd]) => cmd.id === 'scheduler.jobs.delete')?.[0]
30
+ })
31
+ return { create, update, del }
32
+ }
33
+
34
+ function makeEm(schedule: Record<string, unknown> | null) {
35
+ const removeFlush = jest.fn().mockResolvedValue(undefined)
36
+ const created: Record<string, unknown>[] = []
37
+ const em: any = {
38
+ fork: jest.fn().mockReturnThis(),
39
+ findOne: jest.fn().mockResolvedValue(schedule),
40
+ persist: jest.fn(),
41
+ remove: jest.fn().mockReturnValue({ flush: removeFlush }),
42
+ flush: jest.fn().mockResolvedValue(undefined),
43
+ create: jest.fn((_entity: unknown, data: Record<string, unknown>) => {
44
+ created.push(data)
45
+ return data
46
+ }),
47
+ __created: created,
48
+ __removeFlush: removeFlush,
49
+ }
50
+ return em
51
+ }
52
+
53
+ function makeCtx(em: any) {
54
+ return {
55
+ auth: { isSuperAdmin: true, tenantId: null },
56
+ container: { resolve: jest.fn(() => em) },
57
+ } as any
58
+ }
59
+
60
+ // Mirrors command-bus.persistLog: metadata.payload becomes the redo-wrapped
61
+ // `commandPayload`; there is no top-level `payload` on the stored row.
62
+ function persistedLogEntry(snapshots: { before?: unknown; after?: unknown }) {
63
+ return {
64
+ commandPayload: { __redoInput: { id: 'job-1' }, undo: { ...snapshots } },
65
+ snapshotBefore: snapshots.before,
66
+ snapshotAfter: snapshots.after,
67
+ }
68
+ }
69
+
70
+ function baseSnapshot(overrides: Record<string, unknown> = {}) {
71
+ return {
72
+ id: 'job-1',
73
+ name: 'Nightly report',
74
+ description: 'original description',
75
+ scopeType: 'tenant',
76
+ organizationId: null,
77
+ tenantId: 'tenant-a',
78
+ scheduleType: 'cron',
79
+ scheduleValue: '0 0 * * *',
80
+ timezone: 'UTC',
81
+ targetType: 'queue',
82
+ targetQueue: 'default',
83
+ targetCommand: null,
84
+ targetPayload: null,
85
+ requireFeature: null,
86
+ isEnabled: true,
87
+ sourceType: 'user',
88
+ sourceModule: null,
89
+ nextRunAt: null,
90
+ lastRunAt: null,
91
+ ...overrides,
92
+ }
93
+ }
94
+
95
+ describe('scheduler.jobs undo restores state (issue #2504)', () => {
96
+ beforeEach(() => {
97
+ jest.clearAllMocks()
98
+ jest.resetModules()
99
+ })
100
+
101
+ it('update undo restores the prior field values from commandPayload', async () => {
102
+ const { update } = loadCommands()
103
+ expect(update).toBeDefined()
104
+
105
+ const before = baseSnapshot({ name: 'Nightly report' })
106
+ const after = baseSnapshot({ name: 'Nightly report RENAMED' })
107
+ // The live row currently holds the post-update ("after") state.
108
+ const liveRow: Record<string, unknown> = { ...after }
109
+ const em = makeEm(liveRow)
110
+
111
+ await update.undo({ logEntry: persistedLogEntry({ before, after }), ctx: makeCtx(em) })
112
+
113
+ expect(em.flush).toHaveBeenCalled()
114
+ expect(liveRow.name).toBe('Nightly report')
115
+ })
116
+
117
+ it('update undo coerces JSON-serialized Date fields back to Date instances', async () => {
118
+ const { update } = loadCommands()
119
+ // Snapshots persisted in the action log are JSON, so Date fields arrive as
120
+ // ISO strings. They MUST be coerced to Date before assignment, otherwise
121
+ // MikroORM throws on the typed Date column (the real failure behind #2504).
122
+ const before = baseSnapshot({ nextRunAt: '2026-06-05T00:00:00.000Z', lastRunAt: '2026-06-04T00:00:00.000Z' })
123
+ const liveRow: Record<string, unknown> = { ...baseSnapshot() }
124
+ const em = makeEm(liveRow)
125
+
126
+ await update.undo({ logEntry: persistedLogEntry({ before }), ctx: makeCtx(em) })
127
+
128
+ expect(liveRow.nextRunAt).toBeInstanceOf(Date)
129
+ expect(liveRow.lastRunAt).toBeInstanceOf(Date)
130
+ expect((liveRow.nextRunAt as Date).toISOString()).toBe('2026-06-05T00:00:00.000Z')
131
+ })
132
+
133
+ it('update undo is a no-op when no snapshot is recoverable', async () => {
134
+ const { update } = loadCommands()
135
+ const em = makeEm({ id: 'job-1', name: 'whatever' })
136
+ // No commandPayload and no snapshots -> nothing to restore.
137
+ await update.undo({ logEntry: { commandPayload: null }, ctx: makeCtx(em) })
138
+ expect(em.findOne).not.toHaveBeenCalled()
139
+ expect(em.flush).not.toHaveBeenCalled()
140
+ })
141
+
142
+ it('create undo removes the created row using the after snapshot', async () => {
143
+ const { create } = loadCommands()
144
+ const after = baseSnapshot()
145
+ const liveRow = { ...after }
146
+ const em = makeEm(liveRow)
147
+
148
+ await create.undo({ logEntry: persistedLogEntry({ after }), ctx: makeCtx(em) })
149
+
150
+ expect(em.remove).toHaveBeenCalledWith(liveRow)
151
+ expect(em.__removeFlush).toHaveBeenCalled()
152
+ })
153
+
154
+ it('delete undo restores a soft-deleted row by clearing deletedAt', async () => {
155
+ const { del } = loadCommands()
156
+ const before = baseSnapshot()
157
+ const liveRow: Record<string, unknown> = { ...before, deletedAt: new Date() }
158
+ const em = makeEm(liveRow)
159
+
160
+ await del.undo({ logEntry: persistedLogEntry({ before }), ctx: makeCtx(em) })
161
+
162
+ expect(liveRow.deletedAt).toBeNull()
163
+ expect(em.flush).toHaveBeenCalled()
164
+ expect(em.create).not.toHaveBeenCalled()
165
+ })
166
+
167
+ it('delete undo re-materializes a hard-removed row from the snapshot', async () => {
168
+ const { del } = loadCommands()
169
+ const before = baseSnapshot({ name: 'Hard removed job', nextRunAt: '2026-06-05T00:00:00.000Z' })
170
+ // findOne returns null -> the row no longer exists and must be re-created.
171
+ const em = makeEm(null)
172
+
173
+ await del.undo({ logEntry: persistedLogEntry({ before }), ctx: makeCtx(em) })
174
+
175
+ expect(em.create).toHaveBeenCalled()
176
+ expect(em.__created[0]).toMatchObject({ id: 'job-1', name: 'Hard removed job', deletedAt: null })
177
+ // Re-materialization also coerces JSON date strings to Date instances.
178
+ expect(em.__created[0].nextRunAt).toBeInstanceOf(Date)
179
+ expect(em.flush).toHaveBeenCalled()
180
+ })
181
+ })