From f24bfaf5a8f8711c8fa7994f830bd4de9d44767a Mon Sep 17 00:00:00 2001 From: mihir Date: Thu, 8 Oct 2026 16:30:07 +0530 Subject: [PATCH] feat(workflows): add atomic audited order expiry sweeps --- README.md | 2 + docs/order-expiry-workflow-api.md | 28 +++ docs/roadmap.md | 1 + package.json | 1 + prisma/checkout.prisma | 1 + prisma/migration-checksums.json | 3 +- .../migration.sql | 24 ++ prisma/schema.prisma | 1 + prisma/workflows.prisma | 15 ++ src/app.module.ts | 2 + src/checkout/cancel-order.ts | 40 ++++ src/checkout/order.store.ts | 32 +-- src/cli/workflow-expiry.ts | 37 +++ src/identity/permissions.ts | 2 + src/workflows/order-expiry.store.ts | 104 ++++++++ src/workflows/workflow.schemas.ts | 8 + src/workflows/workflows.controller.ts | 30 +++ src/workflows/workflows.module.ts | 10 + test/order-expiry-workflow.spec.ts | 223 ++++++++++++++++++ test/workflow-cli.spec.ts | 69 ++++++ 20 files changed, 603 insertions(+), 30 deletions(-) create mode 100644 docs/order-expiry-workflow-api.md create mode 100644 prisma/migrations/20261008130000_order_expiry_workflow/migration.sql create mode 100644 prisma/workflows.prisma create mode 100644 src/checkout/cancel-order.ts create mode 100644 src/cli/workflow-expiry.ts create mode 100644 src/workflows/order-expiry.store.ts create mode 100644 src/workflows/workflow.schemas.ts create mode 100644 src/workflows/workflows.controller.ts create mode 100644 src/workflows/workflows.module.ts create mode 100644 test/order-expiry-workflow.spec.ts create mode 100644 test/workflow-cli.spec.ts diff --git a/README.md b/README.md index aa57d29..9ec2900 100644 --- a/README.md +++ b/README.md @@ -96,3 +96,5 @@ Captured-request forecast baseline: see [Phase 5C API guide](docs/capture-foreca Accounting source events: see [Phase 5D API guide](docs/accounting-source-feed-api.md). Indicative batch material contribution: see [Phase 5E API guide](docs/batch-contribution-api.md). + +Bounded order expiry automation: see [Phase 5F API guide](docs/order-expiry-workflow-api.md). diff --git a/docs/order-expiry-workflow-api.md b/docs/order-expiry-workflow-api.md new file mode 100644 index 0000000..18e7a50 --- /dev/null +++ b/docs/order-expiry-workflow-api.md @@ -0,0 +1,28 @@ +# Bounded order expiry workflow (Phase 5F) + +An authenticated operator/service account can run a bounded expiry sweep through HTTP or the scheduler-friendly one-shot command. The workflow selects only the caller's organization, `PENDING_PAYMENT` orders whose expiry is at/before one captured server time, then uses the same cancellation routine as the existing customer/staff order endpoints. Live payments remain deferred; future paid states are not selected. + +| Method | Route | Access | +| ------ | ------------------------------------- | ------------------------------------------------------------------- | +| POST | `/api/v1/workflows/order-expiry/runs` | Both `workflows.run` and `orders.manage`; execute one atomic sweep. | +| GET | `/api/v1/workflows/order-expiry/runs` | `workflows.read`; paginated immutable run history. | + +POST body is `{ "limit": 10, "idempotencyKey": "" }`. Limit defaults to 10, ranges 1–25, and bounds orders per transaction. Invalid/extra fields and organization overrides return 400; missing sessions return 401; missing either execution permission returns 403. Both execution permissions and active session are checked again inside the organization-locked transaction. Existing system Owners receive `workflows.read`/`workflows.run`; custom roles remain explicit. + +Orders are considered in expiry/UUID order. The workflow locks all affected stock IDs in deterministic order before shared cancellation logic releases active order-bound holds, stores `CANCELLED`, and enqueues the existing `order.cancelled` event. Physical on-hand stock is unchanged. Already cancelled orders, future pending orders, foreign organizations, and standalone reservations are not selected. Existing reads already exclude expired holds from availability; this sweep finalizes their stored status and audit evidence. + +Audit action `order.expired` distinguishes workflow expiry from manual `order.cancelled`. A successful sweep appends `workflow.order_expiry_completed` and one immutable run record with operator ID, limit, evaluation/completion times and processed order IDs/count. Customer-visible expired orders become stored cancellations; detailed cause remains in the run/audit trail. No money, order prices, addresses, coupons or stock ledger quantities are rewritten. Existing cancellation retry behavior remains unchanged. + +Run keys are organization-scoped. Exact retries return the original result and do not reselect newer expired orders or duplicate holds/events/audits. Changing the limit with the same key returns `IDEMPOTENCY_CONFLICT` (409). New invocations use fresh keys, including empty successful runs. A failure anywhere before commit rolls back every cancellation/release/event and the run record; there is no partial-success report. Failed attempts are not persisted as successful history and can be retried with the same key. + +History contains technical IDs, operator ID, parameters and result counts; tokens, customer profiles, addresses, request hashes and idempotency keys are absent. Existing pagination defaults/maxima apply. Native guards freeze run history, validate limits/hash/time order and ensure listed IDs are distinct, scoped cancelled orders with expired evidence. + +After `pnpm build`, `pnpm workflows:expire` opens an application context, authenticates `WORKFLOW_TOKEN`, and invokes the same permission-checked workflow. Supply a normal active session token for a dedicated account with execution permissions. Optional `WORKFLOW_LIMIT` defaults to 10; optional UUID `WORKFLOW_RUN_KEY` fixes retry identity, otherwise a new UUID is generated. Result JSON contains only the safe run view; errors omit credentials and exit nonzero. Connections close on success/failure. Session expiry, account suspension and permission revocation apply to the command normally. + +Configure the chosen deployment's scheduler to invoke the one-shot command periodically using a secret-managed token and non-overlapping job policy. Keep the same run key when retrying an uncertain attempt and rotate it for the next scheduled invocation. Drain larger backlogs with repeated bounded invocations; timeout/failure remains atomic, so reduce the batch size if needed. This repository does not install or enable a live scheduler, store a bypass/service password, refresh credentials, or create recurring Codex tasks. + +The existing organization lock serializes sweeps and cancellation/catalog work; stock locks also coordinate independent inventory transactions. The batch limit bounds work but a busy organization can still experience lock latency; use a lower limit/cadence, then dedicated job workers if measured load requires it. No generic rule engine, configurable financial posting, stock reorder, production planning, standalone reservation cleanup, message delivery or ledger integration is enabled. + +Deploy the additive run-table, pending-expiry scan index and Owner-permission migration before the application. Source order snapshots, previous migrations and historical financial records remain unchanged. Older code ignores run history, but cannot reopen orders already cancelled by a successful sweep. This branch is stacked on the pushed accounting and contribution branches; merge prerequisites first. Native multi-connection CI and deployment scheduler operation remain pending. + +Verification covers eligible selection, untouched future/foreign orders, hold release/on-hand preservation, exact/conflicting retries, competing sweeps, run-history immutability, transaction rollback, dual permissions/live account status, strict limits, authenticated CLI/resource closure, schema drift and existing manual checkout/cancellation regressions. diff --git a/docs/roadmap.md b/docs/roadmap.md index 6c4e9ef..d0cd714 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -72,6 +72,7 @@ Moderated forums, advanced analytics, forecasts, accounting adapters, profitabil - 5C (baseline implemented): bounded historical daily capture-rate projections with exact unit arithmetic, zero-day inclusion, cancellation exclusion, visible evidence/staleness and current catalog flags. Validated sales/seasonal forecasts, confidence intervals, stock actions and automated production planning remain separate milestones. - 5D (source contract implemented): scoped, bounded accounting source-event pages for supplier invoices/payments and partner receipts, with original/correction links, exact captured amounts and deterministic cursor traversal. Provider posting, ledger/tax mapping and durable export acknowledgements remain separate milestones. - 5E (material-contribution baseline implemented): explicit net-price scenarios against sealed batch material/packaging cost, signed exact contribution, upward break-even prices and zero-output handling. Realized net profit, complete expense/COGS attribution, sales-to-batch linkage and dashboards remain separate milestones. +- 5F (expiry workflow implemented): bounded, idempotent expired-order sweeps with shared cancellation/hold-release logic, immutable run history, atomic rollback and an authenticated scheduler-ready command. Deployment scheduling, broader workflow rules, live providers and complete production launch work remain separate milestones. ## Definition of done for every feature diff --git a/package.json b/package.json index ba5aea9..1ecfab9 100644 --- a/package.json +++ b/package.json @@ -23,6 +23,7 @@ "start:watch": "node --watch dist/main.js", "db:status": "prisma migrate status", "bootstrap:owner": "node dist/cli/bootstrap-owner.js", + "workflows:expire": "node dist/cli/workflow-expiry.js", "admin:prepare-local": "node dist/cli/local-admin.js prepare", "admin:seed-local": "node dist/cli/local-admin.js seed", "db:test": "node scripts/test-migrations.mjs", diff --git a/prisma/checkout.prisma b/prisma/checkout.prisma index 0364766..76a44ed 100644 --- a/prisma/checkout.prisma +++ b/prisma/checkout.prisma @@ -78,6 +78,7 @@ model Order { @@unique([id, organizationId]) @@index([organizationId, userId, createdAt, id]) @@index([organizationId, createdAt, id]) + @@index([organizationId, status, expiresAt, id]) @@unique([id, userId, organizationId]) @@index([couponId, status, expiresAt]) @@map("orders") diff --git a/prisma/migration-checksums.json b/prisma/migration-checksums.json index 5de5db6..96c3ff3 100644 --- a/prisma/migration-checksums.json +++ b/prisma/migration-checksums.json @@ -55,5 +55,6 @@ "20261007170000_commerce_analytics": "800e392f788e176e3fb27c04f956a18e5f1505b820af6bb2364fc990aa8d26ea", "20261008100000_capture_forecasts": "69b94ac61b9f1c3f47268d5586d7f73c4c392cabdd3049d01f34e5e033cac043", "20261008110000_accounting_sources": "47b89e83291dbdf7b9fc7f1f25e7260a9f06bde0291ae2f7db01200e75eed396", - "20261008120000_batch_contribution": "4d6c577e6d59e9163c41253b828ed19729b76d881f21197f6b863c2f79233471" + "20261008120000_batch_contribution": "4d6c577e6d59e9163c41253b828ed19729b76d881f21197f6b863c2f79233471", + "20261008130000_order_expiry_workflow": "e9ff103b0870e6998e2a906924a4f0394ac8ccbbe811b323d8485c3ee0dd92ff" } diff --git a/prisma/migrations/20261008130000_order_expiry_workflow/migration.sql b/prisma/migrations/20261008130000_order_expiry_workflow/migration.sql new file mode 100644 index 0000000..83225b6 --- /dev/null +++ b/prisma/migrations/20261008130000_order_expiry_workflow/migration.sql @@ -0,0 +1,24 @@ +CREATE TABLE order_expiry_runs ( + id UUID NOT NULL, organization_id UUID NOT NULL, actor_id UUID NOT NULL, + idempotency_key UUID NOT NULL, request_hash CHAR(64) NOT NULL, "limit" INTEGER NOT NULL, + as_of TIMESTAMPTZ(3) NOT NULL, completed_at TIMESTAMPTZ(3) NOT NULL, processed_order_ids UUID[] NOT NULL, + CONSTRAINT order_expiry_runs_pkey PRIMARY KEY (id), + CONSTRAINT order_expiry_runs_actor_id_organization_id_fkey FOREIGN KEY (actor_id, organization_id) REFERENCES users(id, organization_id) ON DELETE RESTRICT ON UPDATE CASCADE, + CONSTRAINT expiry_run_valid CHECK ("limit" BETWEEN 1 AND 25 AND cardinality(processed_order_ids) <= "limit" AND completed_at >= as_of AND request_hash ~ '^[a-f0-9]{64}$') +); +CREATE INDEX orders_organization_id_status_expires_at_id_idx ON orders (organization_id, status, expires_at, id); +CREATE UNIQUE INDEX order_expiry_runs_organization_id_idempotency_key_key ON order_expiry_runs (organization_id, idempotency_key); +CREATE INDEX order_expiry_runs_organization_id_completed_at_id_idx ON order_expiry_runs (organization_id, completed_at, id); +CREATE FUNCTION guard_order_expiry_run() RETURNS trigger LANGUAGE plpgsql AS $$ +BEGIN + IF TG_OP <> 'INSERT' THEN RAISE EXCEPTION 'Order expiry run history is immutable'; END IF; + IF (SELECT COUNT(DISTINCT id) FROM unnest(NEW.processed_order_ids) AS ids(id)) <> cardinality(NEW.processed_order_ids) + OR EXISTS (SELECT 1 FROM unnest(NEW.processed_order_ids) AS ids(id) LEFT JOIN orders o ON o.id = ids.id AND o.organization_id = NEW.organization_id + WHERE o.id IS NULL OR o.status <> 'CANCELLED' OR o.expires_at > NEW.as_of) + THEN RAISE EXCEPTION 'Expiry run contains invalid order evidence'; END IF; + RETURN NEW; +END; +$$; +CREATE TRIGGER order_expiry_run_guard BEFORE INSERT OR UPDATE OR DELETE ON order_expiry_runs FOR EACH ROW EXECUTE FUNCTION guard_order_expiry_run(); +UPDATE roles SET permissions = ARRAY(SELECT DISTINCT unnest(permissions || ARRAY['workflows.read', 'workflows.run'])) + WHERE is_system = true AND name = 'Owner'; diff --git a/prisma/schema.prisma b/prisma/schema.prisma index 9ab91b9..4a0d465 100644 --- a/prisma/schema.prisma +++ b/prisma/schema.prisma @@ -96,6 +96,7 @@ model User { blogsWithdrawn BlogArticle[] @relation("BlogWithdrawer") forumPosts ForumPost[] forumDecisions ForumModeration[] + expiryRuns OrderExpiryRun[] reviewPurchases ReviewPurchaseVerification[] @relation("ReviewBuyer") reviewVerifications ReviewPurchaseVerification[] @relation("ReviewVerifier") reviewRevocations ReviewPurchaseRevocation[] diff --git a/prisma/workflows.prisma b/prisma/workflows.prisma new file mode 100644 index 0000000..be171f4 --- /dev/null +++ b/prisma/workflows.prisma @@ -0,0 +1,15 @@ +model OrderExpiryRun { + id String @id @default(uuid()) @db.Uuid + organizationId String @map("organization_id") @db.Uuid + actorId String @map("actor_id") @db.Uuid + idempotencyKey String @map("idempotency_key") @db.Uuid + requestHash String @map("request_hash") @db.Char(64) + limit Int + asOf DateTime @map("as_of") @db.Timestamptz(3) + completedAt DateTime @map("completed_at") @db.Timestamptz(3) + processedOrderIds String[] @map("processed_order_ids") @db.Uuid + actor User @relation(fields: [actorId, organizationId], references: [id, organizationId], onDelete: Restrict) + @@unique([organizationId, idempotencyKey]) + @@index([organizationId, completedAt, id]) + @@map("order_expiry_runs") +} diff --git a/src/app.module.ts b/src/app.module.ts index 06dbd40..1be9d40 100644 --- a/src/app.module.ts +++ b/src/app.module.ts @@ -20,9 +20,11 @@ import { SegmentsModule } from './segments/segments.module'; import { ForumModule } from './forum/forum.module'; import { AnalyticsModule } from './analytics/analytics.module'; import { AccountingModule } from './accounting/accounting.module'; +import { WorkflowsModule } from './workflows/workflows.module'; @Module({ imports: [ + WorkflowsModule, AccountingModule, AnalyticsModule, ForumModule, diff --git a/src/checkout/cancel-order.ts b/src/checkout/cancel-order.ts new file mode 100644 index 0000000..f42c383 --- /dev/null +++ b/src/checkout/cancel-order.ts @@ -0,0 +1,40 @@ +import type { Prisma } from '../generated/prisma/client'; +import type { Principal } from '../identity/identity.types'; +import { lockStock } from '../inventory/stock-lock'; +import { enqueueEvent } from '../events/enqueue-event'; +import { recordAudit } from '../identity/audit'; +import { orderView } from './order-view'; +export const cancellationInclude = { + lines: true, + pricing: true, + reservations: { orderBy: { stockItemId: 'asc' as const } }, +}; +type CancellableOrder = Prisma.OrderGetPayload<{ + include: typeof cancellationInclude; +}>; +export async function cancelOrderRecord( + tx: Prisma.TransactionClient, + actor: Principal, + order: CancellableOrder, + action: 'order.cancelled' | 'order.expired' = 'order.cancelled', +) { + if (order.status === 'CANCELLED') return orderView(order); + for (const reservation of order.reservations) + await lockStock(tx, actor.organizationId, reservation.stockItemId); + await tx.stockReservation.updateMany({ + where: { + orderId: order.id, + organizationId: actor.organizationId, + status: 'ACTIVE', + }, + data: { status: 'RELEASED' }, + }); + const updated = await tx.order.update({ + where: { id: order.id }, + data: { status: 'CANCELLED' }, + include: { lines: true, pricing: true }, + }); + await enqueueEvent(tx, actor.organizationId, order.id, 'order.cancelled'); + await recordAudit(tx, actor.organizationId, actor.userId, action, order.id); + return orderView(updated); +} diff --git a/src/checkout/order.store.ts b/src/checkout/order.store.ts index 6e57c98..d3ba0e7 100644 --- a/src/checkout/order.store.ts +++ b/src/checkout/order.store.ts @@ -2,11 +2,9 @@ import { Injectable } from '@nestjs/common'; import { DatabaseService } from '../database/database.service'; import { AccessStore } from '../identity/access.store'; import type { Principal } from '../identity/identity.types'; -import { recordAudit } from '../identity/audit'; import { AppError } from '../common/errors/app-error'; -import { lockStock } from '../inventory/stock-lock'; import { orderView, orderStatus } from './order-view'; -import { enqueueEvent } from '../events/enqueue-event'; +import { cancellationInclude, cancelOrderRecord } from './cancel-order'; @Injectable() export class OrderStore { @@ -67,34 +65,10 @@ export class OrderStore { organizationId: actor.organizationId, ...(!staff ? { userId: actor.userId } : {}), }, - include: { - lines: true, - pricing: true, - reservations: { orderBy: { stockItemId: 'asc' } }, - }, + include: cancellationInclude, }); if (!order) throw new AppError('ORDER_NOT_FOUND'); - if (order.status === 'CANCELLED') return orderView(order); - for (const reservation of order.reservations) - await lockStock(tx, actor.organizationId, reservation.stockItemId); - await tx.stockReservation.updateMany({ - where: { orderId: id, status: 'ACTIVE' }, - data: { status: 'RELEASED' }, - }); - const updated = await tx.order.update({ - where: { id }, - data: { status: 'CANCELLED' }, - include: { lines: true, pricing: true }, - }); - await enqueueEvent(tx, actor.organizationId, id, 'order.cancelled'); - await recordAudit( - tx, - actor.organizationId, - actor.userId, - 'order.cancelled', - id, - ); - return orderView(updated); + return cancelOrderRecord(tx, actor, order); }, ); } diff --git a/src/cli/workflow-expiry.ts b/src/cli/workflow-expiry.ts new file mode 100644 index 0000000..57ed49f --- /dev/null +++ b/src/cli/workflow-expiry.ts @@ -0,0 +1,37 @@ +import 'reflect-metadata'; +import 'dotenv/config'; +import { randomUUID } from 'node:crypto'; +import { NestFactory } from '@nestjs/core'; +import { z } from 'zod'; +import { AppModule } from '../app.module'; +import { SessionStore } from '../identity/session.store'; +import { OrderExpiryStore } from '../workflows/order-expiry.store'; +import { expiryRunSchema } from '../workflows/workflow.schemas'; +export async function runExpiryCommand(environment = process.env) { + const token = z + .string() + .regex(/^[A-Za-z0-9_-]{43}$/) + .parse(environment.WORKFLOW_TOKEN); + const input = expiryRunSchema.parse({ + limit: Number(environment.WORKFLOW_LIMIT ?? 10), + idempotencyKey: environment.WORKFLOW_RUN_KEY ?? randomUUID(), + }); + const app = await NestFactory.createApplicationContext(AppModule, { + logger: false, + }); + try { + const actor = await app.get(SessionStore).authenticate(token); + return await app.get(OrderExpiryStore).run(actor, input); + } finally { + await app.close(); + } +} +if (require.main === module) + void runExpiryCommand() + .then((result) => console.log(JSON.stringify(result))) + .catch(() => { + console.error( + 'Order expiry workflow failed. Check authentication, permissions and database availability.', + ); + process.exitCode = 1; + }); diff --git a/src/identity/permissions.ts b/src/identity/permissions.ts index 5cbaf6e..e278ad9 100644 --- a/src/identity/permissions.ts +++ b/src/identity/permissions.ts @@ -1,4 +1,6 @@ export const PERMISSIONS = [ + 'workflows.read', + 'workflows.run', 'profitability.read', 'accounting.read', 'forecasts.read', diff --git a/src/workflows/order-expiry.store.ts b/src/workflows/order-expiry.store.ts new file mode 100644 index 0000000..68b1729 --- /dev/null +++ b/src/workflows/order-expiry.store.ts @@ -0,0 +1,104 @@ +import { Injectable } from '@nestjs/common'; +import { AccessStore } from '../identity/access.store'; +import type { Principal } from '../identity/identity.types'; +import type { PageInput } from '../identity/identity.schemas'; +import { assertReplay, commandHash } from '../common/idempotency'; +import { AppError } from '../common/errors/app-error'; +import { recordAudit } from '../identity/audit'; +import { + cancellationInclude, + cancelOrderRecord, +} from '../checkout/cancel-order'; +import { lockStock } from '../inventory/stock-lock'; +import type { ExpiryRunInput } from './workflow.schemas'; +const runSelect = { + id: true, + actorId: true, + limit: true, + asOf: true, + completedAt: true, + processedOrderIds: true, +}; +const view = (run: T) => ({ + ...run, + processedCount: run.processedOrderIds.length, +}); +@Injectable() +export class OrderExpiryStore { + constructor(private readonly access: AccessStore) {} + run(actor: Principal, input: ExpiryRunInput) { + const requestHash = commandHash(input.limit); + return this.access.mutate(actor, 'workflows.run', async (tx, current) => { + if (!current.permissions.includes('orders.manage')) + throw new AppError('ACCESS_DENIED'); + const where = { + organizationId_idempotencyKey: { + organizationId: actor.organizationId, + idempotencyKey: input.idempotencyKey, + }, + }; + const previous = await tx.orderExpiryRun.findUnique({ + where, + select: { ...runSelect, requestHash: true }, + }); + if (previous) { + const { requestHash: priorHash, ...run } = previous; + assertReplay(priorHash, requestHash); + return view(run); + } + const asOf = new Date(); + const orders = await tx.order.findMany({ + where: { + organizationId: actor.organizationId, + status: 'PENDING_PAYMENT', + expiresAt: { lte: asOf }, + }, + include: cancellationInclude, + orderBy: [{ expiresAt: 'asc' }, { id: 'asc' }], + take: input.limit, + }); + const stockIds = [ + ...new Set( + orders.flatMap((o) => o.reservations.map((r) => r.stockItemId)), + ), + ].sort(); + for (const id of stockIds) await lockStock(tx, actor.organizationId, id); + for (const order of orders) + await cancelOrderRecord(tx, actor, order, 'order.expired'); + const run = await tx.orderExpiryRun.create({ + data: { + organizationId: actor.organizationId, + actorId: actor.userId, + idempotencyKey: input.idempotencyKey, + requestHash, + limit: input.limit, + asOf, + completedAt: new Date(), + processedOrderIds: orders.map((o) => o.id), + }, + select: runSelect, + }); + await recordAudit( + tx, + actor.organizationId, + actor.userId, + 'workflow.order_expiry_completed', + run.id, + ); + return view(run); + }); + } + history(actor: Principal, page: PageInput) { + return this.access.mutate(actor, 'workflows.read', async (tx) => + ( + await tx.orderExpiryRun.findMany({ + where: { organizationId: actor.organizationId }, + orderBy: [{ completedAt: 'desc' }, { id: 'desc' }], + skip: page.offset, + take: page.limit, + select: runSelect, + }) + ).map(view), + ); + } +} diff --git a/src/workflows/workflow.schemas.ts b/src/workflows/workflow.schemas.ts new file mode 100644 index 0000000..08548ea --- /dev/null +++ b/src/workflows/workflow.schemas.ts @@ -0,0 +1,8 @@ +import { z } from 'zod'; +export const expiryRunSchema = z + .object({ + limit: z.number().int().min(1).max(25).default(10), + idempotencyKey: z.uuid(), + }) + .strict(); +export type ExpiryRunInput = z.infer; diff --git a/src/workflows/workflows.controller.ts b/src/workflows/workflows.controller.ts new file mode 100644 index 0000000..cd53362 --- /dev/null +++ b/src/workflows/workflows.controller.ts @@ -0,0 +1,30 @@ +import { Body, Controller, Get, Post, Query } from '@nestjs/common'; +import { + CurrentPrincipal, + RequirePermission, +} from '../identity/access.decorator'; +import type { Principal } from '../identity/identity.types'; +import { pageSchema, type PageInput } from '../identity/identity.schemas'; +import { SchemaPipe } from '../common/validation.pipe'; +import { expiryRunSchema, type ExpiryRunInput } from './workflow.schemas'; +import { OrderExpiryStore } from './order-expiry.store'; +@Controller('workflows/order-expiry/runs') +export class WorkflowsController { + constructor(private readonly expiry: OrderExpiryStore) {} + @Post() + @RequirePermission('workflows.run') + run( + @CurrentPrincipal() actor: Principal, + @Body(new SchemaPipe(expiryRunSchema)) input: ExpiryRunInput, + ) { + return this.expiry.run(actor, input); + } + @Get() + @RequirePermission('workflows.read') + history( + @CurrentPrincipal() actor: Principal, + @Query(new SchemaPipe(pageSchema)) page: PageInput, + ) { + return this.expiry.history(actor, page); + } +} diff --git a/src/workflows/workflows.module.ts b/src/workflows/workflows.module.ts new file mode 100644 index 0000000..8f76566 --- /dev/null +++ b/src/workflows/workflows.module.ts @@ -0,0 +1,10 @@ +import { Module } from '@nestjs/common'; +import { IdentityModule } from '../identity/identity.module'; +import { WorkflowsController } from './workflows.controller'; +import { OrderExpiryStore } from './order-expiry.store'; +@Module({ + imports: [IdentityModule], + controllers: [WorkflowsController], + providers: [OrderExpiryStore], +}) +export class WorkflowsModule {} diff --git a/test/order-expiry-workflow.spec.ts b/test/order-expiry-workflow.spec.ts new file mode 100644 index 0000000..d9c5adb --- /dev/null +++ b/test/order-expiry-workflow.spec.ts @@ -0,0 +1,223 @@ +import { randomUUID } from 'node:crypto'; +import { identityApp, type IdentityApp } from './helpers/identity-app'; +import { checkoutFixture } from './helpers/checkout'; +import { secondActor } from './helpers/commerce'; + +describe('bounded auditable order expiry workflow', () => { + let ctx: IdentityApp; + beforeAll(async () => { + ctx = await identityApp(); + }); + afterAll(async () => { + await ctx.close(); + }); + beforeEach(async () => { + await ctx.clearLimits(); + }); + const run = (body: object, token = ctx.token) => + ctx + .api() + .post('/api/v1/workflows/order-expiry/runs') + .auth(token, { type: 'bearer' }) + .send(body); + async function expired() { + const f = await checkoutFixture(ctx); + const createdAt = new Date(Date.now() - 3600000); + const expiresAt = new Date(createdAt.getTime() + 900000); + const order = await ctx.db.order.create({ + data: { + userId: f.actor.userId, + organizationId: f.actor.organizationId, + currency: 'INR', + subtotal: '998.00', + discount: '0.00', + merchandiseTotal: '998.00', + addressSnapshot: { recipient: 'Private recipient' }, + createdAt, + expiresAt, + idempotencyKey: randomUUID(), + requestHash: 'a'.repeat(64), + lines: { + create: [ + { + variantId: f.variant.id, + sku: f.variant.sku, + productName: f.product.name, + variantName: f.variant.name, + quantity: 2, + unitPrice: '499.00', + lineTotal: '998.00', + }, + ], + }, + }, + }); + const reservation = await ctx.db.stockReservation.create({ + data: { + stockItemId: f.stock.id, + organizationId: f.actor.organizationId, + userId: f.actor.userId, + orderId: order.id, + quantity: 2, + expiresAt, + idempotencyKey: randomUUID(), + requestHash: 'b'.repeat(64), + }, + }); + return { ...f, order, reservation }; + } + it('expires only eligible orders, releases holds, preserves stock and replays a run once', async () => { + const f = await expired(); + const active = await ctx + .api() + .post('/api/v1/checkout') + .auth(f.actor.token, { type: 'bearer' }) + .send(f.input) + .expect(201); + const input = { limit: 1, idempotencyKey: randomUUID() }; + const result = await run(input).expect(201); + expect(result.body).toMatchObject({ + processedCount: 1, + processedOrderIds: [f.order.id], + limit: 1, + }); + expect( + (await ctx.db.order.findUniqueOrThrow({ where: { id: f.order.id } })) + .status, + ).toBe('CANCELLED'); + expect( + ( + await ctx.db.stockReservation.findUniqueOrThrow({ + where: { id: f.reservation.id }, + }) + ).status, + ).toBe('RELEASED'); + expect( + (await ctx.db.stockItem.findUniqueOrThrow({ where: { id: f.stock.id } })) + .onHand, + ).toBe(10); + expect( + (await ctx.db.order.findUniqueOrThrow({ where: { id: active.body.id } })) + .status, + ).toBe('PENDING_PAYMENT'); + expect((await run(input).expect(201)).body).toEqual(result.body); + expect((await run({ ...input, limit: 2 }).expect(409)).body.code).toBe( + 'IDEMPOTENCY_CONFLICT', + ); + expect( + await ctx.db.commerceEvent.count({ + where: { orderId: f.order.id, kind: 'order.cancelled' }, + }), + ).toBe(1); + expect( + await ctx.db.auditEvent.count({ + where: { targetId: f.order.id, action: 'order.expired' }, + }), + ).toBe(1); + expect( + (await run({ limit: 1, idempotencyKey: randomUUID() }).expect(201)).body + .processedCount, + ).toBe(0); + expect(JSON.stringify(result.body)).not.toMatch( + /address|recipient|token|requestHash|idempotencyKey/, + ); + }); + it('bounds batches, serializes competing sweeps and preserves immutable history', async () => { + const a = await expired(); + const b = await expired(); + const results = await Promise.all([ + run({ limit: 1, idempotencyKey: randomUUID() }), + run({ limit: 1, idempotencyKey: randomUUID() }), + ]); + expect(results.map((r) => r.status)).toEqual([201, 201]); + expect(new Set(results.flatMap((r) => r.body.processedOrderIds))).toEqual( + new Set([a.order.id, b.order.id]), + ); + const history = await ctx + .api() + .get('/api/v1/workflows/order-expiry/runs') + .auth(ctx.token, { type: 'bearer' }) + .query({ limit: 2 }) + .expect(200); + expect(history.body).toHaveLength(2); + await expect( + ctx.executeSql( + `DELETE FROM order_expiry_runs WHERE id = '${results[0].body.id}'`, + ), + ).rejects.toThrow(/immutable/); + }); + it('requires both workflow and order-management permissions and scopes runs', async () => { + const f = await expired(); + const operator = await secondActor(ctx, true, ['workflows.run']); + await run({ idempotencyKey: randomUUID() }, operator.token).expect(403); + const orderManager = await secondActor(ctx, true, ['orders.manage']); + await run({ idempotencyKey: randomUUID() }, orderManager.token).expect(403); + const foreign = await secondActor(ctx, false, [ + 'workflows.run', + 'orders.manage', + 'workflows.read', + ]); + expect( + (await run({ idempotencyKey: randomUUID() }, foreign.token).expect(201)) + .body.processedCount, + ).toBe(0); + expect( + (await ctx.db.order.findUniqueOrThrow({ where: { id: f.order.id } })) + .status, + ).toBe('PENDING_PAYMENT'); + await ctx + .api() + .get('/api/v1/workflows/order-expiry/runs') + .auth(operator.token, { type: 'bearer' }) + .expect(403); + for (const body of [ + { idempotencyKey: randomUUID(), limit: 26 }, + { idempotencyKey: randomUUID(), limit: 0 }, + { idempotencyKey: randomUUID(), organizationId: foreign.organizationId }, + ]) + await run(body).expect(400); + await ctx + .api() + .post('/api/v1/workflows/order-expiry/runs') + .send({ idempotencyKey: randomUUID() }) + .expect(401); + await ctx.db.user.update({ + where: { id: foreign.userId }, + data: { status: 'SUSPENDED' }, + }); + await run({ idempotencyKey: randomUUID() }, foreign.token).expect(401); + }); + it('rolls back cancellations, releases and outbox events if run persistence fails', async () => { + const f = await expired(); + await ctx.executeSql(`CREATE FUNCTION fail_expiry_run_test() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'Injected run persistence failure'; END; $$; + CREATE TRIGGER fail_expiry_run_test BEFORE INSERT ON order_expiry_runs FOR EACH ROW EXECUTE FUNCTION fail_expiry_run_test();`); + try { + await run({ limit: 25, idempotencyKey: randomUUID() }).expect(500); + } finally { + await ctx.executeSql( + 'DROP TRIGGER fail_expiry_run_test ON order_expiry_runs; DROP FUNCTION fail_expiry_run_test();', + ); + } + expect( + (await ctx.db.order.findUniqueOrThrow({ where: { id: f.order.id } })) + .status, + ).toBe('PENDING_PAYMENT'); + expect( + ( + await ctx.db.stockReservation.findUniqueOrThrow({ + where: { id: f.reservation.id }, + }) + ).status, + ).toBe('ACTIVE'); + expect( + await ctx.db.commerceEvent.count({ + where: { orderId: f.order.id, kind: 'order.cancelled' }, + }), + ).toBe(0); + expect( + await ctx.db.auditEvent.count({ + where: { targetId: f.order.id, action: 'order.expired' }, + }), + ).toBe(0); + }); +}); diff --git a/test/workflow-cli.spec.ts b/test/workflow-cli.spec.ts new file mode 100644 index 0000000..fadc5af --- /dev/null +++ b/test/workflow-cli.spec.ts @@ -0,0 +1,69 @@ +import { NestFactory } from '@nestjs/core'; +import type { INestApplicationContext } from '@nestjs/common'; +import { randomUUID } from 'node:crypto'; +import { SessionStore } from '../src/identity/session.store'; +import { runExpiryCommand } from '../src/cli/workflow-expiry'; + +describe('authenticated expiry command', () => { + afterEach(() => { + jest.restoreAllMocks(); + }); + function fixture(fail = false) { + const actor = { + userId: randomUUID(), + organizationId: randomUUID(), + sessionId: randomUUID(), + permissions: ['workflows.run', 'orders.manage'], + }; + const authenticate = jest.fn().mockResolvedValue(actor); + const run = fail + ? jest.fn().mockRejectedValue(new Error('Failure')) + : jest.fn().mockResolvedValue({ id: 'run-id', processedCount: 0 }); + const close = jest.fn().mockResolvedValue(undefined); + const app = { + get: (type: unknown) => + type === SessionStore ? { authenticate } : { run }, + close, + } as unknown as INestApplicationContext; + const create = jest + .spyOn(NestFactory, 'createApplicationContext') + .mockResolvedValue(app); + return { actor, authenticate, run, close, create }; + } + it('authenticates and runs with a stable supplied key, then closes resources', async () => { + const f = fixture(); + const key = randomUUID(); + const token = 'a'.repeat(43); + expect( + await runExpiryCommand({ + WORKFLOW_TOKEN: token, + WORKFLOW_LIMIT: '5', + WORKFLOW_RUN_KEY: key, + }), + ).toMatchObject({ processedCount: 0 }); + expect(f.authenticate).toHaveBeenCalledWith(token); + expect(f.run).toHaveBeenCalledWith(f.actor, { + limit: 5, + idempotencyKey: key, + }); + expect(f.close).toHaveBeenCalledTimes(1); + }); + it('closes resources after a failed workflow', async () => { + const f = fixture(true); + await expect( + runExpiryCommand({ WORKFLOW_TOKEN: 'a'.repeat(43) }), + ).rejects.toThrow('Failure'); + expect(f.close).toHaveBeenCalledTimes(1); + }); + it('rejects missing credentials and oversized limits before application startup', async () => { + const f = fixture(); + await expect(runExpiryCommand({})).rejects.toThrow(); + await expect( + runExpiryCommand({ + WORKFLOW_TOKEN: 'a'.repeat(43), + WORKFLOW_LIMIT: '26', + }), + ).rejects.toThrow(); + expect(f.create).not.toHaveBeenCalled(); + }); +});