fix(core): money & inventory integrity hardening — server-authoritative pricing, atomic writes, ledger discipline - #90
Merged
Conversation
Every fix in this change was first proven red on real D1 (miniflare + real migrations, no mocks for the flows), then fixed and locked with a regression test at the same seam. Storefront / pricing - Server-authoritative pricing: createStoreOrder resolves unit prices from the catalog (product row / variant rows) instead of trusting the client-sent pricePerUnit; order price = true sum of line totals. A forged 1 DZD price no longer propagates into codAmount, customer totalSpent, or driver pendingCash. - Delivery availability is enforced: a wilaya with no rule under the default profile (or a disabled delivery type) refuses the order with DELIVERY_NOT_AVAILABLE before the customer row is created, instead of silently charging 0. Orders / stock - createOrder deducts stock via guarded subselect ledger writes inside the atomic batch: insufficient stock rolls back the whole order (no silent floor-at-zero), and concurrent orders can no longer double-sell the last unit (proven: two racing qty-1 orders → exactly one commits). - deleteOrder reverses driver credit (totalDelivered, totalEarnings, pendingCash) for unsettled delivered orders; settled orders keep counters so append-only payment history stays reconciled. - deleteOrder skips the totalSpent decrement when cancel/return already rolled the spend back (cancel + delete no longer double-decrements). - syncOrderAfterCarrierUpdate recomputes codAmount = price + deliveryFee so settlement follows carrier amount updates. Drivers - createDriverPayment settles in one atomic batch (payment row, order links, driver counters) — a mid-sequence failure can no longer leave settled orders with inflated pendingCash and no retry path. - getDriverById now reports cashReconciliation: pendingCash vs the real sum of delivered-unsettled orders, with drift surfaced in the dashboard DriverDetail (warning alert, ar/en/fr). Stock / ledger discipline - Catalog inventory edits write movements: updateProduct and updateVariant log ADJUSTMENT_ADD/REMOVE with true deltas, batched with the write; createVariant logs opening stock; deleteVariant relies on the variant FK cascade so the ledger sum stays reconciled. - adjustStock validates movement-type/delta sign coherence, keeps the friendly INSUFFICIENT_STOCK 422, and applies the change as a guarded atomic batch (movement + inventory update) — no lost deltas, no ledger divergence. Errors - Unknown errors return a clean envelope: "An unexpected error occurred" + requestId in context for log correlation. The [variable] redaction soup is gone. Tests - New real-D1 suites: money-integrity-probes, orders.delete-e2e, orders.stock-lifecycle-e2e, flagged-fixes (39 tests over the seams above, including fault-injection atomicity probes). - All e2e files batch migrations through d1.batch — cuts the Miniflare proxy fetch storm that exhausted loopback ports and flaked the suite. Verified: cod-server 117 files / 1705 tests green, typecheck clean; cod-client-astro typecheck + 142 tests green.
5 tasks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
A probe-first audit of every money and inventory path in the platform. Each issue was proven red on real D1 (Miniflare + real migrations, no mocks for the flows) before fixing, and each fix is locked by a regression test at the same seam.
Fixed issues
🔴 Storefront pricing & delivery
price,codAmount, customertotalSpent, driverpendingCashcreateStoreOrderresolves prices server-side from the catalog (product row / variant rows); order price = true Σ line totals;pricePerUnitis display-onlygetDeliveryFeereturned 0 for uncovered wilayanull→ handler refuses withDELIVERY_NOT_AVAILABLE(422) before creating the customer row🔴 Orders / stock
inventory >= qtyWHERE → exactly one order commits (proven with racing pair)company_api_logs/webhook_eventsFKs after committing partial statetotalSpentdeleteOrderskips the spend rollback for orders whose spend cancel/return already rolled backpendingCash/totalEarnings/totalDeliveredstayed inflated forevercodAmountafter carrier amount updatesyncOrderAfterCarrierUpdaterecomputescodAmount = price + deliveryFee🟠 Drivers & stock ledger
pendingCash, retry blocked by settled guardcreateDriverPayment= onedb.batch(payment + links + counters)getDriverByIdreportscashReconciliation(pendingCash vs real unsettled-orders sum); dashboard DriverDetail shows a warning alert when drift ≠ 0 (ar/en/fr)updateProduct/updateVariantlogADJUSTMENT_*movements with true deltas (atomic);createVariantlogs opening stock;deleteVariantfollows the FK cascade so Σ(movements) stays reconciledadjustStockrace + lying labelsADJUSTMENT_ADDaccepted negative deltainventory + delta >= 0WHERE)Errors
"An unexpected error occurred"+requestIdin context for log correlation. The[variable]-redaction message soup is gone (that was this bug's original symptom report).Test plan
money-integrity-probes(6),orders.delete-e2e(2),orders.stock-lifecycle-e2e(14),flagged-fixes(18) — includes fault-injection atomicity probes and racing-order probestsc --noEmitcleand1.batch— fixes the Miniflare loopback-port exhaustion that flaked the full suiteNotes
store/CONTEXT.md,stock/CONTEXT.md) updated: Client-Supplied Price → Server-Authoritative Pricing; delivery availability is server-enforced; catalog-edit ledger discipline.