|
| 1 | +import type { IdempotencyKey, OrderId } from "../money/ids.js"; |
| 2 | +import type { OrderStore } from "../ports/order-store.js"; |
| 3 | +import { emailTemplateForState, isLegalOrderTransition } from "./state-machine.js"; |
| 4 | +import type { CancellationReason, Order } from "./model.js"; |
| 5 | + |
| 6 | +export interface CancelOrderDeps { |
| 7 | + orderStore: OrderStore; |
| 8 | +} |
| 9 | + |
| 10 | +export interface CancelOrderCommand { |
| 11 | + orderId: OrderId; |
| 12 | + reason: CancellationReason; |
| 13 | + /** Optional free-text elaboration — trimmed; an absent/blank value normalizes |
| 14 | + * to `null` (mirrors `recordFulfillment`'s optional `trackingUrl`). */ |
| 15 | + detail?: string | null; |
| 16 | + /** Who cancelled it — trimmed + required non-empty (mirrors an order note's |
| 17 | + * `author`; the domain does not model admin identity). */ |
| 18 | + cancelledBy: string; |
| 19 | + /** Every command carries one (CLAUDE.md); the store's guarded flip enforces |
| 20 | + * once-only. */ |
| 21 | + idempotencyKey: IdempotencyKey; |
| 22 | +} |
| 23 | + |
| 24 | +export type CancelOrderFailure = |
| 25 | + | "ORDER_NOT_FOUND" |
| 26 | + /** The order's current state cannot legally reach `cancelled` (per |
| 27 | + * `isLegalOrderTransition(state, "cancelled")` — today `pending`, `paid`, and |
| 28 | + * `processing`). A terminal order (shipped/delivered/completed/refunded/ |
| 29 | + * already-cancelled-without-reason via a DIFFERENT race, or already failed/ |
| 30 | + * expired) is rejected: cancellation is only meaningful pre-fulfillment. */ |
| 31 | + | "NOT_CANCELLABLE" |
| 32 | + | "EMPTY_CANCELLED_BY"; |
| 33 | + |
| 34 | +export type CancelOrderOutcome = |
| 35 | + | { ok: true; cancelled: boolean; order: Order } |
| 36 | + | { ok: false; reason: CancelOrderFailure }; |
| 37 | + |
| 38 | +/** |
| 39 | + * Cancel an order WITH a structured reason (admin-UX Increment 1, "cancel with |
| 40 | + * reason" slice). Pure orchestration — no IO of its own: validate, confirm the |
| 41 | + * order's current state can legally reach `cancelled` (per the ONE state |
| 42 | + * machine), then delegate the guarded "flip + record" compose to the store. |
| 43 | + * |
| 44 | + * This is the SAME composition shape as `recordFulfillment`: cancelling records |
| 45 | + * the reason envelope AND drives the transition to `cancelled` AND enqueues the |
| 46 | + * cancelled email, atomically, so no reachable state is "cancelled with no |
| 47 | + * reason recorded" (via this path). Mutable-envelope only — it NEVER touches |
| 48 | + * line items, prices, or totals (the snapshot invariant); the bare |
| 49 | + * `transitionOrder` command remains available for other callers/back-compat |
| 50 | + * (a cancellation via that path has `cancellation === null`, an honest "no |
| 51 | + * reason on file" state). |
| 52 | + * |
| 53 | + * Legality + idempotency, mirroring `recordFulfillment`/`transitionOrder`: |
| 54 | + * - a state that can legally cancel (per `isLegalOrderTransition(state, |
| 55 | + * "cancelled")` — never a re-listing; today `pending`/`paid`/`processing`) |
| 56 | + * cancels once; the store's guarded `WHERE state=:fromState` flip makes |
| 57 | + * concurrent/replayed calls a 0-row no-op, so exactly one reason is ever |
| 58 | + * written and exactly one cancelled email enqueued; |
| 59 | + * - an **already-cancelled-WITH-a-reason** order is an idempotent no-op success |
| 60 | + * (`cancelled:false`) — a redelivery / double-submit is not an error; |
| 61 | + * - an **already-cancelled-WITHOUT-a-reason** order (cancelled via the bare |
| 62 | + * transition) is `NOT_CANCELLABLE` — this compose never back-fills a reason |
| 63 | + * onto a cancellation it didn't make (mirrors `recordFulfillment`'s |
| 64 | + * shipped-without-fulfillment case); |
| 65 | + * - any **other state** (shipped/delivered/completed/refunded/failed/expired, |
| 66 | + * or a concurrent transition that won the race first) is `NOT_CANCELLABLE`. |
| 67 | + */ |
| 68 | +export async function cancelOrder( |
| 69 | + deps: CancelOrderDeps, |
| 70 | + cmd: CancelOrderCommand, |
| 71 | +): Promise<CancelOrderOutcome> { |
| 72 | + const cancelledBy = cmd.cancelledBy.trim(); |
| 73 | + if (cancelledBy.length === 0) return { ok: false, reason: "EMPTY_CANCELLED_BY" }; |
| 74 | + // The detail is optional free text: trim and treat a blank/absent value as |
| 75 | + // "none" (null) — mirrors recordFulfillment's optional trackingUrl. |
| 76 | + const trimmedDetail = (cmd.detail ?? "").trim(); |
| 77 | + const detail = trimmedDetail.length === 0 ? null : trimmedDetail; |
| 78 | + |
| 79 | + const order = await deps.orderStore.getById(cmd.orderId); |
| 80 | + if (order === null) return { ok: false, reason: "ORDER_NOT_FOUND" }; |
| 81 | + |
| 82 | + // Already cancelled WITH a reason ⇒ benign idempotent no-op (a replay / double |
| 83 | + // submit). Already cancelled WITHOUT a reason (the bare transition path) is |
| 84 | + // not back-fillable via this compose — mirrors recordFulfillment's |
| 85 | + // shipped-without-fulfillment case. |
| 86 | + if (order.state === "cancelled") { |
| 87 | + if (order.cancellation !== null) return { ok: true, cancelled: false, order }; |
| 88 | + return { ok: false, reason: "NOT_CANCELLABLE" }; |
| 89 | + } |
| 90 | + // Legality is DERIVED from the one state machine (never a hardcoded state |
| 91 | + // list): cancellable ⇔ the current state can legally transition to |
| 92 | + // `cancelled` (today pending/paid/processing; if the machine ever widens |
| 93 | + // this, this — and the store's fromState guard below — follow automatically). |
| 94 | + if (!isLegalOrderTransition(order.state, "cancelled")) { |
| 95 | + return { ok: false, reason: "NOT_CANCELLABLE" }; |
| 96 | + } |
| 97 | + |
| 98 | + const res = await deps.orderStore.cancelOrder({ |
| 99 | + orderId: cmd.orderId, |
| 100 | + // The guarded flip's from-state — the state we just validated as legally |
| 101 | + // able to cancel (the `transition`/`recordFulfillment` fromState precedent). |
| 102 | + fromState: order.state, |
| 103 | + reason: cmd.reason, |
| 104 | + detail, |
| 105 | + cancelledBy, |
| 106 | + idempotencyKey: cmd.idempotencyKey, |
| 107 | + // `cancelled` always has a template — symmetric with `transitionOrder`/ |
| 108 | + // `recordFulfillment`. |
| 109 | + enqueueEmail: emailTemplateForState("cancelled") !== null, |
| 110 | + }); |
| 111 | + if (res.cancelled) return { ok: true, cancelled: true, order: res.order ?? order }; |
| 112 | + |
| 113 | + // The guarded flip missed (0 rows) — someone moved the order out of |
| 114 | + // `fromState` between our read and the UPDATE. Disambiguate on the fresh row: |
| 115 | + // cancelled WITH a reason ⇒ a concurrent cancel won (benign no-op); anything |
| 116 | + // else (a concurrent ship/refund/etc., or cancelled-without-reason) ⇒ not |
| 117 | + // cancellable. |
| 118 | + const fresh = res.order; |
| 119 | + if (fresh !== null && fresh.state === "cancelled" && fresh.cancellation !== null) { |
| 120 | + return { ok: true, cancelled: false, order: fresh }; |
| 121 | + } |
| 122 | + return { ok: false, reason: "NOT_CANCELLABLE" }; |
| 123 | +} |
0 commit comments