@open-mercato/core 0.11.1-develop.8538.1.78ea48b6e6 → 0.11.1-develop.8545.1.dd603570fd
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/customer_accounts/api/admin/users/[id].js +10 -9
- package/dist/modules/customer_accounts/api/admin/users/[id].js.map +2 -2
- package/dist/modules/customer_accounts/api/portal/notifications/[id]/dismiss.js +3 -2
- package/dist/modules/customer_accounts/api/portal/notifications/[id]/dismiss.js.map +2 -2
- package/dist/modules/customer_accounts/api/portal/notifications/[id]/read.js +3 -2
- package/dist/modules/customer_accounts/api/portal/notifications/[id]/read.js.map +2 -2
- package/dist/modules/customer_accounts/api/portal/notifications/mark-all-read.js +4 -0
- package/dist/modules/customer_accounts/api/portal/notifications/mark-all-read.js.map +2 -2
- package/dist/modules/customer_accounts/api/portal/notifications/unread-count.js +4 -0
- package/dist/modules/customer_accounts/api/portal/notifications/unread-count.js.map +2 -2
- package/dist/modules/customer_accounts/api/portal/notifications.js +4 -0
- package/dist/modules/customer_accounts/api/portal/notifications.js.map +2 -2
- package/dist/modules/customer_accounts/lib/customerEntityOwnership.js +12 -1
- package/dist/modules/customer_accounts/lib/customerEntityOwnership.js.map +2 -2
- package/dist/modules/customer_accounts/lib/moduleEntityRegistration.js +8 -0
- package/dist/modules/customer_accounts/lib/moduleEntityRegistration.js.map +7 -0
- package/dist/modules/customer_accounts/lib/portalNotificationsAvailability.js +9 -0
- package/dist/modules/customer_accounts/lib/portalNotificationsAvailability.js.map +7 -0
- package/dist/modules/directory/utils/organizationScope.js +3 -2
- package/dist/modules/directory/utils/organizationScope.js.map +2 -2
- package/dist/modules/entities/api/records.js +4 -3
- package/dist/modules/entities/api/records.js.map +2 -2
- package/dist/modules/entities/backend/entities/user/[entityId]/records/page.js +22 -38
- package/dist/modules/entities/backend/entities/user/[entityId]/records/page.js.map +2 -2
- package/dist/modules/progress/api/active/route.js +11 -3
- package/dist/modules/progress/api/active/route.js.map +2 -2
- package/dist/modules/progress/api/jobPermissions.js +42 -0
- package/dist/modules/progress/api/jobPermissions.js.map +7 -0
- package/dist/modules/progress/api/jobs/[id]/route.js +6 -11
- package/dist/modules/progress/api/jobs/[id]/route.js.map +2 -2
- package/dist/modules/wms/index.js +1 -1
- package/dist/modules/wms/index.js.map +2 -2
- package/dist/modules/wms/setup.js +4 -1
- package/dist/modules/wms/setup.js.map +2 -2
- package/dist/modules/workflows/api/events/route.js +1 -1
- package/dist/modules/workflows/api/events/route.js.map +2 -2
- package/dist/modules/workflows/api/instances/[id]/events/route.js +1 -1
- package/dist/modules/workflows/api/instances/[id]/events/route.js.map +2 -2
- package/dist/modules/workflows/api/instances/[id]/steps/route.js +1 -1
- package/dist/modules/workflows/api/instances/[id]/steps/route.js.map +2 -2
- package/dist/modules/workflows/api/instances/failure-queue/route.js +1 -1
- package/dist/modules/workflows/api/instances/failure-queue/route.js.map +2 -2
- package/dist/modules/workflows/lib/event-logger.js +1 -1
- package/dist/modules/workflows/lib/event-logger.js.map +2 -2
- package/dist/modules/workflows/lib/work-inbox/user-task-source.js +1 -1
- package/dist/modules/workflows/lib/work-inbox/user-task-source.js.map +2 -2
- package/package.json +7 -7
- package/src/modules/customer_accounts/api/admin/users/[id].ts +10 -9
- package/src/modules/customer_accounts/api/portal/notifications/[id]/dismiss.ts +8 -5
- package/src/modules/customer_accounts/api/portal/notifications/[id]/read.ts +8 -5
- package/src/modules/customer_accounts/api/portal/notifications/mark-all-read.ts +4 -0
- package/src/modules/customer_accounts/api/portal/notifications/unread-count.ts +4 -0
- package/src/modules/customer_accounts/api/portal/notifications.ts +4 -0
- package/src/modules/customer_accounts/lib/customerEntityOwnership.ts +13 -1
- package/src/modules/customer_accounts/lib/moduleEntityRegistration.ts +12 -0
- package/src/modules/customer_accounts/lib/portalNotificationsAvailability.ts +7 -0
- package/src/modules/directory/utils/organizationScope.ts +3 -2
- package/src/modules/entities/api/records.ts +4 -3
- package/src/modules/entities/backend/entities/user/[entityId]/records/page.tsx +25 -31
- package/src/modules/entities/i18n/de.json +20 -1
- package/src/modules/entities/i18n/en.json +20 -1
- package/src/modules/entities/i18n/es.json +20 -1
- package/src/modules/entities/i18n/ko.json +20 -1
- package/src/modules/entities/i18n/pl.json +20 -1
- package/src/modules/progress/api/active/route.ts +18 -3
- package/src/modules/progress/api/jobPermissions.ts +50 -0
- package/src/modules/progress/api/jobs/[id]/route.ts +7 -20
- package/src/modules/wms/index.ts +1 -1
- package/src/modules/wms/setup.ts +4 -1
- package/src/modules/workflows/api/events/route.ts +1 -1
- package/src/modules/workflows/api/instances/[id]/events/route.ts +1 -1
- package/src/modules/workflows/api/instances/[id]/steps/route.ts +3 -2
- package/src/modules/workflows/api/instances/failure-queue/route.ts +1 -1
- package/src/modules/workflows/lib/event-logger.ts +1 -1
- package/src/modules/workflows/lib/work-inbox/user-task-source.ts +3 -2
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../../src/modules/workflows/api/events/route.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * Workflow Events API\n *\n * Endpoint:\n * - GET /api/workflows/events - List all workflow events with filtering and pagination\n */\n\nimport { NextRequest, NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport { getWorkflowListPageBounds } from '../../data/pagination'\nimport { workflowEventPageSchema } from '../../data/validators'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { resolveOrganizationScopeForRequest } from '@open-mercato/core/modules/directory/utils/organizationScope'\nimport { resolveOrganizationScopeFilter } from '@open-mercato/core/modules/directory/utils/organizationScopeFilter'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { WorkflowEvent, WorkflowInstance } from '../../data/entities'\nimport { workflowEventListItemSchema } from '../openapi'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('workflows')\n\nexport const metadata = {\n requireAuth: true,\n requireFeatures: ['workflows.instances.view'],\n}\n\n/**\n * GET /api/workflows/events\n *\n * List all workflow events with filtering and pagination\n */\nexport async function GET(request: NextRequest) {\n try {\n const container = await createRequestContainer()\n const em = container.resolve<EntityManager>('em')\n const auth = await getAuthFromRequest(request)\n\n if (!auth) {\n return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n }\n\n const scope = await resolveOrganizationScopeForRequest({ container, auth, request })\n const tenantId = auth.tenantId\n const orgFilter = resolveOrganizationScopeFilter(scope, auth)\n\n if (!tenantId) {\n return NextResponse.json(\n { error: 'Missing tenant context' },\n { status: 400 }\n )\n }\n\n // Check permission\n const rbacService = container.resolve('rbacService')\n const hasPermission = await rbacService.userHasAllFeatures(\n auth.sub,\n ['workflows.instances.view'],\n { tenantId, organizationId: orgFilter.rbacOrganizationId }\n )\n\n if (!hasPermission) {\n return NextResponse.json(\n { error: 'Insufficient permissions' },\n { status: 403 }\n )\n }\n\n const { searchParams } = new URL(request.url)\n\n // Pagination\n const pagination = workflowEventPageSchema.safeParse({\n page: searchParams.get('page') ?? undefined,\n pageSize: searchParams.get('pageSize') ?? undefined,\n })\n if (!pagination.success) {\n return NextResponse.json({ error: pagination.error.message }, { status: 400 })\n }\n const { page, pageSize } = pagination.data\n const offset = (page - 1) * pageSize\n\n // Filters\n const eventType = searchParams.get('eventType')\n const workflowInstanceId = searchParams.get('workflowInstanceId')\n const userId = searchParams.get('userId')\n const occurredAtFrom = searchParams.get('occurredAtFrom')\n const occurredAtTo = searchParams.get('occurredAtTo')\n\n // Sorting\n const sortField = searchParams.get('sortField') || 'occurredAt'\n const sortDir = (searchParams.get('sortDir') || 'desc').toLowerCase() as 'asc' | 'desc'\n\n // Build where clause\n const where: any = {\n tenantId,\n ...orgFilter.where,\n }\n\n if (eventType) {\n where.eventType = eventType\n }\n\n if (workflowInstanceId) {\n where.workflowInstanceId = workflowInstanceId\n }\n\n if (userId) {\n where.userId = userId\n }\n\n if (occurredAtFrom || occurredAtTo) {\n where.occurredAt = {}\n if (occurredAtFrom) {\n where.occurredAt.$gte = new Date(occurredAtFrom)\n }\n if (occurredAtTo) {\n where.occurredAt.$lte = new Date(occurredAtTo)\n }\n }\n\n // Query events\n const [events, total] = await em.findAndCount(\n WorkflowEvent,\n where,\n {\n orderBy: { [sortField]: sortDir },\n limit: pageSize,\n offset,\n }\n )\n\n // Fetch related workflow instances for display\n const instanceIds = [...new Set(events.map(e => e.workflowInstanceId))]\n const instances = await em.find(WorkflowInstance, {\n id: { $in: instanceIds },\n tenantId,\n ...orgFilter.where,\n })\n\n const instanceMap = new Map(instances.map(i => [i.id, i]))\n\n // Enrich events with workflow instance info\n const enrichedEvents = events.map(event => ({\n id: String(event.id), // Convert BigInt to string for JSON serialization\n workflowInstanceId: event.workflowInstanceId,\n stepInstanceId: event.stepInstanceId,\n eventType: event.eventType,\n eventData: event.eventData,\n occurredAt: event.occurredAt,\n userId: event.userId,\n workflowInstance: instanceMap.get(event.workflowInstanceId) ? {\n id: instanceMap.get(event.workflowInstanceId)!.id,\n workflowId: instanceMap.get(event.workflowInstanceId)!.workflowId,\n workflowName: instanceMap.get(event.workflowInstanceId)!.workflowId, // Use workflowId as name\n status: instanceMap.get(event.workflowInstanceId)!.status,\n } : null,\n }))\n\n const { totalPages } = getWorkflowListPageBounds(total, pageSize)\n\n return NextResponse.json({\n items: enrichedEvents,\n total,\n page,\n pageSize,\n totalPages,\n })\n } catch (error) {\n logger.error('Error getting workflow events', { err: error })\n return NextResponse.json(\n { error: 'Failed to get workflow events' },\n { status: 500 }\n )\n }\n}\n\nexport const openApi = {\n methods: {\n GET: {\n summary: 'List all workflow events',\n description: 'Get a paginated list of all workflow events with filtering options',\n tags: ['Workflows'],\n query: z.object({\n page: workflowEventPageSchema.shape.page.describe('Positive integer page number. The derived offset cannot exceed 100000.'),\n pageSize: workflowEventPageSchema.shape.pageSize.describe('Integer page size from 1 to 100.'),\n eventType: z.string().optional(),\n workflowInstanceId: z.string().uuid().optional(),\n userId: z.string().optional(),\n occurredAtFrom: z.string().datetime().optional(),\n occurredAtTo: z.string().datetime().optional(),\n sortField: z.enum(['occurredAt', 'eventType']).default('occurredAt').optional(),\n sortDir: z.enum(['asc', 'desc']).default('desc').optional(),\n }),\n responses: [\n {\n status: 400,\n description: 'Invalid pagination: page size must be an integer from 1 to 100 and the derived offset (page - 1) \u00D7 pageSize cannot exceed 100000.',\n schema: z.object({ error: z.string() }),\n },\n {\n status: 200,\n description: 'List of workflow events',\n schema: z.object({\n items: z.array(workflowEventListItemSchema),\n total: z.number(),\n page: z.number(),\n pageSize: z.number(),\n totalPages: z.number(),\n }),\n },\n {\n status: 401,\n description: 'Unauthorized',\n schema: z.object({ error: z.string() }),\n },\n {\n status: 403,\n description: 'Insufficient permissions',\n schema: z.object({ error: z.string() }),\n },\n {\n status: 500,\n description: 'Internal server error',\n schema: z.object({ error: z.string() }),\n },\n ],\n },\n },\n}\n"],
|
|
5
|
-
"mappings": "AAOA,SAAsB,oBAAoB;AAC1C,SAAS,SAAS;AAClB,SAAS,iCAAiC;AAC1C,SAAS,+BAA+B;AACxC,SAAS,8BAA8B;AACvC,SAAS,0BAA0B;AACnC,SAAS,0CAA0C;AACnD,SAAS,sCAAsC;AAE/C,SAAS,eAAe,wBAAwB;AAChD,SAAS,mCAAmC;AAC5C,SAAS,oBAAoB;AAE7B,MAAM,SAAS,aAAa,WAAW;AAEhC,MAAM,WAAW;AAAA,EACtB,aAAa;AAAA,EACb,iBAAiB,CAAC,0BAA0B;AAC9C;AAOA,eAAsB,IAAI,SAAsB;AAC9C,MAAI;AACF,UAAM,YAAY,MAAM,uBAAuB;AAC/C,UAAM,KAAK,UAAU,QAAuB,IAAI;AAChD,UAAM,OAAO,MAAM,mBAAmB,OAAO;AAE7C,QAAI,CAAC,MAAM;AACT,aAAO,aAAa,KAAK,EAAE,OAAO,eAAe,GAAG,EAAE,QAAQ,IAAI,CAAC;AAAA,IACrE;AAE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,YAAY;AAGpE,UAAM,QAAa;AAAA,MACjB;AAAA,MACA,GAAG,UAAU;AAAA,IACf;AAEA,QAAI,WAAW;AACb,YAAM,YAAY;AAAA,IACpB;AAEA,QAAI,oBAAoB;AACtB,YAAM,qBAAqB;AAAA,IAC7B;AAEA,QAAI,QAAQ;AACV,YAAM,SAAS;AAAA,IACjB;AAEA,QAAI,kBAAkB,cAAc;AAClC,YAAM,aAAa,CAAC;AACpB,UAAI,gBAAgB;AAClB,cAAM,WAAW,OAAO,IAAI,KAAK,cAAc;AAAA,MACjD;AACA,UAAI,cAAc;AAChB,cAAM,WAAW,OAAO,IAAI,KAAK,YAAY;AAAA,MAC/C;AAAA,IACF;AAGA,UAAM,CAAC,QAAQ,KAAK,IAAI,MAAM,GAAG;AAAA,MAC/B;AAAA,MACA;AAAA,MACA;AAAA,QACE,SAAS,EAAE,CAAC,SAAS,GAAG,QAAQ;AAAA,
|
|
4
|
+
"sourcesContent": ["/**\n * Workflow Events API\n *\n * Endpoint:\n * - GET /api/workflows/events - List all workflow events with filtering and pagination\n */\n\nimport { NextRequest, NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport { getWorkflowListPageBounds } from '../../data/pagination'\nimport { workflowEventPageSchema } from '../../data/validators'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { resolveOrganizationScopeForRequest } from '@open-mercato/core/modules/directory/utils/organizationScope'\nimport { resolveOrganizationScopeFilter } from '@open-mercato/core/modules/directory/utils/organizationScopeFilter'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { WorkflowEvent, WorkflowInstance } from '../../data/entities'\nimport { workflowEventListItemSchema } from '../openapi'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('workflows')\n\nexport const metadata = {\n requireAuth: true,\n requireFeatures: ['workflows.instances.view'],\n}\n\n/**\n * GET /api/workflows/events\n *\n * List all workflow events with filtering and pagination\n */\nexport async function GET(request: NextRequest) {\n try {\n const container = await createRequestContainer()\n const em = container.resolve<EntityManager>('em')\n const auth = await getAuthFromRequest(request)\n\n if (!auth) {\n return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n }\n\n const scope = await resolveOrganizationScopeForRequest({ container, auth, request })\n const tenantId = auth.tenantId\n const orgFilter = resolveOrganizationScopeFilter(scope, auth)\n\n if (!tenantId) {\n return NextResponse.json(\n { error: 'Missing tenant context' },\n { status: 400 }\n )\n }\n\n // Check permission\n const rbacService = container.resolve('rbacService')\n const hasPermission = await rbacService.userHasAllFeatures(\n auth.sub,\n ['workflows.instances.view'],\n { tenantId, organizationId: orgFilter.rbacOrganizationId }\n )\n\n if (!hasPermission) {\n return NextResponse.json(\n { error: 'Insufficient permissions' },\n { status: 403 }\n )\n }\n\n const { searchParams } = new URL(request.url)\n\n // Pagination\n const pagination = workflowEventPageSchema.safeParse({\n page: searchParams.get('page') ?? undefined,\n pageSize: searchParams.get('pageSize') ?? undefined,\n })\n if (!pagination.success) {\n return NextResponse.json({ error: pagination.error.message }, { status: 400 })\n }\n const { page, pageSize } = pagination.data\n const offset = (page - 1) * pageSize\n\n // Filters\n const eventType = searchParams.get('eventType')\n const workflowInstanceId = searchParams.get('workflowInstanceId')\n const userId = searchParams.get('userId')\n const occurredAtFrom = searchParams.get('occurredAtFrom')\n const occurredAtTo = searchParams.get('occurredAtTo')\n\n // Sorting\n const sortField = searchParams.get('sortField') || 'occurredAt'\n const sortDir = (searchParams.get('sortDir') || 'desc').toLowerCase() as 'asc' | 'desc'\n\n // Build where clause\n const where: any = {\n tenantId,\n ...orgFilter.where,\n }\n\n if (eventType) {\n where.eventType = eventType\n }\n\n if (workflowInstanceId) {\n where.workflowInstanceId = workflowInstanceId\n }\n\n if (userId) {\n where.userId = userId\n }\n\n if (occurredAtFrom || occurredAtTo) {\n where.occurredAt = {}\n if (occurredAtFrom) {\n where.occurredAt.$gte = new Date(occurredAtFrom)\n }\n if (occurredAtTo) {\n where.occurredAt.$lte = new Date(occurredAtTo)\n }\n }\n\n // Query events\n const [events, total] = await em.findAndCount(\n WorkflowEvent,\n where,\n {\n orderBy: { [sortField]: sortDir, id: sortDir },\n limit: pageSize,\n offset,\n }\n )\n\n // Fetch related workflow instances for display\n const instanceIds = [...new Set(events.map(e => e.workflowInstanceId))]\n const instances = await em.find(WorkflowInstance, {\n id: { $in: instanceIds },\n tenantId,\n ...orgFilter.where,\n })\n\n const instanceMap = new Map(instances.map(i => [i.id, i]))\n\n // Enrich events with workflow instance info\n const enrichedEvents = events.map(event => ({\n id: String(event.id), // Convert BigInt to string for JSON serialization\n workflowInstanceId: event.workflowInstanceId,\n stepInstanceId: event.stepInstanceId,\n eventType: event.eventType,\n eventData: event.eventData,\n occurredAt: event.occurredAt,\n userId: event.userId,\n workflowInstance: instanceMap.get(event.workflowInstanceId) ? {\n id: instanceMap.get(event.workflowInstanceId)!.id,\n workflowId: instanceMap.get(event.workflowInstanceId)!.workflowId,\n workflowName: instanceMap.get(event.workflowInstanceId)!.workflowId, // Use workflowId as name\n status: instanceMap.get(event.workflowInstanceId)!.status,\n } : null,\n }))\n\n const { totalPages } = getWorkflowListPageBounds(total, pageSize)\n\n return NextResponse.json({\n items: enrichedEvents,\n total,\n page,\n pageSize,\n totalPages,\n })\n } catch (error) {\n logger.error('Error getting workflow events', { err: error })\n return NextResponse.json(\n { error: 'Failed to get workflow events' },\n { status: 500 }\n )\n }\n}\n\nexport const openApi = {\n methods: {\n GET: {\n summary: 'List all workflow events',\n description: 'Get a paginated list of all workflow events with filtering options',\n tags: ['Workflows'],\n query: z.object({\n page: workflowEventPageSchema.shape.page.describe('Positive integer page number. The derived offset cannot exceed 100000.'),\n pageSize: workflowEventPageSchema.shape.pageSize.describe('Integer page size from 1 to 100.'),\n eventType: z.string().optional(),\n workflowInstanceId: z.string().uuid().optional(),\n userId: z.string().optional(),\n occurredAtFrom: z.string().datetime().optional(),\n occurredAtTo: z.string().datetime().optional(),\n sortField: z.enum(['occurredAt', 'eventType']).default('occurredAt').optional(),\n sortDir: z.enum(['asc', 'desc']).default('desc').optional(),\n }),\n responses: [\n {\n status: 400,\n description: 'Invalid pagination: page size must be an integer from 1 to 100 and the derived offset (page - 1) \u00D7 pageSize cannot exceed 100000.',\n schema: z.object({ error: z.string() }),\n },\n {\n status: 200,\n description: 'List of workflow events',\n schema: z.object({\n items: z.array(workflowEventListItemSchema),\n total: z.number(),\n page: z.number(),\n pageSize: z.number(),\n totalPages: z.number(),\n }),\n },\n {\n status: 401,\n description: 'Unauthorized',\n schema: z.object({ error: z.string() }),\n },\n {\n status: 403,\n description: 'Insufficient permissions',\n schema: z.object({ error: z.string() }),\n },\n {\n status: 500,\n description: 'Internal server error',\n schema: z.object({ error: z.string() }),\n },\n ],\n },\n },\n}\n"],
|
|
5
|
+
"mappings": "AAOA,SAAsB,oBAAoB;AAC1C,SAAS,SAAS;AAClB,SAAS,iCAAiC;AAC1C,SAAS,+BAA+B;AACxC,SAAS,8BAA8B;AACvC,SAAS,0BAA0B;AACnC,SAAS,0CAA0C;AACnD,SAAS,sCAAsC;AAE/C,SAAS,eAAe,wBAAwB;AAChD,SAAS,mCAAmC;AAC5C,SAAS,oBAAoB;AAE7B,MAAM,SAAS,aAAa,WAAW;AAEhC,MAAM,WAAW;AAAA,EACtB,aAAa;AAAA,EACb,iBAAiB,CAAC,0BAA0B;AAC9C;AAOA,eAAsB,IAAI,SAAsB;AAC9C,MAAI;AACF,UAAM,YAAY,MAAM,uBAAuB;AAC/C,UAAM,KAAK,UAAU,QAAuB,IAAI;AAChD,UAAM,OAAO,MAAM,mBAAmB,OAAO;AAE7C,QAAI,CAAC,MAAM;AACT,aAAO,aAAa,KAAK,EAAE,OAAO,eAAe,GAAG,EAAE,QAAQ,IAAI,CAAC;AAAA,IACrE;AAEA,UAAM,QAAQ,MAAM,mCAAmC,EAAE,WAAW,MAAM,QAAQ,CAAC;AACnF,UAAM,WAAW,KAAK;AACtB,UAAM,YAAY,+BAA+B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,QAAQ,EAAE,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,CAAC;AAAA,QACxC;AAAA,QACA;AAAA,UACE,QAAQ;AAAA,UACR,aAAa;AAAA,UACb,QAAQ,EAAE,OAAO;AAAA,YACf,OAAO,EAAE,MAAM,2BAA2B;AAAA,YAC1C,OAAO,EAAE,OAAO;AAAA,YAChB,MAAM,EAAE,OAAO;AAAA,YACf,UAAU,EAAE,OAAO;AAAA,YACnB,YAAY,EAAE,OAAO;AAAA,UACvB,CAAC;AAAA,QACH;AAAA,QACA;AAAA,UACE,QAAQ;AAAA,UACR,aAAa;AAAA,UACb,QAAQ,EAAE,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,CAAC;AAAA,QACxC;AAAA,QACA;AAAA,UACE,QAAQ;AAAA,UACR,aAAa;AAAA,UACb,QAAQ,EAAE,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,CAAC;AAAA,QACxC;AAAA,QACA;AAAA,UACE,QAAQ;AAAA,UACR,aAAa;AAAA,UACb,QAAQ,EAAE,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,CAAC;AAAA,QACxC;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../../../../src/modules/workflows/api/instances/%5Bid%5D/events/route.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * Workflow Instance Events API\n *\n * Endpoint:\n * - GET /api/workflows/instances/[id]/events - Get event history for a workflow instance\n */\n\nimport { NextRequest, NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport { WORKFLOW_LIST_MAX_OFFSET } from '../../../../data/pagination'\nimport { workflowListPaginationSchema } from '../../../../data/validators'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { resolveOrganizationScopeForRequest } from '@open-mercato/core/modules/directory/utils/organizationScope'\nimport { resolveOrganizationScopeFilter } from '@open-mercato/core/modules/directory/utils/organizationScopeFilter'\nimport { WorkflowInstance, WorkflowEvent } from '../../../../data/entities'\nimport { workflowEventRowSchema, paginationSchema } from '../../../openapi'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('workflows')\n\nexport const metadata = {\n requireAuth: true,\n requireFeatures: ['workflows.instances.view'],\n}\n\ninterface RouteContext {\n params: Promise<{\n id: string\n }>\n}\n\n/**\n * GET /api/workflows/instances/[id]/events\n *\n * Get event history for a workflow instance\n */\nexport async function GET(\n request: NextRequest,\n context: RouteContext\n) {\n try {\n const params = await context.params\n const container = await createRequestContainer()\n const em = container.resolve('em')\n const auth = await getAuthFromRequest(request)\n\n if (!auth) {\n return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n }\n\n const scope = await resolveOrganizationScopeForRequest({ container, auth, request })\n const tenantId = auth.tenantId\n const orgFilter = resolveOrganizationScopeFilter(scope, auth)\n\n if (!tenantId) {\n return NextResponse.json(\n { error: 'Missing tenant context' },\n { status: 400 }\n )\n }\n\n const { searchParams } = new URL(request.url)\n const eventType = searchParams.get('eventType')\n const pagination = workflowListPaginationSchema.safeParse({\n limit: searchParams.get('limit') ?? 100,\n offset: searchParams.get('offset') ?? undefined,\n })\n if (!pagination.success) {\n return NextResponse.json({ error: pagination.error.message }, { status: 400 })\n }\n const { limit, offset } = pagination.data\n\n // Verify instance exists and belongs to tenant\n const instance = await em.findOne(WorkflowInstance, {\n id: params.id,\n tenantId,\n ...orgFilter.where,\n })\n\n if (!instance) {\n return NextResponse.json(\n { error: 'Workflow instance not found' },\n { status: 404 }\n )\n }\n\n // Build where clause\n const where: any = {\n workflowInstanceId: params.id,\n tenantId,\n ...orgFilter.where,\n }\n\n if (eventType) {\n where.eventType = eventType\n }\n\n const [events, total] = await em.findAndCount(\n WorkflowEvent,\n where,\n {\n orderBy: { occurredAt: 'DESC' },\n limit,\n offset,\n }\n )\n\n return NextResponse.json({\n data: events,\n pagination: {\n total,\n limit,\n offset,\n hasMore: offset + limit < total && offset + limit <= WORKFLOW_LIST_MAX_OFFSET,\n },\n })\n } catch (error) {\n logger.error('Error getting workflow events', { err: error })\n return NextResponse.json(\n { error: 'Failed to get workflow events' },\n { status: 500 }\n )\n }\n}\n\nexport const openApi = {\n methods: {\n GET: {\n summary: 'Get workflow instance events',\n description: 'Get a chronological list of events for a workflow instance. Events track all state changes, transitions, and activities.',\n tags: ['Workflows'],\n params: z.object({\n id: z.string().uuid(),\n }),\n query: z.object({\n eventType: z.string().optional(),\n limit: workflowListPaginationSchema.shape.limit.default(100).describe(\"Integer page size from 1 to 100.\"),\n offset: workflowListPaginationSchema.shape.offset.describe(\"Integer result offset from 0 to 100000.\"),\n }),\n responses: [\n {\n status: 400,\n description: 'Invalid pagination: page size must be an integer from 1 to 100 and offset an integer from 0 to 100000.',\n schema: z.object({ error: z.string() }),\n },\n {\n status: 200,\n description: 'List of workflow events',\n schema: z.object({\n data: z.array(workflowEventRowSchema),\n pagination: paginationSchema,\n }),\n },\n {\n status: 401,\n description: 'Unauthorized',\n schema: z.object({ error: z.string() }),\n },\n {\n status: 404,\n description: 'Workflow instance not found',\n schema: z.object({ error: z.string() }),\n },\n {\n status: 500,\n description: 'Internal server error',\n schema: z.object({ error: z.string() }),\n },\n ],\n },\n },\n}\n"],
|
|
5
|
-
"mappings": "AAOA,SAAsB,oBAAoB;AAC1C,SAAS,SAAS;AAClB,SAAS,gCAAgC;AACzC,SAAS,oCAAoC;AAC7C,SAAS,8BAA8B;AACvC,SAAS,0BAA0B;AACnC,SAAS,0CAA0C;AACnD,SAAS,sCAAsC;AAC/C,SAAS,kBAAkB,qBAAqB;AAChD,SAAS,wBAAwB,wBAAwB;AACzD,SAAS,oBAAoB;AAE7B,MAAM,SAAS,aAAa,WAAW;AAEhC,MAAM,WAAW;AAAA,EACtB,aAAa;AAAA,EACb,iBAAiB,CAAC,0BAA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jB,oBAAoB,OAAO;AAAA,MAC3B;AAAA,MACA,GAAG,UAAU;AAAA,IACf;AAEA,QAAI,WAAW;AACb,YAAM,YAAY;AAAA,IACpB;AAEA,UAAM,CAAC,QAAQ,KAAK,IAAI,MAAM,GAAG;AAAA,MAC/B;AAAA,MACA;AAAA,MACA;AAAA,QACE,SAAS,EAAE,YAAY,OAAO;AAAA,
|
|
4
|
+
"sourcesContent": ["/**\n * Workflow Instance Events API\n *\n * Endpoint:\n * - GET /api/workflows/instances/[id]/events - Get event history for a workflow instance\n */\n\nimport { NextRequest, NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport { WORKFLOW_LIST_MAX_OFFSET } from '../../../../data/pagination'\nimport { workflowListPaginationSchema } from '../../../../data/validators'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { resolveOrganizationScopeForRequest } from '@open-mercato/core/modules/directory/utils/organizationScope'\nimport { resolveOrganizationScopeFilter } from '@open-mercato/core/modules/directory/utils/organizationScopeFilter'\nimport { WorkflowInstance, WorkflowEvent } from '../../../../data/entities'\nimport { workflowEventRowSchema, paginationSchema } from '../../../openapi'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('workflows')\n\nexport const metadata = {\n requireAuth: true,\n requireFeatures: ['workflows.instances.view'],\n}\n\ninterface RouteContext {\n params: Promise<{\n id: string\n }>\n}\n\n/**\n * GET /api/workflows/instances/[id]/events\n *\n * Get event history for a workflow instance\n */\nexport async function GET(\n request: NextRequest,\n context: RouteContext\n) {\n try {\n const params = await context.params\n const container = await createRequestContainer()\n const em = container.resolve('em')\n const auth = await getAuthFromRequest(request)\n\n if (!auth) {\n return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n }\n\n const scope = await resolveOrganizationScopeForRequest({ container, auth, request })\n const tenantId = auth.tenantId\n const orgFilter = resolveOrganizationScopeFilter(scope, auth)\n\n if (!tenantId) {\n return NextResponse.json(\n { error: 'Missing tenant context' },\n { status: 400 }\n )\n }\n\n const { searchParams } = new URL(request.url)\n const eventType = searchParams.get('eventType')\n const pagination = workflowListPaginationSchema.safeParse({\n limit: searchParams.get('limit') ?? 100,\n offset: searchParams.get('offset') ?? undefined,\n })\n if (!pagination.success) {\n return NextResponse.json({ error: pagination.error.message }, { status: 400 })\n }\n const { limit, offset } = pagination.data\n\n // Verify instance exists and belongs to tenant\n const instance = await em.findOne(WorkflowInstance, {\n id: params.id,\n tenantId,\n ...orgFilter.where,\n })\n\n if (!instance) {\n return NextResponse.json(\n { error: 'Workflow instance not found' },\n { status: 404 }\n )\n }\n\n // Build where clause\n const where: any = {\n workflowInstanceId: params.id,\n tenantId,\n ...orgFilter.where,\n }\n\n if (eventType) {\n where.eventType = eventType\n }\n\n const [events, total] = await em.findAndCount(\n WorkflowEvent,\n where,\n {\n orderBy: { occurredAt: 'DESC', id: 'DESC' },\n limit,\n offset,\n }\n )\n\n return NextResponse.json({\n data: events,\n pagination: {\n total,\n limit,\n offset,\n hasMore: offset + limit < total && offset + limit <= WORKFLOW_LIST_MAX_OFFSET,\n },\n })\n } catch (error) {\n logger.error('Error getting workflow events', { err: error })\n return NextResponse.json(\n { error: 'Failed to get workflow events' },\n { status: 500 }\n )\n }\n}\n\nexport const openApi = {\n methods: {\n GET: {\n summary: 'Get workflow instance events',\n description: 'Get a chronological list of events for a workflow instance. Events track all state changes, transitions, and activities.',\n tags: ['Workflows'],\n params: z.object({\n id: z.string().uuid(),\n }),\n query: z.object({\n eventType: z.string().optional(),\n limit: workflowListPaginationSchema.shape.limit.default(100).describe(\"Integer page size from 1 to 100.\"),\n offset: workflowListPaginationSchema.shape.offset.describe(\"Integer result offset from 0 to 100000.\"),\n }),\n responses: [\n {\n status: 400,\n description: 'Invalid pagination: page size must be an integer from 1 to 100 and offset an integer from 0 to 100000.',\n schema: z.object({ error: z.string() }),\n },\n {\n status: 200,\n description: 'List of workflow events',\n schema: z.object({\n data: z.array(workflowEventRowSchema),\n pagination: paginationSchema,\n }),\n },\n {\n status: 401,\n description: 'Unauthorized',\n schema: z.object({ error: z.string() }),\n },\n {\n status: 404,\n description: 'Workflow instance not found',\n schema: z.object({ error: z.string() }),\n },\n {\n status: 500,\n description: 'Internal server error',\n schema: z.object({ error: z.string() }),\n },\n ],\n },\n },\n}\n"],
|
|
5
|
+
"mappings": "AAOA,SAAsB,oBAAoB;AAC1C,SAAS,SAAS;AAClB,SAAS,gCAAgC;AACzC,SAAS,oCAAoC;AAC7C,SAAS,8BAA8B;AACvC,SAAS,0BAA0B;AACnC,SAAS,0CAA0C;AACnD,SAAS,sCAAsC;AAC/C,SAAS,kBAAkB,qBAAqB;AAChD,SAAS,wBAAwB,wBAAwB;AACzD,SAAS,oBAAoB;AAE7B,MAAM,SAAS,aAAa,WAAW;AAEhC,MAAM,WAAW;AAAA,EACtB,aAAa;AAAA,EACb,iBAAiB,CAAC,0BAA0B;AAC9C;AAaA,eAAsB,IACpB,SACA,SACA;AACA,MAAI;AACF,UAAM,SAAS,MAAM,QAAQ;AAC7B,UAAM,YAAY,MAAM,uBAAuB;AAC/C,UAAM,KAAK,UAAU,QAAQ,IAAI;AACjC,UAAM,OAAO,MAAM,mBAAmB,OAAO;AAE7C,QAAI,CAAC,MAAM;AACT,aAAO,aAAa,KAAK,EAAE,OAAO,eAAe,GAAG,EAAE,QAAQ,IAAI,CAAC;AAAA,IACrE;AAEA,UAAM,QAAQ,MAAM,mCAAmC,EAAE,WAAW,MAAM,QAAQ,CAAC;AACnF,UAAM,WAAW,KAAK;AACtB,UAAM,YAAY,+BAA+B,OAAO,IAAI;AAE5D,QAAI,CAAC,UAAU;AACb,aAAO,aAAa;AAAA,QAClB,EAAE,OAAO,yBAAyB;AAAA,QAClC,EAAE,QAAQ,IAAI;AAAA,MAChB;AAAA,IACF;AAEA,UAAM,EAAE,aAAa,IAAI,IAAI,IAAI,QAAQ,GAAG;AAC5C,UAAM,YAAY,aAAa,IAAI,WAAW;AAC9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../../../../../../../src/modules/workflows/api/instances/%5Bid%5D/steps/route.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * Workflow Step Instances API (spec \u00A78.3)\n *\n * Endpoint:\n * - GET /api/workflows/instances/[id]/steps - Per-step execution record\n *\n * `StepInstance` has always recorded `inputData`, `outputData`, `errorData`,\n * `executionTimeMs` and `retryCount`, but until this route no API or page read\n * any of it. The per-step I/O inspector and the run Gantt both need it, so the\n * read surface comes first.\n */\n\nimport { NextRequest, NextResponse } from 'next/server'\nimport { WORKFLOW_LIST_MAX_OFFSET, WORKFLOW_LIST_OFFSET_ERROR } from '../../../../data/pagination'\nimport { z } from 'zod'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { resolveOrganizationScopeForRequest } from '@open-mercato/core/modules/directory/utils/organizationScope'\nimport { resolveOrganizationScopeFilter } from '@open-mercato/core/modules/directory/utils/organizationScopeFilter'\nimport { WorkflowInstance, StepInstance } from '../../../../data/entities'\nimport { workflowStepInstanceRowSchema, paginationSchema } from '../../../openapi'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('workflows')\n\nexport const metadata = {\n requireAuth: true,\n requireFeatures: ['workflows.instances.view'],\n}\n\n/**\n * Platform cap: no list surface pages above 100 rows. A run with more step\n * executions than this reports `pagination.hasMore` so the caller can page\n * rather than silently rendering a truncated timeline.\n */\nexport const STEP_INSTANCE_PAGE_SIZE_MAX = 100\n\ninterface RouteContext {\n params: Promise<{\n id: string\n }>\n}\n\nfunction parsePositiveInt(raw: string | null, fallback: number): number {\n if (raw === null) return fallback\n const parsed = Number.parseInt(raw, 10)\n if (!Number.isFinite(parsed)) return fallback\n return parsed\n}\n\n/**\n * GET /api/workflows/instances/[id]/steps\n */\nexport async function GET(request: NextRequest, context: RouteContext) {\n try {\n const params = await context.params\n const container = await createRequestContainer()\n const em = container.resolve('em')\n const auth = await getAuthFromRequest(request)\n\n if (!auth) {\n return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n }\n\n const scope = await resolveOrganizationScopeForRequest({ container, auth, request })\n const tenantId = auth.tenantId\n const orgFilter = resolveOrganizationScopeFilter(scope, auth)\n\n if (!tenantId) {\n return NextResponse.json({ error: 'Missing tenant context' }, { status: 400 })\n }\n\n const instance = await em.findOne(WorkflowInstance, {\n id: params.id,\n tenantId,\n ...orgFilter.where,\n })\n\n if (!instance) {\n return NextResponse.json({ error: 'Workflow instance not found' }, { status: 404 })\n }\n\n const { searchParams } = new URL(request.url)\n const requestedLimit = parsePositiveInt(searchParams.get('limit'), STEP_INSTANCE_PAGE_SIZE_MAX)\n const limit = Math.min(Math.max(requestedLimit, 1), STEP_INSTANCE_PAGE_SIZE_MAX)\n const offset = Math.max(parsePositiveInt(searchParams.get('offset'), 0), 0)\n if (offset > WORKFLOW_LIST_MAX_OFFSET) {\n return NextResponse.json({ error: WORKFLOW_LIST_OFFSET_ERROR }, { status: 400 })\n }\n\n // Ordered by when the step was entered so the Gantt and the overlay read the\n // run in execution order. `createdAt` is the tiebreaker because a step\n // instance is persisted before `enteredAt` is stamped on some paths.\n const [steps, total] = await em.findAndCount(\n StepInstance,\n {\n workflowInstanceId: params.id,\n tenantId,\n ...orgFilter.where,\n },\n {\n orderBy: [{ enteredAt: 'ASC' }, { createdAt: 'ASC' }],\n limit,\n offset,\n }\n )\n\n return NextResponse.json({\n data: steps,\n pagination: {\n total,\n limit,\n offset,\n hasMore: offset + limit < total,\n },\n })\n } catch (error) {\n logger.error('Error getting workflow step instances', { err: error })\n return NextResponse.json({ error: 'Failed to get workflow step instances' }, { status: 500 })\n }\n}\n\nexport const openApi = {\n methods: {\n GET: {\n summary: 'Get workflow instance step executions',\n description:\n 'List the step executions recorded for a workflow instance, including per-step input, output, error payload, duration and attempt count.',\n tags: ['Workflows'],\n params: z.object({\n id: z.string().uuid(),\n }),\n query: z.object({\n limit: z.number().int().positive().max(STEP_INSTANCE_PAGE_SIZE_MAX).default(STEP_INSTANCE_PAGE_SIZE_MAX).optional(),\n offset: z.number().int().min(0).max(WORKFLOW_LIST_MAX_OFFSET).default(0).optional(),\n }),\n responses: [\n {\n status: 400,\n description: 'Requested pagination offset exceeds 100000 (WORKFLOW_LIST_OFFSET_EXCEEDED).',\n schema: z.object({ error: z.string() }),\n },\n {\n status: 200,\n description: 'List of step executions',\n schema: z.object({\n data: z.array(workflowStepInstanceRowSchema),\n pagination: paginationSchema,\n }),\n },\n {\n status: 401,\n description: 'Unauthorized',\n schema: z.object({ error: z.string() }),\n },\n {\n status: 404,\n description: 'Workflow instance not found',\n schema: z.object({ error: z.string() }),\n },\n {\n status: 500,\n description: 'Internal server error',\n schema: z.object({ error: z.string() }),\n },\n ],\n },\n },\n}\n"],
|
|
5
|
-
"mappings": "AAYA,SAAsB,oBAAoB;AAC1C,SAAS,0BAA0B,kCAAkC;AACrE,SAAS,SAAS;AAClB,SAAS,8BAA8B;AACvC,SAAS,0BAA0B;AACnC,SAAS,0CAA0C;AACnD,SAAS,sCAAsC;AAC/C,SAAS,kBAAkB,oBAAoB;AAC/C,SAAS,+BAA+B,wBAAwB;AAChE,SAAS,oBAAoB;AAE7B,MAAM,SAAS,aAAa,WAAW;AAEhC,MAAM,WAAW;AAAA,EACtB,aAAa;AAAA,EACb,iBAAiB,CAAC,0BAA0B;AAC9C;AAOO,MAAM,8BAA8B;AAQ3C,SAAS,iBAAiB,KAAoB,UAA0B;AACtE,MAAI,QAAQ,KAAM,QAAO;AACzB,QAAM,SAAS,OAAO,SAAS,KAAK,EAAE;AACtC,MAAI,CAAC,OAAO,SAAS,MAAM,EAAG,QAAO;AACrC,SAAO;AACT;AAKA,eAAsB,IAAI,SAAsB,SAAuB;AACrE,MAAI;AACF,UAAM,SAAS,MAAM,QAAQ;AAC7B,UAAM,YAAY,MAAM,uBAAuB;AAC/C,UAAM,KAAK,UAAU,QAAQ,IAAI;AACjC,UAAM,OAAO,MAAM,mBAAmB,OAAO;AAE7C,QAAI,CAAC,MAAM;AACT,aAAO,aAAa,KAAK,EAAE,OAAO,eAAe,GAAG,EAAE,QAAQ,IAAI,CAAC;AAAA,IACrE;AAEA,UAAM,QAAQ,MAAM,mCAAmC,EAAE,WAAW,MAAM,QAAQ,CAAC;AACnF,UAAM,WAAW,KAAK;AACtB,UAAM,YAAY,+BAA+B,OAAO,IAAI;AAE5D,QAAI,CAAC,UAAU;AACb,aAAO,aAAa,KAAK,EAAE,OAAO,yBAAyB,GAAG,EAAE,QAAQ,IAAI,CAAC;AAAA,IAC/E;AAEA,UAAM,WAAW,MAAM,GAAG,QAAQ,kBAAkB;AAAA,MAClD,IAAI,OAAO;AAAA,MACX;AAAA,MACA,GAAG,UAAU;AAAA,IACf,CAAC;AAED,QAAI,CAAC,UAAU;AACb,aAAO,aAAa,KAAK,EAAE,OAAO,8BAA8B,GAAG,EAAE,QAAQ,IAAI,CAAC;AAAA,IACpF;AAEA,UAAM,EAAE,aAAa,IAAI,IAAI,IAAI,QAAQ,GAAG;AAC5C,UAAM,iBAAiB,iBAAiB,aAAa,IAAI,OAAO,GAAG,2BAA2B;AAC9F,UAAM,QAAQ,KAAK,IAAI,KAAK,IAAI,gBAAgB,CAAC,GAAG,2BAA2B;AAC/E,UAAM,SAAS,KAAK,IAAI,iBAAiB,aAAa,IAAI,QAAQ,GAAG,CAAC,GAAG,CAAC;AAC1E,QAAI,SAAS,0BAA0B;AACrC,aAAO,aAAa,KAAK,EAAE,OAAO,2BAA2B,GAAG,EAAE,QAAQ,IAAI,CAAC;AAAA,IACjF;
|
|
4
|
+
"sourcesContent": ["/**\n * Workflow Step Instances API (spec \u00A78.3)\n *\n * Endpoint:\n * - GET /api/workflows/instances/[id]/steps - Per-step execution record\n *\n * `StepInstance` has always recorded `inputData`, `outputData`, `errorData`,\n * `executionTimeMs` and `retryCount`, but until this route no API or page read\n * any of it. The per-step I/O inspector and the run Gantt both need it, so the\n * read surface comes first.\n */\n\nimport { NextRequest, NextResponse } from 'next/server'\nimport { WORKFLOW_LIST_MAX_OFFSET, WORKFLOW_LIST_OFFSET_ERROR } from '../../../../data/pagination'\nimport { z } from 'zod'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { resolveOrganizationScopeForRequest } from '@open-mercato/core/modules/directory/utils/organizationScope'\nimport { resolveOrganizationScopeFilter } from '@open-mercato/core/modules/directory/utils/organizationScopeFilter'\nimport { WorkflowInstance, StepInstance } from '../../../../data/entities'\nimport { workflowStepInstanceRowSchema, paginationSchema } from '../../../openapi'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('workflows')\n\nexport const metadata = {\n requireAuth: true,\n requireFeatures: ['workflows.instances.view'],\n}\n\n/**\n * Platform cap: no list surface pages above 100 rows. A run with more step\n * executions than this reports `pagination.hasMore` so the caller can page\n * rather than silently rendering a truncated timeline.\n */\nexport const STEP_INSTANCE_PAGE_SIZE_MAX = 100\n\ninterface RouteContext {\n params: Promise<{\n id: string\n }>\n}\n\nfunction parsePositiveInt(raw: string | null, fallback: number): number {\n if (raw === null) return fallback\n const parsed = Number.parseInt(raw, 10)\n if (!Number.isFinite(parsed)) return fallback\n return parsed\n}\n\n/**\n * GET /api/workflows/instances/[id]/steps\n */\nexport async function GET(request: NextRequest, context: RouteContext) {\n try {\n const params = await context.params\n const container = await createRequestContainer()\n const em = container.resolve('em')\n const auth = await getAuthFromRequest(request)\n\n if (!auth) {\n return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n }\n\n const scope = await resolveOrganizationScopeForRequest({ container, auth, request })\n const tenantId = auth.tenantId\n const orgFilter = resolveOrganizationScopeFilter(scope, auth)\n\n if (!tenantId) {\n return NextResponse.json({ error: 'Missing tenant context' }, { status: 400 })\n }\n\n const instance = await em.findOne(WorkflowInstance, {\n id: params.id,\n tenantId,\n ...orgFilter.where,\n })\n\n if (!instance) {\n return NextResponse.json({ error: 'Workflow instance not found' }, { status: 404 })\n }\n\n const { searchParams } = new URL(request.url)\n const requestedLimit = parsePositiveInt(searchParams.get('limit'), STEP_INSTANCE_PAGE_SIZE_MAX)\n const limit = Math.min(Math.max(requestedLimit, 1), STEP_INSTANCE_PAGE_SIZE_MAX)\n const offset = Math.max(parsePositiveInt(searchParams.get('offset'), 0), 0)\n if (offset > WORKFLOW_LIST_MAX_OFFSET) {\n return NextResponse.json({ error: WORKFLOW_LIST_OFFSET_ERROR }, { status: 400 })\n }\n\n // Ordered by when the step was entered so the Gantt and the overlay read the\n // run in execution order. `createdAt` is the tiebreaker because a step\n // instance is persisted before `enteredAt` is stamped on some paths, and\n // `id` comes last so steps sharing both timestamps page deterministically.\n const [steps, total] = await em.findAndCount(\n StepInstance,\n {\n workflowInstanceId: params.id,\n tenantId,\n ...orgFilter.where,\n },\n {\n orderBy: [{ enteredAt: 'ASC' }, { createdAt: 'ASC' }, { id: 'ASC' }],\n limit,\n offset,\n }\n )\n\n return NextResponse.json({\n data: steps,\n pagination: {\n total,\n limit,\n offset,\n hasMore: offset + limit < total,\n },\n })\n } catch (error) {\n logger.error('Error getting workflow step instances', { err: error })\n return NextResponse.json({ error: 'Failed to get workflow step instances' }, { status: 500 })\n }\n}\n\nexport const openApi = {\n methods: {\n GET: {\n summary: 'Get workflow instance step executions',\n description:\n 'List the step executions recorded for a workflow instance, including per-step input, output, error payload, duration and attempt count.',\n tags: ['Workflows'],\n params: z.object({\n id: z.string().uuid(),\n }),\n query: z.object({\n limit: z.number().int().positive().max(STEP_INSTANCE_PAGE_SIZE_MAX).default(STEP_INSTANCE_PAGE_SIZE_MAX).optional(),\n offset: z.number().int().min(0).max(WORKFLOW_LIST_MAX_OFFSET).default(0).optional(),\n }),\n responses: [\n {\n status: 400,\n description: 'Requested pagination offset exceeds 100000 (WORKFLOW_LIST_OFFSET_EXCEEDED).',\n schema: z.object({ error: z.string() }),\n },\n {\n status: 200,\n description: 'List of step executions',\n schema: z.object({\n data: z.array(workflowStepInstanceRowSchema),\n pagination: paginationSchema,\n }),\n },\n {\n status: 401,\n description: 'Unauthorized',\n schema: z.object({ error: z.string() }),\n },\n {\n status: 404,\n description: 'Workflow instance not found',\n schema: z.object({ error: z.string() }),\n },\n {\n status: 500,\n description: 'Internal server error',\n schema: z.object({ error: z.string() }),\n },\n ],\n },\n },\n}\n"],
|
|
5
|
+
"mappings": "AAYA,SAAsB,oBAAoB;AAC1C,SAAS,0BAA0B,kCAAkC;AACrE,SAAS,SAAS;AAClB,SAAS,8BAA8B;AACvC,SAAS,0BAA0B;AACnC,SAAS,0CAA0C;AACnD,SAAS,sCAAsC;AAC/C,SAAS,kBAAkB,oBAAoB;AAC/C,SAAS,+BAA+B,wBAAwB;AAChE,SAAS,oBAAoB;AAE7B,MAAM,SAAS,aAAa,WAAW;AAEhC,MAAM,WAAW;AAAA,EACtB,aAAa;AAAA,EACb,iBAAiB,CAAC,0BAA0B;AAC9C;AAOO,MAAM,8BAA8B;AAQ3C,SAAS,iBAAiB,KAAoB,UAA0B;AACtE,MAAI,QAAQ,KAAM,QAAO;AACzB,QAAM,SAAS,OAAO,SAAS,KAAK,EAAE;AACtC,MAAI,CAAC,OAAO,SAAS,MAAM,EAAG,QAAO;AACrC,SAAO;AACT;AAKA,eAAsB,IAAI,SAAsB,SAAuB;AACrE,MAAI;AACF,UAAM,SAAS,MAAM,QAAQ;AAC7B,UAAM,YAAY,MAAM,uBAAuB;AAC/C,UAAM,KAAK,UAAU,QAAQ,IAAI;AACjC,UAAM,OAAO,MAAM,mBAAmB,OAAO;AAE7C,QAAI,CAAC,MAAM;AACT,aAAO,aAAa,KAAK,EAAE,OAAO,eAAe,GAAG,EAAE,QAAQ,IAAI,CAAC;AAAA,IACrE;AAEA,UAAM,QAAQ,MAAM,mCAAmC,EAAE,WAAW,MAAM,QAAQ,CAAC;AACnF,UAAM,WAAW,KAAK;AACtB,UAAM,YAAY,+BAA+B,OAAO,IAAI;AAE5D,QAAI,CAAC,UAAU;AACb,aAAO,aAAa,KAAK,EA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A,EACF;AACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -80,7 +80,7 @@ async function GET(request) {
|
|
|
80
80
|
};
|
|
81
81
|
if (workflowId) where.workflowId = workflowId;
|
|
82
82
|
const scanned = await em.find(WorkflowInstance, where, {
|
|
83
|
-
orderBy: { createdAt: "DESC" },
|
|
83
|
+
orderBy: { createdAt: "DESC", id: "DESC" },
|
|
84
84
|
limit: FAILURE_GROUP_SCAN_LIMIT
|
|
85
85
|
});
|
|
86
86
|
const scannedInputs = scanned.map(toTriageInput);
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../../../src/modules/workflows/api/instances/failure-queue/route.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * Failure-queue triage API (spec \u00A78.4)\n *\n * Endpoint:\n * - GET /api/workflows/instances/failure-queue\n *\n * The triage set is \"instances parked by a `failureQueue` directive PLUS FAILED\n * instances\". The list route cannot express that: its `attention` and `status`\n * filters are ANDed, and this is a union.\n */\n\nimport { NextRequest, NextResponse } from 'next/server'\nimport { WORKFLOW_LIST_MAX_OFFSET, WORKFLOW_LIST_OFFSET_ERROR } from '../../../data/pagination'\nimport { z } from 'zod'\nimport { raw } from '@mikro-orm/core'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { resolveOrganizationScopeForRequest } from '@open-mercato/core/modules/directory/utils/organizationScope'\nimport { resolveOrganizationScopeFilter } from '@open-mercato/core/modules/directory/utils/organizationScopeFilter'\nimport { WorkflowInstance } from '../../../data/entities'\nimport { workflowInstanceResponseSchema, paginationSchema } from '../../openapi'\nimport {\n groupFailures,\n matchesFailureGroup,\n type TriageInstanceInput,\n} from '../../../lib/failure-grouping'\nimport { WORKFLOW_ATTENTION_OUTCOMES } from '../../../lib/run-outcome'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('workflows')\n\nexport const metadata = {\n requireAuth: true,\n requireFeatures: ['workflows.instances.view'],\n}\n\n/** Platform list cap. */\nexport const FAILURE_QUEUE_PAGE_SIZE_MAX = 100\n\n/**\n * How many rows the error grouping scans. Grouping normalizes each message in\n * JS, so it cannot be a SQL `GROUP BY`; the response reports `scannedCount` and\n * `groupsTruncated` rather than pretending the groups cover everything.\n */\nexport const FAILURE_GROUP_SCAN_LIMIT = 500\n\nfunction parsePositiveInt(rawValue: string | null, fallback: number): number {\n if (rawValue === null) return fallback\n const parsed = Number.parseInt(rawValue, 10)\n return Number.isFinite(parsed) ? parsed : fallback\n}\n\nfunction toTriageInput(instance: WorkflowInstance): TriageInstanceInput {\n return {\n id: instance.id,\n workflowId: instance.workflowId,\n status: instance.status,\n errorMessage: instance.errorMessage ?? null,\n attentionReason: instance.metadata?.attention?.reason ?? null,\n outcome: instance.outcome ?? null,\n }\n}\n\nexport async function GET(request: NextRequest) {\n try {\n const container = await createRequestContainer()\n const em = container.resolve('em')\n const auth = await getAuthFromRequest(request)\n\n if (!auth) {\n return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n }\n\n const scope = await resolveOrganizationScopeForRequest({ container, auth, request })\n const tenantId = auth.tenantId\n const orgFilter = resolveOrganizationScopeFilter(scope, auth)\n\n if (!tenantId) {\n return NextResponse.json({ error: 'Missing tenant context' }, { status: 400 })\n }\n\n const { searchParams } = new URL(request.url)\n const workflowId = searchParams.get('workflowId')\n const errorGroup = searchParams.get('errorGroup')\n const requestedLimit = parsePositiveInt(searchParams.get('limit'), 50)\n const limit = Math.min(Math.max(requestedLimit, 1), FAILURE_QUEUE_PAGE_SIZE_MAX)\n const offset = Math.max(parsePositiveInt(searchParams.get('offset'), 0), 0)\n if (offset > WORKFLOW_LIST_MAX_OFFSET) {\n return NextResponse.json({ error: WORKFLOW_LIST_OFFSET_ERROR }, { status: 400 })\n }\n\n const attentionPath = raw(`(metadata #>> '{attention,reason}')`)\n const where: Record<string, unknown> = {\n tenantId,\n ...orgFilter.where,\n // A simulation that \"failed\" is a report about a definition, never a run\n // an operator must triage \u2014 and replaying one from here would start a\n // REAL instance from a dry-run's context. The run list has excluded dry\n // runs by default since spec \u00A78.2; this union missed the same filter.\n isDryRun: false,\n // A `partial_failure` reached END and was written COMPLETED, so neither\n // the status arm nor the attention arm reaches it \u2014 and a run nobody\n // looks at because it said COMPLETED is exactly the failure the outcome\n // verdict exists to remove. Third arm, same union.\n $or: [\n { status: 'FAILED' },\n { outcome: { $in: [...WORKFLOW_ATTENTION_OUTCOMES] } },\n { [attentionPath]: { $ne: null } },\n ],\n }\n if (workflowId) where.workflowId = workflowId\n\n // Grouping first, over a bounded scan, so the group counts describe the\n // same set the caller is paging through.\n const scanned = (await em.find(WorkflowInstance, where, {\n orderBy: { createdAt: 'DESC' },\n limit: FAILURE_GROUP_SCAN_LIMIT,\n })) as WorkflowInstance[]\n const scannedInputs = scanned.map(toTriageInput)\n const groups = groupFailures(scannedInputs)\n\n let rows = scanned\n if (errorGroup) {\n rows = scanned.filter((instance) => matchesFailureGroup(toTriageInput(instance), errorGroup))\n }\n\n const total = errorGroup\n ? rows.length\n : await em.count(WorkflowInstance, where)\n\n return NextResponse.json({\n data: rows.slice(offset, offset + limit),\n groups,\n grouping: {\n scannedCount: scanned.length,\n scanLimit: FAILURE_GROUP_SCAN_LIMIT,\n truncated: scanned.length >= FAILURE_GROUP_SCAN_LIMIT,\n },\n pagination: {\n total,\n limit,\n offset,\n hasMore: offset + limit < total,\n },\n })\n } catch (error) {\n logger.error('Error listing the workflow failure queue', { err: error })\n return NextResponse.json({ error: 'Failed to list the workflow failure queue' }, { status: 500 })\n }\n}\n\nexport const failureGroupSchema = z.object({\n key: z.string(),\n label: z.string(),\n count: z.number().int().nonnegative(),\n workflowIds: z.array(z.string()),\n instanceIds: z.array(z.string().uuid()),\n})\n\nexport const openApi = {\n methods: {\n GET: {\n summary: 'List the workflow failure queue',\n description:\n 'Triage list of instances parked by a failure-queue error directive together with FAILED instances, plus normalized error groups so a batch of similar failures reads as one row.',\n tags: ['Workflows'],\n query: z.object({\n workflowId: z.string().optional(),\n errorGroup: z.string().optional().describe('Narrow the list to one normalized error group key.'),\n limit: z.number().int().positive().max(FAILURE_QUEUE_PAGE_SIZE_MAX).default(50).optional(),\n offset: z.number().int().min(0).max(WORKFLOW_LIST_MAX_OFFSET).default(0).optional(),\n }),\n responses: [\n {\n status: 400,\n description: 'Requested pagination offset exceeds 100000 (WORKFLOW_LIST_OFFSET_EXCEEDED).',\n schema: z.object({ error: z.string() }),\n },\n {\n status: 200,\n description: 'Failure queue',\n schema: z.object({\n data: z.array(workflowInstanceResponseSchema),\n groups: z.array(failureGroupSchema),\n grouping: z.object({\n scannedCount: z.number().int().nonnegative(),\n scanLimit: z.number().int().positive(),\n truncated: z.boolean(),\n }),\n pagination: paginationSchema,\n }),\n },\n {\n status: 401,\n description: 'Unauthorized',\n schema: z.object({ error: z.string() }),\n },\n {\n status: 500,\n description: 'Internal server error',\n schema: z.object({ error: z.string() }),\n },\n ],\n },\n },\n}\n"],
|
|
5
|
-
"mappings": "AAWA,SAAsB,oBAAoB;AAC1C,SAAS,0BAA0B,kCAAkC;AACrE,SAAS,SAAS;AAClB,SAAS,WAAW;AACpB,SAAS,8BAA8B;AACvC,SAAS,0BAA0B;AACnC,SAAS,0CAA0C;AACnD,SAAS,sCAAsC;AAC/C,SAAS,wBAAwB;AACjC,SAAS,gCAAgC,wBAAwB;AACjE;AAAA,EACE;AAAA,EACA;AAAA,OAEK;AACP,SAAS,mCAAmC;AAC5C,SAAS,oBAAoB;AAE7B,MAAM,SAAS,aAAa,WAAW;AAEhC,MAAM,WAAW;AAAA,EACtB,aAAa;AAAA,EACb,iBAAiB,CAAC,0BAA0B;AAC9C;AAGO,MAAM,8BAA8B;AAOpC,MAAM,2BAA2B;AAExC,SAAS,iBAAiB,UAAyB,UAA0B;AAC3E,MAAI,aAAa,KAAM,QAAO;AAC9B,QAAM,SAAS,OAAO,SAAS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AI,CAAC;AAAA,IACjF;AAEA,UAAM,gBAAgB,IAAI,qCAAqC;AAC/D,UAAM,QAAiC;AAAA,MACrC;AAAA,MACA,GAAG,UAAU;AAAA;AAAA;AAAA;AAAA;AAAA,MAKb,UAAU;AAAA;AAAA;AAAA;AAAA;AAAA,MAKV,KAAK;AAAA,QACH,EAAE,QAAQ,SAAS;AAAA,QACnB,EAAE,SAAS,EAAE,KAAK,CAAC,GAAG,2BAA2B,EAAE,EAAE;AAAA,QACrD,EAAE,CAAC,aAAa,GAAG,EAAE,KAAK,KAAK,EAAE;AAAA,MACnC;AAAA,IACF;AACA,QAAI,WAAY,OAAM,aAAa;AAInC,UAAM,UAAW,MAAM,GAAG,KAAK,kBAAkB,OAAO;AAAA,MACtD,SAAS,EAAE,WAAW,OAAO;AAAA,
|
|
4
|
+
"sourcesContent": ["/**\n * Failure-queue triage API (spec \u00A78.4)\n *\n * Endpoint:\n * - GET /api/workflows/instances/failure-queue\n *\n * The triage set is \"instances parked by a `failureQueue` directive PLUS FAILED\n * instances\". The list route cannot express that: its `attention` and `status`\n * filters are ANDed, and this is a union.\n */\n\nimport { NextRequest, NextResponse } from 'next/server'\nimport { WORKFLOW_LIST_MAX_OFFSET, WORKFLOW_LIST_OFFSET_ERROR } from '../../../data/pagination'\nimport { z } from 'zod'\nimport { raw } from '@mikro-orm/core'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { resolveOrganizationScopeForRequest } from '@open-mercato/core/modules/directory/utils/organizationScope'\nimport { resolveOrganizationScopeFilter } from '@open-mercato/core/modules/directory/utils/organizationScopeFilter'\nimport { WorkflowInstance } from '../../../data/entities'\nimport { workflowInstanceResponseSchema, paginationSchema } from '../../openapi'\nimport {\n groupFailures,\n matchesFailureGroup,\n type TriageInstanceInput,\n} from '../../../lib/failure-grouping'\nimport { WORKFLOW_ATTENTION_OUTCOMES } from '../../../lib/run-outcome'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('workflows')\n\nexport const metadata = {\n requireAuth: true,\n requireFeatures: ['workflows.instances.view'],\n}\n\n/** Platform list cap. */\nexport const FAILURE_QUEUE_PAGE_SIZE_MAX = 100\n\n/**\n * How many rows the error grouping scans. Grouping normalizes each message in\n * JS, so it cannot be a SQL `GROUP BY`; the response reports `scannedCount` and\n * `groupsTruncated` rather than pretending the groups cover everything.\n */\nexport const FAILURE_GROUP_SCAN_LIMIT = 500\n\nfunction parsePositiveInt(rawValue: string | null, fallback: number): number {\n if (rawValue === null) return fallback\n const parsed = Number.parseInt(rawValue, 10)\n return Number.isFinite(parsed) ? parsed : fallback\n}\n\nfunction toTriageInput(instance: WorkflowInstance): TriageInstanceInput {\n return {\n id: instance.id,\n workflowId: instance.workflowId,\n status: instance.status,\n errorMessage: instance.errorMessage ?? null,\n attentionReason: instance.metadata?.attention?.reason ?? null,\n outcome: instance.outcome ?? null,\n }\n}\n\nexport async function GET(request: NextRequest) {\n try {\n const container = await createRequestContainer()\n const em = container.resolve('em')\n const auth = await getAuthFromRequest(request)\n\n if (!auth) {\n return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n }\n\n const scope = await resolveOrganizationScopeForRequest({ container, auth, request })\n const tenantId = auth.tenantId\n const orgFilter = resolveOrganizationScopeFilter(scope, auth)\n\n if (!tenantId) {\n return NextResponse.json({ error: 'Missing tenant context' }, { status: 400 })\n }\n\n const { searchParams } = new URL(request.url)\n const workflowId = searchParams.get('workflowId')\n const errorGroup = searchParams.get('errorGroup')\n const requestedLimit = parsePositiveInt(searchParams.get('limit'), 50)\n const limit = Math.min(Math.max(requestedLimit, 1), FAILURE_QUEUE_PAGE_SIZE_MAX)\n const offset = Math.max(parsePositiveInt(searchParams.get('offset'), 0), 0)\n if (offset > WORKFLOW_LIST_MAX_OFFSET) {\n return NextResponse.json({ error: WORKFLOW_LIST_OFFSET_ERROR }, { status: 400 })\n }\n\n const attentionPath = raw(`(metadata #>> '{attention,reason}')`)\n const where: Record<string, unknown> = {\n tenantId,\n ...orgFilter.where,\n // A simulation that \"failed\" is a report about a definition, never a run\n // an operator must triage \u2014 and replaying one from here would start a\n // REAL instance from a dry-run's context. The run list has excluded dry\n // runs by default since spec \u00A78.2; this union missed the same filter.\n isDryRun: false,\n // A `partial_failure` reached END and was written COMPLETED, so neither\n // the status arm nor the attention arm reaches it \u2014 and a run nobody\n // looks at because it said COMPLETED is exactly the failure the outcome\n // verdict exists to remove. Third arm, same union.\n $or: [\n { status: 'FAILED' },\n { outcome: { $in: [...WORKFLOW_ATTENTION_OUTCOMES] } },\n { [attentionPath]: { $ne: null } },\n ],\n }\n if (workflowId) where.workflowId = workflowId\n\n // Grouping first, over a bounded scan, so the group counts describe the\n // same set the caller is paging through.\n const scanned = (await em.find(WorkflowInstance, where, {\n orderBy: { createdAt: 'DESC', id: 'DESC' },\n limit: FAILURE_GROUP_SCAN_LIMIT,\n })) as WorkflowInstance[]\n const scannedInputs = scanned.map(toTriageInput)\n const groups = groupFailures(scannedInputs)\n\n let rows = scanned\n if (errorGroup) {\n rows = scanned.filter((instance) => matchesFailureGroup(toTriageInput(instance), errorGroup))\n }\n\n const total = errorGroup\n ? rows.length\n : await em.count(WorkflowInstance, where)\n\n return NextResponse.json({\n data: rows.slice(offset, offset + limit),\n groups,\n grouping: {\n scannedCount: scanned.length,\n scanLimit: FAILURE_GROUP_SCAN_LIMIT,\n truncated: scanned.length >= FAILURE_GROUP_SCAN_LIMIT,\n },\n pagination: {\n total,\n limit,\n offset,\n hasMore: offset + limit < total,\n },\n })\n } catch (error) {\n logger.error('Error listing the workflow failure queue', { err: error })\n return NextResponse.json({ error: 'Failed to list the workflow failure queue' }, { status: 500 })\n }\n}\n\nexport const failureGroupSchema = z.object({\n key: z.string(),\n label: z.string(),\n count: z.number().int().nonnegative(),\n workflowIds: z.array(z.string()),\n instanceIds: z.array(z.string().uuid()),\n})\n\nexport const openApi = {\n methods: {\n GET: {\n summary: 'List the workflow failure queue',\n description:\n 'Triage list of instances parked by a failure-queue error directive together with FAILED instances, plus normalized error groups so a batch of similar failures reads as one row.',\n tags: ['Workflows'],\n query: z.object({\n workflowId: z.string().optional(),\n errorGroup: z.string().optional().describe('Narrow the list to one normalized error group key.'),\n limit: z.number().int().positive().max(FAILURE_QUEUE_PAGE_SIZE_MAX).default(50).optional(),\n offset: z.number().int().min(0).max(WORKFLOW_LIST_MAX_OFFSET).default(0).optional(),\n }),\n responses: [\n {\n status: 400,\n description: 'Requested pagination offset exceeds 100000 (WORKFLOW_LIST_OFFSET_EXCEEDED).',\n schema: z.object({ error: z.string() }),\n },\n {\n status: 200,\n description: 'Failure queue',\n schema: z.object({\n data: z.array(workflowInstanceResponseSchema),\n groups: z.array(failureGroupSchema),\n grouping: z.object({\n scannedCount: z.number().int().nonnegative(),\n scanLimit: z.number().int().positive(),\n truncated: z.boolean(),\n }),\n pagination: paginationSchema,\n }),\n },\n {\n status: 401,\n description: 'Unauthorized',\n schema: z.object({ error: z.string() }),\n },\n {\n status: 500,\n description: 'Internal server error',\n schema: z.object({ error: z.string() }),\n },\n ],\n },\n },\n}\n"],
|
|
5
|
+
"mappings": "AAWA,SAAsB,oBAAoB;AAC1C,SAAS,0BAA0B,kCAAkC;AACrE,SAAS,SAAS;AAClB,SAAS,WAAW;AACpB,SAAS,8BAA8B;AACvC,SAAS,0BAA0B;AACnC,SAAS,0CAA0C;AACnD,SAAS,sCAAsC;AAC/C,SAAS,wBAAwB;AACjC,SAAS,gCAAgC,wBAAwB;AACjE;AAAA,EACE;AAAA,EACA;AAAA,OAEK;AACP,SAAS,mCAAmC;AAC5C,SAAS,oBAAoB;AAE7B,MAAM,SAAS,aAAa,WAAW;AAEhC,MAAM,WAAW;AAAA,EACtB,aAAa;AAAA,EACb,iBAAiB,CAAC,0BAA0B;AAC9C;AAGO,MAAM,8BAA8B;AAOpC,MAAM,2BAA2B;AAExC,SAAS,iBAAiB,UAAyB,UAA0B;AAC3E,MAAI,aAA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AAE,OAAO,EAAE,IAAI,EAAE,SAAS;AAAA,cACrC,WAAW,EAAE,QAAQ;AAAA,YACvB,CAAC;AAAA,YACD,YAAY;AAAA,UACd,CAAC;AAAA,QACH;AAAA,QACA;AAAA,UACE,QAAQ;AAAA,UACR,aAAa;AAAA,UACb,QAAQ,EAAE,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,CAAC;AAAA,QACxC;AAAA,QACA;AAAA,UACE,QAAQ;AAAA,UACR,aAAa;AAAA,UACb,QAAQ,EAAE,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,CAAC;AAAA,QACxC;AAAA,MACF;AAAA,IACF;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/event-logger.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * Workflows Module - Event Logger Service\n *\n * Consolidates workflow event logging for audit trail and replay:\n * - Log workflow lifecycle events\n * - Log step execution events\n * - Log transition events\n * - Query event history\n *\n * Functional API (no classes) following Open Mercato conventions.\n */\n\nimport { EntityManager } from '@mikro-orm/core'\nimport { WorkflowEvent } from '../data/entities'\n\n// ============================================================================\n// Event Type Constants\n// ============================================================================\n\nexport const WorkflowEventTypes = {\n // Workflow lifecycle\n WORKFLOW_STARTED: 'WORKFLOW_STARTED',\n WORKFLOW_COMPLETED: 'WORKFLOW_COMPLETED',\n WORKFLOW_FAILED: 'WORKFLOW_FAILED',\n WORKFLOW_CANCELLED: 'WORKFLOW_CANCELLED',\n WORKFLOW_PAUSED: 'WORKFLOW_PAUSED',\n WORKFLOW_RESUMED: 'WORKFLOW_RESUMED',\n\n // Step lifecycle\n STEP_ENTERED: 'STEP_ENTERED',\n STEP_EXITED: 'STEP_EXITED',\n STEP_FAILED: 'STEP_FAILED',\n STEP_SKIPPED: 'STEP_SKIPPED',\n\n // Transition events\n TRANSITION_EXECUTED: 'TRANSITION_EXECUTED',\n TRANSITION_REJECTED: 'TRANSITION_REJECTED',\n TRANSITION_POST_CONDITION_FAILED: 'TRANSITION_POST_CONDITION_FAILED',\n TRANSITION_FAILED: 'TRANSITION_FAILED',\n\n // Activity events\n ACTIVITY_SCHEDULED: 'ACTIVITY_SCHEDULED',\n ACTIVITY_STARTED: 'ACTIVITY_STARTED',\n ACTIVITY_COMPLETED: 'ACTIVITY_COMPLETED',\n ACTIVITY_FAILED: 'ACTIVITY_FAILED',\n ACTIVITY_RETRY: 'ACTIVITY_RETRY',\n\n // User task events\n USER_TASK_CREATED: 'USER_TASK_CREATED',\n USER_TASK_ASSIGNED: 'USER_TASK_ASSIGNED',\n USER_TASK_STARTED: 'USER_TASK_STARTED',\n USER_TASK_COMPLETED: 'USER_TASK_COMPLETED',\n USER_TASK_CANCELLED: 'USER_TASK_CANCELLED',\n USER_TASK_ESCALATED: 'USER_TASK_ESCALATED',\n\n // Sub-workflow events (Phase 8)\n SUB_WORKFLOW_STARTED: 'SUB_WORKFLOW_STARTED',\n SUB_WORKFLOW_COMPLETED: 'SUB_WORKFLOW_COMPLETED',\n SUB_WORKFLOW_FAILED: 'SUB_WORKFLOW_FAILED',\n\n // Compensation events (Phase 8)\n COMPENSATION_STARTED: 'COMPENSATION_STARTED',\n COMPENSATION_COMPLETED: 'COMPENSATION_COMPLETED',\n COMPENSATION_PARTIAL: 'COMPENSATION_PARTIAL',\n COMPENSATION_FAILED: 'COMPENSATION_FAILED',\n COMPENSATION_ACTIVITY_STARTED: 'COMPENSATION_ACTIVITY_STARTED',\n COMPENSATION_ACTIVITY_COMPLETED: 'COMPENSATION_ACTIVITY_COMPLETED',\n COMPENSATION_ACTIVITY_FAILED: 'COMPENSATION_ACTIVITY_FAILED',\n\n // Signal events (Phase 9)\n SIGNAL_AWAITING: 'SIGNAL_AWAITING',\n SIGNAL_RECEIVED: 'SIGNAL_RECEIVED',\n SIGNAL_TIMEOUT: 'SIGNAL_TIMEOUT',\n\n // Error routing (spec 5.9)\n ERROR_ROUTED: 'ERROR_ROUTED',\n ERROR_DIRECTIVE_APPLIED: 'ERROR_DIRECTIVE_APPLIED',\n ERROR_PARKED: 'ERROR_PARKED',\n ERROR_HANDLER_SCHEDULED: 'ERROR_HANDLER_SCHEDULED',\n ERROR_HANDLER_STARTED: 'ERROR_HANDLER_STARTED',\n ERROR_HANDLER_SKIPPED: 'ERROR_HANDLER_SKIPPED',\n\n // Recovery (spec 8.4). `STEP_RERUN` carries `{ stepId, editedContextDiff, by }`\n // and is the audit record of a rerun \u2014 the terminal StepInstance of the\n // previous attempt is never touched, so the event log is where the two\n // attempts are linked.\n STEP_RERUN: 'STEP_RERUN',\n\n // Agent outcome routing (spec 7.2)\n OUTCOME_ROUTED: 'OUTCOME_ROUTED',\n OUTCOME_UNHANDLED: 'OUTCOME_UNHANDLED',\n\n // Dry run (spec 8.2). Written only by an `isDryRun` instance; the pure\n // `lib/dry-run.ts` owns the same literals as `DRY_RUN_EVENT_TYPES` and builds\n // the \"Would do\" report from them. A test pins the two lists together.\n DRY_RUN_STARTED: 'DRY_RUN_STARTED',\n ACTIVITY_SIMULATED: 'ACTIVITY_SIMULATED',\n ACTIVITY_SIMULATION_REFUSED: 'ACTIVITY_SIMULATION_REFUSED',\n USER_TASK_SIMULATED: 'USER_TASK_SIMULATED',\n BUSINESS_RULE_ACTIONS_SUPPRESSED: 'BUSINESS_RULE_ACTIONS_SUPPRESSED',\n\n // Timer events (Phase 9)\n TIMER_AWAITING: 'TIMER_AWAITING',\n TIMER_FIRED: 'TIMER_FIRED',\n TIMER_CANCELLED: 'TIMER_CANCELLED',\n} as const\n\nexport type WorkflowEventType = typeof WorkflowEventTypes[keyof typeof WorkflowEventTypes]\n\n// ============================================================================\n// Types and Interfaces\n// ============================================================================\n\nexport interface WorkflowEventInput {\n workflowInstanceId: string\n stepInstanceId?: string\n branchInstanceId?: string | null\n eventType: WorkflowEventType | string\n eventData: any\n userId?: string\n tenantId: string\n organizationId: string\n}\n\nexport interface QueryOptions {\n eventTypes?: Array<WorkflowEventType | string>\n stepInstanceId?: string\n fromDate?: Date\n toDate?: Date\n limit?: number\n offset?: number\n}\n\nexport interface EventStatistics {\n totalEvents: number\n eventsByType: Record<string, number>\n firstEvent?: Date\n lastEvent?: Date\n}\n\n// ============================================================================\n// Main Event Logging Functions\n// ============================================================================\n\n/**\n * Log a workflow event to the event sourcing table\n *\n * @param em - Entity manager\n * @param event - Event input data\n * @returns Created event entity\n */\nexport async function logWorkflowEvent(\n em: EntityManager,\n event: WorkflowEventInput\n): Promise<WorkflowEvent> {\n const workflowEvent = em.create(WorkflowEvent, {\n workflowInstanceId: event.workflowInstanceId,\n stepInstanceId: event.stepInstanceId || null,\n branchInstanceId: event.branchInstanceId ?? null,\n eventType: event.eventType,\n eventData: event.eventData || {},\n userId: event.userId || null,\n tenantId: event.tenantId,\n organizationId: event.organizationId,\n occurredAt: new Date(),\n })\n\n await em.persist(workflowEvent).flush()\n\n return workflowEvent\n}\n\n/**\n * Log multiple workflow events in batch\n *\n * @param em - Entity manager\n * @param events - Array of event input data\n * @returns Array of created event entities\n */\nexport async function logWorkflowEvents(\n em: EntityManager,\n events: WorkflowEventInput[]\n): Promise<WorkflowEvent[]> {\n const workflowEvents = events.map(event =>\n em.create(WorkflowEvent, {\n workflowInstanceId: event.workflowInstanceId,\n stepInstanceId: event.stepInstanceId || null,\n branchInstanceId: event.branchInstanceId ?? null,\n eventType: event.eventType,\n eventData: event.eventData || {},\n userId: event.userId || null,\n tenantId: event.tenantId,\n organizationId: event.organizationId,\n occurredAt: new Date(),\n })\n )\n\n await em.persist(workflowEvents).flush()\n\n return workflowEvents\n}\n\n// ============================================================================\n// Event Query Functions\n// ============================================================================\n\n/**\n * Get all events for a workflow instance\n *\n * @param em - Entity manager\n * @param instanceId - Workflow instance ID\n * @param options - Query options (filters, pagination)\n * @returns Array of workflow events\n */\nexport async function getWorkflowEvents(\n em: EntityManager,\n instanceId: string,\n options?: QueryOptions\n): Promise<WorkflowEvent[]> {\n const where: any = {\n workflowInstanceId: instanceId,\n }\n\n // Filter by event types\n if (options?.eventTypes && options.eventTypes.length > 0) {\n where.eventType = { $in: options.eventTypes }\n }\n\n // Filter by step instance\n if (options?.stepInstanceId) {\n where.stepInstanceId = options.stepInstanceId\n }\n\n // Filter by date range\n if (options?.fromDate || options?.toDate) {\n where.occurredAt = {}\n if (options.fromDate) {\n where.occurredAt.$gte = options.fromDate\n }\n if (options.toDate) {\n where.occurredAt.$lte = options.toDate\n }\n }\n\n const events = await em.find(\n WorkflowEvent,\n where,\n {\n orderBy: { occurredAt: 'ASC' },\n limit: options?.limit,\n offset: options?.offset,\n }\n )\n\n return events\n}\n\n/**\n * Get events for a specific step instance\n *\n * @param em - Entity manager\n * @param stepInstanceId - Step instance ID\n * @returns Array of workflow events\n */\nexport async function getStepEvents(\n em: EntityManager,\n stepInstanceId: string\n): Promise<WorkflowEvent[]> {\n const events = await em.find(\n WorkflowEvent,\n { stepInstanceId },\n { orderBy: { occurredAt: 'ASC' } }\n )\n\n return events\n}\n\n/**\n * Get the latest event for a workflow instance\n *\n * @param em - Entity manager\n * @param instanceId - Workflow instance ID\n * @param eventType - Optional event type filter\n * @returns Latest workflow event or null\n */\nexport async function getLatestEvent(\n em: EntityManager,\n instanceId: string,\n eventType?: WorkflowEventType | string\n): Promise<WorkflowEvent | null> {\n const where: any = {\n workflowInstanceId: instanceId,\n }\n\n if (eventType) {\n where.eventType = eventType\n }\n\n const event = await em.findOne(\n WorkflowEvent,\n where,\n { orderBy: { occurredAt: 'DESC' } }\n )\n\n return event\n}\n\n/**\n * Count events for a workflow instance\n *\n * @param em - Entity manager\n * @param instanceId - Workflow instance ID\n * @param eventType - Optional event type filter\n * @returns Count of events\n */\nexport async function countEvents(\n em: EntityManager,\n instanceId: string,\n eventType?: WorkflowEventType | string\n): Promise<number> {\n const where: any = {\n workflowInstanceId: instanceId,\n }\n\n if (eventType) {\n where.eventType = eventType\n }\n\n return await em.count(WorkflowEvent, where)\n}\n\n/**\n * Get event statistics for a workflow instance\n *\n * @param em - Entity manager\n * @param instanceId - Workflow instance ID\n * @returns Event statistics\n */\nexport async function getEventStatistics(\n em: EntityManager,\n instanceId: string\n): Promise<EventStatistics> {\n const events = await em.find(\n WorkflowEvent,\n { workflowInstanceId: instanceId },\n { orderBy: { occurredAt: 'ASC' } }\n )\n\n const eventsByType: Record<string, number> = {}\n\n for (const event of events) {\n eventsByType[event.eventType] = (eventsByType[event.eventType] || 0) + 1\n }\n\n return {\n totalEvents: events.length,\n eventsByType,\n firstEvent: events.length > 0 ? events[0].occurredAt : undefined,\n lastEvent: events.length > 0 ? events[events.length - 1].occurredAt : undefined,\n }\n}\n\n/**\n * Check if a specific event type has occurred for a workflow instance\n *\n * @param em - Entity manager\n * @param instanceId - Workflow instance ID\n * @param eventType - Event type to check\n * @returns True if event has occurred\n */\nexport async function hasEventOccurred(\n em: EntityManager,\n instanceId: string,\n eventType: WorkflowEventType | string\n): Promise<boolean> {\n const count = await em.count(WorkflowEvent, {\n workflowInstanceId: instanceId,\n eventType,\n })\n\n return count > 0\n}\n\n/**\n * Get event timeline for a workflow instance (simplified view)\n *\n * @param em - Entity manager\n * @param instanceId - Workflow instance ID\n * @returns Array of simplified event objects\n */\nexport async function getEventTimeline(\n em: EntityManager,\n instanceId: string\n): Promise<Array<{\n eventType: string\n occurredAt: Date\n stepInstanceId?: string\n userId?: string\n summary: string\n}>> {\n const events = await em.find(\n WorkflowEvent,\n { workflowInstanceId: instanceId },\n { orderBy: { occurredAt: 'ASC' } }\n )\n\n return events.map(event => ({\n eventType: event.eventType,\n occurredAt: event.occurredAt,\n stepInstanceId: event.stepInstanceId || undefined,\n userId: event.userId || undefined,\n summary: generateEventSummary(event),\n }))\n}\n\n// ============================================================================\n// Helper Functions\n// ============================================================================\n\n/**\n * Generate human-readable summary for an event\n */\nfunction generateEventSummary(event: WorkflowEvent): string {\n const data = event.eventData || {}\n\n switch (event.eventType) {\n case WorkflowEventTypes.WORKFLOW_STARTED:\n return `Workflow started${data.workflowId ? ` (${data.workflowId})` : ''}`\n\n case WorkflowEventTypes.WORKFLOW_COMPLETED:\n return `Workflow completed${data.result ? ` with result` : ''}`\n\n case WorkflowEventTypes.WORKFLOW_FAILED:\n return `Workflow failed${data.error ? `: ${data.error}` : ''}`\n\n case WorkflowEventTypes.STEP_ENTERED:\n return `Entered step: ${data.stepName || data.stepId || 'unknown'}`\n\n case WorkflowEventTypes.STEP_EXITED:\n return `Exited step: ${data.stepName || data.stepId || 'unknown'}${\n data.executionTimeMs ? ` (${data.executionTimeMs}ms)` : ''\n }`\n\n case WorkflowEventTypes.STEP_FAILED:\n return `Step failed: ${data.stepName || data.stepId || 'unknown'}${\n data.error ? ` - ${data.error}` : ''\n }`\n\n case WorkflowEventTypes.TRANSITION_EXECUTED:\n return `Transition: ${data.fromStepId} \u2192 ${data.toStepId}`\n\n case WorkflowEventTypes.TRANSITION_REJECTED:\n return `Transition blocked: ${data.fromStepId} \u2192 ${data.toStepId}${\n data.reason ? ` (${data.reason})` : ''\n }`\n\n case WorkflowEventTypes.USER_TASK_CREATED:\n return `User task created: ${data.taskName || 'unnamed'}${\n data.assignedTo ? ` (assigned to ${data.assignedTo})` : ''\n }`\n\n case WorkflowEventTypes.USER_TASK_COMPLETED:\n return `User task completed: ${data.taskName || 'unnamed'}`\n\n case WorkflowEventTypes.ACTIVITY_COMPLETED:\n return `Activity completed: ${data.activityName || data.activityId || 'unknown'}`\n\n case WorkflowEventTypes.ACTIVITY_FAILED:\n return `Activity failed: ${data.activityName || data.activityId || 'unknown'}${\n data.error ? ` - ${data.error}` : ''\n }`\n\n case WorkflowEventTypes.COMPENSATION_STARTED:\n return `Compensation started${data.reason ? `: ${data.reason}` : ''}`\n\n case WorkflowEventTypes.COMPENSATION_COMPLETED:\n return `Compensation completed: ${data.compensatedActivities || 0}/${data.totalActivities || 0} activities`\n\n case WorkflowEventTypes.COMPENSATION_PARTIAL:\n return `Partial compensation: ${data.compensatedActivities || 0}/${data.totalActivities || 0} succeeded`\n\n case WorkflowEventTypes.COMPENSATION_FAILED:\n return `Compensation failed: ${data.failedCompensations?.length || 0} activities failed`\n\n case WorkflowEventTypes.COMPENSATION_ACTIVITY_STARTED:\n return `Compensating: ${data.compensationActivityName || data.compensationActivityId || 'unknown'}`\n\n case WorkflowEventTypes.COMPENSATION_ACTIVITY_COMPLETED:\n return `Compensated: ${data.compensationActivityName || data.compensationActivityId || 'unknown'}`\n\n case WorkflowEventTypes.COMPENSATION_ACTIVITY_FAILED:\n return `Compensation failed: ${data.compensationActivityName || data.compensationActivityId || 'unknown'}${\n data.error ? ` - ${data.error}` : ''\n }`\n\n default:\n return event.eventType\n }\n}\n\n/**\n * Validate event type is a known type\n */\nexport function isValidEventType(eventType: string): eventType is WorkflowEventType {\n return Object.values(WorkflowEventTypes).includes(eventType as WorkflowEventType)\n}\n\n/**\n * Get all known event types\n */\nexport function getAllEventTypes(): WorkflowEventType[] {\n return Object.values(WorkflowEventTypes)\n}\n"],
|
|
5
|
-
"mappings": "AAaA,SAAS,qBAAqB;AAMvB,MAAM,qBAAqB;AAAA;AAAA,EAEhC,kBAAkB;AAAA,EAClB,oBAAoB;AAAA,EACpB,iBAAiB;AAAA,EACjB,oBAAoB;AAAA,EACpB,iBAAiB;AAAA,EACjB,kBAAkB;AAAA;AAAA,EAGlB,cAAc;AAAA,EACd,aAAa;AAAA,EACb,aAAa;AAAA,EACb,cAAc;AAAA;AAAA,EAGd,qBAAqB;AAAA,EACrB,qBAAqB;AAAA,EACrB,kCAAkC;AAAA,EAClC,mBAAmB;AAAA;AAAA,EAGnB,oBAAoB;AAAA,EACpB,kBAAkB;AAAA,EAClB,oBAAoB;AAAA,EACpB,iBAAiB;AAAA,EACjB,gBAAgB;AAAA;AAAA,EAGhB,mBAAmB;AAAA,EACnB,oBAAoB;AAAA,EACpB,mBAAmB;AAAA,EACnB,qBAAqB;AAAA,EACrB,qBAAqB;AAAA,EACrB,qB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,oBAAoB,MAAM;AAAA,MAC1B,gBAAgB,MAAM,kBAAkB;AAAA,MACxC,kBAAkB,MAAM,oBAAoB;AAAA,MAC5C,WAAW,MAAM;AAAA,MACjB,WAAW,MAAM,aAAa,CAAC;AAAA,MAC/B,QAAQ,MAAM,UAAU;AAAA,MACxB,UAAU,MAAM;AAAA,MAChB,gBAAgB,MAAM;AAAA,MACtB,YAAY,oBAAI,KAAK;AAAA,IACvB,CAAC;AAAA,EACH;AAEA,QAAM,GAAG,QAAQ,cAAc,EAAE,MAAM;AAEvC,SAAO;AACT;AAcA,eAAsB,kBACpB,IACA,YACA,SAC0B;AAC1B,QAAM,QAAa;AAAA,IACjB,oBAAoB;AAAA,EACtB;AAGA,MAAI,SAAS,cAAc,QAAQ,WAAW,SAAS,GAAG;AACxD,UAAM,YAAY,EAAE,KAAK,QAAQ,WAAW;AAAA,EAC9C;AAGA,MAAI,SAAS,gBAAgB;AAC3B,UAAM,iBAAiB,QAAQ;AAAA,EACjC;AAGA,MAAI,SAAS,YAAY,SAAS,QAAQ;AACxC,UAAM,aAAa,CAAC;AACpB,QAAI,QAAQ,UAAU;AACpB,YAAM,WAAW,OAAO,QAAQ;AAAA,IAClC;AACA,QAAI,QAAQ,QAAQ;AAClB,YAAM,WAAW,OAAO,QAAQ;AAAA,IAClC;AAAA,EACF;AAEA,QAAM,SAAS,MAAM,GAAG;AAAA,IACtB;AAAA,IACA;AAAA,IACA;AAAA,MACE,SAAS,EAAE,YAAY,MAAM;AAAA,
|
|
4
|
+
"sourcesContent": ["/**\n * Workflows Module - Event Logger Service\n *\n * Consolidates workflow event logging for audit trail and replay:\n * - Log workflow lifecycle events\n * - Log step execution events\n * - Log transition events\n * - Query event history\n *\n * Functional API (no classes) following Open Mercato conventions.\n */\n\nimport { EntityManager } from '@mikro-orm/core'\nimport { WorkflowEvent } from '../data/entities'\n\n// ============================================================================\n// Event Type Constants\n// ============================================================================\n\nexport const WorkflowEventTypes = {\n // Workflow lifecycle\n WORKFLOW_STARTED: 'WORKFLOW_STARTED',\n WORKFLOW_COMPLETED: 'WORKFLOW_COMPLETED',\n WORKFLOW_FAILED: 'WORKFLOW_FAILED',\n WORKFLOW_CANCELLED: 'WORKFLOW_CANCELLED',\n WORKFLOW_PAUSED: 'WORKFLOW_PAUSED',\n WORKFLOW_RESUMED: 'WORKFLOW_RESUMED',\n\n // Step lifecycle\n STEP_ENTERED: 'STEP_ENTERED',\n STEP_EXITED: 'STEP_EXITED',\n STEP_FAILED: 'STEP_FAILED',\n STEP_SKIPPED: 'STEP_SKIPPED',\n\n // Transition events\n TRANSITION_EXECUTED: 'TRANSITION_EXECUTED',\n TRANSITION_REJECTED: 'TRANSITION_REJECTED',\n TRANSITION_POST_CONDITION_FAILED: 'TRANSITION_POST_CONDITION_FAILED',\n TRANSITION_FAILED: 'TRANSITION_FAILED',\n\n // Activity events\n ACTIVITY_SCHEDULED: 'ACTIVITY_SCHEDULED',\n ACTIVITY_STARTED: 'ACTIVITY_STARTED',\n ACTIVITY_COMPLETED: 'ACTIVITY_COMPLETED',\n ACTIVITY_FAILED: 'ACTIVITY_FAILED',\n ACTIVITY_RETRY: 'ACTIVITY_RETRY',\n\n // User task events\n USER_TASK_CREATED: 'USER_TASK_CREATED',\n USER_TASK_ASSIGNED: 'USER_TASK_ASSIGNED',\n USER_TASK_STARTED: 'USER_TASK_STARTED',\n USER_TASK_COMPLETED: 'USER_TASK_COMPLETED',\n USER_TASK_CANCELLED: 'USER_TASK_CANCELLED',\n USER_TASK_ESCALATED: 'USER_TASK_ESCALATED',\n\n // Sub-workflow events (Phase 8)\n SUB_WORKFLOW_STARTED: 'SUB_WORKFLOW_STARTED',\n SUB_WORKFLOW_COMPLETED: 'SUB_WORKFLOW_COMPLETED',\n SUB_WORKFLOW_FAILED: 'SUB_WORKFLOW_FAILED',\n\n // Compensation events (Phase 8)\n COMPENSATION_STARTED: 'COMPENSATION_STARTED',\n COMPENSATION_COMPLETED: 'COMPENSATION_COMPLETED',\n COMPENSATION_PARTIAL: 'COMPENSATION_PARTIAL',\n COMPENSATION_FAILED: 'COMPENSATION_FAILED',\n COMPENSATION_ACTIVITY_STARTED: 'COMPENSATION_ACTIVITY_STARTED',\n COMPENSATION_ACTIVITY_COMPLETED: 'COMPENSATION_ACTIVITY_COMPLETED',\n COMPENSATION_ACTIVITY_FAILED: 'COMPENSATION_ACTIVITY_FAILED',\n\n // Signal events (Phase 9)\n SIGNAL_AWAITING: 'SIGNAL_AWAITING',\n SIGNAL_RECEIVED: 'SIGNAL_RECEIVED',\n SIGNAL_TIMEOUT: 'SIGNAL_TIMEOUT',\n\n // Error routing (spec 5.9)\n ERROR_ROUTED: 'ERROR_ROUTED',\n ERROR_DIRECTIVE_APPLIED: 'ERROR_DIRECTIVE_APPLIED',\n ERROR_PARKED: 'ERROR_PARKED',\n ERROR_HANDLER_SCHEDULED: 'ERROR_HANDLER_SCHEDULED',\n ERROR_HANDLER_STARTED: 'ERROR_HANDLER_STARTED',\n ERROR_HANDLER_SKIPPED: 'ERROR_HANDLER_SKIPPED',\n\n // Recovery (spec 8.4). `STEP_RERUN` carries `{ stepId, editedContextDiff, by }`\n // and is the audit record of a rerun \u2014 the terminal StepInstance of the\n // previous attempt is never touched, so the event log is where the two\n // attempts are linked.\n STEP_RERUN: 'STEP_RERUN',\n\n // Agent outcome routing (spec 7.2)\n OUTCOME_ROUTED: 'OUTCOME_ROUTED',\n OUTCOME_UNHANDLED: 'OUTCOME_UNHANDLED',\n\n // Dry run (spec 8.2). Written only by an `isDryRun` instance; the pure\n // `lib/dry-run.ts` owns the same literals as `DRY_RUN_EVENT_TYPES` and builds\n // the \"Would do\" report from them. A test pins the two lists together.\n DRY_RUN_STARTED: 'DRY_RUN_STARTED',\n ACTIVITY_SIMULATED: 'ACTIVITY_SIMULATED',\n ACTIVITY_SIMULATION_REFUSED: 'ACTIVITY_SIMULATION_REFUSED',\n USER_TASK_SIMULATED: 'USER_TASK_SIMULATED',\n BUSINESS_RULE_ACTIONS_SUPPRESSED: 'BUSINESS_RULE_ACTIONS_SUPPRESSED',\n\n // Timer events (Phase 9)\n TIMER_AWAITING: 'TIMER_AWAITING',\n TIMER_FIRED: 'TIMER_FIRED',\n TIMER_CANCELLED: 'TIMER_CANCELLED',\n} as const\n\nexport type WorkflowEventType = typeof WorkflowEventTypes[keyof typeof WorkflowEventTypes]\n\n// ============================================================================\n// Types and Interfaces\n// ============================================================================\n\nexport interface WorkflowEventInput {\n workflowInstanceId: string\n stepInstanceId?: string\n branchInstanceId?: string | null\n eventType: WorkflowEventType | string\n eventData: any\n userId?: string\n tenantId: string\n organizationId: string\n}\n\nexport interface QueryOptions {\n eventTypes?: Array<WorkflowEventType | string>\n stepInstanceId?: string\n fromDate?: Date\n toDate?: Date\n limit?: number\n offset?: number\n}\n\nexport interface EventStatistics {\n totalEvents: number\n eventsByType: Record<string, number>\n firstEvent?: Date\n lastEvent?: Date\n}\n\n// ============================================================================\n// Main Event Logging Functions\n// ============================================================================\n\n/**\n * Log a workflow event to the event sourcing table\n *\n * @param em - Entity manager\n * @param event - Event input data\n * @returns Created event entity\n */\nexport async function logWorkflowEvent(\n em: EntityManager,\n event: WorkflowEventInput\n): Promise<WorkflowEvent> {\n const workflowEvent = em.create(WorkflowEvent, {\n workflowInstanceId: event.workflowInstanceId,\n stepInstanceId: event.stepInstanceId || null,\n branchInstanceId: event.branchInstanceId ?? null,\n eventType: event.eventType,\n eventData: event.eventData || {},\n userId: event.userId || null,\n tenantId: event.tenantId,\n organizationId: event.organizationId,\n occurredAt: new Date(),\n })\n\n await em.persist(workflowEvent).flush()\n\n return workflowEvent\n}\n\n/**\n * Log multiple workflow events in batch\n *\n * @param em - Entity manager\n * @param events - Array of event input data\n * @returns Array of created event entities\n */\nexport async function logWorkflowEvents(\n em: EntityManager,\n events: WorkflowEventInput[]\n): Promise<WorkflowEvent[]> {\n const workflowEvents = events.map(event =>\n em.create(WorkflowEvent, {\n workflowInstanceId: event.workflowInstanceId,\n stepInstanceId: event.stepInstanceId || null,\n branchInstanceId: event.branchInstanceId ?? null,\n eventType: event.eventType,\n eventData: event.eventData || {},\n userId: event.userId || null,\n tenantId: event.tenantId,\n organizationId: event.organizationId,\n occurredAt: new Date(),\n })\n )\n\n await em.persist(workflowEvents).flush()\n\n return workflowEvents\n}\n\n// ============================================================================\n// Event Query Functions\n// ============================================================================\n\n/**\n * Get all events for a workflow instance\n *\n * @param em - Entity manager\n * @param instanceId - Workflow instance ID\n * @param options - Query options (filters, pagination)\n * @returns Array of workflow events\n */\nexport async function getWorkflowEvents(\n em: EntityManager,\n instanceId: string,\n options?: QueryOptions\n): Promise<WorkflowEvent[]> {\n const where: any = {\n workflowInstanceId: instanceId,\n }\n\n // Filter by event types\n if (options?.eventTypes && options.eventTypes.length > 0) {\n where.eventType = { $in: options.eventTypes }\n }\n\n // Filter by step instance\n if (options?.stepInstanceId) {\n where.stepInstanceId = options.stepInstanceId\n }\n\n // Filter by date range\n if (options?.fromDate || options?.toDate) {\n where.occurredAt = {}\n if (options.fromDate) {\n where.occurredAt.$gte = options.fromDate\n }\n if (options.toDate) {\n where.occurredAt.$lte = options.toDate\n }\n }\n\n const events = await em.find(\n WorkflowEvent,\n where,\n {\n orderBy: { occurredAt: 'ASC', id: 'ASC' },\n limit: options?.limit,\n offset: options?.offset,\n }\n )\n\n return events\n}\n\n/**\n * Get events for a specific step instance\n *\n * @param em - Entity manager\n * @param stepInstanceId - Step instance ID\n * @returns Array of workflow events\n */\nexport async function getStepEvents(\n em: EntityManager,\n stepInstanceId: string\n): Promise<WorkflowEvent[]> {\n const events = await em.find(\n WorkflowEvent,\n { stepInstanceId },\n { orderBy: { occurredAt: 'ASC' } }\n )\n\n return events\n}\n\n/**\n * Get the latest event for a workflow instance\n *\n * @param em - Entity manager\n * @param instanceId - Workflow instance ID\n * @param eventType - Optional event type filter\n * @returns Latest workflow event or null\n */\nexport async function getLatestEvent(\n em: EntityManager,\n instanceId: string,\n eventType?: WorkflowEventType | string\n): Promise<WorkflowEvent | null> {\n const where: any = {\n workflowInstanceId: instanceId,\n }\n\n if (eventType) {\n where.eventType = eventType\n }\n\n const event = await em.findOne(\n WorkflowEvent,\n where,\n { orderBy: { occurredAt: 'DESC' } }\n )\n\n return event\n}\n\n/**\n * Count events for a workflow instance\n *\n * @param em - Entity manager\n * @param instanceId - Workflow instance ID\n * @param eventType - Optional event type filter\n * @returns Count of events\n */\nexport async function countEvents(\n em: EntityManager,\n instanceId: string,\n eventType?: WorkflowEventType | string\n): Promise<number> {\n const where: any = {\n workflowInstanceId: instanceId,\n }\n\n if (eventType) {\n where.eventType = eventType\n }\n\n return await em.count(WorkflowEvent, where)\n}\n\n/**\n * Get event statistics for a workflow instance\n *\n * @param em - Entity manager\n * @param instanceId - Workflow instance ID\n * @returns Event statistics\n */\nexport async function getEventStatistics(\n em: EntityManager,\n instanceId: string\n): Promise<EventStatistics> {\n const events = await em.find(\n WorkflowEvent,\n { workflowInstanceId: instanceId },\n { orderBy: { occurredAt: 'ASC' } }\n )\n\n const eventsByType: Record<string, number> = {}\n\n for (const event of events) {\n eventsByType[event.eventType] = (eventsByType[event.eventType] || 0) + 1\n }\n\n return {\n totalEvents: events.length,\n eventsByType,\n firstEvent: events.length > 0 ? events[0].occurredAt : undefined,\n lastEvent: events.length > 0 ? events[events.length - 1].occurredAt : undefined,\n }\n}\n\n/**\n * Check if a specific event type has occurred for a workflow instance\n *\n * @param em - Entity manager\n * @param instanceId - Workflow instance ID\n * @param eventType - Event type to check\n * @returns True if event has occurred\n */\nexport async function hasEventOccurred(\n em: EntityManager,\n instanceId: string,\n eventType: WorkflowEventType | string\n): Promise<boolean> {\n const count = await em.count(WorkflowEvent, {\n workflowInstanceId: instanceId,\n eventType,\n })\n\n return count > 0\n}\n\n/**\n * Get event timeline for a workflow instance (simplified view)\n *\n * @param em - Entity manager\n * @param instanceId - Workflow instance ID\n * @returns Array of simplified event objects\n */\nexport async function getEventTimeline(\n em: EntityManager,\n instanceId: string\n): Promise<Array<{\n eventType: string\n occurredAt: Date\n stepInstanceId?: string\n userId?: string\n summary: string\n}>> {\n const events = await em.find(\n WorkflowEvent,\n { workflowInstanceId: instanceId },\n { orderBy: { occurredAt: 'ASC' } }\n )\n\n return events.map(event => ({\n eventType: event.eventType,\n occurredAt: event.occurredAt,\n stepInstanceId: event.stepInstanceId || undefined,\n userId: event.userId || undefined,\n summary: generateEventSummary(event),\n }))\n}\n\n// ============================================================================\n// Helper Functions\n// ============================================================================\n\n/**\n * Generate human-readable summary for an event\n */\nfunction generateEventSummary(event: WorkflowEvent): string {\n const data = event.eventData || {}\n\n switch (event.eventType) {\n case WorkflowEventTypes.WORKFLOW_STARTED:\n return `Workflow started${data.workflowId ? ` (${data.workflowId})` : ''}`\n\n case WorkflowEventTypes.WORKFLOW_COMPLETED:\n return `Workflow completed${data.result ? ` with result` : ''}`\n\n case WorkflowEventTypes.WORKFLOW_FAILED:\n return `Workflow failed${data.error ? `: ${data.error}` : ''}`\n\n case WorkflowEventTypes.STEP_ENTERED:\n return `Entered step: ${data.stepName || data.stepId || 'unknown'}`\n\n case WorkflowEventTypes.STEP_EXITED:\n return `Exited step: ${data.stepName || data.stepId || 'unknown'}${\n data.executionTimeMs ? ` (${data.executionTimeMs}ms)` : ''\n }`\n\n case WorkflowEventTypes.STEP_FAILED:\n return `Step failed: ${data.stepName || data.stepId || 'unknown'}${\n data.error ? ` - ${data.error}` : ''\n }`\n\n case WorkflowEventTypes.TRANSITION_EXECUTED:\n return `Transition: ${data.fromStepId} \u2192 ${data.toStepId}`\n\n case WorkflowEventTypes.TRANSITION_REJECTED:\n return `Transition blocked: ${data.fromStepId} \u2192 ${data.toStepId}${\n data.reason ? ` (${data.reason})` : ''\n }`\n\n case WorkflowEventTypes.USER_TASK_CREATED:\n return `User task created: ${data.taskName || 'unnamed'}${\n data.assignedTo ? ` (assigned to ${data.assignedTo})` : ''\n }`\n\n case WorkflowEventTypes.USER_TASK_COMPLETED:\n return `User task completed: ${data.taskName || 'unnamed'}`\n\n case WorkflowEventTypes.ACTIVITY_COMPLETED:\n return `Activity completed: ${data.activityName || data.activityId || 'unknown'}`\n\n case WorkflowEventTypes.ACTIVITY_FAILED:\n return `Activity failed: ${data.activityName || data.activityId || 'unknown'}${\n data.error ? ` - ${data.error}` : ''\n }`\n\n case WorkflowEventTypes.COMPENSATION_STARTED:\n return `Compensation started${data.reason ? `: ${data.reason}` : ''}`\n\n case WorkflowEventTypes.COMPENSATION_COMPLETED:\n return `Compensation completed: ${data.compensatedActivities || 0}/${data.totalActivities || 0} activities`\n\n case WorkflowEventTypes.COMPENSATION_PARTIAL:\n return `Partial compensation: ${data.compensatedActivities || 0}/${data.totalActivities || 0} succeeded`\n\n case WorkflowEventTypes.COMPENSATION_FAILED:\n return `Compensation failed: ${data.failedCompensations?.length || 0} activities failed`\n\n case WorkflowEventTypes.COMPENSATION_ACTIVITY_STARTED:\n return `Compensating: ${data.compensationActivityName || data.compensationActivityId || 'unknown'}`\n\n case WorkflowEventTypes.COMPENSATION_ACTIVITY_COMPLETED:\n return `Compensated: ${data.compensationActivityName || data.compensationActivityId || 'unknown'}`\n\n case WorkflowEventTypes.COMPENSATION_ACTIVITY_FAILED:\n return `Compensation failed: ${data.compensationActivityName || data.compensationActivityId || 'unknown'}${\n data.error ? ` - ${data.error}` : ''\n }`\n\n default:\n return event.eventType\n }\n}\n\n/**\n * Validate event type is a known type\n */\nexport function isValidEventType(eventType: string): eventType is WorkflowEventType {\n return Object.values(WorkflowEventTypes).includes(eventType as WorkflowEventType)\n}\n\n/**\n * Get all known event types\n */\nexport function getAllEventTypes(): WorkflowEventType[] {\n return Object.values(WorkflowEventTypes)\n}\n"],
|
|
5
|
+
"mappings": "AAaA,SAAS,qBAAqB;AAMvB,MAAM,qBAAqB;AAAA;AAAA,EAEhC,kBAAkB;AAAA,EAClB,oBAAoB;AAAA,EACpB,iBAAiB;AAAA,EACjB,oBAAoB;AAAA,EACpB,iBAAiB;AAAA,EACjB,kBAAkB;AAAA;AAAA,EAGlB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,MAAM,KAAK,KAAK,KAAK,EACpC;AAAA,IAEF;AACE,aAAO,MAAM;AAAA,EACjB;AACF;AAKO,SAAS,iBAAiB,WAAmD;AAClF,SAAO,OAAO,OAAO,kBAAkB,EAAE,SAAS,SAA8B;AAClF;AAKO,SAAS,mBAAwC;AACtD,SAAO,OAAO,OAAO,kBAAkB;AACzC;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -121,7 +121,7 @@ async function listUserTaskWorkItems(query, context) {
|
|
|
121
121
|
};
|
|
122
122
|
const where = buildUserTaskWorkInboxWhere(query, context.scope, options);
|
|
123
123
|
const [tasks, total] = await em.findAndCount(UserTask, where, {
|
|
124
|
-
orderBy: [{ dueDate: "ASC" }, { createdAt: "DESC" }],
|
|
124
|
+
orderBy: [{ dueDate: "ASC" }, { createdAt: "DESC" }, { id: "ASC" }],
|
|
125
125
|
limit: query.offset + query.limit,
|
|
126
126
|
offset: 0
|
|
127
127
|
});
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../../src/modules/workflows/lib/work-inbox/user-task-source.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * Work Inbox \u2014 the core `user_task` source.\n *\n * A read-model over the existing `user_tasks` rows (spec \u00A76.3: \"phase 1: a\n * projection/read-model over existing `UserTask` \u2026 with no data migration\").\n * Nothing here writes; the inbox's mutations go through `taskHandler`.\n *\n * Rows are projected through the SAME `serializeUserTask` the task list route\n * uses and carried on the wire under `details`, so a work-inbox row remains a\n * strict superset of a task-list row.\n */\n\nimport type { EntityManager, FilterQuery } from '@mikro-orm/core'\nimport { UserTask } from '../../data/entities'\nimport { serializeUserTask, USER_TASK_INBOX_KIND } from '../../api/tasks/serialize'\nimport {\n WORK_INBOX_TERMINAL_STATUSES,\n deriveWorkInboxOverdue,\n normalizeWorkInboxPriority,\n} from './provider'\nimport {\n buildTaskVisibilityRequestConditions,\n partitionTaskPage,\n} from '../task-visibility-request'\nimport type {\n WorkInboxAction,\n WorkInboxEntityBinding,\n WorkInboxQuery,\n WorkInboxRow,\n WorkInboxScope,\n WorkInboxSourceContext,\n WorkInboxSourceProvider,\n WorkInboxSourceResult,\n} from './provider'\n\nexport const WORKFLOWS_MODULE_ID = 'workflows'\n\n/**\n * Declarative actions the inbox renders for a workflow task. `complete` points\n * at the task detail page rather than an endpoint because completing needs the\n * form; claim and unclaim are one-shot POSTs.\n */\nexport const USER_TASK_WORK_INBOX_ACTIONS: WorkInboxAction[] = [\n {\n id: 'claim',\n labelKey: 'workflows.tasks.actions.claim',\n endpoint: '/api/workflows/tasks/{id}/claim',\n appliesTo: 'claimable',\n },\n {\n id: 'unclaim',\n labelKey: 'workflows.tasks.actions.unclaim',\n endpoint: '/api/workflows/tasks/{id}/unclaim',\n appliesTo: 'claimed-by-me',\n },\n]\n\ntype WorkInboxWhere = FilterQuery<UserTask>\n\n/**\n * Per-source options a `UserTask`-serving provider passes through to the \u00A76.4\n * rule.\n *\n * `administrativeQueueFeature` is the source's own declaration, handed back by\n * `listWorkInbox`. Core's `user_task` source declares none, so an unassigned row\n * keeps falling back to `workflows.tasks.view_all` exactly as before; a\n * specialized source (an administrative queue raised by another module) supplies\n * its own, and the SQL filter and the predicate must be given the SAME value or\n * a row is counted in `pagination.total` and then dropped from the page.\n */\nexport type UserTaskWorkInboxOptions = {\n administrativeQueueFeature?: string | null\n}\n\nfunction asBindings(value: unknown): WorkInboxEntityBinding[] {\n if (!Array.isArray(value)) return []\n const bindings: WorkInboxEntityBinding[] = []\n for (const item of value) {\n if (!item || typeof item !== 'object' || Array.isArray(item)) continue\n const record = item as Record<string, unknown>\n const entityType = record.entityType\n const entityId = record.entityId\n if (typeof entityType !== 'string' || typeof entityId !== 'string') continue\n const label = typeof record.label === 'string' ? record.label : null\n bindings.push({ entityType, entityId, label })\n }\n return bindings\n}\n\n/**\n * Translate a work-inbox query into the ORM filter.\n *\n * Exported and pure so the tenant/organization scoping and every filter can be\n * asserted without a database. Independent predicates are pushed onto `$and`\n * rather than merged into one object, because several of them (`myWork`,\n * `entityTypes`) each need their own `$or` group and a single object can only\n * carry one.\n */\nexport function buildUserTaskWorkInboxWhere(\n query: WorkInboxQuery,\n scope: WorkInboxScope,\n options: UserTaskWorkInboxOptions = {},\n): WorkInboxWhere {\n const conditions: Record<string, unknown>[] = []\n\n if (query.statuses && query.statuses.length > 0) {\n conditions.push({ status: { $in: query.statuses } })\n }\n\n if (query.overdueOnly) {\n conditions.push({ dueDate: { $lt: query.now } })\n conditions.push({ status: { $nin: [...WORK_INBOX_TERMINAL_STATUSES] } })\n }\n\n if (query.assignedTo) {\n conditions.push({ assignedTo: query.assignedTo })\n }\n\n if (query.workflowInstanceId) {\n conditions.push({ workflowInstanceId: query.workflowInstanceId })\n }\n\n if (query.priorities && query.priorities.length > 0) {\n conditions.push({ priority: { $in: query.priorities } })\n }\n\n if (query.roles && query.roles.length > 0) {\n conditions.push({ assignedToRoles: { $overlap: query.roles } })\n }\n\n if (query.entityTypes && query.entityTypes.length > 0) {\n conditions.push({\n $or: query.entityTypes.map((entityType) => ({\n entityBindings: { $contains: [{ entityType }] },\n })),\n })\n }\n\n if (query.myWork) {\n conditions.push({\n $or: [\n { assignedTo: scope.userId },\n { claimedBy: scope.userId },\n { assignedToRoles: { $overlap: scope.roles } },\n ],\n })\n }\n\n // \u00A76.4. Pushed onto the SAME `$and` array as every other predicate, so the\n // relationship clause, the entity gate and the caller's own filters compose\n // rather than overwrite each other. Empty for an administrator, a superadmin,\n // or a tenant that has flipped the opt-out \u2014 the rule then adds nothing and\n // tenant/organization scoping below is still the floor.\n conditions.push(\n ...buildTaskVisibilityRequestConditions(scope.visibility, {\n administrativeQueueFeature: options.administrativeQueueFeature ?? null,\n }),\n )\n\n const where: Record<string, unknown> = { tenantId: scope.tenantId }\n if (scope.organizationIds) {\n where.organizationId = { $in: scope.organizationIds }\n }\n if (conditions.length > 0) {\n where.$and = conditions\n }\n\n return where as WorkInboxWhere\n}\n\nexport function toUserTaskWorkInboxRow(task: UserTask, now: Date): WorkInboxRow {\n const details = serializeUserTask(task)\n const bindings = asBindings(details.entityBindings)\n return {\n id: details.id,\n kind: USER_TASK_INBOX_KIND,\n moduleId: WORKFLOWS_MODULE_ID,\n title: details.taskName,\n description: details.description ?? null,\n status: details.status,\n priority: normalizeWorkInboxPriority(details.priority),\n dueDate: details.dueDate ?? null,\n overdue: deriveWorkInboxOverdue(details.dueDate ?? null, details.status, now),\n createdAt: details.createdAt,\n updatedAt: details.updatedAt,\n assignedTo: details.assignedTo ?? null,\n assignedToRoles: details.assignedToRoles ?? null,\n claimedBy: details.claimedBy ?? null,\n entityTypes: [...new Set(bindings.map((binding) => binding.entityType))],\n entityBindings: bindings,\n detailHref: `/backend/tasks/${details.id}`,\n actions: USER_TASK_WORK_INBOX_ACTIONS,\n details,\n }\n}\n\n/**\n * SQL orders by due date (Postgres puts NULLs last on ASC, which is what the\n * inbox wants)
|
|
5
|
-
"mappings": "AAaA,SAAS,gBAAgB;AACzB,SAAS,mBAAmB,4BAA4B;AACxD;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,OACK;AAYA,MAAM,sBAAsB;AAO5B,MAAM,+BAAkD;AAAA,EAC7D;AAAA,IACE,IAAI;AAAA,IACJ,UAAU;AAAA,IACV,UAAU;AAAA,IACV,WAAW;AAAA,EACb;AAAA,EACA;AAAA,IACE,IAAI;AAAA,IACJ,UAAU;AAAA,IACV,UAAU;AAAA,IACV,WAAW;AAAA,EACb;AACF;AAmBA,SAAS,WAAW,OAA0C;AAC5D,MAAI,CAAC,MAAM,QAAQ,KAAK,EAAG,QAAO,CAAC;AACnC,QAAM,WAAqC,CAAC;AAC5C,aAAW,QAAQ,OAAO;AACxB,QAAI,CAAC,QAAQ,OAAO,SAAS,YAAY,MAAM,QAAQ,IAAI,EAAG;AAC9D,UAAM,SAAS;AACf,UAAM,aAAa,OAAO;AAC1B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ChB,YAAY,kBAAkB,QAAQ,EAAE;AAAA,IACxC,SAAS;AAAA,IACT;AAAA,EACF;AACF;
|
|
4
|
+
"sourcesContent": ["/**\n * Work Inbox \u2014 the core `user_task` source.\n *\n * A read-model over the existing `user_tasks` rows (spec \u00A76.3: \"phase 1: a\n * projection/read-model over existing `UserTask` \u2026 with no data migration\").\n * Nothing here writes; the inbox's mutations go through `taskHandler`.\n *\n * Rows are projected through the SAME `serializeUserTask` the task list route\n * uses and carried on the wire under `details`, so a work-inbox row remains a\n * strict superset of a task-list row.\n */\n\nimport type { EntityManager, FilterQuery } from '@mikro-orm/core'\nimport { UserTask } from '../../data/entities'\nimport { serializeUserTask, USER_TASK_INBOX_KIND } from '../../api/tasks/serialize'\nimport {\n WORK_INBOX_TERMINAL_STATUSES,\n deriveWorkInboxOverdue,\n normalizeWorkInboxPriority,\n} from './provider'\nimport {\n buildTaskVisibilityRequestConditions,\n partitionTaskPage,\n} from '../task-visibility-request'\nimport type {\n WorkInboxAction,\n WorkInboxEntityBinding,\n WorkInboxQuery,\n WorkInboxRow,\n WorkInboxScope,\n WorkInboxSourceContext,\n WorkInboxSourceProvider,\n WorkInboxSourceResult,\n} from './provider'\n\nexport const WORKFLOWS_MODULE_ID = 'workflows'\n\n/**\n * Declarative actions the inbox renders for a workflow task. `complete` points\n * at the task detail page rather than an endpoint because completing needs the\n * form; claim and unclaim are one-shot POSTs.\n */\nexport const USER_TASK_WORK_INBOX_ACTIONS: WorkInboxAction[] = [\n {\n id: 'claim',\n labelKey: 'workflows.tasks.actions.claim',\n endpoint: '/api/workflows/tasks/{id}/claim',\n appliesTo: 'claimable',\n },\n {\n id: 'unclaim',\n labelKey: 'workflows.tasks.actions.unclaim',\n endpoint: '/api/workflows/tasks/{id}/unclaim',\n appliesTo: 'claimed-by-me',\n },\n]\n\ntype WorkInboxWhere = FilterQuery<UserTask>\n\n/**\n * Per-source options a `UserTask`-serving provider passes through to the \u00A76.4\n * rule.\n *\n * `administrativeQueueFeature` is the source's own declaration, handed back by\n * `listWorkInbox`. Core's `user_task` source declares none, so an unassigned row\n * keeps falling back to `workflows.tasks.view_all` exactly as before; a\n * specialized source (an administrative queue raised by another module) supplies\n * its own, and the SQL filter and the predicate must be given the SAME value or\n * a row is counted in `pagination.total` and then dropped from the page.\n */\nexport type UserTaskWorkInboxOptions = {\n administrativeQueueFeature?: string | null\n}\n\nfunction asBindings(value: unknown): WorkInboxEntityBinding[] {\n if (!Array.isArray(value)) return []\n const bindings: WorkInboxEntityBinding[] = []\n for (const item of value) {\n if (!item || typeof item !== 'object' || Array.isArray(item)) continue\n const record = item as Record<string, unknown>\n const entityType = record.entityType\n const entityId = record.entityId\n if (typeof entityType !== 'string' || typeof entityId !== 'string') continue\n const label = typeof record.label === 'string' ? record.label : null\n bindings.push({ entityType, entityId, label })\n }\n return bindings\n}\n\n/**\n * Translate a work-inbox query into the ORM filter.\n *\n * Exported and pure so the tenant/organization scoping and every filter can be\n * asserted without a database. Independent predicates are pushed onto `$and`\n * rather than merged into one object, because several of them (`myWork`,\n * `entityTypes`) each need their own `$or` group and a single object can only\n * carry one.\n */\nexport function buildUserTaskWorkInboxWhere(\n query: WorkInboxQuery,\n scope: WorkInboxScope,\n options: UserTaskWorkInboxOptions = {},\n): WorkInboxWhere {\n const conditions: Record<string, unknown>[] = []\n\n if (query.statuses && query.statuses.length > 0) {\n conditions.push({ status: { $in: query.statuses } })\n }\n\n if (query.overdueOnly) {\n conditions.push({ dueDate: { $lt: query.now } })\n conditions.push({ status: { $nin: [...WORK_INBOX_TERMINAL_STATUSES] } })\n }\n\n if (query.assignedTo) {\n conditions.push({ assignedTo: query.assignedTo })\n }\n\n if (query.workflowInstanceId) {\n conditions.push({ workflowInstanceId: query.workflowInstanceId })\n }\n\n if (query.priorities && query.priorities.length > 0) {\n conditions.push({ priority: { $in: query.priorities } })\n }\n\n if (query.roles && query.roles.length > 0) {\n conditions.push({ assignedToRoles: { $overlap: query.roles } })\n }\n\n if (query.entityTypes && query.entityTypes.length > 0) {\n conditions.push({\n $or: query.entityTypes.map((entityType) => ({\n entityBindings: { $contains: [{ entityType }] },\n })),\n })\n }\n\n if (query.myWork) {\n conditions.push({\n $or: [\n { assignedTo: scope.userId },\n { claimedBy: scope.userId },\n { assignedToRoles: { $overlap: scope.roles } },\n ],\n })\n }\n\n // \u00A76.4. Pushed onto the SAME `$and` array as every other predicate, so the\n // relationship clause, the entity gate and the caller's own filters compose\n // rather than overwrite each other. Empty for an administrator, a superadmin,\n // or a tenant that has flipped the opt-out \u2014 the rule then adds nothing and\n // tenant/organization scoping below is still the floor.\n conditions.push(\n ...buildTaskVisibilityRequestConditions(scope.visibility, {\n administrativeQueueFeature: options.administrativeQueueFeature ?? null,\n }),\n )\n\n const where: Record<string, unknown> = { tenantId: scope.tenantId }\n if (scope.organizationIds) {\n where.organizationId = { $in: scope.organizationIds }\n }\n if (conditions.length > 0) {\n where.$and = conditions\n }\n\n return where as WorkInboxWhere\n}\n\nexport function toUserTaskWorkInboxRow(task: UserTask, now: Date): WorkInboxRow {\n const details = serializeUserTask(task)\n const bindings = asBindings(details.entityBindings)\n return {\n id: details.id,\n kind: USER_TASK_INBOX_KIND,\n moduleId: WORKFLOWS_MODULE_ID,\n title: details.taskName,\n description: details.description ?? null,\n status: details.status,\n priority: normalizeWorkInboxPriority(details.priority),\n dueDate: details.dueDate ?? null,\n overdue: deriveWorkInboxOverdue(details.dueDate ?? null, details.status, now),\n createdAt: details.createdAt,\n updatedAt: details.updatedAt,\n assignedTo: details.assignedTo ?? null,\n assignedToRoles: details.assignedToRoles ?? null,\n claimedBy: details.claimedBy ?? null,\n entityTypes: [...new Set(bindings.map((binding) => binding.entityType))],\n entityBindings: bindings,\n detailHref: `/backend/tasks/${details.id}`,\n actions: USER_TASK_WORK_INBOX_ACTIONS,\n details,\n }\n}\n\n/**\n * SQL orders by due date (Postgres puts NULLs last on ASC, which is what the\n * inbox wants), then by recency, then by `id` so the window is a total order\n * and tied rows cannot shift between requests; the canonical priority \u2192 due \u2192 created\n * ordering is applied by the merge service over the returned window, because\n * `priority` is an authored label with no ordinal column to sort on. Phase 1 is\n * a projection \u2014 a persisted sort key belongs with the `Task` entity, which\n * resolved question #1 defers to the next cycle.\n */\nasync function listUserTaskWorkItems(\n query: WorkInboxQuery,\n context: WorkInboxSourceContext,\n): Promise<WorkInboxSourceResult> {\n const em = context.resolve<EntityManager>('em')\n const options: UserTaskWorkInboxOptions = {\n administrativeQueueFeature: context.administrativeQueueFeature ?? null,\n }\n const where = buildUserTaskWorkInboxWhere(query, context.scope, options)\n\n const [tasks, total] = await em.findAndCount(UserTask, where, {\n orderBy: [{ dueDate: 'ASC' }, { createdAt: 'DESC' }, { id: 'ASC' }],\n limit: query.offset + query.limit,\n offset: 0,\n })\n\n // The `WHERE` already IS the rule; running the predicate over the page keeps\n // this source routed through the single decision point and makes a\n // SQL/predicate divergence lose a row instead of leaking one. It is handed the\n // SAME queue feature the filter was built with, for exactly that reason.\n const { visible, entityHidden } = partitionTaskPage(context.scope.visibility, tasks, options)\n\n return {\n rows: visible.map((task) => toUserTaskWorkInboxRow(task, query.now)),\n total,\n ...(entityHidden.length > 0 ? { entityHidden } : {}),\n }\n}\n\nexport const userTaskWorkInboxSource: WorkInboxSourceProvider = {\n kind: USER_TASK_INBOX_KIND,\n moduleId: WORKFLOWS_MODULE_ID,\n render: 'work-inbox:user_task:detail',\n actions: USER_TASK_WORK_INBOX_ACTIONS,\n list: listUserTaskWorkItems,\n}\n"],
|
|
5
|
+
"mappings": "AAaA,SAAS,gBAAgB;AACzB,SAAS,mBAAmB,4BAA4B;AACxD;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,OACK;AAYA,MAAM,sBAAsB;AAO5B,MAAM,+BAAkD;AAAA,EAC7D;AAAA,IACE,IAAI;AAAA,IACJ,UAAU;AAAA,IACV,UAAU;AAAA,IACV,WAAW;AAAA,EACb;AAAA,EACA;AAAA,IACE,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.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@open-mercato/core",
|
|
3
|
-
"version": "0.11.1-develop.
|
|
3
|
+
"version": "0.11.1-develop.8545.1.dd603570fd",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -268,16 +268,16 @@
|
|
|
268
268
|
"zod": "^4.6.6"
|
|
269
269
|
},
|
|
270
270
|
"peerDependencies": {
|
|
271
|
-
"@open-mercato/ai-assistant": "0.11.1-develop.
|
|
272
|
-
"@open-mercato/shared": "0.11.1-develop.
|
|
273
|
-
"@open-mercato/ui": "0.11.1-develop.
|
|
271
|
+
"@open-mercato/ai-assistant": "0.11.1-develop.8545.1.dd603570fd",
|
|
272
|
+
"@open-mercato/shared": "0.11.1-develop.8545.1.dd603570fd",
|
|
273
|
+
"@open-mercato/ui": "0.11.1-develop.8545.1.dd603570fd",
|
|
274
274
|
"react": "^19.0.0",
|
|
275
275
|
"react-dom": "^19.0.0"
|
|
276
276
|
},
|
|
277
277
|
"devDependencies": {
|
|
278
|
-
"@open-mercato/ai-assistant": "0.11.1-develop.
|
|
279
|
-
"@open-mercato/shared": "0.11.1-develop.
|
|
280
|
-
"@open-mercato/ui": "0.11.1-develop.
|
|
278
|
+
"@open-mercato/ai-assistant": "0.11.1-develop.8545.1.dd603570fd",
|
|
279
|
+
"@open-mercato/shared": "0.11.1-develop.8545.1.dd603570fd",
|
|
280
|
+
"@open-mercato/ui": "0.11.1-develop.8545.1.dd603570fd",
|
|
281
281
|
"@testing-library/dom": "^10.4.1",
|
|
282
282
|
"@testing-library/jest-dom": "^7.0.1",
|
|
283
283
|
"@testing-library/react": "^16.3.3",
|
|
@@ -11,7 +11,7 @@ import { CustomerRbacService } from '@open-mercato/core/modules/customer_account
|
|
|
11
11
|
import { adminUpdateUserSchema } from '@open-mercato/core/modules/customer_accounts/data/validators'
|
|
12
12
|
import { emitCustomerAccountsEvent } from '@open-mercato/core/modules/customer_accounts/events'
|
|
13
13
|
import { findOneWithDecryption, findWithDecryption } from '@open-mercato/shared/lib/encryption/find'
|
|
14
|
-
import { isOwnedCompanyEntity, isOwnedPersonEntity } from '@open-mercato/core/modules/customer_accounts/lib/customerEntityOwnership'
|
|
14
|
+
import { isCustomerEntityRegistered, isOwnedCompanyEntity, isOwnedPersonEntity } from '@open-mercato/core/modules/customer_accounts/lib/customerEntityOwnership'
|
|
15
15
|
import { enforceCommandOptimisticLockWithGuards } from '@open-mercato/shared/lib/crud/optimistic-lock-command'
|
|
16
16
|
import { isCrudHttpError } from '@open-mercato/shared/lib/crud/errors'
|
|
17
17
|
|
|
@@ -158,12 +158,13 @@ export async function PUT(req: Request, { params }: { params: { id: string } })
|
|
|
158
158
|
// Without this check a mislinked company FK cross-links the user into another
|
|
159
159
|
// org/company's portal context and persists indefinitely (#2693). A null value
|
|
160
160
|
// (unlink) needs no ownership check.
|
|
161
|
-
|
|
162
|
-
|
|
161
|
+
const { customerEntityId, personEntityId } = parsed.data
|
|
162
|
+
if (customerEntityId) {
|
|
163
|
+
const owned = await isOwnedCompanyEntity(em, customerEntityId, {
|
|
163
164
|
tenantId: auth.tenantId,
|
|
164
165
|
organizationId: auth.orgId,
|
|
165
166
|
})
|
|
166
|
-
if (!owned) {
|
|
167
|
+
if (!owned && (customerEntityId !== user.customerEntityId || await isCustomerEntityRegistered(em))) {
|
|
167
168
|
return NextResponse.json({ ok: false, error: 'Company not found' }, { status: 400 })
|
|
168
169
|
}
|
|
169
170
|
}
|
|
@@ -173,12 +174,12 @@ export async function PUT(req: Request, { params }: { params: { id: string } })
|
|
|
173
174
|
// It persists (autoLinkCrm short-circuits on any non-null value) and leaks
|
|
174
175
|
// account status into the other org's people list via the account-status
|
|
175
176
|
// enricher. A null value (unlink) needs no ownership check.
|
|
176
|
-
if (
|
|
177
|
-
const owned = await isOwnedPersonEntity(em,
|
|
177
|
+
if (personEntityId) {
|
|
178
|
+
const owned = await isOwnedPersonEntity(em, personEntityId, {
|
|
178
179
|
tenantId: auth.tenantId,
|
|
179
180
|
organizationId: auth.orgId,
|
|
180
181
|
})
|
|
181
|
-
if (!owned) {
|
|
182
|
+
if (!owned && (personEntityId !== user.personEntityId || await isCustomerEntityRegistered(em))) {
|
|
182
183
|
return NextResponse.json({ ok: false, error: 'Person not found' }, { status: 400 })
|
|
183
184
|
}
|
|
184
185
|
}
|
|
@@ -200,8 +201,8 @@ export async function PUT(req: Request, { params }: { params: { id: string } })
|
|
|
200
201
|
const updates: Record<string, unknown> = { updatedAt: nextUpdatedAt }
|
|
201
202
|
if (parsed.data.isActive !== undefined) updates.isActive = parsed.data.isActive
|
|
202
203
|
if (parsed.data.lockedUntil !== undefined) updates.lockedUntil = parsed.data.lockedUntil ? new Date(parsed.data.lockedUntil) : null
|
|
203
|
-
if (
|
|
204
|
-
if (
|
|
204
|
+
if (personEntityId !== undefined && personEntityId !== user.personEntityId) updates.personEntityId = personEntityId
|
|
205
|
+
if (customerEntityId !== undefined && customerEntityId !== user.customerEntityId) updates.customerEntityId = customerEntityId
|
|
205
206
|
|
|
206
207
|
await em.nativeUpdate(CustomerUser, {
|
|
207
208
|
id: user.id,
|
|
@@ -2,6 +2,7 @@ import { NextResponse } from 'next/server'
|
|
|
2
2
|
import { z } from 'zod'
|
|
3
3
|
import type { OpenApiRouteDoc, OpenApiMethodDoc } from '@open-mercato/shared/lib/openapi'
|
|
4
4
|
import { getCustomerAuthFromRequest } from '@open-mercato/core/modules/customer_accounts/lib/customerAuth'
|
|
5
|
+
import { arePortalNotificationsAvailable } from '@open-mercato/core/modules/customer_accounts/lib/portalNotificationsAvailability'
|
|
5
6
|
import { createRequestContainer } from '@open-mercato/shared/lib/di/container'
|
|
6
7
|
import { Notification } from '@open-mercato/core/modules/notifications/data/entities'
|
|
7
8
|
|
|
@@ -16,11 +17,13 @@ export async function PUT(req: Request, { params }: { params: { id: string } })
|
|
|
16
17
|
const container = await createRequestContainer()
|
|
17
18
|
const em = container.resolve('em') as import('@mikro-orm/postgresql').EntityManager
|
|
18
19
|
|
|
19
|
-
const notification =
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
20
|
+
const notification = arePortalNotificationsAvailable(em)
|
|
21
|
+
? await em.findOne(Notification, {
|
|
22
|
+
id: params.id,
|
|
23
|
+
recipientUserId: auth.sub,
|
|
24
|
+
tenantId: auth.tenantId,
|
|
25
|
+
})
|
|
26
|
+
: null
|
|
24
27
|
|
|
25
28
|
if (!notification) {
|
|
26
29
|
return NextResponse.json({ ok: false, error: 'Notification not found' }, { status: 404 })
|