---
title: 'A checkout workflow'
description: 'A checkout as a JSON workflow: async actions in sequence and in a parallel group, and a declined card that cancels the rest of its group through the signal.'
order: 2
---

# A checkout workflow

A checkout is a workflow: reserve the stock, charge the card, tell the warehouse, track the purchase, send a receipt. Some steps depend on the one before, and some can run together. Some can fail, and a failure has to stop the steps that are still running. This example writes the five steps as actions, expresses the order of a purchase as a JSON array, and runs it. A declined card cancels the other members of its group through their `signal`.

The workflow is data, so a server can build it, a CMS can store it and a log can replay it. [Serialized workflows](/docs/actions/serialized-workflows) shows how the text of a workflow is checked with `parseActions` before it runs.

## Install

```bash
pnpm add @schema-engine/actions @schema-engine/registry zod
```

## The actions

Each action is a registration: a `$type`, a schema for its entry, metadata with the triggers it answers by default, and an async `execute`. The context holds the services the actions call: an inventory, a payment provider, a warehouse, an analytics client and a mailer. An app passes clients of its own services, and `main.ts` passes the fakes of `shop.helper.ts`, a file this page does not show.

`chargeCard`, `notifyWarehouse` and `trackPurchase` pass their `signal` to the service call, as you would pass it to `fetch`. That is what makes cancellation work: the dispatcher aborts the signal of the other members of a group when one of them fails with `shouldContinue: false`, and a handler that observes it stops. A handler that ignores its signal keeps the dispatch waiting.

```ts title="actions.ts"
import * as z from 'zod/mini';
import { ActionRegistry, defineAction, type ActionConfigBase } from '@schema-engine/actions';

z.config(z.locales.en());

/**
 * The services the actions of a checkout call.
 *
 * @remarks
 * The actions pass their `signal` to the calls that wait, so a cancelled action stops waiting. An app passes clients
 * of its own services, and a test passes fakes.
 */
export interface CheckoutContext {
	inventory: { reserve(sku: string, quantity: number): Promise<{ ok: true } | { ok: false; left: number }> };
	payments: { charge(amount: number, options: { signal: AbortSignal }): Promise<{ approved: boolean }> };
	warehouse: { notify(options: { signal: AbortSignal }): Promise<void> };
	analytics: { track(event: string, options: { signal: AbortSignal }): Promise<void> };
	mailer: { sendReceipt(to: string): Promise<void> };
}

export type CheckoutTrigger = 'change' | 'submit';

const define = defineAction<CheckoutContext, CheckoutTrigger>();

interface ReserveStockConfig extends ActionConfigBase<'reserveStock'> {
	sku: string;
	quantity: number;
}

const reserveStock = define<ReserveStockConfig>({
	$type: 'reserveStock',
	schema: z.object({
		sku: z.string(),
		quantity: z.number().check(z.int(), z.positive()),
	}),
	metadata: { name: 'Reserve stock', defaultTriggers: ['submit'] },
	execute: async ({ config, inventory }) => {
		const reservation = await inventory.reserve(config.sku, config.quantity);
		if (!reservation.ok) {
			return { success: false, error: `Only ${reservation.left} of ${config.sku} left`, shouldContinue: false };
		}
		return { success: true, message: `Reserved ${config.quantity} of ${config.sku}` };
	},
});

interface ChargeCardConfig extends ActionConfigBase<'chargeCard'> {
	amount: number;
}

const chargeCard = define<ChargeCardConfig>({
	$type: 'chargeCard',
	schema: z.object({ amount: z.number().check(z.positive()) }),
	metadata: { name: 'Charge the card', defaultTriggers: ['submit'] },
	execute: async ({ config, payments, signal }) => {
		const { approved } = await payments.charge(config.amount, { signal });
		if (!approved) return { success: false, error: 'The card was declined', shouldContinue: false };
		return { success: true, message: `Charged ${config.amount}` };
	},
});

type NotifyWarehouseConfig = ActionConfigBase<'notifyWarehouse'>;

const notifyWarehouse = define<NotifyWarehouseConfig>({
	$type: 'notifyWarehouse',
	schema: z.object({}),
	metadata: { name: 'Notify the warehouse', defaultTriggers: ['submit'] },
	execute: async ({ warehouse, signal }) => {
		await warehouse.notify({ signal });
		return { success: true, message: 'Warehouse notified' };
	},
});

interface TrackPurchaseConfig extends ActionConfigBase<'trackPurchase'> {
	event: string;
}

const trackPurchase = define<TrackPurchaseConfig>({
	$type: 'trackPurchase',
	schema: z.object({ event: z.string() }),
	metadata: { name: 'Track the purchase', defaultTriggers: ['change', 'submit'] },
	execute: async ({ config, analytics, signal }) => {
		await analytics.track(config.event, { signal });
		return { success: true, message: `Tracked ${config.event}` };
	},
});

interface SendReceiptConfig extends ActionConfigBase<'sendReceipt'> {
	to: string;
}

const sendReceipt = define<SendReceiptConfig>({
	$type: 'sendReceipt',
	schema: z.object({ to: z.email() }),
	metadata: { name: 'Send the receipt', defaultTriggers: ['submit'] },
	execute: async ({ config, mailer }) => {
		await mailer.sendReceipt(config.to);
		return { success: true, message: `Receipt sent to ${config.to}` };
	},
});

export const registry = new ActionRegistry<CheckoutContext, CheckoutTrigger>([
	reserveStock,
	chargeCard,
	notifyWarehouse,
	trackPurchase,
	sendReceipt,
]);
```

## The workflow

`checkoutWorkflow` returns the text a server sends. The first entry reserves stock. The inner array is a group, so the card is charged, the warehouse told and the purchase tracked together. The receipt goes out last.

```ts title="workflow.ts"
export interface Order {
	sku: string;
	quantity: number;
	amount: number;
	email: string;
}

/**
 * The checkout of an order as JSON text, the way a server or a CMS would send it.
 *
 * @remarks
 * Stock is reserved first. Then the card is charged while the warehouse is told and the purchase is tracked: the
 * inner array is a group, which runs together. The receipt goes out last.
 */
export function checkoutWorkflow({ sku, quantity, amount, email }: Order): string {
	return JSON.stringify(
		[
			{ id: 'reserve', $type: 'reserveStock', sku, quantity },
			[
				{ id: 'charge', $type: 'chargeCard', amount },
				{ id: 'warehouse', $type: 'notifyWarehouse' },
				{ id: 'track', $type: 'trackPurchase', event: 'purchase' },
			],
			{ id: 'receipt', $type: 'sendReceipt', to: email },
		],
		null,
		'\t',
	);
}
```

For an order of two black tees at 120, the text is:

```json
[
	{
		"id": "reserve",
		"$type": "reserveStock",
		"sku": "tee-black-m",
		"quantity": 2
	},
	[
		{
			"id": "charge",
			"$type": "chargeCard",
			"amount": 120
		},
		{
			"id": "warehouse",
			"$type": "notifyWarehouse"
		},
		{
			"id": "track",
			"$type": "trackPurchase",
			"event": "purchase"
		}
	],
	{
		"id": "receipt",
		"$type": "sendReceipt",
		"to": "ada@example.com"
	}
]
```

## Parse and dispatch

`runCheckout` parses the text, checks every entry against the schema of its action with `parseActions`, and dispatches the parsed sequence on `submit`. An entry that does not pass is an issue with its path and nothing runs, not even the entries that are valid. The dispatcher accepts only what `parseActions` returned, so an unchecked workflow cannot reach a handler.

```ts title="checkout.ts"
import { ActionDispatcher, parseActions, type ActionDispatchResult } from '@schema-engine/actions';
import { formatIssuePath } from '@schema-engine/registry';
import { registry, type CheckoutContext } from './actions';

export type Checkout = { success: true; results: ActionDispatchResult[] } | { success: false; issues: string[] };

/**
 * Parses a workflow and runs it on `submit`.
 *
 * @remarks
 * `parseActions` checks every entry against the schema of its action, and the dispatcher accepts only what it
 * returned. A workflow with a bad entry runs nothing, not even its valid entries.
 */
export async function runCheckout(text: string, context: CheckoutContext): Promise<Checkout> {
	let input: unknown;
	try {
		input = JSON.parse(text);
	} catch {
		return { success: false, issues: ['The workflow is not valid JSON.'] };
	}
	const parsed = parseActions(registry, input);
	if (!parsed.success) {
		return {
			success: false,
			issues: parsed.issues.map((issue) => `${formatIssuePath(issue.path)}: ${issue.message}`),
		};
	}
	const results = await new ActionDispatcher(registry).dispatch({ actions: parsed.data, trigger: 'submit', context });
	return { success: true, results };
}
```

## Run it

`main.ts` runs the workflow twice: with a card that pays, and with a card that is declined because the amount is above the limit. It prints one line for each `ActionDispatchResult`, with the entry's step and group, its status and its message or error, and what left the shop.

```ts title="main.ts"
import { runCheckout } from './checkout';
import { createFakeShop } from './shop.helper';
import { checkoutWorkflow } from './workflow';

const order = { sku: 'tee-black-m', quantity: 2, amount: 120, email: 'ada@example.com' };

for (const [name, amount] of [
	['a card that pays', 120],
	['a card that is declined', 900],
] as const) {
	console.log(name);
	const shop = createFakeShop({ 'tee-black-m': 10 }, 500);
	const checkout = await runCheckout(checkoutWorkflow({ ...order, amount }), shop.context);
	if (!checkout.success) console.log(checkout.issues.join('\n'));
	else {
		for (const result of checkout.results) {
			const group = result.groupIndex === undefined ? '' : `, group ${result.groupIndex}`;
			const outcome = result.success ? result.message : result.error;
			console.log(`${result.actionId} (step ${result.sequenceIndex}${group}) ${result.status}: ${outcome}`);
		}
		console.log(`sent: ${shop.sent.join(', ') || 'nothing'}`);
	}
}
```

```text
a card that pays
reserve (step 0) succeeded: Reserved 2 of tee-black-m
charge (step 1, group 0) succeeded: Charged 120
warehouse (step 1, group 1) succeeded: Warehouse notified
track (step 1, group 2) succeeded: Tracked purchase
receipt (step 2) succeeded: Receipt sent to ada@example.com
sent: warehouse, analytics:purchase, receipt:ada@example.com
a card that is declined
reserve (step 0) succeeded: Reserved 2 of tee-black-m
charge (step 1, group 0) failed: The card was declined
warehouse (step 1, group 1) cancelled: The operation was aborted.
track (step 1, group 2) cancelled: The operation was aborted.
sent: nothing
```

- **A card that pays.** The five entries succeed. The three members of the group share the step and have a group of their own, and results come back in configuration order, not in the order they finished.
- **A card that is declined.** `charge` fails with `shouldContinue: false`. The dispatcher aborts the signal of `warehouse` and `track`, which stop waiting and report `cancelled`. No later entry runs, so there is no receipt, and nothing was sent.
- **The reservation stays.** Cancelling stops what is still running. It does not undo what already happened: the stock of the declined order is still reserved. A real checkout adds a `releaseStock` action and dispatches it with its own trigger, for example `declined`, when the result of the `submit` dispatch shows that the charge failed.

The package logs a warning to the console for each failed action. The example's test silences it.

## Take it further

- Run only some entries on some moments: [Serialized workflows](/docs/actions/serialized-workflows#triggers-are-entry-points).
- Receive the workflow as text and check it with `parseActions` before it runs: [Serialized workflows](/docs/actions/serialized-workflows).
- Cancel a whole dispatch from outside: [Sequences, parallel groups, cancellation](/docs/actions/sequences-and-cancellation).
