feat(checkout): cash on delivery and manual UPI orders
continuous-integration/drone/push Build is passing Details

Checkout takes an optional paymentMethod. COD orders are confirmed and
deduct stock at once; UPI_MANUAL orders hold stock for 48 hours while the
customer reports a UTR and staff confirm the payment. Paid checkouts
require a pricing policy so the payable total is known.

Staff confirm, ship (with courier/tracking note) and deliver orders.
Cancelling a confirmed order restocks it; shipped orders cannot be
cancelled. Status changes are kept in an append-only history and a
database trigger enforces the allowed transitions. Coupon limits now
count confirmed, shipped and delivered orders.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
mihir 2026-11-26 15:45:45 +05:30
parent b4f61ff65e
commit 76574a5c71
18 changed files with 564 additions and 17 deletions

View File

@ -47,3 +47,18 @@ Checkout selects available stock across warehouses in stable stock-ID order, wit
Reservations reduce availability, not on-hand stock. Order holds cannot be committed/released through standalone inventory APIs. Cancellation releases all holds atomically and is idempotent; it does not rebuild the cart. After 15 minutes, pending orders display EXPIRED and their holds stop consuming availability without a cleanup job. Expired orders are not payable. The later payment phase must recheck expiry and define stock commitment before fulfillment.
The current organization lock serializes checkout with catalog, address, coupon and cart writes. This favors correctness within the existing architecture; benchmark contention on native PostgreSQL before scaling traffic. Native tests cover duplicate requests, coupon competition and checkout versus standalone inventory reservation.
## Cash on delivery and manual UPI
Checkout accepts an optional `paymentMethod`. Without it, checkout keeps the original unpaid 15-minute stock hold. With it, the address must match an active pricing policy so the order has a payable total; otherwise checkout returns `ORDER_PRICING_REQUIRED` and nothing is written.
- `COD`: the order is created `CONFIRMED` and its stock is deducted immediately. The payable total is collected on delivery.
- `UPI_MANUAL`: the order stays `PENDING_PAYMENT` and holds stock for 48 hours. The customer pays the exact `payableTotal` by UPI, then reports the transaction reference (UTR) with `POST /orders/:id/payment-reference` `{ reference }` (6–40 letters or digits, upper-cased; repeats are idempotent, at most a few per order). Staff match it against the bank statement and confirm.
| Method | Path | Permission | Effect |
| ------ | ------------------------- | ------------- | --------------------------------------------------------------------------- |
| POST | /admin/orders/:id/confirm | orders.manage | `PENDING_PAYMENT` → `CONFIRMED`; deducts held stock; rejects expired orders |
| POST | /admin/orders/:id/ship | orders.manage | `CONFIRMED` → `SHIPPED`; body `note` (3–200 chars), such as courier and AWB |
| POST | /admin/orders/:id/deliver | orders.manage | `SHIPPED` → `DELIVERED` |
Each action is safe to retry; repeating it on an order already in the target state returns the order unchanged. Other transitions return `ORDER_STATUS_CONFLICT`, and a database trigger rejects them too. Customers and staff can cancel `PENDING_PAYMENT` and `CONFIRMED` orders; cancelling a confirmed order credits its stock back through the ledger. Shipped and delivered orders cannot be cancelled. Order views include `paymentMethod` and an append-only `history` of status changes with notes, so customers can see the tracking note. Live gateways, refunds and returns remain later work.

View File

@ -1,6 +1,13 @@
enum OrderStatus {
PENDING_PAYMENT
CANCELLED
CONFIRMED
SHIPPED
DELIVERED
}
enum PaymentMethod {
COD
UPI_MANUAL
}
enum CouponKind {
FIXED
@ -67,6 +74,7 @@ model Order {
idempotencyKey String @map("idempotency_key") @db.Uuid
requestHash String @map("request_hash") @db.Char(64)
expiresAt DateTime @map("expires_at") @db.Timestamptz(3)
paymentMethod PaymentMethod? @map("payment_method")
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3)
user User @relation(fields: [userId, organizationId], references: [id, organizationId], onDelete: Restrict)
coupon Coupon? @relation(fields: [couponId, organizationId], references: [id, organizationId], onDelete: Restrict)
@ -74,6 +82,7 @@ model Order {
reservations StockReservation[]
pricing OrderPricing?
events CommerceEvent[]
statusEvents OrderStatusEvent[]
@@unique([userId, organizationId, idempotencyKey])
@@unique([id, organizationId])
@@index([organizationId, userId, createdAt, id])

View File

@ -57,5 +57,6 @@
"20261008110000_accounting_sources": "47b89e83291dbdf7b9fc7f1f25e7260a9f06bde0291ae2f7db01200e75eed396",
"20261008120000_batch_contribution": "4d6c577e6d59e9163c41253b828ed19729b76d881f21197f6b863c2f79233471",
"20261008130000_order_expiry_workflow": "e9ff103b0870e6998e2a906924a4f0394ac8ccbbe811b323d8485c3ee0dd92ff",
"20261126080000_product_images": "ce59729946f37d8958bb9f42974859b76cdaaa67e85491dc5a7eb3fa9e07d9eb"
"20261126080000_product_images": "ce59729946f37d8958bb9f42974859b76cdaaa67e85491dc5a7eb3fa9e07d9eb",
"20261126110000_offline_payments": "54f469664d10c4dfba5fb5c1b15c121b5aee10029e8ed4908bbd520280b978e8"
}

View File

@ -0,0 +1,45 @@
-- New enum values are only referenced as text below, so they are safe in this transaction.
ALTER TYPE "OrderStatus" ADD VALUE 'CONFIRMED';
ALTER TYPE "OrderStatus" ADD VALUE 'SHIPPED';
ALTER TYPE "OrderStatus" ADD VALUE 'DELIVERED';
CREATE TYPE "PaymentMethod" AS ENUM ('COD', 'UPI_MANUAL');
ALTER TABLE orders ADD COLUMN payment_method "PaymentMethod";
CREATE TABLE order_status_events (
id UUID NOT NULL, order_id UUID NOT NULL, organization_id UUID NOT NULL, actor_id UUID NOT NULL,
status "OrderStatus" NOT NULL, note VARCHAR(200) NOT NULL DEFAULT '',
created_at TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT order_status_events_pkey PRIMARY KEY (id),
CONSTRAINT order_status_events_order_id_organization_id_fkey FOREIGN KEY (order_id, organization_id) REFERENCES orders(id, organization_id) ON DELETE RESTRICT ON UPDATE CASCADE,
CONSTRAINT order_status_events_actor_id_organization_id_fkey FOREIGN KEY (actor_id, organization_id) REFERENCES users(id, organization_id) ON DELETE RESTRICT ON UPDATE CASCADE
);
CREATE INDEX order_status_events_order_id_created_at_id_idx ON order_status_events (order_id, created_at, id);
CREATE FUNCTION protect_order_status_event() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
RAISE EXCEPTION 'Order status history is immutable';
END;
$$;
CREATE TRIGGER order_status_events_immutable BEFORE UPDATE OR DELETE ON order_status_events
FOR EACH ROW EXECUTE FUNCTION protect_order_status_event();
-- Only status may change, and only along the fulfilment path.
CREATE OR REPLACE FUNCTION protect_order_snapshot() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
IF TG_OP = 'DELETE' THEN RAISE EXCEPTION 'Orders cannot be deleted'; END IF;
IF (to_jsonb(NEW) - 'status') IS DISTINCT FROM (to_jsonb(OLD) - 'status') THEN
RAISE EXCEPTION 'Order snapshots are immutable';
END IF;
IF OLD.status = 'CANCELLED' AND NEW.status <> 'CANCELLED' THEN
RAISE EXCEPTION 'Cancelled orders cannot be reopened';
END IF;
IF NEW.status IS DISTINCT FROM OLD.status AND NOT (
(OLD.status::text = 'PENDING_PAYMENT' AND NEW.status::text IN ('CONFIRMED', 'CANCELLED'))
OR (OLD.status::text = 'CONFIRMED' AND NEW.status::text IN ('SHIPPED', 'CANCELLED'))
OR (OLD.status::text = 'SHIPPED' AND NEW.status::text = 'DELIVERED')
) THEN
RAISE EXCEPTION 'Invalid order status transition';
END IF;
RETURN NEW;
END;
$$;

View File

@ -0,0 +1,13 @@
model OrderStatusEvent {
id String @id @default(uuid()) @db.Uuid
orderId String @map("order_id") @db.Uuid
organizationId String @map("organization_id") @db.Uuid
actorId String @map("actor_id") @db.Uuid
status OrderStatus
note String @default("") @db.VarChar(200)
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3)
order Order @relation(fields: [orderId, organizationId], references: [id, organizationId], onDelete: Restrict)
actor User @relation(fields: [actorId, organizationId], references: [id, organizationId], onDelete: Restrict)
@@index([orderId, createdAt, id])
@@map("order_status_events")
}

View File

@ -97,6 +97,7 @@ model User {
forumPosts ForumPost[]
forumDecisions ForumModeration[]
expiryRuns OrderExpiryRun[]
orderStatusEvents OrderStatusEvent[]
reviewPurchases ReviewPurchaseVerification[] @relation("ReviewBuyer")
reviewVerifications ReviewPurchaseVerification[] @relation("ReviewVerifier")
reviewRevocations ReviewPurchaseRevocation[]

View File

@ -3,10 +3,11 @@ 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';
import { AppError } from '../common/errors/app-error';
import { orderInclude, orderView } from './order-view';
import { restockOrder } from './stock-allocation';
export const cancellationInclude = {
lines: true,
pricing: true,
...orderInclude,
reservations: { orderBy: { stockItemId: 'asc' as const } },
};
type CancellableOrder = Prisma.OrderGetPayload<{
@ -19,6 +20,9 @@ export async function cancelOrderRecord(
action: 'order.cancelled' | 'order.expired' = 'order.cancelled',
) {
if (order.status === 'CANCELLED') return orderView(order);
if (order.status === 'SHIPPED' || order.status === 'DELIVERED')
throw new AppError('ORDER_STATUS_CONFLICT');
if (order.status === 'CONFIRMED') await restockOrder(tx, actor, order.id);
for (const reservation of order.reservations)
await lockStock(tx, actor.organizationId, reservation.stockItemId);
await tx.stockReservation.updateMany({
@ -31,8 +35,17 @@ export async function cancelOrderRecord(
});
const updated = await tx.order.update({
where: { id: order.id },
data: { status: 'CANCELLED' },
include: { lines: true, pricing: true },
data: {
status: 'CANCELLED',
statusEvents: {
create: {
actorId: actor.userId,
status: 'CANCELLED',
note: action === 'order.expired' ? 'Payment window expired' : '',
},
},
},
include: orderInclude,
});
await enqueueEvent(tx, actor.organizationId, order.id, 'order.cancelled');
await recordAudit(tx, actor.organizationId, actor.userId, action, order.id);

View File

@ -16,7 +16,22 @@ export const checkoutSchema = z
cartVersion: z.number().int().min(0).max(2147483646),
addressId: z.uuid(),
couponCode: couponCode.optional(),
// Omitted = the original unpaid 15-minute stock hold.
paymentMethod: z.enum(['COD', 'UPI_MANUAL']).optional(),
idempotencyKey: z.uuid(),
})
.strict();
// The UPI transaction reference (UTR) the customer paid with.
export const paymentReferenceSchema = z
.object({
reference: z
.string()
.trim()
.toUpperCase()
.regex(/^[A-Z0-9]{6,40}$/),
})
.strict();
export const shipmentSchema = z
.object({ note: z.string().trim().min(3).max(200) })
.strict();
export type CheckoutInput = z.infer<typeof checkoutSchema>;

View File

@ -6,8 +6,8 @@ import { AppError } from '../common/errors/app-error';
import { assertReplay, commandHash } from '../inventory/inventory.policy';
import type { CheckoutInput } from './checkout.schemas';
import { checkoutSnapshot } from './checkout-snapshot';
import { holdOrderStock } from './stock-allocation';
import { orderView } from './order-view';
import { commitOrderStock, holdOrderStock } from './stock-allocation';
import { orderInclude, orderView } from './order-view';
import { snapshotPrice } from '../pricing/snapshot-price';
import { enqueueEvent } from '../events/enqueue-event';
@ -19,7 +19,9 @@ export class CheckoutStore {
input.cartVersion,
input.addressId,
input.couponCode ?? '',
...(input.paymentMethod ? [input.paymentMethod] : []),
);
const method = input.paymentMethod;
// The organization lock also serializes catalog, coupon and cart changes.
// Stock locks below coordinate with independent inventory transactions.
return this.access.mutate(actor, null, async (tx) => {
@ -31,7 +33,7 @@ export class CheckoutStore {
idempotencyKey: input.idempotencyKey,
},
},
include: { lines: true, pricing: true },
include: orderInclude,
});
if (previous) {
assertReplay(previous.requestHash, requestHash);
@ -54,7 +56,11 @@ export class CheckoutStore {
actor,
input,
);
const expiresAt = new Date(now.getTime() + 15 * 60000);
// UPI orders wait up to two days for staff to match the payment; COD is confirmed at once.
const expiresAt = new Date(
now.getTime() + (method ? 48 * 60 : 15) * 60000,
);
const status = method === 'COD' ? 'CONFIRMED' : 'PENDING_PAYMENT';
const order = await tx.order.create({
data: {
...snapshot,
@ -63,12 +69,25 @@ export class CheckoutStore {
idempotencyKey: input.idempotencyKey,
requestHash,
expiresAt,
status,
paymentMethod: method,
lines: { create: lines },
...(method && {
statusEvents: {
create: {
actorId: actor.userId,
status,
},
},
}),
},
include: { lines: true },
include: { lines: true, statusEvents: true },
});
await holdOrderStock(tx, actor, order.id, expiresAt, lines);
const pricing = await snapshotPrice(tx, order);
// Paid checkouts must show the customer the exact amount to pay or collect.
if (method && !pricing) throw new AppError('ORDER_PRICING_REQUIRED');
if (status === 'CONFIRMED') await commitOrderStock(tx, actor, order.id);
await enqueueEvent(tx, actor.organizationId, order.id, 'order.created');
await tx.cartLine.deleteMany({ where: { cartId } });
await tx.cart.update({

View File

@ -1,4 +1,5 @@
import {
Body,
Controller,
Get,
Param,
@ -14,6 +15,7 @@ import type { Principal } from '../identity/identity.types';
import { SchemaPipe } from '../common/validation.pipe';
import { pageSchema, type PageInput } from '../identity/identity.schemas';
import { OrderStore } from './order.store';
import { shipmentSchema } from './checkout.schemas';
@Controller('admin/orders')
export class OrderAdminController {
@ -42,4 +44,29 @@ export class OrderAdminController {
) {
return this.orders.cancel(actor, id, true);
}
@Post(':id/confirm')
@RequirePermission('orders.manage')
confirm(
@CurrentPrincipal() actor: Principal,
@Param('id', ParseUUIDPipe) id: string,
) {
return this.orders.advance(actor, id, 'CONFIRMED');
}
@Post(':id/ship')
@RequirePermission('orders.manage')
ship(
@CurrentPrincipal() actor: Principal,
@Param('id', ParseUUIDPipe) id: string,
@Body(new SchemaPipe(shipmentSchema)) input: { note: string },
) {
return this.orders.advance(actor, id, 'SHIPPED', input.note);
}
@Post(':id/deliver')
@RequirePermission('orders.manage')
deliver(
@CurrentPrincipal() actor: Principal,
@Param('id', ParseUUIDPipe) id: string,
) {
return this.orders.advance(actor, id, 'DELIVERED');
}
}

View File

@ -2,14 +2,26 @@ import type {
Order,
OrderLine,
OrderPricing,
OrderStatusEvent,
} from '../generated/prisma/client';
export const orderInclude = {
lines: { orderBy: { variantId: 'asc' as const } },
pricing: true,
statusEvents: {
orderBy: [{ createdAt: 'asc' as const }, { id: 'asc' as const }],
},
};
export function orderStatus(order: Pick<Order, 'status' | 'expiresAt'>) {
return order.status === 'PENDING_PAYMENT' && order.expiresAt <= new Date()
? 'EXPIRED'
: order.status;
}
export function orderView(
order: Order & { lines: OrderLine[]; pricing?: OrderPricing | null },
order: Order & {
lines: OrderLine[];
pricing?: OrderPricing | null;
statusEvents?: OrderStatusEvent[];
},
) {
return {
id: order.id,
@ -31,6 +43,12 @@ export function orderView(
}
: null,
paymentAvailable: false,
paymentMethod: order.paymentMethod,
history: (order.statusEvents ?? []).map((event) => ({
status: event.status,
note: event.note,
createdAt: event.createdAt,
})),
address: order.addressSnapshot,
coupon: order.couponSnapshot,
createdAt: order.createdAt,

View File

@ -3,8 +3,17 @@ import { DatabaseService } from '../database/database.service';
import { AccessStore } from '../identity/access.store';
import type { Principal } from '../identity/identity.types';
import { AppError } from '../common/errors/app-error';
import { orderView, orderStatus } from './order-view';
import { recordAudit } from '../identity/audit';
import { orderInclude, orderView, orderStatus } from './order-view';
import { cancellationInclude, cancelOrderRecord } from './cancel-order';
import { commitOrderStock } from './stock-allocation';
const NEXT = {
CONFIRMED: 'PENDING_PAYMENT',
SHIPPED: 'CONFIRMED',
DELIVERED: 'SHIPPED',
} as const;
export type OrderAdvance = keyof typeof NEXT;
@Injectable()
export class OrderStore {
@ -29,6 +38,7 @@ export class OrderStore {
select: {
id: true,
status: true,
paymentMethod: true,
currency: true,
merchandiseTotal: true,
createdAt: true,
@ -49,7 +59,7 @@ export class OrderStore {
organizationId: actor.organizationId,
...(!staff ? { userId: actor.userId } : {}),
},
include: { lines: { orderBy: { variantId: 'asc' } }, pricing: true },
include: orderInclude,
});
if (!order) throw new AppError('ORDER_NOT_FOUND');
return orderView(order);
@ -72,4 +82,93 @@ export class OrderStore {
},
);
}
// The customer reports the UPI transaction reference for staff to match.
submitReference(actor: Principal, id: string, reference: string) {
return this.access.mutate(actor, null, async (tx) => {
const order = await tx.order.findFirst({
where: {
id,
organizationId: actor.organizationId,
userId: actor.userId,
},
include: orderInclude,
});
if (!order) throw new AppError('ORDER_NOT_FOUND');
if (
order.paymentMethod !== 'UPI_MANUAL' ||
orderStatus(order) !== 'PENDING_PAYMENT'
)
throw new AppError('ORDER_STATUS_CONFLICT');
const note = `UPI reference ${reference}`;
if (order.statusEvents.some((event) => event.note === note))
return orderView(order);
if (order.statusEvents.length >= 6) throw new AppError('ORDER_LIMIT');
await tx.orderStatusEvent.create({
data: {
orderId: id,
organizationId: actor.organizationId,
actorId: actor.userId,
status: 'PENDING_PAYMENT',
note,
},
});
await recordAudit(
tx,
actor.organizationId,
actor.userId,
'order.payment_reference',
id,
);
return orderView(
await tx.order.findUniqueOrThrow({
where: { id },
include: orderInclude,
}),
);
});
}
// Staff confirm a matched UPI payment, then record shipment and delivery.
advance(actor: Principal, id: string, target: OrderAdvance, note = '') {
return this.access.mutate(actor, 'orders.manage', async (tx) => {
const order = await tx.order.findFirst({
where: { id, organizationId: actor.organizationId },
});
if (!order) throw new AppError('ORDER_NOT_FOUND');
if (order.status !== target) {
if (order.status !== NEXT[target])
throw new AppError('ORDER_STATUS_CONFLICT');
if (target === 'CONFIRMED') {
if (order.expiresAt <= new Date())
throw new AppError('ORDER_EXPIRED');
await commitOrderStock(tx, actor, id);
}
await tx.order.update({
where: { id },
data: {
status: target,
statusEvents: {
create: {
actorId: actor.userId,
status: target,
note,
},
},
},
});
await recordAudit(
tx,
actor.organizationId,
actor.userId,
`order.${target.toLowerCase()}`,
id,
);
}
return orderView(
await tx.order.findUniqueOrThrow({
where: { id },
include: orderInclude,
}),
);
});
}
}

View File

@ -11,7 +11,11 @@ import { CurrentPrincipal } from '../identity/access.decorator';
import type { Principal } from '../identity/identity.types';
import { SchemaPipe } from '../common/validation.pipe';
import { pageSchema, type PageInput } from '../identity/identity.schemas';
import { checkoutSchema, type CheckoutInput } from './checkout.schemas';
import {
checkoutSchema,
paymentReferenceSchema,
type CheckoutInput,
} from './checkout.schemas';
import { CheckoutStore } from './checkout.store';
import { OrderStore } from './order.store';
@ -49,4 +53,12 @@ export class OrdersController {
) {
return this.orders.cancel(actor, id);
}
@Post('orders/:id/payment-reference')
reference(
@CurrentPrincipal() actor: Principal,
@Param('id', ParseUUIDPipe) id: string,
@Body(new SchemaPipe(paymentReferenceSchema)) input: { reference: string },
) {
return this.orders.submitReference(actor, id, input.reference);
}
}

View File

@ -50,3 +50,80 @@ export async function holdOrderStock(
if ([...remaining.values()].some((quantity) => quantity > 0))
throw new AppError('STOCK_INSUFFICIENT');
}
// Turns an order's active holds into stock leaving the warehouse ledger.
export async function commitOrderStock(
tx: Prisma.TransactionClient,
actor: Principal,
orderId: string,
) {
const holds = await tx.stockReservation.findMany({
where: { orderId, organizationId: actor.organizationId, status: 'ACTIVE' },
orderBy: { stockItemId: 'asc' },
});
for (const hold of holds) {
const stock = await lockStock(tx, actor.organizationId, hold.stockItemId);
if (stock.onHand < hold.quantity) throw new AppError('STOCK_INSUFFICIENT');
await moveStock(
tx,
actor,
stock.id,
-hold.quantity,
`Fulfil order ${orderId}`,
);
}
await tx.stockReservation.updateMany({
where: { orderId, organizationId: actor.organizationId, status: 'ACTIVE' },
data: { status: 'COMMITTED' },
});
}
// Returns committed stock when a confirmed order is cancelled before shipment.
export async function restockOrder(
tx: Prisma.TransactionClient,
actor: Principal,
orderId: string,
) {
const committed = await tx.stockReservation.findMany({
where: {
orderId,
organizationId: actor.organizationId,
status: 'COMMITTED',
},
orderBy: { stockItemId: 'asc' },
});
for (const hold of committed) {
const stock = await lockStock(tx, actor.organizationId, hold.stockItemId);
await moveStock(
tx,
actor,
stock.id,
hold.quantity,
`Restock cancelled order ${orderId}`,
);
}
}
async function moveStock(
tx: Prisma.TransactionClient,
actor: Principal,
stockItemId: string,
delta: number,
reason: string,
) {
await tx.stockItem.update({
where: { id: stockItemId },
data: { onHand: { increment: delta } },
});
await tx.stockLedger.create({
data: {
stockItemId,
organizationId: actor.organizationId,
actorId: actor.userId,
delta,
reason,
idempotencyKey: randomUUID(),
requestHash: commandHash(reason, stockItemId, delta),
},
});
}

View File

@ -32,6 +32,21 @@ export const CHECKOUT_ERRORS = {
'Coupon eligibility rule rejected checkout',
],
ORDER_NOT_FOUND: [404, 'Order not found', 'Scoped order lookup failed'],
ORDER_PRICING_REQUIRED: [
409,
'Tax and shipping are not configured for this address',
'Payable total unavailable for a paid checkout',
],
ORDER_STATUS_CONFLICT: [
409,
'The order is not in a state that allows this action',
'Order status transition rejected',
],
ORDER_EXPIRED: [
409,
'The order expired before payment was confirmed',
'Expired order confirmation rejected',
],
ORDER_LIMIT: [
409,
'Too many active orders',

View File

@ -53,8 +53,14 @@ export async function priceCoupon(
);
const where = {
couponId: coupon?.id ?? '00000000-0000-0000-0000-000000000000',
status: 'PENDING_PAYMENT' as const,
expiresAt: { gt: now },
OR: [
{ status: 'PENDING_PAYMENT' as const, expiresAt: { gt: now } },
{
status: {
in: ['CONFIRMED' as const, 'SHIPPED' as const, 'DELIVERED' as const],
},
},
],
};
const uses = await tx.order.count({ where });
const userUses = await tx.order.count({

View File

@ -88,6 +88,7 @@ describe('checkout resource limits and expiration', () => {
requestHash: 'hash',
createdAt: new Date(0),
expiresAt: new Date(1),
paymentMethod: null,
lines: [],
};
expect(orderView(order)).toMatchObject({

View File

@ -0,0 +1,161 @@
import { randomUUID } from 'node:crypto';
import { identityApp, type IdentityApp } from './helpers/identity-app';
import { checkoutFixture } from './helpers/checkout';
import { activatePricing } from './helpers/pricing';
describe('cash on delivery and manual UPI orders', () => {
let ctx: IdentityApp;
const auth = { type: 'bearer' as const };
const onHand = async (id: string) =>
(await ctx.db.stockItem.findUniqueOrThrow({ where: { id } })).onHand;
const staff = (path: string, body?: object) =>
ctx
.api()
.post(`/api/v1/admin/orders/${path}`)
.auth(ctx.token, auth)
.send(body ?? {});
async function checkout(payment: object) {
const f = await checkoutFixture(ctx);
const response = await ctx
.api()
.post('/api/v1/checkout')
.auth(f.actor.token, auth)
.send({ ...f.input, ...payment });
return { f, response };
}
beforeAll(async () => {
ctx = await identityApp();
}, 60000);
afterAll(async () => {
await ctx?.close();
});
beforeEach(async () => {
await ctx.clearLimits();
});
it('refuses a paid checkout until tax and shipping give a payable total', async () => {
const { f, response } = await checkout({ paymentMethod: 'COD' });
expect(response.status).toBe(409);
expect(response.body.code).toBe('ORDER_PRICING_REQUIRED');
expect(await onHand(f.stock.id)).toBe(10);
await activatePricing(ctx);
});
it('confirms cash on delivery at once, ships, delivers and blocks late cancellation', async () => {
const { f, response } = await checkout({ paymentMethod: 'COD' });
expect(response.status).toBe(201);
await ctx
.api()
.post(`/api/v1/orders/${response.body.id}/payment-reference`)
.auth(f.actor.token, auth)
.send({ reference: 'UTR123456789' })
.expect(409);
expect(response.body).toMatchObject({
status: 'CONFIRMED',
paymentMethod: 'COD',
pricingStatus: 'FINALIZED',
history: [{ status: 'CONFIRMED', note: '' }],
});
expect(response.body.payableTotal).not.toBeNull();
expect(await onHand(f.stock.id)).toBe(8);
const id = response.body.id as string;
await staff(`${id}/deliver`).expect(409);
await staff(`${id}/ship`, { note: '' }).expect(400);
await staff(`${id}/ship`, { note: 'Delhivery AWB 1234567890' }).expect(201);
await staff(`${id}/ship`, { note: 'Delhivery AWB 1234567890' }).expect(201);
const mine = await ctx
.api()
.get(`/api/v1/orders/${id}`)
.auth(f.actor.token, auth)
.expect(200);
expect(mine.body.status).toBe('SHIPPED');
expect(mine.body.history.map((e: { status: string }) => e.status)).toEqual([
'CONFIRMED',
'SHIPPED',
]);
expect(mine.body.history[1].note).toBe('Delhivery AWB 1234567890');
await ctx
.api()
.post(`/api/v1/orders/${id}/cancel`)
.auth(f.actor.token, auth)
.expect(409);
await staff(`${id}/deliver`).expect(201);
expect(await onHand(f.stock.id)).toBe(8);
});
it('restocks a confirmed order cancelled before shipment', async () => {
const { f, response } = await checkout({ paymentMethod: 'COD' });
expect(await onHand(f.stock.id)).toBe(8);
const cancelled = await ctx
.api()
.post(`/api/v1/orders/${response.body.id}/cancel`)
.auth(f.actor.token, auth)
.expect(201);
expect(cancelled.body.status).toBe('CANCELLED');
expect(await onHand(f.stock.id)).toBe(10);
await staff(`${response.body.id}/ship`, { note: 'Too late' }).expect(409);
});
it('holds UPI orders until staff match the reference, then commits stock', async () => {
const { f, response } = await checkout({ paymentMethod: 'UPI_MANUAL' });
expect(response.status).toBe(201);
expect(response.body).toMatchObject({
status: 'PENDING_PAYMENT',
paymentMethod: 'UPI_MANUAL',
history: [{ status: 'PENDING_PAYMENT', note: '' }],
});
const reference = (body: object, token = f.actor.token) =>
ctx
.api()
.post(`/api/v1/orders/${response.body.id}/payment-reference`)
.auth(token, auth)
.send(body);
await reference({ reference: 'bad ref!' }).expect(400);
await reference({ reference: 'UTR123456789' }, ctx.token).expect(404);
const reported = await reference({ reference: ' utr123456789 ' }).expect(
201,
);
await reference({ reference: 'UTR123456789' }).expect(201);
expect(reported.body.history).toHaveLength(2);
expect(reported.body.history[1].note).toBe('UPI reference UTR123456789');
expect(
new Date(response.body.expiresAt).getTime() - Date.now(),
).toBeGreaterThan(47 * 3600000);
expect(await onHand(f.stock.id)).toBe(10);
const id = response.body.id as string;
await ctx
.api()
.post(`/api/v1/admin/orders/${id}/confirm`)
.auth(f.actor.token, auth)
.expect(403);
await staff(`${id}/ship`, { note: 'Not paid yet' }).expect(409);
const confirmed = await staff(`${id}/confirm`).expect(201);
expect(confirmed.body.status).toBe('CONFIRMED');
expect(await onHand(f.stock.id)).toBe(8);
await staff(`${id}/confirm`).expect(201);
expect(await onHand(f.stock.id)).toBe(8);
expect(
await ctx.db.stockReservation.count({
where: { orderId: id, status: 'COMMITTED' },
}),
).toBe(1);
await reference({ reference: 'UTR999999999' }).expect(409);
await staff(`${randomUUID()}/confirm`).expect(404);
});
it('rejects confirming an expired UPI order and invalid direct status writes', async () => {
const { response } = await checkout({ paymentMethod: 'UPI_MANUAL' });
const id = response.body.id as string;
await expect(
ctx.db.order.update({ where: { id }, data: { status: 'DELIVERED' } }),
).rejects.toThrow();
await ctx.executeSql(
`ALTER TABLE orders DISABLE TRIGGER orders_snapshot_immutable;
UPDATE orders SET created_at = NOW() - INTERVAL '3 days', expires_at = NOW() - INTERVAL '1 day' WHERE id = '${id}';
ALTER TABLE orders ENABLE TRIGGER orders_snapshot_immutable;`,
);
expect((await staff(`${id}/confirm`).expect(409)).body.code).toBe(
'ORDER_EXPIRED',
);
});
});