Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
fix(accounting): purchase price variance double-count — GL and cost subledger now move together (#1117)
Brad Barbin008aaa08e780
diff --git a/.ai/plans/2026-07-10-purchase-cost-layer-gl-consistency.md b/.ai/plans/2026-07-10-purchase-cost-layer-gl-consistency.mdnew file mode 100644index 0000000000..7b2841efe0--- /dev/null+++ b/.ai/plans/2026-07-10-purchase-cost-layer-gl-consistency.md@@ -0,0 +1,765 @@+# Purchase cost-layer / GL consistency (PPV double-count fix) — implementation plan++**Spec:** none (combined diagnose+plan; design decisions resolved below — veto before /execute)+**Research:** `.ai/research/purchase-price-variance-actual-costing.md` (SAP/BC/NetSuite/Odoo/Epicor+survey — validates D1–D3, D7; Odoo 16's correction-SVL redesign is structurally identical to this+plan) + production root-cause session 2026-07-10 (journal JE-2026-07-000001…000009, Acme Inc.+company `8Qft6S8aTR467wJdYNZCtt`)+**Branch:** `fix/purchase-cost-layer-gl-consistency`++## The bug (verified in prod + code)++Buying 2 parts at PO price $60, invoicing at $80, consuming, and selling at $100 (cost $80.25)+produces **net income $0** and **GL Inventory −$20**. The $20 price variance is booked twice:++1. `post-purchase-invoice` posts `Dr PPV $20` to expense (GL), **and simultaneously**+2. creates the item's only cost layer at **full invoice cost** ($80, `remainingQuantity = 2`), so+ every downstream consumption (`calculateCOGS` FIFO) re-expenses the same $20 through+ WIP → FG → COGS while crediting a GL inventory account that only ever received $60.++Root facts (all verified against local `main`):++- `post-receipt/index.ts` **never inserts costLedger rows** (zero hits) — between receipt and+ invoice there are no layers, so FIFO consumption falls back to stale `itemCost.unitCost`+ (`shared/calculate-cogs.ts:105-108`).+- `post-purchase-invoice/index.ts:857-874` inserts the layer **unconditionally** for every+ PO-matched line (even invoice-before-receipt: consumable layer for goods not on hand).+- `post-purchase-invoice/index.ts:994-1010` posts the variance to `purchaseVarianceAccount`+ for the receipt-matched quantity.+- `post-receipt/index.ts:1005-1067` (invoice-first): receipt debits Inventory at **PO cost** and+ expenses `invoiceCost − poCost` to PPV — while the invoice-created layer already carries+ invoice cost. Same double-count, opposite ordering.+- `update-purchased-prices/index.ts:122-152` (source `purchaseOrder`, PO finalize) creates+ **consumable pseudo-layers at PO cost for unreceived goods** (`remainingQuantity` = full qty,+ documentType `'Purchase Order'`). These pollute FIFO whenever the finalize route runs.+- `update-purchased-prices/index.ts:385-390` then overwrites `itemCost.unitCost` with the+ ledger-derived actual cost — the same double-count via the `Average` branch / FIFO fallback.++## Target model (design decisions — pre-resolved, veto here)++**Invariant: the cost subledger (costLedger layers) and the GL inventory account always move+together.** Industry precedent: SAP moving-average stock-coverage split; Business Central+receipt-time value entries. Aligned with `.ai/specs/2026-07-04-inventory-valuation-completeness.md`+decision #11 (layer adjustments are child rows via `appliesToCostLedgerId`, never in-place cost+mutation; `remainingQuantity` stays the only mutable column).++| # | Decision |+|---|----------|+| D1 | **Receipt is the sole creator of purchase cost layers.** `post-receipt` inserts a layer per Inventory-tracked, non-outside-processing line: documentType `'Purchase Receipt'`, cost = the same receipt cost that hits the GL (PO price + weighted shipping), `remainingQuantity` = received qty. Receipt GL entries are unchanged for the receipt-first flow. |+| D2 | **Invoice posting adjusts layers instead of creating them.** For the receipt-matched quantity, split the variance by stock coverage: portion still on hand → `Dr Inventory` (GL) + **adjustment child rows** on the covered layers (subledger); portion already consumed → `Dr PPV`. `Cr AP` at invoice cost, `Dr GR/IR` at receipt cost (unchanged). |+| D3 | **Invoice-before-receipt: no layer at invoice time.** Accrual GL entries only (unchanged). When the receipt later posts, the invoice-first portion books `Dr Inventory` at the **accrual (invoice) unit cost**, credits GR/IR at the same, creates the layer at that cost, and posts **no PPV** (actual cost is known before goods arrive). |+| D4 | **`calculateCOGS` consumes adjustment children alongside their parent layer.** Per unit taken from a layer, take the per-unit bump `child.cost / child.quantity` while `child.remainingQuantity > 0` (children decremented with parents). Base-layer query excludes children and `'Purchase Order'` rows. |+| D5 | **PO-finalize pseudo-layers are neutralized**: inserted with `remainingQuantity: 0` (kept for cost-history UI); existing rows backfilled to 0. |+| D6 | **Negative receipts** consume layers via `calculateCOGS` and post GL at the consumed cost (typical undo case: identical to today's PO-cost behavior). |+| D7 | **Standard-costing items**: variance always → PPV, no layer adjustment (layer keeps its basis; matches valuation-spec decisions #10/#13). Standard costing itself remains unimplemented (separate worktree). |+| D8 | **Legacy self-heal**: if the invoice finds no receipt layers for matched qty (goods received before this fix deployed), it creates the layer itself at `receiptCost + inventoryShare` with coverage measured from itemLedger on-hand, so in-flight documents converge instead of double-counting. |+| D9 | **Existing bad books are NOT auto-corrected.** Follow-up per affected company: single JE `Dr Inventory / Cr PPV` for the double-counted amount (user's prod: $20). |++### Worked scenarios (these are the acceptance numbers)++- **S1 (the user's bug):** receive 2@$30 → layer L1(qty 2, cost 60, rem 2). Invoice 2@$40 →+ coverage 2/2 → `Dr GRNI 60, Dr Inventory 20, Cr AP 80`, child A1(appliesTo L1, qty 2, cost 20,+ rem 2), **no PPV**. Consume 2 → 2×30 + 2×(20/2) = **$80**; GL Inventory nets **0**. Sell $100,+ job labor $0.25 → **net income $20** (was $0), PPV $0.+- **S2 (consumption between receipt and invoice):** receive 2@30; issue 1 (consumes $30);+ invoice 2@40 → coverage 1/2 → `Dr Inventory 10, Dr PPV 10`; child A1(qty 1, cost 10, rem 1).+ Second issue consumes 30 + 10 = $40. GL Inventory ends 0; total expense $80 = actual.+- **S3 (partial invoice):** receive 2@30; invoice 1@40 → matched 1, coverage 1 → `Dr Inventory 10`,+ child(qty 1, cost 10, rem 1), GRNI keeps $30 open. Consume 2 → 40 + 30 = $70 (adjusted unit+ first — FIFO-within-layer convention). Later invoice 1@40 → coverage 0 → `Dr PPV 10`. Total $80 ✓.+- **S4 (invoice-first):** invoice 2@40 → accrual only, **no layer**. Receipt 2 → `Dr Inventory 80 /+ Cr GRNI 80` (clears accrual exactly), layer 2@$40, **no PPV**. Consume 2 → $80 ✓.++### Out of scope (do NOT touch)++- Standard-costing implementation (worktree `standard-costing`), revaluation/LCNRV documents,+ landed-cost documents (all in the inventory-valuation spec).+- BC-style retroactive COGS adjustment for goods already shipped before the invoice arrives+ (consumed-portion variance goes to PPV, not back into posted COGS).+- `Average` costing's intrinsic drift (consumption at `itemCost.unitCost`); D2's GL split still+ applies to Average items using itemLedger on-hand coverage.+- Multi-currency variance separation: when the exchange rate moves between receipt and invoice,+ the FX component currently folds into the price variance (SAP separates these: KDM vs PRD).+ Named follow-up — Task 11 flags it if FX scenarios surface during testing.+- The no-PO direct-invoice branch (`post-purchase-invoice/index.ts:741-854`) — already consistent+ (layer + GL both at invoice cost).+- Production data correction (D9 — manual follow-up JE).+- Xero sync (`.ai/rules/accounting-sync-handlers.md` — unrelated).+- The **Fixed Asset** invoice-line branch (`post-purchase-invoice/index.ts` ~1148–1247) has the+ same variance double-count in the FA subledger (PPV expensed AND `acquisitionCost` inflated+ with no GL asset debit) — tracked as a separate spawned task; do NOT touch the+ `case "Fixed Asset"` branch in this plan.++### Caveat for the executor++Production journal descriptions ("Material Issue — Job", "Job Completion") don't appear in local+`main` ("Material Issue to Job"; no FG-completion poster found) — the hosted instance may run+slightly ahead. **Before starting, `git pull` and re-verify the anchor code excerpts in each task+exist; if a task's anchor is missing or moved beyond trivial drift, STOP and report.** All bug+mechanics above were verified against local `main` (`95e658465`); anchors re-verified after+pulling to `60b1ee3e8` (2026-07-10 — pull brought only MES picking-list changes, all anchors+intact at the same line numbers).++## Progress++- [x] Task 1: Migration — `appliesToCostLedgerId` column + neutralize PO pseudo-layers+- [x] Task 2: Regenerate DB types (surgical: only the 3 costLedger lines kept per file; unrelated cloud-types drift reverted)+- [x] Task 3: Pure variance-allocation helper + Deno golden tests (8/8 passing)+- [x] Task 4: `calculate-cogs.ts` — consume adjustment children, filter base layers (deno check: no new errors in touched file; 7 pre-existing lib/* errors affect ALL functions on HEAD — Task 10 escape hatch applies repo-wide)+- [x] Task 5: `post-receipt` — create layers (normal + negative receipts)+- [x] Task 6: `post-receipt` — invoice-first rework (layer at accrual cost, no PPV) — implemented with Task 5 in one commit (same loop, interlocking split logic); deno check baseline 72 → 71 errors, no new+- [x] Task 7: `post-purchase-invoice` — adjust instead of create; coverage split+- [x] Task 8: `post-purchase-invoice` — void path reverses adjustments (plan's counter-child mechanics corrected first: original child stays live so +bump/−bump net out)+- [x] Task 9: `update-purchased-prices` — PO rows non-consumable; history math+- [x] Task 10: Type-check all touched Deno functions (per-file HEAD-baseline error-signature diffs: all identical or fewer; no errors in new/modified shared files from any consumer)+- [ ] Task 11: End-to-end scenario verification (S1–S4) on local stack+- [ ] Task 12: Docs sync — new costing rule + lessons entry++## Dependencies++- Task 2 needs Task 1. Tasks 4–9 need Tasks 1–3.+- Task 6 needs Task 5. Task 7 needs Task 4 (consumption semantics) and Task 3.+- Tasks 5 and 9 are independent of each other (parallelizable). Task 8 needs Task 7.+- Task 11 needs everything before it. Task 12 last.++---++## Task 1: Migration — `appliesToCostLedgerId` column + neutralize PO pseudo-layers++**Depends on:** none+**Files:**+- Create: migration via `pnpm db:migrate:new cost-ledger-adjustment-links` (never hand-pick the+ timestamp; HHMMSS must not be `000000`)++**Steps:**+1. From repo root run `pnpm db:migrate:new cost-ledger-adjustment-links`.+2. Fill the generated file in `packages/database/supabase/migrations/` with exactly:++```sql+-- Layer cost adjustments are child rows pointing at the layer they adjust+-- (inventory-valuation spec decision #11: never mutate a posted layer's cost).+ALTER TABLE "costLedger"+ ADD COLUMN IF NOT EXISTS "appliesToCostLedgerId" TEXT;++CREATE INDEX IF NOT EXISTS "costLedger_appliesToCostLedgerId_idx"+ ON "costLedger" ("appliesToCostLedgerId")+ WHERE "appliesToCostLedgerId" IS NOT NULL;++-- 'Purchase Order' costLedger rows are planning/cost-history artifacts written at PO+-- finalization (update-purchased-prices), not real inventory layers. Make them+-- non-consumable so FIFO/LIFO never eats stock that hasn't been received.+UPDATE "costLedger"+SET "remainingQuantity" = 0+WHERE "documentType" = 'Purchase Order'+ AND "remainingQuantity" IS DISTINCT FROM 0;+```++ Do NOT add a foreign key: `costLedger` predates the composite-PK convention and this follows+ the valuation spec's column design (plain TEXT + partial index). No decimal precision, no new+ RLS needed (existing costLedger policies cover the column).+3. Apply locally with `pnpm db:migrate`.++**Verify:**+```bash+pnpm db:migrate+# Expected: migration applies without error+psql "$DATABASE_URL" -c "SELECT column_name FROM information_schema.columns WHERE table_name='costLedger' AND column_name='appliesToCostLedgerId';"+# Expected: one row: appliesToCostLedgerId+psql "$DATABASE_URL" -c "SELECT COUNT(*) FROM \"costLedger\" WHERE \"documentType\"='Purchase Order' AND \"remainingQuantity\" <> 0;"+# Expected: 0+```++**Out of scope:** any other costLedger schema change; do not touch NUMERIC precisions of+existing columns.++---++## Task 2: Regenerate DB types++**Depends on:** Task 1+**Files:**+- Modify (generated): `packages/database/src/types.ts` and function lib types++**Steps:**+1. Run `pnpm run generate:types` from the repo root.+2. CAUTION (memory: types are cloud-generated): if the diff is enormous (tens of thousands of+ lines touching per-company tables), the local DB snapshot diverges from the committed+ cloud-generated types. In that case do NOT commit the full regeneration — keep only the+ `costLedger.appliesToCostLedgerId` additions (in both `packages/database/src/types.ts` and+ `packages/database/supabase/functions/lib/types.ts`) and revert the rest. If that surgical+ split is not possible, STOP and report.++**Verify:**+```bash+grep -n "appliesToCostLedgerId" packages/database/src/types.ts | head -3+# Expected: at least one hit in the costLedger Row/Insert/Update types+git diff --stat packages/database/src/types.ts+# Expected: small, costLedger-scoped diff (see caution above)+```++**Out of scope:** hand-editing any other generated type.++---++## Task 3: Pure variance-allocation helper + Deno golden tests++**Depends on:** none (pure TS)+**Files:**+- Create: `packages/database/supabase/functions/shared/purchase-cost-adjustment.ts`+- Create: `packages/database/supabase/functions/shared/purchase-cost-adjustment.test.ts`+- Copy from (precedent): `packages/database/supabase/functions/post-payment/build-payment-journal.ts`+ + `post-payment/post-payment.test.ts` (pure journal-builder + golden-master Deno tests)++**Steps:**+1. Create `purchase-cost-adjustment.ts` exporting exactly:++```typescript+export interface ReceiptLayerLike {+ id: string;+ quantity: number; // original layer quantity+ remainingQuantity: number; // unconsumed units+}++export interface VarianceAllocation {+ inventoryShare: number; // GL: Dr Inventory (write-up of on-hand goods)+ ppvShare: number; // GL: Dr PPV (variance on already-consumed goods)+ perLayer: {+ costLedgerId: string;+ appliedQuantity: number; // units of this layer the adjustment applies to+ adjustmentCost: number; // total cost bump for those units+ }[];+}++/**+ * Split an invoice-vs-receipt price variance for `matchedQuantity` units across+ * the receipt layers that hold them. Units still on hand absorb their share of+ * the variance into inventory (per-layer adjustment child rows); units already+ * consumed send their share to PPV. Layers must be passed in FIFO order.+ */+export function allocateVarianceAcrossLayers(+ layers: ReceiptLayerLike[],+ matchedQuantity: number,+ variance: number+): VarianceAllocation {+ if (matchedQuantity <= 0 || Math.abs(variance) <= 0.005) {+ return { inventoryShare: 0, ppvShare: Math.abs(variance) > 0.005 ? variance : 0, perLayer: [] };+ }+ const perUnit = variance / matchedQuantity;+ let uncovered = matchedQuantity;+ let inventoryShare = 0;+ const perLayer: VarianceAllocation["perLayer"] = [];+ for (const layer of layers) {+ if (uncovered <= 0) break;+ const applied = Math.min(Math.max(layer.remainingQuantity, 0), uncovered);+ if (applied <= 0) continue;+ const adjustmentCost = perUnit * applied;+ perLayer.push({ costLedgerId: layer.id, appliedQuantity: applied, adjustmentCost });+ inventoryShare += adjustmentCost;+ uncovered -= applied;+ }+ return { inventoryShare, ppvShare: variance - inventoryShare, perLayer };+}+```++ (Rounding: leave raw floats; the GL layer applies the existing `> 0.005` materiality gate.)+2. Write golden-master Deno tests mirroring the S1–S3 numbers from the plan header, using the+ same assert imports as `post-payment.test.ts`+ (`https://deno.land/[email protected]/testing/asserts.ts`):+ - S1: one layer `(qty 2, rem 2)`, matched 2, variance 20 → `inventoryShare 20, ppvShare 0`,+ one perLayer entry `(appliedQuantity 2, adjustmentCost 20)`.+ - S2: one layer `(qty 2, rem 1)`, matched 2, variance 20 → `inventoryShare 10, ppvShare 10`.+ - S3 second invoice: one layer `(qty 2, rem 0)`, matched 1, variance 10 → `inventoryShare 0,+ ppvShare 10`, empty perLayer.+ - Negative variance: layer `(qty 2, rem 2)`, matched 2, variance −20 → `inventoryShare −20`.+ - Multi-layer: layers `(qty 3, rem 1)` + `(qty 2, rem 2)`, matched 5, variance 10 →+ perUnit 2 → perLayer `[1×2, 2×2]`, `inventoryShare 6, ppvShare 4`.+ - Immaterial variance: `variance 0.004` → all zeros, empty perLayer.++**Verify:**+```bash+cd packages/database/supabase/functions && deno test shared/purchase-cost-adjustment.test.ts+# Expected: "ok" with all test steps passed, 0 failed+```+If `deno` is not on PATH, STOP and report (do not convert the tests to vitest — edge functions+are Deno; see post-payment precedent).++**Out of scope:** touching build-payment-journal or calculate-cogs in this task.++---++## Task 4: `calculate-cogs.ts` — consume adjustment children, filter base layers++**Depends on:** Tasks 1–2 (column exists in types)+**Files:**+- Modify: `packages/database/supabase/functions/shared/calculate-cogs.ts` — FIFO/LIFO branch only++**Steps:**+1. In the `FIFO`/`LIFO` case, change the base-layer query (currently `remainingQuantity > 0`+ ordered by postingDate/createdAt) to also require:+ - `.where("adjustment", "=", false)`+ - `.where("appliesToCostLedgerId", "is", null)`+ - `.where((eb) => eb.or([eb("documentType", "is", null), eb("documentType", "!=", "Purchase Order")]))`+ (belt-and-braces alongside Task 1's backfill).+2. After the base-layer loop picks `quantityFromLayer` from a layer, consume that layer's+ adjustment children in the same pass:++```typescript+const children = await trx+ .selectFrom("costLedger")+ .selectAll()+ .where("appliesToCostLedgerId", "=", layer.id)+ .where("remainingQuantity", ">", 0)+ .orderBy("createdAt", "asc")+ .execute();++let unappliedQuantity = quantityFromLayer;+for (const child of children) {+ if (unappliedQuantity <= 0) break;+ const childQty = Number(child.remainingQuantity);+ const perUnitBump =+ Number(child.quantity) > 0 ? Number(child.cost) / Number(child.quantity) : 0;+ const applyQty = Math.min(childQty, unappliedQuantity);+ totalCost += applyQty * perUnitBump;+ unappliedQuantity -= applyQty;+ await trx+ .updateTable("costLedger")+ .set({ remainingQuantity: childQty - applyQty })+ .where("id", "=", child.id)+ .execute();+}+```++ Place this AFTER the existing `totalCost += costFromLayer` accumulation and the parent+ `remainingQuantity` update, INSIDE the `for (const layer of layers)` loop. The+ `layersConsumed` entry's `unitCost` should stay the parent's base unit cost (callers use+ `totalCost` for GL amounts; per-layer unitCost is informational).+3. `Standard` and `Average` branches: unchanged.++**Verify:**+```bash+cd packages/database/supabase/functions && deno check shared/calculate-cogs.ts+# Expected: no type errors+```+(Behavioral proof lands in Task 11 — S1 consumption must total exactly 80.00.)++**Out of scope:** the `Average` fallback semantics; the `remainingToConsume > 0` fallback block+(leave it — it is the safety net for legacy data).++---++## Task 5: `post-receipt` — create layers (normal + negative receipts)++**Depends on:** Tasks 1–2, 4+**Files:**+- Modify: `packages/database/supabase/functions/post-receipt/index.ts` — the per-line posting+ loop (lines ~894–1069; anchor: `const lineCost = absReceivedQuantity * receiptLine.unitPrice`)+- Copy from (precedent): the costLedger insert shape at+ `packages/database/supabase/functions/post-purchase-invoice/index.ts:858-874`++**Steps:**+1. In the receipt-line loop, for lines where `itemTrackingType` is Inventory/Batch/Serial (i.e.+ the same condition that currently gates itemLedger inserts: NOT Non-Inventory, NOT+ `isOutsideProcessing`) and `receivedQuantity > 0`, collect a costLedger insert:++```typescript+costLedgerInserts.push({+ itemLedgerType: "Purchase",+ costLedgerType: "Direct Cost",+ adjustment: false,+ documentType: "Purchase Receipt",+ documentId: receiptId,+ externalDocumentId: receipt.data?.externalDocumentId ?? undefined,+ itemId: receiptLine.itemId,+ quantity: absReceivedQuantity,+ nominalCost: absReceivedQuantity * (receiptLine.unitPrice ?? 0),+ cost, // the SAME lineCost + lineWeightedShippingCost that hits the GL debit+ remainingQuantity: absReceivedQuantity,+ supplierId: purchaseOrder.data?.supplierId ?? undefined,+ companyId,+});+```++ Add a `costLedgerInserts` array following the function's existing insert-array pattern and+ flush it inside the same Kysely transaction that writes journal + itemLedger rows. IMPORTANT+ (Task 6 depends on this): for the invoice-first portion of a line, Task 6 overrides the cost —+ structure this insert so the invoice-first qty portion can carry a different unit cost+ (split into two rows when `invoiceFirstQty > 0`: one row for the invoice-first qty, one for+ the remainder).+2. **Negative receipt lines** (`receivedQuantity < 0`): instead of a layer, consume via+ `calculateCOGS(trx, { itemId, quantity: absReceivedQuantity, companyId })` (import from+ `../shared/calculate-cogs.ts`) and:+ - use `cogsResult.totalCost` as the GL amount for BOTH the inventory credit and the GR/IR+ debit of that line (replacing the PO-cost amount currently used for negative lines), and+ - insert a consumption row: same shape as above but `quantity: -absReceivedQuantity`,+ `cost: -cogsResult.totalCost`, `remainingQuantity: 0`.+ If the negative-receipt GL block's structure differs materially from the positive block+ (anchor: `debit("liability", ...)` for negative receipts around lines 941–971), STOP and+ report rather than improvising.+3. Serial/Batch lines: one layer per receipt line (not per serial) — quantity is the line's+ received quantity; do not attempt per-tracked-entity layers.++**Verify:**+```bash+cd packages/database/supabase/functions && deno check post-receipt/index.ts+# Expected: no type errors+```+(Behavioral proof in Task 11: after posting a receipt of 2 @ $30, a+`documentType='Purchase Receipt'` costLedger row exists with quantity 2, cost 60,+remainingQuantity 2.)++**Out of scope:** outside-processing (WIP) receipts and Non-Inventory lines get NO layers;+do not change their GL. Do not touch the invoice-first GL block yet (Task 6).++---++## Task 6: `post-receipt` — invoice-first rework (layer at accrual cost, no PPV)++**Depends on:** Task 5+**Files:**+- Modify: `packages/database/supabase/functions/post-receipt/index.ts` — the invoice-first+ variance block (lines ~1005–1067; anchor: `accrualUnitCostByPoLine`)++**Steps:**+1. Keep the existing detection machinery (`invoiceFirstQtyByPoLine`, `accrualUnitCostByPoLine`,+ lines ~825–892) exactly as is.+2. Replace the variance block (currently: `Cr GR/IR variance` + `Dr PPV variance`) with a cost+ substitution: for the `invoiceFirstQty` portion of the line, the receipt's OWN debit/credit+ pair must be posted at `accrualUnitCost` instead of PO unit cost. Concretely, split the+ line's GL amounts:+ - `invoiceFirstPortionCost = invoiceFirstQty * accrualUnitCost`+ - `normalPortionCost = (absReceivedQuantity - invoiceFirstQty) * poUnitCost` (+ that+ portion's weighted shipping)+ - Dr Inventory = `invoiceFirstPortionCost + normalPortionCost`; Cr GR/IR = same total.+ This clears the invoice's GR/IR debit accrual exactly, with **no PPV line at all** in the+ invoice-first flow.+3. The Task 5 layer insert for this line must mirror the same split: the invoice-first qty's+ layer row carries `cost = invoiceFirstPortionCost`; the remainder row carries the PO-cost+ portion.+4. **Transition guard:** before creating the invoice-first layer row, check for a pre-fix+ invoice-created layer covering these goods:++```typescript+const legacyInvoiceLayer = await trx+ .selectFrom("costLedger")+ .select(["id", "remainingQuantity"])+ .where("documentType", "=", "Purchase Invoice")+ .where("itemId", "=", receiptLine.itemId)+ .where("companyId", "=", companyId)+ .where("remainingQuantity", ">", 0)+ .executeTakeFirst();+```++ If found, skip layer creation for the overlapping quantity (the legacy layer already carries+ invoice cost) but keep the new GL treatment. Log via the function logger.+5. If the current invoice-first block's shape makes the per-portion split impossible without+ restructuring the whole line loop, STOP and report with the actual code shape — do not+ improvise a different accounting treatment.++**Verify:**+```bash+cd packages/database/supabase/functions && deno check post-receipt/index.ts+# Expected: no type errors+```+(Behavioral proof in Task 11 scenario S4: invoice 2@$40 then receive 2 → GL Inventory +80,+GR/IR nets to 0, layer(qty 2, cost 80), zero PPV lines in the receipt journal.)++**Out of scope:** receipts with no prior invoice (Task 5 covers them).++---++## Task 7: `post-purchase-invoice` — adjust instead of create; coverage split++**Depends on:** Tasks 3, 4+**Files:**+- Modify: `packages/database/supabase/functions/post-purchase-invoice/index.ts` — PO-matched+ branch (lines ~856–1115)++**Steps:**+1. **Delete the unconditional costLedger insert** at the top of the PO-matched branch+ (lines ~857–874, anchor comment `// create the cost entry`).+2. In the matched-quantity block (`if (quantityToReverse > 0 && accountingEnabled ...)`,+ anchor `receiptCostForReversedQty`), after `variance` is computed (anchor:+ `const variance = invoiceCostForReversedQty - receiptCostForReversedQty`):+ a. Fetch the item's costing method (the function already loads `itemCosts` for posting+ groups — extend that select with `costingMethod` if absent).+ b. Fetch this PO line's receipt layers in FIFO order:++```typescript+const receiptIdsForLine = await trx+ .selectFrom("receiptLine")+ .select(["receiptId"])+ .where("lineId", "=", invoiceLine.purchaseOrderLineId!)+ .where("companyId", "=", companyId)+ .execute();++const receiptLayers = receiptIdsForLine.length > 0+ ? await trx+ .selectFrom("costLedger")+ .selectAll()+ .where("documentType", "=", "Purchase Receipt")+ .where("documentId", "in", receiptIdsForLine.map((r) => r.receiptId))+ .where("itemId", "=", invoiceLine.itemId!)+ .where("adjustment", "=", false)+ .where("companyId", "=", companyId)+ .orderBy("postingDate", "asc")+ .orderBy("createdAt", "asc")+ .execute()+ : [];+```++ c. Compute the split with the Task 3 helper:+ - `costingMethod === "Standard"` → force `{ inventoryShare: 0, ppvShare: variance, perLayer: [] }` (D7).+ - `receiptLayers.length > 0` → `allocateVarianceAcrossLayers(receiptLayers, quantityToReverse, variance)`.+ - `receiptLayers.length === 0` (**legacy self-heal, D8**) → compute on-hand coverage from+ itemLedger (`SUM(quantity)` for the item/company via one Kysely query, clamped to+ `[0, quantityToReverse]`), split `variance` proportionally, and create ONE new layer:+ `documentType 'Purchase Receipt'`, `documentId = purchaseInvoice id`, quantity =+ `quantityToReverse`, `cost = receiptCostForReversedQty + inventoryShare`,+ `remainingQuantity = quantityToReverse`, `adjustment = false`. (No adjustment children+ in this branch — the write-up is baked into the layer.)+ d. Replace the single PPV journal line (lines ~994–1010) with:+ - if `Math.abs(allocation.inventoryShare) > 0.005`: a journal line identical in shape to+ the PPV line but `accountId: accountDefaults.data.inventoryAccount`, description+ `"Inventory Account"`, `amount: debit("asset", allocation.inventoryShare)`.+ - if `Math.abs(allocation.ppvShare) > 0.005`: the existing PPV line with+ `amount: debit("expense", allocation.ppvShare)`.+ - Keep the GR/IR debit (receipt cost) and AP credit (invoice cost) lines unchanged.+ - Update the `journalLineDimensionsMeta` push count to match the actual number of lines+ emitted (anchor: `reverseJlCount` — it derives from array length, verify it still does+ after the edit; if it hardcodes a count, fix it to derive).+ e. For each `allocation.perLayer` entry, insert an adjustment child row in the same+ transaction:++```typescript+costLedgerInserts.push({+ itemLedgerType: "Purchase",+ costLedgerType: "Direct Cost",+ adjustment: true,+ appliesToCostLedgerId: entry.costLedgerId,+ documentType: "Purchase Invoice",+ documentId: purchaseInvoice.data?.id ?? undefined,+ itemId: invoiceLine.itemId,+ quantity: entry.appliedQuantity,+ cost: entry.adjustmentCost,+ nominalCost: entry.adjustmentCost,+ remainingQuantity: entry.appliedQuantity,+ supplierId: purchaseInvoice.data?.supplierId,+ companyId,+});+```++3. **Accrual portion** (lines ~1051–1115): journal lines unchanged; confirm no costLedger row is+ created there after step 1 (it wasn't before — the deleted insert was branch-wide, which is+ exactly why it must go).+4. Import `allocateVarianceAcrossLayers` from `../shared/purchase-cost-adjustment.ts`.++**Verify:**+```bash+cd packages/database/supabase/functions && deno check post-purchase-invoice/index.ts+# Expected: no type errors+cd packages/database/supabase/functions && deno test shared/purchase-cost-adjustment.test.ts+# Expected: still all passing+```++**Out of scope:** the no-PO direct-invoice branch (lines ~741–854) — its layer creation at+invoice cost is correct and stays; `skipReceiptPost` handling stays as-is.++---++## Task 8: `post-purchase-invoice` — void path reverses adjustments++**Depends on:** Task 7+**Files:**+- Modify: `packages/database/supabase/functions/post-purchase-invoice/index.ts` — void/reversal+ section (lines ~283–372; anchor: the block that fetches original costLedger entries by+ `documentId` to reverse them)++**Steps:**+1. Read the void section first. It currently reverses invoice-created costLedger entries. After+ Task 7, a posted invoice may have created: (a) adjustment child rows (`adjustment = true`,+ `appliesToCostLedgerId` set), (b) a legacy self-heal layer, (c) direct-invoice layers (no-PO+ branch, unchanged).+2. Extend the reversal so that for each adjustment child created by this invoice+ (`documentId = invoice id AND adjustment = true AND appliesToCostLedgerId set`):+ - if `remainingQuantity === quantity` (untouched): delete the row;+ - else (partially/fully consumed): insert a counter-child on the same+ `appliesToCostLedgerId` with `cost: -original.cost`, `quantity: original.quantity`,+ `remainingQuantity: original.remainingQuantity`, and **leave the original's+ `remainingQuantity` untouched** — future consumption then applies +bump and −bump+ together, netting the remaining units back to base cost. (Zeroing the original would+ leave only the negative bump — traced wrong against scenario S2.)+3. The legacy self-heal layer is created with `documentType 'Purchase Receipt'` and+ `documentId = invoice id`, so the void fetch must include it explicitly: widen the+ costLedger fetch to both documentTypes for this documentId. Reverse it as: delete if+ unconsumed (restores the pre-invoice no-layer state); if partially consumed, insert the+ negative mirror row and zero its `remainingQuantity` so a voided layer can't keep feeding+ consumption. Plain (c) rows (no-PO direct-invoice layers) keep the existing+ negative-mirror behavior.+4. If the existing void code's structure contradicts this description (e.g., it doesn't fetch by+ `documentId`, or reverses via negative inserts only), STOP and report the actual structure+ with line numbers before writing code.++**Verify:**+```bash+cd packages/database/supabase/functions && deno check post-purchase-invoice/index.ts+# Expected: no type errors+```++**Out of scope:** receipt un-posting (no such flow exists in `post-receipt` today — do not+invent one).++---++## Task 9: `update-purchased-prices` — PO rows non-consumable; history math++**Depends on:** Tasks 1–2+**Files:**+- Modify: `packages/database/supabase/functions/update-purchased-prices/index.ts`++**Steps:**+1. In the `purchaseOrder` source branch (lines ~122–152), change the insert to+ `remainingQuantity: 0` (anchor: `remainingQuantity: line.quantity`). Keep the DELETE+INSERT+ re-finalization behavior.+2. In the cost-history accumulation (lines ~263–275, anchor+ `historicalPartCosts[ledger.itemId].quantity += ledger.quantity`): adjustment rows must+ contribute cost but not quantity:++```typescript+if (!ledger.adjustment) {+ historicalPartCosts[ledger.itemId].quantity += ledger.quantity;+}+historicalPartCosts[ledger.itemId].cost += ledger.cost;+```++3. Guard the division at the `itemCostUpdates.push` site (lines ~385–390): only push when+ `costHistory.quantity > 0` (prevents the existing NaN risk when history nets to zero).++**Verify:**+```bash+cd packages/database/supabase/functions && deno check update-purchased-prices/index.ts+# Expected: no type errors+```++**Out of scope:** lead-time logic; supplierPart upserts; the decision of WHETHER+`itemCost.unitCost` should track invoice actuals (it should — Average items and the FIFO+fallback rely on it, and with the GL fix it is no longer double-counted).++---++## Task 10: Type-check all touched Deno functions++**Depends on:** Tasks 4–9+**Files:** none (verification only)++**Steps:**+1. Run `deno check` over every touched entrypoint.++**Verify:**+```bash+cd packages/database/supabase/functions && deno check \+ shared/calculate-cogs.ts shared/purchase-cost-adjustment.ts \+ post-receipt/index.ts post-purchase-invoice/index.ts \+ update-purchased-prices/index.ts issue/index.ts+# Expected: no errors (issue/index.ts is untouched but consumes calculateCOGS — must still check)+```+If `deno check` fails on PRE-EXISTING errors unrelated to this change, note them and verify+only that no NEW errors appear in the touched files.++**Out of scope:** whole-repo typecheck (OOMs); `pnpm exec turbo run typecheck --filter=erp` is+NOT needed — no app-side files change.++---++## Task 11: End-to-end scenario verification (S1–S4) on local stack++**Depends on:** Tasks 1–10+**Files:** none (verification; scratch SQL allowed in the session scratchpad, never committed)++**Steps:**+1. Boot the stack with plain `crbn up` (portless). Do NOT rebuild/reset the database if one is+ already seeded — ask the user if a reset seems needed.+2. Ensure accounting is enabled: visit `/x/settings/accounting` (memory: fresh seeds default+ `accountingEnabled = false`; posts create no journals until enabled).+3. Log in via the `/auth` skill; drive the flows with `agent-browser` (memory: submit+ ValidatedForms via `requestSubmit(button)`; blur react-aria number fields to commit values).+4. **S1 (the regression):** create a purchased item (FIFO), PO for 2 @ $30 → receive → invoice+ at 2 @ $40 → sell both units for $100 total (sales order 2 @ $50) → ship → invoice.+ (Amended from the job-consumption variant: material issue and shipment consume through the+ IDENTICAL calculateCOGS path; the direct sale asserts the same numbers — revenue 100,+ COGS 80, NI 20 — without requiring MES/production setup. The `issue` function itself is+ untouched by this fix.) Then assert via psql (`psql "$DATABASE_URL"`):++```sql+-- GL inventory account nets to zero+SELECT COALESCE(SUM(jl."amount"), 0) AS inventory_net+FROM "journalLine" jl JOIN "account" a ON a."id" = jl."accountId"+WHERE a."number" = '1210' AND jl."companyId" = :company;+-- Expected: 0.00++-- No PPV posted for S1 (full stock coverage at invoice time)+SELECT COALESCE(SUM(jl."amount"), 0) FROM "journalLine" jl+JOIN "account" a ON a."id" = jl."accountId"+WHERE a."number" = '5210' AND jl."companyId" = :company;+-- Expected: 0.00++-- Adjustment child exists and was fully consumed+SELECT "quantity", "cost", "remainingQuantity" FROM "costLedger"+WHERE "adjustment" = true AND "appliesToCostLedgerId" IS NOT NULL AND "companyId" = :company;+-- Expected: quantity 2, cost 20, remainingQuantity 0+```++ Income-statement check in the UI (or via trial-balance query): revenue 100, COGS 80.25+ (assuming the same $0.25 labor), net income **20.00** — not 0.+5. **S2:** new item; receive 2 @ $30; issue 1 to a job; invoice 2 @ $40. Assert the invoice+ journal contains `Inventory +10` and `PPV +10` lines; issue the second unit and assert the+ consumption journal credits inventory exactly 40 and GL inventory for the item's flow nets 0.+6. **S3:** new item; receive 2 @ $30; invoice qty 1 @ $40 (partial). Assert: invoice journal has+ `Dr GR/IR 30, Dr Inventory 10, Cr AP 40`, no PPV; GR/IR still carries 30 for the line.+7. **S4:** new item; post the invoice BEFORE any receipt (qty 2 @ $40) — assert accrual journal+ only and **zero costLedger rows** for the item; then receive 2 — assert `Dr Inventory 80 /+ Cr GR/IR 80`, no PPV, layer `(qty 2, cost 80, remainingQuantity 2)`.+8. If any step's numbers deviate, STOP: capture the journal + costLedger rows for the failing+ scenario and report — do not patch numbers to pass.++**Verify:** the psql outputs above, matching expectations exactly (±0.005 only where a+materiality gate applies).++**Out of scope:** performance testing; multi-currency scenarios (exchangeRate ≠ 1) — flag for a+follow-up if line-level FX shows up during testing.++---++## Task 12: Docs sync — new costing rule + lessons entry++**Depends on:** Task 11 (document what shipped, not what was planned)+**Files:**+- Create: `.ai/rules/inventory-cost-layers.md` with `paths:` frontmatter covering+ `packages/database/supabase/functions/post-receipt/**`,+ `packages/database/supabase/functions/post-purchase-invoice/**`,+ `packages/database/supabase/functions/shared/calculate-cogs.ts`,+ `packages/database/supabase/functions/update-purchased-prices/**`+- Modify: `.ai/lessons.md` — one entry+- Modify: `.ai/specs/2026-07-04-inventory-valuation-completeness.md` — premise note++**Steps:**+1. Write the rule: layer lifecycle (receipt creates → invoice adjusts via `appliesToCostLedgerId`+ children → consumption decrements parent + children), the GL/subledger invariant, the+ coverage split, the invoice-first treatment, PO pseudo-layers being non-consumable, and the+ Standard-costing carve-out. Ground every claim in the shipped code (cite files).+2. Add a lessons entry in `Context → Problem → Rule → Applies to` format: posting functions must+ never book the same economic amount to the GL and the subledger through different accounts+ (the PPV double-count).+3. In the valuation spec, update the receipt-time-layer premise (its §"Variance at receipt"+ assumed layers did not yet exist at receipt) with a one-line note that receipt-time layer+ creation shipped in this fix; do not rewrite the spec.+4. Add a router row for the new rule in the root `AGENTS.md` Task Router (Domain Modules →+ "Inventory costing / cost layers").++**Verify:**+```bash+ls .ai/rules/inventory-cost-layers.md && grep -n "inventory-cost-layers" AGENTS.md+# Expected: file exists; one Task Router row references it+```++**Out of scope:** the public docs site (`docs/`) — the Guide has no purchase-posting internals+page today; do not create one in this plan.diff --git a/.ai/research/purchase-price-variance-actual-costing.md b/.ai/research/purchase-price-variance-actual-costing.mdnew file mode 100644index 0000000000..b7e4980cff--- /dev/null+++ b/.ai/research/purchase-price-variance-actual-costing.md@@ -0,0 +1,276 @@+# Purchase Price Variance under Actual Costing Research: Best Practices Survey++## Summary++Surveyed how SAP S/4HANA, Microsoft Dynamics 365 Business Central, NetSuite, Odoo (16–19),+and Epicor Kinetic handle the difference between goods-receipt cost and supplier-invoice cost+for inventory items under **actual** costing methods (FIFO/Average — not standard costing),+including GR/IR clearing, stock-coverage splits, invoice-before-receipt, partial documents,+and retroactive COGS adjustment. Purpose: validate the design in+`.ai/plans/2026-07-10-purchase-cost-layer-gl-consistency.md` (receipt-created cost layers,+invoice-time variance split between inventory write-up and PPV by stock coverage).++**Verdict: the plan's design is validated.** Its core mechanics are the SAP moving-average+stock-coverage treatment implemented with Odoo 16/17's exact data structure (correction layers+linked to the receipt layer — Odoo's `stock_valuation_layer_id` link is structurally identical+to the plan's `appliesToCostLedgerId`). The invoice-before-receipt treatment (receipt valued at+invoice price, no variance) is verbatim SAP behavior. Every surveyed system confirms that a+PPV-style expense-always account is a **standard-costing** concept; under actual costing the+consensus is to absorb the difference into inventory for on-hand quantity. Notably, the bug the+plan fixes (variance expensed **and** layer written at invoice cost) is a hybrid no surveyed+system exhibits.++## Competitors Surveyed++- **SAP S/4HANA (MM/FI)** — enterprise reference; the origin of GR/IR clearing and the+ stock-coverage split for moving-average materials.+- **Microsoft Dynamics 365 Business Central** — mid-market manufacturing reference; the most+ complete actual-costing engine (value entries + retroactive cost adjustment).+- **NetSuite** — mid-market ERP; deliberately simple receipt-is-cost-authority model.+- **Odoo 16–19** — closest architectural cousin to Carbon (stock valuation layers ≈ costLedger+ rows); its 16.0 redesign is essentially the same fix the plan makes.+- **Epicor Kinetic** — job-shop manufacturing ERP; behavior differs by costing method.++## Key Consensus Patterns++### 1. A GR/IR clearing account decouples receipt from invoice++- **SAP**: GR/IR (transaction key WRX), credited at PO price on GR, debited on invoice;+ quantity-based clearing per PO line; F.13/F.19/MR11 hygiene jobs.+- **BC**: Inventory Account (Interim) / Invt. Accrual Acc. (Interim) hold "expected cost"+ until invoicing.+- **NetSuite**: Accrued Purchases ("Inventory Received Not Billed"), receipt at PO rate.+- **Odoo**: "Stock Interim (Received)"; auto-reconciled on bill posting.+- **Epicor**: "AP Clearing"/"Accrued Receipts" at PO cost.+- **Rationale**: three-way match requires a balance-sheet parking account; every system agrees.+ Carbon's `goodsReceivedNotInvoicedAccount` already matches.++### 2. Inventory value is created at receipt (at PO price) and trued up at invoice++- **SAP**: GR debits stock at PO price; invoice revalues (MAP) per stock coverage.+- **BC**: receipt posts an "expected cost" value entry; invoicing reverses expected and posts+ actual on the same item ledger entry.+- **Odoo 16+**: receipt creates the SVL at PO price; the bill creates a correction SVL.+- **Epicor (FIFO)**: each receipt is its own FIFO cost bucket, corrected to invoice cost.+- **Exception — NetSuite**: the item receipt is the *permanent* cost authority; a differing+ bill never touches inventory (delta sits in Accrued Purchases until a manual variance-posting+ batch expenses it, or the user edits the receipt cost to trigger a full recalculation).+- **Rationale**: goods are an asset the moment they arrive; the invoice refines the estimate.+ Validates plan D1 (receipt creates the layer) — and shows Carbon's current+ layer-at-invoice-only model matches no surveyed system.++### 3. Under actual costing, the invoice-vs-receipt delta splits by stock coverage++- **SAP (MAP)**: full coverage → all to stock account (revaluation); partial → proportional+ split `stock qty / invoiced qty` between stock and the price-difference account (PRD);+ zero coverage → all to PRD. SAP PRESS worked example: $10 delta, 80/100 pc on hand →+ $8 inventory, $2 expense.+- **Odoo 16/17** (source-verified in `purchase_stock/models/account_move_line.py`):+ `_apply_price_difference()` creates a correction SVL **linked to the receipt layer**+ (`stock_valuation_layer_id = corrected_layer.id`) for the remaining quantity and expenses+ the already-delivered portion via COGS-tagged journal lines. Skips products with+ `cost_method == 'standard'`.+- **BC**: no split — the full delta lands in the value entries and `Adjust Cost – Item Entries`+ pushes the consumed share retroactively into posted COGS (see pattern 5).+- **Epicor**: FIFO parts get an automatic inventory cost adjustment (clearing PPV);+ Average/Last parts get GL-only PPV with **no** inventory correction (documented as a+ weakness requiring "close management").+- **NetSuite**: no split; all to variance accounts, never inventory (unless receipt edited).+- **Rationale**: the on-hand portion is an asset-measurement refinement, not a period expense;+ expensing it distorts both margin and the balance sheet. Validates plan D2; per-layer+ coverage (Odoo/BC style) is finer-grained than SAP's whole-material stock check.++### 4. Invoice-before-receipt: the later receipt is valued at the invoice price, no variance++- **SAP**: invoice debits GR/IR at invoice value (no stock posting); the later GR is valued at+ the **invoice price** — GR/IR settles exactly, no PRD posting. Received qty beyond the+ invoiced qty reverts to PO price.+- **BC**: structurally forbidden — invoiceable quantity is capped by received quantity; a+ standalone item invoice creates the receipt simultaneously.+- **NetSuite**: allowed; IRNB carries a debit; the later receipt still posts at PO rate and the+ delta stays in IRNB for the variance batch.+- **Odoo**: a known gap — `_apply_price_difference` skips when no receipt layers exist+ ("Don't create value for more quantity than received"); invoice-first gets no revaluation+ (criticized in RFC #118687).+- **Rationale**: when actual cost is known before goods arrive, there is nothing to estimate —+ SAP's treatment is the correct one and the plan's D3 matches it exactly (including the+ PO-price reversion for over-receipt).++### 5. Retroactive COGS restatement is the premium tier, not the baseline++- **BC**: `Adjust Cost – Item Entries` forwards late cost changes into posted COGS via+ append-only adjustment value entries (dated to the invoice or next open period).+- **SAP**: only with **Material Ledger actual costing** (requires standard price control ++ period-end costing run computing a periodic unit price that revalues both ending inventory+ and the period's consumption).+- **NetSuite**: only by editing the item receipt cost (triggers a full costing recalculation+ from the receipt date forward).+- **Odoo / Epicor**: no restatement of original postings — the consumed share hits the current+ period (COGS account in Odoo, PPV in Epicor).+- **Rationale**: restatement needs dedicated batch machinery (application chains, period+ guards, G/L reconciliation). Expensing the consumed share in the current period (SAP without+ ML, Odoo, Epicor) is the accepted mid-market baseline. Validates keeping retroactive COGS+ out of the plan's scope.++### 6. "Purchase price variance" is standard-costing vocabulary++- **SAP** officially says "price differences" (PRD); PPV is consulting vernacular for+ standard-price materials.+- **BC** uses the Purchase Variance account **only** for Standard costing ("variance = actual −+ standard"); FIFO/Average have no variance account at all.+- **Epicor**: "PPV account used for Standard Cost parts"; **Odoo 16+** removed the price+ difference account for FIFO/AVCO entirely.+- **Rationale**: under actual costing there is no "correct" price to vary from — only a better+ estimate arriving later. Validates plan D7 (Standard items keep all-variance-to-PPV).++## Answers to Research Questions++1. **On-hand vs consumed split?** — Consensus (SAP, Odoo, Epicor-FIFO): on-hand → inventory+ write-up; consumed → expense (SAP PRD / Odoo COGS). BC goes further (retroactive COGS);+ NetSuite does less (all to variance). The plan's D2 sits on the consensus.+2. **Invoice-before-receipt?** — SAP: GR/IR carries the accrual at invoice value; later receipt+ valued at invoice price, zero variance (= plan D3). BC forbids it; Odoo mishandles it+ (known gap); NetSuite parks it in IRNB.+3. **Layers at receipt or invoice?** — Receipt, everywhere except NetSuite-without-Advanced-+ Receiving and pre-16 Odoo. Adjustments are separate linked records (BC adjustment value+ entries, Odoo correction SVLs with a parent-layer FK) — never in-place mutations (= plan+ D1/D4 and valuation-spec decision #11).+4. **Partial receipts/invoices?** — Quantity-based matching per PO line (SAP), value entries+ per partial invoicing against the same item ledger entry (BC), correction capped at received+ quantity (Odoo — same cap as the plan's `quantityToReverse`). Multiple receipts per invoice+ and vice-versa are table stakes; the plan's journal-group walk + per-layer allocation covers+ both.+5. **Retroactive COGS?** — Premium tier only (BC always-on; SAP only with Material Ledger;+ NetSuite only via receipt edit). Current-period expensing of the consumed share is the+ accepted baseline. Plan's out-of-scope call is sound; BC's append-only adjustment entries+ are the model to follow if Carbon builds it later.+6. **Terminology?** — "Price difference" (SAP) or nothing at all (BC/Odoo actual costing).+ PPV strictly means actual-vs-standard. Carbon keeping the `purchaseVarianceAccount` for the+ consumed share matches SAP's PRD usage; the journal line description could eventually read+ "Price Difference" for actual-cost items, but this is cosmetic.++## Competitor-Specific Details++### SAP S/4HANA+- OBYC keys: BSX (stock), WRX (GR/IR), PRD (price differences; modifiers PRA/PRF/PRU),+ KDM (FX differences at invoice clearing).+- Coverage measured as **current total stock of the material in the valuation area** at invoice+ posting — not per-receipt tracking. Consumption between receipt and invoice therefore shifts+ the split even if unrelated stock covers it (coarser than per-layer coverage).+- MR11 clears residual GR/IR **quantity** mismatches; price residues always resolve through+ stock/PRD at invoice time.++### Microsoft Dynamics 365 Business Central+- Two-ledger model: item ledger entries (quantity, `Remaining Quantity`) + value entries+ (`Cost Amount (Expected)` vs `Cost Amount (Actual)`, `Adjustment` flag) — the closest+ published analog to Carbon's itemLedger/costLedger pair.+- Expected-cost value entries always exist in the subledger; "Expected Cost Posting to G/L"+ only controls whether the interim accounts hit the G/L.+- `Adjust Cost – Item Entries`: detection at posting (item application entries), calculation in+ batch; adjustments are **append-only** value entries; also maintains the item card unit cost.+- Invoice-before-receipt impossible from a PO; a direct purchase invoice receives + invoices in+ one posting, so "invoiced but not received" inventory cannot exist.++### NetSuite+- Verbatim doctrine: "If you change the cost on the vendor bill, NetSuite doesn't update item+ costing… Any variance between the receipt and the bill shows up in the Accrued Purchases+ account."+- `Post Vendor Bill Variances` (manual batch) reclasses IRNB residuals into Bill Price /+ Quantity / Exchange Rate variance accounts configured **on the item record**; eligibility+ depends on "Match Bill to Receipt" (per-receipt) vs PO-line aggregate (PO must be closed).+- Simplest model surveyed, and the source of chronic IRNB-reconciliation pain (multiple+ consulting firms publish reconciliation guides) — a cautionary tale for leaving variances+ parked in the accrual account.++### Odoo+- 16.0 redesign (RFC #118687) is effectively the same fix as this plan: price-difference+ account removed for FIFO/AVCO; correction SVL linked to the receipt layer+ (`stock_valuation_layer_id`); `layer.remaining_value` bumped; delivered share expensed with+ `display_type: 'cogs'` journal lines.+- Known criticisms worth heeding: bill locking once a correction SVL exists, FX fluctuations+ generating spurious corrections, awkward reversal story (plan Task 8 handles reversal+ explicitly; FX is flagged for follow-up in Task 11).+- Odoo 19 moved valuation to invoice-level with period-end accrual entries — a regression per+ community reports (no GL at receipt); not a pattern to follow.++### Epicor Kinetic+- Costing-method split: FIFO parts auto-correct inventory (ADJ-CST); Average/Last parts post+ GL-only PPV (ADJ-PUR touches only accrual + variance, "Nothing to Inventory") — documented+ as requiring manual cost adjustments to keep inventory honest.+- Kinetic quirk: with multiple invoices per receipt, variance computes only when an invoice is+ marked **final**.++## Recommended Approach for Carbon++1. **Proceed with the plan as designed.** D1 (receipt-created layers) and D2 (coverage split+ with adjustment child rows) follow the SAP stock-coverage treatment with Odoo 16/17's+ per-layer data structure — the two systems that solved this most recently and most+ precisely. Per-layer coverage is strictly more accurate than SAP's whole-material check.+2. **Keep D3 (invoice-first → receipt at invoice cost, no variance).** It is exactly SAP's+ behavior, including PO-price reversion for receipt quantity beyond the invoiced quantity,+ and it fixes a gap Odoo still has.+3. **Keep the consumed-portion share in `purchaseVarianceAccount` (D7 semantics).** This+ matches SAP PRD and Epicor; Odoo's alternative (product COGS account) is defensible but+ loses the analyzable variance line. Optionally rename the journal line description to+ "Price Difference" for non-Standard items later — cosmetic, not blocking.+4. **Do not build retroactive COGS restatement now.** It is the BC/Material-Ledger premium+ tier; if built later, follow BC's append-only adjustment value entries dated to the invoice+ (or next open period) — the plan's `appliesToCostLedgerId` children are the right substrate+ for that future work.+5. **Heed Odoo's RFC criticisms in implementation**: make invoice void/reversal of adjustment+ rows first-class (plan Task 8), and treat multi-currency variance (exchange-rate movement+ between receipt and invoice) as a named follow-up — SAP separates FX differences (KDM) from+ price differences (PRD); Carbon currently folds FX into the line cost.+6. **Avoid the NetSuite failure mode**: never leave the delta parked in GRNI for a manual+ batch to clean up — the surveyed reconciliation pain confirms Carbon's choice to resolve+ variance at invoice-posting time.++## Sources++### SAP+- https://help.sap.com/docs/SAP_S4HANA_CLOUD/7f47a6d9441c46ac86c96fd27f6015f0/bbd9b6ce0be14516ad7868da0982024a.html — Valuation with Moving Average Price+- https://help.sap.com/docs/SAP_ERP/56f7319a9048445eb86221af73cab72b/6a5eb6531de6b64ce10000000a174cb4.html — Price Control+- https://learning.sap.com/courses/invoice-verification-in-sap-s-4hana/entering-invoices-with-variances-1 — Entering Invoices with Variances (stock-coverage rule)+- https://userapps.support.sap.com/sap/support/knowledge/en/2674900 — KBA: Posting logic for invoices with price variances (login-gated; preview verified)+- https://userapps.support.sap.com/sap/support/knowledge/en/2674902 — KBA: Posting logic for GR before IR (login-gated; preview verified)+- https://userapps.support.sap.com/sap/support/knowledge/en/2603662 — KBA: Separate G/L accounts for price difference postings+- https://community.sap.com/t5/additional-blog-posts-by-sap/valuation-of-a-goods-receipt-for-a-purchase-order-gr-ir-amount/ba-p/12905602 — GR valuation at invoice price (invoice-first)+- https://blog.sap-press.com/what-is-the-difference-between-moving-average-price-and-standard-price-in-sap — MAP vs standard, $8/$2 worked example+- https://erpcorp.com/sap-controlling-blog/sap-controlling/gr-ir-goods-receipt-invoice-receipt-processing — GR/IR mechanics+- https://erpcorp.com/sap-controlling-blog/actual-costing-with-sap-material-ledger — Material Ledger actual costing+- https://www.pikon.com/en/blog/introduction-to-s4hana-material-ledger-and-actual-costing/ — ML periodic unit price++### Business Central+- https://learn.microsoft.com/en-us/dynamics365/business-central/design-details-expected-cost-posting — Expected Cost Posting (interim accounts, 95→100 example)+- https://learn.microsoft.com/en-us/dynamics365/business-central/design-details-cost-adjustment — Adjust Cost – Item Entries+- https://learn.microsoft.com/en-us/dynamics365/business-central/design-details-inventory-posting — Item ledger vs value entries+- https://learn.microsoft.com/en-us/dynamics365/business-central/design-details-variance — Variance = actual − standard (Standard only)+- https://learn.microsoft.com/en-us/dynamics365/business-central/design-details-costing-methods — Costing methods+- https://learn.microsoft.com/en-us/dynamics365/business-central/design-details-accounts-in-the-general-ledger — Account mapping table+- https://learn.microsoft.com/en-us/dynamics365/business-central/purchasing-how-record-purchases — Receive-before-invoice enforcement+- https://learn.microsoft.com/en-us/dynamics365/business-central/purchasing-how-to-combine-receipts — Get Receipt Lines (many receipts, one invoice)+- https://www.speakingbusinesscentral.com/post/business-central-inventory-gl-entries-purchases — GL walkthrough (actual cost)+- https://www.speakingbusinesscentral.com/post/business-central-inventory-gl-entries-purchases-standard-cost — GL walkthrough (standard cost)++### NetSuite+- https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_N2191818.html — Costing Methods (receipt is cost authority)+- https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_N2371184.html — Vendor Bill Variances+- https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_N2373098.html — Vendor Bill Variance Journals (formulas)+- https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_N2197365.html — Inventory Costing Recalculations+- https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_N2195087.html — System COGS Adjustments+- https://blog.prolecto.com/2017/04/29/explaining-netsuites-inventory-received-not-billed-account/ — IRNB explained+- https://technologyblog.rsmus.com/technologies/netsuite/reconciling-inventory-received-not-billed-irnb/ — IRNB reconciliation pain++### Odoo+- https://github.com/odoo/odoo/issues/118687 — RFC: 16.0 stock accounting redesign (pdiff SVLs, criticisms)+- https://raw.githubusercontent.com/odoo/odoo/17.0/addons/purchase_stock/models/account_move_line.py — `_apply_price_difference` source+- https://www.odoo.com/documentation/19.0/applications/inventory_and_mrp/inventory/inventory_valuation/cheat_sheet.html — Valuation cheat sheet (v19 invoice-level model)+- https://www.odoo.com/forum/help-1/where-is-the-price-difference-account-in-odoo-16-212839 — Price difference account removal+- https://www.odoo.com/forum/help-1/price-difference-purchase-and-stock-264427 — Invoice-before-receipt gap+- https://odootricks.tips/inventory-postings-valuation/ — Stock Interim (Received) postings++### Epicor+- https://www.epiusers.help/t/ap-invoices-affect-on-cost-of-qty-bearing-parts/63860 — ADJ-PUR is GL-only for average/last+- https://www.epiusers.help/t/purchase-price-variance-average-costing/87594 — PPV = standard-cost concept+- https://www.epiusers.help/t/purchase-price-variance-ap-qty-does-not-match-receipt-quantity/116142 — "final invoice" variance timing+- https://dotnetitblog.wordpress.com/tag/inventory-costing/ — FIFO auto cost adjustment vs average PPVdiff --git a/.ai/research/quickbooks-accounting-sync-engine.md b/.ai/research/quickbooks-accounting-sync-engine.mdnew file mode 100644index 0000000000..2634cc6f61--- /dev/null+++ b/.ai/research/quickbooks-accounting-sync-engine.md@@ -0,0 +1,799 @@+# QuickBooks Integration + Accounting Sync Engine Research: Best Practices Survey++> Researched 2026-07-08. Scope: QuickBooks Enterprise Solutions: Manufacturing & Wholesale 24.0+> (QuickBooks **Desktop**) integration for Carbon, plus refactoring the Xero integration into a+> generic accounting sync engine that handles both entity sync and posting (GL) sync.++## Summary++Surveyed Intuit primary sources, the two canonical QBD manufacturing integrations (Fishbowl,+MISys), five cloud MRP multi-provider sync engines (Katana, Cin7 Core, Unleashed, SOS,+MRPeasy, Fulfil), bridge vendors (Conductor, Codat, Merge, Rutter, Apideck), and the+SAP/NetSuite/iPaaS posting-interface canon — against a full inventory of Carbon's existing+`packages/ee/src/accounting` engine and posting pipeline. Headline findings: **(1)** QB Desktop+has no REST API, no webhooks, and no OAuth — the only cloud path is the QuickBooks Web+Connector (a Windows app that polls YOUR SOAP endpoint with qbXML); every bridge vendor wraps+it. QuickBooks **Online** is a completely different platform (OAuth2/REST); "QuickBooks+support" is therefore two providers, not one. **(2)** Enterprise 24.0 is not a dying version —+it is the *terminal, continuously-updated* Desktop platform with no announced end date, still+sold to new customers; and no modern cloud MRP serves it (Katana/Cin7/Unleashed/Fulfil are all+QBO/Xero-only), making QBD support genuine differentiation for exactly the manufacturing+segment Carbon sells to. **(3)** The industry-consensus posting model is **native documents+for AR/AP** (invoices, bills, payments — which Carbon's engine already syncs) **plus journal+entries for inventory economics** (COGS, adjustments, WIP/production, variances — which Carbon+doesn't sync yet), with configurable per-transaction vs daily-summary consolidation and a flat+named-role account-mapping page — Carbon's existing `accountDefault` + per-entity-override+design maps onto this directly. **(4)** Carbon's provider abstraction is further along than+assumed (generic `BaseEntitySyncer`, `SyncFactory`, `externalIntegrationMapping`), but it+assumes synchronous request/response REST providers with OAuth2 credentials; QBD's inverted+poll-based transport forces the one big architectural addition the enterprise canon demands+anyway: a **durable per-record sync outbox/state machine** (pending → pushed → confirmed →+failed) with an error inbox, idempotency keys, and periodic reconciliation.++## Research Questions++1. What integration surface does QB Desktop Enterprise 24.0 actually expose (qbXML version, Web+ Connector, SDK) and what is the real auth model — does OAuth even apply, or is that+ QuickBooks Online only?+2. How does a cloud SaaS reach a customer's on-prem QB Desktop — self-hosted QBWC SOAP endpoint+ vs a bridge vendor (Conductor, Codat, …) — and what is the build-vs-buy tradeoff?+3. Which entities do competitor manufacturing ERPs sync, in which direction, and do they post+ financials as native documents (invoices/bills) or as journal entries (detail vs daily+ summary)?+4. What is the standard architecture for a multi-provider accounting sync engine (external-ID+ mapping, account mapping, idempotency, retries, queues, reconciliation)?+5. What qbXML transaction coverage does Carbon need (customers, vendors, items, invoices, bills,+ payments, JournalEntryAdd, inventory adjustments) and what are its known limits?+6. What is QB Desktop's lifecycle/EOL status in 2026, and does that push the design toward also+ targeting QuickBooks Online from day one?++## Carbon Current State (Codebase Baseline, verified 2026-07-08)++### The sync engine already half-exists++`packages/ee/src/accounting/` contains a provider-neutral core, with Xero as the only live+provider (`providers/xero/`). The old `packages/ee/src/xero/` folder is now mostly config+(`config.tsx` integration definition + empty `xeroOnInstall()` hook); real sync logic lives in+the accounting core.++**Provider-agnostic core (reusable as-is):**++- `BaseEntitySyncer<TLocal, TRemote, TOmit>` (`accounting/core/types.ts`, ~800 lines) — push /+ pull / batch, cooldown (60s per entity per direction), timestamp comparison, conflict+ resolution by `owner`, optional `shouldSync()` business gate, `ensureDependencySynced()` JIT+ dependency sync (e.g. vendor before bill).+- `SyncFactory.getSyncer(context)` (`accounting/core/sync.ts`) — dispatch by entity type.+- `ExternalIntegrationMappingService` (`accounting/core/external-mapping.ts`) — all ID links via+ the `externalIntegrationMapping` table: `(entityType, entityId, integration, companyId)`+ unique, partial-unique on external ID, `lastSyncedAt` (cooldown), `remoteUpdatedAt` (pull+ bailout), JSONB `metadata`.+- `companyIntegration` table — per-company integration row; JSONB `metadata` stores credentials ++ settings; `verifiedAt`.+- Sync config semantics (`accounting/core/models.ts`): per entity `{ enabled, direction:+ two-way | push-to-accounting | pull-from-accounting, owner: carbon | accounting }` ++ `ENTITY_DEFINITIONS` dependency graph. NOTE: company-level `syncConfig` is parsed but NOT yet+ applied — `DEFAULT_SYNC_CONFIG` is hardcoded (`core/service.ts`).+- Inngest jobs: `sync-external-accounting` (webhook/manual pulls + pushes),+ `accounting-backfill` (full entity backfill), `events/sync.ts` (Carbon DB writes → push;+ DELETE logged/skipped — deliberately unimplemented per `packages/ee/AGENTS.md`).+- `withTriggersDisabled()` wraps sync DB writes to prevent loops.++**Entity sync matrix today (Xero):**++| Entity | Direction (default) | Owner | Trigger | Notes |+|---|---|---|---|---|+| customer | two-way | accounting | Xero webhook, backfill, DB-write events | One Xero Contact backs BOTH customer + vendor (`IsCustomer`/`IsSupplier`) |+| vendor | two-way | accounting | same | |+| item | push-to-accounting | carbon | backfill, DB-write events | |+| invoice (AR) | two-way | accounting | webhook (ACCREC), backfill, events | |+| bill (AP) | two-way | accounting | webhook (ACCPAY), backfill, events | |+| purchaseOrder | push-to-accounting | carbon | backfill, events | |+| salesOrder | push (disabled) | carbon | — | |+| inventoryAdjustment | push (disabled) | carbon | — | |+| payment | pull (disabled, stub) | accounting | — | |+| employee | disabled | carbon | — | Xero dropped Employees API |++**Hard-coded Xero-isms a generic engine must abstract:**++1. `ProviderCredentialsSchema` is a discriminated union with only an `oauth2` variant — QB+ Desktop (Web Connector) is username/password + session ticket, a fundamentally different+ shape (and an inverted, poll-based connection model).+2. `tenantId`/`tenantName` in credentials; `xero-tenant-id` header; `GET /connections` tenant+ discovery.+3. OAuth URLs + scopes hardcoded in `xero/config.tsx` / `providers/xero/provider.ts`.+4. Pagination (100/page), .NET date parsing (`/Date(...)/`), phone-type mapping, dual+ customer+vendor Contact logic in `ContactSyncer`.+5. `DEFAULT_SYNC_CONFIG` hardcoded rather than per-company `syncConfig`.+6. Webhook handler (`routes/api+/webhook.xero.ts`) is Xero-specific: HMAC verification+ (fail-open without secret), CONTACT/INVOICE categories only, synchronous Xero GETs to+ resolve entity types.++**Existing provider stubs:** `packages/ee/src/quickbooks/config.tsx` (51 lines, `active:+false`) is wired for **QuickBooks Online** OAuth2 (`appcenter.intuit.com`,+`com.intuit.quickbooks.accounting` scope) — NOT Desktop. `packages/ee/src/sage/config.tsx` is a+similar placeholder.++### Posting/GL side (what the sync engine must carry)++- Journal model: `journal` (status `Draft|Posted|Reversed`, `sourceType` enum of ~19 source+ types, `postingDate`, `accountingPeriodId`, `reversalOfId`/`reversedById`, and — already+ added for integrations — `externalId`, `sourceSystem`, `sourceApiKeyId`) + `journalLine`+ (accountId, signed amount) + `journalLineDimension`.+- Posting happens in Deno edge functions (`post-sales-invoice`, `post-purchase-invoice`,+ `post-receipt`, `post-shipment`, `post-payment` + `build-payment-journal`, `post-memo`,+ production/job functions). Account resolution: `accountDefault` flat company defaults+ (receivables/payables/inventory/COGS/cash/FX gain-loss…) + `itemPostingGroup` per-group+ overrides + per-location GL accounts. Posting-group N×M matrices are a REJECTED pattern+ (`.ai/lessons.md`).+- AR/AP: `salesInvoice`/`purchaseInvoice` + `payment` + `invoiceSettlement` with tie-out RPCs+ (`get_ar_tie_out`, `get_ap_tie_out`, aging). Memos post as Credit/Debit Memo journals.+- Period close: `journal_check_period_open` trigger blocks posting into closed periods; period+ lifecycle Open → Locked → Closed.+- `.ai/specs/2026-07-04-integration-surface.md` (finalized, unimplemented) defines the public+ surface: Trial Balance API, JE export (streaming), **idempotent JE import API** (period- and+ approval-gated, stamps `externalId`+`sourceSystem`), and outbound webhooks+ (`journal_entry.posted`, `journal_entry.reversed`, `period.locked/closed/reopened`,+ `approval.decided`) delivered via PGMQ → Inngest with HMAC signing. Blocked by #1032+ (document approvals) and #1047 (record integrity/JE export definition).+- Cutover (#1057): opening-balance journal at cutover − 1; sync engines must never backdate+ into pre-cutover/closed periods.++**Gaps for posting sync (confirmed absent today):** no `journalEntry` entity type or syncer; no+GL account mapping storage/UI (Xero chart can be fetched but isn't mapped to Carbon accounts);+payments stubbed off; no reconciliation state; no tax-rate mapping; DELETE sync unimplemented.++**Lessons that bind the design (`.ai/lessons.md`):**++- Resolve control accounts by `accountDefault.<x>Account` **id**, never by account number/name.+ External account codes (Xero AccountCodes, QB FullName) are legitimate ONLY as integration+ mapping keys → map external code → `externalIntegrationMapping` → Carbon `account.id`.+- Chart group headers have `number = NULL` — hierarchy walks must not assume numbers.+- No N×M posting-matrix config — flat defaults + per-entity assignment with per-child override.++## Competitors Surveyed++- **SAP S/4HANA** — enterprise reference for external-posting interfaces (BAPI/IDoc), error+ queues, summarization, reconciliation; OBYC account determination as the matrix anti-pattern.+- **NetSuite** — the model sync *target*: externalId idempotent upserts, period validation,+ custom transaction types.+- **Fishbowl** — the canonical "manufacturing system of record + QB Desktop as books" add-on+ (per-transaction hybrid posting).+- **MISys Manufacturing** — SDK-based QBD manufacturing integration (subledger + batch Period+ End with review-before-post).+- **Katana / Cin7 Core (DEAR) / Unleashed / SOS Inventory / MRPeasy / Fulfil** — cloud+ operational systems with multi-provider (Xero/QBO) accounting sync engines.+- **Intuit (primary)** — QB Desktop SDK/qbXML/Web Connector specs, auth model, lifecycle.+- **Bridge vendors** — Conductor, Codat, Merge, Rutter, Apideck; open-source QBWC servers;+ Celigo/Workato/Boomi iPaaS machinery.++## Key Consensus Patterns++### 1. Hybrid posting: native documents for AR/AP, journal entries for inventory economics+- **Fishbowl**: QB Invoice + separate COGS journal entry per shipment; Item Receipt → Bill for+ purchases; JEs for adjustments/scrap/builds.+- **Cin7 Core / Unleashed / SOS / Katana**: invoices/bills as native documents; manual+ journals for COGS, stock adjustments, stocktakes, assembly/WIP moves.+- **MISys**: real-time Bills where payables must surface; everything else batch JEs.+- **Rationale**: accountants need native AR/AP documents for aging, statements, and payment+ workflows; inventory truth (and item-level detail) stays in the ops system, reaching the GL+ as value-level journals.++### 2. The ops system owns items; target items are non-posting placeholders+- **Fishbowl**: single `FB_Item` placeholder (real part number in the line description).+- **SOS / Katana**: items created as non-inventory/service types; target's inventory tracking+ OFF — both document the duplicate-COGS failure if it's left on.+- **MISys/Fishbowl**: QB Advanced Inventory (FIFO/serial-lot/EIR) must be disabled.+- **Rationale**: two systems tracking item-level inventory value double-post COGS and drift.++### 3. Account mapping is a flat page of named roles + direct per-entity overrides+- **Cin7**: ~11 named roles mapped 1:1; per-product overrides. **Fishbowl**: fixed 21-account+ wizard; per-part overrides. **MISys**: 18 accounting controls + overlay Account Sets resolved+ per-control with fall-through **Job → Item → Location → Default** (the cleanest model).+ **Unleashed**: 3 defaults + per-product/per-customer override.+- **SAP OBYC** is the maximal matrix counter-example everyone else avoids.+- **Rationale**: matches Carbon's `accountDefault` + `itemPostingGroup` design and the+ `.ai/lessons.md` no-N×M rule. The SAP lesson worth keeping: **"no mapping found" must be a+ pre-flight validation error**, not a runtime surprise.++### 4. A visible per-record sync state machine with human levers+- **Cin7**: Pending → Completed / Failed / Warning / Skipped; Failed auto-retries, Warning+ waits for review, Completed→Pending is manual re-send. **Unleashed**: Export Data page ++ variance report; Draft-in-target counts as variance. **SOS**: Preview sync (outbound queue,+ removable records). **SAP**: IDoc status 51 + BD87 edit-payload-and-reprocess. **Celigo/+ Boomi**: per-record error inbox with open/resolved/retry, edit-and-retry, bulk retry,+ resolve-without-retry, digest alerts.+- **Rationale**: at-least-once sync into accounting systems fails routinely (locked records,+ closed periods, name collisions); ops teams need an inbox, not logs.++### 5. Caller-owned external reference key; reverse, never delete+- **SAP**: OBJ_KEY/AWKEY on every posting; reversal by reference via REV_POST. **NetSuite**:+ externalId + `PUT eid:{id}` upsert. **Stripe/canon**: idempotency keys + per-record recovery+ points. **QBD**: `newMessageSetID`/`oldMessageSetID` error recovery + RefNumber/DataExt+ stamping + query-before-insert (RefNumber uniqueness NOT enforced).+- **Rationale**: dedupe across retries and crashed connections; corrections are additive+ reversing entries (Fishbowl's delete-and-replace Item Receipt dance is the anti-pattern).++### 6. Posting granularity is configurable; summarize forward, drill back always+- **Cin7**: per-channel No sync / Individual / Consolidated (daily). **MRPeasy**: documents+ per-transaction + one daily balance journal for inventory/WIP/COGS. **MISys**: Period End+ consolidation setting. **SAP**: OBCY summarization + mandatory drill-back reports.+- **Rationale**: high-volume flows need summary postings; auditors need to explain any GL+ line from source detail.++### 7. Period-close: pre-validate, park as error, optionally re-date+- **Xero**: rejects docs before the lock date (lock date queryable). **QBO**: rejects into+ closed books and **the API cannot read or set the close date** — capture it from the admin+ at connect time. **NetSuite**: optional "post to first open period, keep original date."+ **SAP/iPaaS**: park in the error queue for humans.+- **Rationale**: never silently drop or silently re-date accounting data.++### 8. Cutover is first-class+- **Cin7**: Conversion date + opening balances + load/export historical from a chosen date.+ **Fulfil**: opening trial balance import at go-live. Matches Carbon's #1057 cutover spec —+ sync must never backdate into pre-cutover/closed periods.++### 9. Continuous reconciliation+- **SAP**: control accounts + scheduled consistency checks. **Unleashed**: variance view vs+ provider balances. **Fishbowl**: point-in-time valuation-vs-GL tie-out + "the sync is the+ only writer to control accounts" rule. **Formance canon**: event-level, aggregate, and+ balance matching tiers.+- **Rationale**: drift is expected (local success + downstream failure); detect it on a+ schedule, not in an audit.++### 10. QB Desktop transport reality+- Every remote path is **QBWC polling** — Conductor/Codat/Merge/Rutter all wrap it; cloud MRPs+ simply refuse QBD (Katana explicitly; Fishbowl Drive is QBO-only). Whoever integrates QBD+ owns (or rents) a SOAP endpoint, a per-company work queue, and the customer-side Windows+ failure modes.++## Answers to Research Questions++1. **What does QB Desktop Enterprise 24.0 expose, and does OAuth apply?** Two mechanisms only:+ the local COM SDK (qbXML ≤16.0) and the QuickBooks Web Connector for cloud apps. No REST,+ no webhooks (Desktop REST/Sync Manager died in 2016). **OAuth is QBO-only.** QBD auth =+ .QWC file + out-of-band password + session tickets + the in-QB Application Certificate+ grant (admin, single-user, unattended-mode option). (Intuit QBWC Programmer's Guide, SDK+ release notes.)+2. **How does a cloud SaaS reach on-prem QBD?** QBWC polling our SOAP endpoint — self-hosted+ or rented. Build = SOAP state machine + full qbXML layer + customer-support tail (no+ maintained Node OSS starting point). Buy = Conductor ($49/mo/company file, TS SDK,+ real-time, best mfg coverage, powers Ramp) >> Rutter (credible, enterprise-priced) > Codat+ (batch windows, banking pivot) > Merge/Apideck (thin/new). Autofy's 2024 shutdown is the+ vendor-risk case study → isolate any vendor behind Carbon's own provider interface.+3. **What do competitors sync and how do they post?** Consensus matrix: customers/vendors+ two-way or push; items push as non-posting types; SO→invoice and receipt→bill as native+ documents; payments pull or tri-state; COGS/adjustments/WIP as journal entries+ (per-transaction default, daily-summary option). See Consensus Patterns 1–3.+4. **Standard sync-engine architecture?** Outbox written transactionally with the business+ event; per-record state machine (pending → pushed → confirmed → failed) with recovery+ points; target-side external-ID idempotency; visible error inbox with retry/skip/re-send;+ delta cursors; scheduled reconciliation (document-level + aggregate). See Patterns 4–6, 9.+5. **qbXML coverage/limits for Carbon?** Everything needed is writable (customers, vendors,+ items incl. assemblies + builds, invoices, credit memos, sales orders, receive payments,+ bills, vendor credits, bill payments, POs, item receipts, journal entries, inventory+ adjustments, UoM, classes, custom fields). Limits: JE ≤1 AR/AP line with entity required;+ name-length caps (31/41); one currency per customer/vendor; RefNumber not unique; payroll+ read-only; error recovery via newMessageSetID. See the QBD surface section.+6. **QBD lifecycle → target QBO too?** Enterprise 24.0 is the terminal but actively-updated+ Desktop platform (no announced EOL, still sold); the fork is permanent — QBO/IES is a+ wholly different API. Yes: design the engine for both from day one; the QBO provider stub+ already exists and shares nothing with QBD but the brand.++## Competitor-Specific Details++### Fishbowl — the canonical QB Desktop manufacturing integration++- **Connection**: QB Desktop SDK (qbXML/COM) on the **same machine** as Fishbowl Server (QB+ single-user, dedicated "Fishbowl" QB user, "allow access even if QuickBooks is not running");+ LAN reach via their own `Fishbowl Nexus.exe` bridge on the QB machine. Their cloud product+ (Fishbowl Drive) supports **QBO only** — even Fishbowl never solved cloud→QBD.+- **Master data**: Fishbowl owns inventory/SOs/POs; QB keeps chart of accounts, AR/AP+ processing, payments. QB's own inventory + PO features are turned OFF. Items are **not+ mirrored 1:1** — exported documents use a single placeholder item `FB_Item` with the real+ part number in the line description; dollars are directed per-line to mapped accounts.+ Customers/vendors are created in QB lazily (on first exported order), matched by name;+ optional collapse-all to a generic `FB_Customer`.+- **Posting model (hybrid, per-transaction)**: ship/invoice SO → QB **Invoice** (Dr AR / Cr+ Income) **plus a separate Journal Entry** (Dr COGS / Cr Inventory Asset); receive PO → QB+ **Item Receipt**, then reconciling the bill in Fishbowl **creates the QB Bill and deletes+ the Item Receipt**; adjustments/cycle counts/scrap → per-event JEs to mapped accounts+ (Inventory Adjustment, Scrapped Inventory); work orders → **JEs only, no WIP account in QB**+ (labor/overhead move from mapped expense accounts into FG asset value at completion);+ standard-cost variance → required Cost Variance account. No period summarization (only+ POS-checkout sales-receipt batching).+- **Account mapping**: integration wizard forces mapping of a fixed set of **21 named+ accounts** (auto-create in QB or choose existing); defaults by part type + optional+ per-part/per-product account overrides.+- **Sync mechanics**: pull-the-trigger or scheduled-nightly export with three modes —+ **Standard** (everything completed since last successful export), **Repost** (date range;+ loud duplicate warning), **Mark as posted** (skip; irreversible). Pre-flight validation of+ referenced entities. Documented tie-out: point-in-time Asset Valuation by Account vs QB+ Inventory Asset balance ("can only be reconciled as of RIGHT NOW"); operating rule that the+ sync is the only writer to control accounts.+- **Known failure modes**: the unlinked Invoice + COGS-JE pair (a date edit in QB strands COGS+ in another period); Item-Receipt→Bill delete-and-replace choreography doubles payables if a+ human flips the receipt in QB; Accountant's Copy blocks all posting ("Dividing date error");+ closed-period rejects (QBO 6210) resolved by reopening period or irreversibly marking+ posted.++### MISys Manufacturing — subledger + batch Period End (the other QBD reference)++- **Connection**: QB Desktop SDK, QB installed **on the same machine** as each MISys client+ performing integration ops (briefly consumes one QB user license). QBO variant uses REST ++ OAuth2.+- **Split**: QB owns customers/sales/AR/AP/GL + finished-goods sales items; MISys owns raw+ materials, BOMs, WIP, production, purchasing. Item mapping is explicit and N:N with template+ items; GL accounts must pre-exist in QB with **exactly matching name+number** (checker ++ auto-create provided). QB Advanced Inventory (FIFO/serial-lot) must stay disabled.+- **Posting model (subledger + batch)**: every MISys transaction writes Dr/Cr pairs to an+ internal **Master Transaction Log** against **18 named "Accounting Controls"** (Inventory,+ WIP, PO Liability/GRNI, Purchase Price Variance, Sales Transfer Clearing…), flagged "Not+ Posted." **Period End** posts a chosen date range to QB as journal entries and flags rows+ Posted (the idempotency key); **consolidation level is configurable** (full detail ↔+ summarized). WIP reaches QB only via these JEs. Real-time native docs where payables must+ surface: PO Invoice → QB Bill; finished-goods "Transfer to Sales" → Bill + self-paying+ Vendor Credit through a clearing account against a special MISys vendor (works, but+ bewilders accountants — an anti-pattern to avoid). Job costing maps to auto-created QB+ Classes.+- **Account mapping**: default control-account set + named **overlay Account Sets** assignable+ to Job, Item, or Location, resolved **per control with fall-through Job → Item → Location →+ Default** — the cleanest override model observed, and exactly Carbon's flat-defaults+overrides+ doctrine.+- **Sync mechanics**: date-ranged batch with **Print Unposted** (review-before-post) and+ post-run subledger report; "Prior Journal Entries" checkbox sweeps stragglers. Failure mode+ to avoid: mid-Period-End failure requires **restoring both databases** (no per-entry+ recovery).++**Patterns to copy (synthesized from both):** hybrid posting (native AR/AP docs + JEs for+inventory economics); subledger with per-row posted-flag idempotency and date-ranged posting+runs with configurable consolidation; review-before-post preview; export-since-last-success+semantics with explicit Repost/Mark-as-posted escape hatches; pre-flight entity validation;+lazy JIT creation of customers/vendors; GRNI/clearing accounts for timing gaps; published+journal-entry catalog per event type; documented point-in-time tie-out procedure + "sync is+the only writer to control accounts" rule.++**Patterns to avoid:** two unlinked target transactions per business event without a shared+correlation key; delete-and-replace choreography; fake-vendor document contortions; irreversible+mark-as-posted; all-or-nothing batch failure requiring DB restore; no drift detection.++### Cloud MRP/inventory sync engines (Katana, Cin7 Core, Unleashed, SOS, MRPeasy, Fulfil)++**Katana (QBO + Xero; explicitly no QBD).** SO → invoice, PO → bill behind toggles; COGS+pushed as a **journal entry on delivery** (QBO only); items pushed as **non-inventory** items;+flat default-account pickers + one override dimension ("Accounts by Category"); tax-rate+mapping is mandatory before activation (non-US). Cautionary tale: the COGS/stock journal+engine was built for QBO and **never ported to Xero** (Xero users are told to make manual+monthly journals) — per-provider feature skew is what a generic posting engine prevents.++**Cin7 Core (ex-DEAR) — the reference implementation.**+- **Account Mapping** page: 1:1 mapping of ~11 named roles → provider accounts (Inventory+ Control, COGS, Tax Liability, Customer Credit, In-Transit, Unrealised FX, Inventory+ Discrepancy, Default Revenue, WIP, Supplier Deposits, Gift Card Liability; + GRNI/GINR if+ accrual mode). Per-product overrides for inventory/revenue/COGS accounts.+- **Documents vs journals**: invoices/credit notes → native Xero/QBO invoices (with a "Xero+ Invoice Status: Draft or Authorised" setting); COGS → manual journal per authorized shipment;+ assembly/disassembly → WIP journals (components → WIP on start, WIP → FG on complete); stock+ adjustments/stocktakes → journals vs Inventory Discrepancy.+- **Per-channel granularity**: each sales channel independently picks No sync / Individual /+ Consolidated (daily summary) for invoices and COGS — high-volume channels get summarized+ postings.+- **Payments**: tri-state config — bidirectional / pull-only / push-only.+- **Sync state machine** (Synchronization Report): per-record **Pending → Completed / Failed /+ Warning / Skipped**; Failed auto-retries each sync, Warning waits for human review, Skipped+ is permanent opt-out, Completed→Pending is the manual re-send lever. COGS Maintenance can+ **void (recall) prior COGS exports for a date range**.+- **Duplicates**: on ambiguous API failure (no response), Cin7 marks Completed anyway to avoid+ duplicates and relies on manual Completed→Pending recovery — at-most-once bias. Dependency+ ordering enforced (customer + items sync before their invoice).+- **Cutover**: Opening Balances + "Conversion date"; "Load historical transactions" (pull, ≤1+ yr) and "Export historical data" (push from chosen start date). Period locks: pre-flight+ warning icon on transactions dated before the Xero lock date / QBO closing date.++**Unleashed (Xero + QBO).** Real-time push on transaction completion; bills created on **goods+receipt** (not PO creation) with configurable target status; shipment/stocktake/re-cost/+assembly journals to mapped accounts; minimal mapping page (Sales, COGS, Stock-on-Hand) ++per-product/per-customer COGS override; **Export Data** page with per-transaction status,+error reasons, Export All retry, and a **variance report** vs provider balances. Stricter+invariant worth noting: a document left in Draft in Xero counts as a **variance** — sync isn't+"done" until the target doc is approved.++**SOS Inventory (QBO-only, "QBO owns the GL").** Two-way sync of masters and AR/AP docs; all+items non-inventory/service in QBO; shipment → COGS journal entry; "Post COGS to QuickBooks"+checkbox with documented duplicate-COGS failure mode if QBO inventory tracking is also on.+Sync machinery: auto-sync frequency, **Preview sync** (outbound queue with record removal),+Sync errors list, three-cycle grace before auto-correction.++**MRPeasy (QBO + Xero).** Cleanest two-layer split: (1) document sync — invoices/bills within+~5 min, auto-creating missing customers/items; (2) optional **daily balance-level journal+sync** — one summarized posting per day for inventory on hand, WIP (incl. labor + applied+overhead), and COGS. Summary journals make per-transaction idempotency concerns mostly vanish.++**Fulfil.io (closest structural analog to Carbon — own full GL).** Markets per-event real-time+JEs in its own ledger as superior to external sync; the outbound bridge is deliberately+**minimal and transitional**: push sales/purchase invoices to QBO/Xero "on a schedule for a+clean monthly close" during a migration year, plus inbound opening-trial-balance import at+go-live. Position: once the ops system has its own GL, external sync shrinks to AR/AP document+push for the accountant, not full ledger mirroring.++### SAP S/4HANA — external-posting interface (the enterprise reference)++- **Posting API + dry-run**: `BAPI_ACC_DOCUMENT_POST` with paired `BAPI_ACC_DOCUMENT_CHECK`+ (validate-before-post). Even SAP's dry-run is imperfect (some validations only fire on real+ post) — so real-post errors must be handled regardless.+- **Durable staging + error queue**: async path via `ACC_DOCUMENT` IDoc; failures land at+ status 51 in a reprocessing workbench (BD87) where ops can **edit the staged payload and+ replay**. Failed postings are never lost — per-record status, editable, replayable.+- **Idempotency via caller-owned reference key**: external system's identity travels in+ `OBJ_TYPE/OBJ_KEY/OBJ_SYS` → stored on the FI doc header (`BKPF-AWTYP/AWKEY`); dedupe and+ reversal both anchor on it. Reversal is `BAPI_ACC_DOCUMENT_REV_POST` **by reference to the+ original external key** — external documents are never edited/deleted in FI, only reversed+ through the interface by the originating system.+- **Summarization**: OBCY/TTYPV summarizes interface postings (to stay under FI's 999-line+ limit), but never merges debit with credit lines, and SAP pairs summarization with+ **drill-back reports** so a GL doc can always be explained by subledger items. Summarize+ forward, always drill back.+- **Account determination (OBYC)**: the maximal valuation-class × transaction-key matrix — the+ archetype Carbon deliberately simplifies from. Its real lesson: "no mapping found" must be a+ **pre-post validation error** in the pipeline, not a runtime surprise.+- **Reconciliation as a standing control**: control accounts + periodic consistency-check+ programs (SAPF190 etc.) comparing documents to balances; subledger↔GL reconciliation is+ scheduled, not incident-driven.++### NetSuite — the model sync target++- `externalId` on every record; REST `PUT /journalEntry/eid:{id}` is a true **idempotent+ upsert** — Oracle's own guidance for duplicate prevention. (Async REST also supports a+ `NetSuite-Idempotency-Key` header — secondary source only.)+- Closed periods reject integration writes; NetSuite's built-in remedy is a **preference**:+ "Default Posting Period When Transaction Date in Closed Period" = first open period (keeps+ the original transaction date). *Override Period Restrictions* bypasses **locked** but never+ **closed** periods.+- **Custom transaction types**: named, separately-permissioned journal-like documents so synced+ postings are visibly "from system X" rather than anonymous JEs — better auditability.++### iPaaS blueprints (Celigo / Workato / Boomi) — the ops UX bar++Consensus machinery across all three: a **per-record error inbox** (not logs) with+open/resolved/retry states, error message + payload, **edit-payload-and-retry**, bulk retry+(Celigo: up to 20k), **resolve-without-retry** (for things fixed manually in the target),+assignment/tags for triage, digest email notifications (~15 min), connection offline/online+alerts, and **delta cursors** (`lastExportDateTime`-style, advancing only on successful runs).+ID cross-referencing is bidirectional writeback (store target ID on source record and vice+versa) with an explicit flag to suppress writeback-triggered sync loops (Carbon's+`withTriggersDisabled()` is the same idea).++### Integration-engineering canon (applies directly to posting sync)++- **Transactional outbox** (microservices.io/Debezium): posting intent written in the same DB+ transaction as the journal; relay delivers at-least-once; target dedupes.+- **Stripe-style idempotency keys + per-record state machine** (brandur.org): key row stores+ params/result/**recovery point**; "once we make our first foreign state mutation… we+ shouldn't lose track of it"; background completers/reapers make it passively safe. Mapped to+ GL sync: `pending → pushed → confirmed → failed` lifecycle per posting.+- **Checkpointed replayable sync** (Airbyte/Fivetran): at-least-once + destination dedupe by+ key + cursor; idempotence as the failure-proofing primitive.+- **Continuous reconciliation** (Formance/Leapfin): three tiers — event-level matching by+ reference ID (catches missing docs), aggregate matching of per-period/per-account totals+ (catches drift), position matching of balances. Drift is expected whenever a local write+ succeeds but the downstream push fails; reconcile continuously.++### Period-close interaction — cross-vendor consensus++- SAP: park in error queue (BD87), human re-opens period or re-dates and replays.+- NetSuite: optional auto-post to first open period, preserving original transaction date.+- **Xero**: API rejects docs dated before the lock date ("document date cannot be before the+ period lock date"); org lock dates are queryable.+- **QuickBooks Online**: rejects writes into closed books AND **the API can neither read nor+ set the close date** — Intuit's official guidance is to capture the close date from the+ admin at connect time and pre-validate client-side.+- Consensus: never silently drop or silently re-date; either park-as-error with a remediation+ path (default) or an explicit per-connection "post to first open day, preserve original date+ in reference/memo" policy.++## QuickBooks Desktop Integration Surface (Primary-Source Findings)++Scope note: "Manufacturing & Wholesale" is an industry *flavor* of QB Desktop Enterprise 24.0+(same binary, industry menus/reports). Integration surface is identical to any US Enterprise+24.0.++### Mechanisms — definitively++- Exactly two sanctioned mechanisms, both funneling into the same XML request processor:+ 1. **QB Desktop SDK** (`QBXMLRP2.dll` COM component, same machine/LAN): raw **qbXML** or the+ QBFC typed wrapper. Latest SDK = **16.0**; Enterprise 24.0 speaks qbXML ≤ **16.0**.+ 2. **QuickBooks Web Connector (QBWC)**: Intuit's Windows app that acts as a SOAP **client**+ polling *your* HTTPS service and ferrying qbXML to the local request processor. **This is+ the only supported way for a cloud app to talk to QB Desktop.** Outbound HTTPS only+ (firewall-friendly); QBWC version 34.x for the QB 2024 line — maintained but functionally+ frozen (recent releases are cert renewals + a DNS fix).+- **No REST API, no webhooks, ever**: Intuit's hosted Desktop REST API + Sync Manager were+ discontinued March 1, 2016 and never replaced. The SDK's event subscriptions deliver to a+ local COM callback only — useless for cloud. Change detection = polling with+ `ModifiedDateRangeFilter`. All REST façades (Conductor, Codat, …) run QBWC or an equivalent+ local agent underneath.++### Auth — the OAuth answer++- **OAuth does not apply to QB Desktop at all.** OAuth2 + realmId + refresh tokens is+ exclusively QuickBooks Online. QBD needs no Intuit app registration; authorization is+ entirely local, two layers:+ 1. **QBWC ↔ our server**: we issue a **.QWC file** (AppName, AppURL [must be HTTPS with a+ public-CA cert], AppSupport [same domain], UserName, **OwnerID** GUID [one per app],+ **FileID** GUID [stamped into the company file as a private DataExt on first connect],+ QBType, optional Scheduler/RunEveryNMinutes, AuthFlags [0x8 = Enterprise],+ UnattendedModePref, PersonalDataPref). The **password is NOT in the file** — the user+ types it into QBWC (encrypted into the registry); we issue it out-of-band. At runtime+ QBWC calls `authenticate(user, password)` → we return an opaque **session ticket** (the+ only credential) + optionally a company-file path / "none" / "nvu" / "busy".+ 2. **App ↔ QuickBooks**: first connection triggers the **Application Certificate dialog** —+ only the QB Admin in single-user mode can grant access, including personal-data access+ and **unattended mode** ("Yes, always; allow access even if QuickBooks is not running").+ Grants live under Integrated Applications; revocable; enforcement via status codes+ (3261 sensitive data, 3301 interactive-only requests).++### QBWC protocol contract (what our SOAP service implements)++- Eight callbacks — `serverVersion`, `clientVersion`, `authenticate`,+ `sendRequestXML(ticket, strHCPResponse, companyFile, qbXMLMajorVers, qbXMLMinorVers)`,+ `receiveResponseXML(ticket, response, hresult, message) → int percentDone` (0–99 = loop,+ 100 = done, negative = error), `connectionError`, `getLastError`, `closeConnection`.+ WSDL namespace MUST be `http://developer.intuit.com/`; parameter names are load-bearing.+- First `sendRequestXML` of a session carries HostQuery/CompanyQuery/PreferencesQuery results ++ the file's max qbXML version — version requests per client.+- Strictly serial request→response loop; **one update session at a time per company file**;+ user-controlled polling schedule (UI floor 1 min; QBWC must be running on the customer's+ Windows machine — it is NOT a Windows service). Design the server as a **per-company FIFO+ work queue**.+- Large queries: iterator pattern (`iterator="Start"`, `MaxReturned`, `iteratorID`,+ `iteratorRemainingCount`).++### qbXML coverage for Carbon's needs (Enterprise 24.0, spec ≤16.0)++- **All writable**: Customer/Vendor Add/Mod/Query, ItemInventory (with Income/COGS/Asset+ account refs), ItemNonInventory/Service/OtherCharge/Group, **ItemInventoryAssembly incl. BOM+ + BuildAssemblyAdd** (Premier/Enterprise), InvoiceAdd (line ItemRef, ClassRef, link to SOs),+ CreditMemoAdd, **SalesOrderAdd (Premier/Enterprise only)**, ReceivePaymentAdd (apply to+ invoices via AppliedToTxn/SetCredit or IsAutoApply), BillAdd, VendorCreditAdd,+ BillPaymentCheck/CreditCardAdd, PurchaseOrderAdd, ItemReceiptAdd, **JournalEntryAdd/Mod**,+ InventoryAdjustmentAdd (serial/lot 11.0+), TimeTrackingAdd, UnitOfMeasureSet, Class,+ DataExt custom fields.+- **JournalEntry constraints**: debits must equal credits; an A/R-account line requires a+ Customer, an A/P line requires a Vendor; **max ONE line per JE may post to an AR or AP+ account**; foreign-currency JEs restricted to one foreign currency (practitioner consensus).+- **NOT writable**: payroll (reports/queries + TimeTracking input only), attachments,+ bank feeds, some Enterprise Advanced-Inventory UI features (landed cost, pick-pack-ship+ actions). QB's own FIFO/serial-lot/EIR features conflict with external inventory sync+ (Fishbowl/MISys both require them off).+- **References & limits**: every `*Ref` takes ListID (opaque, stable — prefer; store it) and/or+ FullName (colon-joined hierarchy; exact punctuation match). Account name ≤31 chars/level;+ customer/vendor ≤41; RefNumber ≤11 on most txns and **uniqueness is NOT enforced via SDK**;+ requestID ≤50 chars. Multicurrency: transaction currency comes from the customer/vendor+ (fixed once used) → one QB name per currency; we set ExchangeRate.+- **Error semantics**: statusCode + statusSeverity (Info/Warn/Error) per response. The ones a+ sync meets: **3100** name not unique (names share ONE namespace across customer/vendor/+ employee/other), **3120** object not found, **3140** invalid reference, **3200** stale+ EditSequence (re-query, re-apply), **3175/3176** object in use / lock failed (retry-later+ family), **3170/3171** closing-date/condense lock, **3180** generic save failure (often+ transient), 3250 feature not enabled, 3260-series permissions. Connection failures are COM+ HRESULTs via `connectionError` (0x8004040A different file open, 0x80040401 can't access QB…).+ `onError="stopOnError|continueOnError"` per message set; **no rollback support**.+- **Idempotency**: `requestID` echo is correlation only. TRUE dedup across dropped connections+ = **qbXML error recovery**: send `newMessageSetID` (GUID) on every writing message set,+ persist until the response is processed; after a disruption ask with `oldMessageSetID` — QB+ stores the last message-set ID + response, so we learn whether writes landed and get the+ stored response instead of double-posting (mandated by the QBWC guide for web services).+ Belt-and-braces: stamp Carbon's document ID into RefNumber/Memo/DataExt and query-before-+ insert.++### Lifecycle reality (mid-2026)++- **Enterprise 24.0 is the current, terminal Desktop platform**: Intuit's Firm of the Future+ states Desktop Plus 2024 / Enterprise 24.0 "were the last annual platform releases" —+ Desktop moved to **continuous updates on the 24.0 platform** (R-releases, e.g. R21 June+ 2026; feature drops like "October 2025 release"). **Enterprise 25.0/26.0 do not exist.**+ Enterprise is still sold to new customers (the Sept-2024 stop-sell hit only Pro/Premier/Mac).+ QB Desktop 2023 services died May 31, 2026; **Enterprise 24.0 has no announced end date**+ ("won't be discontinued in May 2027" per Intuit-adjacent coverage). SDK 16.0 + QBWC are+ maintained-but-frozen and remain the supported mechanism.+- **Rightworks hosting** ("Enterprise with cloud access"): same SDK/QBWC inside the hosted+ Windows desktop; QBWC installed from their app catalog, auto-start via their support.+- **Intuit Enterprise Suite (IES)** is a separate cloud product on the QBO platform — standard+ QBO API (OAuth2/REST/webhooks), one realmId per entity. A customer migrating QBD → IES+ switches to the QBO adapter entirely.++## Bridge / Build-vs-Buy Matrix (cloud → on-prem QB Desktop)++**The core fact:** there is exactly one Intuit-approved remote channel into QB Desktop — the+**QuickBooks Web Connector (QBWC)**, a Windows app next to QuickBooks that *polls YOUR HTTPS+SOAP service* and relays qbXML via COM. Every vendor option (Conductor, Codat, Merge, Rutter,+Apideck) is QBWC + qbXML under the hood. Build-vs-buy = who operates the SOAP service, the+qbXML translation layer, and the customer-support burden.++| Option | Effort | Ops burden | Mfg entity coverage | GL journals | Cost | Vendor risk | Customer install |+|---|---|---|---|---|---|---|---|+| **Build: self-hosted QBWC SOAP endpoint** | Very high (SOAP session state machine + qbXML layer per entity; no maintained Node OSS — `qbws`/`quickbooks-js` dead, only Ruby `qbwc` gem alive as of 2026-04) | High — we own QBWC support tickets (QBWC1085, restart-after-reboot, TLS certs, version handshake), encoding/field-limit quirks | Full qbXML surface, but we write every entity | Yes (JournalEntryAdd, we implement) | Engineering + support time | None (Intuit protocol, ~20 yrs stable) | Moderate: install QBWC, load .qwc + password, keep PC on (QBWC is NOT a Windows service) |+| **Conductor (conductor.is)** | Low — typed TS SDK (`conductor-node`, ~21k dl/wk, very active), REST, real-time request/response | Low — they own qbXML/QBWC/session layer + end-user error guides | **Best**: 130+ object types incl. sales orders, inventory adjustments, build assemblies, price levels, UoM sets | Yes — documented | **$49/mo per company file** (homepage, Jul 2026), volume tiers | Small startup, funding opaque; mitigated by **Ramp's QBD integration running on Conductor** | Low — guided auth-URL flow; Rightworks-hosted QBD supported |+| **Codat** | Medium | Medium — **batch sync windows only** (default nights; from 2026-01 even initial fetch waits) — not real-time | Broad canonical model; QBD-specific JE-push matrix unverifiable (docs moved) | Push in model; verify for QBD | Opaque; ~$24k/yr median (Vendr) | Medium-high — pivoted to commercial-banking intelligence; SaaS accounting API now secondary | Low-med — one .exe bundling QBWC + auto-run, auto-restarts (better than raw QBWC) |+| **Rutter** | Medium | Medium | Wide QBD read+write incl. POs and sales orders | Yes — JE GET/POST documented for QBD | Custom; est. $12–24k/yr platform + $30–50/connection/mo | Medium (fintech-focused; QBD one of 60+ platforms) | Low-med |+| **Merge.dev** | Medium | Medium | QBD connector exists; field-level coverage/JE writes publicly undocumented — confirm | Unverified | 3 free accounts; $650/mo ≤10; $65/account | Medium (big horizontal vendor; QBD is long-tail) | Low-med (QBWC linking flow) |+| **Apideck** | Medium | Medium | New 2026 connector, unproven in production | Claimed | Self-serve tiers | Medium (too new) | Low-med |+| **Transaction Pro / IIF (fallback)** | Trivial (we generate CSV/IIF) | Manual for customer each cycle | Lists + 20 txn types incl. JEs | Yes, manual; IIF JEs risky (no validation, **no undo**, lines re-sorted) | TPro license / IIF free | Low | High recurring manual effort |++**What comparable products chose:** Ramp → bought (Conductor). ServiceTitan → built its own+QBWC integration (and carries a whole support section for QBWC troubleshooting — the ops+tail). Fishbowl → co-located desktop software using the local SDK (not replicable for cloud).+Katana → refused to support QBD at all. Mosaic → discontinued QBD citing Intuit's desktop+phase-out. Autofy (a bridge many SaaS depended on) → **shut down June 2024, killing dependent+integrations overnight** — the canonical vendor-risk case study, and the argument for hiding+any bridge vendor behind Carbon's own provider interface so a swap is not a rewrite.++**QBD market reality (mid-2026):** Intuit stopped selling Pro/Premier to new US subscribers+Sept 2024, but **Enterprise is exempt and still sold**; QBD 2023 support ended May 31 2026;+Enterprise 24 support runs to ~May 2027 (one source says Sept 2027 — unverified). Roughly 17%+of US SMBs still on QBD; ~268k companies on Enterprise (secondary sources, directional).+Rightworks-hosted QBD has **no API of its own** — same Web Connector inside the hosted desktop,+so any choice must be (and Conductor/Codat are) Rightworks-compatible.++## Recommended Approach for Carbon++1. **Treat "QuickBooks" as two providers.** `quickbooks-online` (OAuth2/REST — the existing+ `ee/src/quickbooks/config.tsx` stub is already aimed here) and `quickbooks-desktop` (Web+ Connector transport). They share nothing but the brand (Intuit's own docs). Sequence QBO+ after the engine is generic — it's nearly free and the bigger funnel — but QBD is the+ differentiator (no modern cloud MRP serves it; Fishbowl's 21-account model is the incumbent+ to displace).++2. **Harden the existing core rather than rebuild** (it's already 70% of a sync engine):+ generalize `ProviderCredentialsSchema` beyond `oauth2` (add a `webconnector` variant:+ username, password hash, ownerId/fileId GUIDs, qbXML version); move tenant discovery,+ pagination, and date parsing fully behind the provider interface; apply per-company+ `syncConfig` (currently hardcoded to `DEFAULT_SYNC_CONFIG`); keep `ENTITY_DEFINITIONS`+ dependency-graph JIT sync (it mirrors Cin7's "customer + items before invoice" rule).++3. **Add the durable sync-run layer the canon demands** (SAP IDoc/BD87, Stripe/brandur,+ Celigo, Cin7): an outbox row written transactionally with the source change, per-record+ lifecycle `pending → pushed → confirmed → failed/skipped`, provider-agnostic **error inbox+ UI** (retry, edit-context-and-retry, skip, re-send, bulk actions — Cin7's status semantics),+ and idempotency keys stored on the mapping row. This is required for QBD (its transport is+ an inverted poll — QBWC drains our queue) and is the reliability/UX upgrade Xero sync needs+ anyway. REST providers drain the queue immediately via Inngest; QBD drains on QBWC poll (or+ synchronously via a bridge vendor).++4. **Posting sync = journal push for inventory economics + the existing document sync for+ AR/AP** (Consensus Pattern 1). Add a `journalEntry` entity type + syncer sourcing Carbon's+ **Posted** journals, filtered by `sourceType`: push journals for receipt/shipment-COGS/+ adjustment/production/variance events; do NOT push journals whose documents already sync+ (sales invoice, purchase invoice, payment) — that double-posts. Per-company consolidation+ setting: Individual (default) vs Daily summary per account (Cin7/MRPeasy). Reversals push+ as reversing entries referencing the original external key — never delete/edit in the+ target.++5. **Account mapping**: map Carbon `account.id` ↔ provider account via+ `externalIntegrationMapping(entityType='account')` (per `.ai/lessons.md`: external codes+ are legitimate only as mapping keys; resolve to Carbon account **id**). Settings UI = flat+ list of Carbon's named default roles + chart picker (the accounts route already fetches+ Xero's chart). **Pre-flight validation**: unmapped account, missing tax mapping, or+ locked-period date = a Warning/Failed row before push, not a provider error after.++6. **Period-close policy per connection** (Pattern 7): store the target's lock/close date+ (queryable for Xero; **manually captured for QBO** — its API can't read it; QBD rejects via+ statusCode 3170 closing-date lock), pre-validate, default **park-as-error**, optional+ "re-date to first open day, original date in memo/reference" (NetSuite pattern).++7. **QBD transport: rent first, isolate always.** Start with **Conductor** ($49/mo per company+ file, TypeScript SDK, real-time, journal entries + sales orders + inventory adjustments ++ build assemblies documented, Rightworks-compatible, powers Ramp) behind Carbon's own+ provider interface, so a later swap to a self-hosted QBWC endpoint (or Rutter) is a+ transport change, not a rewrite — the Autofy shutdown is the cautionary tale for naked+ vendor coupling. Self-hosting QBWC is viable in the Node stack later (the SOAP surface is+ 8 methods; the cost is the qbXML entity layer + customer-side support tail: keep-PC-on,+ QBWC-not-a-service, QBWC1085, cert management). Decision gate: Conductor contract/DPA+ review + a spike proving JournalEntryAdd + InvoiceAdd round-trips.++8. **Positioning for QBD customers = "Carbon is ops, QuickBooks is the books"** (Fishbowl/+ MISys segment). Carbon's own GL keeps running (it is the subledger-of-record and the+ drill-back source, like MISys's Master Transaction Log); what syncs out is documents ++ value journals. Do 1:1 **non-inventory items** in QBD (Enterprise list limits are high;+ more legible than Fishbowl's FB_Item placeholder), QB inventory tracking OFF, documented+ as a setup prerequisite with an activation checklist (tax mapping, account mapping,+ conversion date — Pattern 8, aligning with cutover spec #1057).++9. **Reconciliation job** (Pattern 9): scheduled comparison of per-account/per-period totals+ (Carbon GL vs provider trial balance) + external-ID presence checks, surfacing drift in the+ integration UI (Unleashed's variance report). Operating rule in docs: the sync is the only+ writer to mapped control accounts.++10. **Sequencing**: (A) engine hardening + sync-run/outbox layer + error inbox; (B) posting+ sync shipped **on Xero first** (REST, already-live provider — proves account mapping,+ journal push, consolidation, reconciliation); (C) QBO provider (reuses OAuth infra ++ document/journal syncers); (D) QBD provider via Conductor (entity sync + posting), with+ the self-host QBWC option held in reserve. Avoid Katana's fate (a posting engine built+ for one provider and never ported) by keeping every posting feature in the core, not the+ provider.++## Open Questions (carried to the spec)++1. **Build vs rent the QBD transport** — recommendation: rent (Conductor) behind our+ interface; needs Brad's sign-off (production dependency + per-file cost).+2. **Scope of "QB owns the books" mode** — for QBD/QBO customers, does Carbon suppress its own+ AR/AP-close workflows (Fulfil's minimal-bridge stance) or run full parallel books with+ document sync? Recommendation: full Carbon GL stays on; sync is outbound-only for+ journals + two-way for AR/AP documents per existing `DEFAULT_SYNC_CONFIG` owners.+3. **Default consolidation granularity** — per-transaction (Cin7/Fishbowl) vs daily summary+ (MRPeasy). Recommendation: per-transaction default, per-company toggle.+4. **Item representation in QBD** — 1:1 non-inventory items (recommended) vs Fishbowl-style+ placeholder item; affects invoice legibility in QB.+5. **Employee/time sync** — TimeTrackingAdd exists in qbXML; in scope for payroll-adjacent+ customers or deferred?++## Sources++**Intuit primary (QBD surface, auth, lifecycle)**+- QBWC Programmer's Guide: https://static.developer.intuit.com/qbSDK-current/doc/pdf/QBWC_proguide.pdf+- QBWC release notes (34.x / 33.x): https://static.developer.intuit.com/resources/quickbooksWebconnector/QBWC_ReleaseNotes_34_R0_1001_27.pdf · https://static.developer.intuit.com/resources/quickbooksWebconnector/QBWC_ReleaseNotes_33_R0_10015_91.pdf+- SDK 14/15 release notes: https://static.developer.intuit.com/resources/ReleaseNotes_QBXMLSDK_14_0.pdf · https://static.developer.intuit.com/resources/ReleaseNotes_QBXMLSDK_15_0.pdf+- SDK download/compatibility: https://developer.intuit.com/app/developer/qbdesktop/docs/get-started/download-and-install-the-sdk · https://developer.intuit.com/app/developer/qbdesktop/docs/get-started/sdk-compatibility-with-quickbooks-releases+- Get started with QBWC: https://developer.intuit.com/app/developer/qbdesktop/docs/get-started/get-started-with-quickbooks-web-connector+- Status codes appendix: https://developer.intuit.com/app/developer/qbdesktop/docs/develop/exploring-the-quickbooks-desktop-sdk/status-codes-in-response-messages+- Iterators: https://developer.intuit.com/app/developer/qbdesktop/docs/develop/exploring-the-quickbooks-desktop-sdk/query-requests-and-responses+- Objects/operations list: https://developer.intuit.com/app/developer/qbdesktop/docs/additional-reference/quickbooks-objects-and-operations-accessible-with-the-sdk+- Assembly/BuildAssembly tutorial: https://developer.intuit.com/app/developer/qbdesktop/docs/develop/tutorials/the-assemblyitem-and-buildassembly-requests+- Multicurrency tutorial: https://developer.intuit.com/app/developer/qbdesktop/docs/develop/tutorials/using-the-multicurrency-feature-with-the-sdk+- Desktop REST/Sync Manager discontinuation: https://blogs.intuit.com/blog/2015/12/03/3-months-to-go-timeline-to-discontinue-the-quickbooks-desktop-rest-api-and-intuit-sync-manager/+- Stop-sell + service discontinuation policy: https://quickbooks.intuit.com/learn-support/en-us/help-article/new-subscriptions/us-quickbooks-desktop-sold-july-2024/L5lkQNq7L_US_en_US · https://quickbooks.intuit.com/learn-support/en-us/help-article/feature-preferences/quickbooks-desktop-service-discontinuation-policy/L17cXxlie_US_en_US+- Continuous-release model (last annual release): https://www.firmofthefuture.com/product-update/quickbooks-desktop-improvements/+- Field length limits: https://quickbooks.intuit.com/learn-support/en-us/help-article/printing-preferences/character-limitations-fields-quickbooks/L7eIy5gE3_US_en_US+- Rightworks hosting: https://quickbooks.intuit.com/learn-support/en-us/help-article/login-password/right-networks-hosting/L8jM0SDDj_US_en_US · https://helpdesk.rightworks.com/s/article/QuickBooks-Web-Connector+- IES API stance: https://blogs.intuit.com/2024/11/25/common-questions-about-building-apps-for-intuit-enterprise-suite/+- QBO closed-books API behavior: https://developer.intuit.com/app/developer/qbo/docs/develop/troubleshooting/handling-common-errors+- JE AR/AP line rule: https://tprosupport.rightworks.com/kb/article/627-validation-error-indicated-failed-object/++**Bridges / build-vs-buy**+- Conductor: https://conductor.is/ · https://docs.conductor.is/overview/quickstart · https://docs.conductor.is/llms.txt · https://github.com/conductor-is/quickbooks-desktop-node · https://docs.conductor.is/help/guides/rightworks+- Ramp × Conductor: https://support.ramp.com/hc/en-us/articles/35796967214611-QuickBooks-Desktop-FAQs-about-Conductor-partner+- Codat QBD: https://docs.codat.io/integrations/accounting/quickbooksdesktop/accounting-quickbooksdesktop · https://docs.codat.io/updates/251006-deprecation-quickbooks-desktop-changes-to-sync-schedule+- Merge QBD: https://www.merge.dev/integrations/quickbooks-desktop · https://www.merge.dev/pricing+- Rutter QBD: https://docs.rutter.com/rest/2023-03-14/platforms/quickbooks_desktop+- Apideck QBD + build guide: https://www.apideck.com/integrations/quickbooks-desktop · https://www.apideck.com/blog/build-an-integration-with-quickbooks-desktop-in-2025+- Autofy shutdown: https://help.onpay.com/hc/en-us/articles/360038938631-Autofy-integration-services-discontinued-June-30-2024+- OSS QBWC servers: https://github.com/qbwc/qbwc · https://github.com/johnballantyne/qbws · https://github.com/RappidDevelopment/quickbooks-js · https://www.npmjs.com/package/soap+- QBWC error zoo: https://quickbooks.intuit.com/learn-support/en-us/help-article/open-programs/fix-common-web-connector-errors-quickbooks-desktop/L9slolvg0_US_en_US+- IIF fallback: https://quickbooks.intuit.com/learn-support/en-us/help-article/import-export-data-files/export-import-edit-iif-files/L56LT9Z0Q_US_en_US+- ServiceTitan build example: https://help.servicetitan.com/docs/quickbooks-desktop-1++**Fishbowl / MISys**+- Fishbowl QBD integration (archived official wiki): http://web.archive.org/web/20201028154023/https://www.fishbowlinventory.com/wiki/QuickBooks (live: https://help.fishbowlinventory.com/advanced/s/article/QuickBooks)+- Fishbowl Accounting Journal Entries: http://web.archive.org/web/20210726021144/https://www.fishbowlinventory.com/wiki/Accounting_Journal_Entries+- Fishbowl reconciliation tie-out: https://fishbowlhelp.com/files/Reconciling-Discrepancies.pdf+- Fishbowl Drive = QBO-only: https://quickbooks.intuit.com/app/apps/appdetails/fishbowl_drive/en-us/+- Fishbowl failure modes: https://blog.tarabyte.com/blog/the-top-10-reasons-fishbowl-and-quickbooks-dont-match · https://blog.tarabyte.com/blog/the-easy-way-to-double-your-payables+- MISys QBD FAQ (posting model, control accounts): https://misysinc.com/quickbooks/faqs-for-quickbooks/+- MISys accounting architecture: https://helpdesk.misysinc.com/knowledgebase.php?article=40 · account sets: https://helpdesk.misysinc.com/knowledgebase.php?article=41 · Period End: https://helpdesk.misysinc.com/knowledgebase.php?article=66++**Cloud MRP engines**+- Katana QBO config: https://support.katanamrp.com/en/articles/9447704-how-to-configure-the-quickbooks-online-integration · Xero stock gap: https://support.katanamrp.com/en/articles/5968138-how-to-sync-stock-to-xero-from-katana+- Cin7 Core account mapping: https://help.core.cin7.com/hc/en-us/articles/9034463858831-Accounts-and-Chart-of-Accounts · sync report: https://help.core.cin7.com/hc/en-us/articles/9034605172879-Xero-Synchronization-Report · consolidation: https://help.core.cin7.com/hc/en-us/articles/9735460166543-Consolidate-transactions-for-QuickBooks-Online · errors/locks: https://help.core.cin7.com/hc/en-us/articles/13625639249807-QuickBooks-Online-errors · conversions: https://help.core.cin7.com/hc/en-us/articles/9034487616015-Manage-Opening-Balances-Conversions+- Unleashed Xero setup + reconcile: https://support.unleashedsoftware.com/hc/en-us/articles/4402418327961-Xero-Integration-Setup · https://support.unleashedsoftware.com/hc/en-us/articles/5029216195481-Reconcile-with-Xero-and-export-transactions+- SOS Inventory sync: https://help.sosinventory.com/v8-quickbooks-online-integration-and-connection-overview · https://help.sosinventory.com/v8-sync-menu+- MRPeasy: https://www.mrpeasy.com/quickbooks/ · https://www.mrpeasy.com/xero/+- Fulfil: https://www.fulfil.io/products/general-ledger/ · https://www.fulfil.io/blog/when-fulfil-accounting-make-sense/++**SAP / NetSuite / iPaaS / canon**+- BAPI_ACC_DOCUMENT_POST + CHECK: https://sapficoblog.com/bapi_acc_document_post-accounting-document-in-sap/ · https://community.sap.com/t5/application-development-discussions/bapi-acc-document-check/m-p/10397821+- IDoc reprocessing (BD87): https://community.sap.com/t5/technology-blog-posts-by-members/how-to-use-transaction-bd87-to-reprocess-failed-idocs/ba-p/13641328+- AWKEY idempotency + reversal: https://community.sap.com/t5/application-development-and-automation-discussions/bapi-acc-document-post-awkey/m-p/5178751 · https://community.sap.com/t5/technology-q-a/reversing-a-document-using-the-bapi-bapi-acc-document-rev-post/qaq-p/1134828+- FI summarization (OBCY): https://wiki.scn.sap.com/wiki/display/ERPFI/Summarization+functionality+- OBYC account determination: https://erpcorp.com/sap-controlling-blog/fundamentals-of-mm-fi-account-determination+- NetSuite externalId upsert: https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_156334828635.html · https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_156335203191.html+- NetSuite period behavior: https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_4334084139.html+- Celigo error management: https://docs.celigo.com/hc/en-us/articles/16182564553371-Retry-or-resolve-errors · Boomi retries: https://help.boomi.com/docs/Atomsphere/Integration/Process%20building/r-atm-Try_Catch_shape_7b3dd8df-426e-4ed7-824a-40cc0b5dc68d+- Outbox pattern: https://microservices.io/patterns/data/transactional-outbox.html+- Stripe idempotency: https://stripe.com/blog/idempotency · https://brandur.org/idempotency-keys+- Reconciliation tiers: https://www.formance.com/blog/financial-operations/account-reconciliation-patterns-for-high-volume-fintech+- Xero lock dates: https://central.xero.com/s/article/Set-up-and-work-with-lock-dates++**Flagged unverified**: exact qbXML-16.0↔QB-2024 matrix row (inferred from release-notes+pattern; Intuit SPA wouldn't render); one-foreign-currency-per-JE SDK rule (practitioner+consensus); Enterprise 24 end-of-support date claims (conflicting secondary sources; Intuit+has announced none); Conductor funding; Codat QBD-specific JE-push matrix; Merge QBD+field-level coverage.diff --git a/.ai/rules/mrp-system.md b/.ai/rules/mrp-system.mdindex 08ebd23708..6ec1a85d86 100644--- a/.ai/rules/mrp-system.md+++ b/.ai/rules/mrp-system.md@@ -96,12 +96,21 @@ to child demand. Note current `methodType` enum is## Source views (open demand/supply)Newest defs in `20260417000300_storage-unit-recreate-dependents.sql`-(`openPurchaseOrderLines` in `20260529074512_open-po-lines-required-date.sql`).+(`openPurchaseOrderLines` in `20260529074512_open-po-lines-required-date.sql`,+`openSalesOrderLines` in `20260710051147_mto-sales-lines-drive-demand.sql`).All join through `itemReplenishment` to expose `replenishmentSystem`, `leadTime`,`itemTrackingType`.-- `openSalesOrderLines` — `salesOrderLineType != 'Service'`,- `methodType != 'Make to Order'`, status IN `('To Ship','To Ship and Invoice')`.+- `openSalesOrderLines` — `salesOrderLineType != 'Service'`, status IN+ `('To Ship','To Ship and Invoice')`. Newest def:+ `20260710051147_mto-sales-lines-drive-demand.sql`. Make to Order lines ARE+ included (they were excluded before that migration), but their+ `quantityToSend` is netted down by the remaining output+ (`quantity − quantityReceivedToInventory − quantityShipped`) of live jobs+ linked via `job.salesOrderLineId` (statuses Planned/Ready/In Progress/Paused —+ the same set as `openJobMaterialLines`, so each unit is counted exactly once:+ SO line while unjobbed, job materials once a job is released, inventory once+ produced). Draft/Cancelled jobs do not suppress line demand.- `openJobMaterialLines` — job status IN `('Planned','Ready','In Progress','Paused')`,`methodType != 'Make to Order'`.- `openProductionOrders` — job status IN those 4, `salesOrderId IS NULL`diff --git a/.gitignore b/.gitignoreindex 5e41e856a2..f5b9e4db17 100644--- a/.gitignore+++ b/.gitignore@@ -75,8 +75,15 @@ packages/database/supabase/snippets/**.claude/notes/.codex/+# Editor/IDE settings — local, not source+.vscode/+# .ai/ scratch — runtime, not source.ai/scratch/+.ai/daily-notes/++# Daily notes — runtime scratch, not source+memory/daily-notes/# Loop run artifacts (@carbon/harness RUNS_DIR).# Volatile files (screenshots, raw event log) are excluded; durable run recordsdiff --git a/apps/erp/app/hooks/useModules.tsx b/apps/erp/app/hooks/useModules.tsxindex 46d8bea98e..35725f44fa 100644--- a/apps/erp/app/hooks/useModules.tsx+++ b/apps/erp/app/hooks/useModules.tsx@@ -50,7 +50,7 @@ function useModuleDefinitions(): ModuleDefinition[] {key: "accounting",permission: "accounting",name: t`Accounting`,- to: path.to.chartOfAccounts,+ to: path.to.accounting,icon: LuLandmark},{diff --git a/apps/erp/app/modules/items/ui/Item/ItemCostingForm.tsx b/apps/erp/app/modules/items/ui/Item/ItemCostingForm.tsxindex daa0903e36..b8845bf516 100644--- a/apps/erp/app/modules/items/ui/Item/ItemCostingForm.tsx+++ b/apps/erp/app/modules/items/ui/Item/ItemCostingForm.tsx@@ -67,10 +67,14 @@ const ItemCostingForm = ({ initialValues }: ItemCostingFormProps) => {name="costingMethod"label={t`Costing Method`}termId="costing-method"- options={itemCostingMethods.map((method) => ({- label: method,- value: method- }))}+ options={itemCostingMethods+ // Standard costing isn't implemented yet — hidden until the+ // standard-costing work ships+ .filter((method) => method !== "Standard")+ .map((method) => ({+ label: method,+ value: method+ }))}/><Numberdiff --git a/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json b/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.jsonindex 9ca81c1f6f..52b40c91bf 100644--- a/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json+++ b/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json@@ -1,5 +1,5 @@{- "generated": "2026-07-09T20:57:39.950Z",+ "generated": "2026-07-10T03:22:12.497Z","totalTools": 1303,"modules": 15,"tools": [diff --git a/apps/erp/app/routes/x+/_index.tsx b/apps/erp/app/routes/x+/_index.tsxindex 284b988a69..d68c25a349 100644--- a/apps/erp/app/routes/x+/_index.tsx+++ b/apps/erp/app/routes/x+/_index.tsx@@ -206,7 +206,7 @@ const ModuleCard = ({ module }: { module: Authenticated<NavItem> }) => (<Linkto={module.to}prefetch="intent"- className="flex items-center gap-4 p-4 bg-card/70 backdrop-blur-md rounded-lg border border-border shadow-button-base group hover:bg-accent/40 hover:border-foreground/20 cursor-pointer transition-colors duration-200"+ className="flex items-center gap-4 p-4 bg-card/70 backdrop-blur-md rounded-lg border border-border group hover:bg-accent/40 hover:border-foreground/20 cursor-pointer transition-colors duration-200"><div className="shrink-0 p-2.5 rounded-lg border border-border group-hover:border-foreground/20 transition-colors"><module.icon className="text-xl" />diff --git a/apps/erp/app/routes/x+/accounting+/_index.tsx b/apps/erp/app/routes/x+/accounting+/_index.tsxindex 9ea09c3955..33b3df47bc 100644--- a/apps/erp/app/routes/x+/accounting+/_index.tsx+++ b/apps/erp/app/routes/x+/accounting+/_index.tsx@@ -1,6 +1,20 @@+import { requirePermissions } from "@carbon/auth/auth.server";+import type { LoaderFunctionArgs } from "react-router";import { redirect } from "react-router";+import { getCompanySettings } from "~/modules/settings";import { path } from "~/utils/path";-export async function loader() {- throw redirect(path.to.balanceSheet);+export async function loader({ request }: LoaderFunctionArgs) {+ const { client, companyId } = await requirePermissions(request, {+ view: "accounting"+ });++ const companySettings = await getCompanySettings(client, companyId);+ const accountingEnabled =+ (companySettings.data as { accountingEnabled?: boolean } | null)+ ?.accountingEnabled ?? false;++ throw redirect(+ accountingEnabled ? path.to.balanceSheet : path.to.chartOfAccounts+ );}diff --git a/apps/erp/app/routes/x+/accounting+/_layout.tsx b/apps/erp/app/routes/x+/accounting+/_layout.tsxindex b225000fef..d1a735a5e8 100644--- a/apps/erp/app/routes/x+/accounting+/_layout.tsx+++ b/apps/erp/app/routes/x+/accounting+/_layout.tsx@@ -22,7 +22,7 @@ export const meta: MetaFunction = () => {export const handle: Handle = {breadcrumb: msg`Accounting`,- to: path.to.chartOfAccounts,+ to: path.to.accounting,module: "accounting"};diff --git a/packages/database/src/types.ts b/packages/database/src/types.tsindex 50eca67379..71c2f5f25c 100644--- a/packages/database/src/types.ts+++ b/packages/database/src/types.ts@@ -6045,6 +6045,7 @@ export type Database = {costLedger: {Row: {adjustment: boolean+ appliesToCostLedgerId: string | nullcompanyId: stringcost: numbercostLedgerType: Database["public"]["Enums"]["costLedgerType"]@@ -6066,6 +6067,7 @@ export type Database = {}Insert: {adjustment?: boolean+ appliesToCostLedgerId?: string | nullcompanyId: stringcost?: numbercostLedgerType: Database["public"]["Enums"]["costLedgerType"]@@ -6087,6 +6089,7 @@ export type Database = {}Update: {adjustment?: boolean+ appliesToCostLedgerId?: string | nullcompanyId?: stringcost?: numbercostLedgerType?: Database["public"]["Enums"]["costLedgerType"]diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.tsindex 50eca67379..71c2f5f25c 100644--- a/packages/database/supabase/functions/lib/types.ts+++ b/packages/database/supabase/functions/lib/types.ts@@ -6045,6 +6045,7 @@ export type Database = {costLedger: {Row: {adjustment: boolean+ appliesToCostLedgerId: string | nullcompanyId: stringcost: numbercostLedgerType: Database["public"]["Enums"]["costLedgerType"]@@ -6066,6 +6067,7 @@ export type Database = {}Insert: {adjustment?: boolean+ appliesToCostLedgerId?: string | nullcompanyId: stringcost?: numbercostLedgerType: Database["public"]["Enums"]["costLedgerType"]@@ -6087,6 +6089,7 @@ export type Database = {}Update: {adjustment?: boolean+ appliesToCostLedgerId?: string | nullcompanyId?: stringcost?: numbercostLedgerType?: Database["public"]["Enums"]["costLedgerType"]diff --git a/packages/database/supabase/functions/post-purchase-invoice/index.ts b/packages/database/supabase/functions/post-purchase-invoice/index.tsindex 27f4159ac2..4ebd24b50d 100644--- a/packages/database/supabase/functions/post-purchase-invoice/index.ts+++ b/packages/database/supabase/functions/post-purchase-invoice/index.ts@@ -8,6 +8,10 @@ import { requirePermissions } from "../lib/supabase.ts";import type { Database } from "../lib/types.ts";import { credit, debit, journalReference } from "../lib/utils.ts";import { getCurrentAccountingPeriod } from "../shared/get-accounting-period.ts";+import {+ allocateVarianceAcrossLayers,+ type VarianceAllocation,+} from "../shared/purchase-cost-adjustment.ts";import { getNextSequence } from "../shared/get-next-sequence.ts";import { getDefaultPostingGroup } from "../shared/get-posting-group.ts";@@ -92,7 +96,9 @@ serve(async (req: Request) => {.from("costLedger").select("*").eq("documentId", invoiceId)- .eq("documentType", "Purchase Invoice")+ // 'Purchase Receipt' + documentId=invoiceId are the legacy+ // self-heal layers this invoice may have created+ .in("documentType", ["Purchase Invoice", "Purchase Receipt"]).eq("companyId", companyId),]);@@ -280,8 +286,27 @@ serve(async (req: Request) => {companyId,}));+ // Partition invoice-created costLedger rows for reversal:+ // - adjustment children (variance bumps on receipt layers)+ // - legacy self-heal layers (documentType 'Purchase Receipt')+ // - plain rows (no-PO direct-invoice layers): negative-mirror as before+ type CostLedgerRow = Database["public"]["Tables"]["costLedger"]["Row"];+ const adjustmentChildrenVoid = originalCostLedger.data.filter(+ (entry: CostLedgerRow) =>+ entry.adjustment && entry.appliesToCostLedgerId+ );+ const selfHealLayersVoid = originalCostLedger.data.filter(+ (entry: CostLedgerRow) =>+ !entry.adjustment && entry.documentType === "Purchase Receipt"+ );+ const plainCostLedgerVoid = originalCostLedger.data.filter(+ (entry: CostLedgerRow) =>+ !adjustmentChildrenVoid.includes(entry) &&+ !selfHealLayersVoid.includes(entry)+ );+const reversingCostLedger: Database["public"]["Tables"]["costLedger"]["Insert"][] =- originalCostLedger.data.map((entry) => ({+ plainCostLedgerVoid.map((entry) => ({itemLedgerType: entry.itemLedgerType,costLedgerType: entry.costLedgerType,adjustment: entry.adjustment,@@ -374,6 +399,82 @@ serve(async (req: Request) => {.execute();}+ // Reverse variance adjustment children created by this invoice.+ // Untouched children are deleted; partially consumed ones get a+ // counter-child with the SAME remainingQuantity while the original+ // stays live — future consumption applies +bump and −bump together,+ // netting remaining units back to base cost. Already-consumed bumps+ // stay in posted COGS (no retroactive restatement).+ for (const child of adjustmentChildrenVoid) {+ if (+ Number(child.remainingQuantity ?? 0) === Number(child.quantity)+ ) {+ await trx+ .deleteFrom("costLedger")+ .where("id", "=", child.id)+ .execute();+ } else {+ await trx+ .insertInto("costLedger")+ .values({+ itemLedgerType: child.itemLedgerType,+ costLedgerType: child.costLedgerType,+ adjustment: true,+ appliesToCostLedgerId: child.appliesToCostLedgerId,+ documentType: child.documentType,+ documentId: child.documentId,+ externalDocumentId: child.externalDocumentId,+ itemId: child.itemId,+ quantity: child.quantity,+ nominalCost: -child.nominalCost,+ cost: -child.cost,+ remainingQuantity: child.remainingQuantity,+ supplierId: child.supplierId,+ companyId,+ })+ .execute();+ }+ }++ // Reverse legacy self-heal layers created by this invoice. Unconsumed+ // layers are deleted (restores the pre-invoice no-layer state);+ // partially consumed ones get a negative mirror row and stop feeding+ // consumption (remainingQuantity zeroed).+ for (const layer of selfHealLayersVoid) {+ if (+ Number(layer.remainingQuantity ?? 0) === Number(layer.quantity)+ ) {+ await trx+ .deleteFrom("costLedger")+ .where("id", "=", layer.id)+ .execute();+ } else {+ await trx+ .insertInto("costLedger")+ .values({+ itemLedgerType: layer.itemLedgerType,+ costLedgerType: layer.costLedgerType,+ adjustment: layer.adjustment,+ documentType: layer.documentType,+ documentId: layer.documentId,+ externalDocumentId: layer.externalDocumentId,+ itemId: layer.itemId,+ quantity: -layer.quantity,+ nominalCost: -layer.nominalCost,+ cost: -layer.cost,+ remainingQuantity: 0,+ supplierId: layer.supplierId,+ companyId,+ })+ .execute();+ await trx+ .updateTable("costLedger")+ .set({ remainingQuantity: 0 })+ .where("id", "=", layer.id)+ .execute();+ }+ }+await trx.updateTable("purchaseInvoice").set({@@ -488,7 +589,7 @@ serve(async (req: Request) => {.eq("companyId", companyId),client.from("itemCost")- .select("itemId, itemPostingGroupId")+ .select("itemId, itemPostingGroupId, costingMethod").in("itemId", itemIds),client.from("purchaseOrderLine")@@ -854,24 +955,9 @@ serve(async (req: Request) => {}} // if the line is associated with a purchase order line, we do accrual/reversingelse {- // create the cost entry- costLedgerInserts.push({- itemLedgerType: "Purchase",- costLedgerType: "Direct Cost",- adjustment: false,- documentType: "Purchase Invoice",- documentId: purchaseInvoice.data?.id ?? undefined,- externalDocumentId:- purchaseInvoice.data?.supplierReference ?? undefined,- itemId: invoiceLine.itemId,- quantity: invoiceLineQuantityInInventoryUnit,- nominalCost:- invoiceLine.quantity * (invoiceLine.unitPrice ?? 0),- cost: totalLineCostWithWeightedShipping,- remainingQuantity: invoiceLineQuantityInInventoryUnit,- supplierId: purchaseInvoice.data?.supplierId,- companyId,- });+ // The receipt is the sole creator of purchase cost layers; this+ // invoice adjusts the receipt's layers (below) instead of+ // creating its own.// determine the journal lines that should be reversedconst existingJournalLines = invoiceLine.purchaseOrderLineId@@ -991,12 +1077,203 @@ serve(async (req: Request) => {companyId,});- // DR/CR Purchase Price Variance if invoice cost differs from receipt cost- if (Math.abs(variance) > 0.005) {+ // Split the invoice-vs-receipt variance by stock coverage:+ // the on-hand share writes up Inventory (GL) and the receipt+ // layers (adjustment child rows); the consumed share posts to+ // PPV. Standard-cost items and outside-processing or+ // non-inventory lines keep the full variance in PPV — they+ // have no layers to adjust.+ const lineItemTrackingType =+ items.data.find(+ (item: { id: string }) => item.id === invoiceLine.itemId+ )?.itemTrackingType ?? "Inventory";+ const lineCostingMethod =+ itemCosts.data.find(+ (cost: { itemId: string }) =>+ cost.itemId === invoiceLine.itemId+ )?.costingMethod ?? "FIFO";+ const usesLayers =+ !isOutsideProcessing &&+ lineItemTrackingType !== "Non-Inventory" &&+ lineCostingMethod !== "Standard" &&+ !!invoiceLine.itemId;++ let allocation: VarianceAllocation = {+ inventoryShare: 0,+ ppvShare: Math.abs(variance) > 0.005 ? variance : 0,+ perLayer: [],+ };++ if (usesLayers && Math.abs(variance) > 0.005) {+ const receiptLinesForPoLine = await client+ .from("receiptLine")+ .select("receiptId")+ .eq("lineId", invoiceLine.purchaseOrderLineId!)+ .eq("companyId", companyId);+ if (receiptLinesForPoLine.error) {+ throw new Error("Failed to fetch receipt lines for PO line");+ }+ const receiptIds = [+ ...new Set(+ (receiptLinesForPoLine.data ?? [])+ .map(+ (line: { receiptId: string | null }) =>+ line.receiptId+ )+ .filter((id: string | null): id is string => !!id)+ ),+ ];++ const receiptLayers =+ receiptIds.length > 0+ ? await client+ .from("costLedger")+ .select("id, quantity, remainingQuantity")+ .eq("documentType", "Purchase Receipt")+ .in("documentId", receiptIds)+ .eq("itemId", invoiceLine.itemId!)+ .eq("adjustment", false)+ .eq("companyId", companyId)+ .order("postingDate", { ascending: true })+ .order("createdAt", { ascending: true })+ : { data: [], error: null };+ if (receiptLayers.error) {+ throw new Error("Failed to fetch receipt cost layers");+ }++ if ((receiptLayers.data ?? []).length > 0) {+ allocation = allocateVarianceAcrossLayers(+ (receiptLayers.data ?? []).map(+ (layer: {+ id: string;+ quantity: number | null;+ remainingQuantity: number | null;+ }) => ({+ id: layer.id,+ quantity: Number(layer.quantity),+ remainingQuantity: Number(+ layer.remainingQuantity ?? 0+ ),+ })+ ),+ quantityToReverse,+ variance+ );++ // Subledger: adjustment child rows on the covered layers,+ // consumed alongside their parent by calculateCOGS.+ for (const entry of allocation.perLayer) {+ costLedgerInserts.push({+ itemLedgerType: "Purchase",+ costLedgerType: "Direct Cost",+ adjustment: true,+ appliesToCostLedgerId: entry.costLedgerId,+ documentType: "Purchase Invoice",+ documentId: purchaseInvoice.data?.id ?? undefined,+ externalDocumentId:+ purchaseInvoice.data?.supplierReference ?? undefined,+ itemId: invoiceLine.itemId,+ quantity: entry.appliedQuantity,+ nominalCost: entry.adjustmentCost,+ cost: entry.adjustmentCost,+ remainingQuantity: entry.appliedQuantity,+ supplierId: purchaseInvoice.data?.supplierId,+ companyId,+ });+ }+ } else {+ // Legacy self-heal: goods received before receipt-created+ // layers shipped. Measure coverage from on-hand quantity+ // (itemInventory cache) and create the layer now at+ // receipt cost + on-hand variance share, so downstream+ // consumption converges instead of double-counting.+ const itemInventoryRows = await client+ .from("itemInventory")+ .select("quantityOnHand")+ .eq("itemId", invoiceLine.itemId!)+ .eq("companyId", companyId);+ const onHandQuantity = Math.max(+ 0,+ (itemInventoryRows.data ?? []).reduce(+ (+ acc: number,+ row: { quantityOnHand: number | null }+ ) => acc + Number(row.quantityOnHand ?? 0),+ 0+ )+ );+ const coveredQuantity = Math.min(+ onHandQuantity,+ quantityToReverse+ );+ allocation = allocateVarianceAcrossLayers(+ [+ {+ id: "legacy-self-heal",+ quantity: quantityToReverse,+ remainingQuantity: coveredQuantity,+ },+ ],+ quantityToReverse,+ variance+ );+ // The layer only represents stock still on hand — the+ // consumed remainder's variance is PPV and must not become+ // consumable subledger value.+ if (coveredQuantity > 0) {+ const coverageRatio = coveredQuantity / quantityToReverse;+ costLedgerInserts.push({+ itemLedgerType: "Purchase",+ costLedgerType: "Direct Cost",+ adjustment: false,+ documentType: "Purchase Receipt",+ documentId: purchaseInvoice.data?.id ?? undefined,+ externalDocumentId:+ purchaseInvoice.data?.supplierReference ?? undefined,+ itemId: invoiceLine.itemId,+ quantity: coveredQuantity,+ nominalCost:+ coveredQuantity * invoiceLineUnitCostInInventoryUnit,+ cost:+ receiptCostForReversedQty * coverageRatio ++ allocation.inventoryShare,+ remainingQuantity: coveredQuantity,+ supplierId: purchaseInvoice.data?.supplierId,+ companyId,+ });+ }+ // The write-up is baked into the layer; no child rows.+ allocation = {+ ...allocation,+ perLayer: [],+ };+ }+ }++ // DR Inventory for the on-hand share of the variance+ if (Math.abs(allocation.inventoryShare) > 0.005) {+ journalLineInserts.push({+ accountId: accountDefaults.data.inventoryAccount,+ description: "Inventory Account",+ amount: debit("asset", allocation.inventoryShare),+ quantity: quantityToReverse,+ documentType: "Invoice",+ documentId: purchaseInvoice.data?.id,+ externalDocumentId: purchaseInvoice.data?.supplierReference,+ documentLineReference: journalReference.to.purchaseInvoice(+ invoiceLine.purchaseOrderLineId!+ ),+ journalLineReference,+ companyId,+ });+ }++ // DR/CR Purchase Price Variance for the consumed share+ if (Math.abs(allocation.ppvShare) > 0.005) {journalLineInserts.push({accountId: accountDefaults.data.purchaseVarianceAccount,description: "Purchase Price Variance",- amount: debit("expense", variance),+ amount: debit("expense", allocation.ppvShare),quantity: quantityToReverse,documentType: "Invoice",documentId: purchaseInvoice.data?.id,diff --git a/packages/database/supabase/functions/post-receipt/index.ts b/packages/database/supabase/functions/post-receipt/index.tsindex 82ab7700ce..cfdf6120ad 100644--- a/packages/database/supabase/functions/post-receipt/index.ts+++ b/packages/database/supabase/functions/post-receipt/index.ts@@ -12,6 +12,7 @@ import {journalReference,TrackedEntityAttributes,} from "../lib/utils.ts";+import { calculateCOGS } from "../shared/calculate-cogs.ts";import { getCurrentAccountingPeriod } from "../shared/get-accounting-period.ts";import { getNextSequence } from "../shared/get-next-sequence.ts";import { getDefaultPostingGroup } from "../shared/get-posting-group.ts";@@ -584,6 +585,25 @@ serve(async (req: Request) => {const itemLedgerInserts: Database["public"]["Tables"]["itemLedger"]["Insert"][] =[];+ // Cost layers created by this receipt (the receipt is the sole creator+ // of purchase layers; the invoice adjusts them later). Rows flagged+ // isInvoiceFirst carry their PO line so the flush can exclude quantity+ // already represented by a legacy invoice-created layer (documents+ // posted before receipt-created layers shipped).+ const costLedgerInserts: (Database["public"]["Tables"]["costLedger"]["Insert"] & {+ isInvoiceFirst?: boolean;+ poLineId?: string;+ })[] = [];+ // Negative receipts consume layers at layer cost inside the+ // transaction (calculateCOGS); GL amounts are patched to match.+ // fallbackCost (PO cost) is used when no layers yield a cost.+ const negativeReceiptConsumptions: {+ itemId: string;+ quantity: number;+ fallbackCost: number;+ grIrLineIndex: number | null;+ inventoryLineIndex: number | null;+ }[] = [];const journalLineInserts: Omit<Database["public"]["Tables"]["journalLine"]["Insert"],"journalId"@@ -825,6 +845,7 @@ serve(async (req: Request) => {// Detect invoice-first scenario: PO lines where qty invoiced > qty receivedconst invoiceFirstQtyByPoLine = new Map<string, number>();const accrualUnitCostByPoLine = new Map<string, number>();+ const receivedBeforeInvUnitsByPoLine = new Map<string, number>();if (accountingEnabled) {for (const pol of purchaseOrderLines.data) {@@ -838,6 +859,7 @@ serve(async (req: Request) => {);if (invoiceFirstQty > 0) {invoiceFirstQtyByPoLine.set(pol.id, invoiceFirstQty);+ receivedBeforeInvUnitsByPoLine.set(pol.id, receivedInInventoryUnit);}}@@ -848,7 +870,7 @@ serve(async (req: Request) => {const accrualJournalLines = await client.from("journalLine")- .select("documentLineReference, amount, quantity")+ .select("documentLineReference, amount, quantity, accountId").in("documentLineReference", accrualDocRefs).eq("accrual", true).eq("companyId", companyId);@@ -857,13 +879,21 @@ serve(async (req: Request) => {throw new Error("Failed to fetch accrual journal lines");}- // GR/IR debit entries have negative amounts (debit on a liability)+ // GR/IR debit entries have non-positive amounts (debit on a+ // liability; zero-priced invoices accrue at exactly 0). Matching+ // the GR/IR account keeps the paired AP credit lines, which are+ // also 0 on zero-priced invoices, out of the quantity sum.const accrualCostByPoLine: Record<string,{ totalCost: number; totalQty: number }> = {};for (const jl of accrualJournalLines.data ?? []) {- if ((jl.amount ?? 0) < 0 && (jl.quantity ?? 0) > 0) {+ if (+ (jl.amount ?? 0) <= 0 &&+ (jl.quantity ?? 0) > 0 &&+ jl.accountId ===+ accountDefaults?.data?.goodsReceivedNotInvoicedAccount+ ) {const [, poLineId] = (jl.documentLineReference ?? "").split(":");@@ -906,22 +936,62 @@ serve(async (req: Request) => {const isNegativeReceipt = receivedQuantity < 0;const absReceivedQuantity = Math.abs(receivedQuantity);- if (accountingEnabled && accountDefaults?.data && absReceivedQuantity > 0) {- const lineCost = absReceivedQuantity * receiptLine.unitPrice;-- // Add proportional shipping cost based on line value percentage- const lineValuePercentage =- totalLinesCost === 0 ? 0 : lineCost / totalLinesCost;- const lineWeightedShippingCost = shippingCost * lineValuePercentage;- const cost = lineCost + lineWeightedShippingCost;+ // Line cost at PO price + proportional shipping. Computed outside+ // the accounting gate: cost layers are created regardless of+ // whether GL posting is enabled.+ const lineCost = absReceivedQuantity * receiptLine.unitPrice;+ const lineValuePercentage =+ totalLinesCost === 0 ? 0 : lineCost / totalLinesCost;+ const lineWeightedShippingCost = shippingCost * lineValuePercentage;+ const cost = lineCost + lineWeightedShippingCost;+ const poUnitCost =+ absReceivedQuantity > 0 ? cost / absReceivedQuantity : 0;++ const createsLayers =+ itemTrackingType !== "Non-Inventory" &&+ !isOutsideProcessing &&+ !!receiptLine.itemId &&+ absReceivedQuantity > 0;++ // Invoice-first split: the portion of this line that was invoiced+ // before receipt is valued at the accrual (invoice) unit cost — the+ // actual cost is already known, so no variance arises. The+ // remainder stays at PO cost until its invoice adjusts it.+ const poLineId = receiptLine.lineId;+ let invoiceFirstQty = 0;+ let accrualUnitCost = 0;+ if (+ !isNegativeReceipt &&+ poLineId &&+ invoiceFirstQtyByPoLine.has(poLineId)+ ) {+ const remainingInvoiceFirstQty =+ invoiceFirstQtyByPoLine.get(poLineId)!;+ const claimedQty = Math.min(+ absReceivedQuantity,+ remainingInvoiceFirstQty+ );+ const claimedUnitCost = accrualUnitCostByPoLine.get(poLineId);+ // A recorded accrual basis is claimed even at zero unit cost+ // (zero-priced invoices); only a missing basis falls through to+ // the normal PO-cost path.+ if (claimedQty > 0 && claimedUnitCost !== undefined) {+ invoiceFirstQty = claimedQty;+ accrualUnitCost = claimedUnitCost;+ invoiceFirstQtyByPoLine.set(+ poLineId,+ remainingInvoiceFirstQty - claimedQty+ );+ }+ }+ const normalQty = absReceivedQuantity - invoiceFirstQty;+ const invoiceFirstPortionCost = invoiceFirstQty * accrualUnitCost;+ const normalPortionCost = normalQty * poUnitCost;+ const glCost = invoiceFirstPortionCost + normalPortionCost;+ if (accountingEnabled && accountDefaults?.data && absReceivedQuantity > 0) {const journalLineReference = nanoid();- // Find the PO line for this receipt line- const poLine = purchaseOrderLines.data.find(- (pol) => pol.id === receiptLine.lineId- );-// Determine the debit account based on item typelet debitAccount: string;let debitDescription: string;@@ -938,6 +1008,10 @@ serve(async (req: Request) => {}if (isNegativeReceipt) {+ // Amounts are placeholders at PO cost; for layer-backed lines+ // they are patched to the consumed layer cost inside the+ // transaction (calculateCOGS).+ const grIrLineIndex = journalLineInserts.length;journalLineInserts.push({accountId: accountDefaults.data.goodsReceivedNotInvoicedAccount,description: "Goods Received Not Invoiced",@@ -954,6 +1028,7 @@ serve(async (req: Request) => {companyId,});+ const inventoryLineIndex = journalLineInserts.length;journalLineInserts.push({accountId: debitAccount,description: debitDescription,@@ -969,11 +1044,23 @@ serve(async (req: Request) => {journalLineReference,companyId,});++ if (createsLayers) {+ negativeReceiptConsumptions.push({+ itemId: receiptLine.itemId!,+ quantity: absReceivedQuantity,+ fallbackCost: cost,+ grIrLineIndex,+ inventoryLineIndex,+ });+ }} else {+ // The invoice-first portion posts at accrual (invoice) cost so+ // the invoice's GR/IR debit accrual clears exactly — no PPV.journalLineInserts.push({accountId: debitAccount,description: debitDescription,- amount: debit("asset", cost),+ amount: debit("asset", glCost),quantity: absReceivedQuantity,documentType: "Receipt",documentId: receipt.data?.id ?? undefined,@@ -989,7 +1076,7 @@ serve(async (req: Request) => {journalLineInserts.push({accountId: accountDefaults.data.goodsReceivedNotInvoicedAccount,description: "Goods Received Not Invoiced",- amount: credit("liability", cost),+ amount: credit("liability", glCost),quantity: absReceivedQuantity,documentType: "Receipt",documentId: receipt.data?.id ?? undefined,@@ -1001,70 +1088,58 @@ serve(async (req: Request) => {journalLineReference,companyId,});+ }+ } else if (isNegativeReceipt && createsLayers) {+ // Accounting disabled: still consume layers in the subledger+ negativeReceiptConsumptions.push({+ itemId: receiptLine.itemId!,+ quantity: absReceivedQuantity,+ fallbackCost: cost,+ grIrLineIndex: null,+ inventoryLineIndex: null,+ });+ }- // Invoice-first PPV: when invoice was posted before receipt,- // accrual entries used invoice cost for GR/IR. The standard- // entries above credited GR/IR at PO cost. Add adjustment- // entries so GR/IR clears at invoice cost and PPV captures- // the difference.- const poLineId = receiptLine.lineId;- if (poLineId && invoiceFirstQtyByPoLine.has(poLineId)) {- const remainingInvoiceFirstQty =- invoiceFirstQtyByPoLine.get(poLineId)!;- const invoiceFirstQty = Math.min(- absReceivedQuantity,- remainingInvoiceFirstQty- );-- if (invoiceFirstQty > 0) {- invoiceFirstQtyByPoLine.set(- poLineId,- remainingInvoiceFirstQty - invoiceFirstQty- );-- const accrualUnitCost =- accrualUnitCostByPoLine.get(poLineId) ?? 0;- const poUnitCost = cost / absReceivedQuantity;- const variance =- invoiceFirstQty * (accrualUnitCost - poUnitCost);-- if (Math.abs(variance) > 0.005) {- journalLineInserts.push({- accountId:- accountDefaults.data.goodsReceivedNotInvoicedAccount,- description: "GR/IR Clearing",- amount: credit("liability", variance),- quantity: invoiceFirstQty,- documentType: "Receipt",- documentId: receipt.data?.id ?? undefined,- externalDocumentId:- purchaseOrder.data?.supplierReference ?? undefined,- documentLineReference: journalReference.to.receipt(- poLineId- ),- journalLineReference,- companyId,- });-- journalLineInserts.push({- accountId:- accountDefaults.data.purchaseVarianceAccount,- description: "Purchase Price Variance",- amount: debit("expense", variance),- quantity: invoiceFirstQty,- documentType: "Receipt",- documentId: receipt.data?.id ?? undefined,- externalDocumentId:- purchaseOrder.data?.supplierReference ?? undefined,- documentLineReference: journalReference.to.receipt(- poLineId- ),- journalLineReference,- companyId,- });- }- }- }+ // Cost layers: the receipt is the sole creator of purchase layers.+ // The invoice later adjusts them via appliesToCostLedgerId children.+ if (createsLayers && !isNegativeReceipt) {+ if (invoiceFirstQty > 0) {+ costLedgerInserts.push({+ itemLedgerType: "Purchase",+ costLedgerType: "Direct Cost",+ adjustment: false,+ documentType: "Purchase Receipt",+ documentId: receipt.data?.id ?? undefined,+ externalDocumentId:+ receipt.data?.externalDocumentId ?? undefined,+ itemId: receiptLine.itemId,+ quantity: invoiceFirstQty,+ nominalCost: invoiceFirstQty * (receiptLine.unitPrice ?? 0),+ cost: invoiceFirstPortionCost,+ remainingQuantity: invoiceFirstQty,+ supplierId: purchaseOrder.data?.supplierId ?? undefined,+ companyId,+ isInvoiceFirst: true,+ poLineId: poLineId ?? undefined,+ });+ }+ if (normalQty > 0) {+ costLedgerInserts.push({+ itemLedgerType: "Purchase",+ costLedgerType: "Direct Cost",+ adjustment: false,+ documentType: "Purchase Receipt",+ documentId: receipt.data?.id ?? undefined,+ externalDocumentId:+ receipt.data?.externalDocumentId ?? undefined,+ itemId: receiptLine.itemId,+ quantity: normalQty,+ nominalCost: normalQty * (receiptLine.unitPrice ?? 0),+ cost: normalPortionCost,+ remainingQuantity: normalQty,+ supplierId: purchaseOrder.data?.supplierId ?? undefined,+ companyId,+ });}}@@ -1308,6 +1383,161 @@ serve(async (req: Request) => {: null;await db.transaction().execute(async (trx) => {+ // Negative receipts: consume layers at layer cost (FIFO/LIFO with+ // adjustment children) and patch the placeholder GL amounts so the+ // GL credit matches what actually left the subledger.+ for (const consumption of negativeReceiptConsumptions) {+ const cogsResult = await calculateCOGS(trx, {+ itemId: consumption.itemId,+ quantity: consumption.quantity,+ companyId,+ });+ // A consumed layer's total is authoritative even at zero or+ // negative (free goods, credit-adjusted layers): the GL credit+ // must match the value actually relieved from the subledger. The+ // PO-cost fallback applies only when nothing was consumed and no+ // cost basis was found.+ const consumedCost =+ cogsResult.layersConsumed.length > 0 || cogsResult.totalCost > 0+ ? cogsResult.totalCost+ : consumption.fallbackCost;+ if (consumption.grIrLineIndex !== null) {+ journalLineInserts[consumption.grIrLineIndex].amount = debit(+ "liability",+ consumedCost+ );+ }+ if (consumption.inventoryLineIndex !== null) {+ journalLineInserts[consumption.inventoryLineIndex].amount =+ credit("asset", consumedCost);+ }+ costLedgerInserts.push({+ itemLedgerType: "Purchase",+ costLedgerType: "Direct Cost",+ adjustment: false,+ documentType: "Purchase Receipt",+ documentId: receipt.data?.id ?? undefined,+ itemId: consumption.itemId,+ quantity: -consumption.quantity,+ cost: -consumedCost,+ remainingQuantity: 0,+ supplierId: purchaseOrder.data?.supplierId ?? undefined,+ companyId,+ });+ }++ // Flush cost layers. Transition guard: invoices posted before+ // receipt-created layers shipped created their own layers, so the+ // invoice-first quantity those legacy layers already represent must+ // not create a second one. Coverage is matched to the receipt's PO+ // lines through the legacy invoices' own lines, net of quantity+ // received before this receipt (which already consumed coverage);+ // only the covered quantity is excluded — any remainder still+ // creates a layer.+ if (costLedgerInserts.length > 0) {+ const invoiceFirstRows = costLedgerInserts.filter(+ (row) => row.isInvoiceFirst && row.itemId && row.poLineId+ );+ const legacyCoverageByPoLine = new Map<string, number>();+ if (invoiceFirstRows.length > 0) {+ const invoiceFirstItemIds = [+ ...new Set(invoiceFirstRows.map((row) => row.itemId!)),+ ];+ const legacyLayers = await trx+ .selectFrom("costLedger")+ .select(["documentId"])+ .where("documentType", "=", "Purchase Invoice")+ .where("itemId", "in", invoiceFirstItemIds)+ .where("companyId", "=", companyId)+ .where("remainingQuantity", ">", 0)+ // adjustment children are corrections on receipt layers, not+ // legacy invoice-created layers — must not trip this guard+ .where("adjustment", "=", false)+ .where("appliesToCostLedgerId", "is", null)+ .execute();+ const legacyInvoiceIds = [+ ...new Set(+ legacyLayers+ .map((layer) => layer.documentId)+ .filter((id): id is string => !!id)+ ),+ ];+ if (legacyInvoiceIds.length > 0) {+ const invoiceFirstPoLineIds = [+ ...new Set(invoiceFirstRows.map((row) => row.poLineId!)),+ ];+ const legacyInvoiceLines = await trx+ .selectFrom("purchaseInvoiceLine")+ .select(["purchaseOrderLineId", "quantity", "conversionFactor"])+ .where("invoiceId", "in", legacyInvoiceIds)+ .where("purchaseOrderLineId", "in", invoiceFirstPoLineIds)+ .where("companyId", "=", companyId)+ .execute();+ for (const line of legacyInvoiceLines) {+ if (!line.purchaseOrderLineId) continue;+ legacyCoverageByPoLine.set(+ line.purchaseOrderLineId,+ (legacyCoverageByPoLine.get(line.purchaseOrderLineId) ?? 0) ++ Number(line.quantity ?? 0) *+ Number(line.conversionFactor ?? 1)+ );+ }+ // Legacy layers were created for the full invoiced quantity,+ // and units received earlier consumed that coverage first —+ // subtracting received-to-date leaves exactly the coverage+ // this and future receipts may still exclude.+ for (const [linePoId, covered] of legacyCoverageByPoLine) {+ const receivedBefore =+ receivedBeforeInvUnitsByPoLine.get(linePoId) ?? 0;+ legacyCoverageByPoLine.set(+ linePoId,+ Math.max(0, covered - receivedBefore)+ );+ }+ }+ }+ const costLedgerRows: Database["public"]["Tables"]["costLedger"]["Insert"][] =+ [];+ for (const row of costLedgerInserts) {+ const {+ isInvoiceFirst,+ poLineId: rowPoLineId,+ ...insertRow+ } = row;+ if (isInvoiceFirst && rowPoLineId) {+ const coverage = legacyCoverageByPoLine.get(rowPoLineId) ?? 0;+ const rowQty = Number(insertRow.quantity ?? 0);+ const excludedQty = Math.min(rowQty, coverage);+ if (excludedQty > 0) {+ legacyCoverageByPoLine.set(+ rowPoLineId,+ coverage - excludedQty+ );+ console.log({+ function: "post-receipt",+ message:+ "excluding invoice-first quantity already represented by legacy invoice-created layers",+ itemId: insertRow.itemId,+ purchaseOrderLineId: rowPoLineId,+ excludedQty,+ });+ const layerQty = rowQty - excludedQty;+ if (layerQty <= 0) continue;+ const scale = layerQty / rowQty;+ insertRow.quantity = layerQty;+ insertRow.cost = Number(insertRow.cost ?? 0) * scale;+ insertRow.nominalCost =+ Number(insertRow.nominalCost ?? 0) * scale;+ insertRow.remainingQuantity = layerQty;+ }+ }+ costLedgerRows.push(insertRow);+ }+ if (costLedgerRows.length > 0) {+ await trx.insertInto("costLedger").values(costLedgerRows).execute();+ }+ }+for await (const [purchaseOrderLineId, update] of Object.entries(purchaseOrderLineUpdates)) {diff --git a/packages/database/supabase/functions/shared/calculate-cogs.ts b/packages/database/supabase/functions/shared/calculate-cogs.tsindex c4ef82fe6b..2dd8bf0434 100644--- a/packages/database/supabase/functions/shared/calculate-cogs.ts+++ b/packages/database/supabase/functions/shared/calculate-cogs.ts@@ -63,6 +63,16 @@ export async function calculateCOGS(.where("itemId", "=", itemId).where("companyId", "=", companyId).where("remainingQuantity", ">", 0)+ // adjustment child rows are consumed with their parent, not as layers+ .where("adjustment", "=", false)+ .where("appliesToCostLedgerId", "is", null)+ // 'Purchase Order' rows are planning/cost-history artifacts, not layers+ .where((eb) =>+ eb.or([+ eb("documentType", "is", null),+ eb("documentType", "!=", "Purchase Order"),+ ])+ ).orderBy("postingDate", orderDirection).orderBy("createdAt", orderDirection).execute();@@ -99,6 +109,35 @@ export async function calculateCOGS(}).where("id", "=", layer.id).execute();++ // Consume the layer's cost-adjustment children (invoice-vs-receipt+ // price corrections) alongside the parent: each adjusted unit carries+ // a per-unit bump of child.cost / child.quantity.+ const children = await trx+ .selectFrom("costLedger")+ .selectAll()+ .where("appliesToCostLedgerId", "=", layer.id)+ .where("remainingQuantity", ">", 0)+ .orderBy("createdAt", "asc")+ .execute();++ let unappliedQuantity = quantityFromLayer;+ for (const child of children) {+ if (unappliedQuantity <= 0) break;+ const childQty = Number(child.remainingQuantity);+ const perUnitBump =+ Number(child.quantity) > 0+ ? Number(child.cost) / Number(child.quantity)+ : 0;+ const applyQty = Math.min(childQty, unappliedQuantity);+ totalCost += applyQty * perUnitBump;+ unappliedQuantity -= applyQty;+ await trx+ .updateTable("costLedger")+ .set({ remainingQuantity: childQty - applyQty })+ .where("id", "=", child.id)+ .execute();+ }}// Fallback: insufficient layers (negative inventory scenario)diff --git a/packages/database/supabase/functions/shared/purchase-cost-adjustment.test.ts b/packages/database/supabase/functions/shared/purchase-cost-adjustment.test.tsnew file mode 100644index 0000000000..84e6d2b771--- /dev/null+++ b/packages/database/supabase/functions/shared/purchase-cost-adjustment.test.ts@@ -0,0 +1,92 @@+import {+ assertEquals,+} from "https://deno.land/[email protected]/testing/asserts.ts";+import {+ allocateVarianceAcrossLayers,+ type ReceiptLayerLike,+} from "./purchase-cost-adjustment.ts";++// Golden-master tests for the invoice-vs-receipt variance split. Scenarios+// mirror .ai/plans/2026-07-10-purchase-cost-layer-gl-consistency.md (S1–S3):+// on-hand units absorb their share of the variance into inventory via+// per-layer adjustments; consumed units send their share to PPV.++const layer = (+ id: string,+ quantity: number,+ remainingQuantity: number+): ReceiptLayerLike => ({ id, quantity, remainingQuantity });++Deno.test("S1: full coverage — all variance to inventory, one adjustment", () => {+ const result = allocateVarianceAcrossLayers([layer("L1", 2, 2)], 2, 20);+ assertEquals(result.inventoryShare, 20);+ assertEquals(result.ppvShare, 0);+ assertEquals(result.perLayer, [+ { costLedgerId: "L1", appliedQuantity: 2, adjustmentCost: 20 },+ ]);+});++Deno.test("S2: partial coverage — split between inventory and PPV", () => {+ // 2 received @30, 1 already consumed, invoice 2 @40 → variance 20+ const result = allocateVarianceAcrossLayers([layer("L1", 2, 1)], 2, 20);+ assertEquals(result.inventoryShare, 10);+ assertEquals(result.ppvShare, 10);+ assertEquals(result.perLayer, [+ { costLedgerId: "L1", appliedQuantity: 1, adjustmentCost: 10 },+ ]);+});++Deno.test("S3 second invoice: zero coverage — all variance to PPV", () => {+ const result = allocateVarianceAcrossLayers([layer("L1", 2, 0)], 1, 10);+ assertEquals(result.inventoryShare, 0);+ assertEquals(result.ppvShare, 10);+ assertEquals(result.perLayer, []);+});++Deno.test("negative variance (credit) — full coverage writes inventory down", () => {+ const result = allocateVarianceAcrossLayers([layer("L1", 2, 2)], 2, -20);+ assertEquals(result.inventoryShare, -20);+ assertEquals(result.ppvShare, 0);+ assertEquals(result.perLayer, [+ { costLedgerId: "L1", appliedQuantity: 2, adjustmentCost: -20 },+ ]);+});++Deno.test("multi-layer allocation in FIFO order", () => {+ // matched 5 @ perUnit 2; layer A has 1 remaining, layer B has 2 remaining+ const result = allocateVarianceAcrossLayers(+ [layer("A", 3, 1), layer("B", 2, 2)],+ 5,+ 10+ );+ assertEquals(result.perLayer, [+ { costLedgerId: "A", appliedQuantity: 1, adjustmentCost: 2 },+ { costLedgerId: "B", appliedQuantity: 2, adjustmentCost: 4 },+ ]);+ assertEquals(result.inventoryShare, 6);+ assertEquals(result.ppvShare, 4);+});++Deno.test("immaterial variance — all zeros, no adjustments", () => {+ const result = allocateVarianceAcrossLayers([layer("L1", 2, 2)], 2, 0.004);+ assertEquals(result.inventoryShare, 0);+ assertEquals(result.ppvShare, 0);+ assertEquals(result.perLayer, []);+});++Deno.test("zero matched quantity — variance passes through to PPV", () => {+ const result = allocateVarianceAcrossLayers([], 0, 10);+ assertEquals(result.inventoryShare, 0);+ assertEquals(result.ppvShare, 10);+ assertEquals(result.perLayer, []);+});++Deno.test("coverage exceeding matched quantity is capped at matched", () => {+ // 5 remaining on the layer but only 2 matched by this invoice+ const result = allocateVarianceAcrossLayers([layer("L1", 5, 5)], 2, 10);+ assertEquals(result.perLayer, [+ { costLedgerId: "L1", appliedQuantity: 2, adjustmentCost: 10 },+ ]);+ assertEquals(result.inventoryShare, 10);+ assertEquals(result.ppvShare, 0);+});diff --git a/packages/database/supabase/functions/shared/purchase-cost-adjustment.ts b/packages/database/supabase/functions/shared/purchase-cost-adjustment.tsnew file mode 100644index 0000000000..b51a2c0388--- /dev/null+++ b/packages/database/supabase/functions/shared/purchase-cost-adjustment.ts@@ -0,0 +1,53 @@+export interface ReceiptLayerLike {+ id: string;+ quantity: number; // original layer quantity+ remainingQuantity: number; // unconsumed units+}++export interface VarianceAllocation {+ inventoryShare: number; // GL: Dr Inventory (write-up of on-hand goods)+ ppvShare: number; // GL: Dr PPV (variance on already-consumed goods)+ perLayer: {+ costLedgerId: string;+ appliedQuantity: number; // units of this layer the adjustment applies to+ adjustmentCost: number; // total cost bump for those units+ }[];+}++/**+ * Split an invoice-vs-receipt price variance for `matchedQuantity` units across+ * the receipt layers that hold them. Units still on hand absorb their share of+ * the variance into inventory (per-layer adjustment child rows); units already+ * consumed send their share to PPV. Layers must be passed in FIFO order.+ */+export function allocateVarianceAcrossLayers(+ layers: ReceiptLayerLike[],+ matchedQuantity: number,+ variance: number+): VarianceAllocation {+ if (matchedQuantity <= 0 || Math.abs(variance) <= 0.005) {+ return {+ inventoryShare: 0,+ ppvShare: Math.abs(variance) > 0.005 ? variance : 0,+ perLayer: [],+ };+ }+ const perUnit = variance / matchedQuantity;+ let uncovered = matchedQuantity;+ let inventoryShare = 0;+ const perLayer: VarianceAllocation["perLayer"] = [];+ for (const layer of layers) {+ if (uncovered <= 0) break;+ const applied = Math.min(Math.max(layer.remainingQuantity, 0), uncovered);+ if (applied <= 0) continue;+ const adjustmentCost = perUnit * applied;+ perLayer.push({+ costLedgerId: layer.id,+ appliedQuantity: applied,+ adjustmentCost,+ });+ inventoryShare += adjustmentCost;+ uncovered -= applied;+ }+ return { inventoryShare, ppvShare: variance - inventoryShare, perLayer };+}diff --git a/packages/database/supabase/functions/update-purchased-prices/index.ts b/packages/database/supabase/functions/update-purchased-prices/index.tsindex 0f31a9d384..d5341bb430 100644--- a/packages/database/supabase/functions/update-purchased-prices/index.ts+++ b/packages/database/supabase/functions/update-purchased-prices/index.ts@@ -128,7 +128,10 @@ serve(async (req: Request) => {.where("companyId", "=", companyId).execute();- // Create new cost ledger entries for each line item+ // Create new cost ledger entries for each line item. These are+ // planning/cost-history rows, NOT inventory layers — real layers+ // are created at receipt posting. remainingQuantity stays 0 so+ // FIFO/LIFO consumption can never eat unreceived stock.const costLedgerInserts = lines.filter((line) => line.itemId && line.unitPrice !== 0).map((line) => ({@@ -141,7 +144,7 @@ serve(async (req: Request) => {quantity: line.quantity,cost:(line.quantity / (line.conversionFactor ?? 1)) * line.unitPrice,- remainingQuantity: line.quantity,+ remainingQuantity: 0,supplierId,companyId,}));@@ -269,7 +272,11 @@ serve(async (req: Request) => {};}- historicalPartCosts[ledger.itemId].quantity += ledger.quantity;+ // Adjustment child rows (invoice-vs-receipt price corrections)+ // carry cost but no additional physical quantity+ if (!ledger.adjustment) {+ historicalPartCosts[ledger.itemId].quantity += ledger.quantity;+ }historicalPartCosts[ledger.itemId].cost += ledger.cost;}});@@ -382,7 +389,12 @@ serve(async (req: Request) => {const hasLeadTimeHistory =(historicalPartLeadTimes[line.itemId]?.quantity ?? 0) > 0;- if (shouldUpdatePrices && line.unitPrice !== 0 && costHistory) {+ if (+ shouldUpdatePrices &&+ line.unitPrice !== 0 &&+ costHistory &&+ costHistory.quantity > 0+ ) {itemCostUpdates.push({itemId: line.itemId,unitCost: costHistory.cost / costHistory.quantity,diff --git a/packages/database/supabase/migrations/20260710033458_cost-ledger-adjustment-links.sql b/packages/database/supabase/migrations/20260710033458_cost-ledger-adjustment-links.sqlnew file mode 100644index 0000000000..1563c21382--- /dev/null+++ b/packages/database/supabase/migrations/20260710033458_cost-ledger-adjustment-links.sql@@ -0,0 +1,16 @@+-- Layer cost adjustments are child rows pointing at the layer they adjust+-- (inventory-valuation spec decision #11: never mutate a posted layer's cost).+ALTER TABLE "costLedger"+ ADD COLUMN IF NOT EXISTS "appliesToCostLedgerId" TEXT;++CREATE INDEX IF NOT EXISTS "costLedger_appliesToCostLedgerId_idx"+ ON "costLedger" ("appliesToCostLedgerId")+ WHERE "appliesToCostLedgerId" IS NOT NULL;++-- 'Purchase Order' costLedger rows are planning/cost-history artifacts written at PO+-- finalization (update-purchased-prices), not real inventory layers. Make them+-- non-consumable so FIFO/LIFO never eats stock that hasn't been received.+UPDATE "costLedger"+SET "remainingQuantity" = 0+WHERE "documentType" = 'Purchase Order'+ AND "remainingQuantity" IS DISTINCT FROM 0;diff --git a/packages/database/supabase/migrations/20260710044431_backflush-consumes-cost-adjustments.sql b/packages/database/supabase/migrations/20260710044431_backflush-consumes-cost-adjustments.sqlnew file mode 100644index 0000000000..15e0a74a86--- /dev/null+++ b/packages/database/supabase/migrations/20260710044431_backflush-consumes-cost-adjustments.sql@@ -0,0 +1,404 @@+-- backflush_job_materials is the PL/pgSQL twin of shared/calculate-cogs.ts.+-- Fork of the latest definition (20260706182830_fix-null-user-audit-columns.sql)+-- teaching its FIFO/LIFO loop about invoice-vs-receipt cost adjustment children+-- ("appliesToCostLedgerId"): base layers exclude children and 'Purchase Order'+-- pseudo-layers, and consuming a layer also consumes its children pro-rata so+-- job material cost matches the GL inventory value (receipt + invoice write-up).++DROP FUNCTION IF EXISTS backflush_job_materials(TEXT, NUMERIC, TEXT, TEXT);++CREATE OR REPLACE FUNCTION backflush_job_materials(+ p_job_id TEXT,+ p_quantity_complete NUMERIC,+ p_company_id TEXT,+ p_user_id TEXT+)+RETURNS VOID+LANGUAGE plpgsql+SECURITY DEFINER+SET search_path = public+AS $$+DECLARE+ v_job_quantity NUMERIC;+ v_job_location_id TEXT;+ v_job_id_readable TEXT;+ v_ratio NUMERIC;+ v_target NUMERIC;+ v_material RECORD;+ v_material_qty_to_issue NUMERIC;+ v_material_storage_unit_id TEXT;+ v_material_costing_method TEXT;+ v_material_standard_cost NUMERIC;+ v_material_unit_cost NUMERIC;+ v_material_item_posting_group_id TEXT;+ v_material_cogs_total NUMERIC;+ v_cost_layer RECORD;+ v_remaining_to_consume NUMERIC;+ v_layer_unit_cost NUMERIC;+ v_quantity_from_layer NUMERIC;+ v_adjustment_child RECORD;+ v_child_budget NUMERIC;+ v_child_apply NUMERIC;+ v_child_per_unit NUMERIC;+ v_accounting_enabled BOOLEAN;+ v_company_group_id TEXT;+ v_inventory_account TEXT;+ v_wip_account TEXT;+ v_dimension_item_posting_group TEXT;+ v_dimension_item TEXT;+ v_dimension_location TEXT;+ v_bf_item_ids TEXT[] := '{}';+ v_bf_quantities NUMERIC[] := '{}';+ v_bf_storage_unit_ids TEXT[] := '{}';+ v_bf_journal_id TEXT;+ v_bf_journal_entry_id TEXT;+ v_bf_accounting_period_id TEXT;+ v_bf_journal_line_ref TEXT;+ v_bf_jl_id TEXT;+ v_bf_jl_ids TEXT[];+ v_bf_posting_group_ids TEXT[];+ v_bf_line_item_ids TEXT[];+BEGIN+ -- Never let a NULL user reach NOT NULL audit columns; fall back to the job creator+ p_user_id := COALESCE(p_user_id, (SELECT "createdBy" FROM "job" WHERE id = p_job_id));++ -- Fetch job details+ SELECT quantity, "locationId", "jobId"+ INTO STRICT v_job_quantity, v_job_location_id, v_job_id_readable+ FROM "job"+ WHERE id = p_job_id;++ IF v_job_quantity IS NULL OR v_job_quantity <= 0 THEN+ RETURN;+ END IF;++ v_ratio := p_quantity_complete / v_job_quantity;++ -- Backflush non-tracked materials+ FOR v_material IN+ SELECT jm.id, jm."itemId", jm."quantityToIssue", jm."quantityIssued",+ jm."estimatedQuantity", jm."storageUnitId", jm."defaultStorageUnit"+ FROM "jobMaterial" jm+ WHERE jm."jobId" = p_job_id+ AND jm."itemType" IN ('Material', 'Part', 'Consumable')+ AND jm."methodType" != 'Make to Order'+ AND jm."requiresBatchTracking" = false+ AND jm."requiresSerialTracking" = false+ AND jm."quantityToIssue" > 0+ LOOP+ -- Prorate: only issue what's needed for the completed quantity+ v_target := v_material."estimatedQuantity" * v_ratio;+ v_material_qty_to_issue := GREATEST(v_target - COALESCE(v_material."quantityIssued", 0), 0);++ IF v_material_qty_to_issue <= 0 THEN+ CONTINUE;+ END IF;++ -- Resolve storage unit+ v_material_storage_unit_id := v_material."storageUnitId";++ IF v_material_storage_unit_id IS NULL AND v_material."defaultStorageUnit" THEN+ SELECT "defaultStorageUnitId" INTO v_material_storage_unit_id+ FROM "pickMethod"+ WHERE "itemId" = v_material."itemId"+ AND "locationId" = v_job_location_id+ AND "companyId" = p_company_id;+ END IF;++ IF v_material_storage_unit_id IS NULL THEN+ SELECT "storageUnitId" INTO v_material_storage_unit_id+ FROM "itemLedger"+ WHERE "itemId" = v_material."itemId"+ AND "locationId" = v_job_location_id+ AND "storageUnitId" IS NOT NULL+ GROUP BY "storageUnitId"+ HAVING SUM(quantity) > 0+ ORDER BY SUM(quantity) DESC+ LIMIT 1;+ END IF;++ INSERT INTO "itemLedger" (+ "entryType", "documentType", "documentId", "companyId",+ "itemId", quantity, "locationId", "storageUnitId", "createdBy"+ ) VALUES (+ 'Consumption', 'Job Consumption', p_job_id, p_company_id,+ v_material."itemId", -v_material_qty_to_issue,+ v_job_location_id, v_material_storage_unit_id, p_user_id+ );++ UPDATE "jobMaterial"+ SET "quantityIssued" = COALESCE("quantityIssued", 0) + v_material_qty_to_issue+ WHERE id = v_material.id;++ v_bf_item_ids := v_bf_item_ids || v_material."itemId";+ v_bf_quantities := v_bf_quantities || v_material_qty_to_issue;+ v_bf_storage_unit_ids := v_bf_storage_unit_ids || COALESCE(v_material_storage_unit_id, '');+ END LOOP;++ -- Check if accounting is enabled+ SELECT "accountingEnabled"+ INTO v_accounting_enabled+ FROM "companySettings"+ WHERE id = p_company_id;++ v_accounting_enabled := COALESCE(v_accounting_enabled, false);++ IF NOT v_accounting_enabled THEN+ RETURN;+ END IF;++ IF array_length(v_bf_item_ids, 1) IS NULL OR array_length(v_bf_item_ids, 1) = 0 THEN+ RETURN;+ END IF;++ -- Fetch company group+ SELECT "companyGroupId"+ INTO STRICT v_company_group_id+ FROM company+ WHERE id = p_company_id;++ -- Fetch account defaults+ SELECT "inventoryAccount", "workInProgressAccount"+ INTO STRICT v_inventory_account, v_wip_account+ FROM "accountDefault"+ WHERE "companyId" = p_company_id;++ -- Fetch dimension IDs+ SELECT+ MAX(CASE WHEN "entityType" = 'ItemPostingGroup' THEN id END),+ MAX(CASE WHEN "entityType" = 'Item' THEN "id" END),+ MAX(CASE WHEN "entityType" = 'Location' THEN id END)+ INTO v_dimension_item_posting_group, v_dimension_item, v_dimension_location+ FROM dimension+ WHERE "companyGroupId" = v_company_group_id+ AND active = true+ AND "entityType" IN ('ItemPostingGroup', 'Item', 'Location');++ -- Get accounting period+ SELECT id INTO v_bf_accounting_period_id+ FROM "accountingPeriod"+ WHERE "companyId" = p_company_id+ AND "startDate" <= CURRENT_DATE+ AND "endDate" >= CURRENT_DATE+ AND status = 'Active'+ LIMIT 1;++ IF v_bf_accounting_period_id IS NULL THEN+ UPDATE "accountingPeriod"+ SET status = 'Inactive'+ WHERE status = 'Active' AND "companyId" = p_company_id;++ UPDATE "accountingPeriod"+ SET status = 'Active'+ WHERE "companyId" = p_company_id+ AND "startDate" <= CURRENT_DATE+ AND "endDate" >= CURRENT_DATE+ RETURNING id INTO v_bf_accounting_period_id;++ IF v_bf_accounting_period_id IS NULL THEN+ INSERT INTO "accountingPeriod" (+ "startDate", "endDate", "companyId", status, "createdBy"+ ) VALUES (+ date_trunc('month', CURRENT_DATE)::DATE,+ (date_trunc('month', CURRENT_DATE) + INTERVAL '1 month' - INTERVAL '1 day')::DATE,+ p_company_id, 'Active', 'system'+ )+ RETURNING id INTO v_bf_accounting_period_id;+ END IF;+ END IF;++ v_bf_journal_entry_id := get_next_sequence('journalEntry', p_company_id);++ INSERT INTO journal (+ "journalEntryId", "accountingPeriodId", description,+ "postingDate", "companyId", "sourceType", status,+ "postedAt", "postedBy", "createdBy"+ ) VALUES (+ v_bf_journal_entry_id, v_bf_accounting_period_id,+ 'Material Issue — Job ' || v_job_id_readable,+ CURRENT_DATE, p_company_id, 'Job Consumption', 'Posted',+ NOW(), p_user_id, p_user_id+ )+ RETURNING id INTO v_bf_journal_id;++ v_bf_jl_ids := '{}';+ v_bf_posting_group_ids := '{}';+ v_bf_line_item_ids := '{}';++ FOR i IN 1..array_length(v_bf_item_ids, 1)+ LOOP+ -- Get itemCost for COGS calculation+ SELECT "costingMethod", "standardCost", "unitCost", "itemPostingGroupId"+ INTO v_material_costing_method, v_material_standard_cost, v_material_unit_cost, v_material_item_posting_group_id+ FROM "itemCost"+ WHERE "itemId" = v_bf_item_ids[i]+ AND "companyId" = p_company_id;++ IF v_material_costing_method IS NULL THEN+ CONTINUE;+ END IF;++ -- Calculate COGS based on costing method+ v_material_cogs_total := 0;++ IF v_material_costing_method = 'Standard' THEN+ v_material_cogs_total := COALESCE(v_material_standard_cost, 0) * v_bf_quantities[i];++ ELSIF v_material_costing_method = 'Average' THEN+ v_material_cogs_total := COALESCE(v_material_unit_cost, 0) * v_bf_quantities[i];++ ELSIF v_material_costing_method IN ('FIFO', 'LIFO') THEN+ v_remaining_to_consume := v_bf_quantities[i];++ FOR v_cost_layer IN+ SELECT id, quantity, cost, "remainingQuantity"+ FROM "costLedger"+ WHERE "itemId" = v_bf_item_ids[i]+ AND "companyId" = p_company_id+ AND "remainingQuantity" > 0+ -- adjustment child rows are consumed with their parent, not as layers+ AND adjustment = false+ AND "appliesToCostLedgerId" IS NULL+ -- 'Purchase Order' rows are planning/cost-history artifacts, not layers+ AND ("documentType" IS NULL OR "documentType" <> 'Purchase Order')+ ORDER BY+ CASE WHEN v_material_costing_method = 'FIFO' THEN "postingDate" END ASC,+ CASE WHEN v_material_costing_method = 'LIFO' THEN "postingDate" END DESC,+ CASE WHEN v_material_costing_method = 'FIFO' THEN "createdAt" END ASC,+ CASE WHEN v_material_costing_method = 'LIFO' THEN "createdAt" END DESC+ LOOP+ EXIT WHEN v_remaining_to_consume <= 0;++ v_layer_unit_cost := CASE+ WHEN v_cost_layer.quantity > 0 THEN v_cost_layer.cost / v_cost_layer.quantity+ ELSE 0+ END;++ v_quantity_from_layer := LEAST(v_remaining_to_consume, v_cost_layer."remainingQuantity");+ v_material_cogs_total := v_material_cogs_total + v_quantity_from_layer * v_layer_unit_cost;+ v_remaining_to_consume := v_remaining_to_consume - v_quantity_from_layer;++ UPDATE "costLedger"+ SET "remainingQuantity" = "remainingQuantity" - v_quantity_from_layer+ WHERE id = v_cost_layer.id;++ -- Consume the layer's cost-adjustment children (invoice-vs-receipt+ -- price corrections linked via "appliesToCostLedgerId") alongside the+ -- parent: each adjusted unit carries a bump of child.cost/child.quantity.+ -- Mirrors shared/calculate-cogs.ts.+ v_child_budget := v_quantity_from_layer;+ FOR v_adjustment_child IN+ SELECT id, quantity, cost, "remainingQuantity"+ FROM "costLedger"+ WHERE "appliesToCostLedgerId" = v_cost_layer.id+ AND "remainingQuantity" > 0+ ORDER BY "createdAt" ASC+ LOOP+ EXIT WHEN v_child_budget <= 0;++ v_child_per_unit := CASE+ WHEN v_adjustment_child.quantity > 0+ THEN v_adjustment_child.cost / v_adjustment_child.quantity+ ELSE 0+ END;++ v_child_apply := LEAST(v_adjustment_child."remainingQuantity", v_child_budget);+ v_material_cogs_total := v_material_cogs_total + v_child_apply * v_child_per_unit;+ v_child_budget := v_child_budget - v_child_apply;++ UPDATE "costLedger"+ SET "remainingQuantity" = "remainingQuantity" - v_child_apply+ WHERE id = v_adjustment_child.id;+ END LOOP;+ END LOOP;++ -- Fallback for negative inventory+ IF v_remaining_to_consume > 0 THEN+ v_material_cogs_total := v_material_cogs_total + v_remaining_to_consume * COALESCE(v_material_unit_cost, 0);+ END IF;+ END IF;++ IF v_material_cogs_total <= 0 THEN+ CONTINUE;+ END IF;++ v_bf_journal_line_ref := nanoid();++ -- DR WIP+ INSERT INTO "journalLine" (+ "journalId", "accountId", description, amount, quantity,+ "documentType", "documentId", "documentLineReference",+ "journalLineReference", "companyId"+ ) VALUES (+ v_bf_journal_id, v_wip_account, 'WIP Account',+ v_material_cogs_total, v_bf_quantities[i],+ 'Job Consumption', p_job_id, 'job:' || p_job_id,+ v_bf_journal_line_ref, p_company_id+ )+ RETURNING id INTO v_bf_jl_id;++ v_bf_jl_ids := v_bf_jl_ids || v_bf_jl_id;+ v_bf_posting_group_ids := v_bf_posting_group_ids || COALESCE(v_material_item_posting_group_id, '');+ v_bf_line_item_ids := v_bf_line_item_ids || COALESCE(v_bf_item_ids[i], '');++ -- CR Inventory+ INSERT INTO "journalLine" (+ "journalId", "accountId", description, amount, quantity,+ "documentType", "documentId", "documentLineReference",+ "journalLineReference", "companyId"+ ) VALUES (+ v_bf_journal_id, v_inventory_account, 'Inventory Account',+ -v_material_cogs_total, v_bf_quantities[i],+ 'Job Consumption', p_job_id, 'job:' || p_job_id,+ v_bf_journal_line_ref, p_company_id+ )+ RETURNING id INTO v_bf_jl_id;++ v_bf_jl_ids := v_bf_jl_ids || v_bf_jl_id;+ v_bf_posting_group_ids := v_bf_posting_group_ids || COALESCE(v_material_item_posting_group_id, '');+ v_bf_line_item_ids := v_bf_line_item_ids || COALESCE(v_bf_item_ids[i], '');++ -- Cost ledger entry for consumption+ INSERT INTO "costLedger" (+ "itemLedgerType", "costLedgerType", adjustment,+ "documentType", "documentId", "itemId",+ quantity, cost, "remainingQuantity", "companyId"+ ) VALUES (+ 'Consumption', 'Direct Cost', false,+ 'Job Consumption', p_job_id, v_bf_item_ids[i],+ -v_bf_quantities[i], -v_material_cogs_total,+ 0, p_company_id+ );+ END LOOP;++ -- Dimensions for material consumption journal lines+ IF array_length(v_bf_jl_ids, 1) IS NOT NULL THEN+ FOR i IN 1..array_length(v_bf_jl_ids, 1)+ LOOP+ IF v_bf_posting_group_ids[i] != '' AND v_dimension_item_posting_group IS NOT NULL THEN+ INSERT INTO "journalLineDimension" (+ "journalLineId", "dimensionId", "valueId", "companyId"+ ) VALUES (+ v_bf_jl_ids[i], v_dimension_item_posting_group, v_bf_posting_group_ids[i], p_company_id+ );+ END IF;++ IF v_dimension_item IS NOT NULL AND v_bf_line_item_ids[i] != '' THEN+ INSERT INTO "journalLineDimension" (+ "journalLineId", "dimensionId", "valueId", "companyId"+ ) VALUES (+ v_bf_jl_ids[i], v_dimension_item, v_bf_line_item_ids[i], p_company_id+ );+ END IF;++ IF v_job_location_id IS NOT NULL AND v_dimension_location IS NOT NULL THEN+ INSERT INTO "journalLineDimension" (+ "journalLineId", "dimensionId", "valueId", "companyId"+ ) VALUES (+ v_bf_jl_ids[i], v_dimension_location, v_job_location_id, p_company_id+ );+ END IF;+ END LOOP;+ END IF;+END;+$$;diff --git a/packages/database/supabase/migrations/20260710051147_mto-sales-lines-drive-demand.sql b/packages/database/supabase/migrations/20260710051147_mto-sales-lines-drive-demand.sqlnew file mode 100644index 0000000000..757849d7a4--- /dev/null+++ b/packages/database/supabase/migrations/20260710051147_mto-sales-lines-drive-demand.sql@@ -0,0 +1,49 @@+-- Make to Order sales order lines drive planning demand until a live job+-- covers them. Previously the view excluded MTO lines outright, so a confirmed+-- order for a manufactured item produced no purchasing/production demand at all+-- until someone created the job. Now an MTO line contributes its uncovered+-- quantity: quantityToSend minus the remaining output of live jobs linked to+-- the line. The job-status set ('Planned','Ready','In Progress','Paused')+-- matches openJobMaterialLines, so each unit is counted exactly once — via the+-- SO line while unjobbed, via job materials once a job is released, and via+-- inventory/shipment once produced. Draft and Cancelled jobs do not suppress+-- line demand (their materials drive nothing).+--+-- Also restores WITH (security_invoker=true), which 20250616011758 added and+-- the 20260417000300 recreate accidentally dropped.++DROP VIEW IF EXISTS "openSalesOrderLines";+CREATE VIEW "openSalesOrderLines" WITH (security_invoker=true) AS (+ SELECT+ sol."id",+ sol."salesOrderId",+ sol."itemId",+ sol."promisedDate",+ sol."methodType",+ sol."unitOfMeasureCode",+ CASE+ WHEN sol."methodType" = 'Make to Order' THEN GREATEST(+ sol."quantityToSend" - COALESCE((+ SELECT SUM(GREATEST(j."quantity" - j."quantityReceivedToInventory" - j."quantityShipped", 0))+ FROM "job" j+ WHERE j."salesOrderLineId" = sol."id"+ AND j."companyId" = sol."companyId"+ AND j."status" IN ('Planned', 'Ready', 'In Progress', 'Paused')+ ), 0),+ 0+ )+ ELSE sol."quantityToSend"+ END AS "quantityToSend",+ sol."salesOrderLineType",+ sol."companyId",+ COALESCE(sol."locationId", so."locationId") AS "locationId",+ i."replenishmentSystem",+ i."itemTrackingType",+ ir."leadTime"+ FROM "salesOrderLine" sol+ INNER JOIN "salesOrder" so ON sol."salesOrderId" = so."id"+ INNER JOIN "item" i ON sol."itemId" = i."id"+ INNER JOIN "itemReplenishment" ir ON i."id" = ir."itemId"+ WHERE sol."salesOrderLineType" != 'Service'+ AND so."status" IN ('To Ship', 'To Ship and Invoice')+);diff --git a/packages/locale/locales/de/erp.po b/packages/locale/locales/de/erp.poindex 8fb453944a..9b271e47ae 100644--- a/packages/locale/locales/de/erp.po+++ b/packages/locale/locales/de/erp.po@@ -91,6 +91,9 @@ msgstr "{chainLabel}. Erwägen Sie, diesen Teil direkt auf den endgültigen Nachmsgid "{count, plural, one {# course} other {# courses}}"msgstr "{count, plural, one {# Kurs} other {# Kurse}}"+msgid "{done} of {total} phases complete"+msgstr "{done} von {total} Phasen abgeschlossen"+msgid "{from}–{to} of {count}"msgstr "{from}–{to} von {count}"@@ -7946,9 +7949,6 @@ msgstr "OEM (Original Equipment Manufacturer)"msgid "of"msgstr "von"-msgid "of {total} phases complete"-msgstr "von {total} Phasen abgeschlossen"-msgid "OK"msgstr "OK"diff --git a/packages/locale/locales/en/erp.po b/packages/locale/locales/en/erp.poindex 015b76914a..15e398b980 100644--- a/packages/locale/locales/en/erp.po+++ b/packages/locale/locales/en/erp.po@@ -91,6 +91,9 @@ msgstr "{chainLabel}. Consider pointing this part directly at the final successomsgid "{count, plural, one {# course} other {# courses}}"msgstr "{count, plural, one {# course} other {# courses}}"+msgid "{done} of {total} phases complete"+msgstr "{done} of {total} phases complete"+msgid "{from}–{to} of {count}"msgstr "{from}–{to} of {count}"@@ -7946,9 +7949,6 @@ msgstr "OEM (original equipment manufacturer)"msgid "of"msgstr "of"-msgid "of {total} phases complete"-msgstr "of {total} phases complete"-msgid "OK"msgstr "OK"diff --git a/packages/locale/locales/es/erp.po b/packages/locale/locales/es/erp.poindex e2dff7f28d..17e900f6e1 100644--- a/packages/locale/locales/es/erp.po+++ b/packages/locale/locales/es/erp.po@@ -91,6 +91,9 @@ msgstr "{chainLabel}. Considere apuntar esta pieza directamente al sucesor finalmsgid "{count, plural, one {# course} other {# courses}}"msgstr "{count, plural, one {# curso} other {# cursos}}"+msgid "{done} of {total} phases complete"+msgstr "{done} de {total} fases completadas"+msgid "{from}–{to} of {count}"msgstr "{from}–{to} de {count}"@@ -7946,9 +7949,6 @@ msgstr "OEM (fabricante de equipos originales)"msgid "of"msgstr "de"-msgid "of {total} phases complete"-msgstr "de {total} fases completadas"-msgid "OK"msgstr "Aceptar"diff --git a/packages/locale/locales/fr/erp.po b/packages/locale/locales/fr/erp.poindex 629ff129d3..607c69c72d 100644--- a/packages/locale/locales/fr/erp.po+++ b/packages/locale/locales/fr/erp.po@@ -91,6 +91,9 @@ msgstr "{chainLabel}. Envisagez de pointer cette pièce directement vers le succmsgid "{count, plural, one {# course} other {# courses}}"msgstr "{count, plural, one {# cours} other {# cours}}"+msgid "{done} of {total} phases complete"+msgstr "{done} sur {total} phases terminées"+msgid "{from}–{to} of {count}"msgstr "{from}–{to} sur {count}"@@ -7946,9 +7949,6 @@ msgstr "OEM (fabricant d'équipement d'origine)"msgid "of"msgstr "de"-msgid "of {total} phases complete"-msgstr "de {total} phases complètes"-msgid "OK"msgstr "OK"diff --git a/packages/locale/locales/hi/erp.po b/packages/locale/locales/hi/erp.poindex c042efad51..4a040b9cab 100644--- a/packages/locale/locales/hi/erp.po+++ b/packages/locale/locales/hi/erp.po@@ -91,6 +91,9 @@ msgstr "{chainLabel}. इस भाग को सीधे अंतिम उmsgid "{count, plural, one {# course} other {# courses}}"msgstr "{count, plural, one {# कोर्स} other {# कोर्स}}"+msgid "{done} of {total} phases complete"+msgstr "{done} में से {total} चरण पूर्ण"+msgid "{from}–{to} of {count}"msgstr "{from}–{to} में से {count}"@@ -7946,9 +7949,6 @@ msgstr "OEM (मूल उपकरण निर्माता)"msgid "of"msgstr "का"-msgid "of {total} phases complete"-msgstr "of {total} phases complete"-msgid "OK"msgstr "ठीक है"diff --git a/packages/locale/locales/it/erp.po b/packages/locale/locales/it/erp.poindex 0a8d6057f2..de29c358dc 100644--- a/packages/locale/locales/it/erp.po+++ b/packages/locale/locales/it/erp.po@@ -91,6 +91,9 @@ msgstr "{chainLabel}. Considera di indirizzare direttamente questa parte al succmsgid "{count, plural, one {# course} other {# courses}}"msgstr "{count, plural, one {# corso} other {# corsi}}"+msgid "{done} of {total} phases complete"+msgstr "{done} di {total} fasi completate"+msgid "{from}–{to} of {count}"msgstr "{from}–{to} di {count}"@@ -7946,9 +7949,6 @@ msgstr "OEM (Original Equipment Manufacturer)"msgid "of"msgstr "di"-msgid "of {total} phases complete"-msgstr "di {total} fasi completate"-msgid "OK"msgstr "OK"diff --git a/packages/locale/locales/ja/erp.po b/packages/locale/locales/ja/erp.poindex c9cd46a4dc..fe5c369255 100644--- a/packages/locale/locales/ja/erp.po+++ b/packages/locale/locales/ja/erp.po@@ -91,6 +91,9 @@ msgstr "{chainLabel}。このパーツを最終的な後継品に直接指定すmsgid "{count, plural, one {# course} other {# courses}}"msgstr "{count, plural, one {# コース} other {# コース}}"+msgid "{done} of {total} phases complete"+msgstr "{done} / {total} フェーズ完了"+msgid "{from}–{to} of {count}"msgstr "{from}–{to} / {count}"@@ -7946,9 +7949,6 @@ msgstr "OEM (オリジナル機器メーカー)"msgid "of"msgstr "の"-msgid "of {total} phases complete"-msgstr "{total}フェーズ中完了"-msgid "OK"msgstr "OK"diff --git a/packages/locale/locales/ko/erp.po b/packages/locale/locales/ko/erp.poindex 10dc2e7004..f5a4d5a4e7 100644--- a/packages/locale/locales/ko/erp.po+++ b/packages/locale/locales/ko/erp.po@@ -91,6 +91,9 @@ msgstr "{chainLabel}. 이 품목을 최종 후속 품목으로 직접 연결하msgid "{count, plural, one {# course} other {# courses}}"msgstr "교육과정 {count}개"+msgid "{done} of {total} phases complete"+msgstr "{done}개 중 {total}개 단계 완료"+msgid "{from}–{to} of {count}"msgstr "{count}개 중 {from}–{to}"@@ -1372,10 +1375,10 @@ msgid "Ask an admin with {0} permission to add the first {1}."msgstr "{0} 권한이 있는 관리자에게 첫 {1} 추가를 요청하세요."msgid "Assemblies"-msgstr ""+msgstr "조립품"msgid "Assembly Instructions"-msgstr ""+msgstr "조립 지침"msgid "Assembly:"msgstr "조립:"@@ -7946,9 +7949,6 @@ msgstr "OEM(주문자상표부착생산)"msgid "of"msgstr "중"-msgid "of {total} phases complete"-msgstr "/{total}단계 완료"-msgid "OK"msgstr "확인"diff --git a/packages/locale/locales/ko/mes.po b/packages/locale/locales/ko/mes.poindex f1a3ad515a..b558ae48d3 100644--- a/packages/locale/locales/ko/mes.po+++ b/packages/locale/locales/ko/mes.po@@ -765,7 +765,7 @@ msgid "Preventive"msgstr "예방"msgid "Previous"-msgstr ""+msgstr "이전"msgid "Print"msgstr "인쇄"diff --git a/packages/locale/locales/pl/erp.po b/packages/locale/locales/pl/erp.poindex 0cd2b7035f..d9b0426ba4 100644--- a/packages/locale/locales/pl/erp.po+++ b/packages/locale/locales/pl/erp.po@@ -91,6 +91,9 @@ msgstr "{chainLabel}. Rozważ wskazanie tej części bezpośrednio na ostatecznemsgid "{count, plural, one {# course} other {# courses}}"msgstr "{count, plural, one {# kurs} other {# kursy}}"+msgid "{done} of {total} phases complete"+msgstr "{done} z {total} faz ukończonych"+msgid "{from}–{to} of {count}"msgstr "{from}–{to} z {count}"@@ -7946,9 +7949,6 @@ msgstr "OEM (producent oryginalnego sprzętu)"msgid "of"msgstr "z"-msgid "of {total} phases complete"-msgstr "z {total} faz ukończonych"-msgid "OK"msgstr "OK"diff --git a/packages/locale/locales/pt/erp.po b/packages/locale/locales/pt/erp.poindex 5f54d70e74..305b962a60 100644--- a/packages/locale/locales/pt/erp.po+++ b/packages/locale/locales/pt/erp.po@@ -91,6 +91,9 @@ msgstr "{chainLabel}. Considere apontar esta peça diretamente para o sucessor fmsgid "{count, plural, one {# course} other {# courses}}"msgstr "{count, plural, one {# curso} other {# cursos}}"+msgid "{done} of {total} phases complete"+msgstr "{done} de {total} fases concluídas"+msgid "{from}–{to} of {count}"msgstr "{from}–{to} de {count}"@@ -7946,9 +7949,6 @@ msgstr "OEM (fabricante de equipamento original)"msgid "of"msgstr "de"-msgid "of {total} phases complete"-msgstr "de {total} fases completas"-msgid "OK"msgstr "OK"diff --git a/packages/locale/locales/ru/erp.po b/packages/locale/locales/ru/erp.poindex 8aeb65aa65..929be23694 100644--- a/packages/locale/locales/ru/erp.po+++ b/packages/locale/locales/ru/erp.po@@ -91,6 +91,9 @@ msgstr "{chainLabel}. Рассмотрите возможность указанmsgid "{count, plural, one {# course} other {# courses}}"msgstr "{count, plural, one {# курс} other {# курсов}}"+msgid "{done} of {total} phases complete"+msgstr "{done} из {total} этапов завершено"+msgid "{from}–{to} of {count}"msgstr "{from}–{to} из {count}"@@ -7946,9 +7949,6 @@ msgstr "OEM (производитель оригинального оборудmsgid "of"msgstr "из"-msgid "of {total} phases complete"-msgstr "из {total} этапов завершено"-msgid "OK"msgstr "ОК"diff --git a/packages/locale/locales/tr/erp.po b/packages/locale/locales/tr/erp.poindex 9d053900a2..94a2a1a067 100644--- a/packages/locale/locales/tr/erp.po+++ b/packages/locale/locales/tr/erp.po@@ -91,6 +91,9 @@ msgstr "{chainLabel}. Bu parçayı doğrudan son halefine yönlendirmeyi düşümsgid "{count, plural, one {# course} other {# courses}}"msgstr "{count, plural, one {# kurs} other {# kurs}}"+msgid "{done} of {total} phases complete"+msgstr "{done} / {total} aşama tamamlandı"+msgid "{from}–{to} of {count}"msgstr "{from}–{to} / {count}"@@ -7946,9 +7949,6 @@ msgstr "OEM (Orijinal Ekipman Üreticisi)"msgid "of"msgstr "adet"-msgid "of {total} phases complete"-msgstr "{total} aşamanın tamamlandığı"-msgid "OK"msgstr "Tamam"diff --git a/packages/locale/locales/zh/erp.po b/packages/locale/locales/zh/erp.poindex 28da180251..a2fecec434 100644--- a/packages/locale/locales/zh/erp.po+++ b/packages/locale/locales/zh/erp.po@@ -91,6 +91,9 @@ msgstr "{chainLabel}。考虑将此零件直接指向最终后继产品。"msgid "{count, plural, one {# course} other {# courses}}"msgstr "{count, plural, one {# 门课程} other {# 门课程}}"+msgid "{done} of {total} phases complete"+msgstr "{done} 个,共 {total} 个阶段已完成"+msgid "{from}–{to} of {count}"msgstr "{from}–{to} 共 {count}"@@ -7946,9 +7949,6 @@ msgstr "OEM (原始设备制造商)"msgid "of"msgstr "的"-msgid "of {total} phases complete"-msgstr "的 {total} 个阶段已完成"-msgid "OK"msgstr "确定"diff --git a/packages/onboarding/src/ui/GanttChart.tsx b/packages/onboarding/src/ui/GanttChart.tsxindex 0666d044b6..44ab5d07cf 100644--- a/packages/onboarding/src/ui/GanttChart.tsx+++ b/packages/onboarding/src/ui/GanttChart.tsx@@ -20,7 +20,7 @@ export function GanttChart({ steps }: { steps: StepDef[] }) {if (timeline.bars.length === 0) return null;return (- <div className="rounded-2xl border bg-card shadow-button-base p-5 sm:p-6 overflow-x-auto">+ <div className="rounded-2xl border border-border bg-card p-5 sm:p-6 overflow-x-auto"><div className="min-w-[620px]">{!timeline.hasDates ? (<div className="flex items-center justify-end mb-3">diff --git a/packages/onboarding/src/ui/GuidedUpsellCard.tsx b/packages/onboarding/src/ui/GuidedUpsellCard.tsxindex 6125969dd0..50017ddf82 100644--- a/packages/onboarding/src/ui/GuidedUpsellCard.tsx+++ b/packages/onboarding/src/ui/GuidedUpsellCard.tsx@@ -13,12 +13,12 @@ export function GuidedUpsellCard({}) {const { i18n } = useLingui();return (- <section className="rounded-2xl border border-primary/30 bg-primary/5 shadow-button-base p-6 flex items-start gap-4">+ <section className="rounded-2xl border border-border p-6 flex items-start gap-4"><div className="shrink-0 size-11 rounded-2xl bg-primary/15 flex items-center justify-center text-primary"><LuSparkles className="text-xl" /></div><div className="flex-1 min-w-0">- <div className="text-xxs uppercase tracking-wide font-medium text-primary">+ <div className="text-xxs uppercase text-muted-foreground tracking-wide font-medium">{i18n._(GUIDED_UPSELL.eyebrow)}</div><div className="text-base font-semibold tracking-tight mt-0.5 text-balance">diff --git a/packages/onboarding/src/ui/OnboardingHub.tsx b/packages/onboarding/src/ui/OnboardingHub.tsxindex d27ee52c3e..dea7c333fc 100644--- a/packages/onboarding/src/ui/OnboardingHub.tsx+++ b/packages/onboarding/src/ui/OnboardingHub.tsx@@ -102,7 +102,7 @@ export function OnboardingHub({className="size-7 hidden dark:block"/></div>- <h1 className="text-3xl font-semibold tracking-tight text-balance">+ <h1 className="text-3xl font-medium tracking-tight text-balance">{companyName ? (<Trans>Welcome, {companyName}</Trans>) : (@@ -127,12 +127,12 @@ export function OnboardingHub({) : null}{done === total ? (- <div className="rounded-2xl border border-emerald-500/30 bg-emerald-500/5 shadow-button-base p-6 flex items-center gap-4 motion-safe:animate-in motion-safe:fade-in-50 motion-safe:zoom-in-95 motion-safe:duration-500">+ <div className="rounded-2xl border border-emerald-500/30 bg-emerald-500/5 p-6 flex items-center gap-4 motion-safe:animate-in motion-safe:fade-in-50 motion-safe:zoom-in-95 motion-safe:duration-500"><div className="shrink-0 size-12 rounded-2xl bg-emerald-500/15 flex items-center justify-center"><LuPartyPopper className="text-2xl text-emerald-600 dark:text-emerald-400" /></div><div className="flex-1 min-w-0">- <div className="text-lg font-semibold tracking-tight">+ <div className="text-lg font-medium tracking-tight"><Trans>You're live on Carbon</Trans></div><p className="text-sm text-muted-foreground mt-0.5">@@ -150,11 +150,12 @@ export function OnboardingHub({</div>) : null}- <div className="rounded-2xl border bg-card shadow-button-base overflow-hidden">+ <div className="rounded-2xl border bg-card overflow-hidden"><div className="flex items-end justify-between gap-4 flex-wrap p-6 pb-4 border-b">- <div className="text-2xl font-semibold tracking-tight">- <span className="tabular-nums">{done}</span>{" "}- <Trans>of {total} phases complete</Trans>+ <div className="text-base font-medium tracking-tight">+ <Trans>+ {done} of {total} phases complete+ </Trans></div><span className="inline-flex items-center gap-2 text-sm font-medium text-muted-foreground"><span@@ -239,15 +240,15 @@ function NextStepCard({: undefined;return (- <div className="rounded-2xl border border-primary/30 bg-primary/5 shadow-button-base p-5 flex items-start gap-4 motion-safe:animate-in motion-safe:fade-in-50 motion-safe:slide-in-from-bottom-2 motion-safe:duration-300">- <div className="shrink-0 size-9 rounded-xl bg-primary/15 flex items-center justify-center text-sm font-semibold tabular-nums text-primary">+ <div className="rounded-2xl border border-border p-5 flex items-start gap-4 motion-safe:animate-in motion-safe:fade-in-50 motion-safe:slide-in-from-bottom-2 motion-safe:duration-300">+ <div className="shrink-0 size-9 rounded-xl bg-primary/15 flex items-center justify-center text-sm font-medium tabular-nums text-primary">{action.gateNumber}</div><div className="flex-1 min-w-0">- <div className="text-xxs uppercase tracking-wide font-medium text-primary">+ <div className="text-xxs uppercase text-muted-foreground tracking-wide font-medium"><Trans>Next step</Trans></div>- <div className="text-base font-semibold tracking-tight mt-0.5">+ <div className="text-base font-medium tracking-tight mt-0.5">{i18n._(action.title)}</div>{action.detail ? (@@ -342,7 +343,7 @@ function GateRow({<div className="flex items-center gap-2 flex-wrap"><spanclassName={cn(- "text-sm font-semibold transition-colors group-hover:text-primary",+ "text-sm font-medium transition-colors group-hover:text-primary",status === "done" && "line-through text-muted-foreground")}>