Refunds, Payments, and State Transitions
Track two purchased tickets through partial refunds, repeated requests, payment evidence, and recovery from partial failures.
You’re reading a preview. Premium includes the full lesson and specialist practice. View the full curriculum.
Mia bought two tickets. She refunds one. How many can she refund next? The answer depends on what was purchased and what has already been refunded, not just whether she owns the order.
| Before the request | Requested quantity | Permitted? |
|---|---|---|
| Bought 2, refunded 0 | 1 | Yes; 1 remains afterward |
| Bought 2, refunded 1 | 2 | No; only 1 remains |
| Bought 2, refunded 2 | 1 | No; nothing remains |
We'll follow this remaining quantity through a refund. Then we'll examine payment evidence, retries, coupons, and partial failures. Repeating requests one at a time is enough to find some workflow bugs; overlapping requests come in the next topic.
Model the entitlement explicitly
A purchase can create a finite right to return or refund some quantity under specific conditions. Represent what was purchased, what was already refunded, what is pending, which states allow another request, and how fees or shipping affect value. A status string such as paid is not a complete entitlement model.
// Unsafe original refund outline.
const order = await orders.requireOwned(actor.userId, body.orderId);
const quantity = parsePositiveInteger(body.quantity);
const credit = order.unitPriceMinor * BigInt(quantity);
await db.transaction(async tx => {
await tx.wallets.lock(actor.walletId);
await tx.wallets.increment(actor.walletId, credit);
await tx.refunds.insert({ orderId: order.id, quantity, credit });
});
The ownership and stored-price controls should be preserved. The wallet lock may serialize wallet changes, but it does not prove quantity is at most the remaining refundable entitlement. If one item was bought and ten are requested, a single request can already violate the rule. If one legitimate refund succeeds and the same request succeeds again, sequential replay is enough.
Trace ownership, authoritative value, and remaining entitlement separately.
Own. The order belongs to the actor; this existing check remains valuable.
const order = await requireOwnedOrder(actor, orderId);
Value. The price comes from the purchase record, not the caller.
const credit = order.paidUnitPriceMinor * BigInt(quantity);
Consume. The transition must reject excessive or already-refunded quantity before crediting.
require(quantity <= remainingQuantity);
consumeAndCreditAtomically(quantity, credit);
Review question: Correct ownership and price do not replace current state and entitlement.