224 lines
7.4 KiB
TypeScript
224 lines
7.4 KiB
TypeScript
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);
|
|
});
|
|
});
|