@open-mercato/core 0.11.1-develop.8557.1.e615240a3e → 0.11.1-develop.8572.1.85986dc508
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/api_keys/di.js +6 -2
- package/dist/modules/api_keys/di.js.map +2 -2
- package/dist/modules/api_keys/services/oneTimeIssuerService.js +47 -0
- package/dist/modules/api_keys/services/oneTimeIssuerService.js.map +7 -0
- package/dist/modules/audit_logs/di.js +2 -1
- package/dist/modules/audit_logs/di.js.map +2 -2
- package/dist/modules/audit_logs/services/actionLogService.js +65 -1
- package/dist/modules/audit_logs/services/actionLogService.js.map +2 -2
- package/dist/modules/auth/cli.js +1 -0
- package/dist/modules/auth/cli.js.map +2 -2
- package/dist/modules/auth/commands/users.js +10 -2
- package/dist/modules/auth/commands/users.js.map +2 -2
- package/dist/modules/auth/lib/setup-app.js +19 -5
- package/dist/modules/auth/lib/setup-app.js.map +2 -2
- package/dist/modules/catalog/lib/productScopeReindex.js +1 -1
- package/dist/modules/catalog/lib/productScopeReindex.js.map +2 -2
- package/dist/modules/configs/cli.js +26 -29
- package/dist/modules/configs/cli.js.map +2 -2
- package/dist/modules/configs/di.js +3 -1
- package/dist/modules/configs/di.js.map +2 -2
- package/dist/modules/configs/lib/instance-config-initializer.js +44 -0
- package/dist/modules/configs/lib/instance-config-initializer.js.map +7 -0
- package/dist/modules/configs/lib/instance-defaults.js +204 -0
- package/dist/modules/configs/lib/instance-defaults.js.map +7 -0
- package/dist/modules/configs/lib/module-config-service.js +115 -1
- package/dist/modules/configs/lib/module-config-service.js.map +2 -2
- package/dist/modules/entities/api/definitions.batch.js +55 -25
- package/dist/modules/entities/api/definitions.batch.js.map +2 -2
- package/dist/modules/entities/api/definitions.js +35 -8
- package/dist/modules/entities/api/definitions.js.map +2 -2
- package/dist/modules/entities/backend/entities/user/[entityId]/page.js +14 -8
- package/dist/modules/entities/backend/entities/user/[entityId]/page.js.map +2 -2
- package/dist/modules/notifications/lib/deliveryConfig.js +19 -12
- package/dist/modules/notifications/lib/deliveryConfig.js.map +2 -2
- package/dist/modules/notifications/setup.js +10 -0
- package/dist/modules/notifications/setup.js.map +2 -2
- package/dist/modules/payment_gateways/lib/gateway-service.js +1 -1
- package/dist/modules/payment_gateways/lib/gateway-service.js.map +2 -2
- package/dist/modules/query_index/api/purge.js +1 -1
- package/dist/modules/query_index/api/purge.js.map +2 -2
- package/dist/modules/query_index/api/reindex.js +1 -1
- package/dist/modules/query_index/api/reindex.js.map +2 -2
- package/dist/modules/query_index/cli.js +2 -2
- package/dist/modules/query_index/cli.js.map +2 -2
- package/dist/modules/query_index/lib/engine.js +5 -1
- package/dist/modules/query_index/lib/engine.js.map +2 -2
- package/dist/modules/query_index/subscribers/purge.js +3 -3
- package/dist/modules/query_index/subscribers/purge.js.map +2 -2
- package/dist/modules/query_index/subscribers/reindex.js +11 -13
- package/dist/modules/query_index/subscribers/reindex.js.map +2 -2
- package/dist/modules/translations/components/TranslationManager.js +47 -10
- package/dist/modules/translations/components/TranslationManager.js.map +2 -2
- package/dist/modules/wms/components/backend/CompletePutawayTaskDialog.js +8 -1
- package/dist/modules/wms/components/backend/CompletePutawayTaskDialog.js.map +2 -2
- package/dist/modules/workflows/ai-tools/authoring-pack.js +1 -1
- package/dist/modules/workflows/ai-tools/authoring-pack.js.map +2 -2
- package/dist/modules/workflows/api/instances/[id]/advance/route.js +1 -0
- package/dist/modules/workflows/api/instances/[id]/advance/route.js.map +2 -2
- package/dist/modules/workflows/api/instances/route.js +1 -1
- package/dist/modules/workflows/api/instances/route.js.map +2 -2
- package/dist/modules/workflows/api/instances/validate-start/route.js +3 -1
- package/dist/modules/workflows/api/instances/validate-start/route.js.map +2 -2
- package/dist/modules/workflows/components/fields/ActivityConfigFields.js +2 -0
- package/dist/modules/workflows/components/fields/ActivityConfigFields.js.map +2 -2
- package/dist/modules/workflows/di.js +3 -1
- package/dist/modules/workflows/di.js.map +2 -2
- package/dist/modules/workflows/events.js +13 -0
- package/dist/modules/workflows/events.js.map +2 -2
- package/dist/modules/workflows/lib/activity-executor.js +48 -15
- package/dist/modules/workflows/lib/activity-executor.js.map +2 -2
- package/dist/modules/workflows/lib/condition-handler.js +1 -1
- package/dist/modules/workflows/lib/condition-handler.js.map +2 -2
- package/dist/modules/workflows/lib/error-handler.js +1 -1
- package/dist/modules/workflows/lib/error-handler.js.map +2 -2
- package/dist/modules/workflows/lib/event-trigger-service.js +1 -1
- package/dist/modules/workflows/lib/event-trigger-service.js.map +2 -2
- package/dist/modules/workflows/lib/example-definition-authoring.js +90 -0
- package/dist/modules/workflows/lib/example-definition-authoring.js.map +7 -0
- package/dist/modules/workflows/lib/named-rules.js +42 -0
- package/dist/modules/workflows/lib/named-rules.js.map +7 -0
- package/dist/modules/workflows/lib/owned-definition.js +2 -0
- package/dist/modules/workflows/lib/owned-definition.js.map +2 -2
- package/dist/modules/workflows/lib/parallel-handler.js +1 -1
- package/dist/modules/workflows/lib/parallel-handler.js.map +2 -2
- package/dist/modules/workflows/lib/signal-handler.js +1 -0
- package/dist/modules/workflows/lib/signal-handler.js.map +2 -2
- package/dist/modules/workflows/lib/start-validator.js +87 -85
- package/dist/modules/workflows/lib/start-validator.js.map +2 -2
- package/dist/modules/workflows/lib/step-handler.js +1 -1
- package/dist/modules/workflows/lib/step-handler.js.map +2 -2
- package/dist/modules/workflows/lib/task-handler.js +1 -0
- package/dist/modules/workflows/lib/task-handler.js.map +2 -2
- package/dist/modules/workflows/lib/timer-handler.js +1 -0
- package/dist/modules/workflows/lib/timer-handler.js.map +2 -2
- package/dist/modules/workflows/lib/transition-handler.js +48 -166
- package/dist/modules/workflows/lib/transition-handler.js.map +3 -3
- package/dist/modules/workflows/lib/workflow-executor.js +3 -2
- package/dist/modules/workflows/lib/workflow-executor.js.map +2 -2
- package/package.json +8 -8
- package/src/modules/api_keys/di.ts +7 -2
- package/src/modules/api_keys/services/oneTimeIssuerService.ts +61 -0
- package/src/modules/audit_logs/di.ts +1 -0
- package/src/modules/audit_logs/services/actionLogService.ts +132 -1
- package/src/modules/auth/cli.ts +1 -0
- package/src/modules/auth/commands/users.ts +10 -2
- package/src/modules/auth/i18n/de.json +2 -0
- package/src/modules/auth/i18n/en.json +2 -0
- package/src/modules/auth/i18n/es.json +2 -0
- package/src/modules/auth/i18n/ko.json +2 -0
- package/src/modules/auth/i18n/pl.json +2 -0
- package/src/modules/auth/lib/setup-app.ts +30 -7
- package/src/modules/catalog/lib/productScopeReindex.ts +1 -1
- package/src/modules/configs/cli.ts +39 -37
- package/src/modules/configs/di.ts +2 -0
- package/src/modules/configs/lib/instance-config-initializer.ts +56 -0
- package/src/modules/configs/lib/instance-defaults.ts +262 -0
- package/src/modules/configs/lib/module-config-service.ts +156 -0
- package/src/modules/entities/api/definitions.batch.ts +65 -27
- package/src/modules/entities/api/definitions.ts +40 -11
- package/src/modules/entities/backend/entities/user/[entityId]/page.tsx +14 -7
- package/src/modules/notifications/lib/deliveryConfig.ts +20 -11
- package/src/modules/notifications/setup.ts +11 -0
- package/src/modules/payment_gateways/lib/gateway-service.ts +2 -2
- package/src/modules/query_index/api/purge.ts +1 -1
- package/src/modules/query_index/api/reindex.ts +1 -1
- package/src/modules/query_index/cli.ts +2 -2
- package/src/modules/query_index/lib/engine.ts +5 -1
- package/src/modules/query_index/subscribers/purge.ts +5 -4
- package/src/modules/query_index/subscribers/reindex.ts +14 -15
- package/src/modules/translations/components/TranslationManager.tsx +49 -10
- package/src/modules/translations/i18n/de.json +1 -0
- package/src/modules/translations/i18n/en.json +1 -0
- package/src/modules/translations/i18n/es.json +1 -0
- package/src/modules/translations/i18n/ko.json +1 -0
- package/src/modules/translations/i18n/pl.json +1 -0
- package/src/modules/wms/components/backend/CompletePutawayTaskDialog.tsx +8 -1
- package/src/modules/wms/i18n/de.json +1 -0
- package/src/modules/wms/i18n/en.json +1 -0
- package/src/modules/wms/i18n/es.json +1 -0
- package/src/modules/wms/i18n/ko.json +1 -0
- package/src/modules/wms/i18n/pl.json +1 -0
- package/src/modules/workflows/ai-tools/authoring-pack.ts +3 -1
- package/src/modules/workflows/api/instances/[id]/advance/route.ts +1 -0
- package/src/modules/workflows/api/instances/route.ts +1 -1
- package/src/modules/workflows/api/instances/validate-start/route.ts +3 -1
- package/src/modules/workflows/components/fields/ActivityConfigFields.tsx +2 -0
- package/src/modules/workflows/di.ts +2 -0
- package/src/modules/workflows/events.ts +14 -0
- package/src/modules/workflows/lib/activity-executor.ts +64 -40
- package/src/modules/workflows/lib/condition-handler.ts +1 -1
- package/src/modules/workflows/lib/error-handler.ts +1 -1
- package/src/modules/workflows/lib/event-trigger-service.ts +1 -1
- package/src/modules/workflows/lib/example-definition-authoring.ts +114 -0
- package/src/modules/workflows/lib/named-rules.ts +54 -0
- package/src/modules/workflows/lib/owned-definition.ts +4 -1
- package/src/modules/workflows/lib/parallel-handler.ts +1 -1
- package/src/modules/workflows/lib/signal-handler.ts +1 -0
- package/src/modules/workflows/lib/start-validator.ts +96 -94
- package/src/modules/workflows/lib/step-handler.ts +1 -1
- package/src/modules/workflows/lib/task-handler.ts +1 -0
- package/src/modules/workflows/lib/timer-handler.ts +1 -0
- package/src/modules/workflows/lib/transition-handler.ts +74 -238
- package/src/modules/workflows/lib/workflow-executor.ts +7 -4
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/modules/workflows/lib/task-handler.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * Workflows Module - User Task Handler Service\n *\n * Handles user task lifecycle operations:\n * - Completing user tasks\n * - Claiming tasks from role queues\n * - Reassigning tasks\n * - Escalating overdue tasks\n *\n * Functional API (no classes) following Open Mercato conventions.\n */\n\nimport { EntityManager } from '@mikro-orm/core'\nimport type { AwilixContainer } from 'awilix'\nimport {\n UserTask,\n WorkflowInstance,\n WorkflowEvent,\n StepInstance,\n} from '../data/entities'\nimport { executeWorkflow, handleTransitionFailure } from './workflow-executor'\nimport { findDefinitionForInstance } from './find-definition'\nimport {\n findTaskDecision,\n findTaskDecisionTransition,\n withRecordedDecision,\n} from './task-decisions'\nimport { loadTaskDecisionContext } from './task-decision-context'\nimport { readRequiredFormFields } from './task-form-schema'\nimport { isRunClosedToUserTasks } from './instance-status'\nimport * as stepHandler from './step-handler'\nimport * as transitionHandler from './transition-handler'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('workflows')\n\n// ============================================================================\n// Types and Interfaces\n// ============================================================================\n\n/**\n * Tenant/organization the caller is acting within. Every task lookup filters on\n * it, so a task id from another tenant resolves to \"not found\" instead of being\n * mutated.\n */\nexport interface UserTaskScope {\n tenantId: string\n organizationId: string\n}\n\n/**\n * Shape of the `taskHandler` DI registration (`di.ts`).\n *\n * The functions below stay exported \u2014 third-party modules may import them and\n * `BACKWARD_COMPATIBILITY.md` \u00A73 freezes import paths \u2014 but callers inside the\n * platform MUST resolve this service instead, per the module's first rule.\n */\nexport interface TaskHandlerService {\n completeUserTask: typeof completeUserTask\n claimUserTask: typeof claimUserTask\n releaseUserTask: typeof releaseUserTask\n reassignUserTask: typeof reassignUserTask\n}\n\nexport interface CompleteUserTaskOptions {\n taskId: string\n formData: Record<string, any>\n userId: string\n comments?: string\n /**\n * The decision button the assignee pressed, when the step authored any.\n *\n * It does two things: it SELECTS the outgoing route (the decision's\n * `transitionId` wins over the first-valid-transition default), and it is\n * RECORDED as part of the completion payload. Omitted, completion behaves\n * exactly as it always did.\n */\n decisionId?: string\n scope: UserTaskScope\n}\n\nexport class UserTaskError extends Error {\n constructor(\n message: string,\n public code: string,\n public details?: any\n ) {\n super(message)\n this.name = 'UserTaskError'\n }\n}\n\n// ============================================================================\n// User Task Completion\n// ============================================================================\n\n/**\n * Complete a user task and resume workflow execution\n *\n * This function:\n * 1. Validates the task exists and can be completed\n * 2. Updates the task with form data and completion info\n * 3. Merges form data into workflow context\n * 4. Logs completion event\n * 5. Resumes workflow execution\n *\n * Closing the task is a COMPARE-AND-SET, like `claimUserTask`: the lookup only\n * decides which error to report, while the row is closed with a conditional\n * `UPDATE \u2026 WHERE status IN ('PENDING', 'IN_PROGRESS')`. Two submissions of the\n * same task (the task page and a notification quick action, two tabs, a client\n * retrying after a timeout) can both pass the lookup; only one closes the row,\n * and the other gets the same `TASK_NOT_FOUND` a later submission would, before\n * any event is logged or the run is advanced.\n *\n * @param em - Entity manager\n * @param container - DI container for workflow execution\n * @param options - Task completion options\n * @throws UserTaskError if task not found or validation fails\n */\nexport async function completeUserTask(\n em: EntityManager,\n container: AwilixContainer,\n options: CompleteUserTaskOptions\n): Promise<void> {\n const { taskId, formData, userId, comments, decisionId, scope } = options\n\n // Fetch task\n const task = await em.findOne(UserTask, {\n id: taskId,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n status: { $in: ['PENDING', 'IN_PROGRESS'] },\n })\n\n if (!task) {\n throw new UserTaskError(\n 'Task not found or already completed',\n 'TASK_NOT_FOUND',\n { taskId }\n )\n }\n\n // A task addressed to one person is that person's to finish. Tasks that name\n // nobody \u2014 agent dispositions, role queues nobody has claimed \u2014 stay open to\n // anyone the route's feature gate already admitted, so this narrows the\n // over-permissive case without stranding the unassigned ones.\n const claimant = task.claimedBy ?? task.assignedTo\n if (claimant && claimant !== userId) {\n throw new UserTaskError(\n 'Task is assigned to another user',\n 'TASK_ASSIGNED_TO_ANOTHER_USER',\n { taskId, assignedTo: claimant }\n )\n }\n\n // Validate form data against schema (simple validation for MVP)\n // In Phase 7, we'll add comprehensive JSON Schema validation\n if (task.formSchema) {\n try {\n validateFormData(formData, task.formSchema)\n } catch (error) {\n throw new UserTaskError(\n error instanceof Error ? error.message : 'Form validation failed',\n 'FORM_VALIDATION_FAILED',\n { taskId, formSchema: task.formSchema, formData }\n )\n }\n }\n\n // Resolve the pressed decision BEFORE anything is mutated: an unknown\n // decision id must leave the task untouched rather than complete it down the\n // default route. The list is re-resolved from the instance's pinned\n // definition, so it is exactly the list the assignee was shown.\n const chosenDecision = decisionId\n ? findTaskDecision((await loadTaskDecisionContext(em, task)).decisions, decisionId)\n : null\n\n if (decisionId && !chosenDecision) {\n throw new UserTaskError(\n 'Unknown decision for this task',\n 'UNKNOWN_DECISION',\n { taskId, decisionId }\n )\n }\n\n const instance = await em.findOne(WorkflowInstance, task.workflowInstanceId)\n if (!instance) {\n throw new UserTaskError(\n 'Workflow instance not found',\n 'INSTANCE_NOT_FOUND',\n { workflowInstanceId: task.workflowInstanceId }\n )\n }\n\n if (isRunClosedToUserTasks(instance.status)) {\n throw new UserTaskError(\n 'Workflow is no longer active',\n 'WORKFLOW_NOT_ACTIVE',\n { taskId, workflowInstanceId: instance.id, status: instance.status }\n )\n }\n\n // The chosen decision rides along inside the completion payload the task\n // already persists \u2014 no new column, and downstream route conditions can read\n // it once the payload is merged into the run context.\n const completionData = withRecordedDecision(formData, chosenDecision?.id)\n\n const now = new Date()\n const closed = await em.nativeUpdate(\n UserTask,\n {\n id: taskId,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n status: { $in: ['PENDING', 'IN_PROGRESS'] },\n assignedTo: task.assignedTo ?? null,\n claimedBy: task.claimedBy ?? null,\n },\n {\n status: 'COMPLETED',\n formData: completionData,\n completedBy: userId,\n completedAt: now,\n comments: comments || null,\n updatedAt: now,\n },\n )\n\n if (closed === 0) {\n throw new UserTaskError(\n 'Task not found or already completed',\n 'TASK_NOT_FOUND',\n { taskId }\n )\n }\n\n task.status = 'COMPLETED'\n task.formData = completionData\n task.completedBy = userId\n task.completedAt = now\n task.comments = comments || null\n task.updatedAt = now\n\n await em.flush()\n\n // Branch-scoped completion: when the task belongs to a parallel branch,\n // merge form data into the branch namespace and resume just that branch.\n //\n // The decision is RECORDED here exactly as it is on the main path, but it does\n // not select the route: a branch advances through `resumeBranch` with its own\n // token, and overriding a branch's outgoing route is a parallel-execution\n // change rather than a task-surface one.\n if (task.branchInstanceId) {\n await logWorkflowEvent(em, {\n workflowInstanceId: instance.id,\n stepInstanceId: task.stepInstanceId,\n branchInstanceId: task.branchInstanceId,\n eventType: 'USER_TASK_COMPLETED',\n eventData: {\n taskId: task.id,\n taskName: task.taskName,\n completedBy: userId,\n formData: completionData,\n ...(chosenDecision ? { decisionId: chosenDecision.id } : {}),\n },\n userId,\n tenantId: instance.tenantId,\n organizationId: instance.organizationId,\n })\n\n const { resumeBranch } = await import('./parallel-handler')\n const resumed = await resumeBranch(em, {\n instanceId: instance.id,\n branchInstanceId: task.branchInstanceId,\n tenantId: instance.tenantId,\n organizationId: instance.organizationId,\n contextMerge: completionData,\n exitStepInstanceId: task.stepInstanceId,\n exitOutput: { userTaskId: task.id, formData: completionData },\n })\n\n if (resumed) {\n await executeWorkflow(em, container, instance.id, { userId })\n }\n return\n }\n\n // Merge form data into workflow context\n instance.context = {\n ...instance.context,\n ...completionData,\n }\n instance.updatedAt = now\n\n // Log USER_TASK_COMPLETED event\n await logWorkflowEvent(em, {\n workflowInstanceId: instance.id,\n stepInstanceId: task.stepInstanceId,\n eventType: 'USER_TASK_COMPLETED',\n eventData: {\n taskId: task.id,\n taskName: task.taskName,\n completedBy: userId,\n formData: completionData,\n ...(chosenDecision ? { decisionId: chosenDecision.id } : {}),\n },\n userId,\n tenantId: instance.tenantId,\n organizationId: instance.organizationId,\n })\n\n // Mark the step instance as completed\n const stepInstance = await em.findOne(StepInstance, {\n id: task.stepInstanceId,\n status: 'ACTIVE',\n })\n\n if (stepInstance) {\n await stepHandler.exitStep(em, stepInstance, { userTaskId: task.id, formData: completionData })\n }\n\n // Find the next automatic transition from the current step\n const currentStepId = instance.currentStepId\n\n // Load workflow definition to find transitions\n const definition = await findDefinitionForInstance(em, instance)\n\n if (!definition) {\n throw new UserTaskError(\n 'Workflow definition not found',\n 'DEFINITION_NOT_FOUND',\n { definitionId: instance.definitionId }\n )\n }\n\n const transitionContext = {\n workflowContext: instance.context,\n userId,\n }\n\n // A decision names the route to take. It is bound to the transition's durable\n // id, so it survives every route reorder, and it is looked up among the routes\n // LEAVING this step only \u2014 a button can never send the run down a route that\n // does not start where the run currently is. A decision whose route no longer\n // exists there falls through to the default evaluation rather than stranding\n // the run at a step it already completed.\n const decisionTransition = chosenDecision\n ? findTaskDecisionTransition(\n definition.definition.transitions || [],\n chosenDecision.transitionId,\n currentStepId\n )\n : null\n\n if (chosenDecision && !decisionTransition) {\n logger.warn('Task decision route not found on the current step; falling back to auto routing', {\n component: 'task-handler',\n taskId: task.id,\n decisionId: chosenDecision.id,\n transitionId: chosenDecision.transitionId,\n currentStepId,\n })\n }\n\n let selectedTransition = decisionTransition ?? null\n let targetStepId = selectedTransition?.toStepId ?? null\n\n if (!targetStepId) {\n // Find automatic transitions from current step\n const autoTransitions = (definition.definition.transitions || []).filter(\n (t: any) => t.fromStepId === currentStepId && t.trigger === 'auto'\n )\n\n if (autoTransitions.length === 0) {\n // No automatic transitions, workflow stays paused at current step\n return\n }\n\n // Find valid transitions using transition handler\n const validTransitions = await transitionHandler.findValidTransitions(\n em,\n instance,\n currentStepId,\n transitionContext\n )\n\n const firstValidTransition = validTransitions.find(t => t.isValid)\n\n if (!firstValidTransition || !firstValidTransition.transition) {\n // Resume workflow execution anyway, maybe conditions will be met later\n instance.status = 'RUNNING'\n await em.flush()\n return\n }\n\n targetStepId = firstValidTransition.transition.toStepId\n selectedTransition = firstValidTransition.transition\n }\n\n // Resume from the paused wait BEFORE executing the transition, exactly as\n // `sendSignal` does. Without it the executor's defense-in-depth PAUSED check\n // stops the run at the first step the completion traverses, so the instance\n // sits there as PAUSED and never reaches END. Guarded on PAUSED so completing\n // a stale task can never resurrect a CANCELLED or terminal run.\n if (instance.status === 'PAUSED') {\n instance.status = 'RUNNING'\n await em.flush()\n }\n\n // Execute the transition to move to next step\n\n const transitionResult = await transitionHandler.executeTransition(\n em,\n container,\n instance,\n currentStepId,\n targetStepId,\n { ...transitionContext, transitionId: selectedTransition?.transitionId },\n )\n\n if (!transitionResult.success) {\n const failure = await handleTransitionFailure(em, container, instance, transitionResult, {\n evalContext: transitionContext,\n fromStepId: currentStepId,\n toStepId: targetStepId,\n source: 'task-completion',\n })\n if (failure.kind === 'failed' || failure.kind === 'parked') return\n }\n\n // Now continue workflow execution from the new step\n await executeWorkflow(em, container, instance.id, { userId })\n}\n\n/**\n * Whether the caller belongs to at least one of the task's queues.\n *\n * Exact string equality on role NAMES \u2014 no case folding and no trimming, because\n * the names on both sides come from the same tenant role table and normalizing\n * one side would let `Approver` claim an `approver` queue that RBAC treats as a\n * different role.\n */\nfunction hasRoleOverlap(\n taskRoles: readonly string[],\n callerRoleNames: readonly string[],\n): boolean {\n if (callerRoleNames.length === 0) return false\n const held = new Set(callerRoleNames)\n return taskRoles.some((role) => held.has(role))\n}\n\n/**\n * Claim a user task from a role queue\n *\n * Allows a user to claim a task that's assigned to their role(s).\n *\n * The claim itself is a COMPARE-AND-SET, not a read-then-write: the lookup\n * below only decides which error to report, while the row is taken with a\n * conditional `UPDATE \u2026 WHERE status = 'PENDING' AND claimed_by IS NULL`. Two\n * callers racing for the same task \u2014 which is exactly what the work inbox's\n * claim-next affordance produces \u2014 therefore cannot both win; the loser sees\n * zero affected rows and the same `TASK_NOT_FOUND` it would have seen a moment\n * later. Reading the status and flushing the entity afterwards would have let\n * both transactions read `PENDING` and both write.\n *\n * Membership in the queue is a REQUIREMENT, not a hint: a caller who holds none\n * of `assignedToRoles` is refused with the same `TASK_NOT_FOUND` a nonexistent\n * id produces, so a queue the caller does not belong to is indistinguishable\n * from a task that is not there. Holding `workflows.tasks.claim` admits you to\n * the endpoint; it does not admit you to somebody else's queue.\n *\n * `assignedToRoles` and `callerRoleNames` are both role NAMES \u2014 the Studio\n * picker writes names, the engine copies them onto the task, and `auth.roles`\n * carries names. A role RENAME therefore orphans existing assignments; moving\n * the comparison onto immutable role ids is a coordinated data + authored-\n * definition migration and is deliberately not done here.\n *\n * @param em - Entity manager\n * @param taskId - Task ID to claim\n * @param userId - User claiming the task\n * @param scope - Tenant/organization the caller acts within; both the lookup and\n * the conditional update filter on it, so a task belonging to another tenant\n * is never reachable and never writable\n * @param callerRoleNames - Server-derived role names of the caller (`auth.roles`),\n * never client-supplied. Required rather than optional so a caller that cannot\n * supply them fails to compile instead of silently claiming any queue.\n * @throws UserTaskError if task cannot be claimed\n */\nexport async function claimUserTask(\n em: EntityManager,\n taskId: string,\n userId: string,\n scope: UserTaskScope,\n callerRoleNames: readonly string[]\n): Promise<void> {\n const task = await em.findOne(UserTask, {\n id: taskId,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n status: 'PENDING',\n })\n\n if (!task) {\n throw new UserTaskError(\n 'Task not found or already claimed',\n 'TASK_NOT_FOUND',\n { taskId }\n )\n }\n\n if (task.assignedTo) {\n throw new UserTaskError(\n 'Task is already assigned to a specific user',\n 'TASK_ALREADY_ASSIGNED',\n { taskId, assignedTo: task.assignedTo }\n )\n }\n\n if (!task.assignedToRoles || task.assignedToRoles.length === 0) {\n throw new UserTaskError(\n 'Task is not assigned to any roles',\n 'TASK_NOT_ROLE_ASSIGNED',\n { taskId }\n )\n }\n\n if (!hasRoleOverlap(task.assignedToRoles, callerRoleNames)) {\n throw new UserTaskError(\n 'Task not found or already claimed',\n 'TASK_NOT_FOUND',\n { taskId }\n )\n }\n\n const now = new Date()\n const claimed = await em.nativeUpdate(\n UserTask,\n {\n id: taskId,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n status: 'PENDING',\n claimedBy: null,\n },\n {\n claimedBy: userId,\n claimedAt: now,\n status: 'IN_PROGRESS',\n updatedAt: now,\n },\n )\n\n if (claimed === 0) {\n throw new UserTaskError(\n 'Task not found or already claimed',\n 'TASK_NOT_FOUND',\n { taskId }\n )\n }\n\n // The conditional update above already wrote the row; mirroring it onto the\n // managed entity keeps the caller's identity-mapped copy from reporting the\n // pre-claim state back to the client.\n task.claimedBy = userId\n task.claimedAt = now\n task.status = 'IN_PROGRESS'\n task.updatedAt = now\n\n await em.flush()\n\n // Log event\n const instance = await em.findOne(WorkflowInstance, task.workflowInstanceId)\n if (instance) {\n await logWorkflowEvent(em, {\n workflowInstanceId: instance.id,\n stepInstanceId: task.stepInstanceId,\n eventType: 'USER_TASK_STARTED',\n eventData: {\n taskId: task.id,\n taskName: task.taskName,\n claimedBy: userId,\n },\n userId,\n tenantId: instance.tenantId,\n organizationId: instance.organizationId,\n })\n }\n}\n\n/**\n * Release a claimed task back to its role queue.\n *\n * The counterpart of `claimUserTask`, and deliberately its mirror image: the\n * write is the same compare-and-set, guarded on the caller still being the\n * claimant, so a task reassigned or completed in the meantime is refused rather\n * than silently reopened. It uses the EXISTING statuses \u2014 the row goes back to\n * `PENDING` \u2014 because adding a `UserTaskStatus` value is an Ask-First\n * state-machine change and a released task is exactly as pending as it was\n * before anyone claimed it.\n *\n * @throws UserTaskError if the task is not the caller's to release\n */\nexport async function releaseUserTask(\n em: EntityManager,\n taskId: string,\n userId: string,\n scope: UserTaskScope\n): Promise<void> {\n const task = await em.findOne(UserTask, {\n id: taskId,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n status: 'IN_PROGRESS',\n })\n\n if (!task) {\n throw new UserTaskError(\n 'Task not found or not claimed',\n 'TASK_NOT_FOUND',\n { taskId }\n )\n }\n\n if (task.claimedBy !== userId) {\n throw new UserTaskError(\n 'Task is claimed by another user',\n 'TASK_ASSIGNED_TO_ANOTHER_USER',\n { taskId, claimedBy: task.claimedBy }\n )\n }\n\n const now = new Date()\n const released = await em.nativeUpdate(\n UserTask,\n {\n id: taskId,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n status: 'IN_PROGRESS',\n claimedBy: userId,\n },\n {\n claimedBy: null,\n claimedAt: null,\n status: 'PENDING',\n updatedAt: now,\n },\n )\n\n if (released === 0) {\n throw new UserTaskError(\n 'Task not found or not claimed',\n 'TASK_NOT_FOUND',\n { taskId }\n )\n }\n\n task.claimedBy = null\n task.claimedAt = null\n task.status = 'PENDING'\n task.updatedAt = now\n\n await em.flush()\n\n const instance = await em.findOne(WorkflowInstance, task.workflowInstanceId)\n if (instance) {\n await logWorkflowEvent(em, {\n workflowInstanceId: instance.id,\n stepInstanceId: task.stepInstanceId,\n eventType: 'USER_TASK_RELEASED',\n eventData: {\n taskId: task.id,\n taskName: task.taskName,\n releasedBy: userId,\n },\n userId,\n tenantId: instance.tenantId,\n organizationId: instance.organizationId,\n })\n }\n}\n\n// ============================================================================\n// User Task Reassignment\n// ============================================================================\n\n/**\n * The new owner of a task, as the reassign route resolved it.\n *\n * At least one of the two must be non-empty, and the route enforces it: the\n * shape \u00A76.4 makes uncompletable is precisely \"no assignee AND no role queue\",\n * so a reassignment that produced it would be the one write that can create the\n * problem reassignment exists to fix.\n */\nexport interface ReassignUserTaskTarget {\n assignedTo?: string | null\n assignedToRoles?: readonly string[] | null\n}\n\nexport interface ReassignUserTaskOptions {\n taskId: string\n /** Who performed the reassignment \u2014 recorded on `reassigned_by`. */\n userId: string\n target: ReassignUserTaskTarget\n reason?: string | null\n scope: UserTaskScope\n}\n\n/**\n * Statuses a task can be reassigned in.\n *\n * The same pair `completeUserTask` accepts: moving a COMPLETED or CANCELLED row\n * to somebody else records an audit trail for work that can never be done, and\n * the assignee would be handed a task whose Complete button always fails.\n */\nconst REASSIGNABLE_STATUSES: readonly string[] = ['PENDING', 'IN_PROGRESS']\n\n/**\n * Move a task to a different assignee or role queue, with an audit trail.\n *\n * This is the ACT half of the \u00A76.4 model's central asymmetry: administration\n * widens seeing, never acting, so an administrator who can see a colleague's\n * task \u2014 or a task that belongs to nobody at all \u2014 takes it first and the taking\n * is permanently recorded. It is also the documented remedy for the one shape\n * the model leaves uncompletable (no assignee, no claim, no role queue), which\n * is why it deliberately accepts a task in exactly that state.\n *\n * No new `UserTaskStatus` value is introduced. The audit lives on the columns\n * Phase 4a added (`reassigned_by` / `reassigned_at` / `reassign_reason`) plus a\n * `WorkflowEvent`, and a reassigned task is exactly as pending or in-progress as\n * it was \u2014 the same choice `releaseUserTask` made, and the one Phase 3a's\n * failure queue made when it reused `PAUSED` plus a marker.\n *\n * An in-flight CLAIM is always released. Handing a row to somebody else while a\n * colleague still holds it would leave `claimedBy ?? assignedTo` naming the old\n * claimant, so the predicate would keep treating the task as theirs and the new\n * assignee could not act on what they were just given.\n *\n * @throws UserTaskError when the task is absent from the caller's scope or is\n * in a terminal status\n */\nexport async function reassignUserTask(\n em: EntityManager,\n options: ReassignUserTaskOptions,\n): Promise<UserTask> {\n const { taskId, userId, target, reason, scope } = options\n\n const task = await em.findOne(UserTask, {\n id: taskId,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n })\n\n if (!task) {\n throw new UserTaskError('Task not found', 'TASK_NOT_FOUND', { taskId })\n }\n\n if (!REASSIGNABLE_STATUSES.includes(task.status)) {\n throw new UserTaskError(\n 'Task is no longer open and cannot be reassigned',\n 'TASK_NOT_REASSIGNABLE',\n { taskId, status: task.status },\n )\n }\n\n const assignedTo = target.assignedTo ?? null\n const assignedToRoles =\n target.assignedToRoles && target.assignedToRoles.length > 0 ? [...target.assignedToRoles] : null\n\n const previous = {\n assignedTo: task.assignedTo ?? null,\n assignedToRoles: task.assignedToRoles ?? null,\n claimedBy: task.claimedBy ?? null,\n }\n\n const now = new Date()\n\n task.assignedTo = assignedTo\n // Reassignment is a backoffice administration act and its target is resolved\n // from the tenant's user/role vocabulary, so the row lands in the backoffice\n // namespace. Portal reassignment would need a portal principal picker and is\n // not part of this surface.\n task.assigneeKind = 'user'\n task.assignedToRoles = assignedToRoles\n task.claimedBy = null\n task.claimedAt = null\n // A queued task must be PENDING to be claimable, and a task whose claim was\n // just released is exactly as pending as it was before anyone claimed it.\n if (task.status === 'IN_PROGRESS') task.status = 'PENDING'\n task.reassignedBy = userId\n task.reassignedAt = now\n task.reassignReason = reason ?? null\n task.updatedAt = now\n\n await em.flush()\n\n const instance = await em.findOne(WorkflowInstance, task.workflowInstanceId)\n if (instance) {\n await logWorkflowEvent(em, {\n workflowInstanceId: instance.id,\n stepInstanceId: task.stepInstanceId,\n branchInstanceId: task.branchInstanceId ?? null,\n eventType: 'USER_TASK_REASSIGNED',\n eventData: {\n taskId: task.id,\n taskName: task.taskName,\n reassignedBy: userId,\n reason: reason ?? null,\n from: previous,\n to: { assignedTo, assignedToRoles },\n },\n userId,\n tenantId: instance.tenantId,\n organizationId: instance.organizationId,\n })\n }\n\n return task\n}\n\n// ============================================================================\n// Helper Functions\n// ============================================================================\n\n/**\n * Log workflow event to event sourcing table\n */\nasync function logWorkflowEvent(\n em: EntityManager,\n event: {\n workflowInstanceId: string\n stepInstanceId: string | null\n branchInstanceId?: string | null\n eventType: string\n eventData: any\n userId?: string\n tenantId: string\n organizationId: string\n }\n): Promise<WorkflowEvent> {\n const workflowEvent = em.create(WorkflowEvent, {\n ...event,\n occurredAt: new Date(),\n })\n\n await em.persist(workflowEvent).flush()\n return workflowEvent\n}\n\n/**\n * Validate form data against the task's authored schema.\n *\n * Required-field presence in BOTH accepted `formSchema` shapes: the JSON-Schema\n * form and the `{ fields: [...] }` form the Studio writes, whose per-field\n * `required: true` flag this used to ignore entirely \u2014 so a task authored in\n * the visual editor validated nothing however many fields its author marked\n * mandatory. Both shapes now resolve through `lib/task-form-schema.ts`, the\n * same module the renderer walks, so they cannot drift apart again.\n *\n * Presence-only, deliberately: type checking would need the full JSON-Schema\n * vocabulary, and what matters is that a required field cannot be skipped.\n *\n * @param formData - User-provided form data\n * @param formSchema - Authored schema, in either accepted shape\n * @throws Error if validation fails\n */\nexport function validateFormData(\n formData: Record<string, any>,\n formSchema: unknown\n): void {\n for (const field of readRequiredFormFields(formSchema)) {\n if (!(field in formData) || formData[field] === null || formData[field] === undefined) {\n throw new Error(`Required field missing: ${field}`)\n }\n }\n}\n"],
|
|
5
|
-
"mappings": "AAcA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,iBAAiB,+BAA+B;AACzD,SAAS,iCAAiC;AAC1C;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,+B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K;AAAA,QACf,cAAc;AAAA,QACd,QAAQ,UAAU;AAAA,QAClB,MAAM;AAAA,QACN,IAAI,EAAE,YAAY,gBAAgB;AAAA,MACpC;AAAA,MACA;AAAA,MACA,UAAU,SAAS;AAAA,MACnB,gBAAgB,SAAS;AAAA,IAC3B,CAAC;AAAA,EACH;AAEA,SAAO;AACT;AASA,eAAe,iBACb,IACA,OAUwB;AACxB,QAAM,gBAAgB,GAAG,OAAO,eAAe;AAAA,IAC7C,GAAG;AAAA,IACH,YAAY,oBAAI,KAAK;AAAA,EACvB,CAAC;AAED,QAAM,GAAG,QAAQ,aAAa,EAAE,MAAM;AACtC,SAAO;AACT;AAmBO,SAAS,iBACd,UACA,YACM;AACN,aAAW,SAAS,uBAAuB,UAAU,GAAG;AACtD,QAAI,EAAE,SAAS,aAAa,SAAS,KAAK,MAAM,QAAQ,SAAS,KAAK,MAAM,QAAW;AACrF,YAAM,IAAI,MAAM,2BAA2B,KAAK,EAAE;AAAA,IACpD;AAAA,EACF;AACF;",
|
|
4
|
+
"sourcesContent": ["/**\n * Workflows Module - User Task Handler Service\n *\n * Handles user task lifecycle operations:\n * - Completing user tasks\n * - Claiming tasks from role queues\n * - Reassigning tasks\n * - Escalating overdue tasks\n *\n * Functional API (no classes) following Open Mercato conventions.\n */\n\nimport { EntityManager } from '@mikro-orm/core'\nimport type { AwilixContainer } from 'awilix'\nimport {\n UserTask,\n WorkflowInstance,\n WorkflowEvent,\n StepInstance,\n} from '../data/entities'\nimport { executeWorkflow, handleTransitionFailure } from './workflow-executor'\nimport { findDefinitionForInstance } from './find-definition'\nimport {\n findTaskDecision,\n findTaskDecisionTransition,\n withRecordedDecision,\n} from './task-decisions'\nimport { loadTaskDecisionContext } from './task-decision-context'\nimport { readRequiredFormFields } from './task-form-schema'\nimport { isRunClosedToUserTasks } from './instance-status'\nimport * as stepHandler from './step-handler'\nimport * as transitionHandler from './transition-handler'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('workflows')\n\n// ============================================================================\n// Types and Interfaces\n// ============================================================================\n\n/**\n * Tenant/organization the caller is acting within. Every task lookup filters on\n * it, so a task id from another tenant resolves to \"not found\" instead of being\n * mutated.\n */\nexport interface UserTaskScope {\n tenantId: string\n organizationId: string\n}\n\n/**\n * Shape of the `taskHandler` DI registration (`di.ts`).\n *\n * The functions below stay exported \u2014 third-party modules may import them and\n * `BACKWARD_COMPATIBILITY.md` \u00A73 freezes import paths \u2014 but callers inside the\n * platform MUST resolve this service instead, per the module's first rule.\n */\nexport interface TaskHandlerService {\n completeUserTask: typeof completeUserTask\n claimUserTask: typeof claimUserTask\n releaseUserTask: typeof releaseUserTask\n reassignUserTask: typeof reassignUserTask\n}\n\nexport interface CompleteUserTaskOptions {\n taskId: string\n formData: Record<string, any>\n userId: string\n comments?: string\n /**\n * The decision button the assignee pressed, when the step authored any.\n *\n * It does two things: it SELECTS the outgoing route (the decision's\n * `transitionId` wins over the first-valid-transition default), and it is\n * RECORDED as part of the completion payload. Omitted, completion behaves\n * exactly as it always did.\n */\n decisionId?: string\n scope: UserTaskScope\n}\n\nexport class UserTaskError extends Error {\n constructor(\n message: string,\n public code: string,\n public details?: any\n ) {\n super(message)\n this.name = 'UserTaskError'\n }\n}\n\n// ============================================================================\n// User Task Completion\n// ============================================================================\n\n/**\n * Complete a user task and resume workflow execution\n *\n * This function:\n * 1. Validates the task exists and can be completed\n * 2. Updates the task with form data and completion info\n * 3. Merges form data into workflow context\n * 4. Logs completion event\n * 5. Resumes workflow execution\n *\n * Closing the task is a COMPARE-AND-SET, like `claimUserTask`: the lookup only\n * decides which error to report, while the row is closed with a conditional\n * `UPDATE \u2026 WHERE status IN ('PENDING', 'IN_PROGRESS')`. Two submissions of the\n * same task (the task page and a notification quick action, two tabs, a client\n * retrying after a timeout) can both pass the lookup; only one closes the row,\n * and the other gets the same `TASK_NOT_FOUND` a later submission would, before\n * any event is logged or the run is advanced.\n *\n * @param em - Entity manager\n * @param container - DI container for workflow execution\n * @param options - Task completion options\n * @throws UserTaskError if task not found or validation fails\n */\nexport async function completeUserTask(\n em: EntityManager,\n container: AwilixContainer,\n options: CompleteUserTaskOptions\n): Promise<void> {\n const { taskId, formData, userId, comments, decisionId, scope } = options\n\n // Fetch task\n const task = await em.findOne(UserTask, {\n id: taskId,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n status: { $in: ['PENDING', 'IN_PROGRESS'] },\n })\n\n if (!task) {\n throw new UserTaskError(\n 'Task not found or already completed',\n 'TASK_NOT_FOUND',\n { taskId }\n )\n }\n\n // A task addressed to one person is that person's to finish. Tasks that name\n // nobody \u2014 agent dispositions, role queues nobody has claimed \u2014 stay open to\n // anyone the route's feature gate already admitted, so this narrows the\n // over-permissive case without stranding the unassigned ones.\n const claimant = task.claimedBy ?? task.assignedTo\n if (claimant && claimant !== userId) {\n throw new UserTaskError(\n 'Task is assigned to another user',\n 'TASK_ASSIGNED_TO_ANOTHER_USER',\n { taskId, assignedTo: claimant }\n )\n }\n\n // Validate form data against schema (simple validation for MVP)\n // In Phase 7, we'll add comprehensive JSON Schema validation\n if (task.formSchema) {\n try {\n validateFormData(formData, task.formSchema)\n } catch (error) {\n throw new UserTaskError(\n error instanceof Error ? error.message : 'Form validation failed',\n 'FORM_VALIDATION_FAILED',\n { taskId, formSchema: task.formSchema, formData }\n )\n }\n }\n\n // Resolve the pressed decision BEFORE anything is mutated: an unknown\n // decision id must leave the task untouched rather than complete it down the\n // default route. The list is re-resolved from the instance's pinned\n // definition, so it is exactly the list the assignee was shown.\n const chosenDecision = decisionId\n ? findTaskDecision((await loadTaskDecisionContext(em, task)).decisions, decisionId)\n : null\n\n if (decisionId && !chosenDecision) {\n throw new UserTaskError(\n 'Unknown decision for this task',\n 'UNKNOWN_DECISION',\n { taskId, decisionId }\n )\n }\n\n const instance = await em.findOne(WorkflowInstance, task.workflowInstanceId)\n if (!instance) {\n throw new UserTaskError(\n 'Workflow instance not found',\n 'INSTANCE_NOT_FOUND',\n { workflowInstanceId: task.workflowInstanceId }\n )\n }\n\n if (isRunClosedToUserTasks(instance.status)) {\n throw new UserTaskError(\n 'Workflow is no longer active',\n 'WORKFLOW_NOT_ACTIVE',\n { taskId, workflowInstanceId: instance.id, status: instance.status }\n )\n }\n\n // The chosen decision rides along inside the completion payload the task\n // already persists \u2014 no new column, and downstream route conditions can read\n // it once the payload is merged into the run context.\n const completionData = withRecordedDecision(formData, chosenDecision?.id)\n\n const now = new Date()\n const closed = await em.nativeUpdate(\n UserTask,\n {\n id: taskId,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n status: { $in: ['PENDING', 'IN_PROGRESS'] },\n assignedTo: task.assignedTo ?? null,\n claimedBy: task.claimedBy ?? null,\n },\n {\n status: 'COMPLETED',\n formData: completionData,\n completedBy: userId,\n completedAt: now,\n comments: comments || null,\n updatedAt: now,\n },\n )\n\n if (closed === 0) {\n throw new UserTaskError(\n 'Task not found or already completed',\n 'TASK_NOT_FOUND',\n { taskId }\n )\n }\n\n task.status = 'COMPLETED'\n task.formData = completionData\n task.completedBy = userId\n task.completedAt = now\n task.comments = comments || null\n task.updatedAt = now\n\n await em.flush()\n\n // Branch-scoped completion: when the task belongs to a parallel branch,\n // merge form data into the branch namespace and resume just that branch.\n //\n // The decision is RECORDED here exactly as it is on the main path, but it does\n // not select the route: a branch advances through `resumeBranch` with its own\n // token, and overriding a branch's outgoing route is a parallel-execution\n // change rather than a task-surface one.\n if (task.branchInstanceId) {\n await logWorkflowEvent(em, {\n workflowInstanceId: instance.id,\n stepInstanceId: task.stepInstanceId,\n branchInstanceId: task.branchInstanceId,\n eventType: 'USER_TASK_COMPLETED',\n eventData: {\n taskId: task.id,\n taskName: task.taskName,\n completedBy: userId,\n formData: completionData,\n ...(chosenDecision ? { decisionId: chosenDecision.id } : {}),\n },\n userId,\n tenantId: instance.tenantId,\n organizationId: instance.organizationId,\n })\n\n const { resumeBranch } = await import('./parallel-handler')\n const resumed = await resumeBranch(em, {\n instanceId: instance.id,\n branchInstanceId: task.branchInstanceId,\n tenantId: instance.tenantId,\n organizationId: instance.organizationId,\n contextMerge: completionData,\n exitStepInstanceId: task.stepInstanceId,\n exitOutput: { userTaskId: task.id, formData: completionData },\n })\n\n if (resumed) {\n await executeWorkflow(em, container, instance.id, { userId })\n }\n return\n }\n\n // Merge form data into workflow context\n instance.context = {\n ...instance.context,\n ...completionData,\n }\n instance.updatedAt = now\n\n // Log USER_TASK_COMPLETED event\n await logWorkflowEvent(em, {\n workflowInstanceId: instance.id,\n stepInstanceId: task.stepInstanceId,\n eventType: 'USER_TASK_COMPLETED',\n eventData: {\n taskId: task.id,\n taskName: task.taskName,\n completedBy: userId,\n formData: completionData,\n ...(chosenDecision ? { decisionId: chosenDecision.id } : {}),\n },\n userId,\n tenantId: instance.tenantId,\n organizationId: instance.organizationId,\n })\n\n // Mark the step instance as completed\n const stepInstance = await em.findOne(StepInstance, {\n id: task.stepInstanceId,\n status: 'ACTIVE',\n })\n\n if (stepInstance) {\n await stepHandler.exitStep(em, stepInstance, { userTaskId: task.id, formData: completionData })\n }\n\n // Find the next automatic transition from the current step\n const currentStepId = instance.currentStepId\n\n // Load workflow definition to find transitions\n const definition = await findDefinitionForInstance(em, instance)\n\n if (!definition) {\n throw new UserTaskError(\n 'Workflow definition not found',\n 'DEFINITION_NOT_FOUND',\n { definitionId: instance.definitionId }\n )\n }\n\n const transitionContext = {\n container,\n workflowContext: instance.context,\n userId,\n }\n\n // A decision names the route to take. It is bound to the transition's durable\n // id, so it survives every route reorder, and it is looked up among the routes\n // LEAVING this step only \u2014 a button can never send the run down a route that\n // does not start where the run currently is. A decision whose route no longer\n // exists there falls through to the default evaluation rather than stranding\n // the run at a step it already completed.\n const decisionTransition = chosenDecision\n ? findTaskDecisionTransition(\n definition.definition.transitions || [],\n chosenDecision.transitionId,\n currentStepId\n )\n : null\n\n if (chosenDecision && !decisionTransition) {\n logger.warn('Task decision route not found on the current step; falling back to auto routing', {\n component: 'task-handler',\n taskId: task.id,\n decisionId: chosenDecision.id,\n transitionId: chosenDecision.transitionId,\n currentStepId,\n })\n }\n\n let selectedTransition = decisionTransition ?? null\n let targetStepId = selectedTransition?.toStepId ?? null\n\n if (!targetStepId) {\n // Find automatic transitions from current step\n const autoTransitions = (definition.definition.transitions || []).filter(\n (t: any) => t.fromStepId === currentStepId && t.trigger === 'auto'\n )\n\n if (autoTransitions.length === 0) {\n // No automatic transitions, workflow stays paused at current step\n return\n }\n\n // Find valid transitions using transition handler\n const validTransitions = await transitionHandler.findValidTransitions(\n em,\n instance,\n currentStepId,\n transitionContext\n )\n\n const firstValidTransition = validTransitions.find(t => t.isValid)\n\n if (!firstValidTransition || !firstValidTransition.transition) {\n // Resume workflow execution anyway, maybe conditions will be met later\n instance.status = 'RUNNING'\n await em.flush()\n return\n }\n\n targetStepId = firstValidTransition.transition.toStepId\n selectedTransition = firstValidTransition.transition\n }\n\n // Resume from the paused wait BEFORE executing the transition, exactly as\n // `sendSignal` does. Without it the executor's defense-in-depth PAUSED check\n // stops the run at the first step the completion traverses, so the instance\n // sits there as PAUSED and never reaches END. Guarded on PAUSED so completing\n // a stale task can never resurrect a CANCELLED or terminal run.\n if (instance.status === 'PAUSED') {\n instance.status = 'RUNNING'\n await em.flush()\n }\n\n // Execute the transition to move to next step\n\n const transitionResult = await transitionHandler.executeTransition(\n em,\n container,\n instance,\n currentStepId,\n targetStepId,\n { ...transitionContext, transitionId: selectedTransition?.transitionId },\n )\n\n if (!transitionResult.success) {\n const failure = await handleTransitionFailure(em, container, instance, transitionResult, {\n evalContext: transitionContext,\n fromStepId: currentStepId,\n toStepId: targetStepId,\n source: 'task-completion',\n })\n if (failure.kind === 'failed' || failure.kind === 'parked') return\n }\n\n // Now continue workflow execution from the new step\n await executeWorkflow(em, container, instance.id, { userId })\n}\n\n/**\n * Whether the caller belongs to at least one of the task's queues.\n *\n * Exact string equality on role NAMES \u2014 no case folding and no trimming, because\n * the names on both sides come from the same tenant role table and normalizing\n * one side would let `Approver` claim an `approver` queue that RBAC treats as a\n * different role.\n */\nfunction hasRoleOverlap(\n taskRoles: readonly string[],\n callerRoleNames: readonly string[],\n): boolean {\n if (callerRoleNames.length === 0) return false\n const held = new Set(callerRoleNames)\n return taskRoles.some((role) => held.has(role))\n}\n\n/**\n * Claim a user task from a role queue\n *\n * Allows a user to claim a task that's assigned to their role(s).\n *\n * The claim itself is a COMPARE-AND-SET, not a read-then-write: the lookup\n * below only decides which error to report, while the row is taken with a\n * conditional `UPDATE \u2026 WHERE status = 'PENDING' AND claimed_by IS NULL`. Two\n * callers racing for the same task \u2014 which is exactly what the work inbox's\n * claim-next affordance produces \u2014 therefore cannot both win; the loser sees\n * zero affected rows and the same `TASK_NOT_FOUND` it would have seen a moment\n * later. Reading the status and flushing the entity afterwards would have let\n * both transactions read `PENDING` and both write.\n *\n * Membership in the queue is a REQUIREMENT, not a hint: a caller who holds none\n * of `assignedToRoles` is refused with the same `TASK_NOT_FOUND` a nonexistent\n * id produces, so a queue the caller does not belong to is indistinguishable\n * from a task that is not there. Holding `workflows.tasks.claim` admits you to\n * the endpoint; it does not admit you to somebody else's queue.\n *\n * `assignedToRoles` and `callerRoleNames` are both role NAMES \u2014 the Studio\n * picker writes names, the engine copies them onto the task, and `auth.roles`\n * carries names. A role RENAME therefore orphans existing assignments; moving\n * the comparison onto immutable role ids is a coordinated data + authored-\n * definition migration and is deliberately not done here.\n *\n * @param em - Entity manager\n * @param taskId - Task ID to claim\n * @param userId - User claiming the task\n * @param scope - Tenant/organization the caller acts within; both the lookup and\n * the conditional update filter on it, so a task belonging to another tenant\n * is never reachable and never writable\n * @param callerRoleNames - Server-derived role names of the caller (`auth.roles`),\n * never client-supplied. Required rather than optional so a caller that cannot\n * supply them fails to compile instead of silently claiming any queue.\n * @throws UserTaskError if task cannot be claimed\n */\nexport async function claimUserTask(\n em: EntityManager,\n taskId: string,\n userId: string,\n scope: UserTaskScope,\n callerRoleNames: readonly string[]\n): Promise<void> {\n const task = await em.findOne(UserTask, {\n id: taskId,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n status: 'PENDING',\n })\n\n if (!task) {\n throw new UserTaskError(\n 'Task not found or already claimed',\n 'TASK_NOT_FOUND',\n { taskId }\n )\n }\n\n if (task.assignedTo) {\n throw new UserTaskError(\n 'Task is already assigned to a specific user',\n 'TASK_ALREADY_ASSIGNED',\n { taskId, assignedTo: task.assignedTo }\n )\n }\n\n if (!task.assignedToRoles || task.assignedToRoles.length === 0) {\n throw new UserTaskError(\n 'Task is not assigned to any roles',\n 'TASK_NOT_ROLE_ASSIGNED',\n { taskId }\n )\n }\n\n if (!hasRoleOverlap(task.assignedToRoles, callerRoleNames)) {\n throw new UserTaskError(\n 'Task not found or already claimed',\n 'TASK_NOT_FOUND',\n { taskId }\n )\n }\n\n const now = new Date()\n const claimed = await em.nativeUpdate(\n UserTask,\n {\n id: taskId,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n status: 'PENDING',\n claimedBy: null,\n },\n {\n claimedBy: userId,\n claimedAt: now,\n status: 'IN_PROGRESS',\n updatedAt: now,\n },\n )\n\n if (claimed === 0) {\n throw new UserTaskError(\n 'Task not found or already claimed',\n 'TASK_NOT_FOUND',\n { taskId }\n )\n }\n\n // The conditional update above already wrote the row; mirroring it onto the\n // managed entity keeps the caller's identity-mapped copy from reporting the\n // pre-claim state back to the client.\n task.claimedBy = userId\n task.claimedAt = now\n task.status = 'IN_PROGRESS'\n task.updatedAt = now\n\n await em.flush()\n\n // Log event\n const instance = await em.findOne(WorkflowInstance, task.workflowInstanceId)\n if (instance) {\n await logWorkflowEvent(em, {\n workflowInstanceId: instance.id,\n stepInstanceId: task.stepInstanceId,\n eventType: 'USER_TASK_STARTED',\n eventData: {\n taskId: task.id,\n taskName: task.taskName,\n claimedBy: userId,\n },\n userId,\n tenantId: instance.tenantId,\n organizationId: instance.organizationId,\n })\n }\n}\n\n/**\n * Release a claimed task back to its role queue.\n *\n * The counterpart of `claimUserTask`, and deliberately its mirror image: the\n * write is the same compare-and-set, guarded on the caller still being the\n * claimant, so a task reassigned or completed in the meantime is refused rather\n * than silently reopened. It uses the EXISTING statuses \u2014 the row goes back to\n * `PENDING` \u2014 because adding a `UserTaskStatus` value is an Ask-First\n * state-machine change and a released task is exactly as pending as it was\n * before anyone claimed it.\n *\n * @throws UserTaskError if the task is not the caller's to release\n */\nexport async function releaseUserTask(\n em: EntityManager,\n taskId: string,\n userId: string,\n scope: UserTaskScope\n): Promise<void> {\n const task = await em.findOne(UserTask, {\n id: taskId,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n status: 'IN_PROGRESS',\n })\n\n if (!task) {\n throw new UserTaskError(\n 'Task not found or not claimed',\n 'TASK_NOT_FOUND',\n { taskId }\n )\n }\n\n if (task.claimedBy !== userId) {\n throw new UserTaskError(\n 'Task is claimed by another user',\n 'TASK_ASSIGNED_TO_ANOTHER_USER',\n { taskId, claimedBy: task.claimedBy }\n )\n }\n\n const now = new Date()\n const released = await em.nativeUpdate(\n UserTask,\n {\n id: taskId,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n status: 'IN_PROGRESS',\n claimedBy: userId,\n },\n {\n claimedBy: null,\n claimedAt: null,\n status: 'PENDING',\n updatedAt: now,\n },\n )\n\n if (released === 0) {\n throw new UserTaskError(\n 'Task not found or not claimed',\n 'TASK_NOT_FOUND',\n { taskId }\n )\n }\n\n task.claimedBy = null\n task.claimedAt = null\n task.status = 'PENDING'\n task.updatedAt = now\n\n await em.flush()\n\n const instance = await em.findOne(WorkflowInstance, task.workflowInstanceId)\n if (instance) {\n await logWorkflowEvent(em, {\n workflowInstanceId: instance.id,\n stepInstanceId: task.stepInstanceId,\n eventType: 'USER_TASK_RELEASED',\n eventData: {\n taskId: task.id,\n taskName: task.taskName,\n releasedBy: userId,\n },\n userId,\n tenantId: instance.tenantId,\n organizationId: instance.organizationId,\n })\n }\n}\n\n// ============================================================================\n// User Task Reassignment\n// ============================================================================\n\n/**\n * The new owner of a task, as the reassign route resolved it.\n *\n * At least one of the two must be non-empty, and the route enforces it: the\n * shape \u00A76.4 makes uncompletable is precisely \"no assignee AND no role queue\",\n * so a reassignment that produced it would be the one write that can create the\n * problem reassignment exists to fix.\n */\nexport interface ReassignUserTaskTarget {\n assignedTo?: string | null\n assignedToRoles?: readonly string[] | null\n}\n\nexport interface ReassignUserTaskOptions {\n taskId: string\n /** Who performed the reassignment \u2014 recorded on `reassigned_by`. */\n userId: string\n target: ReassignUserTaskTarget\n reason?: string | null\n scope: UserTaskScope\n}\n\n/**\n * Statuses a task can be reassigned in.\n *\n * The same pair `completeUserTask` accepts: moving a COMPLETED or CANCELLED row\n * to somebody else records an audit trail for work that can never be done, and\n * the assignee would be handed a task whose Complete button always fails.\n */\nconst REASSIGNABLE_STATUSES: readonly string[] = ['PENDING', 'IN_PROGRESS']\n\n/**\n * Move a task to a different assignee or role queue, with an audit trail.\n *\n * This is the ACT half of the \u00A76.4 model's central asymmetry: administration\n * widens seeing, never acting, so an administrator who can see a colleague's\n * task \u2014 or a task that belongs to nobody at all \u2014 takes it first and the taking\n * is permanently recorded. It is also the documented remedy for the one shape\n * the model leaves uncompletable (no assignee, no claim, no role queue), which\n * is why it deliberately accepts a task in exactly that state.\n *\n * No new `UserTaskStatus` value is introduced. The audit lives on the columns\n * Phase 4a added (`reassigned_by` / `reassigned_at` / `reassign_reason`) plus a\n * `WorkflowEvent`, and a reassigned task is exactly as pending or in-progress as\n * it was \u2014 the same choice `releaseUserTask` made, and the one Phase 3a's\n * failure queue made when it reused `PAUSED` plus a marker.\n *\n * An in-flight CLAIM is always released. Handing a row to somebody else while a\n * colleague still holds it would leave `claimedBy ?? assignedTo` naming the old\n * claimant, so the predicate would keep treating the task as theirs and the new\n * assignee could not act on what they were just given.\n *\n * @throws UserTaskError when the task is absent from the caller's scope or is\n * in a terminal status\n */\nexport async function reassignUserTask(\n em: EntityManager,\n options: ReassignUserTaskOptions,\n): Promise<UserTask> {\n const { taskId, userId, target, reason, scope } = options\n\n const task = await em.findOne(UserTask, {\n id: taskId,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n })\n\n if (!task) {\n throw new UserTaskError('Task not found', 'TASK_NOT_FOUND', { taskId })\n }\n\n if (!REASSIGNABLE_STATUSES.includes(task.status)) {\n throw new UserTaskError(\n 'Task is no longer open and cannot be reassigned',\n 'TASK_NOT_REASSIGNABLE',\n { taskId, status: task.status },\n )\n }\n\n const assignedTo = target.assignedTo ?? null\n const assignedToRoles =\n target.assignedToRoles && target.assignedToRoles.length > 0 ? [...target.assignedToRoles] : null\n\n const previous = {\n assignedTo: task.assignedTo ?? null,\n assignedToRoles: task.assignedToRoles ?? null,\n claimedBy: task.claimedBy ?? null,\n }\n\n const now = new Date()\n\n task.assignedTo = assignedTo\n // Reassignment is a backoffice administration act and its target is resolved\n // from the tenant's user/role vocabulary, so the row lands in the backoffice\n // namespace. Portal reassignment would need a portal principal picker and is\n // not part of this surface.\n task.assigneeKind = 'user'\n task.assignedToRoles = assignedToRoles\n task.claimedBy = null\n task.claimedAt = null\n // A queued task must be PENDING to be claimable, and a task whose claim was\n // just released is exactly as pending as it was before anyone claimed it.\n if (task.status === 'IN_PROGRESS') task.status = 'PENDING'\n task.reassignedBy = userId\n task.reassignedAt = now\n task.reassignReason = reason ?? null\n task.updatedAt = now\n\n await em.flush()\n\n const instance = await em.findOne(WorkflowInstance, task.workflowInstanceId)\n if (instance) {\n await logWorkflowEvent(em, {\n workflowInstanceId: instance.id,\n stepInstanceId: task.stepInstanceId,\n branchInstanceId: task.branchInstanceId ?? null,\n eventType: 'USER_TASK_REASSIGNED',\n eventData: {\n taskId: task.id,\n taskName: task.taskName,\n reassignedBy: userId,\n reason: reason ?? null,\n from: previous,\n to: { assignedTo, assignedToRoles },\n },\n userId,\n tenantId: instance.tenantId,\n organizationId: instance.organizationId,\n })\n }\n\n return task\n}\n\n// ============================================================================\n// Helper Functions\n// ============================================================================\n\n/**\n * Log workflow event to event sourcing table\n */\nasync function logWorkflowEvent(\n em: EntityManager,\n event: {\n workflowInstanceId: string\n stepInstanceId: string | null\n branchInstanceId?: string | null\n eventType: string\n eventData: any\n userId?: string\n tenantId: string\n organizationId: string\n }\n): Promise<WorkflowEvent> {\n const workflowEvent = em.create(WorkflowEvent, {\n ...event,\n occurredAt: new Date(),\n })\n\n await em.persist(workflowEvent).flush()\n return workflowEvent\n}\n\n/**\n * Validate form data against the task's authored schema.\n *\n * Required-field presence in BOTH accepted `formSchema` shapes: the JSON-Schema\n * form and the `{ fields: [...] }` form the Studio writes, whose per-field\n * `required: true` flag this used to ignore entirely \u2014 so a task authored in\n * the visual editor validated nothing however many fields its author marked\n * mandatory. Both shapes now resolve through `lib/task-form-schema.ts`, the\n * same module the renderer walks, so they cannot drift apart again.\n *\n * Presence-only, deliberately: type checking would need the full JSON-Schema\n * vocabulary, and what matters is that a required field cannot be skipped.\n *\n * @param formData - User-provided form data\n * @param formSchema - Authored schema, in either accepted shape\n * @throws Error if validation fails\n */\nexport function validateFormData(\n formData: Record<string, any>,\n formSchema: unknown\n): void {\n for (const field of readRequiredFormFields(formSchema)) {\n if (!(field in formData) || formData[field] === null || formData[field] === undefined) {\n throw new Error(`Required field missing: ${field}`)\n }\n }\n}\n"],
|
|
5
|
+
"mappings": "AAcA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,iBAAiB,+BAA+B;AACzD,SAAS,iCAAiC;AAC1C;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,+BAA+B;AACxC,SAAS,8BAA8B;AACvC,SAAS,8BAA8B;AACvC,YAAY,iBAAiB;AAC7B,YAAY,uBAAuB;AACnC,SAAS,oBAAoB;AAE7B,MAAM,SAAS,aAAa,WAAW;AA+ChC,MAAM,sBAAsB,MAAM;AAAA,EACvC,YACE,SACO,MACA,SACP;AACA,UAAM,OAAO;AAHN;AACA;AAGP,SAAK,OAAO;AAAA,EACd;AACF;AA6BA,eAAsB,iBACpB,IACA,WAC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AAe;AAAA,IAC7C,GAAG;AAAA,IACH,YAAY,oBAAI,KAAK;AAAA,EACvB,CAAC;AAED,QAAM,GAAG,QAAQ,aAAa,EAAE,MAAM;AACtC,SAAO;AACT;AAmBO,SAAS,iBACd,UACA,YACM;AACN,aAAW,SAAS,uBAAuB,UAAU,GAAG;AACtD,QAAI,EAAE,SAAS,aAAa,SAAS,KAAK,MAAM,QAAQ,SAAS,KAAK,MAAM,QAAW;AACrF,YAAM,IAAI,MAAM,2BAA2B,KAAK,EAAE;AAAA,IACpD;AAAA,EACF;AACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/modules/workflows/lib/timer-handler.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * Timer Handler Service\n *\n * Fires timers for WAIT_FOR_TIMER steps: resumes a paused workflow instance\n * when its scheduled timer job is processed by the activity worker.\n */\n\nimport { EntityManager } from '@mikro-orm/core'\nimport type { EntityManager as PostgreSqlEntityManager } from '@mikro-orm/postgresql'\nimport type { AwilixContainer } from 'awilix'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { WorkflowInstance, WorkflowDefinition, StepInstance } from '../data/entities'\nimport type * as eventLoggerModule from './event-logger'\nimport type * as stepHandlerModule from './step-handler'\nimport type * as transitionHandlerModule from './transition-handler'\nimport type * as workflowExecutorModule from './workflow-executor'\nimport { resolveCodeDefinitionForInstance } from './find-definition'\n\nexport interface FireTimerOptions {\n instanceId: string\n stepInstanceId?: string\n branchInstanceId?: string | null\n userId?: string\n tenantId: string\n organizationId: string\n}\n\nexport class TimerError extends Error {\n constructor(\n message: string,\n public code: string,\n public details?: any\n ) {\n super(message)\n this.name = 'TimerError'\n }\n}\n\n/**\n * Fire a timer and resume workflow execution.\n *\n * Mirrors `sendSignal` from signal-handler.ts \u2014 verifies the instance is\n * paused at a WAIT_FOR_TIMER step, logs TIMER_FIRED, exits the step, then\n * executes auto transitions and resumes the workflow.\n */\nexport async function fireTimer(\n em: EntityManager,\n container: AwilixContainer,\n options: FireTimerOptions\n): Promise<void> {\n const { instanceId, stepInstanceId, branchInstanceId, userId, tenantId, organizationId } = options\n\n const eventLogger = container.resolve<typeof eventLoggerModule>('eventLogger')\n const stepHandler = container.resolve<typeof stepHandlerModule>('stepHandler')\n const transitionHandler = container.resolve<typeof transitionHandlerModule>('transitionHandler')\n const workflowExecutor = container.resolve<typeof workflowExecutorModule>('workflowExecutor')\n\n // Branch-scoped timer: the instance is FORKED and the branch is PAUSED at the\n // WAIT_FOR_TIMER step. Resume just that branch, then drive the parallel loop.\n if (branchInstanceId) {\n await eventLogger.logWorkflowEvent(em, {\n workflowInstanceId: instanceId,\n stepInstanceId,\n branchInstanceId,\n eventType: 'TIMER_FIRED',\n eventData: { firedAt: new Date().toISOString(), branch: true },\n userId,\n tenantId,\n organizationId,\n })\n const { resumeBranch } = await import('./parallel-handler')\n const resumed = await resumeBranch(em, {\n instanceId,\n branchInstanceId,\n tenantId,\n organizationId,\n exitStepInstanceId: stepInstanceId,\n exitOutput: { firedAt: new Date().toISOString() },\n })\n if (resumed) {\n await workflowExecutor.executeWorkflow(em, container, instanceId, { userId })\n }\n return\n }\n\n const instance = await findOneWithDecryption(\n em as PostgreSqlEntityManager,\n WorkflowInstance,\n {\n id: instanceId,\n tenantId,\n organizationId,\n },\n undefined,\n { tenantId, organizationId },\n )\n\n if (!instance) {\n throw new TimerError(\n 'Workflow instance not found',\n 'INSTANCE_NOT_FOUND',\n { instanceId }\n )\n }\n\n if (instance.status !== 'PAUSED') {\n throw new TimerError(\n 'Workflow is not paused',\n 'WORKFLOW_NOT_PAUSED',\n { instanceId, status: instance.status }\n )\n }\n\n const definition = (await findOneWithDecryption(\n em as PostgreSqlEntityManager,\n WorkflowDefinition,\n {\n id: instance.definitionId,\n tenantId: instance.tenantId,\n organizationId: instance.organizationId,\n deletedAt: null,\n },\n undefined,\n { tenantId: instance.tenantId, organizationId: instance.organizationId },\n )) ?? resolveCodeDefinitionForInstance(instance)\n if (!definition) {\n throw new TimerError(\n 'Workflow definition not found',\n 'DEFINITION_NOT_FOUND',\n { definitionId: instance.definitionId }\n )\n }\n\n const currentStep = definition.definition.steps.find(\n (s: any) => s.stepId === instance.currentStepId\n )\n\n if (!currentStep || currentStep.stepType !== 'WAIT_FOR_TIMER') {\n throw new TimerError(\n 'Workflow is not waiting for timer',\n 'NOT_WAITING_FOR_TIMER',\n { instanceId, currentStepId: instance.currentStepId }\n )\n }\n\n const now = new Date()\n instance.updatedAt = now\n\n await eventLogger.logWorkflowEvent(em, {\n workflowInstanceId: instance.id,\n stepInstanceId,\n eventType: 'TIMER_FIRED',\n eventData: {\n stepId: instance.currentStepId,\n firedAt: now.toISOString(),\n },\n userId,\n tenantId: instance.tenantId,\n organizationId: instance.organizationId,\n })\n\n const stepInstance = stepInstanceId\n ? await findOneWithDecryption(\n em as PostgreSqlEntityManager,\n StepInstance,\n {\n id: stepInstanceId,\n workflowInstanceId: instance.id,\n tenantId: instance.tenantId,\n organizationId: instance.organizationId,\n },\n undefined,\n { tenantId: instance.tenantId, organizationId: instance.organizationId },\n )\n : await findOneWithDecryption(\n em as PostgreSqlEntityManager,\n StepInstance,\n {\n workflowInstanceId: instance.id,\n stepId: instance.currentStepId,\n status: 'ACTIVE',\n tenantId: instance.tenantId,\n organizationId: instance.organizationId,\n },\n undefined,\n { tenantId: instance.tenantId, organizationId: instance.organizationId },\n )\n\n if (stepInstance) {\n await stepHandler.exitStep(em, stepInstance, {\n firedAt: now.toISOString(),\n })\n }\n\n const autoTransitions = (definition.definition.transitions || []).filter(\n (t: any) => t.fromStepId === instance.currentStepId && t.trigger === 'auto'\n )\n\n if (autoTransitions.length === 0) {\n instance.status = 'RUNNING'\n await em.flush()\n return\n }\n\n const transitionContext = {\n workflowContext: instance.context,\n userId,\n }\n\n const validTransitions = await transitionHandler.findValidTransitions(\n em,\n instance,\n instance.currentStepId,\n transitionContext\n )\n\n const firstValidTransition = validTransitions.find((t) => t.isValid)\n\n if (!firstValidTransition || !firstValidTransition.transition) {\n instance.status = 'RUNNING'\n await em.flush()\n return\n }\n\n // Resume from the paused wait BEFORE executing the transition, exactly as\n // `sendSignal` does. Without it the executor's defense-in-depth PAUSED check\n // stops the run at the very first step the timer traverses, so the instance\n // sits at that step (typically END) as PAUSED and never completes.\n instance.status = 'RUNNING'\n await em.flush()\n\n const transitionResult = await transitionHandler.executeTransition(\n em,\n container,\n instance,\n instance.currentStepId,\n firstValidTransition.transition.toStepId,\n { ...transitionContext, transitionId: firstValidTransition.transition.transitionId },\n )\n\n if (!transitionResult.success) {\n const { handleTransitionFailure } = await import('./workflow-executor')\n const failure = await handleTransitionFailure(em, container, instance, transitionResult, {\n evalContext: transitionContext,\n fromStepId: firstValidTransition.transition.fromStepId,\n toStepId: firstValidTransition.transition.toStepId,\n source: 'timer',\n })\n if (failure.kind === 'parked') return\n if (failure.kind === 'failed') {\n throw new TimerError(\n 'Transition failed after timer fired',\n 'TRANSITION_FAILED',\n { error: transitionResult.error }\n )\n }\n }\n\n await workflowExecutor.executeWorkflow(em, container, instance.id, { userId })\n}\n"],
|
|
5
|
-
"mappings": "AAUA,SAAS,6BAA6B;AACtC,SAAS,kBAAkB,oBAAoB,oBAAoB;AAKnE,SAAS,wCAAwC;AAW1C,MAAM,mBAAmB,MAAM;AAAA,EACpC,YACE,SACO,MACA,SACP;AACA,UAAM,OAAO;AAHN;AACA;AAGP,SAAK,OAAO;AAAA,EACd;AACF;AASA,eAAsB,UACpB,IACA,WACA,SACe;AACf,QAAM,EAAE,YAAY,gBAAgB,kBAAkB,QAAQ,UAAU,eAAe,IAAI;AAE3F,QAAM,cAAc,UAAU,QAAkC,aAAa;AAC7E,QAAM,cAAc,UAAU,QAAkC,aAAa;AAC7E,QAAM,oBAAoB,UAAU,QAAwC,mBAAmB;AAC/F,QAAM,mBAAmB,UAAU,QAAuC,kBAAkB;AAI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iB,MAAM;AAAA,MAClC;AAAA,IACF;AAAA,EACF;AAEA,QAAM,iBAAiB,gBAAgB,IAAI,WAAW,SAAS,IAAI,EAAE,OAAO,CAAC;AAC/E;",
|
|
4
|
+
"sourcesContent": ["/**\n * Timer Handler Service\n *\n * Fires timers for WAIT_FOR_TIMER steps: resumes a paused workflow instance\n * when its scheduled timer job is processed by the activity worker.\n */\n\nimport { EntityManager } from '@mikro-orm/core'\nimport type { EntityManager as PostgreSqlEntityManager } from '@mikro-orm/postgresql'\nimport type { AwilixContainer } from 'awilix'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { WorkflowInstance, WorkflowDefinition, StepInstance } from '../data/entities'\nimport type * as eventLoggerModule from './event-logger'\nimport type * as stepHandlerModule from './step-handler'\nimport type * as transitionHandlerModule from './transition-handler'\nimport type * as workflowExecutorModule from './workflow-executor'\nimport { resolveCodeDefinitionForInstance } from './find-definition'\n\nexport interface FireTimerOptions {\n instanceId: string\n stepInstanceId?: string\n branchInstanceId?: string | null\n userId?: string\n tenantId: string\n organizationId: string\n}\n\nexport class TimerError extends Error {\n constructor(\n message: string,\n public code: string,\n public details?: any\n ) {\n super(message)\n this.name = 'TimerError'\n }\n}\n\n/**\n * Fire a timer and resume workflow execution.\n *\n * Mirrors `sendSignal` from signal-handler.ts \u2014 verifies the instance is\n * paused at a WAIT_FOR_TIMER step, logs TIMER_FIRED, exits the step, then\n * executes auto transitions and resumes the workflow.\n */\nexport async function fireTimer(\n em: EntityManager,\n container: AwilixContainer,\n options: FireTimerOptions\n): Promise<void> {\n const { instanceId, stepInstanceId, branchInstanceId, userId, tenantId, organizationId } = options\n\n const eventLogger = container.resolve<typeof eventLoggerModule>('eventLogger')\n const stepHandler = container.resolve<typeof stepHandlerModule>('stepHandler')\n const transitionHandler = container.resolve<typeof transitionHandlerModule>('transitionHandler')\n const workflowExecutor = container.resolve<typeof workflowExecutorModule>('workflowExecutor')\n\n // Branch-scoped timer: the instance is FORKED and the branch is PAUSED at the\n // WAIT_FOR_TIMER step. Resume just that branch, then drive the parallel loop.\n if (branchInstanceId) {\n await eventLogger.logWorkflowEvent(em, {\n workflowInstanceId: instanceId,\n stepInstanceId,\n branchInstanceId,\n eventType: 'TIMER_FIRED',\n eventData: { firedAt: new Date().toISOString(), branch: true },\n userId,\n tenantId,\n organizationId,\n })\n const { resumeBranch } = await import('./parallel-handler')\n const resumed = await resumeBranch(em, {\n instanceId,\n branchInstanceId,\n tenantId,\n organizationId,\n exitStepInstanceId: stepInstanceId,\n exitOutput: { firedAt: new Date().toISOString() },\n })\n if (resumed) {\n await workflowExecutor.executeWorkflow(em, container, instanceId, { userId })\n }\n return\n }\n\n const instance = await findOneWithDecryption(\n em as PostgreSqlEntityManager,\n WorkflowInstance,\n {\n id: instanceId,\n tenantId,\n organizationId,\n },\n undefined,\n { tenantId, organizationId },\n )\n\n if (!instance) {\n throw new TimerError(\n 'Workflow instance not found',\n 'INSTANCE_NOT_FOUND',\n { instanceId }\n )\n }\n\n if (instance.status !== 'PAUSED') {\n throw new TimerError(\n 'Workflow is not paused',\n 'WORKFLOW_NOT_PAUSED',\n { instanceId, status: instance.status }\n )\n }\n\n const definition = (await findOneWithDecryption(\n em as PostgreSqlEntityManager,\n WorkflowDefinition,\n {\n id: instance.definitionId,\n tenantId: instance.tenantId,\n organizationId: instance.organizationId,\n deletedAt: null,\n },\n undefined,\n { tenantId: instance.tenantId, organizationId: instance.organizationId },\n )) ?? resolveCodeDefinitionForInstance(instance)\n if (!definition) {\n throw new TimerError(\n 'Workflow definition not found',\n 'DEFINITION_NOT_FOUND',\n { definitionId: instance.definitionId }\n )\n }\n\n const currentStep = definition.definition.steps.find(\n (s: any) => s.stepId === instance.currentStepId\n )\n\n if (!currentStep || currentStep.stepType !== 'WAIT_FOR_TIMER') {\n throw new TimerError(\n 'Workflow is not waiting for timer',\n 'NOT_WAITING_FOR_TIMER',\n { instanceId, currentStepId: instance.currentStepId }\n )\n }\n\n const now = new Date()\n instance.updatedAt = now\n\n await eventLogger.logWorkflowEvent(em, {\n workflowInstanceId: instance.id,\n stepInstanceId,\n eventType: 'TIMER_FIRED',\n eventData: {\n stepId: instance.currentStepId,\n firedAt: now.toISOString(),\n },\n userId,\n tenantId: instance.tenantId,\n organizationId: instance.organizationId,\n })\n\n const stepInstance = stepInstanceId\n ? await findOneWithDecryption(\n em as PostgreSqlEntityManager,\n StepInstance,\n {\n id: stepInstanceId,\n workflowInstanceId: instance.id,\n tenantId: instance.tenantId,\n organizationId: instance.organizationId,\n },\n undefined,\n { tenantId: instance.tenantId, organizationId: instance.organizationId },\n )\n : await findOneWithDecryption(\n em as PostgreSqlEntityManager,\n StepInstance,\n {\n workflowInstanceId: instance.id,\n stepId: instance.currentStepId,\n status: 'ACTIVE',\n tenantId: instance.tenantId,\n organizationId: instance.organizationId,\n },\n undefined,\n { tenantId: instance.tenantId, organizationId: instance.organizationId },\n )\n\n if (stepInstance) {\n await stepHandler.exitStep(em, stepInstance, {\n firedAt: now.toISOString(),\n })\n }\n\n const autoTransitions = (definition.definition.transitions || []).filter(\n (t: any) => t.fromStepId === instance.currentStepId && t.trigger === 'auto'\n )\n\n if (autoTransitions.length === 0) {\n instance.status = 'RUNNING'\n await em.flush()\n return\n }\n\n const transitionContext = {\n container,\n workflowContext: instance.context,\n userId,\n }\n\n const validTransitions = await transitionHandler.findValidTransitions(\n em,\n instance,\n instance.currentStepId,\n transitionContext\n )\n\n const firstValidTransition = validTransitions.find((t) => t.isValid)\n\n if (!firstValidTransition || !firstValidTransition.transition) {\n instance.status = 'RUNNING'\n await em.flush()\n return\n }\n\n // Resume from the paused wait BEFORE executing the transition, exactly as\n // `sendSignal` does. Without it the executor's defense-in-depth PAUSED check\n // stops the run at the very first step the timer traverses, so the instance\n // sits at that step (typically END) as PAUSED and never completes.\n instance.status = 'RUNNING'\n await em.flush()\n\n const transitionResult = await transitionHandler.executeTransition(\n em,\n container,\n instance,\n instance.currentStepId,\n firstValidTransition.transition.toStepId,\n { ...transitionContext, transitionId: firstValidTransition.transition.transitionId },\n )\n\n if (!transitionResult.success) {\n const { handleTransitionFailure } = await import('./workflow-executor')\n const failure = await handleTransitionFailure(em, container, instance, transitionResult, {\n evalContext: transitionContext,\n fromStepId: firstValidTransition.transition.fromStepId,\n toStepId: firstValidTransition.transition.toStepId,\n source: 'timer',\n })\n if (failure.kind === 'parked') return\n if (failure.kind === 'failed') {\n throw new TimerError(\n 'Transition failed after timer fired',\n 'TRANSITION_FAILED',\n { error: transitionResult.error }\n )\n }\n }\n\n await workflowExecutor.executeWorkflow(em, container, instance.id, { userId })\n}\n"],
|
|
5
|
+
"mappings": "AAUA,SAAS,6BAA6B;AACtC,SAAS,kBAAkB,oBAAoB,oBAAoB;AAKnE,SAAS,wCAAwC;AAW1C,MAAM,mBAAmB,MAAM;AAAA,EACpC,YACE,SACO,MACA,SACP;AACA,UAAM,OAAO;AAHN;AACA;AAGP,SAAK,OAAO;AAAA,EACd;AACF;AASA,eAAsB,UACpB,IACA,WACA,SACe;AACf,QAAM,EAAE,YAAY,gBAAgB,kBAAkB,QAAQ,UAAU,eAAe,IAAI;AAE3F,QAAM,cAAc,UAAU,QAAkC,aAAa;AAC7E,QAAM,cAAc,UAAU,QAAkC,aAAa;AAC7E,QAAM,oBAAoB,UAAU,QAAwC,mBAAmB;AAC/F,QAAM,mBAAmB,UAAU,QAAuC,kBAAkB;AAI5F,MAAI,kBAAkB;AACpB,UAAM,YAAY,iBAAiB,IAAI;AAAA,MACrC,oBAAoB;AAAA,MACpB;AAAA,MACA;AAAA,MACA,WAAW;AAAA,MACX,WAAW,EAAE,UAAS,oBAAI,KAAK,GAAE,YAAY,GAAG,QAAQ,KAAK;AAAA,MAC7D;AAAA,MACA;AAAA,MACA;AAAA,IACF,CAAC;AACD,UAAM,EAAE,aAAa,IAAI,MAAM,OAAO,oBAAoB;AAC1D,UAAM,UAAU,MAAM,aAAa,IAAI;AAAA,MACrC;AAAA,MACA;AAAA,MACA;AAAA,MACA;A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,mBAAmB,MAAM,kBAAkB;AAAA,IAC/C;AAAA,IACA;AAAA,IACA,SAAS;AAAA,IACT;AAAA,EACF;AAEA,QAAM,uBAAuB,iBAAiB,KAAK,CAAC,MAAM,EAAE,OAAO;AAEnE,MAAI,CAAC,wBAAwB,CAAC,qBAAqB,YAAY;AAC7D,aAAS,SAAS;AAClB,UAAM,GAAG,MAAM;AACf;AAAA,EACF;AAMA,WAAS,SAAS;AAClB,QAAM,GAAG,MAAM;AAEf,QAAM,mBAAmB,MAAM,kBAAkB;AAAA,IAC/C;AAAA,IACA;AAAA,IACA;AAAA,IACA,SAAS;AAAA,IACT,qBAAqB,WAAW;AAAA,IAChC,EAAE,GAAG,mBAAmB,cAAc,qBAAqB,WAAW,aAAa;AAAA,EACrF;AAEA,MAAI,CAAC,iBAAiB,SAAS;AAC7B,UAAM,EAAE,wBAAwB,IAAI,MAAM,OAAO,qBAAqB;AACtE,UAAM,UAAU,MAAM,wBAAwB,IAAI,WAAW,UAAU,kBAAkB;AAAA,MACvF,aAAa;AAAA,MACb,YAAY,qBAAqB,WAAW;AAAA,MAC5C,UAAU,qBAAqB,WAAW;AAAA,MAC1C,QAAQ;AAAA,IACV,CAAC;AACD,QAAI,QAAQ,SAAS,SAAU;AAC/B,QAAI,QAAQ,SAAS,UAAU;AAC7B,YAAM,IAAI;AAAA,QACR;AAAA,QACA;AAAA,QACA,EAAE,OAAO,iBAAiB,MAAM;AAAA,MAClC;AAAA,IACF;AAAA,EACF;AAEA,QAAM,iBAAiB,gBAAgB,IAAI,WAAW,SAAS,IAAI,EAAE,OAAO,CAAC;AAC/E;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -1,8 +1,9 @@
|
|
|
1
|
+
import { reportError } from "@open-mercato/telemetry";
|
|
1
2
|
import {
|
|
2
3
|
WorkflowEvent
|
|
3
4
|
} from "../data/entities.js";
|
|
4
5
|
import * as ruleEvaluator from "../../business_rules/lib/rule-evaluator.js";
|
|
5
|
-
import
|
|
6
|
+
import { createNamedWorkflowRuleScope } from "./named-rules.js";
|
|
6
7
|
import * as activityExecutor from "./activity-executor.js";
|
|
7
8
|
import * as stepHandler from "./step-handler.js";
|
|
8
9
|
import { findDefinitionForInstance } from "./find-definition.js";
|
|
@@ -137,6 +138,7 @@ async function evaluateTransition(em, instance, fromStepId, toStepId, context) {
|
|
|
137
138
|
}
|
|
138
139
|
}
|
|
139
140
|
async function findValidTransitions(em, instance, fromStepId, context) {
|
|
141
|
+
const namedRules = createNamedWorkflowRuleScope(context.container);
|
|
140
142
|
try {
|
|
141
143
|
const definition = await findDefinitionForInstance(em, instance);
|
|
142
144
|
if (!definition) {
|
|
@@ -156,14 +158,14 @@ async function findValidTransitions(em, instance, fromStepId, context) {
|
|
|
156
158
|
results.push(conditionResult);
|
|
157
159
|
continue;
|
|
158
160
|
}
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
const preConditionsResult = await evaluatePreConditions(
|
|
161
|
+
if (transition.preConditions?.length) {
|
|
162
|
+
const preConditionsResult = await evaluateNamedTransitionRules(
|
|
162
163
|
em,
|
|
163
164
|
instance,
|
|
164
165
|
transition,
|
|
165
166
|
context,
|
|
166
|
-
|
|
167
|
+
namedRules.resolve,
|
|
168
|
+
"pre_transition"
|
|
167
169
|
);
|
|
168
170
|
if (!preConditionsResult.allowed) {
|
|
169
171
|
const failedRules = preConditionsResult.executedRules.filter((r) => !r.conditionResult).map((r) => r.rule.ruleId || r.rule.ruleName);
|
|
@@ -185,6 +187,8 @@ async function findValidTransitions(em, instance, fromStepId, context) {
|
|
|
185
187
|
} catch (error) {
|
|
186
188
|
logger.error("Error finding valid transitions", { err: error });
|
|
187
189
|
return [];
|
|
190
|
+
} finally {
|
|
191
|
+
await namedRules.dispose();
|
|
188
192
|
}
|
|
189
193
|
}
|
|
190
194
|
async function executeTransition(em, container, instance, fromStepId, toStepId, context) {
|
|
@@ -194,13 +198,8 @@ async function executeTransitionForToken(em, container, token, fromStepId, toSte
|
|
|
194
198
|
const instance = token.instance;
|
|
195
199
|
const branch = token.kind === "branch" ? token.branch : null;
|
|
196
200
|
const branchInstanceId = tokenBranchInstanceId(token);
|
|
201
|
+
const namedRules = createNamedWorkflowRuleScope(container);
|
|
197
202
|
try {
|
|
198
|
-
let eventBus = null;
|
|
199
|
-
try {
|
|
200
|
-
eventBus = container.resolve("eventBus");
|
|
201
|
-
} catch {
|
|
202
|
-
eventBus = null;
|
|
203
|
-
}
|
|
204
203
|
const evaluation = await evaluateTransition(
|
|
205
204
|
em,
|
|
206
205
|
instance,
|
|
@@ -215,12 +214,13 @@ async function executeTransitionForToken(em, container, token, fromStepId, toSte
|
|
|
215
214
|
};
|
|
216
215
|
}
|
|
217
216
|
const transition = evaluation.transition;
|
|
218
|
-
const preConditionsResult = await
|
|
217
|
+
const preConditionsResult = await evaluateNamedTransitionRules(
|
|
219
218
|
em,
|
|
220
219
|
instance,
|
|
221
220
|
transition,
|
|
222
221
|
context,
|
|
223
|
-
|
|
222
|
+
namedRules.resolve,
|
|
223
|
+
"pre_transition"
|
|
224
224
|
);
|
|
225
225
|
if (!preConditionsResult.allowed) {
|
|
226
226
|
const failedRules = preConditionsResult.executedRules.filter((r) => !r.conditionResult).map((r) => ({
|
|
@@ -448,12 +448,13 @@ async function executeTransitionForToken(em, container, token, fromStepId, toSte
|
|
|
448
448
|
}
|
|
449
449
|
}
|
|
450
450
|
const stepPaused = stepExecutionResult.status === "WAITING" && stepExecutionResult.waitReason !== "FORK";
|
|
451
|
-
const postConditionsResult = await
|
|
451
|
+
const postConditionsResult = await evaluateNamedTransitionRules(
|
|
452
452
|
em,
|
|
453
453
|
instance,
|
|
454
454
|
transition,
|
|
455
455
|
context,
|
|
456
|
-
|
|
456
|
+
namedRules.resolve,
|
|
457
|
+
"post_transition"
|
|
457
458
|
);
|
|
458
459
|
if (!postConditionsResult.allowed) {
|
|
459
460
|
const failedRules = postConditionsResult.errors?.join(", ") || "Unknown post-condition failure";
|
|
@@ -518,6 +519,8 @@ async function executeTransitionForToken(em, container, token, fromStepId, toSte
|
|
|
518
519
|
success: false,
|
|
519
520
|
error: `Transition execution failed: ${errorMessage}`
|
|
520
521
|
};
|
|
522
|
+
} finally {
|
|
523
|
+
await namedRules.dispose();
|
|
521
524
|
}
|
|
522
525
|
}
|
|
523
526
|
async function evaluateTransitionConditions(em, instance, transition, context) {
|
|
@@ -554,131 +557,31 @@ async function evaluateTransitionConditions(em, instance, transition, context) {
|
|
|
554
557
|
};
|
|
555
558
|
}
|
|
556
559
|
}
|
|
557
|
-
async function
|
|
560
|
+
async function evaluateNamedTransitionRules(em, instance, transition, context, resolveRunner, phase) {
|
|
561
|
+
const isPreCondition = phase === "pre_transition";
|
|
562
|
+
const conditions = isPreCondition ? transition.preConditions : transition.postConditions;
|
|
558
563
|
try {
|
|
559
564
|
const definition = await findDefinitionForInstance(em, instance);
|
|
560
|
-
if (!definition) {
|
|
561
|
-
|
|
562
|
-
allowed: true,
|
|
563
|
-
executedRules: [],
|
|
564
|
-
totalExecutionTime: 0
|
|
565
|
-
};
|
|
566
|
-
}
|
|
567
|
-
const preConditions = transition.preConditions || [];
|
|
568
|
-
if (preConditions.length === 0) {
|
|
569
|
-
return {
|
|
570
|
-
allowed: true,
|
|
571
|
-
executedRules: [],
|
|
572
|
-
totalExecutionTime: 0
|
|
573
|
-
};
|
|
574
|
-
}
|
|
565
|
+
if (!definition || !conditions?.length) return { allowed: true, executedRules: [] };
|
|
566
|
+
const runner = await resolveRunner();
|
|
575
567
|
const dryRun = isDryRunInstance(instance);
|
|
576
|
-
const startTime = Date.now();
|
|
577
568
|
const executedRules = [];
|
|
578
569
|
const errors = [];
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
...instance.context,
|
|
591
|
-
...context.workflowContext
|
|
592
|
-
},
|
|
593
|
-
triggerData: context.triggerData
|
|
594
|
-
},
|
|
595
|
-
user: context.userId ? { id: context.userId } : void 0,
|
|
596
|
-
tenantId: instance.tenantId,
|
|
597
|
-
organizationId: instance.organizationId,
|
|
598
|
-
executedBy: context.userId,
|
|
599
|
-
entityType: `workflow:${definition.workflowId}:transition`,
|
|
600
|
-
entityId: transition.transitionId || `${transition.fromStepId}->${transition.toStepId}`,
|
|
601
|
-
eventType: "pre_transition",
|
|
602
|
-
// Dry run (spec section 8.2): the rule engine's own `dryRun` only
|
|
603
|
-
// suppresses its execution LOG — a rule's success/failure ACTIONS run
|
|
604
|
-
// regardless — so a side-effect-free run has to ask for `skipActions`.
|
|
605
|
-
// The conditions still evaluate, so the run takes the routes it really
|
|
606
|
-
// would; only the ACTION arm is withheld, and it is reported.
|
|
607
|
-
skipActions: dryRun
|
|
608
|
-
});
|
|
609
|
-
if (dryRun && result.actionsExecuted === null) {
|
|
610
|
-
await logSuppressedRuleActions(em, instance, condition.ruleId, "pre_transition");
|
|
611
|
-
}
|
|
612
|
-
const ruleResult = {
|
|
613
|
-
rule: {
|
|
614
|
-
ruleId: result.ruleId,
|
|
615
|
-
ruleName: result.ruleName,
|
|
616
|
-
ruleType: "GUARD"
|
|
617
|
-
},
|
|
618
|
-
conditionResult: result.conditionResult,
|
|
619
|
-
actionsExecuted: result.actionsExecuted,
|
|
620
|
-
executionTime: result.executionTime,
|
|
621
|
-
error: result.error,
|
|
622
|
-
logId: result.logId
|
|
623
|
-
};
|
|
624
|
-
executedRules.push(ruleResult);
|
|
625
|
-
if (result.error) {
|
|
626
|
-
const isRequired2 = condition.required !== false;
|
|
627
|
-
if (isRequired2) {
|
|
628
|
-
allowed = false;
|
|
629
|
-
errors.push(`Rule '${result.ruleId}': ${result.error}`);
|
|
630
|
-
}
|
|
570
|
+
for (const condition of conditions) {
|
|
571
|
+
const required = !isPreCondition || condition.required !== false;
|
|
572
|
+
if (!runner) {
|
|
573
|
+
if (!required) continue;
|
|
574
|
+
const error = "Business rules engine unavailable";
|
|
575
|
+
executedRules.push({
|
|
576
|
+
rule: { ruleId: condition.ruleId, ruleName: condition.ruleId },
|
|
577
|
+
conditionResult: false,
|
|
578
|
+
error
|
|
579
|
+
});
|
|
580
|
+
errors.push(`Rule '${condition.ruleId}': ${error}`);
|
|
631
581
|
continue;
|
|
632
582
|
}
|
|
633
|
-
const
|
|
634
|
-
if (isRequired && !result.conditionResult) {
|
|
635
|
-
allowed = false;
|
|
636
|
-
errors.push(`Pre-condition '${result.ruleName || result.ruleId}' failed`);
|
|
637
|
-
}
|
|
638
|
-
}
|
|
639
|
-
return {
|
|
640
|
-
allowed,
|
|
641
|
-
executedRules,
|
|
642
|
-
totalExecutionTime: Date.now() - startTime,
|
|
643
|
-
errors: errors.length > 0 ? errors : void 0
|
|
644
|
-
};
|
|
645
|
-
} catch (error) {
|
|
646
|
-
logger.error("Error evaluating pre-conditions", { err: error });
|
|
647
|
-
return {
|
|
648
|
-
allowed: false,
|
|
649
|
-
executedRules: [],
|
|
650
|
-
totalExecutionTime: 0,
|
|
651
|
-
errors: [error instanceof Error ? error.message : String(error)]
|
|
652
|
-
};
|
|
653
|
-
}
|
|
654
|
-
}
|
|
655
|
-
async function evaluatePostConditions(em, instance, transition, context, eventBus) {
|
|
656
|
-
try {
|
|
657
|
-
const definition = await findDefinitionForInstance(em, instance);
|
|
658
|
-
if (!definition) {
|
|
659
|
-
return {
|
|
660
|
-
allowed: true,
|
|
661
|
-
executedRules: [],
|
|
662
|
-
totalExecutionTime: 0
|
|
663
|
-
};
|
|
664
|
-
}
|
|
665
|
-
const postConditions = transition.postConditions || [];
|
|
666
|
-
if (postConditions.length === 0) {
|
|
667
|
-
return {
|
|
668
|
-
allowed: true,
|
|
669
|
-
executedRules: [],
|
|
670
|
-
totalExecutionTime: 0
|
|
671
|
-
};
|
|
672
|
-
}
|
|
673
|
-
const dryRun = isDryRunInstance(instance);
|
|
674
|
-
const startTime = Date.now();
|
|
675
|
-
const executedRules = [];
|
|
676
|
-
const errors = [];
|
|
677
|
-
let allowed = true;
|
|
678
|
-
for (const condition of postConditions) {
|
|
679
|
-
const result = await ruleEngine.executeRuleByRuleId(em, {
|
|
583
|
+
const result = await runner.executeRuleByRuleId(em, {
|
|
680
584
|
ruleId: condition.ruleId,
|
|
681
|
-
// String identifier
|
|
682
585
|
data: {
|
|
683
586
|
workflowInstanceId: instance.id,
|
|
684
587
|
workflowId: definition.workflowId,
|
|
@@ -696,52 +599,31 @@ async function evaluatePostConditions(em, instance, transition, context, eventBu
|
|
|
696
599
|
executedBy: context.userId,
|
|
697
600
|
entityType: `workflow:${definition.workflowId}:transition`,
|
|
698
601
|
entityId: transition.transitionId || `${transition.fromStepId}->${transition.toStepId}`,
|
|
699
|
-
eventType:
|
|
700
|
-
// Dry run (spec section 8.2): the rule engine's own `dryRun` only
|
|
701
|
-
// suppresses its execution LOG — a rule's success/failure ACTIONS run
|
|
702
|
-
// regardless — so a side-effect-free run has to ask for `skipActions`.
|
|
703
|
-
// The conditions still evaluate, so the run takes the routes it really
|
|
704
|
-
// would; only the ACTION arm is withheld, and it is reported.
|
|
602
|
+
eventType: phase,
|
|
705
603
|
skipActions: dryRun
|
|
706
604
|
});
|
|
707
605
|
if (dryRun && result.actionsExecuted === null) {
|
|
708
|
-
await logSuppressedRuleActions(em, instance, condition.ruleId,
|
|
606
|
+
await logSuppressedRuleActions(em, instance, condition.ruleId, phase);
|
|
709
607
|
}
|
|
710
|
-
|
|
711
|
-
rule: {
|
|
712
|
-
ruleId: result.ruleId,
|
|
713
|
-
ruleName: result.ruleName,
|
|
714
|
-
ruleType: "GUARD"
|
|
715
|
-
},
|
|
608
|
+
executedRules.push({
|
|
609
|
+
rule: { ruleId: result.ruleId, ruleName: result.ruleName },
|
|
716
610
|
conditionResult: result.conditionResult,
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
logId: result.logId
|
|
721
|
-
};
|
|
722
|
-
executedRules.push(ruleResult);
|
|
723
|
-
if (result.error) {
|
|
611
|
+
error: result.error
|
|
612
|
+
});
|
|
613
|
+
if (required && result.error) {
|
|
724
614
|
errors.push(`Rule '${result.ruleId}': ${result.error}`);
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
if (!result.conditionResult) {
|
|
729
|
-
allowed = false;
|
|
730
|
-
errors.push(`Post-condition '${result.ruleName || result.ruleId}' failed`);
|
|
615
|
+
} else if (required && !result.conditionResult) {
|
|
616
|
+
const label = isPreCondition ? "Pre-condition" : "Post-condition";
|
|
617
|
+
errors.push(`${label} '${result.ruleName || result.ruleId}' failed`);
|
|
731
618
|
}
|
|
732
619
|
}
|
|
733
|
-
return {
|
|
734
|
-
allowed,
|
|
735
|
-
executedRules,
|
|
736
|
-
totalExecutionTime: Date.now() - startTime,
|
|
737
|
-
errors: errors.length > 0 ? errors : void 0
|
|
738
|
-
};
|
|
620
|
+
return { allowed: errors.length === 0, executedRules, errors: errors.length ? errors : void 0 };
|
|
739
621
|
} catch (error) {
|
|
740
|
-
logger.error("Error evaluating post-conditions", { err: error });
|
|
622
|
+
logger.error(isPreCondition ? "Error evaluating pre-conditions" : "Error evaluating post-conditions", { err: error });
|
|
623
|
+
reportError(error, { module: "workflows", code: "workflows.named_transition_rule_failed" });
|
|
741
624
|
return {
|
|
742
625
|
allowed: false,
|
|
743
626
|
executedRules: [],
|
|
744
|
-
totalExecutionTime: 0,
|
|
745
627
|
errors: [error instanceof Error ? error.message : String(error)]
|
|
746
628
|
};
|
|
747
629
|
}
|