@open-mercato/scheduler 0.6.4-develop.4371.1.8f3030407e → 0.6.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.turbo/turbo-build.log +1 -1
- package/dist/modules/scheduler/__integration__/TC-SCHED-002.spec.js +49 -0
- package/dist/modules/scheduler/__integration__/TC-SCHED-002.spec.js.map +7 -0
- package/dist/modules/scheduler/__integration__/TC-SCHED-003.spec.js +38 -0
- package/dist/modules/scheduler/__integration__/TC-SCHED-003.spec.js.map +7 -0
- package/dist/modules/scheduler/__integration__/TC-SCHED-004.spec.js +36 -0
- package/dist/modules/scheduler/__integration__/TC-SCHED-004.spec.js.map +7 -0
- package/dist/modules/scheduler/__integration__/TC-SCHED-005.spec.js +41 -0
- package/dist/modules/scheduler/__integration__/TC-SCHED-005.spec.js.map +7 -0
- package/dist/modules/scheduler/__integration__/TC-SCHED-006.spec.js +61 -0
- package/dist/modules/scheduler/__integration__/TC-SCHED-006.spec.js.map +7 -0
- package/dist/modules/scheduler/__integration__/TC-SCHED-007.spec.js +36 -0
- package/dist/modules/scheduler/__integration__/TC-SCHED-007.spec.js.map +7 -0
- package/dist/modules/scheduler/__integration__/TC-SCHED-CRUDFORM-001.spec.js +105 -0
- package/dist/modules/scheduler/__integration__/TC-SCHED-CRUDFORM-001.spec.js.map +7 -0
- package/dist/modules/scheduler/__integration__/TC-UNDO-001-scheduler-jobs.spec.js +124 -0
- package/dist/modules/scheduler/__integration__/TC-UNDO-001-scheduler-jobs.spec.js.map +7 -0
- package/dist/modules/scheduler/__integration__/helpers/scheduler.js +59 -0
- package/dist/modules/scheduler/__integration__/helpers/scheduler.js.map +7 -0
- package/dist/modules/scheduler/backend/config/scheduled-jobs/[id]/edit/page.js +1 -1
- package/dist/modules/scheduler/backend/config/scheduled-jobs/[id]/edit/page.js.map +2 -2
- package/dist/modules/scheduler/backend/config/scheduled-jobs/page.js +10 -1
- package/dist/modules/scheduler/backend/config/scheduled-jobs/page.js.map +2 -2
- package/dist/modules/scheduler/commands/jobs.js +56 -13
- 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/scheduledJobFormConfig.js +8 -1
- package/dist/modules/scheduler/lib/scheduledJobFormConfig.js.map +2 -2
- package/package.json +7 -8
- package/src/modules/scheduler/__integration__/TC-SCHED-002.spec.ts +63 -0
- package/src/modules/scheduler/__integration__/TC-SCHED-003.spec.ts +48 -0
- package/src/modules/scheduler/__integration__/TC-SCHED-004.spec.ts +52 -0
- package/src/modules/scheduler/__integration__/TC-SCHED-005.spec.ts +51 -0
- package/src/modules/scheduler/__integration__/TC-SCHED-006.spec.ts +84 -0
- package/src/modules/scheduler/__integration__/TC-SCHED-007.spec.ts +50 -0
- package/src/modules/scheduler/__integration__/TC-SCHED-CRUDFORM-001.spec.ts +144 -0
- package/src/modules/scheduler/__integration__/TC-UNDO-001-scheduler-jobs.spec.ts +179 -0
- package/src/modules/scheduler/__integration__/helpers/scheduler.ts +110 -0
- package/src/modules/scheduler/backend/config/scheduled-jobs/[id]/edit/page.tsx +1 -1
- package/src/modules/scheduler/backend/config/scheduled-jobs/page.tsx +9 -1
- package/src/modules/scheduler/commands/__tests__/jobs.undo.test.ts +181 -0
- package/src/modules/scheduler/commands/jobs.ts +76 -13
- package/src/modules/scheduler/data/__tests__/validators.test.ts +17 -0
- 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/__tests__/scheduledJobFormConfig.test.ts +24 -0
- package/src/modules/scheduler/lib/scheduledJobFormConfig.tsx +11 -1
|
@@ -85,7 +85,8 @@ function scheduledJobFormSchema(t) {
|
|
|
85
85
|
isEnabled: z.boolean()
|
|
86
86
|
});
|
|
87
87
|
}
|
|
88
|
-
function scheduledJobFields(t, loaders) {
|
|
88
|
+
function scheduledJobFields(t, loaders, options) {
|
|
89
|
+
const lockScope = options?.lockScope ?? false;
|
|
89
90
|
return [
|
|
90
91
|
{
|
|
91
92
|
id: "name",
|
|
@@ -103,6 +104,12 @@ function scheduledJobFields(t, loaders) {
|
|
|
103
104
|
type: "select",
|
|
104
105
|
label: t("scheduler.form.scope_type", "Scope"),
|
|
105
106
|
required: true,
|
|
107
|
+
// Scope is derived from the creator's auth context at create time and is
|
|
108
|
+
// immutable afterwards (the update schema/command never persist it). Lock
|
|
109
|
+
// the field on edit so it does not deceptively accept input that is then
|
|
110
|
+
// silently dropped on save.
|
|
111
|
+
disabled: lockScope,
|
|
112
|
+
description: lockScope ? t("scheduler.form.scope_type.locked_description", "Scope is set when the schedule is created and cannot be changed afterwards.") : void 0,
|
|
106
113
|
options: [
|
|
107
114
|
{ value: "system", label: t("scheduler.scope.system", "System") },
|
|
108
115
|
{ value: "organization", label: t("scheduler.scope.organization", "Organization") },
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/modules/scheduler/lib/scheduledJobFormConfig.tsx"],
|
|
4
|
-
"sourcesContent": ["import * as React from 'react'\nimport { z } from 'zod'\nimport { ComboboxInput, type ComboboxOption } from '@open-mercato/ui/backend/inputs/ComboboxInput'\nimport { Label } from '@open-mercato/ui/primitives/label'\nimport { Switch } from '@open-mercato/ui/primitives/switch'\nimport { JsonBuilder } from '@open-mercato/ui/backend/JsonBuilder'\nimport type { CrudField, CrudFormGroup, CrudCustomFieldRenderProps } from '@open-mercato/ui/backend/CrudForm'\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport type ScheduleFormValues = {\n name: string\n description?: string\n scopeType: 'system' | 'organization' | 'tenant'\n scheduleType: 'cron' | 'interval'\n scheduleValue: string\n timezone?: string\n targetType: 'queue' | 'command'\n targetQueue?: string\n targetCommand?: string\n targetPayload?: Record<string, unknown>\n isEnabled: boolean\n}\n\nexport type TargetOptions = {\n queues: ComboboxOption[]\n commands: ComboboxOption[]\n}\n\n// ---------------------------------------------------------------------------\n// Components\n// ---------------------------------------------------------------------------\n\nexport function PayloadJsonEditor({ value, setValue, disabled }: CrudCustomFieldRenderProps) {\n return (\n <JsonBuilder\n value={value || {}}\n onChange={setValue}\n disabled={disabled}\n />\n )\n}\n\nexport function ScheduledJobEnabledSwitch({\n isEnabled,\n setIsEnabled,\n t,\n}: {\n isEnabled: boolean\n setIsEnabled: (value: boolean) => void\n t: (key: string, fallback: string) => string\n}) {\n return (\n <div className=\"flex items-center gap-2\">\n <Label htmlFor=\"enabled-switch\" className=\"text-sm font-medium cursor-pointer\">\n {isEnabled ? t('scheduler.form.enabled', 'Enabled') : t('scheduler.form.disabled', 'Disabled')}\n </Label>\n <Switch\n id=\"enabled-switch\"\n checked={isEnabled}\n onCheckedChange={setIsEnabled}\n />\n </div>\n )\n}\n\n// ---------------------------------------------------------------------------\n// Option loaders\n// ---------------------------------------------------------------------------\n\nexport function createTargetOptionsLoader(\n apiCallFn: <T>(url: string, init?: RequestInit, options?: Record<string, unknown>) => Promise<{ result: T | null }>\n) {\n const targetOptionsRef = { current: null as TargetOptions | null }\n\n async function loadTargetOptions(): Promise<TargetOptions> {\n if (targetOptionsRef.current) return targetOptionsRef.current\n try {\n const { result } = await apiCallFn<TargetOptions>('/api/scheduler/targets')\n const options = result ?? { queues: [], commands: [] }\n targetOptionsRef.current = options\n return options\n } catch {\n return { queues: [], commands: [] }\n }\n }\n\n async function loadQueueOptions(query?: string): Promise<ComboboxOption[]> {\n const options = await loadTargetOptions()\n if (!query) return options.queues\n const lower = query.toLowerCase()\n return options.queues.filter((q) => q.label.toLowerCase().includes(lower))\n }\n\n async function loadCommandOptions(query?: string): Promise<ComboboxOption[]> {\n const options = await loadTargetOptions()\n if (!query) return options.commands\n const lower = query.toLowerCase()\n return options.commands.filter((c) => c.label.toLowerCase().includes(lower))\n }\n\n return { loadTargetOptions, loadQueueOptions, loadCommandOptions, targetOptionsRef }\n}\n\nexport async function loadTimezoneOptions(query?: string): Promise<ComboboxOption[]> {\n try {\n const allTz = Array.from(new Set(['UTC', ...Intl.supportedValuesOf('timeZone')]))\n const filtered = query\n ? allTz.filter((tz) => tz.toLowerCase().includes(query.toLowerCase()))\n : allTz\n return filtered.slice(0, 100).map((tz) => ({\n value: tz,\n label: tz,\n }))\n } catch {\n return [{ value: 'UTC', label: 'UTC' }]\n }\n}\n\n// ---------------------------------------------------------------------------\n// Schema\n// ---------------------------------------------------------------------------\n\nexport function scheduledJobFormSchema(t: (key: string, fallback: string) => string) {\n return z.object({\n name: z.string().min(1, t('scheduler.form.name.required', 'Name is required')),\n description: z.string().optional(),\n scopeType: z.enum(['system', 'organization', 'tenant']),\n scheduleType: z.enum(['cron', 'interval']),\n scheduleValue: z.string().min(1, t('scheduler.form.schedule.required', 'Schedule is required')),\n timezone: z.string(),\n targetType: z.enum(['queue', 'command']),\n targetQueue: z.string().optional(),\n targetCommand: z.string().optional(),\n targetPayload: z.record(z.string(), z.unknown()).optional(),\n isEnabled: z.boolean(),\n })\n}\n\n// ---------------------------------------------------------------------------\n// Fields\n// ---------------------------------------------------------------------------\n\nexport function scheduledJobFields(\n t: (key: string, fallback: string) => string,\n loaders: {\n loadQueueOptions: (query?: string) => Promise<ComboboxOption[]>\n loadCommandOptions: (query?: string) => Promise<ComboboxOption[]>\n loadTimezoneOptions: (query?: string) => Promise<ComboboxOption[]>\n }\n): CrudField[] {\n return [\n {\n id: 'name',\n type: 'text',\n label: t('scheduler.form.name', 'Name'),\n required: true,\n },\n {\n id: 'description',\n type: 'textarea',\n label: t('scheduler.form.description', 'Description'),\n },\n {\n id: 'scopeType',\n type: 'select',\n label: t('scheduler.form.scope_type', 'Scope'),\n required: true,\n options: [\n { value: 'system', label: t('scheduler.scope.system', 'System') },\n { value: 'organization', label: t('scheduler.scope.organization', 'Organization') },\n { value: 'tenant', label: t('scheduler.scope.tenant', 'Tenant') },\n ],\n },\n {\n id: 'scheduleType',\n type: 'select',\n label: t('scheduler.form.schedule_type', 'Schedule Type'),\n required: true,\n options: [\n { value: 'cron', label: t('scheduler.type.cron', 'Cron Expression') },\n { value: 'interval', label: t('scheduler.type.interval', 'Simple Interval') },\n ],\n },\n {\n id: 'scheduleValue',\n type: 'text',\n label: t('scheduler.form.schedule_value', 'Schedule Value'),\n placeholder: t('scheduler.form.schedule_value.placeholder', 'e.g. 0 */6 * * * or 15m'),\n description: t('scheduler.form.schedule_value.description', 'For cron: use cron expression (e.g., \"0 0 * * *\"). For interval: use format like \"15m\", \"2h\", \"1d\" (s=seconds, m=minutes, h=hours, d=days)'),\n required: true,\n },\n {\n id: 'timezone',\n type: 'combobox',\n label: t('scheduler.form.timezone', 'Timezone'),\n placeholder: t('scheduler.form.timezone.placeholder', 'Search timezone...'),\n required: true,\n loadOptions: loaders.loadTimezoneOptions,\n allowCustomValues: false,\n },\n {\n id: 'targetType',\n type: 'select',\n label: t('scheduler.form.target_type', 'Target Type'),\n required: true,\n options: [\n { value: 'queue', label: t('scheduler.target.queue', 'Queue') },\n { value: 'command', label: t('scheduler.target.command', 'Command') },\n ],\n },\n {\n id: 'targetFields',\n type: 'custom',\n label: '',\n component: ({ values, setFormValue }) => {\n const targetType = values?.targetType as string | undefined\n const targetQueue = (values?.targetQueue as string) || ''\n const targetCommand = (values?.targetCommand as string) || ''\n\n return (\n <div className=\"space-y-4\">\n {targetType === 'queue' && (\n <div className=\"space-y-1\">\n <Label htmlFor=\"targetQueue\">\n {t('scheduler.form.target_queue', 'Target Queue')}\n <span className=\"text-status-error-icon ml-0.5\" aria-hidden=\"true\">*</span>\n </Label>\n <ComboboxInput\n value={targetQueue}\n onChange={(next) => setFormValue && setFormValue('targetQueue', next)}\n placeholder={t('scheduler.form.target_queue.placeholder', 'Search queues...')}\n loadSuggestions={loaders.loadQueueOptions}\n allowCustomValues={true}\n />\n </div>\n )}\n {targetType === 'command' && (\n <div className=\"space-y-1\">\n <Label htmlFor=\"targetCommand\">\n {t('scheduler.form.target_command', 'Target Command')}\n <span className=\"text-status-error-icon ml-0.5\" aria-hidden=\"true\">*</span>\n </Label>\n <ComboboxInput\n value={targetCommand}\n onChange={(next) => setFormValue && setFormValue('targetCommand', next)}\n placeholder={t('scheduler.form.target_command.placeholder', 'Search commands...')}\n loadSuggestions={loaders.loadCommandOptions}\n allowCustomValues={false}\n />\n </div>\n )}\n </div>\n )\n },\n },\n {\n id: 'targetPayload',\n type: 'custom',\n label: t('scheduler.form.target_payload', 'Job Arguments (JSON)'),\n description: t('scheduler.form.target_payload.description', 'Optional JSON payload. Fields tenantId and organizationId are injected automatically at execution time.'),\n component: (props) => <PayloadJsonEditor {...props} />,\n },\n ]\n}\n\n// ---------------------------------------------------------------------------\n// Groups\n// ---------------------------------------------------------------------------\n\nexport function scheduledJobGroups(t: (key: string, fallback: string) => string): CrudFormGroup[] {\n return [\n {\n id: 'basic',\n title: t('scheduler.form.group.basic', 'Basic Information'),\n fields: ['name', 'description', 'scopeType'],\n },\n {\n id: 'schedule',\n title: t('scheduler.form.group.schedule', 'Schedule Configuration'),\n fields: ['scheduleType', 'scheduleValue', 'timezone'],\n },\n {\n id: 'target',\n title: t('scheduler.form.group.target', 'Target Configuration'),\n fields: ['targetType', 'targetFields', 'targetPayload'],\n },\n ]\n}\n\n// ---------------------------------------------------------------------------\n// Payload builder\n// ---------------------------------------------------------------------------\n\nexport function buildScheduledJobPayload(\n values: ScheduleFormValues,\n isEnabled: boolean\n): Record<string, unknown> {\n const targetPayload = values.targetPayload && Object.keys(values.targetPayload).length > 0\n ? values.targetPayload\n : null\n\n return {\n ...values,\n targetPayload,\n isEnabled,\n }\n}\n"],
|
|
5
|
-
"mappings": "AAqCI,cAkBA,YAlBA;AApCJ,SAAS,SAAS;AAClB,SA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EAAE,OAAO,EAAE,OAAO,GAAG,EAAE,QAAQ,CAAC,EAAE,SAAS;AAAA,IAC1D,WAAW,EAAE,QAAQ;AAAA,EACvB,CAAC;AACH;AAMO,SAAS,mBACd,GACA,
|
|
4
|
+
"sourcesContent": ["import * as React from 'react'\nimport { z } from 'zod'\nimport { ComboboxInput, type ComboboxOption } from '@open-mercato/ui/backend/inputs/ComboboxInput'\nimport { Label } from '@open-mercato/ui/primitives/label'\nimport { Switch } from '@open-mercato/ui/primitives/switch'\nimport { JsonBuilder } from '@open-mercato/ui/backend/JsonBuilder'\nimport type { CrudField, CrudFormGroup, CrudCustomFieldRenderProps } from '@open-mercato/ui/backend/CrudForm'\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport type ScheduleFormValues = {\n name: string\n description?: string\n scopeType: 'system' | 'organization' | 'tenant'\n scheduleType: 'cron' | 'interval'\n scheduleValue: string\n timezone?: string\n targetType: 'queue' | 'command'\n targetQueue?: string\n targetCommand?: string\n targetPayload?: Record<string, unknown>\n isEnabled: boolean\n}\n\nexport type TargetOptions = {\n queues: ComboboxOption[]\n commands: ComboboxOption[]\n}\n\n// ---------------------------------------------------------------------------\n// Components\n// ---------------------------------------------------------------------------\n\nexport function PayloadJsonEditor({ value, setValue, disabled }: CrudCustomFieldRenderProps) {\n return (\n <JsonBuilder\n value={value || {}}\n onChange={setValue}\n disabled={disabled}\n />\n )\n}\n\nexport function ScheduledJobEnabledSwitch({\n isEnabled,\n setIsEnabled,\n t,\n}: {\n isEnabled: boolean\n setIsEnabled: (value: boolean) => void\n t: (key: string, fallback: string) => string\n}) {\n return (\n <div className=\"flex items-center gap-2\">\n <Label htmlFor=\"enabled-switch\" className=\"text-sm font-medium cursor-pointer\">\n {isEnabled ? t('scheduler.form.enabled', 'Enabled') : t('scheduler.form.disabled', 'Disabled')}\n </Label>\n <Switch\n id=\"enabled-switch\"\n checked={isEnabled}\n onCheckedChange={setIsEnabled}\n />\n </div>\n )\n}\n\n// ---------------------------------------------------------------------------\n// Option loaders\n// ---------------------------------------------------------------------------\n\nexport function createTargetOptionsLoader(\n apiCallFn: <T>(url: string, init?: RequestInit, options?: Record<string, unknown>) => Promise<{ result: T | null }>\n) {\n const targetOptionsRef = { current: null as TargetOptions | null }\n\n async function loadTargetOptions(): Promise<TargetOptions> {\n if (targetOptionsRef.current) return targetOptionsRef.current\n try {\n const { result } = await apiCallFn<TargetOptions>('/api/scheduler/targets')\n const options = result ?? { queues: [], commands: [] }\n targetOptionsRef.current = options\n return options\n } catch {\n return { queues: [], commands: [] }\n }\n }\n\n async function loadQueueOptions(query?: string): Promise<ComboboxOption[]> {\n const options = await loadTargetOptions()\n if (!query) return options.queues\n const lower = query.toLowerCase()\n return options.queues.filter((q) => q.label.toLowerCase().includes(lower))\n }\n\n async function loadCommandOptions(query?: string): Promise<ComboboxOption[]> {\n const options = await loadTargetOptions()\n if (!query) return options.commands\n const lower = query.toLowerCase()\n return options.commands.filter((c) => c.label.toLowerCase().includes(lower))\n }\n\n return { loadTargetOptions, loadQueueOptions, loadCommandOptions, targetOptionsRef }\n}\n\nexport async function loadTimezoneOptions(query?: string): Promise<ComboboxOption[]> {\n try {\n const allTz = Array.from(new Set(['UTC', ...Intl.supportedValuesOf('timeZone')]))\n const filtered = query\n ? allTz.filter((tz) => tz.toLowerCase().includes(query.toLowerCase()))\n : allTz\n return filtered.slice(0, 100).map((tz) => ({\n value: tz,\n label: tz,\n }))\n } catch {\n return [{ value: 'UTC', label: 'UTC' }]\n }\n}\n\n// ---------------------------------------------------------------------------\n// Schema\n// ---------------------------------------------------------------------------\n\nexport function scheduledJobFormSchema(t: (key: string, fallback: string) => string) {\n return z.object({\n name: z.string().min(1, t('scheduler.form.name.required', 'Name is required')),\n description: z.string().optional(),\n scopeType: z.enum(['system', 'organization', 'tenant']),\n scheduleType: z.enum(['cron', 'interval']),\n scheduleValue: z.string().min(1, t('scheduler.form.schedule.required', 'Schedule is required')),\n timezone: z.string(),\n targetType: z.enum(['queue', 'command']),\n targetQueue: z.string().optional(),\n targetCommand: z.string().optional(),\n targetPayload: z.record(z.string(), z.unknown()).optional(),\n isEnabled: z.boolean(),\n })\n}\n\n// ---------------------------------------------------------------------------\n// Fields\n// ---------------------------------------------------------------------------\n\nexport function scheduledJobFields(\n t: (key: string, fallback: string) => string,\n loaders: {\n loadQueueOptions: (query?: string) => Promise<ComboboxOption[]>\n loadCommandOptions: (query?: string) => Promise<ComboboxOption[]>\n loadTimezoneOptions: (query?: string) => Promise<ComboboxOption[]>\n },\n options?: { lockScope?: boolean }\n): CrudField[] {\n const lockScope = options?.lockScope ?? false\n return [\n {\n id: 'name',\n type: 'text',\n label: t('scheduler.form.name', 'Name'),\n required: true,\n },\n {\n id: 'description',\n type: 'textarea',\n label: t('scheduler.form.description', 'Description'),\n },\n {\n id: 'scopeType',\n type: 'select',\n label: t('scheduler.form.scope_type', 'Scope'),\n required: true,\n // Scope is derived from the creator's auth context at create time and is\n // immutable afterwards (the update schema/command never persist it). Lock\n // the field on edit so it does not deceptively accept input that is then\n // silently dropped on save.\n disabled: lockScope,\n description: lockScope\n ? t('scheduler.form.scope_type.locked_description', 'Scope is set when the schedule is created and cannot be changed afterwards.')\n : undefined,\n options: [\n { value: 'system', label: t('scheduler.scope.system', 'System') },\n { value: 'organization', label: t('scheduler.scope.organization', 'Organization') },\n { value: 'tenant', label: t('scheduler.scope.tenant', 'Tenant') },\n ],\n },\n {\n id: 'scheduleType',\n type: 'select',\n label: t('scheduler.form.schedule_type', 'Schedule Type'),\n required: true,\n options: [\n { value: 'cron', label: t('scheduler.type.cron', 'Cron Expression') },\n { value: 'interval', label: t('scheduler.type.interval', 'Simple Interval') },\n ],\n },\n {\n id: 'scheduleValue',\n type: 'text',\n label: t('scheduler.form.schedule_value', 'Schedule Value'),\n placeholder: t('scheduler.form.schedule_value.placeholder', 'e.g. 0 */6 * * * or 15m'),\n description: t('scheduler.form.schedule_value.description', 'For cron: use cron expression (e.g., \"0 0 * * *\"). For interval: use format like \"15m\", \"2h\", \"1d\" (s=seconds, m=minutes, h=hours, d=days)'),\n required: true,\n },\n {\n id: 'timezone',\n type: 'combobox',\n label: t('scheduler.form.timezone', 'Timezone'),\n placeholder: t('scheduler.form.timezone.placeholder', 'Search timezone...'),\n required: true,\n loadOptions: loaders.loadTimezoneOptions,\n allowCustomValues: false,\n },\n {\n id: 'targetType',\n type: 'select',\n label: t('scheduler.form.target_type', 'Target Type'),\n required: true,\n options: [\n { value: 'queue', label: t('scheduler.target.queue', 'Queue') },\n { value: 'command', label: t('scheduler.target.command', 'Command') },\n ],\n },\n {\n id: 'targetFields',\n type: 'custom',\n label: '',\n component: ({ values, setFormValue }) => {\n const targetType = values?.targetType as string | undefined\n const targetQueue = (values?.targetQueue as string) || ''\n const targetCommand = (values?.targetCommand as string) || ''\n\n return (\n <div className=\"space-y-4\">\n {targetType === 'queue' && (\n <div className=\"space-y-1\">\n <Label htmlFor=\"targetQueue\">\n {t('scheduler.form.target_queue', 'Target Queue')}\n <span className=\"text-status-error-icon ml-0.5\" aria-hidden=\"true\">*</span>\n </Label>\n <ComboboxInput\n value={targetQueue}\n onChange={(next) => setFormValue && setFormValue('targetQueue', next)}\n placeholder={t('scheduler.form.target_queue.placeholder', 'Search queues...')}\n loadSuggestions={loaders.loadQueueOptions}\n allowCustomValues={true}\n />\n </div>\n )}\n {targetType === 'command' && (\n <div className=\"space-y-1\">\n <Label htmlFor=\"targetCommand\">\n {t('scheduler.form.target_command', 'Target Command')}\n <span className=\"text-status-error-icon ml-0.5\" aria-hidden=\"true\">*</span>\n </Label>\n <ComboboxInput\n value={targetCommand}\n onChange={(next) => setFormValue && setFormValue('targetCommand', next)}\n placeholder={t('scheduler.form.target_command.placeholder', 'Search commands...')}\n loadSuggestions={loaders.loadCommandOptions}\n allowCustomValues={false}\n />\n </div>\n )}\n </div>\n )\n },\n },\n {\n id: 'targetPayload',\n type: 'custom',\n label: t('scheduler.form.target_payload', 'Job Arguments (JSON)'),\n description: t('scheduler.form.target_payload.description', 'Optional JSON payload. Fields tenantId and organizationId are injected automatically at execution time.'),\n component: (props) => <PayloadJsonEditor {...props} />,\n },\n ]\n}\n\n// ---------------------------------------------------------------------------\n// Groups\n// ---------------------------------------------------------------------------\n\nexport function scheduledJobGroups(t: (key: string, fallback: string) => string): CrudFormGroup[] {\n return [\n {\n id: 'basic',\n title: t('scheduler.form.group.basic', 'Basic Information'),\n fields: ['name', 'description', 'scopeType'],\n },\n {\n id: 'schedule',\n title: t('scheduler.form.group.schedule', 'Schedule Configuration'),\n fields: ['scheduleType', 'scheduleValue', 'timezone'],\n },\n {\n id: 'target',\n title: t('scheduler.form.group.target', 'Target Configuration'),\n fields: ['targetType', 'targetFields', 'targetPayload'],\n },\n ]\n}\n\n// ---------------------------------------------------------------------------\n// Payload builder\n// ---------------------------------------------------------------------------\n\nexport function buildScheduledJobPayload(\n values: ScheduleFormValues,\n isEnabled: boolean\n): Record<string, unknown> {\n const targetPayload = values.targetPayload && Object.keys(values.targetPayload).length > 0\n ? values.targetPayload\n : null\n\n return {\n ...values,\n targetPayload,\n isEnabled,\n }\n}\n"],
|
|
5
|
+
"mappings": "AAqCI,cAkBA,YAlBA;AApCJ,SAAS,SAAS;AAClB,SAAS,qBAA0C;AACnD,SAAS,aAAa;AACtB,SAAS,cAAc;AACvB,SAAS,mBAAmB;AA8BrB,SAAS,kBAAkB,EAAE,OAAO,UAAU,SAAS,GAA+B;AAC3F,SACE;AAAA,IAAC;AAAA;AAAA,MACC,OAAO,SAAS,CAAC;AAAA,MACjB,UAAU;AAAA,MACV;AAAA;AAAA,EACF;AAEJ;AAEO,SAAS,0BAA0B;AAAA,EACxC;AAAA,EACA;AAAA,EACA;AACF,GAIG;AACD,SACE,qBAAC,SAAI,WAAU,2BACb;AAAA,wBAAC,SAAM,SAAQ,kBAAiB,WAAU,sCACvC,sBAAY,EAAE,0BAA0B,SAAS,IAAI,EAAE,2BAA2B,UAAU,GAC/F;AAAA,IACA;AAAA,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C,sBAAsB;AAAA,MAChE,aAAa,EAAE,6CAA6C,yGAAyG;AAAA,MACrK,WAAW,CAAC,UAAU,oBAAC,qBAAmB,GAAG,OAAO;AAAA,IACtD;AAAA,EACF;AACF;AAMO,SAAS,mBAAmB,GAA+D;AAChG,SAAO;AAAA,IACL;AAAA,MACE,IAAI;AAAA,MACJ,OAAO,EAAE,8BAA8B,mBAAmB;AAAA,MAC1D,QAAQ,CAAC,QAAQ,eAAe,WAAW;AAAA,IAC7C;AAAA,IACA;AAAA,MACE,IAAI;AAAA,MACJ,OAAO,EAAE,iCAAiC,wBAAwB;AAAA,MAClE,QAAQ,CAAC,gBAAgB,iBAAiB,UAAU;AAAA,IACtD;AAAA,IACA;AAAA,MACE,IAAI;AAAA,MACJ,OAAO,EAAE,+BAA+B,sBAAsB;AAAA,MAC9D,QAAQ,CAAC,cAAc,gBAAgB,eAAe;AAAA,IACxD;AAAA,EACF;AACF;AAMO,SAAS,yBACd,QACA,WACyB;AACzB,QAAM,gBAAgB,OAAO,iBAAiB,OAAO,KAAK,OAAO,aAAa,EAAE,SAAS,IACrF,OAAO,gBACP;AAEJ,SAAO;AAAA,IACL,GAAG;AAAA,IACH;AAAA,IACA;AAAA,EACF;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.4
|
|
3
|
+
"version": "0.6.4",
|
|
4
4
|
"description": "Database-managed scheduled jobs with admin UI",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -58,13 +58,13 @@
|
|
|
58
58
|
"./*/*/*/*/*/*.json": "./src/*/*/*/*/*/*.json"
|
|
59
59
|
},
|
|
60
60
|
"dependencies": {
|
|
61
|
-
"@open-mercato/events": "0.6.4
|
|
62
|
-
"@open-mercato/queue": "0.6.4
|
|
61
|
+
"@open-mercato/events": "0.6.4",
|
|
62
|
+
"@open-mercato/queue": "0.6.4",
|
|
63
63
|
"cron-parser": "^5.5.0"
|
|
64
64
|
},
|
|
65
65
|
"peerDependencies": {
|
|
66
66
|
"@mikro-orm/core": "^7.0.14",
|
|
67
|
-
"@open-mercato/shared": "0.6.4
|
|
67
|
+
"@open-mercato/shared": "0.6.4",
|
|
68
68
|
"bullmq": "^5.0.0",
|
|
69
69
|
"ioredis": "^5.0.0",
|
|
70
70
|
"zod": ">=3.23.0"
|
|
@@ -78,9 +78,9 @@
|
|
|
78
78
|
}
|
|
79
79
|
},
|
|
80
80
|
"devDependencies": {
|
|
81
|
-
"@open-mercato/shared": "0.6.4
|
|
81
|
+
"@open-mercato/shared": "0.6.4",
|
|
82
82
|
"@types/jest": "^30.0.0",
|
|
83
|
-
"@types/node": "^25.9.
|
|
83
|
+
"@types/node": "^25.9.2",
|
|
84
84
|
"jest": "^30.4.2",
|
|
85
85
|
"ts-jest": "^29.4.11"
|
|
86
86
|
},
|
|
@@ -91,6 +91,5 @@
|
|
|
91
91
|
"type": "git",
|
|
92
92
|
"url": "https://github.com/open-mercato/open-mercato",
|
|
93
93
|
"directory": "packages/scheduler"
|
|
94
|
-
}
|
|
95
|
-
"stableVersion": "0.6.3"
|
|
94
|
+
}
|
|
96
95
|
}
|
|
@@ -0,0 +1,63 @@
|
|
|
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 {
|
|
5
|
+
SCHEDULER_JOBS_PATH,
|
|
6
|
+
createScheduleJob,
|
|
7
|
+
deleteScheduleJob,
|
|
8
|
+
getScheduleJobById,
|
|
9
|
+
uniqueScheduleName,
|
|
10
|
+
} from './helpers/scheduler'
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* TC-SCHED-002: PUT /api/scheduler/jobs updates schedule fields correctly
|
|
14
|
+
*
|
|
15
|
+
* Note: scheduleUpdateSchema requires `scheduleType` whenever `scheduleValue`
|
|
16
|
+
* changes, so the update payload sends both (the issue's draft omitted the
|
|
17
|
+
* type — the route rejects that with 400). This asserts the real contract.
|
|
18
|
+
*/
|
|
19
|
+
test.describe('TC-SCHED-002: PUT /api/scheduler/jobs updates schedule fields', () => {
|
|
20
|
+
test('updates name and scheduleValue while preserving identity and scope', async ({ request }) => {
|
|
21
|
+
const token = await getAuthToken(request, 'admin')
|
|
22
|
+
let scheduleId: string | null = null
|
|
23
|
+
|
|
24
|
+
try {
|
|
25
|
+
scheduleId = await createScheduleJob(request, token, {
|
|
26
|
+
name: uniqueScheduleName('Sched Update'),
|
|
27
|
+
scheduleType: 'interval',
|
|
28
|
+
scheduleValue: '15m',
|
|
29
|
+
})
|
|
30
|
+
|
|
31
|
+
const original = await getScheduleJobById(request, token, scheduleId)
|
|
32
|
+
expect(original).not.toBeNull()
|
|
33
|
+
expect(original!.scheduleValue).toBe('15m')
|
|
34
|
+
|
|
35
|
+
const updateResponse = await apiRequest(request, 'PUT', SCHEDULER_JOBS_PATH, {
|
|
36
|
+
token,
|
|
37
|
+
data: { id: scheduleId, name: 'Updated-Test-1', scheduleType: 'interval', scheduleValue: '30m' },
|
|
38
|
+
})
|
|
39
|
+
expect(updateResponse.status()).toBe(200)
|
|
40
|
+
const updateBody = await readJsonSafe<{ ok?: boolean }>(updateResponse)
|
|
41
|
+
expect(updateBody?.ok).toBe(true)
|
|
42
|
+
|
|
43
|
+
const updated = await getScheduleJobById(request, token, scheduleId)
|
|
44
|
+
expect(updated).not.toBeNull()
|
|
45
|
+
// Mutated fields persisted
|
|
46
|
+
expect(updated!.name).toBe('Updated-Test-1')
|
|
47
|
+
expect(updated!.scheduleValue).toBe('30m')
|
|
48
|
+
// Identity and scope unchanged
|
|
49
|
+
expect(updated!.id).toBe(scheduleId)
|
|
50
|
+
expect(updated!.tenantId).toBe(original!.tenantId)
|
|
51
|
+
expect(updated!.organizationId).toBe(original!.organizationId)
|
|
52
|
+
expect(updated!.targetQueue).toBe(original!.targetQueue)
|
|
53
|
+
// updatedAt advances past the original creation timestamp
|
|
54
|
+
if (original!.createdAt && updated!.updatedAt) {
|
|
55
|
+
expect(new Date(updated!.updatedAt).getTime()).toBeGreaterThanOrEqual(
|
|
56
|
+
new Date(original!.createdAt).getTime(),
|
|
57
|
+
)
|
|
58
|
+
}
|
|
59
|
+
} finally {
|
|
60
|
+
await deleteScheduleJob(request, token, scheduleId)
|
|
61
|
+
}
|
|
62
|
+
})
|
|
63
|
+
})
|
|
@@ -0,0 +1,48 @@
|
|
|
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, getScheduleJobById } from './helpers/scheduler'
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* TC-SCHED-003: DELETE /api/scheduler/jobs soft-deletes a schedule and
|
|
8
|
+
* prevents re-listing. The list endpoint keeps returning 200 (not 404) with
|
|
9
|
+
* the soft-deleted record filtered out by the `deletedAt` soft-delete field.
|
|
10
|
+
*/
|
|
11
|
+
test.describe('TC-SCHED-003: DELETE /api/scheduler/jobs soft-deletes a schedule', () => {
|
|
12
|
+
test('removes the schedule from listings and returns 200 (not 404) afterwards', async ({ request }) => {
|
|
13
|
+
const token = await getAuthToken(request, 'admin')
|
|
14
|
+
let scheduleId: string | null = null
|
|
15
|
+
let deleted = false
|
|
16
|
+
|
|
17
|
+
try {
|
|
18
|
+
scheduleId = await createScheduleJob(request, token)
|
|
19
|
+
|
|
20
|
+
const present = await getScheduleJobById(request, token, scheduleId)
|
|
21
|
+
expect(present).not.toBeNull()
|
|
22
|
+
|
|
23
|
+
const deleteResponse = await apiRequest(request, 'DELETE', SCHEDULER_JOBS_PATH, {
|
|
24
|
+
token,
|
|
25
|
+
data: { id: scheduleId },
|
|
26
|
+
})
|
|
27
|
+
expect(deleteResponse.status()).toBe(200)
|
|
28
|
+
const deleteBody = await readJsonSafe<{ ok?: boolean }>(deleteResponse)
|
|
29
|
+
expect(deleteBody?.ok).toBe(true)
|
|
30
|
+
deleted = true
|
|
31
|
+
|
|
32
|
+
// Soft delete: list still returns 200 with an (empty) items array, never 404.
|
|
33
|
+
const afterResponse = await apiRequest(
|
|
34
|
+
request,
|
|
35
|
+
'GET',
|
|
36
|
+
`${SCHEDULER_JOBS_PATH}?id=${encodeURIComponent(scheduleId)}`,
|
|
37
|
+
{ token },
|
|
38
|
+
)
|
|
39
|
+
expect(afterResponse.status()).toBe(200)
|
|
40
|
+
const afterBody = await readJsonSafe<{ items?: Array<{ id: string }> }>(afterResponse)
|
|
41
|
+
expect(Array.isArray(afterBody?.items)).toBe(true)
|
|
42
|
+
expect((afterBody?.items ?? []).some((item) => item.id === scheduleId)).toBe(false)
|
|
43
|
+
expect((afterBody?.items ?? []).length).toBe(0)
|
|
44
|
+
} finally {
|
|
45
|
+
if (!deleted) await deleteScheduleJob(request, token, scheduleId)
|
|
46
|
+
}
|
|
47
|
+
})
|
|
48
|
+
})
|
|
@@ -0,0 +1,52 @@
|
|
|
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_EXECUTION_QUEUE, SCHEDULER_TARGETS_PATH } from './helpers/scheduler'
|
|
5
|
+
|
|
6
|
+
type TargetOption = { value: string; label: string }
|
|
7
|
+
type TargetsResponse = { queues?: TargetOption[]; commands?: TargetOption[] }
|
|
8
|
+
|
|
9
|
+
function expectSortedByValue(options: TargetOption[], label: string) {
|
|
10
|
+
const values = options.map((option) => option.value)
|
|
11
|
+
expect(values, `${label} should be sorted alphabetically by value`).toEqual(
|
|
12
|
+
[...values].sort((a, b) => a.localeCompare(b)),
|
|
13
|
+
)
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
function expectOptionShape(options: TargetOption[], label: string) {
|
|
17
|
+
for (const option of options) {
|
|
18
|
+
expect(typeof option.value, `${label} option value should be a string`).toBe('string')
|
|
19
|
+
expect(typeof option.label, `${label} option label should be a string`).toBe('string')
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* TC-SCHED-004: GET /api/scheduler/targets returns available queue names
|
|
25
|
+
* (from module workers) and registered command IDs (from the command
|
|
26
|
+
* registry), both sorted alphabetically by value. Read-only, no fixtures.
|
|
27
|
+
*/
|
|
28
|
+
test.describe('TC-SCHED-004: GET /api/scheduler/targets lists queues and commands', () => {
|
|
29
|
+
test('returns sorted queues (incl. scheduler-execution) and a non-empty command list', async ({ request }) => {
|
|
30
|
+
const token = await getAuthToken(request, 'admin')
|
|
31
|
+
|
|
32
|
+
const response = await apiRequest(request, 'GET', SCHEDULER_TARGETS_PATH, { token })
|
|
33
|
+
expect(response.status()).toBe(200)
|
|
34
|
+
|
|
35
|
+
const body = await readJsonSafe<TargetsResponse>(response)
|
|
36
|
+
const queues = body?.queues ?? []
|
|
37
|
+
const commands = body?.commands ?? []
|
|
38
|
+
|
|
39
|
+
// Queues: non-empty, well-shaped, sorted, and include the known scheduler queue.
|
|
40
|
+
expect(Array.isArray(body?.queues)).toBe(true)
|
|
41
|
+
expect(queues.length).toBeGreaterThan(0)
|
|
42
|
+
expectOptionShape(queues, 'queues')
|
|
43
|
+
expect(queues.map((queue) => queue.value)).toContain(SCHEDULER_EXECUTION_QUEUE)
|
|
44
|
+
expectSortedByValue(queues, 'queues')
|
|
45
|
+
|
|
46
|
+
// Commands: non-empty, well-shaped, and sorted.
|
|
47
|
+
expect(Array.isArray(body?.commands)).toBe(true)
|
|
48
|
+
expect(commands.length).toBeGreaterThan(0)
|
|
49
|
+
expectOptionShape(commands, 'commands')
|
|
50
|
+
expectSortedByValue(commands, 'commands')
|
|
51
|
+
})
|
|
52
|
+
})
|
|
@@ -0,0 +1,51 @@
|
|
|
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 {
|
|
5
|
+
SCHEDULER_TRIGGER_PATH,
|
|
6
|
+
createScheduleJob,
|
|
7
|
+
deleteScheduleJob,
|
|
8
|
+
uniqueScheduleName,
|
|
9
|
+
} from './helpers/scheduler'
|
|
10
|
+
|
|
11
|
+
const isAsyncQueueStrategy = (process.env.QUEUE_STRATEGY || 'local') === 'async'
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* TC-SCHED-005: POST /api/scheduler/trigger manually enqueues a schedule for
|
|
15
|
+
* execution. Manual triggers require the async (BullMQ) queue strategy, so the
|
|
16
|
+
* assertion branches on QUEUE_STRATEGY exactly like TC-SCHED-001: async returns
|
|
17
|
+
* 200 + jobId, local returns 400 with an "async required" message.
|
|
18
|
+
*/
|
|
19
|
+
test.describe('TC-SCHED-005: POST /api/scheduler/trigger manual execution', () => {
|
|
20
|
+
test('enqueues an execution job (async) or rejects with async-required (local)', async ({ request }) => {
|
|
21
|
+
const token = await getAuthToken(request, 'admin')
|
|
22
|
+
let scheduleId: string | null = null
|
|
23
|
+
|
|
24
|
+
try {
|
|
25
|
+
scheduleId = await createScheduleJob(request, token, {
|
|
26
|
+
name: uniqueScheduleName('Trigger-Test'),
|
|
27
|
+
scheduleType: 'interval',
|
|
28
|
+
scheduleValue: '1h',
|
|
29
|
+
})
|
|
30
|
+
|
|
31
|
+
const response = await apiRequest(request, 'POST', SCHEDULER_TRIGGER_PATH, {
|
|
32
|
+
token,
|
|
33
|
+
data: { id: scheduleId },
|
|
34
|
+
})
|
|
35
|
+
|
|
36
|
+
if (isAsyncQueueStrategy) {
|
|
37
|
+
expect(response.status()).toBe(200)
|
|
38
|
+
const body = await readJsonSafe<{ ok?: boolean; jobId?: string; message?: string }>(response)
|
|
39
|
+
expect(body?.ok).toBe(true)
|
|
40
|
+
expect(typeof body?.jobId === 'string' && (body?.jobId?.length ?? 0) > 0).toBe(true)
|
|
41
|
+
expect(body?.message ?? '').toMatch(/queued|triggered/i)
|
|
42
|
+
} else {
|
|
43
|
+
expect(response.status()).toBe(400)
|
|
44
|
+
const body = await readJsonSafe<{ error?: string; message?: string }>(response)
|
|
45
|
+
expect(`${body?.error ?? ''} ${body?.message ?? ''}`).toMatch(/async/i)
|
|
46
|
+
}
|
|
47
|
+
} finally {
|
|
48
|
+
await deleteScheduleJob(request, token, scheduleId)
|
|
49
|
+
}
|
|
50
|
+
})
|
|
51
|
+
})
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import { expect, test } from '@playwright/test'
|
|
2
|
+
import { apiRequest, getAuthToken } from '@open-mercato/core/helpers/integration/api'
|
|
3
|
+
import {
|
|
4
|
+
createRoleFixture,
|
|
5
|
+
createUserFixture,
|
|
6
|
+
deleteRoleIfExists,
|
|
7
|
+
deleteUserIfExists,
|
|
8
|
+
setRoleAclFeatures,
|
|
9
|
+
} from '@open-mercato/core/helpers/integration/authFixtures'
|
|
10
|
+
import { getTokenContext, readJsonSafe } from '@open-mercato/core/helpers/integration/generalFixtures'
|
|
11
|
+
import { SCHEDULER_JOBS_PATH, createScheduleJob, deleteScheduleJob, getScheduleJobById } from './helpers/scheduler'
|
|
12
|
+
|
|
13
|
+
type ForbiddenBody = { error?: string; requiredFeatures?: string[] }
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* TC-SCHED-006: PUT and DELETE on /api/scheduler/jobs are gated by
|
|
17
|
+
* `scheduler.jobs.manage`. A user holding only `scheduler.jobs.view` can read
|
|
18
|
+
* schedules but is denied with 403 on both mutating verbs, and a failed attempt
|
|
19
|
+
* leaves the schedule untouched.
|
|
20
|
+
*/
|
|
21
|
+
test.describe('TC-SCHED-006: scheduler.jobs.manage gate on PUT/DELETE', () => {
|
|
22
|
+
test('view-only user gets 403 on PUT and DELETE; schedule stays intact', async ({ request }) => {
|
|
23
|
+
const adminToken = await getAuthToken(request, 'admin')
|
|
24
|
+
const { organizationId } = getTokenContext(adminToken)
|
|
25
|
+
expect(organizationId.length, 'admin token should carry an organization id').toBeGreaterThan(0)
|
|
26
|
+
|
|
27
|
+
const stamp = `${Date.now()}`
|
|
28
|
+
let roleId: string | null = null
|
|
29
|
+
let userId: string | null = null
|
|
30
|
+
let scheduleId: string | null = null
|
|
31
|
+
|
|
32
|
+
try {
|
|
33
|
+
// A role that can view schedules but not manage them.
|
|
34
|
+
roleId = await createRoleFixture(request, adminToken, { name: `sched-view-only-${stamp}` })
|
|
35
|
+
await setRoleAclFeatures(request, adminToken, { roleId, features: ['scheduler.jobs.view'] })
|
|
36
|
+
|
|
37
|
+
const email = `sched-view-only-${stamp}@example.com`
|
|
38
|
+
// Password must satisfy the default policy (min length + digit + uppercase + special).
|
|
39
|
+
const password = 'Sched-View-1!'
|
|
40
|
+
userId = await createUserFixture(request, adminToken, {
|
|
41
|
+
email,
|
|
42
|
+
password,
|
|
43
|
+
organizationId,
|
|
44
|
+
roles: [roleId],
|
|
45
|
+
name: 'Scheduler View Only',
|
|
46
|
+
})
|
|
47
|
+
const viewToken = await getAuthToken(request, email, password)
|
|
48
|
+
|
|
49
|
+
scheduleId = await createScheduleJob(request, adminToken)
|
|
50
|
+
|
|
51
|
+
// Sanity: the view-only user authenticates and CAN list (has the view feature),
|
|
52
|
+
// so the 403s below are specifically about the missing manage feature.
|
|
53
|
+
const listResponse = await apiRequest(request, 'GET', SCHEDULER_JOBS_PATH, { token: viewToken })
|
|
54
|
+
expect(listResponse.status()).toBe(200)
|
|
55
|
+
|
|
56
|
+
// PUT denied
|
|
57
|
+
const putResponse = await apiRequest(request, 'PUT', SCHEDULER_JOBS_PATH, {
|
|
58
|
+
token: viewToken,
|
|
59
|
+
data: { id: scheduleId, name: 'Should-Not-Apply' },
|
|
60
|
+
})
|
|
61
|
+
expect(putResponse.status()).toBe(403)
|
|
62
|
+
const putBody = await readJsonSafe<ForbiddenBody>(putResponse)
|
|
63
|
+
expect(putBody?.requiredFeatures ?? []).toContain('scheduler.jobs.manage')
|
|
64
|
+
|
|
65
|
+
// DELETE denied
|
|
66
|
+
const deleteResponse = await apiRequest(request, 'DELETE', SCHEDULER_JOBS_PATH, {
|
|
67
|
+
token: viewToken,
|
|
68
|
+
data: { id: scheduleId },
|
|
69
|
+
})
|
|
70
|
+
expect(deleteResponse.status()).toBe(403)
|
|
71
|
+
const deleteBody = await readJsonSafe<ForbiddenBody>(deleteResponse)
|
|
72
|
+
expect(deleteBody?.requiredFeatures ?? []).toContain('scheduler.jobs.manage')
|
|
73
|
+
|
|
74
|
+
// The schedule is unchanged and still present (admin can read it).
|
|
75
|
+
const after = await getScheduleJobById(request, adminToken, scheduleId)
|
|
76
|
+
expect(after).not.toBeNull()
|
|
77
|
+
expect(after!.name).not.toBe('Should-Not-Apply')
|
|
78
|
+
} finally {
|
|
79
|
+
await deleteScheduleJob(request, adminToken, scheduleId)
|
|
80
|
+
await deleteUserIfExists(request, adminToken, userId)
|
|
81
|
+
await deleteRoleIfExists(request, adminToken, roleId)
|
|
82
|
+
}
|
|
83
|
+
})
|
|
84
|
+
})
|
|
@@ -0,0 +1,50 @@
|
|
|
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_EXECUTION_QUEUE, SCHEDULER_JOBS_PATH, uniqueScheduleName } from './helpers/scheduler'
|
|
5
|
+
|
|
6
|
+
type ValidationError = { error?: string; details?: Array<{ path?: Array<string | number> }> }
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* TC-SCHED-007: POST /api/scheduler/jobs rejects invalid cron and interval
|
|
10
|
+
* `scheduleValue`s with 400 and an error scoped to the `scheduleValue` path.
|
|
11
|
+
*
|
|
12
|
+
* Interval format is `<number><unit>` with unit in s|m|h|d, so the inputs below
|
|
13
|
+
* are genuinely malformed (the issue's "99h"/"0m" drafts are actually valid).
|
|
14
|
+
* All cases are rejected at validation, so no records are created and no
|
|
15
|
+
* teardown is required.
|
|
16
|
+
*/
|
|
17
|
+
const invalidCases = [
|
|
18
|
+
{ label: 'cron: not a cron expression', scheduleType: 'cron' as const, scheduleValue: 'not-a-cron' },
|
|
19
|
+
{ label: 'cron: too few fields', scheduleType: 'cron' as const, scheduleValue: '* * *' },
|
|
20
|
+
{ label: 'interval: unsupported unit', scheduleType: 'interval' as const, scheduleValue: '15x' },
|
|
21
|
+
{ label: 'interval: missing unit', scheduleType: 'interval' as const, scheduleValue: '99' },
|
|
22
|
+
]
|
|
23
|
+
|
|
24
|
+
test.describe('TC-SCHED-007: POST /api/scheduler/jobs validates schedule value format', () => {
|
|
25
|
+
for (const testCase of invalidCases) {
|
|
26
|
+
test(`rejects ${testCase.label} with 400 on scheduleValue`, async ({ request }) => {
|
|
27
|
+
const token = await getAuthToken(request, 'admin')
|
|
28
|
+
|
|
29
|
+
const response = await apiRequest(request, 'POST', SCHEDULER_JOBS_PATH, {
|
|
30
|
+
token,
|
|
31
|
+
data: {
|
|
32
|
+
name: uniqueScheduleName('Invalid Schedule Value'),
|
|
33
|
+
scopeType: 'organization',
|
|
34
|
+
scheduleType: testCase.scheduleType,
|
|
35
|
+
scheduleValue: testCase.scheduleValue,
|
|
36
|
+
timezone: 'UTC',
|
|
37
|
+
targetType: 'queue',
|
|
38
|
+
targetQueue: SCHEDULER_EXECUTION_QUEUE,
|
|
39
|
+
isEnabled: true,
|
|
40
|
+
sourceType: 'user',
|
|
41
|
+
},
|
|
42
|
+
})
|
|
43
|
+
|
|
44
|
+
expect(response.status(), `${testCase.label} should be rejected with 400`).toBe(400)
|
|
45
|
+
const body = await readJsonSafe<ValidationError>(response)
|
|
46
|
+
const issuePaths = (body?.details ?? []).map((issue) => (issue.path ?? []).join('.'))
|
|
47
|
+
expect(issuePaths, `${testCase.label} error should target scheduleValue`).toContain('scheduleValue')
|
|
48
|
+
})
|
|
49
|
+
}
|
|
50
|
+
})
|