@blamejs/blamejs-shop 0.3.76 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -6,6 +6,10 @@ Pre-1.0 the surface is intentionally evolving — every release may
6
6
  change something operators depend on. Read each entry before
7
7
  upgrading across more than a few patches at a time.
8
8
 
9
+ ## v0.4.x
10
+
11
+ - v0.4.0 (2026-06-05) — **Inventory is enforced at the point of sale, completing the transactions, checkout, and analytics surface.** Stock levels were previously display-only: the product page showed honest availability, but nothing reserved inventory at checkout or debited it on a sale, so concurrent buyers could oversell a SKU and stock counts never moved. Checkout now places an atomic per-SKU hold before any charge — a sold-out line re-renders the form with a friendly message instead of charging — and the order lifecycle settles the hold: payment converts it to a real stock decrement (idempotent across webhook re-deliveries), cancellation releases it, and refunds deliberately leave restocking to the operator's judgment. Untracked SKUs remain unlimited, and pre-order campaigns keep their own reservation flow. The README previously described an oversell-prevention mechanism that was not actually wired; it now describes the real one. This minor release caps the transactions, checkout, and analytics arc: server-validated addresses and digital-cart checkout, discount codes with console authoring, gift cards, loyalty, store pickup, a dark-themed Stripe payment surface with express wallets and verified 3-D Secure, shipment tracking timelines, consent-gated funnel analytics with an admin dashboard, abandoned-cart visibility with honest recovery codes, operator error logs, and confirmation resends. Known, documented deferrals: customer receipt downloads (the confirmation page and signed email serve as the receipt), partial refunds from the browser console (the JSON API supports them), and a real-time new-order notification (the dashboard and outbound webhooks cover arrival today). **Added:** *Point-of-sale inventory enforcement* — Checkout reserves stock with an atomic conditional hold per shippable line before charging — insufficient stock re-renders the checkout with a clear message and charges nothing, and two concurrent buyers of the last unit resolve to exactly one sale. Payment converts holds into stock decrements, idempotently across webhook re-deliveries; cancelling a pending order releases its holds precisely, even when other shoppers hold the same SKU. Refunds do not auto-restock — returned goods re-enter stock through the operator's existing restock action, by judgment. SKUs without an inventory row remain available without limit, and pre-order campaigns are unaffected. The inventory primitive gains the hold and decrement operations its documentation previously described, and the README now reflects the actual oversell-prevention mechanism. **Changed:** *The 0.3 series rolls up* — This release follows nineteen 0.3.x patches that built out the commerce surface: server-side address validation with accessible per-field errors, digital-cart checkout without an address, delivery-date estimates, discount unlock codes with cart redemption and console authoring, full shipment-tracking timelines, consent-gated funnel analytics and an Analytics console screen, abandoned-cart visibility with single-use recovery codes, an operator-readable error log with a JSON API, order-confirmation resends, segment CSV exports, payment-processor TLS fixes verified by live payment, a dark-themed payment surface with express wallets, and a vendored-framework refresh. See the changelog for the full sequence.
12
+
9
13
  ## v0.3.x
10
14
 
11
15
  - v0.3.76 (2026-06-05) — **Abandoned-cart visibility in the admin console, with honest recovery.** The admin console gains a Carts screen showing abandoned carts: active carts with items whose last activity is older than a tunable window (twenty-four hours by default), listed freshest-first with line counts, subtotals, guest or signed-in attribution, and a value-at-risk summary. Recovery is built around what the privacy stance actually permits: buyer email addresses are stored only as one-way hashes, so a recovery email is impossible by design and the screen says so plainly. Instead, a per-cart action mints a single-use, code-gated percent-off discount — composing the existing unlock-code rules — and shows the code once for the operator to share through whatever channel they have. Fresh, empty, and converted carts are excluded; queries are window- and limit-bounded; the screen and its JSON shape are bearer-gated like every other console surface. **Added:** *Abandoned-carts screen with single-use recovery codes* — GET /admin/carts lists abandoned carts — active, containing items, idle past the window (tunable via the hours parameter, clamped to sane bounds) — with per-cart line counts, subtotal, last activity, and the customer link for signed-in carts, plus a count and value-at-risk summary. The per-cart Issue-code action creates a single-use unlock-code discount rule at the operator's chosen percentage and reveals the code once; the action is audited and appears only when the discounts primitive is wired. Session identifiers never appear in the JSON shape, and the screen states why no email recovery exists: addresses are one-way hashed.
package/README.md CHANGED
@@ -43,7 +43,7 @@ node test/smoke.js
43
43
 
44
44
  - **Cloudflare deploy topology** — `Dockerfile` (multi-stage Node LTS, non-root, tini PID 1, vendor refresh + smoke run as build stages), `wrangler.toml` (Container + Worker + D1 + R2 + KV + Durable Objects), `worker/index.js` (edge router: health, asset pass-through, Stripe webhook signature pre-verification, D1 service-binding bridge, container forward, cold-start retry).
45
45
  - **`b.externalDb` adapter for Cloudflare D1** (`lib/externaldb-d1.js`) — service-binding + REST-API modes, normalized result envelope, AbortController timeouts, jittered retry on transient errors.
46
- - **`InventoryLock` Durable Object** — per-SKU serialization point so concurrent checkouts across container replicas can't oversell.
46
+ - **Oversell-safe stock at checkout** — checkout reserves stock with an atomic conditional `UPDATE` (`held = held + qty WHERE on_hand - held >= qty`) before charging, converts the hold to a shelf debit when the order is paid, and releases it if the pending order is cancelled or expires; pre-order / backorder / digital lines are exempt. The conditional write is the serialization point, so two concurrent checkouts for the last unit can't both succeed — the loser gets a friendly out-of-stock re-prompt. An `InventoryLock` Durable Object ships as an optional per-SKU serialization aid for multi-replica deployments.
47
47
  - **`docs/deploy-cloudflare.md`** — operator deploy recipe end-to-end.
48
48
  - **Database backup & recovery** — D1 Time Travel gives 30 days of
49
49
  always-on point-in-time recovery; `npm run d1-export` (`scripts/d1-export.js`)
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "0.3.76",
2
+ "version": "0.4.0",
3
3
  "assets": {
4
4
  "css/admin.css": {
5
5
  "integrity": "sha384-6k53cvkRrxMgmeStLIoLjVXZQHqIJgTmv1Izd8TYhh1HOC4POgE6GCvx1bsalyEP",
package/lib/catalog.js CHANGED
@@ -10,7 +10,8 @@
10
10
  * - `products` — create, get, bySlug, list, update, archive, restore
11
11
  * - `variants` — create, get, listForProduct, update, delete
12
12
  * - `prices` — set (versioned), current, history
13
- * - `inventory` — create, get, decrement, release, restock
13
+ * - `inventory` — create, get, list, hold, decrement, release,
14
+ * restock, setThreshold, checkLowStock
14
15
  * - `media` — attach, get, listForProduct, listForVariant, delete,
15
16
  * reorder, setPrimary
16
17
  *
@@ -679,10 +680,16 @@ function _inventoryModule(query, opts) {
679
680
  return { rows: (await query(sql, [limit])).rows };
680
681
  },
681
682
 
682
- // Hot-path decrement happens via the Worker's InventoryLock
683
- // Durable Object this primitive is for admin restock / release
684
- // operations that don't need the DO serialization. Concurrent
685
- // decrements MUST go through the DO (see worker/index.js).
683
+ // `hold`, `decrement`, and `release` are the checkout-time stock
684
+ // primitives; `restock` and `setThreshold` are admin operations.
685
+ // Concurrency on the buy path is enforced by the conditional-UPDATE
686
+ // guards in `hold` / `decrement` (the WHERE clause refuses the write
687
+ // when stock is insufficient), so two racing confirms against the
688
+ // same SKU can never both succeed beyond the shelf. The container
689
+ // runs a single replica today; the guards are written to hold under
690
+ // N replicas without change — D1 applies each UPDATE atomically and
691
+ // the WHERE clause re-reads the row inside the same statement, so the
692
+ // check-and-set is a single SQL operation, not a read-then-write race.
686
693
  restock: async function (sku, qty) {
687
694
  _sku(sku);
688
695
  _positiveInt(qty, "qty");
@@ -714,6 +721,71 @@ function _inventoryModule(query, opts) {
714
721
  return await this.get(sku);
715
722
  },
716
723
 
724
+ // Place an atomic hold against available stock (on_hand − held).
725
+ // Called at checkout-confirm time, BEFORE the buyer is charged, so
726
+ // two concurrent confirms for the last unit can't both proceed. The
727
+ // conditional WHERE is the serialization point: D1 evaluates the
728
+ // `(stock_on_hand - stock_held) >= qty` predicate and applies the
729
+ // `stock_held = stock_held + qty` write in one atomic statement, so
730
+ // the second racer's predicate sees the first racer's increment and
731
+ // the UPDATE matches zero rows.
732
+ //
733
+ // Returns `{ held: true, sku, qty }` when the hold lands;
734
+ // `{ held: false, sku, qty }` when there's a row but it lacks the
735
+ // available stock (the caller renders the friendly out-of-stock
736
+ // message); `null` when the SKU has NO inventory row at all — an
737
+ // un-tracked SKU is treated as unlimited everywhere in the storefront
738
+ // (PDP, facets, edge all read a missing row as available), so a hold
739
+ // simply doesn't apply and the caller lets the line through.
740
+ hold: async function (sku, qty) {
741
+ _sku(sku);
742
+ _positiveInt(qty, "qty");
743
+ var ts = _now();
744
+ var r = await query(
745
+ "UPDATE inventory SET stock_held = stock_held + ?1, updated_at = ?2 " +
746
+ "WHERE sku = ?3 AND (stock_on_hand - stock_held) >= ?1",
747
+ [qty, ts, sku],
748
+ );
749
+ if (r.rowCount === 1) {
750
+ // Hold lowers available; a low-stock threshold may now trip.
751
+ await _afterMutation(sku);
752
+ return { held: true, sku: sku, qty: qty };
753
+ }
754
+ // Zero rows: either the SKU has no row, or it has a row but
755
+ // insufficient available stock. Distinguish so the caller can let
756
+ // an un-tracked SKU through while refusing a tracked-but-empty one.
757
+ var existing = await this.get(sku);
758
+ if (!existing) return null;
759
+ return { held: false, sku: sku, qty: qty };
760
+ },
761
+
762
+ // Convert a hold into a sale: debit on_hand and clear the matching
763
+ // held units in one atomic statement. Called on the order's paid
764
+ // transition. The `stock_held >= qty AND stock_on_hand >= qty` guard
765
+ // makes this a no-op for any SKU that was never held (an exempt or
766
+ // un-tracked line) and for a re-delivered paid event whose hold was
767
+ // already consumed — so it is idempotent: a second call against an
768
+ // already-debited SKU matches zero rows and returns `{ decremented:
769
+ // false }`. Both columns stay non-negative (the schema CHECKs would
770
+ // reject otherwise), so a bookkeeping drift can never write a
771
+ // negative shelf.
772
+ decrement: async function (sku, qty) {
773
+ _sku(sku);
774
+ _positiveInt(qty, "qty");
775
+ var ts = _now();
776
+ var r = await query(
777
+ "UPDATE inventory SET stock_on_hand = stock_on_hand - ?1, " +
778
+ "stock_held = stock_held - ?1, updated_at = ?2 " +
779
+ "WHERE sku = ?3 AND stock_held >= ?1 AND stock_on_hand >= ?1",
780
+ [qty, ts, sku],
781
+ );
782
+ if (r.rowCount === 1) {
783
+ await _afterMutation(sku);
784
+ return { decremented: true, sku: sku, qty: qty };
785
+ }
786
+ return { decremented: false, sku: sku, qty: qty };
787
+ },
788
+
717
789
  // Set / clear the per-SKU low-stock threshold. `threshold = null`
718
790
  // disables alerts for the SKU. Operators set this via the admin
719
791
  // API (`PATCH /admin/inventory/:sku/threshold`).
package/lib/checkout.js CHANGED
@@ -234,6 +234,17 @@ function create(deps) {
234
234
  // Disabled when absent — the buy path is byte-identical to the un-wired
235
235
  // flow.
236
236
  var discountAllocation = deps.discountAllocation || null;
237
+ // Optional backorder + preorder handles. When wired, a line whose SKU
238
+ // is actively backorderable (`backorder.availabilityFor` →
239
+ // `backorderable`) or has an open pre-order campaign
240
+ // (`preorder.openCampaignForSku` → a row) is EXEMPT from the
241
+ // confirm-time stock hold: those flows deliberately sell beyond the
242
+ // shelf (the operator commits to ship later / the unit isn't released
243
+ // yet). Absent — no SKU is exempted on these grounds, which matches
244
+ // production today (neither primitive is mounted on the buy path);
245
+ // a SKU with no inventory row is still treated as unlimited regardless.
246
+ var backorder = deps.backorder || null;
247
+ var preorder = deps.preorder || null;
237
248
 
238
249
  // Reprice a list of cart lines through the quantity-discount engine.
239
250
  // Returns a shallow copy with `unit_amount_minor` overwritten by the
@@ -587,6 +598,80 @@ function create(deps) {
587
598
  }
588
599
  }
589
600
 
601
+ // Is this SKU exempt from the confirm-time stock hold? Pre-order and
602
+ // backorder lines deliberately sell beyond the shelf, so they pass
603
+ // through without a hold. Both lookups are optional (the handles may
604
+ // be unwired) and defensive — any read failure falls back to "not
605
+ // exempt" so a flaky lookup tightens (never loosens) enforcement.
606
+ async function _holdExempt(sku) {
607
+ if (preorder && typeof preorder.openCampaignForSku === "function") {
608
+ try {
609
+ if (await preorder.openCampaignForSku(sku)) return true;
610
+ } catch (_e) { /* not exempt on lookup failure */ }
611
+ }
612
+ if (backorder && typeof backorder.availabilityFor === "function") {
613
+ try {
614
+ var a = await backorder.availabilityFor(sku);
615
+ if (a && a.status === "backorderable") return true;
616
+ } catch (_e) { /* not exempt on lookup failure */ }
617
+ }
618
+ return false;
619
+ }
620
+
621
+ // Reserve stock for every shippable, non-exempt line BEFORE any charge.
622
+ // Each hold is an atomic conditional UPDATE (`catalog.inventory.hold`):
623
+ // the SKU's available stock (on_hand − held) must cover the line qty or
624
+ // the write matches zero rows. On the FIRST insufficient line we release
625
+ // every hold already placed in this pass and throw a coded
626
+ // INSUFFICIENT_STOCK error carrying a friendly, per-line message — the
627
+ // storefront re-renders the checkout form inline with that message, the
628
+ // same recoverable UX a rejected gift-card / loyalty code gets. Nothing
629
+ // is charged and no order row is created, so a refused checkout leaves
630
+ // zero side effects beyond the already-rolled-back holds.
631
+ //
632
+ // Digital lines (requires_shipping false) never debit stock. An
633
+ // un-tracked SKU (no inventory row) is unlimited (hold → null) and
634
+ // passes through. Each line that DID hold is annotated with `_held_qty`
635
+ // so the order line records the exact reserved quantity (the paid
636
+ // decrement + cancel release act on it). Returns the list of placed
637
+ // { sku, qty } holds so the caller can release them if a LATER step
638
+ // (gift-card burn, order create) throws before the order is committed.
639
+ async function _placeStockHolds(quoteLines) {
640
+ var placed = [];
641
+ for (var i = 0; i < quoteLines.length; i += 1) {
642
+ var l = quoteLines[i];
643
+ l._held_qty = 0; // default: held nothing
644
+ if (!l.requires_shipping) continue; // digital — no shelf
645
+ if (await _holdExempt(l.sku)) continue; // preorder / backorder
646
+ var res = await catalog.inventory.hold(l.sku, l.qty);
647
+ if (res == null) continue; // un-tracked SKU — unlimited
648
+ if (res.held) { l._held_qty = l.qty; placed.push({ sku: l.sku, qty: l.qty }); continue; }
649
+ // Insufficient stock for this line — roll back the pass and refuse.
650
+ await _releaseStockHolds(placed);
651
+ var title = l.title || l.sku;
652
+ var refused = new Error("checkout: " + title + " — only a limited quantity is in stock. " +
653
+ "Lower the quantity or remove it to continue.");
654
+ refused.code = "INSUFFICIENT_STOCK";
655
+ refused.sku = l.sku;
656
+ throw refused;
657
+ }
658
+ return placed;
659
+ }
660
+
661
+ // Best-effort release of a set of placed holds (the rollback path).
662
+ // Drop-silent per hold: a release failure must not mask the original
663
+ // error that triggered the rollback, and the TTL-free holds here are
664
+ // only ever consumed by the paid decrement or cleared by a cancel, so
665
+ // a missed release self-heals when the abandoned pending order is later
666
+ // cancelled / expired.
667
+ async function _releaseStockHolds(holds) {
668
+ if (!Array.isArray(holds)) return;
669
+ for (var i = 0; i < holds.length; i += 1) {
670
+ try { await catalog.inventory.release(holds[i].sku, holds[i].qty); }
671
+ catch (_e) { /* drop-silent — rollback best-effort */ }
672
+ }
673
+ }
674
+
590
675
  // Compose a quote from a cart + ship-to + (optional) selected
591
676
  // shipping service. Pure read — no DB writes.
592
677
  async function _buildQuote(input) {
@@ -726,10 +811,39 @@ function create(deps) {
726
811
  throw new TypeError("checkout.confirm: grand_total_minor must be > 0 (zero-total orders use a separate freebie flow)");
727
812
  }
728
813
 
729
- // Resolve an optional gift-card credit BEFORE any charge so a
730
- // bad code fails the checkout without touching Stripe. The
731
- // credit reduces the amount due; the order still records the
732
- // full grand total it owed.
814
+ // Reserve stock for every shippable, non-exempt line BEFORE any
815
+ // charge. Insufficient stock throws a coded INSUFFICIENT_STOCK error
816
+ // here (no PaymentIntent, no order) which the storefront re-renders
817
+ // inline. The holds placed here ride into the pending order and are
818
+ // converted to a real shelf debit on the paid transition (or released
819
+ // when the order is cancelled / expires). Everything AFTER this point
820
+ // runs inside a guard that releases the holds if a later step throws
821
+ // before the order is committed, so a refused gift-card / payment
822
+ // error never strands held stock.
823
+ var stockHolds = await _placeStockHolds(quote.lines);
824
+ try {
825
+ return await this._confirmAfterHolds(input, quote, email, stockHolds);
826
+ } catch (e) {
827
+ await _releaseStockHolds(stockHolds);
828
+ throw e;
829
+ }
830
+ },
831
+
832
+ // The body of confirm() once stock is held. Split out so the holds
833
+ // placed in confirm() release on any throw from here down via the
834
+ // single try/catch above — the two return paths (fully-credited and
835
+ // Stripe-intent) both live inside that guard. Internal — invoked only
836
+ // through confirm() above (hence the `_` prefix); `stockHolds` is the
837
+ // list of placed holds, which both terminal paths leave in place (the
838
+ // pending order owns them until paid / cancelled).
839
+ _confirmAfterHolds: async function (input, quote, email, stockHolds) {
840
+ // Already validated in confirm() above; re-read here since the PI
841
+ // creation moved into this split-out body.
842
+ var idempotencyKey = input.idempotency_key;
843
+ // Resolve an optional gift-card credit BEFORE any charge so a bad
844
+ // code fails the checkout without touching Stripe. The credit
845
+ // reduces the amount due; the order still records the full grand
846
+ // total it owed.
733
847
  var gc = await _resolveGiftCard(input.gift_card_code, quote);
734
848
  // Loyalty points credit stacks on top of any gift-card credit —
735
849
  // both reduce the same amount due. The loyalty credit is capped
@@ -760,6 +874,9 @@ function create(deps) {
760
874
  qty: l.qty,
761
875
  unit_amount_minor: l.unit_amount_minor,
762
876
  unit_currency: l.unit_currency,
877
+ // Units this line reserved at confirm (0 unless a hold landed) so
878
+ // the order's paid/cancel transitions settle the exact hold.
879
+ stock_held_qty: l._held_qty || 0,
763
880
  };
764
881
  });
765
882
  // Reuse the cart row already fetched for the loyalty
@@ -968,6 +1085,13 @@ function create(deps) {
968
1085
  if (quote.totals.grand_total_minor <= 0) {
969
1086
  throw new TypeError("checkout.createPaypalOrder: grand_total_minor must be > 0");
970
1087
  }
1088
+ // Reserve stock before opening the PayPal order — same atomic holds
1089
+ // the Stripe confirm places, so the two payment paths can't oversell
1090
+ // against each other. Insufficient stock throws INSUFFICIENT_STOCK
1091
+ // here (no PayPal order created). Released on any throw before the
1092
+ // local order row commits.
1093
+ var ppHolds = await _placeStockHolds(quote.lines);
1094
+ try {
971
1095
  // Resolve an optional gift-card credit before opening the PayPal
972
1096
  // order so a bad code fails without a remote round-trip.
973
1097
  var gc = await _resolveGiftCard(input.gift_card_code, quote);
@@ -975,7 +1099,7 @@ function create(deps) {
975
1099
  var cartRow = await cart.get(quote.cart_id);
976
1100
  var emailHash = customers ? customers.hashEmail(email) : null;
977
1101
  var ppLines = quote.lines.map(function (l) {
978
- return { variant_id: l.variant_id, sku: l.sku, qty: l.qty, unit_amount_minor: l.unit_amount_minor, unit_currency: l.unit_currency };
1102
+ return { variant_id: l.variant_id, sku: l.sku, qty: l.qty, unit_amount_minor: l.unit_amount_minor, unit_currency: l.unit_currency, stock_held_qty: l._held_qty || 0 };
979
1103
  });
980
1104
 
981
1105
  // Gift card fully covers the order — no PayPal order (PayPal
@@ -1028,6 +1152,12 @@ function create(deps) {
1028
1152
  if (gc) await _redeemGiftCard(gc, createdOrder.id);
1029
1153
  await cart.setStatus(quote.cart_id, "converted");
1030
1154
  return { order: createdOrder, paypal_order_id: ppOrder.id, status: ppOrder.status, gift_card: gc ? { applied_minor: gc.applied_minor, amount_due_minor: amountDue } : null };
1155
+ } catch (e) {
1156
+ // Any throw before the order row commits (PayPal open failure,
1157
+ // gift-card error) releases the holds so PayPal can't strand stock.
1158
+ await _releaseStockHolds(ppHolds);
1159
+ throw e;
1160
+ }
1031
1161
  },
1032
1162
 
1033
1163
  // Capture an approved PayPal order, then advance the local order to paid.
package/lib/order.js CHANGED
@@ -128,6 +128,34 @@ function _shipTo(s) {
128
128
 
129
129
  function _now() { return Date.now(); }
130
130
 
131
+ // Read the per-SKU stock-hold map an order recorded at creation time. It
132
+ // lives in the `__init__` transition's metadata (`{ stock_holds: { sku:
133
+ // qty } }`), written by createFromCart when the checkout reserved shelf
134
+ // units. Returns `{}` for an order that held nothing (digital-only, an
135
+ // inventory-less deploy, or an order created before this was wired) so the
136
+ // settlement loop is a clean no-op. Defensive against a missing /
137
+ // malformed metadata blob — a parse failure yields no holds rather than a
138
+ // throw that would break a legitimate state transition.
139
+ function _stockHoldMap(order) {
140
+ if (!order || !Array.isArray(order.transitions)) return {};
141
+ var init = null;
142
+ for (var i = 0; i < order.transitions.length; i += 1) {
143
+ if (order.transitions[i].from_state === "__init__") { init = order.transitions[i]; break; }
144
+ }
145
+ if (!init || !init.metadata_json) return {};
146
+ var parsed;
147
+ try { parsed = JSON.parse(init.metadata_json); }
148
+ catch (_e) { return {}; }
149
+ if (!parsed || typeof parsed.stock_holds !== "object" || !parsed.stock_holds) return {};
150
+ var out = {};
151
+ var skus = Object.keys(parsed.stock_holds);
152
+ for (var s = 0; s < skus.length; s += 1) {
153
+ var q = Number(parsed.stock_holds[skus[s]]);
154
+ if (Number.isInteger(q) && q > 0) out[skus[s]] = q;
155
+ }
156
+ return out;
157
+ }
158
+
131
159
  // ---- factory ------------------------------------------------------------
132
160
 
133
161
  function create(opts) {
@@ -162,6 +190,25 @@ function create(opts) {
162
190
  // fire-and-forget on the same detached-promise discipline as the
163
191
  // loyalty fan-out: the transition has already persisted.
164
192
  var referrals = opts.referrals || null;
193
+ // Optional inventory handle — when present, the order FSM converts the
194
+ // confirm-time stock holds into real shelf movements as the order
195
+ // changes state. On `mark_paid` (pending → paid) each shippable line's
196
+ // held units are debited from on_hand via `inventory.decrement`; on
197
+ // `cancel` FROM PENDING (pending → cancelled — a never-paid order that
198
+ // timed out or the buyer abandoned) each line's hold is released via
199
+ // `inventory.release`. Both run SYNCHRONOUSLY inside the transition,
200
+ // before the fire-and-forget fan-outs, because stock truth is not
201
+ // best-effort: a paid order MUST debit the shelf and a cancelled
202
+ // pending order MUST free its hold. Both verbs are idempotent and
203
+ // self-targeting — `decrement` matches only lines that still hold the
204
+ // qty (so a re-delivered mark_paid is a no-op and an exempt / un-tracked
205
+ // line is skipped), and `release` only clears an active hold. Refund
206
+ // (paid → refunded) and cancel-after-paid (paid → cancelled) DO NOT
207
+ // touch inventory: a returned item is not automatically back on the
208
+ // shelf — the operator restocks via the admin inventory console once
209
+ // the physical return is inspected. Opt-in like the other handles so
210
+ // tests and an inventory-less deploy run unchanged.
211
+ var inventory = opts.inventory || null;
165
212
  // Pagination cursors for listForCustomer are HMAC-tagged via
166
213
  // b.pagination so an operator can't hand-craft one to skip past a
167
214
  // hidden order or replay across deployments. The secret defaults
@@ -215,10 +262,22 @@ function create(opts) {
215
262
  input.customer_email_hash || null, ts,
216
263
  ],
217
264
  );
265
+ // Accumulate the per-SKU stock-hold map as we write the lines. The
266
+ // checkout passes `stock_held_qty` on every line that reserved shelf
267
+ // units at confirm; lines that held nothing (digital / preorder /
268
+ // backorder / un-tracked SKU) contribute 0. The map is stamped onto
269
+ // the init-transition metadata below so the paid-time decrement and
270
+ // the cancel-time release settle exactly the units THIS order held —
271
+ // no schema column needed, and a cancel can never release stock that
272
+ // belongs to another shopper's hold on the same SKU.
273
+ var heldBySku = {};
218
274
  for (var i = 0; i < input.lines.length; i += 1) {
219
275
  var l = input.lines[i];
220
276
  _positiveInt(l.qty, "lines[" + i + "].qty");
221
277
  _nonNegInt(l.unit_amount_minor, "lines[" + i + "].unit_amount_minor");
278
+ var heldQty = l.stock_held_qty == null ? 0 : l.stock_held_qty;
279
+ _nonNegInt(heldQty, "lines[" + i + "].stock_held_qty");
280
+ if (heldQty > 0) heldBySku[l.sku] = (heldBySku[l.sku] || 0) + heldQty;
222
281
  await query(
223
282
  "INSERT INTO order_lines (id, order_id, variant_id, sku, qty, " +
224
283
  "unit_amount_minor, unit_currency, line_total_minor) " +
@@ -230,11 +289,14 @@ function create(opts) {
230
289
  ],
231
290
  );
232
291
  }
233
- // Initial transition row — from no-prior-state into pending.
292
+ // Initial transition row — from no-prior-state into pending. Its
293
+ // metadata carries the stock-hold map (`{ stock_holds: { sku: qty } }`)
294
+ // so the FSM can settle the holds without a dedicated column.
295
+ var initMeta = Object.keys(heldBySku).length ? JSON.stringify({ stock_holds: heldBySku }) : "{}";
234
296
  await query(
235
297
  "INSERT INTO order_transitions (id, order_id, from_state, to_state, on_event, reason, metadata_json, occurred_at) " +
236
- "VALUES (?1, ?2, '__init__', 'pending', 'create', ?3, '{}', ?4)",
237
- [b.uuid.v7(), id, input.reason || null, ts],
298
+ "VALUES (?1, ?2, '__init__', 'pending', 'create', ?3, ?5, ?4)",
299
+ [b.uuid.v7(), id, input.reason || null, ts, initMeta],
238
300
  );
239
301
  return await this.get(id);
240
302
  },
@@ -301,6 +363,41 @@ function create(opts) {
301
363
  ],
302
364
  );
303
365
  var refreshed = await this.get(orderId);
366
+ // Inventory settlement — SYNCHRONOUS, before the fire-and-forget
367
+ // fan-outs below. Stock truth is not best-effort: a paid order debits
368
+ // the shelf, a cancelled-while-pending order frees its hold. The
369
+ // edge (result.from → result.to) is authoritative, so this runs once
370
+ // per real state change — a re-delivered webhook is collapsed to a
371
+ // no-op transition upstream (the FSM refuses a second mark_paid from
372
+ // `paid`), and the underlying verbs are idempotent regardless. Only
373
+ // the two edges that own a hold act; refund and cancel-after-paid are
374
+ // deliberately inert (the operator restocks a physical return by hand).
375
+ if (inventory) {
376
+ var holdMap = _stockHoldMap(refreshed);
377
+ var holdSkus = Object.keys(holdMap);
378
+ if (holdSkus.length) {
379
+ if (result.from === "pending" && result.to === "paid"
380
+ && typeof inventory.decrement === "function") {
381
+ // Convert each held SKU's reservation into a real shelf debit,
382
+ // scoped to the exact units this order held. decrement's own
383
+ // guard (stock_held >= qty) makes a re-delivered mark_paid a
384
+ // no-op, so this is idempotent across webhook re-deliveries.
385
+ for (var di = 0; di < holdSkus.length; di += 1) {
386
+ await inventory.decrement(holdSkus[di], holdMap[holdSkus[di]]);
387
+ }
388
+ } else if (result.from === "pending" && result.to === "cancelled"
389
+ && typeof inventory.release === "function") {
390
+ // Free the holds of a pending order that never paid (timed out,
391
+ // payment_intent.canceled, or an explicit cancel), scoped to the
392
+ // exact units this order held so a cancel can never release stock
393
+ // another shopper holds on the same SKU. release floors at zero
394
+ // so a double-cancel can't underflow stock_held.
395
+ for (var ri = 0; ri < holdSkus.length; ri += 1) {
396
+ await inventory.release(holdSkus[ri], holdMap[holdSkus[ri]]);
397
+ }
398
+ }
399
+ }
400
+ }
304
401
  // Fan-out to merchant webhook subscribers is fire-and-forget. The
305
402
  // transition has already persisted; the request must not wait on
306
403
  // outbound HTTP, or a slow / unreachable endpoint would block the
package/lib/storefront.js CHANGED
@@ -12869,11 +12869,15 @@ function mount(router, deps) {
12869
12869
  // fat-fingered value re-prompts rather than 500-ing checkout.
12870
12870
  var code = (e && typeof e.code === "string") ? e.code : "";
12871
12871
  var msg = (e && e.message) || "checkout failed";
12872
- // A coded gift-card / loyalty error is something the shopper can
12873
- // fix in place — re-render the checkout form with the message
12874
- // inline (preserving the cart + their prefilled fields where
12872
+ // A coded gift-card / loyalty / out-of-stock error is something the
12873
+ // shopper can fix in place — re-render the checkout form with the
12874
+ // message inline (preserving the cart + their prefilled fields where
12875
12875
  // possible) rather than dead-ending on a separate page.
12876
- if (code.indexOf("GIFTCARD_") === 0 || code.indexOf("LOYALTY_") === 0) {
12876
+ // INSUFFICIENT_STOCK carries a friendly per-line message and means
12877
+ // the buyer must lower a quantity or drop a line; nothing was
12878
+ // charged and any holds placed mid-confirm were already released.
12879
+ if (code.indexOf("GIFTCARD_") === 0 || code.indexOf("LOYALTY_") === 0 ||
12880
+ code === "INSUFFICIENT_STOCK") {
12877
12881
  try {
12878
12882
  var coLines = await _repriceCartLines(await deps.cart.listLines(c.id));
12879
12883
  if (coLines.length) {
@@ -12999,7 +13003,14 @@ function mount(router, deps) {
12999
13003
  // The PayPal JS SDK's createOrder expects `{ id }`.
13000
13004
  return _json(200, { id: created.paypal_order_id, order_id: created.order.id });
13001
13005
  } catch (e) {
13002
- var gcErr = e && typeof e.code === "string" && e.code.indexOf("GIFTCARD_") === 0;
13006
+ var ecode = (e && typeof e.code === "string") ? e.code : "";
13007
+ var gcErr = ecode.indexOf("GIFTCARD_") === 0;
13008
+ // Out-of-stock is a 409 (conflict) carrying the friendly per-line
13009
+ // message so the PayPal button surfaces it; nothing was charged
13010
+ // and the mid-confirm holds were already released.
13011
+ if (ecode === "INSUFFICIENT_STOCK") {
13012
+ return _json(409, { error: (e && e.message) || "out-of-stock", code: ecode });
13013
+ }
13003
13014
  return _json((e instanceof TypeError || gcErr) ? 400 : 502, { error: (e && e.message) || "paypal-create-failed" });
13004
13015
  }
13005
13016
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blamejs/blamejs-shop",
3
- "version": "0.3.76",
3
+ "version": "0.4.0",
4
4
  "description": "Open-source framework built on blamejs. Vendored stack, zero npm runtime deps, PQC-first crypto, security-on by default.",
5
5
  "main": "lib/index.js",
6
6
  "scripts": {