Open MercatoDocsSearch docsAPI reference

Framework

Workflow services

An integration may start an approval today and send a signal when a supplier responds tomorrow. Use the REST API when the caller is external, or the workflow services in application code. Keep the instance identifier so the later signal reaches the correct run.

Starting Workflows

REST API

Endpoint:

POST /api/workflows/instances

Request Body:

{
  "workflowId": "purchase-approval-v1",
  "initialContext": {
    "orderId": "order-123",
    "customerId": "cust-456",
    "amount": 150.00,
    "items": [
      { "productId": "prod-1", "quantity": 2 }
    ]
  },
  "correlationKey": "order-123"
}

Response:

{
  "id": "wf-inst-abc123",
  "workflowId": "purchase-approval-v1",
  "version": 1,
  "status": "RUNNING",
  "currentStepId": "start",
  "context": { ... },
  "correlationKey": "order-123",
  "startedAt": "2024-01-15T10:00:00Z"
}

TypeScript Example

import { apiFetch } from '@open-mercato/ui/backend/utils/api'

async function startApprovalWorkflow(orderId: string, amount: number) {
  const response = await apiFetch('/api/workflows/instances', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      workflowId: 'purchase-approval-v1',
      initialContext: {
        orderId,
        amount,
        requesterEmail: '[email protected]',
        approverEmail: '[email protected]'
      },
      correlationKey: orderId
    })
  })

  if (!response.ok) {
    const error = await response.json()
    throw new Error(`Failed to start workflow: ${error.message}`)
  }

  const instance = await response.json()
  console.log(`Workflow started: ${instance.id}`)
  return instance
}

Service Integration

For server-side code, inject the workflow service via DI:

import { inject, injectable } from 'awilix'
import { WorkflowService } from '@/modules/workflows/lib/workflow-service'

@injectable()
export class OrderService {
  constructor(
    @inject('workflowService') private workflowService: WorkflowService
  ) {}

  async createOrder(orderData: any) {
    // Create order in database
    const order = await this.orderRepository.create(orderData)

    // Start workflow
    const instance = await this.workflowService.startWorkflow({
      workflowId: 'order-fulfillment-v1',
      initialContext: {
        orderId: order.id,
        customerId: order.customerId,
        items: order.items
      },
      correlationKey: order.id
    })

    // Store instance ID on order
    order.workflowInstanceId = instance.id
    await this.orderRepository.save(order)

    return order
  }
}

Sending Signals

REST API

Endpoint:

POST /api/workflows/instances/{instanceId}/signal

Request Body:

{
  "signalName": "payment-confirmed",
  "payload": {
    "transactionId": "txn_abc123",
    "amount": 150.00,
    "paidAt": "2024-01-15T10:30:00Z"
  }
}

Response:

{
  "success": true,
  "instanceId": "wf-inst-abc123",
  "signalReceived": "payment-confirmed",
  "updatedContext": { ... }
}

TypeScript Example

async function sendPaymentConfirmation(
  instanceId: string,
  transactionId: string,
  amount: number
) {
  const response = await apiFetch(`/api/workflows/instances/${instanceId}/signal`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      signalName: 'payment-confirmed',
      payload: {
        transactionId,
        amount,
        paidAt: new Date().toISOString()
      }
    })
  })

  if (!response.ok) {
    throw new Error('Failed to send signal')
  }

  return await response.json()
}

Webhook Integration

Integrate signals with external webhooks:

import { Router } from 'express'
import { WorkflowService } from '@/modules/workflows/lib/workflow-service'

const router = Router()

router.post('/webhooks/stripe', async (req, res) => {
  const { orderId, transactionId, amount, status } = req.body

  if (status !== 'succeeded') {
    return res.status(200).json({ received: true })
  }

  // Find workflow instance by correlation key
  const instances = await fetch(
    `/api/workflows/instances?correlationKey=${orderId}`
  ).then(r => r.json())

  if (instances.length === 0) {
    return res.status(404).json({ error: 'Workflow not found' })
  }

  // Send signal to resume workflow
  await fetch(`/api/workflows/instances/${instances[0].id}/signal`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      signalName: 'payment-confirmed',
      payload: { transactionId, amount }
    })
  })

  res.status(200).json({ received: true })
})

Querying Instances

List Instances

Endpoint:

GET /api/workflows/instances?status=RUNNING&correlationKey=order-123

Query Parameters:

Response:

{
  "instances": [
    {
      "id": "wf-inst-abc123",
      "workflowId": "order-fulfillment-v1",
      "status": "RUNNING",
      "currentStepId": "wait-for-payment",
      "correlationKey": "order-123",
      "startedAt": "2024-01-15T10:00:00Z"
    }
  ],
  "total": 1
}

Get Instance Details

Endpoint:

GET /api/workflows/instances/{instanceId}

Response:

{
  "id": "wf-inst-abc123",
  "workflowId": "order-fulfillment-v1",
  "version": 1,
  "status": "RUNNING",
  "currentStepId": "wait-for-payment",
  "context": {
    "orderId": "order-123",
    "customerId": "cust-456",
    "amount": 150.00
  },
  "correlationKey": "order-123",
  "startedAt": "2024-01-15T10:00:00Z",
  "workflowInstance": {
    "id": "wf-inst-abc123",
    // ... additional details
  }
}

TypeScript Example

async function getOrderWorkflow(orderId: string) {
  // Query by correlation key
  const response = await apiFetch(
    `/api/workflows/instances?correlationKey=${orderId}`
  )

  if (!response.ok) {
    throw new Error('Failed to query workflows')
  }

  const { instances } = await response.json()

  if (instances.length === 0) {
    return null
  }

  // Get full details
  const detailResponse = await apiFetch(
    `/api/workflows/instances/${instances[0].id}`
  )

  return await detailResponse.json()
}

Completing Tasks

REST API

Endpoint:

POST /api/workflows/tasks/{taskId}/complete

Request Body:

{
  "formData": {
    "decision": "approve",
    "comments": "Approved for budget 2024"
  }
}

Response:

{
  "success": true,
  "taskId": "task-123",
  "workflowInstanceId": "wf-inst-abc123",
  "status": "COMPLETED"
}

TypeScript Example

async function approveRequest(taskId: string, comments: string) {
  const response = await apiFetch(`/api/workflows/tasks/${taskId}/complete`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      formData: {
        decision: 'approve',
        comments,
        approvedAt: new Date().toISOString()
      }
    })
  })

  if (!response.ok) {
    throw new Error('Failed to complete task')
  }

  return await response.json()
}

Completing with a decision

When the step authored decision buttons, pass the id of the one that was pressed:

await apiFetch(`/api/workflows/tasks/${taskId}/complete`, {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ formData: { comments }, decisionId: 'reject' }),
})

decisionId is optional and additive – a task without decisions completes exactly as before. When present it does two things: it selects the outgoing route (the decision's durable transitionId wins over the default first-valid-transition evaluation) and it is recorded on the completion, under the reserved __decision key in user_tasks.form_data and in the USER_TASK_COMPLETED event. Because form data is merged into the run context, a downstream route condition can branch on context.__decision.

The lookup is constrained to routes leaving the step the task is parked on, and error and SLA-breach routes are excluded – a button can never send a run down a route that starts elsewhere, or down a path only a failure may reach. An unknown decisionId is resolved before anything is mutated and answered 400, so the task is left untouched rather than completed down the wrong route. A decision whose route no longer exists on the step logs a warning and falls back to normal routing instead of stranding the run.

A task inside a parallel branch records the decision but does not route on it: a branch advances through resumeBranch with its own token, and overriding its outgoing route is a parallel-execution change rather than a task-surface one.

Work Inbox

GET  /api/workflows/work-inbox        # merged, filtered, ordered work items
POST /api/workflows/work-inbox/next   # claim the top claimable item
POST /api/workflows/tasks/{id}/unclaim  # release a claim back to its queue

GET /api/workflows/work-inbox (feature workflows.tasks.view) merges every registered source. Query parameters: kind, module, entityType, role, priority, status, overdue, myWork (alias myTasks), assignedTo, workflowInstanceId, limit, offset.

{
  data: [ /* rows */ ],
  pagination: { total, limit, offset, hasMore },
  meta: { kinds: ['user_task'], degradedKinds: [] },
}

POST /api/workflows/work-inbox/next (feature workflows.tasks.claim) walks the caller's claimable queue in inbox order and claims the first item it wins, returning the claimed row. Nothing claimable is a 200 with data: null, not a 404. It accepts the same query string as the list, so the candidate set can be narrowed.

Claiming is a compare-and-set: claimUserTask takes the row with a conditional UPDATE … WHERE status = 'PENDING' AND claimed_by IS NULL. The candidate list is a plain read and is expected to be stale; two callers racing therefore never receive the same item – the loser's update affects zero rows and the handler moves on to the next candidate instead of failing.

Resolve the service directly when you need the same queue server-side:

const workInboxService = container.resolve('workInboxService')
const { rows, total, kinds, degradedKinds } = await workInboxService.listWorkInbox(query, {
  scope: { tenantId, organizationIds, userId, roles },
  resolve: (name) => container.resolve(name),
})

Task Administration and Portal Tasks

POST /api/workflows/tasks/{id}/reassign   # feature workflows.tasks.reassign
GET  /api/workflows/task-settings         # feature workflows.tasks.view_all
PUT  /api/workflows/task-settings         # feature workflows.tasks.manage
GET  /api/workflows/portal/tasks          # customer feature portal.tasks.view
GET  /api/workflows/portal/tasks/{id}     # customer feature portal.tasks.view
POST /api/workflows/portal/tasks/{id}/complete  # customer feature portal.tasks.complete

Every one of these is a new route; no existing route's URL, method or response fields changed. Which rows the existing task routes return did change – see Task Visibility for the full model, which is required reading before integrating against any of them.

// Take a colleague's task before acting on it. `view_all` grants reading, never acting:
// completing somebody else's task answers 409 TASK_ASSIGNED_TO_ANOTHER_USER.
await apiFetch(`/api/workflows/tasks/${taskId}/reassign`, {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ assignedTo: myUserId, reason: 'Owner on leave' }),
})

Completing a task whose run is no longer active (COMPLETED, FAILED, CANCELLED, COMPENSATING or COMPENSATED) answers 409 with code: 'WORKFLOW_NOT_ACTIVE' and writes nothing – the task, the run context and the cursor stay as they were; the portal route answers its standard 404. Cancelling a run moves its PENDING / IN_PROGRESS tasks to CANCELLED and logs one USER_TASK_CANCELLED event per task, so they leave the open-task lists.

Reassignment stamps reassigned_by / reassigned_at / reassign_reason, logs a USER_TASK_REASSIGNED event, releases an in-flight claim, and returns an IN_PROGRESS task to PENDING. It honours x-om-ext-optimistic-lock-expected-updated-at when a client sends one. Its gate is visibility, not ownership – which is what makes it the remedy for a task nobody owns (403 TASK_NOT_ACTIONABLE on the act routes).

The portal routes are a new surface, not a relaxation: they take a portal session (not a bearer token), refuse a backoffice principal with 401, and the backoffice task routes still refuse a portal session with 401. GET /api/workflows/portal/tasks/{id} additionally returns canComplete, which is false for a company administrator reading a member's task. Every portal refusal is the same 404 body.

Task Deadlines and Reminders

A USER_TASK with a deadline schedules its reminders and its breach once, at task creation, as delayed jobs on the existing workflow-activities queue (job kind task_sla) – the same absolute-deadline backstop WAIT_FOR_CONDITION uses. A new queue would need its own worker registration and its own database connection budget for jobs that are one row read plus an event.

Event Listeners

Subscribe to workflow events to react to state changes:

Using Event Subscribers

Create a subscriber in src/modules/your-module/subscribers/workflow-completed.ts:

import { WorkflowEvent } from '@/modules/workflows/data/entities'

export default async function handleWorkflowCompleted(event: WorkflowEvent) {
  console.log(`Workflow ${event.workflowInstanceId} completed`)

  // Access workflow context from event
  const { orderId, amount } = event.eventData

  // Trigger follow-up actions
  await sendCompletionEmail(orderId)
  await updateOrderStatus(orderId, 'WORKFLOW_COMPLETED')
}

export const metadata = {
  event: 'workflow.completed',
  persistent: true
}

Event Types

Subscribe to these events:

Context Access

Reading Context

Get the current workflow context:

const instance = await apiFetch(`/api/workflows/instances/${instanceId}`)
  .then(r => r.json())

console.log(instance.context)
// { orderId: "order-123", amount: 150.00, ... }

Updating Context

Context is updated automatically through:

For custom updates from outside the engine, patch the instance context over HTTP:

PATCH /api/workflows/instances/{instanceId}/context
Content-Type: application/json

{
  "context": {
    "gridApproval": { "status": "APPROVED", "reference": "GA-4471" }
  }
}
{
  "ok": true,
  "instanceId": "instance-uuid",
  "woken": ["await_grid_approval"]
}

The patch is merged into the run context, and any WAIT_FOR_CONDITION step whose predicate now holds is woken in the same call – woken names the step ids that resumed. The per-waiter poll job remains the durability backstop, so a missed call here costs latency, never correctness.

Rules worth knowing before you call it:

Error Handling

API Errors

Handle errors from API calls:

import { apiFetch } from '@open-mercato/ui/backend/utils/api'

async function safeStartWorkflow(workflowId: string, context: any) {
  try {
    const response = await apiFetch('/api/workflows/instances', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ workflowId, initialContext: context })
    })

    if (!response.ok) {
      const error = await response.json()
      console.error('Workflow start failed:', error.message)
      return null
    }

    return await response.json()
  } catch (error) {
    console.error('Network error:', error)
    return null
  }
}

Retry and Compensation

Configure retry policies in activity definitions:

{
  activityId: "call-payment-api",
  activityType: "CALL_API",
  retryPolicy: {
    maxAttempts: 3,
    backoff: "exponential"
  },
  compensate: true,
  compensationActivity: {
    activityType: "CALL_API",
    config: { url: "https://api.example.com/refund" }
  }
}

Service Interfaces

WorkflowService

interface WorkflowService {
  startWorkflow(params: {
    workflowId: string
    initialContext: any
    correlationKey?: string
  }): Promise<WorkflowInstance>

  sendSignal(instanceId: string, params: {
    signalName: string
    payload?: any
  }): Promise<void>

  getInstance(instanceId: string): Promise<WorkflowInstance>

  queryInstances(filters: {
    status?: WorkflowStatus
    workflowId?: string
    correlationKey?: string
  }): Promise<WorkflowInstance[]>

  cancelInstance(instanceId: string): Promise<void>
}

WorkflowInstance

interface WorkflowInstance {
  id: string
  workflowId: string
  version: number
  status: WorkflowStatus
  currentStepId: string
  context: Record<string, any>
  correlationKey: string | null
  startedAt: Date
  completedAt: Date | null
  updatedAt: Date
}

type WorkflowStatus =
  | 'RUNNING'
  | 'COMPLETED'
  | 'FAILED'
  | 'PAUSED'
  | 'WAITING_FOR_SIGNAL'
  | 'WAITING_FOR_ACTIVITIES'
  | 'CANCELLED'

Next Steps

See Also:

Previous: Run State Presentation · Next: Task Visibility