@open-mercato/scheduler 0.10.1-develop.8231.1.ae76b1d2c5 → 0.10.1-develop.8258.1.62a94b74a2

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.
@@ -1,2 +1,2 @@
1
- [build:scheduler] found 65 entry points
1
+ [build:scheduler] found 66 entry points
2
2
  [build:scheduler] built successfully
@@ -0,0 +1,49 @@
1
+ import { expect, test } 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 { SCHEDULER_JOBS_PATH, createScheduleJob, deleteScheduleJob } from "./helpers/scheduler.js";
5
+ const ONE_HOUR_MS = 60 * 60 * 1e3;
6
+ async function readRunTimes(request, token, id) {
7
+ const response = await apiRequest(
8
+ request,
9
+ "GET",
10
+ `${SCHEDULER_JOBS_PATH}?id=${encodeURIComponent(id)}&probe=${Date.now()}`,
11
+ { token }
12
+ );
13
+ expect(response.status()).toBe(200);
14
+ const body = await readJsonSafe(response);
15
+ const item = (body?.items ?? []).find((entry) => entry.id === id);
16
+ expect(item?.nextRunAt, "schedule should expose nextRunAt").toBeTruthy();
17
+ expect(item?.updatedAt, "schedule should expose updatedAt").toBeTruthy();
18
+ return {
19
+ nextRunAt: new Date(String(item?.nextRunAt)).getTime(),
20
+ updatedAt: new Date(String(item?.updatedAt)).getTime()
21
+ };
22
+ }
23
+ test.describe("TC-SCHED-011: enabling a schedule recomputes nextRunAt", () => {
24
+ test("PUT { id, isEnabled: true } moves nextRunAt to one interval after the enable", async ({ request }) => {
25
+ const token = await getAuthToken(request, "admin");
26
+ let scheduleId = null;
27
+ try {
28
+ scheduleId = await createScheduleJob(request, token, { scheduleValue: "1h", isEnabled: true });
29
+ const created = await readRunTimes(request, token, scheduleId);
30
+ const disableResponse = await apiRequest(request, "PUT", SCHEDULER_JOBS_PATH, {
31
+ token,
32
+ data: { id: scheduleId, isEnabled: false }
33
+ });
34
+ expect(disableResponse.status()).toBe(200);
35
+ await new Promise((resolve) => setTimeout(resolve, 2e3));
36
+ const enableResponse = await apiRequest(request, "PUT", SCHEDULER_JOBS_PATH, {
37
+ token,
38
+ data: { id: scheduleId, isEnabled: true }
39
+ });
40
+ expect(enableResponse.status()).toBe(200);
41
+ const enabled = await readRunTimes(request, token, scheduleId);
42
+ expect(enabled.nextRunAt).toBeGreaterThan(created.nextRunAt);
43
+ expect(Math.abs(enabled.nextRunAt - (enabled.updatedAt + ONE_HOUR_MS))).toBeLessThan(1e3);
44
+ } finally {
45
+ await deleteScheduleJob(request, token, scheduleId);
46
+ }
47
+ });
48
+ });
49
+ //# sourceMappingURL=TC-SCHED-011.spec.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../src/modules/scheduler/__integration__/TC-SCHED-011.spec.ts"],
4
+ "sourcesContent": ["import { expect, test } from '@playwright/test'\nimport { apiRequest, getAuthToken } from '@open-mercato/core/helpers/integration/api'\nimport { readJsonSafe } from '@open-mercato/core/helpers/integration/generalFixtures'\nimport { SCHEDULER_JOBS_PATH, createScheduleJob, deleteScheduleJob } from './helpers/scheduler'\n\nconst ONE_HOUR_MS = 60 * 60 * 1000\n\nasync function readRunTimes(\n request: Parameters<typeof getAuthToken>[0],\n token: string,\n id: string,\n): Promise<{ nextRunAt: number; updatedAt: number }> {\n const response = await apiRequest(\n request,\n 'GET',\n `${SCHEDULER_JOBS_PATH}?id=${encodeURIComponent(id)}&probe=${Date.now()}`,\n { token },\n )\n expect(response.status()).toBe(200)\n const body = await readJsonSafe<{\n items?: Array<{ id: string; nextRunAt: string | null; updatedAt: string | null }>\n }>(response)\n const item = (body?.items ?? []).find((entry) => entry.id === id)\n expect(item?.nextRunAt, 'schedule should expose nextRunAt').toBeTruthy()\n expect(item?.updatedAt, 'schedule should expose updatedAt').toBeTruthy()\n return {\n nextRunAt: new Date(String(item?.nextRunAt)).getTime(),\n updatedAt: new Date(String(item?.updatedAt)).getTime(),\n }\n}\n\n/**\n * TC-SCHED-011: enabling a disabled schedule recomputes nextRunAt from its own\n * definition, so a value left over from before it was disabled never makes the\n * local poller treat it as already due.\n */\ntest.describe('TC-SCHED-011: enabling a schedule recomputes nextRunAt', () => {\n test('PUT { id, isEnabled: true } moves nextRunAt to one interval after the enable', async ({ request }) => {\n const token = await getAuthToken(request, 'admin')\n let scheduleId: string | null = null\n\n try {\n scheduleId = await createScheduleJob(request, token, { scheduleValue: '1h', isEnabled: true })\n const created = await readRunTimes(request, token, scheduleId)\n\n const disableResponse = await apiRequest(request, 'PUT', SCHEDULER_JOBS_PATH, {\n token,\n data: { id: scheduleId, isEnabled: false },\n })\n expect(disableResponse.status()).toBe(200)\n\n await new Promise((resolve) => setTimeout(resolve, 2_000))\n\n const enableResponse = await apiRequest(request, 'PUT', SCHEDULER_JOBS_PATH, {\n token,\n data: { id: scheduleId, isEnabled: true },\n })\n expect(enableResponse.status()).toBe(200)\n\n const enabled = await readRunTimes(request, token, scheduleId)\n expect(enabled.nextRunAt).toBeGreaterThan(created.nextRunAt)\n expect(Math.abs(enabled.nextRunAt - (enabled.updatedAt + ONE_HOUR_MS))).toBeLessThan(1_000)\n } finally {\n await deleteScheduleJob(request, token, scheduleId)\n }\n })\n})\n"],
5
+ "mappings": "AAAA,SAAS,QAAQ,YAAY;AAC7B,SAAS,YAAY,oBAAoB;AACzC,SAAS,oBAAoB;AAC7B,SAAS,qBAAqB,mBAAmB,yBAAyB;AAE1E,MAAM,cAAc,KAAK,KAAK;AAE9B,eAAe,aACb,SACA,OACA,IACmD;AACnD,QAAM,WAAW,MAAM;AAAA,IACrB;AAAA,IACA;AAAA,IACA,GAAG,mBAAmB,OAAO,mBAAmB,EAAE,CAAC,UAAU,KAAK,IAAI,CAAC;AAAA,IACvE,EAAE,MAAM;AAAA,EACV;AACA,SAAO,SAAS,OAAO,CAAC,EAAE,KAAK,GAAG;AAClC,QAAM,OAAO,MAAM,aAEh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AA,IAC5F,UAAE;AACA,YAAM,kBAAkB,SAAS,OAAO,UAAU;AAAA,IACpD;AAAA,EACF,CAAC;AACH,CAAC;",
6
+ "names": []
7
+ }
@@ -285,7 +285,8 @@ const updateScheduleCommand = {
285
285
  }
286
286
  }
287
287
  const scheduleChanged = input.scheduleType !== void 0 || input.scheduleValue !== void 0 || input.timezone !== void 0;
288
- const nextRunAt = scheduleChanged ? calculateNextRunForWrite(
288
+ const reenabling = input.isEnabled === true && schedule.isEnabled !== true;
289
+ const nextRunAt = scheduleChanged || reenabling ? calculateNextRunForWrite(
289
290
  input.scheduleType ?? schedule.scheduleType,
290
291
  input.scheduleValue ?? schedule.scheduleValue,
291
292
  input.timezone ?? schedule.timezone
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/scheduler/commands/jobs.ts"],
4
- "sourcesContent": ["import { registerCommand } from '@open-mercato/shared/lib/commands'\nimport type { CommandHandler, CommandRuntimeContext } from '@open-mercato/shared/lib/commands'\nimport { extractUndoPayload, type UndoPayload } from '@open-mercato/shared/lib/commands/undo'\nimport { makeCreateRedo } from '@open-mercato/shared/lib/commands/redo'\nimport { ensureOrganizationScope } from '@open-mercato/shared/lib/commands/scope'\nimport { CrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport type { EntityManager } from '@mikro-orm/core'\nimport { ScheduledJob } from '../data/entities.js'\nimport { calculateNextRunForWrite } from '../lib/nextRunCalculator.js'\nimport { enforceTenantActiveScheduleLimit } from '../lib/activeScheduleLimits.js'\nimport type {\n ScheduleCreateInput,\n ScheduleUpdateInput,\n} from '../data/validators.js'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport type { BullMQSchedulerService } from '../services/bullmqSchedulerService.js'\nimport {\n assertSchedulerQueueTargetAuthorized,\n isSchedulerSafeQueue,\n validateSchedulerTargetPayload,\n} from '../lib/safeQueueTargets.js'\nimport type { SchedulerTargetRbacService } from '../lib/safeQueueTargets.js'\n/**\n * Snapshot of a schedule for undo/redo\n */\ntype ScheduleSnapshot = {\n id: string\n name: string\n description: string | null\n scopeType: 'system' | 'organization' | 'tenant'\n organizationId: string | null\n tenantId: string | null\n scheduleType: 'cron' | 'interval'\n scheduleValue: string\n timezone: string\n targetType: 'queue' | 'command'\n targetQueue: string | null\n targetCommand: string | null\n targetPayload: Record<string, unknown> | null\n requireFeature: string | null\n isEnabled: boolean\n sourceType: 'user' | 'module'\n sourceModule: string | null\n nextRunAt: Date | null\n lastRunAt: Date | null\n}\n\n/**\n * Load a schedule snapshot\n */\nasync function loadScheduleSnapshot(\n em: EntityManager,\n scheduleId: string\n): Promise<ScheduleSnapshot | null> {\n const schedule = await em.findOne(ScheduledJob, { id: scheduleId })\n if (!schedule) return null\n\n return {\n id: schedule.id,\n name: schedule.name,\n description: schedule.description ?? null,\n scopeType: schedule.scopeType,\n organizationId: schedule.organizationId ?? null,\n tenantId: schedule.tenantId ?? null,\n scheduleType: schedule.scheduleType,\n scheduleValue: schedule.scheduleValue,\n timezone: schedule.timezone,\n targetType: schedule.targetType,\n targetQueue: schedule.targetQueue ?? null,\n targetCommand: schedule.targetCommand ?? null,\n targetPayload: schedule.targetPayload ?? null,\n requireFeature: schedule.requireFeature ?? null,\n isEnabled: schedule.isEnabled,\n sourceType: schedule.sourceType,\n sourceModule: schedule.sourceModule ?? null,\n nextRunAt: schedule.nextRunAt ?? null,\n lastRunAt: schedule.lastRunAt ?? null,\n }\n}\n\n/**\n * Snapshots are persisted as JSON (in the action log's command payload), so Date\n * fields come back as ISO strings on undo. Coerce them to Date before writing\n * them onto the entity, otherwise MikroORM throws while flushing a Date column.\n */\nfunction toDate(value: Date | string | null | undefined): Date | null {\n if (!value) return null\n return value instanceof Date ? value : new Date(value)\n}\n\nfunction canonicalJson(value: unknown): string {\n if (value === null || typeof value !== 'object') return JSON.stringify(value ?? null)\n if (Array.isArray(value)) return `[${value.map(canonicalJson).join(',')}]`\n const entries = Object.entries(value as Record<string, unknown>)\n .filter(([, v]) => v !== undefined)\n .sort(([a], [b]) => a.localeCompare(b))\n return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${canonicalJson(v)}`).join(',')}}`\n}\n\nfunction normalizeTargetPayloadValue(value: unknown): unknown {\n // `schedulerService.register()` persists `{}` as-is while the edit form sends\n // `null` for an empty payload \u2014 treat the three empty shapes as equal (#5213).\n if (value !== null && typeof value === 'object' && !Array.isArray(value)\n && Object.keys(value as Record<string, unknown>).length === 0) return null\n return value\n}\n\nfunction targetPayloadChanged(inputValue: unknown, storedValue: unknown): boolean {\n return targetValueChanged(\n normalizeTargetPayloadValue(inputValue),\n normalizeTargetPayloadValue(storedValue),\n )\n}\n\nfunction targetValueChanged(inputValue: unknown, storedValue: unknown): boolean {\n if (inputValue === undefined) return false\n return canonicalJson(inputValue ?? null) !== canonicalJson(storedValue ?? null)\n}\n\ntype QueueTargetAuthorizationContext = CommandRuntimeContext\n\nasync function assertQueueTargetAuthorizedForActor(\n ctx: QueueTargetAuthorizationContext,\n queue: string,\n): Promise<void> {\n const rbacService = (() => {\n try {\n return ctx.container?.resolve<SchedulerTargetRbacService>('rbacService') ?? null\n } catch {\n return null\n }\n })()\n const reason = await assertSchedulerQueueTargetAuthorized({\n queue,\n actorUserId: resolveCommandActorUserId(ctx),\n tenantId: ctx.auth?.tenantId ?? null,\n organizationId: ctx.auth?.orgId ?? null,\n isSuperAdmin: ctx.auth?.isSuperAdmin === true,\n rbacService,\n })\n if (reason) throw new CrudHttpError(403, { error: reason })\n}\n\nasync function assertQueueTargetPayloadAllowed(queue: string, targetPayload: Record<string, unknown> | null | undefined): Promise<void> {\n const reason = validateSchedulerTargetPayload(queue, targetPayload)\n if (reason) throw new CrudHttpError(422, { error: `Invalid target payload for queue ${queue}: ${reason}` })\n}\n\nexport function resolveCommandActorUserId(ctx: CommandRuntimeContext): string | null {\n const auth = ctx.auth\n if (!auth) return null\n if (typeof auth.userId === 'string' && auth.userId.trim().length > 0) return auth.userId.trim()\n if (auth.isApiKey) return null\n return typeof auth.sub === 'string' && auth.sub.trim().length > 0 ? auth.sub.trim() : null\n}\n\n/**\n * Build a full create seed (including the original id and Date-coerced timestamps)\n * from a snapshot. Shared by `materializeScheduleFromSnapshot` (delete-undo) and the\n * create command's id-preserving `redo`.\n */\nfunction scheduleSeedFromSnapshot(snapshot: ScheduleSnapshot): Record<string, unknown> {\n const now = new Date()\n return {\n id: snapshot.id,\n name: snapshot.name,\n description: snapshot.description,\n scopeType: snapshot.scopeType,\n organizationId: snapshot.organizationId,\n tenantId: snapshot.tenantId,\n scheduleType: snapshot.scheduleType,\n scheduleValue: snapshot.scheduleValue,\n timezone: snapshot.timezone,\n targetType: snapshot.targetType,\n targetQueue: snapshot.targetQueue,\n targetCommand: snapshot.targetCommand,\n targetPayload: snapshot.targetPayload,\n requireFeature: snapshot.requireFeature,\n isEnabled: snapshot.isEnabled,\n sourceType: snapshot.sourceType,\n sourceModule: snapshot.sourceModule,\n nextRunAt: toDate(snapshot.nextRunAt),\n lastRunAt: toDate(snapshot.lastRunAt),\n deletedAt: null,\n createdAt: now,\n updatedAt: now,\n }\n}\n\n/**\n * Re-create a ScheduledJob entity from a snapshot, preserving its original id.\n * Used by delete-undo when the row was hard-removed rather than soft-deleted.\n */\nfunction materializeScheduleFromSnapshot(em: EntityManager, snapshot: ScheduleSnapshot): ScheduledJob {\n return em.create(ScheduledJob, scheduleSeedFromSnapshot(snapshot) as never)\n}\n\n/**\n * Trigger BullMQ sync after undo operations.\n * Best-effort: if BullMQ service is unavailable (e.g. local strategy), this is a no-op.\n */\nasync function syncBullMQAfterUndo(ctx: CommandRuntimeContext, schedule: ScheduledJob | null): Promise<void> {\n try {\n if (!ctx.container?.resolve) return\n const bullmqService = ctx.container.resolve<BullMQSchedulerService>('bullmqSchedulerService')\n if (!bullmqService) return\n\n if (schedule && schedule.isEnabled && !schedule.deletedAt) {\n await bullmqService.register(schedule, { skipNextRunUpdate: true })\n } else if (schedule) {\n await bullmqService.unregister(schedule.id)\n }\n } catch {\n // Best-effort: BullMQ service may not be registered (local strategy)\n }\n}\n\n/**\n * Ensure tenant/org scope for security\n */\nfunction ensureTenantScope(ctx: CommandRuntimeContext, tenantId: string | null | undefined) {\n if (tenantId && ctx.auth?.tenantId && ctx.auth.tenantId !== tenantId) {\n throw new Error('Tenant mismatch')\n }\n}\n\n// Super-admin status is the immutable `isSuperAdmin` flag derived from\n// RoleAcl/UserAcl at session resolution. Never compare role names to a string\n// like 'superadmin' \u2014 role names are tenant-mutable and trivially spoofable.\nfunction isSuperAdminActor(ctx: CommandRuntimeContext): boolean {\n return ctx.auth?.isSuperAdmin === true\n}\n\n// `ensureTenantScope` is a no-op for system-scoped jobs (tenantId === null), so a\n// `scheduler.jobs.manage` holder could otherwise update/delete a system schedule\n// belonging to the whole deployment. System-scoped jobs MUST be super-admin only,\n// mirroring the create route's system-scope gate.\nfunction ensureCanManageSystemScopedJob(\n ctx: CommandRuntimeContext,\n job: { scopeType?: string | null; tenantId?: string | null },\n): void {\n const isSystemScoped = job.scopeType === 'system' || job.tenantId == null\n if (!isSystemScoped) return\n if (isSuperAdminActor(ctx)) return\n throw new CrudHttpError(403, {\n error: 'System-scoped scheduled jobs can only be managed by a super administrator.',\n })\n}\n\n/**\n * CREATE SCHEDULE COMMAND\n */\nconst createScheduleCommand: CommandHandler<ScheduleCreateInput, { id: string }> = {\n id: 'scheduler.jobs.create',\n\n async execute(input, ctx) {\n ensureTenantScope(ctx, input.tenantId)\n if (input.organizationId) ensureOrganizationScope(ctx, input.organizationId)\n ensureCanManageSystemScopedJob(ctx, { scopeType: input.scopeType, tenantId: input.tenantId })\n\n const em = ctx.container.resolve<EntityManager>('em').fork()\n\n if (input.isEnabled ?? true) {\n await enforceTenantActiveScheduleLimit(em, input.tenantId)\n }\n\n // Calculate next run time\n const nextRunAt = calculateNextRunForWrite(\n input.scheduleType,\n input.scheduleValue,\n input.timezone || 'UTC'\n )\n\n if (!nextRunAt) {\n throw new Error('Failed to calculate next run time')\n }\n\n if (input.targetType === 'queue' && input.targetQueue) {\n await assertQueueTargetAuthorizedForActor(ctx, input.targetQueue)\n await assertQueueTargetPayloadAllowed(input.targetQueue, input.targetPayload)\n }\n\n // Create schedule\n const schedule = em.create(ScheduledJob, {\n name: input.name,\n description: input.description ?? null,\n scopeType: input.scopeType,\n organizationId: input.organizationId ?? null,\n tenantId: input.tenantId ?? null,\n scheduleType: input.scheduleType,\n scheduleValue: input.scheduleValue,\n timezone: input.timezone ?? 'UTC',\n targetType: input.targetType,\n targetQueue: input.targetQueue ?? null,\n targetCommand: input.targetCommand ?? null,\n targetPayload: input.targetPayload ?? null,\n requireFeature: input.requireFeature ?? null,\n isEnabled: input.isEnabled ?? true,\n sourceType: 'user',\n sourceModule: null,\n nextRunAt,\n createdByUserId: resolveCommandActorUserId(ctx),\n createdAt: new Date(),\n updatedAt: new Date(),\n })\n\n em.persist(schedule)\n await em.flush()\n\n return { id: schedule.id }\n },\n\n async captureAfter(_input, result, ctx) {\n const em = ctx.container.resolve<EntityManager>('em')\n return await loadScheduleSnapshot(em, result.id)\n },\n\n async buildLog({ result, ctx, snapshots }) {\n const { translate } = await resolveTranslations()\n const after = snapshots.after as ScheduleSnapshot | undefined\n\n return {\n actionLabel: translate('scheduler.audit.create', 'Create schedule'),\n resourceKind: 'scheduler.job',\n resourceId: result.id,\n tenantId: after?.tenantId || null,\n organizationId: after?.organizationId || null,\n snapshotAfter: after,\n payload: { undo: { after } },\n }\n },\n\n async undo({ logEntry, ctx }) {\n const after = extractUndoPayload<UndoPayload<ScheduleSnapshot>>(logEntry)?.after\n if (!after) return\n\n const em = ctx.container.resolve<EntityManager>('em').fork()\n const schedule = await em.findOne(ScheduledJob, { id: after.id })\n\n if (schedule) {\n await em.remove(schedule).flush()\n await syncBullMQAfterUndo(ctx, schedule)\n }\n },\n\n redo: makeCreateRedo<ScheduledJob, ScheduleSnapshot, ScheduleCreateInput, { id: string }>({\n entityClass: ScheduledJob,\n getSnapshotId: (snapshot) => snapshot.id,\n seedFromSnapshot: scheduleSeedFromSnapshot,\n buildResult: (entity) => ({ id: entity.id }),\n afterRestore: async ({ ctx, entity }) => {\n await syncBullMQAfterUndo(ctx, entity)\n },\n }),\n}\n\n/**\n * UPDATE SCHEDULE COMMAND\n */\nconst updateScheduleCommand: CommandHandler<ScheduleUpdateInput, { ok: boolean }> = {\n id: 'scheduler.jobs.update',\n\n async prepare(input, ctx) {\n const em = ctx.container.resolve<EntityManager>('em')\n const before = await loadScheduleSnapshot(em, input.id)\n return { before }\n },\n\n async execute(input, ctx) {\n const em = ctx.container.resolve<EntityManager>('em').fork()\n\n const schedule = await em.findOne(ScheduledJob, { id: input.id, deletedAt: null })\n if (!schedule) {\n throw new Error('Schedule not found')\n }\n\n ensureTenantScope(ctx, schedule.tenantId)\n if (schedule.organizationId) ensureOrganizationScope(ctx, schedule.organizationId)\n ensureCanManageSystemScopedJob(ctx, schedule)\n\n // Module-authored schedules are trusted infrastructure wiring (#5213): their\n // target and payload are owned by the registering module. Submitting them\n // unchanged is a no-op (the edit form always resends every field) \u2014 only an\n // actual change to provenance-relevant values is rejected.\n const touchesModuleOwnedTarget =\n schedule.sourceType === 'module'\n && (\n targetValueChanged(input.targetType, schedule.targetType)\n || targetValueChanged(input.targetQueue, schedule.targetQueue)\n || targetValueChanged(input.targetCommand, schedule.targetCommand)\n || targetPayloadChanged(input.targetPayload, schedule.targetPayload)\n )\n if (touchesModuleOwnedTarget) {\n const { translate } = await resolveTranslations()\n throw new CrudHttpError(403, {\n error: translate(\n 'scheduler.errors.module_target_immutable',\n 'Module-authored schedules own their target; only operational fields can be updated here.',\n ),\n })\n }\n\n if (input.isEnabled === true && schedule.isEnabled !== true) {\n await enforceTenantActiveScheduleLimit(em, schedule.tenantId)\n }\n\n const effectiveTargetType = input.targetType ?? schedule.targetType\n const effectiveQueue = input.targetQueue ?? schedule.targetQueue\n const queueChanged =\n effectiveTargetType === 'queue'\n && (\n targetValueChanged(input.targetQueue, schedule.targetQueue)\n || targetValueChanged(input.targetType, schedule.targetType)\n || targetPayloadChanged(input.targetPayload, schedule.targetPayload)\n )\n if (effectiveTargetType === 'queue' && effectiveQueue) {\n const retargetedToUnapprovedQueue =\n input.targetQueue !== undefined\n && input.targetQueue !== schedule.targetQueue\n && !isSchedulerSafeQueue(input.targetQueue)\n // A save that leaves a user-authored row ACTIVE on an unapproved queue\n // restores the invariant the update schema used to enforce; disabling the\n // row stays allowed so admins can remediate legacy targets from the UI.\n // (Dispatch-time re-verification remains the backstop either way.)\n const keepsUnapprovedQueueActive =\n effectiveQueue != null\n && !isSchedulerSafeQueue(effectiveQueue)\n && input.isEnabled !== false\n && schedule.isEnabled !== false\n if (\n (retargetedToUnapprovedQueue || keepsUnapprovedQueueActive)\n && schedule.sourceType !== 'module'\n ) {\n const { translate } = await resolveTranslations()\n throw new CrudHttpError(422, {\n error: translate(\n 'scheduler.errors.queue_not_approved',\n 'Target queue is not an approved scheduler target. Only workers that opted into scheduling can be selected.',\n ),\n })\n }\n if (queueChanged) {\n await assertQueueTargetAuthorizedForActor(ctx, effectiveQueue)\n const effectivePayload = input.targetPayload !== undefined\n ? input.targetPayload\n : schedule.targetPayload\n await assertQueueTargetPayloadAllowed(effectiveQueue, effectivePayload)\n }\n }\n\n const scheduleChanged = input.scheduleType !== undefined || input.scheduleValue !== undefined || input.timezone !== undefined\n const nextRunAt = scheduleChanged\n ? calculateNextRunForWrite(\n input.scheduleType ?? schedule.scheduleType,\n input.scheduleValue ?? schedule.scheduleValue,\n input.timezone ?? schedule.timezone,\n )\n : null\n\n if (scheduleChanged && !nextRunAt) {\n const { translate } = await resolveTranslations()\n throw new CrudHttpError(422, {\n error: translate('scheduler.error.invalid_schedule_value', 'Invalid schedule value.'),\n })\n }\n\n // Update fields\n if (input.name !== undefined) schedule.name = input.name\n if (input.description !== undefined) schedule.description = input.description ?? null\n if (input.scheduleType !== undefined) schedule.scheduleType = input.scheduleType\n if (input.scheduleValue !== undefined) schedule.scheduleValue = input.scheduleValue\n if (input.timezone !== undefined) schedule.timezone = input.timezone\n if (input.targetPayload !== undefined) schedule.targetPayload = input.targetPayload ?? null\n if (input.requireFeature !== undefined) schedule.requireFeature = input.requireFeature || null\n if (input.isEnabled !== undefined) schedule.isEnabled = input.isEnabled\n \n // Handle target type changes - clear stale values when switching between queue and command\n if (input.targetType !== undefined) {\n schedule.targetType = input.targetType\n \n if (input.targetType === 'queue') {\n // Switching to queue: set new queue and clear command\n if (input.targetQueue !== undefined) schedule.targetQueue = input.targetQueue\n schedule.targetCommand = null\n } else if (input.targetType === 'command') {\n // Switching to command: set new command and clear queue\n if (input.targetCommand !== undefined) schedule.targetCommand = input.targetCommand\n schedule.targetQueue = null\n }\n } else {\n // targetType not changing, but allow updating individual target fields\n if (input.targetQueue !== undefined) schedule.targetQueue = input.targetQueue\n if (input.targetCommand !== undefined) schedule.targetCommand = input.targetCommand\n }\n\n if (nextRunAt) {\n schedule.nextRunAt = nextRunAt\n }\n\n schedule.updatedAt = new Date()\n schedule.updatedByUserId = resolveCommandActorUserId(ctx)\n\n await em.flush()\n\n return { ok: true }\n },\n\n async captureAfter(input, _result, ctx) {\n const em = ctx.container.resolve<EntityManager>('em')\n return await loadScheduleSnapshot(em, input.id)\n },\n\n async buildLog({ input, ctx, snapshots }) {\n const { translate } = await resolveTranslations()\n const before = snapshots.before as ScheduleSnapshot | undefined\n const after = snapshots.after as ScheduleSnapshot | undefined\n\n return {\n actionLabel: translate('scheduler.audit.update', 'Update schedule'),\n resourceKind: 'scheduler.job',\n resourceId: input.id,\n tenantId: after?.tenantId || null,\n organizationId: after?.organizationId || null,\n snapshotBefore: before,\n snapshotAfter: after,\n payload: { undo: { before, after } },\n }\n },\n\n async undo({ logEntry, ctx }) {\n const before = extractUndoPayload<UndoPayload<ScheduleSnapshot>>(logEntry)?.before\n if (!before) return\n\n const em = ctx.container.resolve<EntityManager>('em').fork()\n const schedule = await em.findOne(ScheduledJob, { id: before.id })\n\n if (schedule) {\n // Restore all fields\n schedule.name = before.name\n schedule.description = before.description\n schedule.scopeType = before.scopeType\n schedule.organizationId = before.organizationId\n schedule.tenantId = before.tenantId\n schedule.scheduleType = before.scheduleType\n schedule.scheduleValue = before.scheduleValue\n schedule.timezone = before.timezone\n schedule.targetType = before.targetType\n schedule.targetQueue = before.targetQueue\n schedule.targetCommand = before.targetCommand\n schedule.targetPayload = before.targetPayload\n schedule.requireFeature = before.requireFeature\n schedule.isEnabled = before.isEnabled\n schedule.sourceType = before.sourceType\n schedule.sourceModule = before.sourceModule\n schedule.nextRunAt = toDate(before.nextRunAt)\n schedule.lastRunAt = toDate(before.lastRunAt)\n schedule.updatedAt = new Date()\n\n await em.flush()\n await syncBullMQAfterUndo(ctx, schedule)\n }\n },\n}\n\n/**\n * DELETE SCHEDULE COMMAND\n */\nconst deleteScheduleCommand: CommandHandler<{ id: string }, { ok: boolean }> = {\n id: 'scheduler.jobs.delete',\n\n async prepare(input, ctx) {\n const em = ctx.container.resolve<EntityManager>('em')\n const before = await loadScheduleSnapshot(em, input.id)\n return { before }\n },\n\n async execute(input, ctx) {\n const em = ctx.container.resolve<EntityManager>('em').fork()\n\n const schedule = await em.findOne(ScheduledJob, { id: input.id, deletedAt: null })\n if (!schedule) {\n throw new Error('Schedule not found')\n }\n\n ensureTenantScope(ctx, schedule.tenantId)\n if (schedule.organizationId) ensureOrganizationScope(ctx, schedule.organizationId)\n ensureCanManageSystemScopedJob(ctx, schedule)\n\n // Soft delete\n schedule.deletedAt = new Date()\n schedule.updatedAt = new Date()\n schedule.updatedByUserId = resolveCommandActorUserId(ctx)\n\n await em.flush()\n\n return { ok: true }\n },\n\n async buildLog({ input, ctx, snapshots }) {\n const { translate } = await resolveTranslations()\n const before = snapshots.before as ScheduleSnapshot | undefined\n\n return {\n actionLabel: translate('scheduler.audit.delete', 'Delete schedule'),\n resourceKind: 'scheduler.job',\n resourceId: input.id,\n tenantId: before?.tenantId || null,\n organizationId: before?.organizationId || null,\n snapshotBefore: before,\n payload: { undo: { before } },\n }\n },\n\n async undo({ logEntry, ctx }) {\n const before = extractUndoPayload<UndoPayload<ScheduleSnapshot>>(logEntry)?.before\n if (!before) return\n\n const em = ctx.container.resolve<EntityManager>('em').fork()\n const existing = await em.findOne(ScheduledJob, { id: before.id })\n\n // Soft-deleted rows are restored by clearing `deletedAt`. A hard-removed row\n // (no surviving record) is re-materialized from the snapshot so undo is\n // robust to either deletion strategy \u2014 mirroring the sales reference undo.\n const schedule = existing ?? materializeScheduleFromSnapshot(em, before)\n if (existing) {\n schedule.deletedAt = null\n schedule.updatedAt = new Date()\n }\n await em.flush()\n await syncBullMQAfterUndo(ctx, schedule)\n },\n}\n\n// Register all commands\nregisterCommand(createScheduleCommand)\nregisterCommand(updateScheduleCommand)\nregisterCommand(deleteScheduleCommand)\n"],
5
- "mappings": "AAAA,SAAS,uBAAuB;AAEhC,SAAS,0BAA4C;AACrD,SAAS,sBAAsB;AAC/B,SAAS,+BAA+B;AACxC,SAAS,qBAAqB;AAE9B,SAAS,oBAAoB;AAC7B,SAAS,gCAAgC;AACzC,SAAS,wCAAwC;AAKjD,SAAS,2BAA2B;AAEpC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AA8BP,eAAe,qBACb,IACA,YACkC;AAClC,QAAM,WAAW,MAAM,GAAG,QAAQ,cAAc,EAAE,IAAI,WAAW,CAAC;AAClE,MAAI,CAAC,SAAU,QAAO;AAEpB,SAAO;AAAA,IACP,IAAI,SAAS;AAAA,IACb,MAAM,SAAS;AAAA,IACf,aAAa,SAAS,eAAe;AAAA,IACrC,WAAW,SAAS;AAAA,IACpB,gBAAgB,SAAS,kBAAkB;AAAA,IAC3C,UAAU,SAAS,YAAY;AAAA,IAC/B,cAAc,SAAS;AAAA,IACvB,eAAe,SAAS;AAAA,IACxB,UAAU,SAAS;AAAA,IACnB,YAAY,SAAS;AAAA,IACrB,aAAa,SAAS,eAAe;AAAA,IACrC,eAAe,SAAS,iBAAiB;AAAA,IACzC,eAAe,S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QAAI,UAAU;AACZ,eAAS,YAAY;AACrB,eAAS,YAAY,oBAAI,KAAK;AAAA,IAChC;AACA,UAAM,GAAG,MAAM;AACf,UAAM,oBAAoB,KAAK,QAAQ;AAAA,EACzC;AACF;AAGA,gBAAgB,qBAAqB;AACrC,gBAAgB,qBAAqB;AACrC,gBAAgB,qBAAqB;",
4
+ "sourcesContent": ["import { registerCommand } from '@open-mercato/shared/lib/commands'\nimport type { CommandHandler, CommandRuntimeContext } from '@open-mercato/shared/lib/commands'\nimport { extractUndoPayload, type UndoPayload } from '@open-mercato/shared/lib/commands/undo'\nimport { makeCreateRedo } from '@open-mercato/shared/lib/commands/redo'\nimport { ensureOrganizationScope } from '@open-mercato/shared/lib/commands/scope'\nimport { CrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport type { EntityManager } from '@mikro-orm/core'\nimport { ScheduledJob } from '../data/entities.js'\nimport { calculateNextRunForWrite } from '../lib/nextRunCalculator.js'\nimport { enforceTenantActiveScheduleLimit } from '../lib/activeScheduleLimits.js'\nimport type {\n ScheduleCreateInput,\n ScheduleUpdateInput,\n} from '../data/validators.js'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport type { BullMQSchedulerService } from '../services/bullmqSchedulerService.js'\nimport {\n assertSchedulerQueueTargetAuthorized,\n isSchedulerSafeQueue,\n validateSchedulerTargetPayload,\n} from '../lib/safeQueueTargets.js'\nimport type { SchedulerTargetRbacService } from '../lib/safeQueueTargets.js'\n/**\n * Snapshot of a schedule for undo/redo\n */\ntype ScheduleSnapshot = {\n id: string\n name: string\n description: string | null\n scopeType: 'system' | 'organization' | 'tenant'\n organizationId: string | null\n tenantId: string | null\n scheduleType: 'cron' | 'interval'\n scheduleValue: string\n timezone: string\n targetType: 'queue' | 'command'\n targetQueue: string | null\n targetCommand: string | null\n targetPayload: Record<string, unknown> | null\n requireFeature: string | null\n isEnabled: boolean\n sourceType: 'user' | 'module'\n sourceModule: string | null\n nextRunAt: Date | null\n lastRunAt: Date | null\n}\n\n/**\n * Load a schedule snapshot\n */\nasync function loadScheduleSnapshot(\n em: EntityManager,\n scheduleId: string\n): Promise<ScheduleSnapshot | null> {\n const schedule = await em.findOne(ScheduledJob, { id: scheduleId })\n if (!schedule) return null\n\n return {\n id: schedule.id,\n name: schedule.name,\n description: schedule.description ?? null,\n scopeType: schedule.scopeType,\n organizationId: schedule.organizationId ?? null,\n tenantId: schedule.tenantId ?? null,\n scheduleType: schedule.scheduleType,\n scheduleValue: schedule.scheduleValue,\n timezone: schedule.timezone,\n targetType: schedule.targetType,\n targetQueue: schedule.targetQueue ?? null,\n targetCommand: schedule.targetCommand ?? null,\n targetPayload: schedule.targetPayload ?? null,\n requireFeature: schedule.requireFeature ?? null,\n isEnabled: schedule.isEnabled,\n sourceType: schedule.sourceType,\n sourceModule: schedule.sourceModule ?? null,\n nextRunAt: schedule.nextRunAt ?? null,\n lastRunAt: schedule.lastRunAt ?? null,\n }\n}\n\n/**\n * Snapshots are persisted as JSON (in the action log's command payload), so Date\n * fields come back as ISO strings on undo. Coerce them to Date before writing\n * them onto the entity, otherwise MikroORM throws while flushing a Date column.\n */\nfunction toDate(value: Date | string | null | undefined): Date | null {\n if (!value) return null\n return value instanceof Date ? value : new Date(value)\n}\n\nfunction canonicalJson(value: unknown): string {\n if (value === null || typeof value !== 'object') return JSON.stringify(value ?? null)\n if (Array.isArray(value)) return `[${value.map(canonicalJson).join(',')}]`\n const entries = Object.entries(value as Record<string, unknown>)\n .filter(([, v]) => v !== undefined)\n .sort(([a], [b]) => a.localeCompare(b))\n return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${canonicalJson(v)}`).join(',')}}`\n}\n\nfunction normalizeTargetPayloadValue(value: unknown): unknown {\n // `schedulerService.register()` persists `{}` as-is while the edit form sends\n // `null` for an empty payload \u2014 treat the three empty shapes as equal (#5213).\n if (value !== null && typeof value === 'object' && !Array.isArray(value)\n && Object.keys(value as Record<string, unknown>).length === 0) return null\n return value\n}\n\nfunction targetPayloadChanged(inputValue: unknown, storedValue: unknown): boolean {\n return targetValueChanged(\n normalizeTargetPayloadValue(inputValue),\n normalizeTargetPayloadValue(storedValue),\n )\n}\n\nfunction targetValueChanged(inputValue: unknown, storedValue: unknown): boolean {\n if (inputValue === undefined) return false\n return canonicalJson(inputValue ?? null) !== canonicalJson(storedValue ?? null)\n}\n\ntype QueueTargetAuthorizationContext = CommandRuntimeContext\n\nasync function assertQueueTargetAuthorizedForActor(\n ctx: QueueTargetAuthorizationContext,\n queue: string,\n): Promise<void> {\n const rbacService = (() => {\n try {\n return ctx.container?.resolve<SchedulerTargetRbacService>('rbacService') ?? null\n } catch {\n return null\n }\n })()\n const reason = await assertSchedulerQueueTargetAuthorized({\n queue,\n actorUserId: resolveCommandActorUserId(ctx),\n tenantId: ctx.auth?.tenantId ?? null,\n organizationId: ctx.auth?.orgId ?? null,\n isSuperAdmin: ctx.auth?.isSuperAdmin === true,\n rbacService,\n })\n if (reason) throw new CrudHttpError(403, { error: reason })\n}\n\nasync function assertQueueTargetPayloadAllowed(queue: string, targetPayload: Record<string, unknown> | null | undefined): Promise<void> {\n const reason = validateSchedulerTargetPayload(queue, targetPayload)\n if (reason) throw new CrudHttpError(422, { error: `Invalid target payload for queue ${queue}: ${reason}` })\n}\n\nexport function resolveCommandActorUserId(ctx: CommandRuntimeContext): string | null {\n const auth = ctx.auth\n if (!auth) return null\n if (typeof auth.userId === 'string' && auth.userId.trim().length > 0) return auth.userId.trim()\n if (auth.isApiKey) return null\n return typeof auth.sub === 'string' && auth.sub.trim().length > 0 ? auth.sub.trim() : null\n}\n\n/**\n * Build a full create seed (including the original id and Date-coerced timestamps)\n * from a snapshot. Shared by `materializeScheduleFromSnapshot` (delete-undo) and the\n * create command's id-preserving `redo`.\n */\nfunction scheduleSeedFromSnapshot(snapshot: ScheduleSnapshot): Record<string, unknown> {\n const now = new Date()\n return {\n id: snapshot.id,\n name: snapshot.name,\n description: snapshot.description,\n scopeType: snapshot.scopeType,\n organizationId: snapshot.organizationId,\n tenantId: snapshot.tenantId,\n scheduleType: snapshot.scheduleType,\n scheduleValue: snapshot.scheduleValue,\n timezone: snapshot.timezone,\n targetType: snapshot.targetType,\n targetQueue: snapshot.targetQueue,\n targetCommand: snapshot.targetCommand,\n targetPayload: snapshot.targetPayload,\n requireFeature: snapshot.requireFeature,\n isEnabled: snapshot.isEnabled,\n sourceType: snapshot.sourceType,\n sourceModule: snapshot.sourceModule,\n nextRunAt: toDate(snapshot.nextRunAt),\n lastRunAt: toDate(snapshot.lastRunAt),\n deletedAt: null,\n createdAt: now,\n updatedAt: now,\n }\n}\n\n/**\n * Re-create a ScheduledJob entity from a snapshot, preserving its original id.\n * Used by delete-undo when the row was hard-removed rather than soft-deleted.\n */\nfunction materializeScheduleFromSnapshot(em: EntityManager, snapshot: ScheduleSnapshot): ScheduledJob {\n return em.create(ScheduledJob, scheduleSeedFromSnapshot(snapshot) as never)\n}\n\n/**\n * Trigger BullMQ sync after undo operations.\n * Best-effort: if BullMQ service is unavailable (e.g. local strategy), this is a no-op.\n */\nasync function syncBullMQAfterUndo(ctx: CommandRuntimeContext, schedule: ScheduledJob | null): Promise<void> {\n try {\n if (!ctx.container?.resolve) return\n const bullmqService = ctx.container.resolve<BullMQSchedulerService>('bullmqSchedulerService')\n if (!bullmqService) return\n\n if (schedule && schedule.isEnabled && !schedule.deletedAt) {\n await bullmqService.register(schedule, { skipNextRunUpdate: true })\n } else if (schedule) {\n await bullmqService.unregister(schedule.id)\n }\n } catch {\n // Best-effort: BullMQ service may not be registered (local strategy)\n }\n}\n\n/**\n * Ensure tenant/org scope for security\n */\nfunction ensureTenantScope(ctx: CommandRuntimeContext, tenantId: string | null | undefined) {\n if (tenantId && ctx.auth?.tenantId && ctx.auth.tenantId !== tenantId) {\n throw new Error('Tenant mismatch')\n }\n}\n\n// Super-admin status is the immutable `isSuperAdmin` flag derived from\n// RoleAcl/UserAcl at session resolution. Never compare role names to a string\n// like 'superadmin' \u2014 role names are tenant-mutable and trivially spoofable.\nfunction isSuperAdminActor(ctx: CommandRuntimeContext): boolean {\n return ctx.auth?.isSuperAdmin === true\n}\n\n// `ensureTenantScope` is a no-op for system-scoped jobs (tenantId === null), so a\n// `scheduler.jobs.manage` holder could otherwise update/delete a system schedule\n// belonging to the whole deployment. System-scoped jobs MUST be super-admin only,\n// mirroring the create route's system-scope gate.\nfunction ensureCanManageSystemScopedJob(\n ctx: CommandRuntimeContext,\n job: { scopeType?: string | null; tenantId?: string | null },\n): void {\n const isSystemScoped = job.scopeType === 'system' || job.tenantId == null\n if (!isSystemScoped) return\n if (isSuperAdminActor(ctx)) return\n throw new CrudHttpError(403, {\n error: 'System-scoped scheduled jobs can only be managed by a super administrator.',\n })\n}\n\n/**\n * CREATE SCHEDULE COMMAND\n */\nconst createScheduleCommand: CommandHandler<ScheduleCreateInput, { id: string }> = {\n id: 'scheduler.jobs.create',\n\n async execute(input, ctx) {\n ensureTenantScope(ctx, input.tenantId)\n if (input.organizationId) ensureOrganizationScope(ctx, input.organizationId)\n ensureCanManageSystemScopedJob(ctx, { scopeType: input.scopeType, tenantId: input.tenantId })\n\n const em = ctx.container.resolve<EntityManager>('em').fork()\n\n if (input.isEnabled ?? true) {\n await enforceTenantActiveScheduleLimit(em, input.tenantId)\n }\n\n // Calculate next run time\n const nextRunAt = calculateNextRunForWrite(\n input.scheduleType,\n input.scheduleValue,\n input.timezone || 'UTC'\n )\n\n if (!nextRunAt) {\n throw new Error('Failed to calculate next run time')\n }\n\n if (input.targetType === 'queue' && input.targetQueue) {\n await assertQueueTargetAuthorizedForActor(ctx, input.targetQueue)\n await assertQueueTargetPayloadAllowed(input.targetQueue, input.targetPayload)\n }\n\n // Create schedule\n const schedule = em.create(ScheduledJob, {\n name: input.name,\n description: input.description ?? null,\n scopeType: input.scopeType,\n organizationId: input.organizationId ?? null,\n tenantId: input.tenantId ?? null,\n scheduleType: input.scheduleType,\n scheduleValue: input.scheduleValue,\n timezone: input.timezone ?? 'UTC',\n targetType: input.targetType,\n targetQueue: input.targetQueue ?? null,\n targetCommand: input.targetCommand ?? null,\n targetPayload: input.targetPayload ?? null,\n requireFeature: input.requireFeature ?? null,\n isEnabled: input.isEnabled ?? true,\n sourceType: 'user',\n sourceModule: null,\n nextRunAt,\n createdByUserId: resolveCommandActorUserId(ctx),\n createdAt: new Date(),\n updatedAt: new Date(),\n })\n\n em.persist(schedule)\n await em.flush()\n\n return { id: schedule.id }\n },\n\n async captureAfter(_input, result, ctx) {\n const em = ctx.container.resolve<EntityManager>('em')\n return await loadScheduleSnapshot(em, result.id)\n },\n\n async buildLog({ result, ctx, snapshots }) {\n const { translate } = await resolveTranslations()\n const after = snapshots.after as ScheduleSnapshot | undefined\n\n return {\n actionLabel: translate('scheduler.audit.create', 'Create schedule'),\n resourceKind: 'scheduler.job',\n resourceId: result.id,\n tenantId: after?.tenantId || null,\n organizationId: after?.organizationId || null,\n snapshotAfter: after,\n payload: { undo: { after } },\n }\n },\n\n async undo({ logEntry, ctx }) {\n const after = extractUndoPayload<UndoPayload<ScheduleSnapshot>>(logEntry)?.after\n if (!after) return\n\n const em = ctx.container.resolve<EntityManager>('em').fork()\n const schedule = await em.findOne(ScheduledJob, { id: after.id })\n\n if (schedule) {\n await em.remove(schedule).flush()\n await syncBullMQAfterUndo(ctx, schedule)\n }\n },\n\n redo: makeCreateRedo<ScheduledJob, ScheduleSnapshot, ScheduleCreateInput, { id: string }>({\n entityClass: ScheduledJob,\n getSnapshotId: (snapshot) => snapshot.id,\n seedFromSnapshot: scheduleSeedFromSnapshot,\n buildResult: (entity) => ({ id: entity.id }),\n afterRestore: async ({ ctx, entity }) => {\n await syncBullMQAfterUndo(ctx, entity)\n },\n }),\n}\n\n/**\n * UPDATE SCHEDULE COMMAND\n */\nconst updateScheduleCommand: CommandHandler<ScheduleUpdateInput, { ok: boolean }> = {\n id: 'scheduler.jobs.update',\n\n async prepare(input, ctx) {\n const em = ctx.container.resolve<EntityManager>('em')\n const before = await loadScheduleSnapshot(em, input.id)\n return { before }\n },\n\n async execute(input, ctx) {\n const em = ctx.container.resolve<EntityManager>('em').fork()\n\n const schedule = await em.findOne(ScheduledJob, { id: input.id, deletedAt: null })\n if (!schedule) {\n throw new Error('Schedule not found')\n }\n\n ensureTenantScope(ctx, schedule.tenantId)\n if (schedule.organizationId) ensureOrganizationScope(ctx, schedule.organizationId)\n ensureCanManageSystemScopedJob(ctx, schedule)\n\n // Module-authored schedules are trusted infrastructure wiring (#5213): their\n // target and payload are owned by the registering module. Submitting them\n // unchanged is a no-op (the edit form always resends every field) \u2014 only an\n // actual change to provenance-relevant values is rejected.\n const touchesModuleOwnedTarget =\n schedule.sourceType === 'module'\n && (\n targetValueChanged(input.targetType, schedule.targetType)\n || targetValueChanged(input.targetQueue, schedule.targetQueue)\n || targetValueChanged(input.targetCommand, schedule.targetCommand)\n || targetPayloadChanged(input.targetPayload, schedule.targetPayload)\n )\n if (touchesModuleOwnedTarget) {\n const { translate } = await resolveTranslations()\n throw new CrudHttpError(403, {\n error: translate(\n 'scheduler.errors.module_target_immutable',\n 'Module-authored schedules own their target; only operational fields can be updated here.',\n ),\n })\n }\n\n if (input.isEnabled === true && schedule.isEnabled !== true) {\n await enforceTenantActiveScheduleLimit(em, schedule.tenantId)\n }\n\n const effectiveTargetType = input.targetType ?? schedule.targetType\n const effectiveQueue = input.targetQueue ?? schedule.targetQueue\n const queueChanged =\n effectiveTargetType === 'queue'\n && (\n targetValueChanged(input.targetQueue, schedule.targetQueue)\n || targetValueChanged(input.targetType, schedule.targetType)\n || targetPayloadChanged(input.targetPayload, schedule.targetPayload)\n )\n if (effectiveTargetType === 'queue' && effectiveQueue) {\n const retargetedToUnapprovedQueue =\n input.targetQueue !== undefined\n && input.targetQueue !== schedule.targetQueue\n && !isSchedulerSafeQueue(input.targetQueue)\n // A save that leaves a user-authored row ACTIVE on an unapproved queue\n // restores the invariant the update schema used to enforce; disabling the\n // row stays allowed so admins can remediate legacy targets from the UI.\n // (Dispatch-time re-verification remains the backstop either way.)\n const keepsUnapprovedQueueActive =\n effectiveQueue != null\n && !isSchedulerSafeQueue(effectiveQueue)\n && input.isEnabled !== false\n && schedule.isEnabled !== false\n if (\n (retargetedToUnapprovedQueue || keepsUnapprovedQueueActive)\n && schedule.sourceType !== 'module'\n ) {\n const { translate } = await resolveTranslations()\n throw new CrudHttpError(422, {\n error: translate(\n 'scheduler.errors.queue_not_approved',\n 'Target queue is not an approved scheduler target. Only workers that opted into scheduling can be selected.',\n ),\n })\n }\n if (queueChanged) {\n await assertQueueTargetAuthorizedForActor(ctx, effectiveQueue)\n const effectivePayload = input.targetPayload !== undefined\n ? input.targetPayload\n : schedule.targetPayload\n await assertQueueTargetPayloadAllowed(effectiveQueue, effectivePayload)\n }\n }\n\n const scheduleChanged = input.scheduleType !== undefined || input.scheduleValue !== undefined || input.timezone !== undefined\n const reenabling = input.isEnabled === true && schedule.isEnabled !== true\n const nextRunAt = scheduleChanged || reenabling\n ? calculateNextRunForWrite(\n input.scheduleType ?? schedule.scheduleType,\n input.scheduleValue ?? schedule.scheduleValue,\n input.timezone ?? schedule.timezone,\n )\n : null\n\n if (scheduleChanged && !nextRunAt) {\n const { translate } = await resolveTranslations()\n throw new CrudHttpError(422, {\n error: translate('scheduler.error.invalid_schedule_value', 'Invalid schedule value.'),\n })\n }\n\n // Update fields\n if (input.name !== undefined) schedule.name = input.name\n if (input.description !== undefined) schedule.description = input.description ?? null\n if (input.scheduleType !== undefined) schedule.scheduleType = input.scheduleType\n if (input.scheduleValue !== undefined) schedule.scheduleValue = input.scheduleValue\n if (input.timezone !== undefined) schedule.timezone = input.timezone\n if (input.targetPayload !== undefined) schedule.targetPayload = input.targetPayload ?? null\n if (input.requireFeature !== undefined) schedule.requireFeature = input.requireFeature || null\n if (input.isEnabled !== undefined) schedule.isEnabled = input.isEnabled\n \n // Handle target type changes - clear stale values when switching between queue and command\n if (input.targetType !== undefined) {\n schedule.targetType = input.targetType\n \n if (input.targetType === 'queue') {\n // Switching to queue: set new queue and clear command\n if (input.targetQueue !== undefined) schedule.targetQueue = input.targetQueue\n schedule.targetCommand = null\n } else if (input.targetType === 'command') {\n // Switching to command: set new command and clear queue\n if (input.targetCommand !== undefined) schedule.targetCommand = input.targetCommand\n schedule.targetQueue = null\n }\n } else {\n // targetType not changing, but allow updating individual target fields\n if (input.targetQueue !== undefined) schedule.targetQueue = input.targetQueue\n if (input.targetCommand !== undefined) schedule.targetCommand = input.targetCommand\n }\n\n if (nextRunAt) {\n schedule.nextRunAt = nextRunAt\n }\n\n schedule.updatedAt = new Date()\n schedule.updatedByUserId = resolveCommandActorUserId(ctx)\n\n await em.flush()\n\n return { ok: true }\n },\n\n async captureAfter(input, _result, ctx) {\n const em = ctx.container.resolve<EntityManager>('em')\n return await loadScheduleSnapshot(em, input.id)\n },\n\n async buildLog({ input, ctx, snapshots }) {\n const { translate } = await resolveTranslations()\n const before = snapshots.before as ScheduleSnapshot | undefined\n const after = snapshots.after as ScheduleSnapshot | undefined\n\n return {\n actionLabel: translate('scheduler.audit.update', 'Update schedule'),\n resourceKind: 'scheduler.job',\n resourceId: input.id,\n tenantId: after?.tenantId || null,\n organizationId: after?.organizationId || null,\n snapshotBefore: before,\n snapshotAfter: after,\n payload: { undo: { before, after } },\n }\n },\n\n async undo({ logEntry, ctx }) {\n const before = extractUndoPayload<UndoPayload<ScheduleSnapshot>>(logEntry)?.before\n if (!before) return\n\n const em = ctx.container.resolve<EntityManager>('em').fork()\n const schedule = await em.findOne(ScheduledJob, { id: before.id })\n\n if (schedule) {\n // Restore all fields\n schedule.name = before.name\n schedule.description = before.description\n schedule.scopeType = before.scopeType\n schedule.organizationId = before.organizationId\n schedule.tenantId = before.tenantId\n schedule.scheduleType = before.scheduleType\n schedule.scheduleValue = before.scheduleValue\n schedule.timezone = before.timezone\n schedule.targetType = before.targetType\n schedule.targetQueue = before.targetQueue\n schedule.targetCommand = before.targetCommand\n schedule.targetPayload = before.targetPayload\n schedule.requireFeature = before.requireFeature\n schedule.isEnabled = before.isEnabled\n schedule.sourceType = before.sourceType\n schedule.sourceModule = before.sourceModule\n schedule.nextRunAt = toDate(before.nextRunAt)\n schedule.lastRunAt = toDate(before.lastRunAt)\n schedule.updatedAt = new Date()\n\n await em.flush()\n await syncBullMQAfterUndo(ctx, schedule)\n }\n },\n}\n\n/**\n * DELETE SCHEDULE COMMAND\n */\nconst deleteScheduleCommand: CommandHandler<{ id: string }, { ok: boolean }> = {\n id: 'scheduler.jobs.delete',\n\n async prepare(input, ctx) {\n const em = ctx.container.resolve<EntityManager>('em')\n const before = await loadScheduleSnapshot(em, input.id)\n return { before }\n },\n\n async execute(input, ctx) {\n const em = ctx.container.resolve<EntityManager>('em').fork()\n\n const schedule = await em.findOne(ScheduledJob, { id: input.id, deletedAt: null })\n if (!schedule) {\n throw new Error('Schedule not found')\n }\n\n ensureTenantScope(ctx, schedule.tenantId)\n if (schedule.organizationId) ensureOrganizationScope(ctx, schedule.organizationId)\n ensureCanManageSystemScopedJob(ctx, schedule)\n\n // Soft delete\n schedule.deletedAt = new Date()\n schedule.updatedAt = new Date()\n schedule.updatedByUserId = resolveCommandActorUserId(ctx)\n\n await em.flush()\n\n return { ok: true }\n },\n\n async buildLog({ input, ctx, snapshots }) {\n const { translate } = await resolveTranslations()\n const before = snapshots.before as ScheduleSnapshot | undefined\n\n return {\n actionLabel: translate('scheduler.audit.delete', 'Delete schedule'),\n resourceKind: 'scheduler.job',\n resourceId: input.id,\n tenantId: before?.tenantId || null,\n organizationId: before?.organizationId || null,\n snapshotBefore: before,\n payload: { undo: { before } },\n }\n },\n\n async undo({ logEntry, ctx }) {\n const before = extractUndoPayload<UndoPayload<ScheduleSnapshot>>(logEntry)?.before\n if (!before) return\n\n const em = ctx.container.resolve<EntityManager>('em').fork()\n const existing = await em.findOne(ScheduledJob, { id: before.id })\n\n // Soft-deleted rows are restored by clearing `deletedAt`. A hard-removed row\n // (no surviving record) is re-materialized from the snapshot so undo is\n // robust to either deletion strategy \u2014 mirroring the sales reference undo.\n const schedule = existing ?? materializeScheduleFromSnapshot(em, before)\n if (existing) {\n schedule.deletedAt = null\n schedule.updatedAt = new Date()\n }\n await em.flush()\n await syncBullMQAfterUndo(ctx, schedule)\n },\n}\n\n// Register all commands\nregisterCommand(createScheduleCommand)\nregisterCommand(updateScheduleCommand)\nregisterCommand(deleteScheduleCommand)\n"],
5
+ "mappings": "AAAA,SAAS,uBAAuB;AAEhC,SAAS,0BAA4C;AACrD,SAAS,sBAAsB;AAC/B,SAAS,+BAA+B;AACxC,SAAS,qBAAqB;AAE9B,SAAS,oBAAoB;AAC7B,SAAS,gCAAgC;AACzC,SAAS,wCAAwC;AAKjD,SAAS,2BAA2B;AAEpC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AA8BP,eAAe,qBACb,IACA,YACkC;AAClC,QAAM,WAAW,MAAM,GAAG,QAAQ,cAAc,EAAE,IAAI,WAAW,CAAC;AAClE,MAAI,CAAC,SAAU,QAAO;AAEpB,SAAO;AAAA,IACP,IAAI,SAAS;AAAA,IACb,MAAM,SAAS;AAAA,IACf,aAAa,SAAS,eAAe;AAAA,IACrC,WAAW,SAAS;AAAA,IACpB,gBAAgB,SAAS,kBAAkB;AAAA,IAC3C,UAAU,SAAS,YAAY;AAAA,IAC/B,cAAc,SAAS;AAAA,IACvB,eAAe,SAAS;AAAA,IACxB,UAAU,SAAS;AAAA,IACnB,YAAY,SAAS;AAAA,IACrB,aAAa,SAAS,eAAe;AAAA,IACrC,eAAe,SAAS,iBAAiB;AAAA,IACzC,eAAe,SAAS,iBAAiB;AAAA,IACzC,gBAAgB,SAAS,kBAAkB;AAAA,IAC3C,WAAW,SAAS;AAAA,IACpB,YAAY,SAAS;AAAA,IACrB,cAAc,SAAS,gBAAgB;AAAA,IACvC,WAAW,SAAS,aAAa;AAAA,IACjC,WAAW,SAAS,aAAa;AAAA,EACnC;AACF;AAOA,SAAS,OAAO,OAAsD;AACpE,MAAI,CAAC,MAAO,QAAO;AACnB,SAAO,i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
6
  "names": []
7
7
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@open-mercato/scheduler",
3
- "version": "0.10.1-develop.8231.1.ae76b1d2c5",
3
+ "version": "0.10.1-develop.8258.1.62a94b74a2",
4
4
  "license": "MIT",
5
5
  "description": "Database-managed scheduled jobs with admin UI",
6
6
  "type": "module",
@@ -59,13 +59,13 @@
59
59
  "./*/*/*/*/*/*.json": "./src/*/*/*/*/*/*.json"
60
60
  },
61
61
  "dependencies": {
62
- "@open-mercato/events": "0.10.1-develop.8231.1.ae76b1d2c5",
63
- "@open-mercato/queue": "0.10.1-develop.8231.1.ae76b1d2c5",
62
+ "@open-mercato/events": "0.10.1-develop.8258.1.62a94b74a2",
63
+ "@open-mercato/queue": "0.10.1-develop.8258.1.62a94b74a2",
64
64
  "cron-parser": "^5.6.2"
65
65
  },
66
66
  "peerDependencies": {
67
67
  "@mikro-orm/core": "^7.0.14",
68
- "@open-mercato/shared": "0.10.1-develop.8231.1.ae76b1d2c5",
68
+ "@open-mercato/shared": "0.10.1-develop.8258.1.62a94b74a2",
69
69
  "bullmq": "^5.0.0 || ^6.0.0",
70
70
  "ioredis": "^5.0.0 || ^6.0.0",
71
71
  "zod": ">=3.23.0"
@@ -79,7 +79,7 @@
79
79
  }
80
80
  },
81
81
  "devDependencies": {
82
- "@open-mercato/shared": "0.10.1-develop.8231.1.ae76b1d2c5",
82
+ "@open-mercato/shared": "0.10.1-develop.8258.1.62a94b74a2",
83
83
  "@types/jest": "^30.0.0",
84
84
  "@types/node": "^26.4.0",
85
85
  "jest": "^30.4.2",
@@ -0,0 +1,67 @@
1
+ import { expect, test } 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 { SCHEDULER_JOBS_PATH, createScheduleJob, deleteScheduleJob } from './helpers/scheduler'
5
+
6
+ const ONE_HOUR_MS = 60 * 60 * 1000
7
+
8
+ async function readRunTimes(
9
+ request: Parameters<typeof getAuthToken>[0],
10
+ token: string,
11
+ id: string,
12
+ ): Promise<{ nextRunAt: number; updatedAt: number }> {
13
+ const response = await apiRequest(
14
+ request,
15
+ 'GET',
16
+ `${SCHEDULER_JOBS_PATH}?id=${encodeURIComponent(id)}&probe=${Date.now()}`,
17
+ { token },
18
+ )
19
+ expect(response.status()).toBe(200)
20
+ const body = await readJsonSafe<{
21
+ items?: Array<{ id: string; nextRunAt: string | null; updatedAt: string | null }>
22
+ }>(response)
23
+ const item = (body?.items ?? []).find((entry) => entry.id === id)
24
+ expect(item?.nextRunAt, 'schedule should expose nextRunAt').toBeTruthy()
25
+ expect(item?.updatedAt, 'schedule should expose updatedAt').toBeTruthy()
26
+ return {
27
+ nextRunAt: new Date(String(item?.nextRunAt)).getTime(),
28
+ updatedAt: new Date(String(item?.updatedAt)).getTime(),
29
+ }
30
+ }
31
+
32
+ /**
33
+ * TC-SCHED-011: enabling a disabled schedule recomputes nextRunAt from its own
34
+ * definition, so a value left over from before it was disabled never makes the
35
+ * local poller treat it as already due.
36
+ */
37
+ test.describe('TC-SCHED-011: enabling a schedule recomputes nextRunAt', () => {
38
+ test('PUT { id, isEnabled: true } moves nextRunAt to one interval after the enable', async ({ request }) => {
39
+ const token = await getAuthToken(request, 'admin')
40
+ let scheduleId: string | null = null
41
+
42
+ try {
43
+ scheduleId = await createScheduleJob(request, token, { scheduleValue: '1h', isEnabled: true })
44
+ const created = await readRunTimes(request, token, scheduleId)
45
+
46
+ const disableResponse = await apiRequest(request, 'PUT', SCHEDULER_JOBS_PATH, {
47
+ token,
48
+ data: { id: scheduleId, isEnabled: false },
49
+ })
50
+ expect(disableResponse.status()).toBe(200)
51
+
52
+ await new Promise((resolve) => setTimeout(resolve, 2_000))
53
+
54
+ const enableResponse = await apiRequest(request, 'PUT', SCHEDULER_JOBS_PATH, {
55
+ token,
56
+ data: { id: scheduleId, isEnabled: true },
57
+ })
58
+ expect(enableResponse.status()).toBe(200)
59
+
60
+ const enabled = await readRunTimes(request, token, scheduleId)
61
+ expect(enabled.nextRunAt).toBeGreaterThan(created.nextRunAt)
62
+ expect(Math.abs(enabled.nextRunAt - (enabled.updatedAt + ONE_HOUR_MS))).toBeLessThan(1_000)
63
+ } finally {
64
+ await deleteScheduleJob(request, token, scheduleId)
65
+ }
66
+ })
67
+ })
@@ -0,0 +1,168 @@
1
+ import type { CommandHandler, CommandRuntimeContext } from '@open-mercato/shared/lib/commands'
2
+ import type { ScheduleUpdateInput } from '../../data/validators.js'
3
+
4
+ const registerCommand = jest.fn()
5
+
6
+ jest.mock('@open-mercato/shared/lib/commands', () => ({
7
+ registerCommand,
8
+ }))
9
+
10
+ jest.mock('@open-mercato/shared/lib/i18n/server', () => ({
11
+ resolveTranslations: jest.fn().mockResolvedValue({
12
+ translate: (key: string) => `translated:${key}`,
13
+ }),
14
+ }))
15
+
16
+ const FIFTEEN_MINUTES_MS = 15 * 60 * 1000
17
+ const THIRTY_MINUTES_MS = 30 * 60 * 1000
18
+
19
+ function loadUpdateCommand() {
20
+ let update: CommandHandler<ScheduleUpdateInput, { ok: boolean }> | undefined
21
+ jest.isolateModules(() => {
22
+ require('../jobs')
23
+ update = registerCommand.mock.calls.find(([command]) => command.id === 'scheduler.jobs.update')?.[0]
24
+ })
25
+ if (!update) throw new Error('[internal] scheduler.jobs.update was not registered')
26
+ return update
27
+ }
28
+
29
+ type ScheduleRow = {
30
+ id: string
31
+ tenantId: string
32
+ organizationId: string | null
33
+ scopeType: string
34
+ isEnabled: boolean
35
+ scheduleType: 'cron' | 'interval'
36
+ scheduleValue: string
37
+ timezone: string
38
+ nextRunAt: Date | null
39
+ targetType: string
40
+ targetCommand: string
41
+ sourceType: string
42
+ }
43
+
44
+ function makeSchedule(overrides: Partial<ScheduleRow> = {}): ScheduleRow {
45
+ return {
46
+ id: 'job-1',
47
+ tenantId: 'tenant-a',
48
+ organizationId: null,
49
+ scopeType: 'tenant',
50
+ isEnabled: false,
51
+ scheduleType: 'interval',
52
+ scheduleValue: '15m',
53
+ timezone: 'UTC',
54
+ nextRunAt: new Date(Date.now() - 24 * 60 * 60 * 1000),
55
+ targetType: 'command',
56
+ targetCommand: 'example.todo.cleanup',
57
+ sourceType: 'user',
58
+ ...overrides,
59
+ }
60
+ }
61
+
62
+ function makeEm(schedule: ScheduleRow) {
63
+ return {
64
+ fork: jest.fn().mockReturnThis(),
65
+ findOne: jest.fn().mockResolvedValue(schedule),
66
+ count: jest.fn().mockResolvedValue(0),
67
+ flush: jest.fn().mockResolvedValue(undefined),
68
+ }
69
+ }
70
+
71
+ function makeCtx(em: ReturnType<typeof makeEm>): CommandRuntimeContext {
72
+ return {
73
+ auth: { isSuperAdmin: false, tenantId: 'tenant-a', orgId: 'org-a' },
74
+ container: { resolve: jest.fn(() => em) },
75
+ } as unknown as CommandRuntimeContext
76
+ }
77
+
78
+ describe('scheduler.jobs.update nextRunAt on re-enable', () => {
79
+ beforeEach(() => {
80
+ jest.clearAllMocks()
81
+ jest.resetModules()
82
+ })
83
+
84
+ it('recomputes a stale past nextRunAt from the stored interval when a disabled schedule is enabled', async () => {
85
+ const update = loadUpdateCommand()
86
+ const schedule = makeSchedule()
87
+ const em = makeEm(schedule)
88
+
89
+ const startedAt = Date.now()
90
+ await expect(update.execute({ id: 'job-1', isEnabled: true }, makeCtx(em))).resolves.toEqual({ ok: true })
91
+ const finishedAt = Date.now()
92
+
93
+ expect(schedule.isEnabled).toBe(true)
94
+ const nextRunAt = schedule.nextRunAt?.getTime() ?? 0
95
+ expect(nextRunAt).toBeGreaterThanOrEqual(startedAt + FIFTEEN_MINUTES_MS)
96
+ expect(nextRunAt).toBeLessThanOrEqual(finishedAt + FIFTEEN_MINUTES_MS)
97
+ })
98
+
99
+ it('recomputes nextRunAt from the stored cron expression when a disabled schedule is enabled', async () => {
100
+ const update = loadUpdateCommand()
101
+ const schedule = makeSchedule({ scheduleType: 'cron', scheduleValue: '0 0 * * *' })
102
+ const em = makeEm(schedule)
103
+
104
+ const startedAt = Date.now()
105
+ await update.execute({ id: 'job-1', isEnabled: true }, makeCtx(em))
106
+
107
+ const nextRunAt = schedule.nextRunAt as Date
108
+ expect(nextRunAt.getTime()).toBeGreaterThan(startedAt)
109
+ expect(nextRunAt.getUTCHours()).toBe(0)
110
+ expect(nextRunAt.getUTCMinutes()).toBe(0)
111
+ })
112
+
113
+ it('recomputes nextRunAt in the stored timezone when a disabled cron schedule is enabled', async () => {
114
+ const update = loadUpdateCommand()
115
+ const schedule = makeSchedule({ scheduleType: 'cron', scheduleValue: '0 9 * * *', timezone: 'Europe/Warsaw' })
116
+ const em = makeEm(schedule)
117
+
118
+ const startedAt = Date.now()
119
+ await update.execute({ id: 'job-1', isEnabled: true }, makeCtx(em))
120
+
121
+ const nextRunAt = schedule.nextRunAt as Date
122
+ expect(nextRunAt.getTime()).toBeGreaterThan(startedAt)
123
+ const warsawTime = new Intl.DateTimeFormat('en-GB', {
124
+ timeZone: 'Europe/Warsaw',
125
+ hour: '2-digit',
126
+ minute: '2-digit',
127
+ hourCycle: 'h23',
128
+ }).format(nextRunAt)
129
+ expect(warsawTime).toBe('09:00')
130
+ })
131
+
132
+ it('uses the new schedule value when enabling and changing the interval in one update', async () => {
133
+ const update = loadUpdateCommand()
134
+ const schedule = makeSchedule()
135
+ const em = makeEm(schedule)
136
+
137
+ const startedAt = Date.now()
138
+ await update.execute({ id: 'job-1', isEnabled: true, scheduleValue: '30m' }, makeCtx(em))
139
+ const finishedAt = Date.now()
140
+
141
+ const nextRunAt = schedule.nextRunAt?.getTime() ?? 0
142
+ expect(nextRunAt).toBeGreaterThanOrEqual(startedAt + THIRTY_MINUTES_MS)
143
+ expect(nextRunAt).toBeLessThanOrEqual(finishedAt + THIRTY_MINUTES_MS)
144
+ })
145
+
146
+ it('keeps nextRunAt when an already-enabled schedule is saved with isEnabled true', async () => {
147
+ const update = loadUpdateCommand()
148
+ const pendingRun = new Date(Date.now() + 5 * 60 * 1000)
149
+ const schedule = makeSchedule({ isEnabled: true, nextRunAt: pendingRun })
150
+ const em = makeEm(schedule)
151
+
152
+ await update.execute({ id: 'job-1', isEnabled: true, name: 'Renamed' }, makeCtx(em))
153
+
154
+ expect(schedule.nextRunAt).toBe(pendingRun)
155
+ })
156
+
157
+ it('keeps nextRunAt when a schedule is disabled', async () => {
158
+ const update = loadUpdateCommand()
159
+ const pendingRun = new Date(Date.now() + 5 * 60 * 1000)
160
+ const schedule = makeSchedule({ isEnabled: true, nextRunAt: pendingRun })
161
+ const em = makeEm(schedule)
162
+
163
+ await update.execute({ id: 'job-1', isEnabled: false }, makeCtx(em))
164
+
165
+ expect(schedule.isEnabled).toBe(false)
166
+ expect(schedule.nextRunAt).toBe(pendingRun)
167
+ })
168
+ })
@@ -449,7 +449,8 @@ const updateScheduleCommand: CommandHandler<ScheduleUpdateInput, { ok: boolean }
449
449
  }
450
450
 
451
451
  const scheduleChanged = input.scheduleType !== undefined || input.scheduleValue !== undefined || input.timezone !== undefined
452
- const nextRunAt = scheduleChanged
452
+ const reenabling = input.isEnabled === true && schedule.isEnabled !== true
453
+ const nextRunAt = scheduleChanged || reenabling
453
454
  ? calculateNextRunForWrite(
454
455
  input.scheduleType ?? schedule.scheduleType,
455
456
  input.scheduleValue ?? schedule.scheduleValue,