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), ); } }