Skip to content

fix(core): keep live stock in plugin storage on EmDash 1.6 - #151

Open
cavewebs wants to merge 2 commits into
mainfrom
cursor/stock-draft-staging-7b96
Open

cavewebs wants to merge 2 commits into
mainfrom
cursor/stock-draft-staging-7b96

Conversation

@cavewebs

@cavewebs cavewebs commented Dec 3, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #141.

Rebased onto current main (keeps signed download links in paid receipts from #145).

Root cause

On EmDash 1.6, plugin content.update on a revisioned collection (products) goes through updateDraftAware. That writes a draft and leaves the published row unchanged. Checkout and cart read content.get, so paid orders never lowered live stock. Each sale also left a stock-only draft; publishing it later could roll the count backwards. Variant stock was a read-then-write on product_variants, so two concurrent sales could overwrite each other.

EmDash 0.37 and 1.1-1.5 expose the same content.update shape. None of 0.37 or 1.1-1.6 provide a plugin API that writes live published fields without _rev / publish.

Fix

Live on-hand now lives in an additive stock_levels plugin collection (p:{productId} / v:{variantId}).

  • Published stock_quantity / variant stockQuantity is the merchant-set baseline. A row is created on first movement. Publishing a new content value resets the row, and that reset is stored so publishing 25 then 24 cannot bring back 23.
  • A write carrying an older content stamp cannot replace a newer baseline. It applies its delta to the current row instead.
  • Decrement, refund restock, and paid-order cancel write that collection. They do not call content.update.
  • Writes use updateIf or compareAndSet when the host provides them, and fall back to put on EmDash 0.37.
  • Restore puts back only units the ledger shows this order still has out. A second decrement for the same order line is a no-op.
  • A full remaining-balance refund with Restock restores the order's units. A partial refund without line quantities leaves stock unchanged. If that refund later fails, the restock is taken back from the ledger.
  • Cart, checkout, the low-stock widget, and add-to-cart read live on-hand. GET /stock?ids= is the storefront lookup.
  • A paid order that oversells stays on-hold (including through a partial refund) and does not get download grants. Moving it to processing retries the remaining debit after replenishment.
  • If the checkout draft write fails after the stock lock, the lock is released.

Existing shops pick this up on the next sale. No migration. Stock-only drafts already staged by 0.5.0 still exist; publishing one still resets live stock to that draft's number, so those drafts should be discarded.

Behaviour by EmDash line

  • 1.6: sales no longer stage drafts; live stock moves.
  • 1.1-1.5: same storage path. Concurrent writes use compare-and-set when present.
  • 0.37: same storage path with put fallback (last write can still race).

Tests

Core suite: 455 pass. bun run typecheck clean. Covers draft-staging (fail before, pass after), stale baseline overwrite, 25-then-24 reset, partial vs full restock, failed-refund reversal from the ledger, draft-write lock release, oversold hold, and staff retry after replenishment.

Open in Web Open in Cursor 

@moset15

moset15 commented Dec 6, 2026

Copy link
Copy Markdown
Contributor

Thanks for taking this on. It replaces the stock PR I'd planned for #141, so I've reviewed this one instead of opening a second. Core tests and typecheck pass on 05baf2f. GitHub shows a conflict with main in orders/create.ts.

I tested it on a shop running EmDash 1.6 with Paystack in test mode:

  • The fix works. A paid order for 2 lowered live stock from 25 to 23. The product got no new draft or revision, and the ledger shows −2.
  • The cart limit works. Asking for 30 answered "only 25 available".
  • Points 2 and 3 below, and two of the smaller ones (the sold-out button and old drafts), showed up on the same shop.

Four things I think need a change before it lands:

  1. A sale that read the old baseline overwrites a new one (inventory/stock.ts:179). attemptAdjust starts from input.baseline whenever it differs from the row's, without checking which is newer. Live 3 on baseline 10; the merchant publishes 20; sale B reads 20 and writes 19; sale A had read the content before the publish, so it writes baseline 10, live 9. Readers then see 20 (the content value) instead of 18, and the shop can oversell. Keeping the newest baseline seen (or a content revision) on the row, and refusing a write with an older one, would close it.
  2. Publishing the same number doesn't reset (stock.ts:83). The reset only happens when the content value changes. Sell 10 down to 3, recount, publish 10 again: live stays 3. On the test shop, with 24 published and live at 23 after a sale, a recount of 24 left nothing to publish. Publishing 25 reset live to 25, but publishing 24 again brought back 23, because the row's baseline was still 24. A merchant correcting stock after a count can't.
  3. A partial refund with Restock puts the whole order back (orders/refund.ts:294). The admin refund form never sends lineItemRefunds, so the new else branch restocks every line whatever the amount. On the test shop, a KSh 100 refund with Restock on the 2-mug order moved live stock from 23 back to 25. Before this PR that path restocked nothing, which was its own bug, but this one oversells. Restocking all lines only on a full refund, or asking for quantities in the form, would fix it.
  4. A refund that fails later keeps that stock (refund.ts:540). reverseFailedRefund returns early without lineItemRefunds, so a pending refund that later fails (Paystack and M-PESA refunds often are pending first) leaves the units from point 3 counted twice.

Against the cases @alexasomba listed on #141:

Case This PR
A failed draft write releases the stock lock Not covered: checkout.ts creates the lock, then writes the draft, with nothing releasing it if that throws (#146 has a test for this).
A paid order after a sell-out stays on hold In the code (orders/create.ts, with downloads withheld), but no test.
A partial refund keeps that hold Not covered: orders/status.ts turns any partial refund into partially-refunded.
Restock only units the order debited Covered (restores only units the order actually debited).
A staff retry after replenishment Not covered: moving the order off hold never debits the oversold lines.

Smaller ones, fine as follow-ups:

  • One 409 insufficient_stock sets the add-to-cart button to "Sold out" until reload (AddToCartIsland.tsx). On the test shop, after "only 25 available" the button stayed disabled when I lowered the quantity to 2.
  • The product page, its JSON-LD and ProductCard still read stock_status, so a sold-out product stays InStock.
  • Shops on 0.5.0 already have stock-only drafts. Nothing in the admin warns about them, and publishing a product that carries one resets live stock to the old lowered number. On the test shop the editor opened the old draft showing 24 while live stock was 25, and publishing it set live stock to 24.

Not tested by hand: points 1 and 4, and the oversell hold, which need concurrent sales or a failed refund. I'll test the next head on the same shop and report back here.

cursoragent and others added 2 commits December 6, 2026 00:16
Plugin content.update on a revisioned products collection stages a
draft and leaves the published row unchanged, so sales never lowered
what checkout reads. Live on-hand now lives in stock_levels. The
published stock_quantity is the merchant baseline. Decrement, refund,
and cancel restock write that collection with compare-and-set when
the host provides it.

Co-authored-by: Timchosen Uzua <timchosen@gmail.com>
A sale that still holds an older published stamp no longer overwrites a
newer baseline. Publishing a new stock number stores the reset, so
toggling back cannot revive the old on-hand. Partial refunds with
Restock and no line list leave stock alone; a full refund still
restores. A later failed refund takes that restock back from the
ledger. Draft-write failures release the checkout lock. Oversold paid
orders stay on hold through a partial refund, and moving them to
processing retries the remaining debit.

Co-authored-by: Timchosen Uzua <timchosen@gmail.com>
@cursor
cursor Bot force-pushed the cursor/stock-draft-staging-7b96 branch from 05baf2f to c356de1 Compare December 6, 2026 00:20
@cursor

cursor Bot commented Dec 6, 2026

Copy link
Copy Markdown

Addressed the four blockers on c356de1, rebased onto current main.

  1. Stale baseline. attemptAdjust keeps the newer baselineAt. A sale that still holds the old published stamp applies its delta to the current row instead of writing the old quantity back.
  2. Publish 25 then 24. Observing a published quantity that differs from the row persists the reset, so toggling back cannot revive the previous on-hand. A same-number publish that EmDash treats as a no-op still cannot reset (nothing new is stored). Changing the number, then setting the count, does.
  3. Partial Restock. With no lineItemRefunds, only a full remaining-balance refund restores units. A partial refund leaves stock alone.
  4. Later failed refund. reverseFailedRefund takes restock back from ledger rows for that refund id, so a full restock with no line list still reverses.

Also: draft-write failure releases the lock; oversold paid orders stay on-hold through a partial refund; moving on-hold to processing retries remaining debit (409 if still short); insufficient_stock only marks the button sold-out when available === 0.

Core tests 455 pass, typecheck clean. Left the 0.5.0 stock-only draft warning and JSON-LD stock_status as follow-ups. Ready for another pass on the same shop.

@moset15

moset15 commented Dec 6, 2026

Copy link
Copy Markdown
Contributor

Re-tested c356de1 on the same EmDash 1.6 shop as before (Paystack test mode, the enamel mug at 24). Thanks for the quick turnaround: three of the four points are fixed by hand.

Fixed

  • Partial refund with Restock. KSh 100 off a one-unit order with Restock ticked: stock stayed at 24, and a warning was logged.
  • "Sold out" button. Asking for 30 against 24 shows "only 24 available", and the button stays "Add to cart".
  • Republish with a stock read in between. Publish 25, open the product, publish 24: live stock is 24 (it was 23 before).
  • Core tests: 455 pass and the typecheck is clean.

Still open: republish with no read in between

Starting from published 24 with 23 on hand, publish 25 and then 24 again, with no storefront or admin read of stock in between. Live stock comes back as 23.

observePublishedQuantity only runs when something reads stock, so a quick correction (25 typed by mistake, put back to 24) on a quiet shop brings the old on-hand back. The new test reads between the two publishes (liveOnHand(ctx, "p1", 25)), so it doesn't cover this path.

Suggestion: also observe on publish. EmDash 1.6 has a content:afterPublish hook. Calling observePublishedQuantity there for products (and on variant saves) would record the reset when it happens, not on the next read.

Two smaller points

  • The refund above is stored with restocked: true, though nothing went back. It does no harm today (the failed-refund reversal works from the ledger, and the admin doesn't show the flag), but the stored data is wrong. The merchant also gets no message that Restock was ignored. Perhaps set restocked only when units actually go back, and either return a note the admin can show or disable the checkbox for partial refunds.
  • observePublishedQuantity resets on any baseline difference, with no stamp check, and it now runs on every stock read. A reader holding an older copy of the product (a D1 read replica, for example) would reset on-hand to the old number. Comparing baselineAt there, as attemptAdjust now does, would close that.

Not re-tested by hand: the stale-baseline sale race and the failed-refund reversal. Both have new tests, and the code reads right.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Stock never goes down on EmDash 1.6 (plugin content updates stage a draft)

3 participants