@blamejs/blamejs-shop 0.4.65 → 0.4.66

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
@@ -8,6 +8,8 @@ upgrading across more than a few patches at a time.
8
8
 
9
9
  ## v0.4.x
10
10
 
11
+ - v0.4.66 (2026-06-20) — **Inventory-audit finalization can no longer double-apply its stock adjustments.** Finalizing an inventory audit with apply_adjustments writes one shelf adjustment per counted line, then marks the audit finalized. Two failure modes could move a shelf twice. First, if a later line was refused mid-loop — most commonly a negative variance that would have pushed the shelf below its outstanding paid holds — the audit stayed open, but the lines already adjusted had moved; re-running the finalize re-applied those earlier adjustments on top of themselves. Second, two finalize calls overlapping on the same audit both applied every adjustment before either marked the audit finalized. Finalization now claims the audit's transition to finalized in a single conditional write BEFORE touching any shelf, so exactly one finalize applies the adjustments and a concurrent or duplicate call applies nothing. Each adjustment is applied as the difference between the counted variance and what this audit has already moved, so a retry lands only the not-yet-applied remainder and a recount made before the retry is reflected exactly. A finalize that is refused part-way re-opens the audit so the operator can clear the blocker and retry. No API change. **Fixed:** *Finalization claims the audit before moving any shelf* — The transition that marks an audit finalized now lands in one conditional write, gated on the audit still being open or in progress, BEFORE any stock adjustment is written. Two finalize calls racing the same audit — or a duplicate retry overlapping a still-running finalize — resolve to a single winner that applies the adjustments; the loser writes nothing and returns the computed totals. The claim also freezes the audit's scan lines, so the variances being applied can't change underneath the writer. · *Adjustments reconcile against what already landed* — Each shelf adjustment is applied as the counted variance minus what this audit has already moved for that SKU and location. A finalize refused part-way (a respect-holds floor on one line) re-opens the audit; the retry then applies only the remaining difference instead of re-applying lines that already succeeded, and a recount that changed a line's variance before the retry is corrected to the new value rather than left at the old one.
12
+
11
13
  - v0.4.65 (2026-06-19) — **Dropship-forwarding and scheduled-export status transitions are now claimed atomically.** Closes two status-transition races in modules that validated the transition with the state-machine primitive but then persisted it with an unconditional update keyed only on the row id. Because the state-machine validation runs in process (each request rebuilds the machine from a fresh row), two concurrent transitions on the same row both passed validation and the second write silently clobbered the first — for example a dropship forwarding being marked shipped while a retry marks it failed, or a scheduled export being cancelled while a worker marks it running. Both now gate the write on the row still being in the state that was validated against (the same single-statement compare-and-swap the order and inventory-receipt lifecycles already use), so exactly one transition lands and a concurrent loser is refused rather than overwriting it. No API change. **Fixed:** *Dropship-forwarding transitions claim the from-state* — Every dropship-forwarding lifecycle edge routes through one helper that validated the transition against the state machine and then wrote UPDATE … WHERE id = ?. The write now also requires the row to still be in the state the transition was validated against (… AND status = <from>) and treats a zero-row result as a lost race (a typed refusal), so two concurrent vendor callbacks (e.g. accept racing ship, or a retry) can't both advance the row and silently overwrite each other. · *Scheduled-export status writers claim the from-state* — The four scheduled-export transitions (cancel, mark-running, mark-complete, mark-failed) validated against the export state machine and then wrote keyed only on the export id. Each now gates the write on the observed from-state and refuses on a zero-row result, so a cancel racing a mark-running (or a duplicate worker callback) no longer last-writer-wins into an illegal state. The state machine still enforces the legal-edge validation; the conditional update is the atomic claim.
12
14
 
13
15
  - v0.4.64 (2026-06-19) — **A failed side-effect can no longer strand a claimed record.** Hardens the atomic-claim concurrency fixes (shipped over the previous releases) against the case where the side-effect fails or the worker crashes AFTER a record was claimed. Each claim now restores or recovers the record so a transient failure can't leave it permanently stuck. A scheduled payment retry that is claimed out of the due set but then fails to advance (a malformed policy or a database write error) restores its next-retry time, so the retry isn't silently dropped. Approving a seller application that crashes between claiming the approval and persisting the vendor is now recoverable — an application left approved with no vendor can be approved again rather than being stranded in a terminal state. A survey response whose insert fails after the invitation was claimed reverts the invitation to issued so it can be answered. A reorder reminder or wishlist digest whose send fails defers the retry to a later tick on a distinct cursor, so a concurrent overlapping tick can't pick up the rolled-back row and send a duplicate in the same window. No API change. **Fixed:** *Payment retry restores its schedule on a failed advance* — The retry scheduler claims an enrollment out of the due set by clearing its next-retry time before doing processor work. If advancing the enrollment then throws (a malformed retry policy, or a database write failure while recording the attempt), the next-retry time is restored to the value the tick observed, so a later tick re-attempts the retry. Previously the enrollment was left active with no next-retry time, and the due query (which requires a next-retry time) would never pick it up again, silently stopping the customer's recovery retries. · *Seller approval is recoverable after a mid-approval crash* — Approving a seller application claims the in-review-to-approved transition before registering the vendor. If the worker crashes or times out between the claim and persisting the vendor, the application is left approved with no vendor — a terminal state the rest of the primitive could never move out of. Approval now treats an approved application that has no vendor attached as re-approvable, so the registration can be retried and the application recovered instead of stranded. · *Survey response keeps the invitation retryable on insert failure* — Submitting a survey response claims the invitation (issued to responded) before inserting the response row. If that insert fails (a transient write error), the invitation is reverted to issued so the response can be submitted again, rather than being stuck responded with no response recorded and every retry rejected as already-responded. · *Reorder reminder and wishlist digest defer a failed send instead of re-firing it* — When a reorder reminder or a wishlist digest send fails after the row was claimed, the schedule cursor is rolled to a value distinct from the one the tick observed (still due, so a later tick retries) rather than back to the exact observed value. A concurrent overlapping tick that read the same cursor was waiting to claim it; restoring the exact value let it match and send a duplicate in the same window. The retry is now deferred to a later tick with no duplicate.
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "0.4.65",
2
+ "version": "0.4.66",
3
3
  "assets": {
4
4
  "css/admin.css": {
5
5
  "integrity": "sha384-imfe0otYErcB8rr2h6KLSGTtStirysptpXETSPY4zLv3bZoIT75Lo1dOvkOav+xL",
@@ -595,9 +595,12 @@ function create(opts) {
595
595
  ", only open or in_progress audits can be finalized");
596
596
  }
597
597
  var lines = await _getLines(auditId);
598
+ // PASS 1 — compute each line's variance, persist it (idempotent),
599
+ // and collect the shelf adjustments to apply. No shelf is touched
600
+ // yet: the atomic claim below decides who, if anyone, applies them.
598
601
  var varianceCount = 0;
599
602
  var varianceValueMinor = 0;
600
- var adjustmentsWritten = 0;
603
+ var adjustable = [];
601
604
  for (var i = 0; i < lines.length; i += 1) {
602
605
  var line = lines[i];
603
606
  // recount_qty wins when present; else counted_qty drives.
@@ -611,36 +614,95 @@ function create(opts) {
611
614
  varianceCount += 1;
612
615
  var unitValue = await _unitValueMinor(line.sku);
613
616
  varianceValueMinor += Math.abs(variance) * unitValue;
614
- if (applyAdjustments) {
615
- // Adjustments only land on lines that carry a
616
- // location_code. A whole-audit-summed line (no
617
- // location_code) computes variance for the operator's
618
- // reconciliation report but does NOT write to
619
- // inventory_locations the catalog-side correction is
620
- // the right verb for the single-bucket inventory.
621
- if (line.location_code) {
622
- await inventoryLocations.adjustStock({
623
- sku: line.sku,
624
- location_code: line.location_code,
625
- delta: variance,
626
- reason: "inventory-audit:" + header.slug,
627
- // A negative variance shrinks the shelf — guard it from
628
- // dropping below the outstanding paid holds for the SKU
629
- // so a later commitHold can't be stranded. Positive
630
- // variances (credits) ignore the flag.
631
- respect_holds: true,
632
- });
633
- adjustmentsWritten += 1;
634
- }
617
+ // Adjustments only land on lines that carry a location_code. A
618
+ // whole-audit-summed line (no location_code) computes variance
619
+ // for the operator's reconciliation report but does NOT write
620
+ // to inventory_locations the catalog-side correction is the
621
+ // right verb for the single-bucket inventory.
622
+ if (applyAdjustments && line.location_code) {
623
+ adjustable.push({ sku: line.sku, location_code: line.location_code, variance: variance });
635
624
  }
636
625
  }
637
626
  }
627
+
638
628
  var ts = _now();
639
- await query(
629
+ // ATOMIC CLAIM — advance the audit out of open/in_progress in a
630
+ // single statement BEFORE any shelf moves. On the D1 bridge there
631
+ // are no interactive transactions, so this UPDATE is the
632
+ // serialization point: two concurrent finalizeAudit calls both
633
+ // reach here, but only one matches a row. The loser changes zero
634
+ // rows, applies NOTHING, and returns the deterministic totals — so
635
+ // a shelf can never be double-adjusted by overlapping finalizes.
636
+ // The flip also freezes the scan lines (recordScanLine / markRecount
637
+ // refuse on a finalized audit), so the variances we're about to
638
+ // apply can't shift underfoot.
639
+ var claim = await query(
640
640
  "UPDATE inventory_audits SET status = 'finalized', variance_count = ?1, " +
641
- "variance_value_minor = ?2, finalized_at = ?3, updated_at = ?3 WHERE id = ?4",
641
+ "variance_value_minor = ?2, finalized_at = ?3, updated_at = ?3 " +
642
+ "WHERE id = ?4 AND status IN ('open', 'in_progress')",
642
643
  [varianceCount, varianceValueMinor, ts, auditId],
643
644
  );
645
+ if (Number(claim.rowCount || 0) !== 1) {
646
+ // Lost the claim — a concurrent (or prior) finalize already
647
+ // advanced this audit and owns the adjustment writes. Touch no
648
+ // shelves; return the totals computed from the now-frozen lines.
649
+ return {
650
+ variance_count: varianceCount,
651
+ variance_value_minor: varianceValueMinor,
652
+ adjustments_written: adjustable.length,
653
+ };
654
+ }
655
+
656
+ // PASS 2 (winner only) — apply each shelf adjustment, reconciling
657
+ // against what already landed under this audit's reason. The audit's
658
+ // slug is unique and (audit_id, sku, location_code) is UNIQUE, so
659
+ // every inventory_adjustments row under (sku, location_code, reason)
660
+ // belongs to this one logical adjustment; their summed delta is what
661
+ // the shelf has already moved. Applying only `variance - applied`
662
+ // makes a retry land exactly the remaining delta and never a double,
663
+ // and self-corrects if a recount changed the variance before the
664
+ // retry. The common abort is a respect_holds floor refusal on a
665
+ // negative variance; the catch re-opens the audit so the operator
666
+ // can clear the blocker and retry.
667
+ var adjustmentsWritten = 0;
668
+ var adjReason = "inventory-audit:" + header.slug;
669
+ try {
670
+ for (var j = 0; j < adjustable.length; j += 1) {
671
+ var adj = adjustable[j];
672
+ var appliedRow = await query(
673
+ "SELECT COALESCE(SUM(delta), 0) AS applied FROM inventory_adjustments " +
674
+ "WHERE sku = ?1 AND location_code = ?2 AND reason = ?3",
675
+ [adj.sku, adj.location_code, adjReason],
676
+ );
677
+ var alreadyApplied = Number((appliedRow.rows[0] || {}).applied || 0);
678
+ var needed = adj.variance - alreadyApplied;
679
+ if (needed !== 0) {
680
+ await inventoryLocations.adjustStock({
681
+ sku: adj.sku,
682
+ location_code: adj.location_code,
683
+ delta: needed,
684
+ reason: adjReason,
685
+ // A negative variance shrinks the shelf — guard it from
686
+ // dropping below the outstanding paid holds for the SKU so a
687
+ // later commitHold can't be stranded. Positive variances
688
+ // (credits) ignore the flag.
689
+ respect_holds: true,
690
+ });
691
+ }
692
+ adjustmentsWritten += 1;
693
+ }
694
+ } catch (applyErr) {
695
+ // Re-open the audit so the operator can clear the blocker and
696
+ // retry. The reconciling apply above guarantees the retry lands
697
+ // only the remaining delta, so nothing double-counts.
698
+ await query(
699
+ "UPDATE inventory_audits SET status = 'in_progress', finalized_at = NULL, " +
700
+ "updated_at = ?1 WHERE id = ?2 AND status = 'finalized'",
701
+ [_now(), auditId],
702
+ );
703
+ throw applyErr;
704
+ }
705
+
644
706
  return {
645
707
  variance_count: varianceCount,
646
708
  variance_value_minor: varianceValueMinor,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blamejs/blamejs-shop",
3
- "version": "0.4.65",
3
+ "version": "0.4.66",
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": {