@open-mercato/scheduler 0.6.7-develop.6774.1.d836fe3135 → 0.6.7-develop.6784.1.f80b9afce5
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.
- package/dist/modules/scheduler/commands/jobs.js +4 -1
- package/dist/modules/scheduler/commands/jobs.js.map +2 -2
- package/dist/modules/scheduler/i18n/de.json +2 -0
- package/dist/modules/scheduler/i18n/en.json +2 -0
- package/dist/modules/scheduler/i18n/es.json +2 -0
- package/dist/modules/scheduler/i18n/pl.json +2 -0
- package/dist/modules/scheduler/lib/activeScheduleLimits.js +16 -1
- package/dist/modules/scheduler/lib/activeScheduleLimits.js.map +2 -2
- package/package.json +5 -5
- package/src/modules/scheduler/commands/__tests__/jobs.active-limit.test.ts +15 -4
- package/src/modules/scheduler/commands/jobs.ts +4 -1
- package/src/modules/scheduler/i18n/de.json +2 -0
- package/src/modules/scheduler/i18n/en.json +2 -0
- package/src/modules/scheduler/i18n/es.json +2 -0
- package/src/modules/scheduler/i18n/pl.json +2 -0
- package/src/modules/scheduler/lib/activeScheduleLimits.ts +17 -1
- package/src/modules/scheduler/services/__tests__/schedulerService.test.ts +16 -2
|
@@ -209,7 +209,10 @@ const updateScheduleCommand = {
|
|
|
209
209
|
input.timezone ?? schedule.timezone
|
|
210
210
|
) : null;
|
|
211
211
|
if (scheduleChanged && !nextRunAt) {
|
|
212
|
-
|
|
212
|
+
const { translate } = await resolveTranslations();
|
|
213
|
+
throw new CrudHttpError(422, {
|
|
214
|
+
error: translate("scheduler.error.invalid_schedule_value", "Invalid schedule value.")
|
|
215
|
+
});
|
|
213
216
|
}
|
|
214
217
|
if (input.name !== void 0) schedule.name = input.name;
|
|
215
218
|
if (input.description !== void 0) schedule.description = input.description ?? null;
|
|
@@ -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'\n\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 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 // 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: input.sourceType ?? 'user',\n sourceModule: input.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 if (input.isEnabled === true && schedule.isEnabled !== true) {\n await enforceTenantActiveScheduleLimit(em, schedule.tenantId)\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 throw new CrudHttpError(422, { error: 'Invalid schedule value.' })\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;AA+BpC,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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AAqB,IAAI,MAAM,EAAE;AACtD,WAAO,EAAE,OAAO;AAAA,EAClB;AAAA,EAEA,MAAM,QAAQ,OAAO,KAAK;AACxB,UAAM,KAAK,IAAI,UAAU,QAAuB,IAAI,EAAE,KAAK;AAE3D,UAAM,WAAW,MAAM,GAAG,QAAQ,cAAc,EAAE,IAAI,MAAM,IAAI,WAAW,KAAK,CAAC;AACjF,QAAI,CAAC,UAAU;AACb,YAAM,IAAI,MAAM,oBAAoB;AAAA,IACtC;AAEA,sBAAkB,KAAK,SAAS,QAAQ;AACxC,QAAI,SAAS,eAAgB,yBAAwB,KAAK,SAAS,cAAc;AACjF,mCAA+B,KAAK,QAAQ;AAE5C,QAAI,MAAM,cAAc,QAAQ,SAAS,cAAc,MAAM;AAC3D,YAAM,iCAAiC,IAAI,SAAS,QAAQ;AAAA,IAC9D;AAEA,UAAM,kBAAkB,MAAM,iBAAiB,UAAa,MAAM,kBAAkB,UAAa,MAAM,aAAa;AACpH,UAAM,YAAY,kBACd;AAAA,MACA,MAAM,gBAAgB,SAAS;AAAA,MAC/B,MAAM,iBAAiB,SAAS;AAAA,MAChC,MAAM,YAAY,SAAS;AAAA,IAC7B,IACE;AAEJ,QAAI,mBAAmB,CAAC,WAAW;AACjC,YAAM,IAAI,cAAc,KAAK,
|
|
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'\n\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 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 // 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: input.sourceType ?? 'user',\n sourceModule: input.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 if (input.isEnabled === true && schedule.isEnabled !== true) {\n await enforceTenantActiveScheduleLimit(em, schedule.tenantId)\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;AA+BpC,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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AAEf,WAAO,EAAE,IAAI,KAAK;AAAA,EACpB;AAAA,EAEA,MAAM,SAAS,EAAE,OAAO,KAAK,UAAU,GAAG;AACxC,UAAM,EAAE,UAAU,IAAI,MAAM,oBAAoB;AAChD,UAAM,SAAS,UAAU;AAEzB,WAAO;AAAA,MACL,aAAa,UAAU,0BAA0B,iBAAiB;AAAA,MAClE,cAAc;AAAA,MACd,YAAY,MAAM;AAAA,MAClB,UAAU,QAAQ,YAAY;AAAA,MAC9B,gBAAgB,QAAQ,kBAAkB;AAAA,MAC1C,gBAAgB;AAAA,MAChB,SAAS,EAAE,MAAM,EAAE,OAAO,EAAE;AAAA,IAC9B;AAAA,EACF;AAAA,EAEA,MAAM,KAAK,EAAE,UAAU,IAAI,GAAG;AAC5B,UAAM,SAAS,mBAAkD,QAAQ,GAAG;AAC5E,QAAI,CAAC,OAAQ;AAEb,UAAM,KAAK,IAAI,UAAU,QAAuB,IAAI,EAAE,KAAK;AAC3D,UAAM,WAAW,MAAM,GAAG,QAAQ,cAAc,EAAE,IAAI,OAAO,GAAG,CAAC;AAKjE,UAAM,WAAW,YAAY,gCAAgC,IAAI,MAAM;AACvE,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;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -26,6 +26,7 @@
|
|
|
26
26
|
"scheduler.details.triggering": "Wird ausgeführt...",
|
|
27
27
|
"scheduler.edit.title": "Zeitplan bearbeiten",
|
|
28
28
|
"scheduler.error.access_denied": "Zugriff verweigert",
|
|
29
|
+
"scheduler.error.active_schedule_limit": "Das Limit aktiver geplanter Aufgaben für diesen Mandanten wurde erreicht ({max}).",
|
|
29
30
|
"scheduler.error.async_strategy_hint": "Bitte setzen Sie QUEUE_STRATEGY=async, um den Ausführungsverlauf einzusehen",
|
|
30
31
|
"scheduler.error.async_strategy_required": "Ausführungsverlauf erfordert QUEUE_STRATEGY=async",
|
|
31
32
|
"scheduler.error.bullmq_required": "BullMQ-Job-Logs sind nur mit QUEUE_STRATEGY=async verfügbar",
|
|
@@ -36,6 +37,7 @@
|
|
|
36
37
|
"scheduler.error.forbidden": "Verboten",
|
|
37
38
|
"scheduler.error.invalidPayload": "Ungültiges JSON-Payload",
|
|
38
39
|
"scheduler.error.invalid_queue_name": "Ungültiger Queue-Name",
|
|
40
|
+
"scheduler.error.invalid_schedule_value": "Ungültiger Zeitplanwert.",
|
|
39
41
|
"scheduler.error.job_not_found": "Job in BullMQ nicht gefunden (möglicherweise entfernt)",
|
|
40
42
|
"scheduler.error.load_failed": "Fehler beim Laden des Zeitplans",
|
|
41
43
|
"scheduler.error.not_found": "Zeitplan nicht gefunden",
|
|
@@ -26,6 +26,7 @@
|
|
|
26
26
|
"scheduler.details.triggering": "Triggering...",
|
|
27
27
|
"scheduler.edit.title": "Edit Schedule",
|
|
28
28
|
"scheduler.error.access_denied": "Access denied",
|
|
29
|
+
"scheduler.error.active_schedule_limit": "Active scheduled job limit reached for this tenant ({max}).",
|
|
29
30
|
"scheduler.error.async_strategy_hint": "Please set QUEUE_STRATEGY=async to view execution history",
|
|
30
31
|
"scheduler.error.async_strategy_required": "Execution history requires QUEUE_STRATEGY=async",
|
|
31
32
|
"scheduler.error.bullmq_required": "BullMQ job logs are only available with QUEUE_STRATEGY=async",
|
|
@@ -36,6 +37,7 @@
|
|
|
36
37
|
"scheduler.error.forbidden": "Forbidden",
|
|
37
38
|
"scheduler.error.invalidPayload": "Invalid JSON payload",
|
|
38
39
|
"scheduler.error.invalid_queue_name": "Invalid queue name",
|
|
40
|
+
"scheduler.error.invalid_schedule_value": "Invalid schedule value.",
|
|
39
41
|
"scheduler.error.job_not_found": "Job not found in BullMQ (may have been removed)",
|
|
40
42
|
"scheduler.error.load_failed": "Failed to load schedule",
|
|
41
43
|
"scheduler.error.not_found": "Schedule not found",
|
|
@@ -26,6 +26,7 @@
|
|
|
26
26
|
"scheduler.details.triggering": "Ejecutando...",
|
|
27
27
|
"scheduler.edit.title": "Editar programación",
|
|
28
28
|
"scheduler.error.access_denied": "Acceso denegado",
|
|
29
|
+
"scheduler.error.active_schedule_limit": "Se alcanzó el límite de tareas programadas activas para este inquilino ({max}).",
|
|
29
30
|
"scheduler.error.async_strategy_hint": "Configure QUEUE_STRATEGY=async para ver el historial de ejecución",
|
|
30
31
|
"scheduler.error.async_strategy_required": "El historial de ejecución requiere QUEUE_STRATEGY=async",
|
|
31
32
|
"scheduler.error.bullmq_required": "Los registros de trabajos de BullMQ solo están disponibles con QUEUE_STRATEGY=async",
|
|
@@ -36,6 +37,7 @@
|
|
|
36
37
|
"scheduler.error.forbidden": "Prohibido",
|
|
37
38
|
"scheduler.error.invalidPayload": "Carga JSON no válida",
|
|
38
39
|
"scheduler.error.invalid_queue_name": "Nombre de cola inválido",
|
|
40
|
+
"scheduler.error.invalid_schedule_value": "Valor de programación no válido.",
|
|
39
41
|
"scheduler.error.job_not_found": "Trabajo no encontrado en BullMQ (puede haber sido eliminado)",
|
|
40
42
|
"scheduler.error.load_failed": "Error al cargar la programación",
|
|
41
43
|
"scheduler.error.not_found": "Programación no encontrada",
|
|
@@ -26,6 +26,7 @@
|
|
|
26
26
|
"scheduler.details.triggering": "Uruchamianie...",
|
|
27
27
|
"scheduler.edit.title": "Edytuj harmonogram",
|
|
28
28
|
"scheduler.error.access_denied": "Odmowa dostępu",
|
|
29
|
+
"scheduler.error.active_schedule_limit": "Osiągnięto limit aktywnych zaplanowanych zadań dla tego najemcy ({max}).",
|
|
29
30
|
"scheduler.error.async_strategy_hint": "Ustaw QUEUE_STRATEGY=async, aby wyświetlić historię wykonań",
|
|
30
31
|
"scheduler.error.async_strategy_required": "Historia wykonań wymaga QUEUE_STRATEGY=async",
|
|
31
32
|
"scheduler.error.bullmq_required": "Logi zadań BullMQ są dostępne tylko z QUEUE_STRATEGY=async",
|
|
@@ -36,6 +37,7 @@
|
|
|
36
37
|
"scheduler.error.forbidden": "Zabronione",
|
|
37
38
|
"scheduler.error.invalidPayload": "Nieprawidłowy ładunek JSON",
|
|
38
39
|
"scheduler.error.invalid_queue_name": "Nieprawidłowa nazwa kolejki",
|
|
40
|
+
"scheduler.error.invalid_schedule_value": "Nieprawidłowa wartość harmonogramu.",
|
|
39
41
|
"scheduler.error.job_not_found": "Zadanie nie zostało znalezione w BullMQ (mogło zostać usunięte)",
|
|
40
42
|
"scheduler.error.load_failed": "Nie udało się załadować harmonogramu",
|
|
41
43
|
"scheduler.error.not_found": "Harmonogram nie znaleziony",
|
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
import { CrudHttpError } from "@open-mercato/shared/lib/crud/errors";
|
|
2
|
+
import { resolveTranslations } from "@open-mercato/shared/lib/i18n/server";
|
|
3
|
+
import { createFallbackTranslator } from "@open-mercato/shared/lib/i18n/translate";
|
|
2
4
|
import { ScheduledJob } from "../data/entities.js";
|
|
3
5
|
const DEFAULT_MAX_ACTIVE_SCHEDULES_PER_TENANT = 100;
|
|
4
6
|
const ACTIVE_SCHEDULE_LIMIT_ENV = "OM_SCHEDULER_MAX_ACTIVE_SCHEDULES_PER_TENANT";
|
|
@@ -7,6 +9,14 @@ function getMaxActiveSchedulesPerTenant() {
|
|
|
7
9
|
if (Number.isFinite(parsed) && parsed > 0) return parsed;
|
|
8
10
|
return DEFAULT_MAX_ACTIVE_SCHEDULES_PER_TENANT;
|
|
9
11
|
}
|
|
12
|
+
async function resolveActiveScheduleLimitTranslator() {
|
|
13
|
+
try {
|
|
14
|
+
const { translate } = await resolveTranslations();
|
|
15
|
+
return translate;
|
|
16
|
+
} catch {
|
|
17
|
+
return createFallbackTranslator({});
|
|
18
|
+
}
|
|
19
|
+
}
|
|
10
20
|
async function enforceTenantActiveScheduleLimit(em, tenantId) {
|
|
11
21
|
if (!tenantId) return;
|
|
12
22
|
const maxActiveSchedules = getMaxActiveSchedulesPerTenant();
|
|
@@ -16,8 +26,13 @@ async function enforceTenantActiveScheduleLimit(em, tenantId) {
|
|
|
16
26
|
deletedAt: null
|
|
17
27
|
});
|
|
18
28
|
if (activeScheduleCount >= maxActiveSchedules) {
|
|
29
|
+
const translate = await resolveActiveScheduleLimitTranslator();
|
|
19
30
|
throw new CrudHttpError(422, {
|
|
20
|
-
error:
|
|
31
|
+
error: translate(
|
|
32
|
+
"scheduler.error.active_schedule_limit",
|
|
33
|
+
"Active scheduled job limit reached for this tenant ({max}).",
|
|
34
|
+
{ max: maxActiveSchedules }
|
|
35
|
+
)
|
|
21
36
|
});
|
|
22
37
|
}
|
|
23
38
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/modules/scheduler/lib/activeScheduleLimits.ts"],
|
|
4
|
-
"sourcesContent": ["import type { EntityManager } from '@mikro-orm/core'\nimport { CrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport { ScheduledJob } from '../data/entities.js'\n\nexport const DEFAULT_MAX_ACTIVE_SCHEDULES_PER_TENANT = 100\nconst ACTIVE_SCHEDULE_LIMIT_ENV = 'OM_SCHEDULER_MAX_ACTIVE_SCHEDULES_PER_TENANT'\n\nexport function getMaxActiveSchedulesPerTenant(): number {\n const parsed = Number.parseInt(process.env[ACTIVE_SCHEDULE_LIMIT_ENV] ?? '', 10)\n if (Number.isFinite(parsed) && parsed > 0) return parsed\n return DEFAULT_MAX_ACTIVE_SCHEDULES_PER_TENANT\n}\n\nexport async function enforceTenantActiveScheduleLimit(\n em: EntityManager,\n tenantId: string | null | undefined,\n): Promise<void> {\n if (!tenantId) return\n\n const maxActiveSchedules = getMaxActiveSchedulesPerTenant()\n const activeScheduleCount = await em.count(ScheduledJob, {\n tenantId,\n isEnabled: true,\n deletedAt: null,\n })\n\n if (activeScheduleCount >= maxActiveSchedules) {\n throw new CrudHttpError(422, {\n error:
|
|
5
|
-
"mappings": "AACA,SAAS,qBAAqB;AAC9B,SAAS,oBAAoB;AAEtB,MAAM,0CAA0C;AACvD,MAAM,4BAA4B;AAE3B,SAAS,iCAAyC;AACvD,QAAM,SAAS,OAAO,SAAS,QAAQ,IAAI,yBAAyB,KAAK,IAAI,EAAE;AAC/E,MAAI,OAAO,SAAS,MAAM,KAAK,SAAS,EAAG,QAAO;AAClD,SAAO;AACT;AAEA,eAAsB,iCACpB,IACA,UACe;AACf,MAAI,CAAC,SAAU;AAEf,QAAM,qBAAqB,+BAA+B;AAC1D,QAAM,sBAAsB,MAAM,GAAG,MAAM,cAAc;AAAA,IACvD;AAAA,IACA,WAAW;AAAA,IACX,WAAW;AAAA,EACb,CAAC;AAED,MAAI,uBAAuB,oBAAoB;AAC7C,UAAM,IAAI,cAAc,KAAK;AAAA,MAC3B,OAAO,
|
|
4
|
+
"sourcesContent": ["import type { EntityManager } from '@mikro-orm/core'\nimport { CrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport { createFallbackTranslator, type TranslateWithFallbackFn } from '@open-mercato/shared/lib/i18n/translate'\nimport { ScheduledJob } from '../data/entities.js'\n\nexport const DEFAULT_MAX_ACTIVE_SCHEDULES_PER_TENANT = 100\nconst ACTIVE_SCHEDULE_LIMIT_ENV = 'OM_SCHEDULER_MAX_ACTIVE_SCHEDULES_PER_TENANT'\n\nexport function getMaxActiveSchedulesPerTenant(): number {\n const parsed = Number.parseInt(process.env[ACTIVE_SCHEDULE_LIMIT_ENV] ?? '', 10)\n if (Number.isFinite(parsed) && parsed > 0) return parsed\n return DEFAULT_MAX_ACTIVE_SCHEDULES_PER_TENANT\n}\n\nasync function resolveActiveScheduleLimitTranslator(): Promise<TranslateWithFallbackFn> {\n try {\n const { translate } = await resolveTranslations()\n return translate\n } catch {\n return createFallbackTranslator({})\n }\n}\n\nexport async function enforceTenantActiveScheduleLimit(\n em: EntityManager,\n tenantId: string | null | undefined,\n): Promise<void> {\n if (!tenantId) return\n\n const maxActiveSchedules = getMaxActiveSchedulesPerTenant()\n const activeScheduleCount = await em.count(ScheduledJob, {\n tenantId,\n isEnabled: true,\n deletedAt: null,\n })\n\n if (activeScheduleCount >= maxActiveSchedules) {\n const translate = await resolveActiveScheduleLimitTranslator()\n throw new CrudHttpError(422, {\n error: translate(\n 'scheduler.error.active_schedule_limit',\n 'Active scheduled job limit reached for this tenant ({max}).',\n { max: maxActiveSchedules },\n ),\n })\n }\n}\n"],
|
|
5
|
+
"mappings": "AACA,SAAS,qBAAqB;AAC9B,SAAS,2BAA2B;AACpC,SAAS,gCAA8D;AACvE,SAAS,oBAAoB;AAEtB,MAAM,0CAA0C;AACvD,MAAM,4BAA4B;AAE3B,SAAS,iCAAyC;AACvD,QAAM,SAAS,OAAO,SAAS,QAAQ,IAAI,yBAAyB,KAAK,IAAI,EAAE;AAC/E,MAAI,OAAO,SAAS,MAAM,KAAK,SAAS,EAAG,QAAO;AAClD,SAAO;AACT;AAEA,eAAe,uCAAyE;AACtF,MAAI;AACF,UAAM,EAAE,UAAU,IAAI,MAAM,oBAAoB;AAChD,WAAO;AAAA,EACT,QAAQ;AACN,WAAO,yBAAyB,CAAC,CAAC;AAAA,EACpC;AACF;AAEA,eAAsB,iCACpB,IACA,UACe;AACf,MAAI,CAAC,SAAU;AAEf,QAAM,qBAAqB,+BAA+B;AAC1D,QAAM,sBAAsB,MAAM,GAAG,MAAM,cAAc;AAAA,IACvD;AAAA,IACA,WAAW;AAAA,IACX,WAAW;AAAA,EACb,CAAC;AAED,MAAI,uBAAuB,oBAAoB;AAC7C,UAAM,YAAY,MAAM,qCAAqC;AAC7D,UAAM,IAAI,cAAc,KAAK;AAAA,MAC3B,OAAO;AAAA,QACL;AAAA,QACA;AAAA,QACA,EAAE,KAAK,mBAAmB;AAAA,MAC5B;AAAA,IACF,CAAC;AAAA,EACH;AACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@open-mercato/scheduler",
|
|
3
|
-
"version": "0.6.7-develop.
|
|
3
|
+
"version": "0.6.7-develop.6784.1.f80b9afce5",
|
|
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.6.7-develop.
|
|
63
|
-
"@open-mercato/queue": "0.6.7-develop.
|
|
62
|
+
"@open-mercato/events": "0.6.7-develop.6784.1.f80b9afce5",
|
|
63
|
+
"@open-mercato/queue": "0.6.7-develop.6784.1.f80b9afce5",
|
|
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.6.7-develop.
|
|
68
|
+
"@open-mercato/shared": "0.6.7-develop.6784.1.f80b9afce5",
|
|
69
69
|
"bullmq": "^5.0.0",
|
|
70
70
|
"ioredis": "^5.0.0",
|
|
71
71
|
"zod": ">=3.23.0"
|
|
@@ -79,7 +79,7 @@
|
|
|
79
79
|
}
|
|
80
80
|
},
|
|
81
81
|
"devDependencies": {
|
|
82
|
-
"@open-mercato/shared": "0.6.7-develop.
|
|
82
|
+
"@open-mercato/shared": "0.6.7-develop.6784.1.f80b9afce5",
|
|
83
83
|
"@types/jest": "^30.0.0",
|
|
84
84
|
"@types/node": "^26.0.1",
|
|
85
85
|
"jest": "^30.4.2",
|
|
@@ -9,7 +9,9 @@ jest.mock('@open-mercato/shared/lib/commands', () => ({
|
|
|
9
9
|
|
|
10
10
|
jest.mock('@open-mercato/shared/lib/i18n/server', () => ({
|
|
11
11
|
resolveTranslations: jest.fn().mockResolvedValue({
|
|
12
|
-
translate: (
|
|
12
|
+
translate: (key: string, _fallback?: string, params?: Record<string, unknown>) => (
|
|
13
|
+
params?.max === undefined ? `translated:${key}` : `translated:${key}:max=${params.max}`
|
|
14
|
+
),
|
|
13
15
|
}),
|
|
14
16
|
}))
|
|
15
17
|
|
|
@@ -76,7 +78,10 @@ describe('scheduler.jobs active schedule tenant limit', () => {
|
|
|
76
78
|
const em = makeEm(null)
|
|
77
79
|
em.count.mockResolvedValue(2)
|
|
78
80
|
|
|
79
|
-
await expect(create.execute(createInput(), makeCtx(em))).rejects.toMatchObject({
|
|
81
|
+
await expect(create.execute(createInput(), makeCtx(em))).rejects.toMatchObject({
|
|
82
|
+
status: 422,
|
|
83
|
+
body: { error: 'translated:scheduler.error.active_schedule_limit:max=2' },
|
|
84
|
+
})
|
|
80
85
|
|
|
81
86
|
expect(em.count).toHaveBeenCalledWith(expect.any(Function), {
|
|
82
87
|
tenantId: 'tenant-a',
|
|
@@ -115,7 +120,10 @@ describe('scheduler.jobs active schedule tenant limit', () => {
|
|
|
115
120
|
const em = makeEm(schedule)
|
|
116
121
|
em.count.mockResolvedValue(2)
|
|
117
122
|
|
|
118
|
-
await expect(update.execute({ id: 'job-1', isEnabled: true }, makeCtx(em))).rejects.toMatchObject({
|
|
123
|
+
await expect(update.execute({ id: 'job-1', isEnabled: true }, makeCtx(em))).rejects.toMatchObject({
|
|
124
|
+
status: 422,
|
|
125
|
+
body: { error: 'translated:scheduler.error.active_schedule_limit:max=2' },
|
|
126
|
+
})
|
|
119
127
|
|
|
120
128
|
expect(em.count).toHaveBeenCalledWith(expect.any(Function), {
|
|
121
129
|
tenantId: 'tenant-a',
|
|
@@ -164,7 +172,10 @@ describe('scheduler.jobs active schedule tenant limit', () => {
|
|
|
164
172
|
|
|
165
173
|
await expect(
|
|
166
174
|
update.execute({ id: 'job-1', scheduleType: 'interval', scheduleValue: '1s' }, makeCtx(em)),
|
|
167
|
-
).rejects.toMatchObject({
|
|
175
|
+
).rejects.toMatchObject({
|
|
176
|
+
status: 422,
|
|
177
|
+
body: { error: 'translated:scheduler.error.invalid_schedule_value' },
|
|
178
|
+
})
|
|
168
179
|
|
|
169
180
|
expect(schedule.scheduleValue).toBe('15m')
|
|
170
181
|
expect(schedule.nextRunAt).toEqual(new Date('2026-01-01T00:15:00.000Z'))
|
|
@@ -324,7 +324,10 @@ const updateScheduleCommand: CommandHandler<ScheduleUpdateInput, { ok: boolean }
|
|
|
324
324
|
: null
|
|
325
325
|
|
|
326
326
|
if (scheduleChanged && !nextRunAt) {
|
|
327
|
-
|
|
327
|
+
const { translate } = await resolveTranslations()
|
|
328
|
+
throw new CrudHttpError(422, {
|
|
329
|
+
error: translate('scheduler.error.invalid_schedule_value', 'Invalid schedule value.'),
|
|
330
|
+
})
|
|
328
331
|
}
|
|
329
332
|
|
|
330
333
|
// Update fields
|
|
@@ -26,6 +26,7 @@
|
|
|
26
26
|
"scheduler.details.triggering": "Wird ausgeführt...",
|
|
27
27
|
"scheduler.edit.title": "Zeitplan bearbeiten",
|
|
28
28
|
"scheduler.error.access_denied": "Zugriff verweigert",
|
|
29
|
+
"scheduler.error.active_schedule_limit": "Das Limit aktiver geplanter Aufgaben für diesen Mandanten wurde erreicht ({max}).",
|
|
29
30
|
"scheduler.error.async_strategy_hint": "Bitte setzen Sie QUEUE_STRATEGY=async, um den Ausführungsverlauf einzusehen",
|
|
30
31
|
"scheduler.error.async_strategy_required": "Ausführungsverlauf erfordert QUEUE_STRATEGY=async",
|
|
31
32
|
"scheduler.error.bullmq_required": "BullMQ-Job-Logs sind nur mit QUEUE_STRATEGY=async verfügbar",
|
|
@@ -36,6 +37,7 @@
|
|
|
36
37
|
"scheduler.error.forbidden": "Verboten",
|
|
37
38
|
"scheduler.error.invalidPayload": "Ungültiges JSON-Payload",
|
|
38
39
|
"scheduler.error.invalid_queue_name": "Ungültiger Queue-Name",
|
|
40
|
+
"scheduler.error.invalid_schedule_value": "Ungültiger Zeitplanwert.",
|
|
39
41
|
"scheduler.error.job_not_found": "Job in BullMQ nicht gefunden (möglicherweise entfernt)",
|
|
40
42
|
"scheduler.error.load_failed": "Fehler beim Laden des Zeitplans",
|
|
41
43
|
"scheduler.error.not_found": "Zeitplan nicht gefunden",
|
|
@@ -26,6 +26,7 @@
|
|
|
26
26
|
"scheduler.details.triggering": "Triggering...",
|
|
27
27
|
"scheduler.edit.title": "Edit Schedule",
|
|
28
28
|
"scheduler.error.access_denied": "Access denied",
|
|
29
|
+
"scheduler.error.active_schedule_limit": "Active scheduled job limit reached for this tenant ({max}).",
|
|
29
30
|
"scheduler.error.async_strategy_hint": "Please set QUEUE_STRATEGY=async to view execution history",
|
|
30
31
|
"scheduler.error.async_strategy_required": "Execution history requires QUEUE_STRATEGY=async",
|
|
31
32
|
"scheduler.error.bullmq_required": "BullMQ job logs are only available with QUEUE_STRATEGY=async",
|
|
@@ -36,6 +37,7 @@
|
|
|
36
37
|
"scheduler.error.forbidden": "Forbidden",
|
|
37
38
|
"scheduler.error.invalidPayload": "Invalid JSON payload",
|
|
38
39
|
"scheduler.error.invalid_queue_name": "Invalid queue name",
|
|
40
|
+
"scheduler.error.invalid_schedule_value": "Invalid schedule value.",
|
|
39
41
|
"scheduler.error.job_not_found": "Job not found in BullMQ (may have been removed)",
|
|
40
42
|
"scheduler.error.load_failed": "Failed to load schedule",
|
|
41
43
|
"scheduler.error.not_found": "Schedule not found",
|
|
@@ -26,6 +26,7 @@
|
|
|
26
26
|
"scheduler.details.triggering": "Ejecutando...",
|
|
27
27
|
"scheduler.edit.title": "Editar programación",
|
|
28
28
|
"scheduler.error.access_denied": "Acceso denegado",
|
|
29
|
+
"scheduler.error.active_schedule_limit": "Se alcanzó el límite de tareas programadas activas para este inquilino ({max}).",
|
|
29
30
|
"scheduler.error.async_strategy_hint": "Configure QUEUE_STRATEGY=async para ver el historial de ejecución",
|
|
30
31
|
"scheduler.error.async_strategy_required": "El historial de ejecución requiere QUEUE_STRATEGY=async",
|
|
31
32
|
"scheduler.error.bullmq_required": "Los registros de trabajos de BullMQ solo están disponibles con QUEUE_STRATEGY=async",
|
|
@@ -36,6 +37,7 @@
|
|
|
36
37
|
"scheduler.error.forbidden": "Prohibido",
|
|
37
38
|
"scheduler.error.invalidPayload": "Carga JSON no válida",
|
|
38
39
|
"scheduler.error.invalid_queue_name": "Nombre de cola inválido",
|
|
40
|
+
"scheduler.error.invalid_schedule_value": "Valor de programación no válido.",
|
|
39
41
|
"scheduler.error.job_not_found": "Trabajo no encontrado en BullMQ (puede haber sido eliminado)",
|
|
40
42
|
"scheduler.error.load_failed": "Error al cargar la programación",
|
|
41
43
|
"scheduler.error.not_found": "Programación no encontrada",
|
|
@@ -26,6 +26,7 @@
|
|
|
26
26
|
"scheduler.details.triggering": "Uruchamianie...",
|
|
27
27
|
"scheduler.edit.title": "Edytuj harmonogram",
|
|
28
28
|
"scheduler.error.access_denied": "Odmowa dostępu",
|
|
29
|
+
"scheduler.error.active_schedule_limit": "Osiągnięto limit aktywnych zaplanowanych zadań dla tego najemcy ({max}).",
|
|
29
30
|
"scheduler.error.async_strategy_hint": "Ustaw QUEUE_STRATEGY=async, aby wyświetlić historię wykonań",
|
|
30
31
|
"scheduler.error.async_strategy_required": "Historia wykonań wymaga QUEUE_STRATEGY=async",
|
|
31
32
|
"scheduler.error.bullmq_required": "Logi zadań BullMQ są dostępne tylko z QUEUE_STRATEGY=async",
|
|
@@ -36,6 +37,7 @@
|
|
|
36
37
|
"scheduler.error.forbidden": "Zabronione",
|
|
37
38
|
"scheduler.error.invalidPayload": "Nieprawidłowy ładunek JSON",
|
|
38
39
|
"scheduler.error.invalid_queue_name": "Nieprawidłowa nazwa kolejki",
|
|
40
|
+
"scheduler.error.invalid_schedule_value": "Nieprawidłowa wartość harmonogramu.",
|
|
39
41
|
"scheduler.error.job_not_found": "Zadanie nie zostało znalezione w BullMQ (mogło zostać usunięte)",
|
|
40
42
|
"scheduler.error.load_failed": "Nie udało się załadować harmonogramu",
|
|
41
43
|
"scheduler.error.not_found": "Harmonogram nie znaleziony",
|
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import type { EntityManager } from '@mikro-orm/core'
|
|
2
2
|
import { CrudHttpError } from '@open-mercato/shared/lib/crud/errors'
|
|
3
|
+
import { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'
|
|
4
|
+
import { createFallbackTranslator, type TranslateWithFallbackFn } from '@open-mercato/shared/lib/i18n/translate'
|
|
3
5
|
import { ScheduledJob } from '../data/entities.js'
|
|
4
6
|
|
|
5
7
|
export const DEFAULT_MAX_ACTIVE_SCHEDULES_PER_TENANT = 100
|
|
@@ -11,6 +13,15 @@ export function getMaxActiveSchedulesPerTenant(): number {
|
|
|
11
13
|
return DEFAULT_MAX_ACTIVE_SCHEDULES_PER_TENANT
|
|
12
14
|
}
|
|
13
15
|
|
|
16
|
+
async function resolveActiveScheduleLimitTranslator(): Promise<TranslateWithFallbackFn> {
|
|
17
|
+
try {
|
|
18
|
+
const { translate } = await resolveTranslations()
|
|
19
|
+
return translate
|
|
20
|
+
} catch {
|
|
21
|
+
return createFallbackTranslator({})
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
|
|
14
25
|
export async function enforceTenantActiveScheduleLimit(
|
|
15
26
|
em: EntityManager,
|
|
16
27
|
tenantId: string | null | undefined,
|
|
@@ -25,8 +36,13 @@ export async function enforceTenantActiveScheduleLimit(
|
|
|
25
36
|
})
|
|
26
37
|
|
|
27
38
|
if (activeScheduleCount >= maxActiveSchedules) {
|
|
39
|
+
const translate = await resolveActiveScheduleLimitTranslator()
|
|
28
40
|
throw new CrudHttpError(422, {
|
|
29
|
-
error:
|
|
41
|
+
error: translate(
|
|
42
|
+
'scheduler.error.active_schedule_limit',
|
|
43
|
+
'Active scheduled job limit reached for this tenant ({max}).',
|
|
44
|
+
{ max: maxActiveSchedules },
|
|
45
|
+
),
|
|
30
46
|
})
|
|
31
47
|
}
|
|
32
48
|
}
|
|
@@ -4,6 +4,14 @@ import { ScheduledJob } from '../../data/entities.js'
|
|
|
4
4
|
import type { BullMQSchedulerService } from '../bullmqSchedulerService'
|
|
5
5
|
import { createLogger } from '@open-mercato/shared/lib/logger'
|
|
6
6
|
|
|
7
|
+
jest.mock('@open-mercato/shared/lib/i18n/server', () => ({
|
|
8
|
+
resolveTranslations: jest.fn().mockResolvedValue({
|
|
9
|
+
translate: (key: string, _fallback?: string, params?: Record<string, unknown>) => (
|
|
10
|
+
params?.max === undefined ? `translated:${key}` : `translated:${key}:max=${params.max}`
|
|
11
|
+
),
|
|
12
|
+
}),
|
|
13
|
+
}))
|
|
14
|
+
|
|
7
15
|
jest.mock('@open-mercato/shared/lib/logger', () => {
|
|
8
16
|
const mocked = {
|
|
9
17
|
debug: jest.fn(),
|
|
@@ -198,7 +206,10 @@ describe('SchedulerService', () => {
|
|
|
198
206
|
tenantId: 'tenant-1',
|
|
199
207
|
scheduleType: 'interval',
|
|
200
208
|
scheduleValue: '15m',
|
|
201
|
-
})).rejects.
|
|
209
|
+
})).rejects.toMatchObject({
|
|
210
|
+
status: 422,
|
|
211
|
+
body: { error: 'translated:scheduler.error.active_schedule_limit:max=2' },
|
|
212
|
+
})
|
|
202
213
|
|
|
203
214
|
expect(mockForkedEm.count).toHaveBeenCalledWith(ScheduledJob, {
|
|
204
215
|
tenantId: 'tenant-1',
|
|
@@ -427,7 +438,10 @@ describe('SchedulerService', () => {
|
|
|
427
438
|
mockForkedEm.findOne.mockResolvedValue(schedule)
|
|
428
439
|
mockForkedEm.count.mockResolvedValue(2)
|
|
429
440
|
|
|
430
|
-
await expect(service.update('test-1', { isEnabled: true })).rejects.
|
|
441
|
+
await expect(service.update('test-1', { isEnabled: true })).rejects.toMatchObject({
|
|
442
|
+
status: 422,
|
|
443
|
+
body: { error: 'translated:scheduler.error.active_schedule_limit:max=2' },
|
|
444
|
+
})
|
|
431
445
|
|
|
432
446
|
expect(mockForkedEm.count).toHaveBeenCalledWith(ScheduledJob, {
|
|
433
447
|
tenantId: 'tenant-1',
|