Skip to content

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.

feat(inventory): valuation report + GL posting for inventory adjustments (#1149)

Brad Barbina6524bc45f8c
diff --git a/.ai/lessons.md b/.ai/lessons.md
index 5eb2ef3712..44ccd97bae 100644
--- a/.ai/lessons.md
+++ b/.ai/lessons.md
@@ -349,6 +349,46 @@ Format: `Context → Problem → Rule → Applies to`
**Applies to:** `check_accounting_period_open`; `snapshotAccountingPeriodBalances` / `accountingPeriodBalance`; any close/snapshot-on-commit pattern.
+## Inline-editable table cells commit on blur — the container must own navigation keys in the capture phase
+
+**Context:** Inventory count table (PR #1135 follow-up): typed Counted Qty values were lost on Tab/Enter (only click-away saved), Enter never navigated, arrows stepped the number instead of moving the selection, and keyboard nav went dead after a commit.
+
+**Problem:** Editable cells (`~/components/Editable/*`) persist via the input's native `onBlur`, but three things prevent that blur from ever firing on keyboard navigation: (1) the Table's key handler `preventDefault()`s Tab/Enter, so the browser never moves focus; (2) React unmounts the still-focused input when the selection moves, and browsers fire no blur on a removed element; (3) react-aria's NumberField swallows Enter entirely (`onKeyDownEnter` commits internally without `continuePropagation()`) and consumes ArrowUp/Down as spinbutton steps, so a bubble-phase table handler never sees those keys. Blurring at the input level without navigating drops `document.activeElement` to `body`, after which the table wrapper hears no further keys.
+
+**Rule:** The table container owns the Excel keyboard model: attach the handler with `onKeyDownCapture` (so it beats react-aria to Enter/arrows), `stopPropagation()` for handled keys while editing, blur `document.activeElement` to commit *before* `setSelectedCell`, and let the roving-tabindex cell ref (`useMovingCellRef`) refocus the newly selected cell. Skip events targeting portaled overlays (`[data-radix-popper-content-wrapper]`, `[role=menu|listbox|dialog]`) — those own their keys. Editors must keep blur as their *single* commit path (no keydown commits — they double-fire the mutation, as `EditableText` did in Grid).
+
+**Applies to:** `apps/erp/app/components/Table/Table.tsx`, `apps/erp/app/components/Grid/Grid.tsx`, `apps/erp/app/components/Editable/*`, any future inline-editable cell editor.
+
+## Seeding useState from a prop goes stale when the document flips state in place
+
+**Context:** After Rectify flipped a Posted inventory count back to Draft, the lines table stayed read-only until a full page reload.
+
+**Problem:** `Table` read `forceEditMode` only as the `useState` initial value. Rectify/Post actions revalidate the route in place — the component never remounts, so the prop change never reached the state, and the Edit/Lock toggle is hidden while `forceEditMode` is set, leaving no way to recover. The same staleness applied in the opposite direction after posting a Draft (table looked editable on a read-only document).
+
+**Rule:** When a prop derives from a document's mutable status (Draft/Posted etc.) and controls interaction mode, sync it with an effect (`useEffect(() => setEditMode(forceEditMode), [forceEditMode])`) or derive it instead of seeding state once. Test the transition without a reload — loader revalidation does not remount components.
+
+**Applies to:** `apps/erp/app/components/Table/Table.tsx` (`forceEditMode`), any component seeding state from status-derived props on revalidating routes.
+
+## journalLineDocumentType and itemLedgerDocumentType are different enums with near-identical value sets
+
+**Context:** Adding GL posting for inventory adjustments: journal lines needed a `documentType` of `'Inventory Adjustment'`, and the plan also stamped the same value onto `itemLedger`/`costLedger` rows.
+
+**Problem:** `journalLine.documentType` uses the `journalLineDocumentType` enum while `itemLedger.documentType` AND `costLedger.documentType` share the `itemLedgerDocumentType` enum. The two lists overlap heavily ('Inventory Count' exists in both) but are not identical — `'Inventory Adjustment'` existed in neither and was added only to `journalLineDocumentType`. Writing a journal-only value into a ledger column fails at runtime with an invalid-enum error, and stamping a new documentType onto manual-adjustment `itemLedger` rows would also have broken the "byte-identical ledger writes when accounting is disabled" guarantee (they are NULL today).
+
+**Rule:** Before using a `documentType` string, check WHICH enum the target column uses (`\dT+` or grep the migration) — never assume the journal and ledger enums share values. When adding GL posting to an existing subledger flow, keep the subledger rows' shape unchanged (documentType stays whatever it was, usually NULL) and put the new linkage value on the journal lines only.
+
+**Applies to:** `packages/database/supabase/migrations/` enum additions; `functions/shared/post-adjustment.ts`; any `post-*` function writing both `itemLedger`/`costLedger` and `journalLine`.
+
+## Deno edge functions are not deno-check-clean — gate on own-file error deltas, not exit code
+
+**Context:** Verifying new/edited Supabase edge functions (`post-inventory-adjustment`, `post-inventory-count`) with `deno check`.
+
+**Problem:** `deno check` on ANY edge function fails with ~10–20 pre-existing errors from the shared dependency graph (TS2589 in `shared/get-next-sequence.ts`, kysely pool-config type skew, supabase-js generic inference collapsing to implicit-any callbacks). CI never runs `deno check`, so committed, working functions fail it — a red exit code proves nothing about the change, and chasing those errors means rewriting shared files out of scope.
+
+**Rule:** Gate edge-function changes on the DELTA of errors attributed to the touched file: `deno check <file> 2>&1 | sed 's/\x1b\[[0-9;]*m//g' | grep -c "<file>:"` must not exceed the committed baseline (copy the HEAD version beside it to measure, e.g. `git show HEAD:<path> > <dir>/index.orig.ts`, check, delete). New code should contribute zero; annotate supabase-js callbacks with explicit row types instead of leaving implicit-any. Pure logic goes in a small module importing only `lib/types.ts` so `deno test` type-checks clean.
+
+**Applies to:** `packages/database/supabase/functions/**` verification; `.ai/skills/check-and-commit` runs touching edge functions.
+
## Forking a SQL function migration silently drops sibling branches added since your fork base
**Context:** `complete_job_to_inventory` gained a Non-Inventory branch in `20260707022142` (services post WIP→COGS, no inventory artifacts). Six days later, two migrations (`20260713190909` raw-materials split, `20260713222236` overhead fix) each forked the function from the older `20260630092517` baseline — silently deleting the Non-Inventory branch. Service job completions then posted phantom Finished Goods until the branch was restored in `20260714043017`.
diff --git a/.ai/plans/2026-07-14-inventory-value-report.md b/.ai/plans/2026-07-14-inventory-value-report.md
new file mode 100644
index 0000000000..86743d22cc
--- /dev/null
+++ b/.ai/plans/2026-07-14-inventory-value-report.md
@@ -0,0 +1,819 @@
+# Inventory Valuation Report — implementation plan
+
+**Spec:** .ai/specs/2026-07-14-inventory-value-report.md
+**Research:** .ai/research/inventory-value-report.md
+**Run record:** .ai/runs/2026-07-14-inventory-value-report.md
+**Branch:** feat/inventory-report
+
+> Browser verification (/test) and self-review were **deselected by the user** in
+> the feature run — the verification story is: rolled-back psql validation of the
+> RPC math (Task 2), scoped typecheck + lint per task, and the user verifying in
+> the browser themselves.
+
+> **Generated types:** `pnpm db:migrate` applies the migration AND regenerates
+> `packages/database/src/types.ts` + `swagger-docs-schema.ts`. Commit the
+> regenerated files with the migration — they are part of the change (AGENTS.md:
+> generate types after schema changes, BEFORE typechecking). Never hand-edit them.
+
+## Progress
+- [x] Task 1: Create the migration — `get_inventory_valuation` + `get_inventory_tie_out` RPCs (commit 1e3e89fbe)
+- [x] Task 2: Apply migration and validate the math in a rolled-back psql transaction (7/7 asserts PASS; fixed account join — companyGroup-scoped, no companyId)
+- [x] Task 3: Service functions + row types in the inventory module (typed rpc calls; erp typecheck green — note: correct filter is `erp`, not `@carbon/erp`)
+- [x] Task 4: Path helper + sidebar nav entry (Track group, accounting_view-gated, LuChartBar)
+- [x] Task 5: Workbench UI component (grouped union rows + tie-out popover + as-of label; cloned from ARAPWorkbench)
+- [x] Task 6: Route `/x/inventory/valuation` (accounting_view gate; valuation errors throw to boundary; +156 translations filled via /translate)
+- [x] Task 7: Final verification sweep (typecheck + biome + 7/7 psql asserts + pnpm test 21/21 green; fixed stale AGENTS.md validation command)
+
+## Dependencies
+- Task 2 needs Task 1 (migration file). Task 3 needs Task 2 (functions exist locally).
+- Tasks 4 and 5 are independent of each other; both need Task 3 (types).
+- Task 6 needs Tasks 3, 4, 5. Task 7 needs all.
+
+---
+
+## Task 1: Create the migration — `get_inventory_valuation` + `get_inventory_tie_out` RPCs
+
+**Depends on:** none
+**Files:**
+- Create: `packages/database/supabase/migrations/<timestamp>_inventory-valuation-rpc.sql` (via `pnpm db:migrate:new`)
+- Copy from (precedent): `packages/database/supabase/migrations/20260713235406_item-ledger-snapshot.sql` (snapshot+delta arms), `packages/database/supabase/migrations/20260713233919_balance-rpc-snapshot-delta.sql` (GL balance filter convention)
+
+**Steps:**
+
+1. Run `pnpm db:migrate:new inventory-valuation-rpc` from the repo root. It creates
+ the timestamped file. Confirm the HHMMSS portion is not `000000`; if it is,
+ rename the file with a randomized HHMMSS (e.g. `143217`) before writing SQL.
+2. Write exactly this SQL into the file (bare `NUMERIC` everywhere — never a
+ precision spec; no `SET search_path`, matching the 20260713235406 precedent):
+
+```sql
+-- ============================================================
+-- get_inventory_valuation: method-faithful inventory value by (item, location).
+-- Spec: .ai/specs/2026-07-14-inventory-value-report.md
+--
+-- * quantityOnHand = ALL physical stock (On Hold + Rejected included; they are
+-- assets until written off). quantityOnHold / quantityRejected are additive
+-- breakdown columns from the denormalized itemLedger.trackedEntityStatus.
+-- * unitCost: FIFO/LIFO = remaining cost-layer value incl. applied adjustment
+-- children (appliesToCostLedgerId), fallback itemCost.unitCost when no open
+-- layers; Average = itemCost.unitCost; Standard = itemCost.standardCost.
+-- This is the completeness spec's carrying CTE
+-- (.ai/specs/2026-07-04-inventory-valuation-completeness.md §3).
+-- * as_of_date NULL/today: snapshot + delta (exact 20260713235406 pattern).
+-- as_of_date in the past: raw itemLedger scan filtered by postingDate —
+-- the snapshot has no date grain. Costs are ALWAYS current-state; the UI
+-- labels dated results accordingly.
+-- * Status buckets reflect CURRENT tracked-entity statuses even for past
+-- dates (statuses are rewritten in place by 20260420112047).
+-- ============================================================
+
+DROP FUNCTION IF EXISTS get_inventory_valuation(TEXT, DATE, TEXT);
+
+CREATE OR REPLACE FUNCTION get_inventory_valuation(
+ company_id TEXT,
+ as_of_date DATE DEFAULT NULL,
+ location_id TEXT DEFAULT NULL
+)
+RETURNS TABLE (
+ "locationId" TEXT,
+ "locationName" TEXT,
+ "itemId" TEXT,
+ "readableIdWithRevision" TEXT,
+ "name" TEXT,
+ "type" "itemType",
+ "replenishmentSystem" "itemReplenishmentSystem",
+ "unitOfMeasureCode" TEXT,
+ "costingMethod" "itemCostingMethod",
+ "quantityOnHand" NUMERIC,
+ "quantityOnHold" NUMERIC,
+ "quantityRejected" NUMERIC,
+ "unitCost" NUMERIC,
+ "totalValue" NUMERIC
+) AS $$
+DECLARE
+ v_cutoff TIMESTAMPTZ;
+ v_dated BOOLEAN := as_of_date IS NOT NULL AND as_of_date < CURRENT_DATE;
+BEGIN
+ SELECT MAX("snapshotCutoff") INTO v_cutoff
+ FROM "itemLedgerSnapshot"
+ WHERE "companyId" = company_id;
+
+ RETURN QUERY
+ WITH quantities AS (
+ SELECT
+ combined."itemId",
+ combined."locationId",
+ SUM(combined."quantity") AS "quantityOnHand",
+ SUM(combined."onHold") AS "quantityOnHold",
+ SUM(combined."rejected") AS "quantityRejected"
+ FROM (
+ -- Arm 1: snapshot (untracked, immutable). Skipped on dated queries —
+ -- the snapshot has no postingDate grain.
+ SELECT
+ s."itemId",
+ NULLIF(s."locationId", '') AS "locationId",
+ s."quantity",
+ 0::NUMERIC AS "onHold",
+ 0::NUMERIC AS "rejected"
+ FROM "itemLedgerSnapshot" s
+ WHERE NOT v_dated
+ AND s."companyId" = company_id
+ AND (location_id IS NULL OR s."locationId" = location_id)
+
+ UNION ALL
+
+ -- Arm 2: tracked rows, always live (status flips in place).
+ SELECT
+ il."itemId",
+ il."locationId",
+ il."quantity",
+ CASE WHEN il."trackedEntityStatus" = 'On Hold' THEN il."quantity" ELSE 0 END,
+ CASE WHEN il."trackedEntityStatus" = 'Rejected' THEN il."quantity" ELSE 0 END
+ FROM "itemLedger" il
+ WHERE il."companyId" = company_id
+ AND il."trackedEntityId" IS NOT NULL
+ AND (location_id IS NULL OR il."locationId" = location_id)
+ AND (NOT v_dated OR il."postingDate" <= as_of_date)
+
+ UNION ALL
+
+ -- Arm 3: untracked delta past the cutoff (current path) OR the full
+ -- untracked history filtered by postingDate (dated path / no snapshot).
+ SELECT
+ il."itemId",
+ il."locationId",
+ il."quantity",
+ 0::NUMERIC,
+ 0::NUMERIC
+ FROM "itemLedger" il
+ WHERE il."companyId" = company_id
+ AND il."trackedEntityId" IS NULL
+ AND (location_id IS NULL OR il."locationId" = location_id)
+ AND (v_dated OR v_cutoff IS NULL OR il."createdAt" >= v_cutoff)
+ AND (NOT v_dated OR il."postingDate" <= as_of_date)
+ ) combined
+ GROUP BY combined."itemId", combined."locationId"
+ HAVING SUM(combined."quantity") <> 0
+ ),
+ carrying AS (
+ -- Company-level effective unit cost per item, by costing method.
+ SELECT
+ ic."itemId",
+ ic."costingMethod",
+ CASE ic."costingMethod"
+ WHEN 'Standard' THEN ic."standardCost"
+ WHEN 'Average' THEN ic."unitCost"
+ ELSE COALESCE(layers."layerUnitCost", ic."unitCost")
+ END AS "unitCost"
+ FROM "itemCost" ic
+ LEFT JOIN LATERAL (
+ SELECT
+ SUM(
+ cl."remainingQuantity"
+ * (cl."cost" + COALESCE(adj."applied", 0))
+ / NULLIF(cl."quantity", 0)
+ ) / NULLIF(SUM(cl."remainingQuantity"), 0) AS "layerUnitCost"
+ FROM "costLedger" cl
+ LEFT JOIN LATERAL (
+ SELECT SUM(a."cost") AS "applied"
+ FROM "costLedger" a
+ WHERE a."appliesToCostLedgerId" = cl."id"
+ AND a."companyId" = cl."companyId"
+ ) adj ON TRUE
+ WHERE cl."itemId" = ic."itemId"
+ AND cl."companyId" = ic."companyId"
+ AND cl."remainingQuantity" > 0
+ ) layers ON ic."costingMethod" IN ('FIFO', 'LIFO')
+ WHERE ic."companyId" = company_id
+ )
+ SELECT
+ l."id" AS "locationId",
+ l."name" AS "locationName",
+ i."id" AS "itemId",
+ i."readableIdWithRevision",
+ i."name",
+ i."type",
+ i."replenishmentSystem",
+ i."unitOfMeasureCode",
+ c."costingMethod",
+ q."quantityOnHand",
+ q."quantityOnHold",
+ q."quantityRejected",
+ COALESCE(c."unitCost", 0) AS "unitCost",
+ q."quantityOnHand" * COALESCE(c."unitCost", 0) AS "totalValue"
+ FROM quantities q
+ INNER JOIN "item" i ON q."itemId" = i."id" AND i."companyId" = company_id
+ INNER JOIN "location" l ON q."locationId" = l."id"
+ LEFT JOIN carrying c ON c."itemId" = q."itemId"
+ ORDER BY l."name", i."readableIdWithRevision";
+END;
+$$ LANGUAGE plpgsql SECURITY DEFINER;
+
+-- ============================================================
+-- get_inventory_tie_out: subledger value vs GL balance per stock account
+-- (SAP MB5L shape). Subledger side calls get_inventory_valuation so the two
+-- surfaces can never disagree. Items classify to accounts exactly like
+-- resolveInventoryAccount (functions/shared/get-posting-group.ts):
+-- Make / Buy and Make -> finishedGoodsAccount, else rawMaterialsAccount.
+-- GL side follows the newest balance convention (20260713233919):
+-- journal.status <> 'Draft', journal.postingDate <= as-of, journalLine.accountId.
+-- ============================================================
+
+DROP FUNCTION IF EXISTS get_inventory_tie_out(TEXT, DATE);
+
+CREATE OR REPLACE FUNCTION get_inventory_tie_out(
+ company_id TEXT,
+ as_of_date DATE DEFAULT NULL
+)
+RETURNS TABLE (
+ "accountKind" TEXT,
+ "accountId" TEXT,
+ "accountName" TEXT,
+ "subledgerValue" NUMERIC,
+ "glBalance" NUMERIC,
+ "variance" NUMERIC
+) AS $$
+DECLARE
+ v_as_of DATE := COALESCE(as_of_date, CURRENT_DATE);
+ v_rm_account TEXT;
+ v_fg_account TEXT;
+BEGIN
+ SELECT ad."rawMaterialsAccount", ad."finishedGoodsAccount"
+ INTO v_rm_account, v_fg_account
+ FROM "accountDefault" ad
+ WHERE ad."companyId" = company_id;
+
+ IF v_rm_account IS NULL OR v_fg_account IS NULL THEN
+ RETURN; -- company has no account defaults (accounting never configured)
+ END IF;
+
+ RETURN QUERY
+ WITH subledger AS (
+ SELECT
+ CASE WHEN v."replenishmentSystem" IN ('Make', 'Buy and Make')
+ THEN 'finishedGoods' ELSE 'rawMaterials' END AS "kind",
+ SUM(v."totalValue") AS "value"
+ FROM get_inventory_valuation(company_id, as_of_date, NULL) v
+ GROUP BY 1
+ ),
+ gl AS (
+ SELECT jl."accountId" AS "account", SUM(jl."amount") AS "balance"
+ FROM "journal" j
+ INNER JOIN "journalLine" jl ON jl."journalId" = j."id"
+ WHERE j."companyId" = company_id
+ AND j."status" <> 'Draft'
+ AND j."postingDate" <= v_as_of
+ AND jl."accountId" IN (v_rm_account, v_fg_account)
+ GROUP BY jl."accountId"
+ ),
+ accounts AS (
+ SELECT 'rawMaterials' AS "kind", v_rm_account AS "account"
+ UNION ALL
+ SELECT 'finishedGoods' AS "kind", v_fg_account AS "account"
+ )
+ SELECT
+ a."kind" AS "accountKind",
+ a."account" AS "accountId",
+ acc."name" AS "accountName",
+ COALESCE(s."value", 0) AS "subledgerValue",
+ COALESCE(g."balance", 0) AS "glBalance",
+ COALESCE(s."value", 0) - COALESCE(g."balance", 0) AS "variance"
+ FROM accounts a
+ LEFT JOIN "account" acc ON acc."id" = a."account" AND acc."companyId" = company_id
+ LEFT JOIN subledger s ON s."kind" = a."kind"
+ LEFT JOIN gl g ON g."account" = a."account"
+ ORDER BY a."kind" DESC; -- rawMaterials first
+END;
+$$ LANGUAGE plpgsql SECURITY DEFINER;
+
+-- Kept per spec decision (grill Q5): superseded but not dropped.
+COMMENT ON FUNCTION get_inventory_value_by_location(TEXT) IS
+ 'Deprecated: superseded by get_inventory_valuation (method-faithful costs, status breakdown, as-of-date). Kept for API compatibility.';
+```
+
+3. Do not add tables, RLS, enums, or touch `get_inventory_value_by_location`'s
+ body. If `journal` lacks a `status` or `postingDate` column, or `accountDefault`
+ lacks `rawMaterialsAccount`/`finishedGoodsAccount` (check
+ `20260713190909_raw-materials-finished-goods-accounts.sql`), STOP and report —
+ do not improvise.
+
+**Verify:**
+```bash
+ls packages/database/supabase/migrations/ | tail -3
+# Expected: the new <timestamp>_inventory-valuation-rpc.sql is the newest file
+# (timestamp strictly greater than 20260713235406) and HHMMSS != 000000
+```
+
+**Out of scope:** dropping or editing `get_inventory_value_by_location`;
+`itemLedgerSnapshot` definition; any index changes; `costLedger` schema.
+
+---
+
+## Task 2: Apply migration and validate the math in a rolled-back psql transaction
+
+**Depends on:** Task 1
+**Files:**
+- Create: `.ai/scratch/validate-inventory-valuation.sql` (gitignored scratch — do not commit)
+- Copy from (precedent): the rolled-back-txn validation approach used for prior migrations (memory: BEGIN / fixtures / asserts / ROLLBACK as `supabase_admin`)
+
+**Steps:**
+
+1. Apply: `pnpm db:migrate`. This applies the pending migration and regenerates
+ DB types + swagger. Confirm the new RPCs landed in the generated types:
+ `grep -c "get_inventory_valuation\|get_inventory_tie_out" packages/database/src/types.ts`
+ (expected: ≥ 2). The regenerated `types.ts` / `swagger-docs-schema.ts` diffs
+ are part of this task's commit.
+2. Write `.ai/scratch/validate-inventory-valuation.sql` with exactly:
+
+```sql
+BEGIN;
+DO $test$
+DECLARE
+ cid TEXT; uid TEXT; loc_a TEXT; loc_b TEXT;
+ itm_fifo TEXT; itm_std TEXT; itm_zero TEXT;
+ l1 TEXT; l2 TEXT;
+ r RECORD;
+ v_total NUMERIC;
+BEGIN
+ SELECT id INTO cid FROM "company" LIMIT 1;
+ SELECT id INTO uid FROM "user" WHERE "email" = '[email protected]';
+ IF uid IS NULL THEN SELECT id INTO uid FROM "user" LIMIT 1; END IF;
+
+ INSERT INTO "location" ("name", "timezone", "companyId", "createdBy")
+ VALUES ('VALTEST-A', 'America/New_York', cid, uid) RETURNING id INTO loc_a;
+ INSERT INTO "location" ("name", "timezone", "companyId", "createdBy")
+ VALUES ('VALTEST-B', 'America/New_York', cid, uid) RETURNING id INTO loc_b;
+
+ -- Items: interceptors auto-create itemCost/itemReplenishment on item insert.
+ INSERT INTO "item" ("readableId", "name", "type", "replenishmentSystem",
+ "itemTrackingType", "unitOfMeasureCode", "companyId", "createdBy")
+ VALUES ('VALTEST-FIFO', 'Valuation Test FIFO', 'Part', 'Buy', 'Inventory', 'EA', cid, uid)
+ RETURNING id INTO itm_fifo;
+ INSERT INTO "item" ("readableId", "name", "type", "replenishmentSystem",
+ "itemTrackingType", "unitOfMeasureCode", "companyId", "createdBy")
+ VALUES ('VALTEST-STD', 'Valuation Test Standard', 'Part', 'Buy', 'Inventory', 'EA', cid, uid)
+ RETURNING id INTO itm_std;
+ INSERT INTO "item" ("readableId", "name", "type", "replenishmentSystem",
+ "itemTrackingType", "unitOfMeasureCode", "companyId", "createdBy")
+ VALUES ('VALTEST-ZERO', 'Valuation Test Zero', 'Part', 'Buy', 'Inventory', 'EA', cid, uid)
+ RETURNING id INTO itm_zero;
+
+ UPDATE "itemCost" SET "costingMethod" = 'FIFO', "unitCost" = 99
+ WHERE "itemId" = itm_fifo AND "companyId" = cid;
+ UPDATE "itemCost" SET "costingMethod" = 'Standard', "standardCost" = 5, "unitCost" = 0
+ WHERE "itemId" = itm_std AND "companyId" = cid;
+
+ -- FIFO quantities: 80 @ A, 30 @ B (total 110)
+ INSERT INTO "itemLedger" ("entryType", "documentType", "itemId", "locationId",
+ "quantity", "companyId", "createdBy")
+ VALUES ('Purchase', 'Purchase Receipt', itm_fifo, loc_a, 80, cid, uid),
+ ('Purchase', 'Purchase Receipt', itm_fifo, loc_b, 30, cid, uid);
+
+ -- FIFO layers: L1 qty 100 cost 1000 remaining 60; L2 qty 50 cost 600 remaining 50.
+ -- Child on L1: +55 (appliesToCostLedgerId).
+ -- Effective = (60*(1000+55)/100 + 50*600/50) / 110 = (633 + 600) / 110 = 11.2090909...
+ INSERT INTO "costLedger" ("itemLedgerType", "costLedgerType", "itemId",
+ "quantity", "cost", "remainingQuantity", "companyId")
+ VALUES ('Purchase', 'Direct Cost', itm_fifo, 100, 1000, 60, cid)
+ RETURNING id INTO l1;
+ INSERT INTO "costLedger" ("itemLedgerType", "costLedgerType", "itemId",
+ "quantity", "cost", "remainingQuantity", "companyId")
+ VALUES ('Purchase', 'Direct Cost', itm_fifo, 50, 600, 50, cid)
+ RETURNING id INTO l2;
+ INSERT INTO "costLedger" ("itemLedgerType", "costLedgerType", "adjustment",
+ "appliesToCostLedgerId", "itemId", "quantity", "cost",
+ "remainingQuantity", "companyId")
+ VALUES ('Purchase', 'Variance', true, l1, itm_fifo, 100, 55, 0, cid);
+
+ -- Standard: 10 @ A. Zero-sum item: +5/-5 @ A (must be excluded).
+ INSERT INTO "itemLedger" ("entryType", "documentType", "itemId", "locationId",
+ "quantity", "companyId", "createdBy")
+ VALUES ('Purchase', 'Purchase Receipt', itm_std, loc_a, 10, cid, uid),
+ ('Purchase', 'Purchase Receipt', itm_zero, loc_a, 5, cid, uid),
+ ('Negative Adjmt.', 'Inventory Shipment', itm_zero, loc_a, -5, cid, uid);
+
+ -- Assert 1: FIFO @ A = 80 x 11.20909... = 896.73
+ SELECT * INTO r FROM get_inventory_valuation(cid, NULL, NULL)
+ WHERE "itemId" = itm_fifo AND "locationId" = loc_a;
+ IF r IS NULL OR ROUND(r."totalValue", 2) <> 896.73 OR r."quantityOnHand" <> 80 THEN
+ RAISE EXCEPTION 'FAIL FIFO@A: qty=%, value=%', r."quantityOnHand", r."totalValue";
+ END IF;
+ RAISE NOTICE 'PASS: FIFO layer math @ A (896.73)';
+
+ -- Assert 2: FIFO @ B = 30 x 11.20909... = 336.27; item total = 1233.00
+ SELECT * INTO r FROM get_inventory_valuation(cid, NULL, NULL)
+ WHERE "itemId" = itm_fifo AND "locationId" = loc_b;
+ IF ROUND(r."totalValue", 2) <> 336.27 THEN
+ RAISE EXCEPTION 'FAIL FIFO@B: value=%', r."totalValue";
+ END IF;
+ SELECT SUM("totalValue") INTO v_total FROM get_inventory_valuation(cid, NULL, NULL)
+ WHERE "itemId" = itm_fifo;
+ IF ROUND(v_total, 2) <> 1233.00 THEN
+ RAISE EXCEPTION 'FAIL FIFO total: %', v_total;
+ END IF;
+ RAISE NOTICE 'PASS: FIFO split + remaining-layer total (1233.00)';
+
+ -- Assert 3: Standard valued at standardCost (10 x 5 = 50), not unitCost (0)
+ SELECT * INTO r FROM get_inventory_valuation(cid, NULL, NULL)
+ WHERE "itemId" = itm_std;
+ IF ROUND(r."totalValue", 2) <> 50.00 OR r."costingMethod" <> 'Standard' THEN
+ RAISE EXCEPTION 'FAIL Standard: value=%', r."totalValue";
+ END IF;
+ RAISE NOTICE 'PASS: Standard basis (50.00)';
+
+ -- Assert 4: zero-sum item excluded
+ IF EXISTS (SELECT 1 FROM get_inventory_valuation(cid, NULL, NULL) WHERE "itemId" = itm_zero) THEN
+ RAISE EXCEPTION 'FAIL: zero-quantity item present';
+ END IF;
+ RAISE NOTICE 'PASS: HAVING <> 0 exclusion';
+
+ -- Assert 5: dated query excludes today's rows (fixtures post today)
+ IF EXISTS (SELECT 1 FROM get_inventory_valuation(cid, CURRENT_DATE - 1, NULL)
+ WHERE "itemId" IN (itm_fifo, itm_std)) THEN
+ RAISE EXCEPTION 'FAIL: as-of-date did not exclude today''s postings';
+ END IF;
+ RAISE NOTICE 'PASS: as-of-date postingDate filter';
+
+ -- Assert 6: tie-out returns 2 rows (or 0 if accountDefault missing — then NOTICE)
+ IF (SELECT COUNT(*) FROM get_inventory_tie_out(cid, NULL)) NOT IN (0, 2) THEN
+ RAISE EXCEPTION 'FAIL: tie-out row count';
+ END IF;
+ RAISE NOTICE 'PASS: tie-out shape';
+
+ -- Assert 7: status breakdown — a Rejected tracked entity is VALUED (all
+ -- physical stock counts) and surfaces in quantityRejected.
+ DECLARE
+ te TEXT;
+ BEGIN
+ INSERT INTO "trackedEntity" ("readableId", "quantity", "status", "companyId", "createdBy")
+ VALUES ('VALTEST-TE-1', 5, 'Rejected', cid, uid)
+ RETURNING id INTO te;
+ INSERT INTO "itemLedger" ("entryType", "documentType", "itemId", "locationId",
+ "quantity", "trackedEntityId", "trackedEntityStatus",
+ "companyId", "createdBy")
+ VALUES ('Purchase', 'Purchase Receipt', itm_std, loc_a, 5, te, 'Rejected', cid, uid);
+
+ SELECT * INTO r FROM get_inventory_valuation(cid, NULL, NULL)
+ WHERE "itemId" = itm_std AND "locationId" = loc_a;
+ -- 10 untracked + 5 rejected tracked = 15 valued at standardCost 5 => 75
+ IF r."quantityOnHand" <> 15 OR r."quantityRejected" <> 5
+ OR ROUND(r."totalValue", 2) <> 75.00 THEN
+ RAISE EXCEPTION 'FAIL status breakdown: qty=%, rejected=%, value=%',
+ r."quantityOnHand", r."quantityRejected", r."totalValue";
+ END IF;
+ RAISE NOTICE 'PASS: rejected stock valued + bucketed (15 / 5 / 75.00)';
+ END;
+END
+$test$;
+ROLLBACK;
+```
+
+3. Run it against the local worktree DB as `supabase_admin` (port from `.env.local`):
+
+```bash
+PORT_DB=$(grep '^PORT_DB=' .env.local | cut -d= -f2)
+psql "postgresql://supabase_admin:[email protected]:${PORT_DB}/postgres" \
+ -v ON_ERROR_STOP=1 -f .ai/scratch/validate-inventory-valuation.sql
+```
+
+4. If an `INSERT` fails on a NOT NULL column not listed here (e.g. `item` or
+ `trackedEntity` gained a required column), add that column to the INSERT with a
+ sensible literal and re-run. If the `itemCost` UPDATE affects 0 rows
+ (interceptor did not fire), STOP and report — do not hand-insert `itemCost`.
+5. Expected-cost math note: if Assert 1 fails with value 896.72 vs 896.73, the
+ difference is rounding order — STOP and report rather than adjusting the
+ expected value; the assert values are exact for `ROUND(80 * (1233.0/110), 2)`.
+
+**Verify:**
+```bash
+# (the psql run above)
+# Expected: seven lines "PASS: ..." and final "ROLLBACK"; exit code 0
+grep -c "get_inventory_valuation" packages/database/src/types.ts
+# Expected: >= 1 (types regenerated with the new RPC)
+```
+
+**Out of scope:** committing the scratch SQL; seeding permanent fixtures;
+refreshing `itemLedgerSnapshot`; hand-editing the regenerated types.
+
+---
+
+## Task 3: Service functions + row types in the inventory module
+
+**Depends on:** Task 2
+**Files:**
+- Modify: `apps/erp/app/modules/inventory/inventory.service.ts` — add `getInventoryValuation`, `getInventoryValuationTieOut` (place near `getInventoryItems`)
+- Modify: `apps/erp/app/modules/inventory/types.ts` — add `InventoryValuationRow`, `InventoryTieOutRow`
+- Copy from (precedent): `apps/erp/app/modules/invoicing/invoicing.service.ts` `getArTieOut` (~line 2286) for the rpc-wrapper shape
+
+**Steps:**
+
+1. In `inventory.service.ts`, add (client-first, `{data, error}` return, no
+ throw; the RPC names are fully typed because Task 2 regenerated types):
+
+```typescript
+export async function getInventoryValuation(
+ client: SupabaseClient<Database>,
+ companyId: string,
+ args: { asOfDate?: string | null; locationId?: string | null }
+) {
+ return client.rpc("get_inventory_valuation", {
+ company_id: companyId,
+ as_of_date: args.asOfDate ?? undefined,
+ location_id: args.locationId ?? undefined,
+ });
+}
+
+export async function getInventoryValuationTieOut(
+ client: SupabaseClient<Database>,
+ companyId: string,
+ asOfDate?: string | null
+) {
+ return client.rpc("get_inventory_tie_out", {
+ company_id: companyId,
+ as_of_date: asOfDate ?? undefined,
+ });
+}
+```
+
+ If the generated `Args` type requires `null` rather than `undefined` for the
+ optional params, use `?? null` instead — match whatever typecheck accepts.
+
+2. In `types.ts`, derive the row types through the standard type chain
+ (`Awaited<ReturnType<...>>`, the repo convention):
+
+```typescript
+import type {
+ getInventoryValuation,
+ getInventoryValuationTieOut,
+} from "./inventory.service";
+
+export type InventoryValuationRow = NonNullable<
+ Awaited<ReturnType<typeof getInventoryValuation>>["data"]
+>[number];
+
+export type InventoryTieOutRow = NonNullable<
+ Awaited<ReturnType<typeof getInventoryValuationTieOut>>["data"]
+>[number];
+```
+
+ Match the file's existing import/derivation style (it already uses
+ `Awaited<ReturnType<typeof ...>>` for other service functions — copy the
+ nearest example exactly, including whether the functions are imported as
+ types or values). The module barrel (`index.ts`) already re-exports service +
+ types — verify (`export * from "./types"` / `"./inventory.service"`); add the
+ export line only if missing.
+
+**Verify:**
+```bash
+pnpm --filter @carbon/erp typecheck
+# Expected: exits 0, no new errors
+```
+
+**Out of scope:** `inventory.models.ts` (no forms on this feature); touching
+`getInventoryItems`; edge functions.
+
+---
+
+## Task 4: Path helper + sidebar nav entry
+
+**Depends on:** Task 3
+**Files:**
+- Modify: `apps/erp/app/utils/path.ts` — add `inventoryValuation` near the existing inventory entries (~line 1068)
+- Modify: `apps/erp/app/modules/inventory/ui/useInventorySubmodules.tsx` — add a "Valuation" route to the **Track** group
+- Copy from (precedent): existing entries in both files
+
+**Steps:**
+
+1. `path.ts`, next to `inventory: \`${x}/inventory/quantities\``, add:
+ `inventoryValuation: \`${x}/inventory/valuation\`,` (keep alphabetical-ish local
+ ordering with the other `inventory*` keys).
+2. `useInventorySubmodules.tsx`: the hook returns `{ groups }` filtered by
+ `permissions`. Add to the "Track" group's `routes` array an entry shaped like
+ its siblings:
+
+```typescript
+{
+ name: t`Valuation`,
+ to: path.to.inventoryValuation,
+ icon: <LuChartColumn />,
+}
+```
+
+ Import `LuChartColumn` from `react-icons/lu` (if that icon name doesn't exist in
+ the installed version, pick another `Lu*` chart icon already used in the app —
+ grep `react-icons/lu` imports). Gate it on accounting view: the hook already has
+ `permissions` in scope (it filters by `permissions.is(...)`) — wrap the entry so
+ it is only included when `permissions.can("view", "accounting")`. Follow the
+ hook's existing filtering style: if routes support a `role` field only, filter
+ the entry with a conditional spread:
+
+```typescript
+...(permissions.can("view", "accounting")
+ ? [{ name: t`Valuation`, to: path.to.inventoryValuation, icon: <LuChartColumn /> }]
+ : []),
+```
+
+ If `permissions.can` is not available in the hook, import `usePermissions` from
+ `~/hooks` (it is the app's standard permissions hook). If the hook has no `t`
+ macro, follow whatever its sibling entries do for names (match the file's
+ existing i18n style exactly).
+
+**Verify:**
+```bash
+pnpm --filter @carbon/erp typecheck
+# Expected: exits 0
+grep -n "inventoryValuation" apps/erp/app/utils/path.ts apps/erp/app/modules/inventory/ui/useInventorySubmodules.tsx
+# Expected: one hit in each file
+```
+
+**Out of scope:** new nav groups; changing other groups' entries; MES nav.
+
+---
+
+## Task 5: Workbench UI component
+
+**Depends on:** Task 3 (types). Independent of Task 4.
+**Files:**
+- Create: `apps/erp/app/modules/inventory/ui/Valuation/InventoryValuationWorkbench.tsx`
+- Create: `apps/erp/app/modules/inventory/ui/Valuation/index.ts` (barrel: `export { default as InventoryValuationWorkbench } from "./InventoryValuationWorkbench"` — match the export style of a sibling `ui/*/index.ts`)
+- Modify: `apps/erp/app/modules/inventory/ui/index.ts` (or wherever sibling ui folders are re-exported — mirror how `ui/Receipts` etc. are exported; if ui folders are imported directly rather than barreled, skip this file)
+- Copy from (precedent): `apps/erp/app/modules/invoicing/ui/Workbench/ARAPWorkbench.tsx` — clone its structure: union row type (lines ~92–204), heterogeneous columns (~236–396), filter bar with tie-out Popover + DatePicker + Select (~403–532)
+
+**Steps:**
+
+1. Clone the ARAPWorkbench skeleton and adapt:
+ - **Props:** `{ rows: InventoryValuationRow[]; tieOut: InventoryTieOutRow[] | null; asOfDate: string; groupBy: "location" | "item"; locationId: string | null; locations: { id: string; name: string }[] }`.
+ - **Row model:** `type ValuationRow = { kind: "group"; id: string; label: string; quantityOnHand: number; totalValue: number; pctOfTotal: number } | { kind: "detail"; ...InventoryValuationRow; pctOfTotal: number }`. Group rows are locations when `groupBy === "location"` (details = items at that location) and items when `groupBy === "item"` (details = locations holding that item). Compute groups + grand total with `useMemo` from `rows`; maintain `expandedIds` state exactly like ARAPWorkbench (chevron toggle on group rows, details rendered when expanded).
+ - **Columns:** group/item label (with expand chevron on group rows), Costing Method (detail rows only, `groupBy === "location"`), Qty On Hand, On Hold, Rejected, UoM (detail only), Unit Cost (detail only), Total Value (bold on group rows), % of Total. Numeric formatting: `useCurrencyFormatter` for money (see its use in ARAPWorkbench) and plain number formatting for quantities. Style negative `quantityOnHand`/`totalValue` with the destructive text class used by ARAPWorkbench for negative amounts (grep `text-destructive` in that file; reuse the same class).
+ - **Detail-row drill-through:** the item label on detail rows links to `path.to.inventoryItemActivity(itemId)`.
+ - **Filter bar** (top, HStack — clone ARAPWorkbench's):
+ - Tie-out `Popover` (only when `tieOut !== null`): a small table with one row per `tieOut` entry — Account (name), Subledger, GL Balance, Variance — plus a totals row; a muted caveat line: `t\`Manual quantity adjustments don't post to the GL yet, so a nonzero variance is expected if you cycle count.\``
+ - Group-by `Select` with options Location / Item → `setParams({ groupBy })`.
+ - Location combobox (options from `locations`, plus "All locations") → `setParams({ locationId })`.
+ - `DatePicker` for asOfDate → `setParams({ asOfDate })` (clone ARAPWorkbench lines ~524–530).
+ - **Semantics label:** when `asOfDate` is before today, render a muted inline note above the table: `t\`Values apply today's unit costs to historical quantities.\``
+ - **Table + CSV:** use the same ERP `Table` component ARAPWorkbench uses so CSV export comes free (`.ai/rules/table-csv-export.md`); set `meta.exportValue` on money columns if ARAPWorkbench does.
+ - **i18n:** every user-visible string through `useLingui().t` or `<Trans>` from `@lingui/react/macro` — never `t` from `@lingui/core/macro`.
+2. Do not add charts, saved views, or storage-unit drill-down (spec: out of scope).
+
+**Verify:**
+```bash
+pnpm --filter @carbon/erp typecheck
+# Expected: exits 0
+pnpm exec biome check apps/erp/app/modules/inventory/ui/Valuation
+# Expected: "Checked N files" with 0 errors
+```
+
+**Out of scope:** Recharts/graphs; editing ARAPWorkbench; TanStack saved-view
+`table:` registration; MES.
+
+---
+
+## Task 6: Route `/x/inventory/valuation`
+
+**Depends on:** Tasks 3, 4, 5
+**Files:**
+- Create: `apps/erp/app/routes/x+/inventory+/valuation.tsx`
+- Copy from (precedent): `apps/erp/app/routes/x+/invoicing+/receivables.tsx` (loader shape, accountingEnabled gate, param parsing)
+
+**Steps:**
+
+1. Create the route with this structure (adapted from receivables.tsx):
+
+```typescript
+import { requirePermissions } from "@carbon/auth/auth.server";
+import type { LoaderFunctionArgs } from "react-router";
+import { useLoaderData } from "react-router";
+import {
+ getInventoryValuation,
+ getInventoryValuationTieOut,
+} from "~/modules/inventory";
+import { InventoryValuationWorkbench } from "~/modules/inventory/ui/Valuation";
+import { getCompanySettings } from "~/modules/settings";
+import type { Handle } from "~/utils/handle";
+import { path } from "~/utils/path";
+
+export const handle: Handle = {
+ breadcrumb: "Valuation",
+ to: path.to.inventoryValuation,
+ module: "inventory",
+};
+
+export async function loader({ request }: LoaderFunctionArgs) {
+ const { client, companyId } = await requirePermissions(request, {
+ view: "accounting",
+ });
+
+ const url = new URL(request.url);
+ const asOfDate =
+ url.searchParams.get("asOfDate") ?? new Date().toISOString().slice(0, 10);
+ const groupBy: "location" | "item" =
+ url.searchParams.get("groupBy") === "item" ? "item" : "location";
+ const locationId = url.searchParams.get("locationId") || null;
+
+ const companySettings = await getCompanySettings(client, companyId);
+ const accountingEnabled =
+ (companySettings.data as { accountingEnabled?: boolean } | null)
+ ?.accountingEnabled ?? false;
+
+ const [valuation, tieOut, locations] = await Promise.all([
+ getInventoryValuation(client, companyId, { asOfDate, locationId }),
+ accountingEnabled
+ ? getInventoryValuationTieOut(client, companyId, asOfDate)
+ : Promise.resolve({ data: null, error: null }),
+ client
+ .from("location")
+ .select("id, name")
+ .eq("companyId", companyId)
+ .order("name"),
+ ]);
+
+ return {
+ asOfDate,
+ groupBy,
+ locationId,
+ rows: valuation.data ?? [],
+ tieOut: tieOut.data ?? null,
+ locations: locations.data ?? [],
+ };
+}
+
+export default function InventoryValuationRoute() {
+ const { asOfDate, groupBy, locationId, rows, tieOut, locations } =
+ useLoaderData<typeof loader>();
+ return (
+ <InventoryValuationWorkbench
+ rows={rows}
+ tieOut={tieOut}
+ asOfDate={asOfDate}
+ groupBy={groupBy}
+ locationId={locationId}
+ locations={locations}
+ />
+ );
+}
+```
+
+2. Check `valuation.error` handling convention: receivables.tsx ignores `.error`
+ and defaults to `[]`; per lesson "check `.error`, don't `?? []` a failed query
+ into silent emptiness", improve on the precedent: if `valuation.error` is
+ non-null, `throw new Error(valuation.error.message)` so the route error
+ boundary surfaces it instead of rendering an empty report.
+3. If `~/modules/inventory` barrel does not re-export the new service functions
+ (Task 3 verified it), import from the service file path the barrel uses.
+ If the breadcrumb convention in sibling inventory routes uses `msg\`...\``
+ descriptors instead of plain strings, match the sibling exactly (check
+ `apps/erp/app/routes/x+/inventory+/quantities.tsx`'s `handle`).
+
+**Verify:**
+```bash
+pnpm --filter @carbon/erp typecheck
+# Expected: exits 0
+grep -rn "view: \"accounting\"" apps/erp/app/routes/x+/inventory+/valuation.tsx
+# Expected: 1 hit (the permission gate)
+```
+
+**Out of scope:** clientLoader caching; actions/mutations; changing
+receivables.tsx.
+
+---
+
+## Task 7: Final verification sweep
+
+**Depends on:** Tasks 1–6
+**Files:** none (verification only)
+
+**Steps:**
+
+1. Run the scoped gates:
+
+```bash
+pnpm --filter @carbon/erp typecheck
+pnpm exec biome check apps/erp/app/modules/inventory apps/erp/app/routes/x+/inventory+ apps/erp/app/utils/path.ts
+```
+
+2. Confirm the regenerated types were committed with the migration (Task 2's
+ commit) and still contain the new RPCs:
+
+```bash
+git status --porcelain packages/database/src/
+# Expected: empty (regenerated files were committed, not left dirty)
+grep -c "get_inventory_valuation\|get_inventory_tie_out" packages/database/src/types.ts
+# Expected: >= 2
+```
+
+3. Re-run the Task 2 psql validation once more against the applied DB (same
+ command) — expected: all PASS lines, ROLLBACK.
+4. Note in the run record (`.ai/runs/2026-07-14-inventory-value-report.md`) that
+ browser verification was deselected by the user; suggest they verify manually:
+ `crbn up`, log in, open `/x/inventory/valuation` with an accounting-view user,
+ check group toggle, as-of label, tie-out popover, CSV download.
+
+**Verify:**
+```bash
+pnpm --filter @carbon/erp typecheck && echo GATES-GREEN
+# Expected: GATES-GREEN
+```
+
+**Out of scope:** committing (handled per task by /check-and-commit during
+execute); pushing; PR creation (user decides).
diff --git a/.ai/plans/2026-07-15-inventory-adjustment-gl-posting.md b/.ai/plans/2026-07-15-inventory-adjustment-gl-posting.md
new file mode 100644
index 0000000000..94806698e8
--- /dev/null
+++ b/.ai/plans/2026-07-15-inventory-adjustment-gl-posting.md
@@ -0,0 +1,389 @@
+# Inventory Adjustment GL Posting — implementation plan
+
+**Spec:** .ai/specs/2026-07-14-inventory-adjustment-gl-posting.md
+**Research:** .ai/research/inventory-adjustment-gl-posting.md
+**Branch:** feat/inventory-report
+
+## Progress
+- [x] Task 1: Migration — journal document-type enum values + regenerated types
+- [x] Task 2: Shared posting core `shared/post-adjustment.ts` (+ pure cost helper with deno test)
+- [x] Task 3: New edge function `post-inventory-adjustment` (full adjustment semantics port)
+- [x] Task 4: ERP service wrapper delegates to the edge function
+- [x] Task 5: MES service wrapper delegates to the edge function
+- [x] Task 6: `post-inventory-count` books lines through the shared core
+- [x] Task 7: Reconcile service + route (`valuation.reconcile`)
+- [x] Task 8: Workbench Reconcile button + tie-out caveat copy
+- [x] Task 9: Rules / AGENTS.md / product-docs sync
+- [ ] Task 10: End-to-end verification (browser via /test + SQL spot checks)
+
+## Dependencies
+- Task 2 needs Task 1 (regenerated enum types).
+- Task 3 needs Task 2. Tasks 4 and 5 need Task 3 and are **independent of each other** (parallel OK).
+- Task 6 needs Task 2 (independent of Tasks 3–5; parallel OK).
+- Task 7 is independent of Tasks 1–6 (parallel OK). Task 8 needs Task 7.
+- Task 9 needs Tasks 3–8. Task 10 is last.
+
+---
+
+## Task 1: Migration — journal document-type enum values + regenerated types
+
+**Depends on:** none
+**Files:**
+- Create: `packages/database/supabase/migrations/<timestamp>_inventory-adjustment-gl-posting.sql` (via CLI)
+- Modify: `packages/database/src/types.ts`, `packages/database/supabase/functions/lib/types.ts` — regenerated only, never hand-edited
+
+**Steps:**
+1. `pnpm db:migrate:new inventory-adjustment-gl-posting` (never hand-pick the timestamp; HHMMSS must not be `000000`).
+2. File contents, exactly:
+ ```sql
+ -- Inventory adjustments and inventory counts now post GL journals
+ -- (spec: .ai/specs/2026-07-14-inventory-adjustment-gl-posting.md).
+ -- journalEntrySourceType already contains 'Inventory Adjustment' (20260402000000).
+ ALTER TYPE "journalLineDocumentType" ADD VALUE IF NOT EXISTS 'Inventory Adjustment';
+ ALTER TYPE "journalLineDocumentType" ADD VALUE IF NOT EXISTS 'Inventory Count';
+ ```
+3. `pnpm db:migrate` (applies to the local DB and regenerates types + swagger).
+4. If step 3 did not regenerate types (no new migrations detected), run `pnpm run generate:types` explicitly.
+
+**Verify:**
+```bash
+grep -n "Inventory Adjustment" packages/database/src/types.ts | head -3
+# Expected: at least one hit inside the journalLineDocumentType enum union
+pnpm exec turbo run typecheck --filter=@carbon/database
+# Expected: 1 successful, 0 errors
+```
+
+**Out of scope:** no new tables, no RLS, no changes to `journalEntrySourceType` (value already exists).
+
+---
+
+## Task 2: Shared posting core `shared/post-adjustment.ts`
+
+**Depends on:** Task 1
+**Files:**
+- Create: `packages/database/supabase/functions/shared/post-adjustment.ts`
+- Create: `packages/database/supabase/functions/shared/post-adjustment.test.ts`
+- Copy from (precedent): `packages/database/supabase/functions/post-shipment/index.ts:1140-1205` (COGS consumption + costLedger row + journal insert), `packages/database/supabase/functions/shared/calculate-cogs.ts` (layer filters), `packages/database/supabase/functions/issue/resolve-tracked-entity-bin.test.ts` (deno test shape)
+
+**Steps:**
+1. Export a pure function (unit-testable, no I/O):
+ ```ts
+ export function computeCurrentUnitCost(
+ itemCost: { costingMethod: "Standard" | "Average" | "FIFO" | "LIFO"; unitCost: number | null; standardCost: number | null },
+ openLayers: Array<{ quantity: number; remainingQuantity: number; cost: number; appliedChildCost: number }>
+ ): number
+ ```
+ - `Standard` → `standardCost ?? 0`; `Average` → `unitCost ?? 0`.
+ - `FIFO`/`LIFO` → `Σ(remainingQuantity × (cost + appliedChildCost) / quantity) / Σ remainingQuantity` over layers with `remainingQuantity > 0`; when there are no open layers (or Σ remaining is 0) fall back to `unitCost ?? 0`. Guard `quantity > 0` per layer (skip zero-quantity layers).
+2. Export the booking function. It writes ONE movement (item ledger + optional cost layers + optional journal) inside the caller's transaction and returns what it wrote:
+ ```ts
+ import type { Transaction } from "kysely";
+ import { DB } from "../lib/database.ts";
+
+ export interface BookAdjustmentArgs {
+ ledger: {
+ postingDate: string; // yyyy-MM-dd (today)
+ itemId: string;
+ quantity: number; // SIGNED delta: >0 Positive Adjmt., <0 Negative Adjmt.
+ locationId: string | null;
+ storageUnitId: string | null;
+ trackedEntityId: string | null;
+ entryType: "Positive Adjmt." | "Negative Adjmt.";
+ documentType?: "Inventory Count" | null; // itemLedgerDocumentType enum — manual adjustments stay NULL
+ // (byte-identical ledger rows; 'Inventory Adjustment' exists only
+ // on journalLineDocumentType)
+ documentId?: string | null; // count id for counts; null for manual (backfilled with the ledger id)
+ correctionOfItemLedgerId?: string | null;
+ comment?: string | null;
+ companyId: string;
+ createdBy: string;
+ };
+ item: { itemTrackingType: string | null; replenishmentSystem: "Buy" | "Make" | "Buy and Make" | null };
+ itemCost: { costingMethod: "Standard" | "Average" | "FIFO" | "LIFO"; unitCost: number | null; standardCost: number | null };
+ accounting: {
+ accountingPeriodId: string;
+ accountDefaults: { rawMaterialsAccount: string; finishedGoodsAccount: string; inventoryAdjustmentVarianceAccount: string };
+ description: string; // journal description, e.g. `Inventory Count IC-000042`
+ userId: string;
+ } | null; // null ⇒ accountingEnabled=false: ledger + layers only
+ skipValuation?: boolean; // true for storage-unit-transfer legs: ledger row ONLY
+ }
+ export async function bookAdjustment(trx: Transaction<DB>, args: BookAdjustmentArgs):
+ Promise<{ itemLedgerId: string; journalId: string | null; cost: number }>
+ ```
+ Behavior, in order:
+ a. Insert the `itemLedger` row (all `ledger` fields verbatim), `returning(["id"])`.
+ b. If `skipValuation` or `item.itemTrackingType === "Non-Inventory"` → return `{ itemLedgerId, journalId: null, cost: 0 }` (no layers, no journal).
+ c. **Cost layers (always, even when `accounting` is null — the post-receipt precedent):**
+ - `quantity < 0`: `const cogs = await calculateCOGS(trx, { itemId, quantity: Math.abs(quantity), companyId })` (import from `../shared/calculate-cogs.ts`), then insert the consumption `costLedger` row exactly like `post-shipment/index.ts:1163-1180`: `{ itemLedgerType: ledger.entryType, costLedgerType: "Direct Cost", adjustment: false, documentType: ledger.documentType ?? null, documentId, itemId, quantity: -abs, cost: -cogs.totalCost, remainingQuantity: 0, companyId }` (NOTE: `costPostedToGL` was dropped from `costLedger` — do not set it). `cost = cogs.totalCost`.
+ - `quantity > 0`: query open layers with the SAME filters `calculateCOGS` uses (`remainingQuantity > 0`, `adjustment = false`, `appliesToCostLedgerId is null`, `documentType` null-or-not-`'Purchase Order'`) plus, per layer, the applied-children sum (`SUM(cost)` of rows whose `appliesToCostLedgerId` = layer id) — then `unitCost = computeCurrentUnitCost(itemCost, layers)`; insert a NEW layer: `{ itemLedgerType: ledger.entryType, costLedgerType: "Direct Cost", adjustment: false, documentType: ledger.documentType ?? null, documentId, itemId, quantity: abs, cost: abs × unitCost, remainingQuantity: abs, companyId }`. `cost = abs × unitCost`.
+ d. **Journal** — only when `accounting !== null` AND `cost > 0` (a zero-value movement posts no journal):
+ - `const journalEntryId = await getNextSequence(trx, "journalEntry", companyId)` (import from `./get-next-sequence.ts`).
+ - Insert `journal` exactly like `post-shipment/index.ts:1184-1200`: `{ journalEntryId, accountingPeriodId, description, postingDate: ledger.postingDate, companyId, sourceType: "Inventory Adjustment", status: "Posted", postedAt: new Date().toISOString(), postedBy: accounting.userId, createdBy: accounting.userId }`, returning `id`.
+ - Resolve the inventory side with `resolveInventoryAccount(item.replenishmentSystem, accounting.accountDefaults)` (import from `./get-posting-group.ts`).
+ - Insert two `journalLine` rows sharing one `journalLineReference` (use `nanoid` exactly as `post-receipt/index.ts` imports it), both with `documentType: ledger.documentType ?? "Inventory Adjustment"`, `documentId` (the count id, else the new itemLedger id), `quantity: Math.abs(ledger.quantity)`, `companyId`, and amounts via the `debit`/`credit` helpers from `../lib/utils.ts`:
+ - `quantity > 0` (gain): inventory account `debit("asset", cost)` with the resolved account description; 5310 (`inventoryAdjustmentVarianceAccount`) `credit("expense", cost)` with description `"Inventory Adjustment"`.
+ - `quantity < 0` (loss): 5310 `debit("expense", cost)`; inventory account `credit("asset", cost)`.
+ - `accountId` column, never account number (lesson: control accounts resolve by id).
+ e. Return `{ itemLedgerId, journalId, cost }`.
+3. `post-adjustment.test.ts`: deno tests for `computeCurrentUnitCost` only (shape copied from `issue/resolve-tracked-entity-bin.test.ts`): Standard, Average, FIFO weighted-average with applied children (layers 60 rem @ base $10 qty 100 + child $55 ⇒ effective (60×10.55)/60 = 10.55), no-open-layers fallback, zero-quantity-layer skip.
+
+**Verify:**
+```bash
+cd packages/database/supabase/functions && deno check shared/post-adjustment.ts && deno test shared/post-adjustment.test.ts
+# Expected: check passes; test output ends with "ok" and 0 failed
+```
+
+**Out of scope:** tracked-entity mutations (each caller owns them); no HTTP handling; do not modify `calculate-cogs.ts`.
+If `deno` is unavailable on this machine, STOP and report — do not skip the check.
+
+---
+
+## Task 3: New edge function `post-inventory-adjustment`
+
+**Depends on:** Task 2
+**Files:**
+- Create: `packages/database/supabase/functions/post-inventory-adjustment/index.ts`
+- Modify: `packages/database/supabase/config.toml` — add function entry
+- Copy from (precedent): `packages/database/supabase/functions/post-inventory-count/index.ts` (skeleton, error contract, FOR-UPDATE txn style), `apps/erp/app/modules/inventory/inventory.service.ts:1442-1834` (the semantics being ported, verbatim behavior)
+
+**Steps:**
+1. Skeleton per `.ai/rules/workflow-edge-function.md`: CORS OPTIONS short-circuit, module-scope `getConnectionPool(1)` + `getDatabaseClient`, try/catch returning `{ message }` with status 400 for business-validation failures and 500 otherwise (copy the error-contract comment block from `post-inventory-count/index.ts:219-246` so `getEdgeFunctionErrorMessage` keeps working).
+2. Payload validator (zod):
+ ```ts
+ const payloadValidator = z.object({
+ adjustmentType: z.enum(["Positive Adjmt.", "Negative Adjmt.", "Set Quantity"]),
+ itemId: z.string(),
+ locationId: z.string(),
+ storageUnitId: z.string().optional().nullable(),
+ trackedEntityId: z.string().optional().nullable(),
+ quantity: z.number(),
+ readableId: z.string().optional().nullable(),
+ originalStorageUnitId: z.string().optional().nullable(),
+ expirationDate: z.string().optional().nullable(),
+ comment: z.string().optional().nullable(),
+ companyId: z.string(),
+ userId: z.string()
+ });
+ ```
+3. `requirePermissions(req, companyId, userId, { update: "inventory" })`.
+4. Preloads (supabase client, before the transaction): `get_item_quantities_by_tracking_id` RPC (`{ item_id, company_id, location_id }`), `item` (`itemTrackingType, replenishmentSystem, readableIdWithRevision`), `itemCost` (`costingMethod, unitCost, standardCost`), `companySettings.accountingEnabled`, `getDefaultPostingGroup(client, companyId)` (only when accounting enabled), `itemShelfLife` (`mode, days`), and — when accounting enabled — `getCurrentAccountingPeriod` with the same arguments `post-inventory-count`/`post-shipment` pass it.
+5. Inside one `db.transaction()`, port `insertManualInventoryAdjustment` (`inventory.service.ts:1442-1834`) **verbatim in behavior**, replacing every `client.from("itemLedger").insert(...)` with `bookAdjustment(trx, ...)` and every trackedEntity read/write with `trx` equivalents:
+ - **Storage-unit transfer** (trackedEntityId + originalStorageUnitId ≠ storageUnitId, lines 1537-1606): optional `readableId` update; expiry override; then TWO `bookAdjustment` calls with `skipValuation: true` — negative `-currentQuantityOnHand` at `originalStorageUnitId`, positive `+currentQuantityOnHand` at `storageUnitId`.
+ - **Set Quantity** (lines 1608-1633): delta = `quantity - currentQuantityOnHand`; >0 ⇒ Positive, <0 ⇒ Negative (absolute delta), =0 ⇒ apply readableId/expiry updates only and respond `{ success: true, itemLedger: null }`.
+ - **Negative resolution** (lines 1643-1742): keep the three branches and these EXACT error strings (routes string-match them): `"Serial number not found"`, `"Insufficient quantity for negative adjustment"`, `"Multiple tracked entities in this storage unit — select a specific row to adjust"`. Tracked-entity quantity decrements stay as in the source (now via `trx`).
+ - **Plain negative guard** (lines 1745-1752) and **tracked entity update/create** (lines 1754-1831) including: the `"Inventory Adjustment"` attributes stamp + `expiryOverrides` blob exactly as lines 1783-1804; new-entity expiry fallback from `itemShelfLife` `Fixed Duration` (lines 1473-1490); existing-entity expiry override replicating `updateTrackedEntityExpiry` semantics — locate that function in `inventory.service.ts` (grep `export async function updateTrackedEntityExpiry`) and reproduce its writes (update `expirationDate`, append to `attributes.expiryOverrides` with `{previous, next, reason, source: "Inventory Adjustment", userId, at}`).
+ - **Final movement**: `bookAdjustment` with signed quantity, `documentType: null` (manual ledger rows keep today's NULL documentType; the JOURNAL lines get 'Inventory Adjustment' from the core), `documentId: null` (core backfills the ledger id), `accounting` context when enabled (`description: "Inventory Adjustment"` + `— ${comment}` when present).
+6. Response: 200 `{ success: true, itemLedger: { id } }` (or `itemLedger: null` on the no-op path).
+7. `config.toml`, after the `[functions.post-inventory-count]` block:
+ ```toml
+ [functions.post-inventory-adjustment]
+ enabled = true
+ verify_jwt = true
+ entrypoint = "./functions/post-inventory-adjustment/index.ts"
+ ```
+
+**Verify:**
+```bash
+cd packages/database/supabase/functions && deno check post-inventory-adjustment/index.ts
+# Expected: no errors
+grep -A2 "post-inventory-adjustment" packages/database/supabase/config.toml
+# Expected: enabled = true, verify_jwt = true
+```
+
+**Out of scope:** do not modify `post-inventory-count` here (Task 6); do not touch the ERP/MES services yet (Tasks 4–5).
+If `get_item_quantities_by_tracking_id` cannot be invoked with the service-role client from the edge runtime, STOP and report — do not substitute a different quantity source.
+
+---
+
+## Task 4: ERP service wrapper delegates to the edge function
+
+**Depends on:** Task 3
+**Files:**
+- Modify: `apps/erp/app/modules/inventory/inventory.service.ts` — replace the body of `insertManualInventoryAdjustment` (lines 1442-1834) with an invoke; keep the exported signature IDENTICAL
+- Copy from (precedent): the invoke + error-extraction pattern used by the inventory-count post route — grep `getEdgeFunctionErrorMessage` under `apps/erp/app/` and reuse that helper
+
+**Steps:**
+1. New body: map `createdBy` → `userId`, pass all validator fields + `companyId` in `body`, then
+ `const result = await client.functions.invoke("post-inventory-adjustment", { body })`.
+2. Return contract must stay drop-in for the caller (`routes/x+/inventory+/quantities+/$itemId.adjustment.tsx:106-118` compares `itemLedger.error === "<message>"` — the old service returned bare-STRING errors from its validation branches):
+ - success → `{ data: result.data?.itemLedger ?? null, error: null }`
+ - failure → `{ data: null, error: <string message> }` where the message is extracted from the response body via `getEdgeFunctionErrorMessage` (`apps/erp/app/utils/error.ts`), falling back to "Failed to create manual inventory adjustment".
+3. Delete the now-dead local helpers (`resolveExpirationForNewEntity`, `applyExpirationOverride`) — but do NOT delete `updateTrackedEntityExpiry` (it has other callers).
+4. Leave `inventoryAdjustmentValidator` in `inventory.models.ts` untouched (the form contract is unchanged).
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=erp
+# Expected: 1 successful, 0 errors
+grep -c "itemLedger" apps/erp/app/modules/inventory/inventory.service.ts
+# Expected: fewer hits than before in the 1442-region (no direct itemLedger insert remains in insertManualInventoryAdjustment)
+```
+
+**Out of scope:** route files, forms, MES.
+
+---
+
+## Task 5: MES service wrapper delegates to the edge function
+
+**Depends on:** Task 3 (independent of Task 4)
+**Files:**
+- Modify: `apps/mes/app/services/inventory.service.ts` — `insertManualInventoryAdjustment` (line 439) and nothing else
+
+**Steps:**
+1. Replace the direct `itemLedger` insert with an invoke of `post-inventory-adjustment`. Map the MES validator (line 36: `itemId, locationId, storageUnitId?, entryType, quantity`) to the payload: `adjustmentType: entryType`, quantity as-is (positive; the edge function owns sign normalization and the insufficient-quantity guard), `companyId`, `userId: createdBy`.
+2. Same return-contract mapping as Task 4 (the MES route `x+/adjustment.tsx:32-43` string-matches the insufficient-quantity message).
+
+**Verify:**
+```bash
+sed -n 's/.*"name": "\(.*\)".*/\1/p' apps/mes/package.json | head -1 # confirm the package name first
+pnpm exec turbo run typecheck --filter=<that name>
+# Expected: 1 successful, 0 errors
+```
+
+**Out of scope:** MES routes/components (`AdjustInventory.tsx` unchanged).
+
+---
+
+## Task 6: `post-inventory-count` books lines through the shared core
+
+**Depends on:** Task 2 (independent of Tasks 3–5)
+**Files:**
+- Modify: `packages/database/supabase/functions/post-inventory-count/index.ts` — per-line loop (lines 144-190) + preloads + header comment
+
+**Steps:**
+1. Extend the preloads: the existing `item` query (line 99) additionally selects `replenishmentSystem`; add `itemCost` rows for the counted item ids; add `companySettings.accountingEnabled`; when enabled, `getDefaultPostingGroup` + `getCurrentAccountingPeriod` (same call shape as `post-shipment`).
+2. In the transaction loop, replace the raw `trx.insertInto("itemLedger")` (lines 147-171) with `bookAdjustment(trx, ...)`:
+ - `ledger`: same fields as today plus `documentType: "Inventory Count"`, `documentId: inventoryCountId`, `correctionOfItemLedgerId: line.postedItemLedgerId ?? null`, signed `quantity: delta`.
+ - `accounting`: the preloaded context with `description: \`Inventory Count ${inventoryCount.data.inventoryCountId}\``, or `null` when accounting is disabled.
+ - Keep the trackedEntity delta-apply (lines 175-182) and the `postedItemLedgerId` bookkeeping (lines 184-189, now using the returned `itemLedgerId`) EXACTLY as they are.
+3. Update the header comment (lines 38-46): counts now maintain cost layers and post journals; remove the "no GL journal lines" sentence. Rectify semantics are unchanged (incremental delta, `correctionOfItemLedgerId` link, valued at posting-time cost).
+
+**Verify:**
+```bash
+cd packages/database/supabase/functions && deno check post-inventory-count/index.ts
+# Expected: no errors
+grep -n "no GL journal lines" packages/database/supabase/functions/post-inventory-count/index.ts
+# Expected: no matches
+```
+
+**Out of scope:** `plan-post.ts` (snapshot-delta reconciliation math is untouched); `rectifyInventoryCount` in the ERP service (already correct — it posts nothing).
+
+---
+
+## Task 7: Reconcile service + route
+
+**Depends on:** none (parallel with Tasks 1–6)
+**Files:**
+- Modify: `apps/erp/app/modules/inventory/inventory.service.ts` — add `createInventoryReconciliationJournal`
+- Create: `apps/erp/app/routes/x+/inventory+/valuation.reconcile.tsx` (action only)
+- Modify: `apps/erp/app/utils/path.ts` — add `inventoryValuationReconcile`
+- Copy from (precedent): `createIntercompanyTransaction` (`apps/erp/app/modules/accounting/accounting.service.ts:2967-3028`) for the journal + paired-line insert; `getInventoryValuationTieOut` (`inventory.service.ts:342`) for the variance rows
+
+**Steps:**
+1. Service function:
+ ```ts
+ export async function createInventoryReconciliationJournal(
+ client: SupabaseClient<Database>,
+ companyId: string,
+ args: { asOfDate: string; userId: string }
+ )
+ ```
+ - Call `getInventoryValuationTieOut(client, companyId, args.asOfDate)`; keep rows with `Math.abs(variance) > 0.005`. If none → return `{ data: null, error: { message: "Nothing to reconcile — variance is zero" } }`.
+ - `getNextSequence(client, "journalEntry", companyId)` (same import `createIntercompanyTransaction` uses).
+ - Insert ONE `journal`: `{ journalEntryId, description: \`Inventory subledger reconciliation as of ${asOfDate}\`, postingDate: <today>, sourceType: "Manual", status: "Draft", companyId, createdBy: userId }`.
+ - Per variance row insert a `journalLine` pair sharing a `crypto.randomUUID()` reference (variance = subledger − GL, so this brings GL up to the subledger):
+ - inventory account (`row.accountId`): `amount: +variance`
+ - `accountDefault.inventoryAdjustmentVarianceAccount` (fetch by id from `accountDefault`): `amount: -variance`
+ (positive amount on an Asset = debit, negative on an Expense = credit — the `journalEntries` view derives debit/credit from class + sign; the raw amounts sum to 0.)
+ - Return `{ data: { journalId }, error: null }`.
+2. Route `valuation.reconcile.tsx`: `assertIsPost`; `requirePermissions(request, { create: "accounting" })`; read `asOfDate` from formData (default today); call the service; on error `return data({}, await flash(request, error(...)))`; on success `throw redirect(<journals list>, await flash(request, success("Draft reconciliation journal created")))`. Find the journals-list helper with `grep -n "journal" apps/erp/app/utils/path.ts` — use the helper that maps to `routes/x+/accounting+/journals.tsx`.
+3. `path.ts`: `inventoryValuationReconcile: ${x}/inventory/valuation/reconcile` next to the existing `inventoryValuation` entry.
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=erp
+# Expected: 1 successful, 0 errors
+```
+
+**Out of scope:** no changes to `getInventoryValuationTieOut`, the valuation RPC, or the journals UI. The journal is Draft — never auto-post it.
+
+---
+
+## Task 8: Workbench Reconcile button + tie-out caveat copy
+
+**Depends on:** Task 7
+**Files:**
+- Modify: `apps/erp/app/modules/inventory/ui/Valuation/InventoryValuationWorkbench.tsx` — tie-out Popover (lines ~446-545)
+- Copy from (precedent): this file's own Popover + any `fetcher.Form` submit button in `apps/erp/app/modules/invoicing/ui/Workbench/ARAPWorkbench.tsx`
+
+**Steps:**
+1. Inside the tie-out `PopoverContent`, after the totals row, add a `fetcher.Form` (`method="post"`, `action={path.to.inventoryValuationReconcile}`) with a hidden `asOfDate` input (the current filter value) and a `Button` labeled `t\`Reconcile\``, `isLoading` off the fetcher. Render only when `hasVariance && permissions.can("create", "accounting")` (`usePermissions`).
+2. Remove the caveat string `"Manual quantity adjustments don't post to the GL yet, so a nonzero variance is expected if you cycle count."` entirely — NO replacement text (Brad, 2026-07-15); the popover shows only the Reconcile button when `hasVariance`.
+3. All new strings through Lingui (`useLingui`/`<Trans>`); `/translate` fills catalogs at commit time via check-and-commit.
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=erp
+# Expected: 1 successful, 0 errors
+grep -n "don't post to the GL yet" apps/erp/app/modules/inventory/ui/Valuation/InventoryValuationWorkbench.tsx
+# Expected: no matches
+```
+
+**Out of scope:** no layout redesign of the popover; no changes to the table or filters.
+
+---
+
+## Task 9: Rules / AGENTS.md / product-docs sync
+
+**Depends on:** Tasks 3–8
+**Files:**
+- Modify: `.ai/rules/inventory-system.md` — `insertManualInventoryAdjustment` bullet: now a wrapper over the `post-inventory-adjustment` edge function; adjustments/counts maintain cost layers and post journals (5310 vs RM/FG); note the Reconcile action
+- Modify: `apps/erp/app/modules/inventory/AGENTS.md` — same one-line update in Key Service Functions + Safety (still: never INSERT itemLedger directly)
+- Modify: `docs/` — inventory adjustments + valuation report pages via the `carbon-docs` skill (ground every claim in the merged code)
+
+**Steps:**
+1. Update the two rule/AGENTS files with the new posting path (keep edits surgical — only lines that are now stale).
+2. Invoke the `carbon-docs` skill for the docs site: adjustments now post journals; valuation tie-out Reconcile action. If the docs app fails to build for unrelated reasons, STOP and report.
+
+**Verify:**
+```bash
+grep -n "post-inventory-adjustment" .ai/rules/inventory-system.md apps/erp/app/modules/inventory/AGENTS.md
+# Expected: at least one hit in each file
+```
+
+**Out of scope:** root AGENTS.md Task Router (no new subsystem file).
+
+---
+
+## Task 10: End-to-end verification (browser via /test + SQL spot checks)
+
+**Depends on:** Tasks 1–8 (Task 9 may run in parallel)
+**Files:** none (verification only)
+
+**Steps:**
+1. Prerequisites: local stack running (`crbn up`, plain portless form); accounting enabled for the dev company (toggle at `/x/settings/accounting` — a fresh `crbn reset` seeds it off).
+2. Invoke the `/test` skill with these scenarios (it handles `/auth` login):
+ a. ERP → Inventory → Quantities → adjust an untracked Buy item −N and +N; expect success toasts.
+ b. ERP → Accounting → Journals: two new Posted journals with source "Inventory Adjustment" — loss = Dr Inventory Adjustment / Cr Raw Materials, gain mirrored.
+ c. ERP → Inventory → Valuation: tie-out variance for Raw Materials still $0.00 after both adjustments; old caveat copy gone.
+ d. Inventory Count: create, count one line with a variance, post; journal appears with the count's readable id in the description. Rectify → change the count → re-post; second linked movement appears in the count's movements list.
+ e. Storage-unit transfer: move a tracked batch between two bins from the quantities page; expect the ledger pair in the item's movements, NO new journal (Journals list count unchanged), and tie-out variance unchanged.
+ f. MES (`https://<worktree>.mes.dev`): shop-floor adjustment posts the same journal shape.
+ g. Tie-out Reconcile: only if a nonzero variance exists (e.g. seeded pre-feature adjustment) — button creates a Draft journal and redirects to Journals; tie-out unchanged until that journal is posted.
+3. SQL spot checks against the local DB (connection string from `.env.local`):
+ ```sql
+ -- balanced journals, layer integrity for the adjusted item
+ SELECT "journalId", SUM("amount") FROM "journalLine" WHERE "documentType" = 'Inventory Adjustment' GROUP BY "journalId";
+ -- Expected: every SUM = 0
+ SELECT "remainingQuantity" >= 0 FROM "costLedger" WHERE "itemId" = '<adjusted item>' ORDER BY "createdAt" DESC LIMIT 5;
+ -- Expected: all true
+ ```
+4. Check off the Progress list in this plan file; record evidence (screenshots from /test) in `.ai/runs/`.
+
+**Verify:**
+```bash
+# /test run completes with all scenarios PASS; the two SQL checks return expected values.
+```
+
+**Out of scope:** performance load-testing the count post; period-close concurrency testing (covered by the existing `FOR SHARE` guard migration).
diff --git a/.ai/research/inventory-adjustment-gl-posting.md b/.ai/research/inventory-adjustment-gl-posting.md
new file mode 100644
index 0000000000..7817559bec
--- /dev/null
+++ b/.ai/research/inventory-adjustment-gl-posting.md
@@ -0,0 +1,326 @@
+# Inventory Adjustment GL Posting Research: Best Practices Survey
+
+## Summary
+
+Surveyed how SAP S/4HANA, NetSuite, Fishbowl, and Epicor Kinetic post inventory
+quantity adjustments (cycle counts, manual adjustments, shop-floor scrap) to the
+general ledger. Strong consensus: an adjustment is a posting event that hits the
+GL immediately (perpetual inventory), valued at quantity × the item's current
+cost under its costing method (never a user-entered cost on decreases), with the
+inventory asset account on one side and a dedicated "inventory adjustment"
+(gain/loss/shrinkage) P&L account on the other. The offset account resolves from
+a company-level default, optionally refined by reason codes (Epicor) or separate
+scrap accounts (Fishbowl, SAP movement types). Cycle counts do not have their own
+posting mechanism — count approval funnels into the same adjustment transaction
+(NetSuite creates literal Inventory Adjustments on approval; SAP PI difference
+posting *is* a goods movement; Epicor Post Counts creates ADJ-QTY transactions).
+Carbon's current gap: `insertManualInventoryAdjustment` writes quantity-only
+`itemLedger` rows with no `costLedger` or `journal`/`journalLine` counterpart,
+which is exactly the tie-out variance the valuation workbench warns about.
+
+## Competitors Surveyed
+
+- **SAP S/4HANA** — the enterprise reference for physical inventory,
+ movement types, and automatic account determination (OBYC).
+- **NetSuite** — closest analogue to Carbon: perpetual inventory in a cloud ERP
+ with costing methods (Average/FIFO/LIFO/Standard) and a native Inventory
+ Count → Inventory Adjustment pipeline.
+- **Fishbowl** — inventory point solution posting journal entries to an external
+ GL (QuickBooks); relevant for its simple account-mapping model.
+- **Epicor Kinetic** — discrete-manufacturing reference for reason-code-driven
+ account routing and shop-floor scrap treatment.
+
+## Key Consensus Patterns
+
+### 1. An adjustment is a paired subledger + GL posting, created synchronously
+
+- **SAP**: posting a physical-inventory difference (MI07) creates a material
+ document and, for valuated stock, an accounting document *together,
+ synchronously*. "From the accounting point of view, this corresponds to a
+ goods receipt or goods issue."
+- **NetSuite**: the Inventory Adjustment is a posting transaction — GL impact on
+ save, no separate post step. Count approval generates adjustments that post
+ immediately.
+- **Fishbowl**: each adjustment sends a journal entry to QuickBooks instantly.
+- **Epicor (outlier)**: part transactions accumulate and the batch **Capture
+ COS/WIP Activity** process materializes GL entries periodically — a documented
+ source of "why can't I see GL activity during the month?" complaints and
+ reconciliation pain. The industry trend even within Epicor shops is to run
+ capture nightly to approximate real-time.
+- **Rationale**: perpetual inventory requires the subledger and GL to move in
+ lockstep or tie-outs break — the exact problem Carbon has today.
+
+### 2. Adjustment value = quantity × current cost under the costing method
+
+- **SAP**: difference qty × current valuation price (standard price for price
+ control S, moving average for V). No price-difference (PRD) posting arises —
+ there is no external value on a PI posting.
+- **NetSuite**: **negative** adjustments never take a user cost — the system
+ computes the credit from the costing method (average cost; FIFO consumes
+ oldest layers, LIFO newest; standard at standard). **Positive** adjustments
+ take an "Est. Unit Cost" that defaults to current average cost and creates a
+ new cost layer (behaves like a receipt).
+- **Fishbowl**: Cycle Count and Scrap take no user cost (valued from costing
+ layers / set cost); only "Add Inventory" lets the user assign a cost, to
+ create a real costing layer.
+- **Rationale**: decreases must relieve the same value the subledger is
+ carrying, or the asset account drifts from the subledger. Increases need a
+ cost source; current cost is the default, with optional override for
+ found/donated stock.
+
+### 3. Offset is a dedicated inventory-adjustment P&L account with a default + override hierarchy
+
+- **SAP**: transaction key **GBB-INV** — "expenditure/income from inventory
+ differences" — resolved by valuation class (item grouping). Scrap uses a
+ *different* key (GBB-VNG) so shrinkage and deliberate scrap are separable on
+ the P&L. The inventory (BSX) side is never manually posted.
+- **NetSuite**: "Adjustment Account" chosen per transaction (usually an expense
+ account); cycle counts pre-fill from the global preference **Default
+ Inventory Count Account**. Not per-item or per-reason natively.
+- **Epicor**: resolution hierarchy — reason-code GL control → part GL control →
+ part-class GL control → company default ("Inventory COS and WIP" GL control's
+ Inventory Adjustment account).
+- **Fishbowl**: mandatory part-type default mapping + optional per-part
+ override; separate Inventory Adjustment vs Scrap accounts.
+- **Rationale**: one company default makes the feature usable day one; the
+ hierarchy exists so businesses can separate shrinkage / scrap / count
+ variance on the P&L without reclassing journal entries.
+
+### 4. Adjustment direction determines debit/credit, same accounts both ways
+
+Consensus entry shape (SAP example, valuation price $10, difference 5 EA):
+
+| Case | Debit | Credit |
+|---|---|---|
+| Gain (count > book) | Inventory asset $50 | Inventory adjustment (income) $50 |
+| Loss (count < book) | Inventory adjustment (expense) $50 | Inventory asset $50 |
+
+NetSuite and Fishbowl post the same shape. Most shops use a single P&L account
+for both directions (SAP training text describes an expense/revenue pair, but a
+single "inventory differences" account per valuation class is common practice).
+
+### 5. Cycle counts funnel into the same adjustment posting path
+
+- **NetSuite**: count lifecycle (Open → Started → Completed/Pending Approval →
+ Approved); approval creates one positive and/or one negative **Inventory
+ Adjustment** transaction — the count itself never posts.
+- **SAP**: the PI document lifecycle (create → count → recount → post
+ difference) ends in a goods movement (701/702) like any other.
+- **Epicor**: Post Counts creates ADJ-QTY part transactions stamped with the
+ count-discrepancy reason code.
+- **Rationale**: one posting code path, many entry points. The count feature is
+ workflow (snapshot, count, approve); the posting is just an adjustment.
+
+### 6. Posting lands in an open accounting period, dated at posting time
+
+- **SAP**: the count date fixes the posting period; differences must post in
+ the same (or next open) period — cross-fiscal-year posting is blocked.
+- **NetSuite**: posts to the selected open posting period; date defaults to
+ today; closed periods reject postings.
+- **Rationale**: shrinkage discovered in July must hit July's P&L; backdating
+ into closed periods breaks reported financials.
+
+### 7. Shop-floor scrap during production is a WIP problem, not an inventory-adjustment problem
+
+- **Epicor**: scrap reported on a job operation has *no* immediate GL impact —
+ cost stays in WIP and purges as manufacturing variance (MFG-VAR) at job
+ close. Only inventory-level scrap (ADJ-QTY with a scrap reason) posts an
+ adjustment.
+- **SAP**: scrapping *from stock* (movement 551 → GBB-VNG) posts immediately;
+ scrap *within an order* flows through order settlement/variance.
+- **Rationale**: material already issued to a job is WIP, relieved by the
+ production-costing flow. Inventory adjustments cover on-hand stock only.
+
+## Answers to Research Questions
+
+1. **What document/entity is created, and what lifecycle?** SAP: a physical
+ inventory document (create → count → recount → post difference) ending in a
+ material document + accounting document pair. NetSuite: an Inventory
+ Adjustment posting transaction (no draft state); Inventory Counts have a
+ lifecycle (Open → Started → Pending Approval → Approved) and materialize
+ adjustments at approval. Epicor: ADJ-QTY part transaction, GL entry at
+ capture. Consensus: the *adjustment* itself posts immediately without its
+ own approval workflow; approval lifecycles belong to the *count*, upstream.
+
+2. **Which accounts, and how is the offset determined?** Inventory asset
+ (auto-determined from the item — SAP valuation class, NetSuite item record's
+ asset account, Carbon's `resolveInventoryAccount` equivalent) against a
+ dedicated inventory-adjustment P&L account. Offset resolution: SAP GBB-INV
+ by valuation class; NetSuite per-transaction with a global default for
+ counts; Epicor reason → part → part class → company default; Fishbowl
+ part-type default + per-part override.
+
+3. **How is the adjustment valued?** Quantity × current cost under the item's
+ costing method (SAP, NetSuite, Fishbowl agree). Negative adjustments consume
+ cost layers exactly like a sale/issue (FIFO oldest-first, LIFO newest-first,
+ average at current average, standard at standard) with no user cost input.
+ Positive adjustments default to current cost; NetSuite/Fishbowl allow a user
+ override which creates a new cost layer. NetSuite's "underwater" preference
+ (last purchase price / zero / average for depletions below zero) handles
+ negative-inventory costing with corrections posted when stock resurfaces.
+
+4. **Do cycle counts, manual adjustments, and scrap post differently?** Same
+ mechanism, different offset routing. SAP separates by movement type
+ (701/702 PI diff → GBB-INV vs 551/552 scrap → GBB-VNG); Epicor and Fishbowl
+ separate by reason code / mapped scrap account. NetSuite doesn't natively
+ (reason codes are a common customization). In-production scrap is a WIP
+ variance concern, out of scope for inventory adjustments (see pattern 7).
+
+5. **When does posting happen and with what date?** Immediately at
+ posting/approval (SAP, NetSuite, Fishbowl), into an open accounting period,
+ dated at posting time (NetSuite count-generated adjustments date at
+ approval; SAP forces same-period-as-count). Epicor's batch capture is the
+ outlier and a documented pain point — not a model to copy.
+
+6. **Standard terminology?** "Inventory Adjustment" (NetSuite/Epicor/Fishbowl —
+ the natural fit for Carbon, which already uses "Positive Adjmt."/"Negative
+ Adjmt." entry types), "physical inventory difference" (SAP), "Adjustment
+ Account" / "expense or income from inventory differences" for the offset,
+ "shrinkage" colloquially for losses, "cost layers" for FIFO/LIFO valuation.
+
+## Competitor-Specific Details
+
+### SAP S/4HANA
+- Movement types auto-selected by stock type at difference posting: 701/702
+ (unrestricted gain/loss), 703/704 (quality inspection), 707/708 (blocked).
+ Scrap 551/552; initial stock load 561/562 (offset GBB-BSA, the only flow here
+ that can hit a price-difference account under standard costing).
+- OBYC lookup chain: chart of accounts → transaction key (BSX/GBB) → valuation
+ grouping code (plant grouping) → general modification (INV/VNG/BSA/VBR) →
+ valuation class (item grouping) → GL account.
+- BSX (stock) accounts are posted **only automatically** — manual FI postings
+ to them are prohibited by convention, or the stock account stops tying to the
+ subledger.
+- MI07 posts in the background with no cost-center field; cost-center
+ assignment for the P&L account comes from OKB9 defaults.
+- Tolerances: max difference amount per line/user tolerance group.
+
+### NetSuite
+- Inventory Adjustment: header Adjustment Account (required), Date, Posting
+ Period, Memo, Department/Class/Location segments, optional Customer for job
+ costing; lines carry Adjust Qty By (delta) and Est. Unit Cost
+ (increases only).
+- Inventory Adjustment **Worksheet** (absolute "New Qty" reset) is explicitly
+ discouraged for FIFO/LIFO — it destroys costing history ("sells the items and
+ buys them back"). Delta adjustments preserve layers. Carbon's "Set Quantity"
+ adjustment type should internally resolve to a delta for exactly this reason.
+- Zero-GL escape hatch: a positive adjustment at cost 0 creates a zero-cost
+ layer and posts nothing.
+- Count feature: snapshot at Start Count; Calculated (next-count-date driven)
+ vs Manual counts; approval gate reviews variance detail; rejection re-counts;
+ a preference re-snapshots on reject to absorb mid-count transactions.
+
+### Fishbowl
+- Three adjustment types with distinct offsets: Cycle Count (set-to-counted →
+ inventory adjustment account), Add Inventory (delta with user cost → creates
+ costing layer), Scrap (→ separate mapped scrap account).
+- Cost Adjustment: changing a part's cost posts (cost change × on-hand qty) to
+ inventory vs the adjustment account — value corrections are also GL events.
+- Initial go-live count deliberately posts nothing (value assumed already on
+ the books).
+
+### Epicor Kinetic
+- Reason codes typed (Inventory Adjustment, Scrap, RMA, DMR), each optionally
+ carrying a GL control; multiple reasons can share one control; falls back to
+ the company COS-and-WIP control's Inventory Adjustment account.
+- Documented gotcha: if the inventory account and adjustment account resolve to
+ the same GL account, Epicor suppresses the $0-net entry — adjustments appear
+ to vanish from the GL.
+- Batch capture evaluates GL controls at *run* time, not transaction time —
+ another reconciliation failure mode Carbon avoids by posting synchronously.
+
+## Recommended Approach for Carbon
+
+1. **Post adjustments synchronously through an edge function, following the
+ `post-receipt` pattern** (SAP/NetSuite immediate-posting model, and Carbon's
+ own established pattern). Manual adjustments currently write quantity-only
+ `itemLedger` rows from `insertManualInventoryAdjustment`
+ (`apps/erp/app/modules/inventory/inventory.service.ts`); the posting path
+ must add paired `costLedger` and `journal`/`journalLine` writes in the same
+ transaction, guarded by `accountingEnabled` like receipts/shipments.
+
+2. **Value adjustments by the item's costing method** (SAP qty × valuation
+ price rule; NetSuite layer consumption): negative adjustments consume open
+ `costLedger` layers via the existing `calculateCOGS`-style layer logic
+ (FIFO/LIFO) or current `itemCost` unit cost (Average/Standard); positive
+ adjustments post at current cost and create a `costLedger` layer so the
+ valuation RPC and the GL carry the same value. No user-entered cost on
+ decreases, ever.
+
+3. **Add a single company-level `inventoryAdjustmentAccount` to
+ `accountDefault`** as the offset (NetSuite Default Inventory Count Account /
+ SAP GBB-INV analogue). This respects Carbon's flat-defaults-over-matrix
+ convention. The inventory side reuses the existing `resolveInventoryAccount`
+ (rawMaterials vs finishedGoods by replenishment system) so adjustments hit
+ the same asset accounts the tie-out already watches.
+
+4. **One posting path, all entry points**: quantities page, item master
+ shelves, cycle count confirm, and MES shop-floor adjustments all already (or
+ should) funnel through `insertManualInventoryAdjustment` — attach GL posting
+ there, not per-surface (NetSuite count-approval-creates-adjustment pattern).
+ In-production scrap on jobs stays in the WIP/variance flow (Epicor/SAP
+ consensus) and is out of scope.
+
+5. **Resolve "Set Quantity" to a signed delta before posting** (NetSuite
+ worksheet lesson: absolute resets destroy FIFO/LIFO cost history; delta
+ adjustments preserve layers).
+
+6. **Post into the current open accounting period, dated at posting time**,
+ reusing `getCurrentAccountingPeriod` — matching SAP/NetSuite period
+ discipline and the tie-out RPC's `postingDate <= as_of_date` filter.
+
+7. **Defer reason-code → account routing** (Epicor hierarchy, Fishbowl scrap
+ account) to a follow-up. Capture the existing adjustment comment/type on the
+ journal description now so a later reason-code feature has a seam. If a
+ second account is ever wanted, scrap-vs-shrinkage is the first split the
+ industry makes.
+
+8. **Backfill question for the spec**: historical unposted adjustments will
+ still show a tie-out variance after the feature ships. The spec must decide
+ between a one-time catch-up journal (SAP-style opening adjustment) or
+ documenting the variance start date. Carry this into Open Questions.
+
+## Sources
+
+### SAP
+- https://learning.sap.com/courses/inventory-management-and-physical-inventory-in-sap-s-4hana/conducting-physical-inventory — PI phases, qty × price valuation, expense/revenue from PI offsets, period rules
+- https://www.guru99.com/all-about-physical-inventory.html — PI lifecycle MI01/MI04/MI07, posting block/freeze flags, movement types
+- https://community.sap.com/t5/enterprise-resource-planning-q-a/accounting-entries-for-movement-types-701-702/qaq-p/3408376 — Dr BSX / Cr GBB-INV for 701, reverse for 702
+- https://www.erpgreat.com/financial/obyc-different-transaction-like-bsx-gbb.htm — BSX auto-posting-only rule, GBB modifier list
+- https://erpcorp.com/sap-controlling-blog/fundamentals-of-mm-fi-account-determination — OBYC lookup chain
+- https://community.sap.com/t5/enterprise-resource-planning-q-a/reg-703-704-and-707-708-movement-types-for-stock-adjustments-mi10-migo/qaq-p/11317683 — movement type by stock type
+- https://community.sap.com/t5/enterprise-resource-planning-q-a/account-determination-for-entry-gbb-vng-class-7920-not-possible/qaq-p/9531456 — 551 scrap → GBB-VNG
+- https://userapps.support.sap.com/sap/support/knowledge/en/1589511 — cross-period/fiscal-year PI posting blocked
+- https://robertsap.wordpress.com/2014/05/23/posting-period-of-count-difference/ — count date fixes posting period
+- https://community.sap.com/t5/enterprise-resource-planning-q-a/select-cost-center-for-physical-inventory-difference-posting/qaq-p/7483436 — MI07 background FI doc, OKB9
+- https://help.sap.com/docs/SAP_S4HANA_CLOUD/4603118feda9495892abadbe8f8c3d14/32ddb3c915ed47fd9bca1b86ca2da762.html — goods movement → material doc + accounting doc
+- https://community.sap.com/t5/enterprise-resource-planning-q-a/accounting-entries-for-initial-stock-upload-urgent-help-needed/qaq-p/3419752 — 561 → GBB-BSA
+
+### NetSuite
+- https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_161981111273.html — Entering an Inventory Adjustment (Adjustment Account field)
+- https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_N2259648.html — Adjustment vs Worksheet overview
+- https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/bridgehead_4337970267.html — FIFO/LIFO on the worksheet (costing-history destruction)
+- https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_N2191818.html — costing methods / layer consumption
+- https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_1497451045.html — negative-inventory cost-estimate preference
+- https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_N2296970.html — Inventory Count overview
+- https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_N2297156.html — Default Inventory Count Account preference
+- https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_N2299731.html — count lifecycle, snapshot, approval
+- https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_155993309646.html — approval creates inventory adjustments
+- https://www.hotwax.co/blog/decoding-netsuite-transaction-types-impact-on-financials-and-inventory — DR/CR shape for adjustments
+- https://technologyblog.rsmus.com/technologies/netsuite/how-to-set-up-inventory-adjustment-reason-codes-in-netsuite/ — reason codes as customization
+- https://archive.netsuiteprofessionals.com/t/382050/how-to-do-inventory-adjustments-without-gl-impact — zero-cost positive adjustment trick
+
+### Fishbowl
+- https://blog.tarabyte.com/blog/how-do-inventory-adjustments-work-in-fishbowl — adjustment types → JE targets
+- https://blog.tarabyte.com/blog/oops-vs-ugh-a-guide-to-inventory-adjustments-for-fishbowl-inventory — Add vs Cycle Count vs Scrap, per-part account coding
+- https://inventorygurutarabyte.blogspot.com/2015/07/fishbowl-inventory-accounting-basics.html — part-type default + per-part mapping, costing layers
+- https://help.fishbowlinventory.com/advanced/s/article/Accounting-Journal-Entries — canonical JE table (not machine-fetchable; corroborated via TaraByte)
+
+### Epicor
+- https://www.epiusers.help/t/reason-codes-type-gl-control-code/81966 — reason-code GL controls, COS-and-WIP fallback, job scrap stays in WIP
+- https://www.epiusers.help/t/accounting-help-where-do-adj-qty-transactions-hit/38775 — ADJ-QTY posting, $0-net suppression gotcha
+- https://www.studocu.com/row/document/shah-abdul-latif-university/computer-science/kinetic-hierarchy-required/109050892 — ADJ-QTY account resolution hierarchy
+- https://community.epicorusers.org/kinetic-epicor-erp-81/controlling-the-inventory-adjustment-account-used-for-cycle-count-variances-physical-inventory-variances-cost-variances-created-during-the-mfg-stk-transaction-87738 — count-discrepancy reason routing
+- https://www.epiusers.help/t/timing-of-gl-trans-from-parttrans-capture-cos-wip/42682 — batch Capture COS/WIP creates GL entries
+- https://www.epiusers.help/t/how-often-to-capture-cos-wip-monthly-weekly-daily/70759 — capture cadence pain
+- https://www.epiusers.help/t/job-closing-detail-information/74699 — MFG-VAR purges remaining job cost at close
diff --git a/.ai/research/inventory-value-report.md b/.ai/research/inventory-value-report.md
new file mode 100644
index 0000000000..5e0bd05776
--- /dev/null
+++ b/.ai/research/inventory-value-report.md
@@ -0,0 +1,265 @@
+# Inventory Value Report Research: Best Practices Survey
+
+## Summary
+
+Surveyed how SAP (S/4HANA + Business One), NetSuite, Dynamics 365 Business Central,
+Fishbowl, and Odoo build inventory valuation reports — grouping by location and item,
+as-of-date valuation, costing-method handling, GL tie-out, and interactivity. The
+industry consensus: valuation reports are built by **replaying an immutable
+quantity/value ledger** (never a snapshot table alone), the canonical drill hierarchy
+is **two levels (summary by location or item → transaction detail)**, every vendor
+ships a **GL tie-out** view because item-subledger vs GL divergence is the #1 support
+issue, and there is a well-understood industry split between **accurate historical
+valuation (replay ledger values)** and **fast approximate valuation (historical qty ×
+current cost)** — SAP ships both and documents the difference. Carbon already has the
+raw materials: `itemLedger` (quantity), `costLedger` (value + `costPostedToGL`),
+`itemCost.unitCost`, and an existing-but-unused `get_inventory_value_by_location` RPC
+(migration `20260325031223_inventory-value-report.sql`) that no app code calls today.
+
+## Competitors Surveyed
+
+- **SAP S/4HANA** — the enterprise reference: MB52/MB5B/MB5L transaction family, Fiori F1422 apps, Material Ledger.
+- **SAP Business One** — SMB manufacturing reference: Inventory Audit Report (OINM transaction replay), Valuation Simulation report.
+- **NetSuite** — cloud mid-market reference: Inventory Valuation Summary/Detail pair, Stock Ledger.
+- **Dynamics 365 Business Central** — the cleanest ledger data model (item ledger + value entries); its Inventory Valuation report (1001) and Power BI by-Item/by-Location apps map almost 1:1 to Carbon's ledger design.
+- **Fishbowl** — SMB inventory point solution; notable for Location/Item as the exactly-two Group By options (matching this feature request verbatim) and costing-method-as-report-parameter.
+- **Odoo** — open-source reference: stock valuation layers (SVLs), "Valuation at Date", per-category costing method. Notably **cannot** value by location in core — a documented gap users complain about.
+
+## Key Consensus Patterns
+
+### 1. Two parallel ledgers: quantity and value are separate records
+- **SAP**: material documents (MSEG) carry quantity; valuation (MBEW/ACDOCA Material Ledger) carries value. Value exists only at plant level; storage-location "value" is derived qty × plant price.
+- **Business Central**: Item Ledger Entries carry quantity; Value Entries carry cost. One item ledger entry has many value entries (direct cost, revaluation, variance, adjustment).
+- **Odoo**: stock moves carry quantity; stock valuation layers carry value.
+- **Carbon equivalent**: `itemLedger` (quantity, has `locationId`/`storageUnitId`) + `costLedger` (cost, `costPostedToGL` — but **no `locationId`**). Carbon's value ledger is company-grained; per-location value must be derived as qty × unit cost. (See the Per-Location Costing addendum below — SAP is location-blind only *below* the plant; it does cost per plant.)
+- **Rationale**: cost corrections (late invoices, revaluations, variances) arrive after the physical movement; separating them keeps quantity history immutable while value history accretes.
+
+### 2. Grouping: location and item are THE two primary dimensions
+- **Fishbowl**: Inventory Valuation Summary has exactly two Group By options — **Location** (default) and **Item** — each with group subtotals.
+- **Business Central**: Power BI app ships "Inventory Valuation by Item" and "Inventory Valuation by Location" as separate pages.
+- **NetSuite**: item-grained by default; location added via report customization ("Group With Previous Column") or the Stock Ledger.
+- **SAP MB52**: hierarchical display plant → storage location → material with totals per level.
+- **Rationale**: finance asks "what's the value at each site" (balance-sheet by warehouse); operations asks "where is this item and what's it worth". Both views over the same rows.
+
+### 3. Summary → Detail is the canonical drill-down
+- **NetSuite**: Valuation Summary (one row per item: qty, value, % of total) → click through to Valuation Detail (per-transaction costing rows).
+- **SAP B1**: Inventory Audit Report rows drill to the originating document via link arrows.
+- **BC**: Inventory – G/L Reconciliation matrix drills from any total to the underlying value entries.
+- **Odoo**: valuation list grouped by product expands to the individual valuation layers; reference links open the stock move.
+- **Rationale**: the summary answers "how much"; the detail answers "why" — troubleshooting bad costs requires seeing the transactions that produced the number.
+
+### 4. As-of-date valuation: replay the ledger, with a documented fast/accurate split
+- **BC** (gold standard): sum `Cost Amount (Actual)` value entries with a posting-date filter — exact and reproducible because value entries are immutable, dated facts; corrections are new entries, never updates.
+- **SAP MB5B**: replays material documents backwards from current stock; period-end snapshot tables (MBEWH) accelerate it. Fiori apps instead use **historical qty × current price** for speed, and SAP documents that both semantics exist.
+- **NetSuite**: can run for a past date but replays *current* transaction state — documented limitation that historical average cost is not reproduced.
+- **Odoo**: "Valuation at Date" filters SVLs by date (with quirks: remaining-qty columns stay current).
+- **Fishbowl**: as-of date filters costing layers but "cost values are based on today's costs" in the base report.
+- **Rationale**: only ledger replay is audit-grade; qty-at-date × current-cost is the accepted cheap approximation. Vendors that conflate the two without documenting it generate support tickets.
+
+### 5. GL tie-out is a first-class feature, not an afterthought
+- **SAP MB5L**: three columns — MM value, GL stock-account balance, variance (should be 0).
+- **BC**: report shows `Cost Posted to G/L` next to `Ending Value` ("should be equal; if not, run Post Inventory Cost to G/L"); a dedicated Inventory – G/L Reconciliation matrix explains discrepancies.
+- **NetSuite**: documented reconciliation procedure (GL detail filtered to Item = empty finds item-less JEs).
+- **Fishbowl**: valuation report explicitly framed as "THE report to compare to your QuickBooks balance sheet".
+- **Rationale**: the universal failure mode is transactions hitting the inventory GL account without touching the item subledger (manual JEs), or subledger movements not yet posted. Carbon's `costLedger.costPostedToGL` column exists for exactly this comparison.
+
+### 6. Costing method is a per-item posting-time property; the report displays, it doesn't choose
+- **NetSuite/BC/SAP**: method lives on the item (or material master / product category in Odoo); one report freely mixes FIFO/Average/Standard items; the displayed unit value ≈ value ÷ qty regardless of method.
+- **Fishbowl** is the outlier: costing method is a *report parameter* (render the same stock under any method) — a what-if tool, like SAP B1's Valuation Simulation report.
+- **Standard-cost items**: variances post to variance GL accounts and are excluded from inventory value everywhere.
+- **Carbon equivalent**: `itemCost.costingMethod` per item; `itemCost.unitCost` is the current cost used for valuation; `calculateCOGS` walks `costLedger` for FIFO/LIFO at shipment.
+
+### 7. Standard column set
+Across all five vendors the summary columns converge on: **item (id + description), quantity on hand, unit of measure, unit cost, total value**, plus optionally **% of total value** (NetSuite) and group subtotals. Period-movement variants add **beginning value + increases − decreases = ending value** (BC 1001, NetSuite Stock Ledger).
+
+## Answers to Research Questions
+
+1. **What grouping dimensions, and what drill hierarchy?** Location and item are the two primary groupings (Fishbowl offers exactly these two; BC ships one Power BI page per dimension). Secondary dimensions: item category/posting group (BC subtotals by Inventory Posting Group; SAP by valuation class → GL account), lot/serial (Odoo opt-in). Hierarchy: group summary → item rows → transaction detail.
+2. **How is as-of-date valuation computed?** Ledger replay with posting-date filter (BC value entries, SAP MB5B, Odoo SVLs) is the accurate method; historical qty × current cost (SAP Fiori, Fishbowl) is the documented fast approximation. Snapshots (SAP MBEWH, Carbon's `itemLedgerSnapshot` materialized view) are an acceleration, not the source of truth.
+3. **How do costing methods shape the report?** Method is a per-item property; the report shows value ÷ qty as unit cost for all methods. Standard-cost items show frozen standard; variances live in GL variance accounts, not inventory value. Only Fishbowl/SAP B1 offer method-as-parameter simulation reports.
+4. **How does the report tie out to GL?** A dedicated comparison of subledger value vs GL inventory-account balance (SAP MB5L's Materials/Stock Account/Variance columns; BC's Cost Posted to G/L column + reconciliation matrix). Documented discrepancy causes everywhere: manual JEs to inventory accounts, unposted subledger costs, date/period mismatches.
+5. **What interactivity is standard?** Filters (location, item, category, date), group-by toggle, expand/collapse groups, drill-through to source transactions/documents, CSV/Excel export, saved customization. Modern implementations (Fiori, Power BI, Odoo pivot) add free pivoting and charts.
+6. **Terminology and columns?** "Inventory Valuation" is the universal report name (NetSuite/BC/Fishbowl all use it; SAP B1 says "Inventory Audit"). Columns: item, description, qty on hand, UoM, unit cost, total value, % of total; movement variants add beginning/increase/decrease/ending.
+
+## Competitor-Specific Details
+
+### SAP S/4HANA
+- MB52 (stock on hand w/ value), MB5B (stocks for posting date — replay), MB5L (GL tie-out, period-granular only), CKM3 (Material Ledger price analysis). Fiori F1422 "Material Inventory Values – Balance Summary".
+- Value only exists at valuation-area (plant) level; storage-location value is qty × plant price — precedent for Carbon deriving storage-unit value the same way.
+- Ships both historical-accurate (MB5B) and current-price-fast (Fiori) semantics, documented.
+
+### SAP Business One
+- Inventory Audit Report replays OINM rows: posting date, doc, item, warehouse, receipt/issue qty, cost, **cumulative qty, cumulative value** — running-balance presentation. Explicitly "does not recalculate costs; displays what was posted."
+- Group by Warehouse is a checkbox; warned against when item cost is managed at company level (Carbon's cost is company-level too — same caveat applies).
+- Valuation Simulation report = what-if under any method for a key date.
+
+### NetSuite
+- Valuation Summary columns: Item, Description, Value ($), % of Total Value, Qty On Hand, Unit Value (landed cost included). Click qty → Detail report (per-transaction costing).
+- Past-date runs replay current transaction state; average cost not recalculated as-of — documented limitation. Backdated transactions trigger forward cost recalculation (hourly engine).
+- Valuation report runs on transaction **date**; Balance Sheet on **period** — documented source of tie-out mismatch.
+
+### Dynamics 365 Business Central
+- Value-entry model is the cleanest precedent for Carbon: quantity ledger + value ledger, `Cost Amount (Actual)` vs `Cost Amount (Expected)` (received-not-invoiced), summed by posting date → exact retroactive valuation.
+- Report 1001 columns: beginning qty/value + increases − decreases = ending qty/value, plus **Cost Posted to G/L** ("should equal Ending Value").
+- "Adjust Cost – Item Entries" batch job must run before the report is trusted — cost corrections are forwarded to consumers as new adjustment value entries; closed periods never change (adjustments land in the next open period).
+- NA-localized report 10139 adds "Breakdown by Location" / "Breakdown by Variants" and "As of Date".
+
+### Fishbowl
+- Inventory Valuation Summary: Group By = **Location | Item** (exactly the two axes requested for Carbon); Location Total / Item Total subtotal bands; "Show Location Details" toggles child-location rollup.
+- Costing method is a report parameter — same stock rendered under Average/FIFO/LIFO/Standard.
+- Columns: Item, Qty, UOM, Unit Cost, Asset Value (= qty × unit cost).
+
+### Odoo
+- Stock valuation layers (immutable value records per validated move); list/pivot/graph views; "Valuation at Date" popup.
+- **No location dimension on valuation in core** — the most-complained-about gap; community modules fill it. Carbon can beat this out of the box because `itemLedger` is location-grained.
+- Costing method per product category; changing it posts revaluation layers (negative + positive pair).
+
+## Recommended Approach for Carbon
+
+1. **Name it "Inventory Valuation"** and put it under the Inventory module's reporting area — the term is universal across NetSuite, BC, and Fishbowl.
+2. **Follow Fishbowl's exactly-two-groupings model for v1**: a single report with a Group By toggle — **by Location → item rows** (default) and **by Item → location rows** — each with group subtotals and a grand total. This matches the user's ask verbatim and is the industry-minimal viable shape.
+3. **Current-value computation: qty × `itemCost.unitCost`** (the SAP-Fiori/Fishbowl semantics), building on the existing `get_inventory_value_by_location` RPC (`20260325031223_inventory-value-report.sql` — currently dead code, no app callers) but fixing its known gaps: make it status-aware (exclude Rejected tracked entities, matching `get_inventory_quantities`), and use the `itemLedgerSnapshot` + delta pattern from `20260713235406` for performance. Carbon's cost is company-level (like SAP B1), so per-location value is qty × company unit cost — same documented caveat.
+4. **Standard column set**: item readableId, name, qty on hand, UoM, unit cost, total value, % of total (NetSuite), with subtotal rows per group and a grand total.
+5. **Defer as-of-date valuation to a follow-up** unless required now: audit-grade as-of requires BC-style replay of `costLedger` by `postingDate` (Carbon's costLedger lacks `locationId`, so historical *by-location* value would need qty-at-date × current-cost approximation — the documented SAP Fiori semantics). If shipped, label the semantics explicitly like SAP does.
+6. **Interactivity v1**: location filter, item-group/search filter, group-by toggle, expand/collapse groups, CSV export (Carbon has `.ai/rules/table-csv-export.md` conventions), drill-through from an item row to its item ledger / inventory detail page.
+7. **Plan for (not necessarily build now) a GL tie-out panel**: `SUM(costLedger.costPostedToGL)` vs the inventory GL account balance, following the AR/AP workbench precedent (`receivables.tsx` tie-out panel) — every surveyed vendor treats this as the companion feature, and Carbon's AR/AP aging reports already established the workbench UI pattern.
+8. **UI precedent**: clone the AR/AP workbench pattern (`apps/erp/app/routes/x+/invoicing+/receivables.tsx` — loader with `requirePermissions` + service functions + workbench component), not a new design from concepts.
+
+## Addendum: Per-Location Costing (2026-07-14 follow-up)
+
+Follow-up question raised during the feature run: *should Carbon add `locationId` to
+`costLedger`?* Answered from competitor practice plus a read of Carbon's actual
+posting code.
+
+### What competitors do
+
+- **SAP S/4HANA**: costs **per plant**. Valuation is keyed to the valuation area
+ (normally the plant); the material master carries a separate moving-average or
+ standard price per material per plant (MBEW). Below the plant, storage locations
+ carry quantity only — their "value" is derived qty × plant price. Mapping: SAP
+ plant ≈ Carbon `location`; SAP storage location ≈ Carbon `storageUnit`. So at
+ Carbon's `location` grain, SAP *is* location-costed.
+- **NetSuite**: costs **per location** with Multi-Location Inventory — MLI "tracks
+ purchasing costs, stock levels, and valuation for each item in each location";
+ average cost is a separate weighted average per location; cost-layer behavior
+ depends on a preference for cost held per item vs per location. **Group Average**
+ exists to opt a set of locations back into one shared average.
+- **SAP Business One**: configurable — item cost at company level *or* per warehouse.
+- **Business Central**: average cost calculated "per item" or "per item + location +
+ variant"; value entries carry a Location Code.
+- **Odoo**: the outlier — no location dimension on valuation in core.
+- **Carbon today**: company-level (`itemCost.unitCost` per item per company) — like
+ SAP B1's company-level mode and Fishbowl.
+
+### What Carbon's costing engine actually does (code-grounded)
+
+- `costLedger` rows are **FIFO/LIFO cost layers**, not just journal-style entries:
+ they carry `remainingQuantity` (drawn down on consumption), `nominalCost`, and
+ `appliesToCostLedgerId` (variance adjustment children created by purchase
+ invoices). Writers: `post-receipt`, `post-shipment`, `post-purchase-invoice`,
+ `post-sales-invoice`, `issue`, `update-purchased-prices`,
+ `shared/purchase-cost-adjustment.ts`.
+- **Layer consumption is company-wide.** `calculateCOGS`
+ (`packages/database/supabase/functions/shared/calculate-cogs.ts:65`) selects
+ layers by item + company with **no location filter** — a shipment from Location B
+ can consume a layer created by a receipt into Location A.
+- **Transfers move quantity, not value.** `post-stock-transfer` writes only
+ `itemLedger` rows; zero `costLedger` entries.
+- **Revaluations are company-scoped.** `update-purchased-prices` and invoice
+ variance adjustments reprice layers with no location allocation.
+
+### Decision (recorded for the spec)
+
+**Do not add `locationId` to `costLedger` for this feature.** Stamping the column
+without redesigning the engine would produce per-location sums that never balance
+(cross-location layer consumption → phantom value at the receiving location,
+negative at the shipping one; transfers would silently strand value at the source).
+The "informational-only" middle ground was also rejected: partially-populated data
+(old rows null, transfers absent) invites people to sum and trust it.
+
+- **v1 report semantics**: per-location value = on-hand qty by location (from
+ `itemLedger`, which is location-grained and exact) × company-level
+ `itemCost.unitCost`. Same semantics as SAP below-plant, SAP B1 company-level mode,
+ and Fishbowl. Historical company-level value remains exact via
+ `costLedger.postingDate` replay.
+- **Deferred, industry-validated follow-up**: true per-location costing as its own
+ spec — per-item-per-location cost master, location-scoped layer consumption in
+ `calculateCOGS`, paired cost entries on transfers, and a revaluation allocation
+ policy (`costLedger.locationId` falls out of that design naturally). The report's
+ data contract should keep a per-row `unitCost` so a location-specific cost can
+ slot in later without reshaping the UI.
+
+### Addendum sources
+
+- https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_N2303574.html (NetSuite Multi-Location Inventory)
+- https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_N2194541.html (NetSuite LIFO/FIFO and Advanced Receiving)
+- https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_N2191818.html (NetSuite Costing Methods)
+- https://help.sap.com/docs/SAP_ERP/56f7319a9048445eb86221af73cab72b/6a5eb6531de6b64ce10000000a174cb4.html (SAP price control / valuation area)
+- https://learning.sap.com/courses/managing-logistics-in-sap-business-one/exploring-the-inventory-valuation-methods-in-sap-business-one (SAP B1 per-warehouse item cost)
+- https://learn.microsoft.com/en-us/dynamics365/business-central/design-details-average-cost (BC average cost per item/location/variant)
+
+## Sources
+
+### SAP
+- https://help.sap.com/docs/SAP_S4HANA_ON-PREMISE/5e23dc8fe9be4fd496f8ab556667ea05/6c1f050e52914a3bb46717ef4f807e86.html
+- https://help.sap.com/docs/SAP_S4HANA_ON-PREMISE/91b21005dded4984bcccf4a69ae1300c/59bf7e548af58e4ce10000000a4450e5.html
+- https://help.sap.com/docs/SAP_ERP/56f7319a9048445eb86221af73cab72b/6a5eb6531de6b64ce10000000a174cb4.html
+- https://help.sap.com/docs/SAP_BUSINESS_ONE/68a2e87fb29941b5bf959a184d9c6727/4522e91373c80108e10000000a114a6b.html
+- https://help.sap.com/docs/SAP_BUSINESS_ONE/87e1767ca7584b8f8d60775347637b07/f241a76a746f497699eed703763a9f0b.html
+- https://fioriappslibrary.hana.ondemand.com/sap/fix/externalViewer/?appId=F1422
+- https://userapps.support.sap.com/sap/support/knowledge/en/3211374
+- https://community.sap.com/t5/enterprise-resource-planning-q-a/mb5b-valuated-stock-report-by-sloc-material-storage-location-will-be-reset/qaq-p/9269164
+- https://community.sap.com/t5/enterprise-resource-planning-q-a/mb5l-transaction-list-of-stock-values-balances/qaq-p/2688453
+- https://community.sap.com/t5/application-development-and-automation-blog-posts/how-to-get-stock-on-posting-date-manually-and-programmatically/ba-p/13580392
+- https://community.sap.com/t5/enterprise-resource-planning-blog-posts-by-sap/working-with-inventory-audit-report/ba-p/13369410
+- https://community.sap.com/t5/technology-blog-posts-by-members/a-comprehensive-guide-to-sap-s-4hana-material-ledger-amp-integrated/ba-p/14224569
+- https://blogs.sap.com/2012/11/30/getting-opening-and-closing-quantities-of-stock-with-accuracy-of-mb5b/
+- https://www.erpgreat.com/materials/variances-between-material-and-account-of-stock-when-you-use-mb5l.htm
+- https://www.profzilla.com/articles/post/sap-t-code-mb5l-closing-inventory-report-in-value-quantity-terms
+- https://softat.co.in/mb52-tcode-in-sap/
+- https://blog.vision33.com/how-to-leverage-the-inventory-audit-report-in-sap-business-one
+- https://www.sap-business-one-tips.com/en/inventory-audit-report-not-match-with-gl-account-balance/
+- https://sap-b1-blog.com/en/glossary/inventory-valuation-simulation-report-sap-business-one/
+- https://learning.sap.com/courses/managing-logistics-in-sap-business-one/exploring-the-inventory-valuation-methods-in-sap-business-one
+
+### NetSuite
+- https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_N2358933.html (Inventory Valuation Summary)
+- https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_N2359248.html (Inventory Valuation Detail)
+- https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_N2191818.html (Costing Methods)
+- 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_N720282.html (Report Footer Options)
+- https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_4521145431.html (Stock Ledger)
+- https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_N1456591.html (Period Close inventory tasks)
+- http://www.netsuiterp.com/2018/09/reconcile-inventory-valuation-report.html
+- https://www.houseblend.io/articles/netsuite-inventory-costing-methods
+- https://www.anchorgroup.tech/blog/netsuite-average-cost-method-inventory-valuation
+- https://technologyblog.rsmus.com/technologies/netsuite/netsuite-reporting-dates-or-periods-part-1/
+
+### Dynamics 365 Business Central
+- https://learn.microsoft.com/en-us/dynamics365/business-central/reports/report-1001
+- https://learn.microsoft.com/en-us/dynamics365/business-central/design-details-inventory-valuation
+- https://learn.microsoft.com/en-us/dynamics365/business-central/design-details-expected-cost-posting
+- https://learn.microsoft.com/en-us/dynamics365/business-central/design-details-reconciliation-with-the-general-ledger
+- https://learn.microsoft.com/en-us/dynamics365/business-central/design-details-cost-adjustment
+- https://learn.microsoft.com/en-us/dynamics365/business-central/design-details-costing-methods
+- https://learn.microsoft.com/en-us/dynamics365/business-central/finance-how-to-post-inventory-costs-to-the-general-ledger
+- https://learn.microsoft.com/en-us/dynamics365/business-central/inventory-valuation-powerbi-app
+- https://learn.microsoft.com/en-us/dynamics365/business-central/inventory-valuation-powerbi-inventory-valuation-by-item
+- https://learn.microsoft.com/en-us/dynamics365/business-central/inventory-valuation-powerbi-inventory-valuation-by-location
+- https://learn.microsoft.com/en-us/dynamics365/business-central/inventory-valuation-powerbi-kpis
+- https://github.com/StefanMaron/MSDyn365BC.Code.History/blob/d95f870441365db61f6456ed36b2609c3f1c0fad/BaseApp/Source/Base%20Application/Inventory/Reports/InventoryValuation.Report.al
+- https://usedynamics.com/business-central/finance/reconcile-inventory/
+
+### Fishbowl
+- https://help.fishbowlinventory.com/drive/s/article/Drive-Inventory-Valuation-Summary-Report
+- https://help.fishbowlinventory.com/drive/s/article/Drive-Costing-Methods
+- https://tarabyte.com/fishbowl-inventory/controllers-toolbox-the-valuation-reports/
+- https://fishbowlhelp.com/files/Reconciling-Discrepancies.pdf
+
+### Odoo
+- https://www.odoo.com/documentation/18.0/applications/inventory_and_mrp/inventory/product_management/inventory_valuation/using_inventory_valuation.html
+- https://www.odoo.com/documentation/18.0/applications/inventory_and_mrp/inventory/product_management/inventory_valuation/inventory_valuation_config.html
+- https://www.odoo.com/documentation/18.0/applications/inventory_and_mrp/inventory/warehouses_storage/reporting/aging.html
+- https://www.odoo.com/documentation/19.0/applications/inventory_and_mrp/inventory/inventory_valuation/cheat_sheet.html
+- https://www.odoo.com/documentation/19.0/applications/inventory_and_mrp/inventory/warehouses_storage/reporting/locations.html
+- https://www.odoo.com/forum/help-1/odoo-16-location-wise-report-at-particular-inventory-date-261818
diff --git a/.ai/rules/i18n-lingui-system.md b/.ai/rules/i18n-lingui-system.md
index e20e1ce36e..1db5d2226e 100644
--- a/.ai/rules/i18n-lingui-system.md
+++ b/.ai/rules/i18n-lingui-system.md
@@ -16,8 +16,8 @@ runs via `@lingui/vite-plugin` (`lingui()` plugin in `apps/erp/vite.config.ts` a
## Config & catalogs
- Root `lingui.config.js`: `sourceLocale: "en"`, format `po`, `fallbackLocales.default: "en"`.
-- Locales: `en, es, de, it, ja, zh, fr, pl, pt, ru, hi` (11). The runtime list in
- `packages/locale/src/config.ts` (`supportedLanguages`) matches this set.
+- Locales: `en, es, de, it, ja, zh, fr, pl, pt, ru, hi, tr, ko` (13). The runtime
+ list in `packages/locale/src/config.ts` (`supportedLanguages`) matches this set.
- Two catalogs, each extracted from app + shared package sources:
- `packages/locale/locales/{locale}/erp` ← `apps/erp/app`, `packages/react/src`, `packages/form/src`, `packages/printing/src/ui`
- `packages/locale/locales/{locale}/mes` ← `apps/mes/app` + the same three shared dirs
diff --git a/.ai/rules/inventory-system.md b/.ai/rules/inventory-system.md
index 65dd836a7b..e64ae6025a 100644
--- a/.ai/rules/inventory-system.md
+++ b/.ai/rules/inventory-system.md
@@ -25,8 +25,17 @@ Key service functions (verified):
- `getInventoryItems` / `getInventoryItemsCount` — call the `get_inventory_quantities` RPC
(args `{ location_id, company_id }`, `count: "exact"`); supports search + generic filters.
- `getItemLedgerPage` — paginated item-ledger history for an item at a location.
-- `insertManualInventoryAdjustment` — positive/negative/set-quantity adjustments, tracked-entity
- storage-unit transfers, expiry override, batch/serial assignment.
+- `insertManualInventoryAdjustment` — thin wrapper over the **`post-inventory-adjustment`
+ edge function** (MES has a matching wrapper in `apps/mes/app/services/inventory.service.ts`).
+ The edge function owns positive/negative/set-quantity resolution, tracked-entity storage-unit
+ transfers, expiry override, batch/serial assignment — and, in one Kysely transaction, maintains
+ `costLedger` layers (consume via `calculateCOGS` on decreases, new layer at current cost on
+ increases) and posts a journal (Dr/Cr `resolveInventoryAccount` vs
+ `accountDefault.inventoryAdjustmentVarianceAccount`) when `companySettings.accountingEnabled`.
+ `post-inventory-count` books its variances through the same shared core
+ (`functions/shared/post-adjustment.ts`). Storage-unit transfers post no GL. The valuation
+ workbench tie-out offers a **Reconcile** action (`createInventoryReconciliationJournal`) that
+ drafts an adjusting journal for any residual pre-feature variance.
- Storage units: `getStorageUnit(s)`, `getStorageUnitRoots`, `getStorageUnitChildren`,
`getStorageUnitTree`, `getStorageUnitsTreeForLocation`, `getDefaultStorageUnitForJob`,
`getDefaultStorageUnitOrStorageUnitWithHighestQuantity` (these are the picking/job defaults).
diff --git a/.ai/runs/2026-07-14-inventory-value-report.md b/.ai/runs/2026-07-14-inventory-value-report.md
new file mode 100644
index 0000000000..20a229dc40
--- /dev/null
+++ b/.ai/runs/2026-07-14-inventory-value-report.md
@@ -0,0 +1,26 @@
+# Feature run: Interactive inventory value report (by location, by item)
+
+- Date: 2026-07-14
+- Mode: approval-per-phase
+- Request: "we need to be able to create an interactive report for inventory that allows us to look at the value by location, and by item. let's use the /feature skill"
+- Phase plan: research [run — ERP-domain logic (inventory valuation), force-included] · spec [run — new report surface, crosses inventory module + UI] · plan [run] · execute [run] · test [skip — user opted out at phase selection] · self-review [skip — user opted out at phase selection]
+
+## Decisions
+<!-- approval mode — gates are human; none auto-resolved -->
+- Grill Q1 — valuation basis (Brad, 2026-07-14): **method-faithful carrying cost.** FIFO/LIFO = remaining layer value incl. `appliesToCostLedgerId` children (fallback unitCost when no layers); Average = unitCost; Standard = standardCost. Per-location value = locationQty × company-level effective unit cost. Ties to subledger; matches completeness-spec carrying math.
+- Grill Q2 — status scope (Brad, 2026-07-14): **value ALL physical on-hand (incl. On Hold + Rejected), with On Hold / Rejected breakdown columns.** SAP MB52 stock-bucket precedent; rejected stock stays an asset until written off, so totals tie to the books.
+- Grill Q3 — as-of-date (Brad, 2026-07-14): **IN for v1, approximate + labeled** (overrode the defer recommendation). Historical qty exact via itemLedger.postingDate ≤ asOfDate; cost = today's effective unit cost; UI carries a permanent semantics label (SAP Fiori precedent). Caveats to label: snapshot matview unusable for dated queries (raw ledger aggregation); status breakdown reflects current tracked-entity statuses even at past dates.
+- Grill Q4 — GL tie-out (Brad, 2026-07-14): **IN for v1** (overrode the defer recommendation). Per-account tie-out (MB5L shape): rawMaterialsAccount + finishedGoodsAccount (resolveInventoryAccount, `20260713190909` split) — subledger value vs GL balance per account + total; accountingEnabled companies only; WIP excluded; known-noise caveat (unposted cycle-count adjustments) surfaced in the panel copy until completeness-spec §4 lands.
+- Grill Q5 — old RPC (Brad, 2026-07-14): **keep `get_inventory_value_by_location` (deprecated)**, don't drop. New `get_inventory_valuation` ships alongside; zero API-breakage risk accepted over surface cleanliness.
+- Grill Q6 — permissions (Brad, 2026-07-14): **accounting_view gates the whole report** (strictest option). Lives in Inventory nav but entry renders only for users with accounting view; costs never reach ops-only roles.
+- costLedger.locationId: NOT added for this feature (user question, resolved 2026-07-14). Layer consumption in calculateCOGS is company-wide, transfers write no cost entries, revaluations are company-scoped — a stamped column would never balance per location. v1 = per-location qty × company-level unitCost; true per-location costing (industry-validated: SAP per-plant, NetSuite MLI) deferred to its own spec. Details in research addendum.
+
+## Phase log
+- Plan: written — `.ai/plans/2026-07-14-inventory-value-report.md` (7 tasks; awaiting approval gate). Revised 2026-07-14 per Brad: types ARE regenerated + committed normally (`pnpm db:migrate`); the "cloud-generated types, use casts" memory was wrong and has been deleted/corrected; services use fully typed rpc calls + Awaited<ReturnType> row types.
+- Spec: done — `.ai/specs/2026-07-14-inventory-value-report.md`. All 6 grill questions + costLedger.locationId decision resolved by Brad before writing; spec written with resolutions baked in. Gate satisfied: zero unresolved open questions.
+- Research: done — `.ai/research/inventory-value-report.md`. Surveyed SAP (S/4HANA + B1), NetSuite, Dynamics BC, Fishbowl, Odoo + explored Carbon internals. Key internal finding: `get_inventory_value_by_location` RPC exists (migration 20260325031223) but has zero app callers — dead code this feature will supersede.
+
+- Execute: done — 7/7 tasks, 6 commits on feat/inventory-report. RPC math proven by rolled-back psql validation (7/7 asserts, incl. one real bug caught: account is companyGroup-scoped). 156 translations filled. Browser verification was deselected by Brad at phase selection — verify manually: open /x/inventory/valuation as an accounting-view user on the running stack; check group toggle, as-of label, tie-out popover, CSV download, and that a non-accounting user sees no nav entry + 403.
+
+## Outcome
+- Implementation complete on feat/inventory-report (not pushed — branch upstream is origin/main, pushing would target main). PR creation left to Brad.
diff --git a/.ai/specs/2026-07-04-inventory-valuation-completeness.md b/.ai/specs/2026-07-04-inventory-valuation-completeness.md
index 5936025b47..30205ec53e 100644
--- a/.ai/specs/2026-07-04-inventory-valuation-completeness.md
+++ b/.ai/specs/2026-07-04-inventory-valuation-completeness.md
@@ -104,6 +104,12 @@ Lines are proposed only where `NRV < carrying unit cost` (item level — the ASC
### 4. Quantity-adjustment GL posting
+> **Superseded/expanded 2026-07-14** by
+> `.ai/specs/2026-07-14-inventory-adjustment-gl-posting.md`: posting is unified
+> into a `post-inventory-adjustment` edge function (Kysely transaction) used by
+> ERP + MES + `post-inventory-count` — not a service-level leg as sketched
+> below. Accounts and valuation rules below still hold.
+
`insertManualInventoryAdjustment` gains a posting leg (service-level, so the MCP path is covered too, per the document-approvals spec's lesson that route-level gates are bypassable):
- **Negative adjustment**: consume layers via `calculateCOGS` → `Dr inventoryAdjustmentVarianceAccount (5310) / Cr inventoryAccount` at consumed-layer cost; costLedger rows decrement `remainingQuantity` as usual.
@@ -366,4 +372,9 @@ No new blocking questions surfaced while writing; judgment calls (direct write-d
## Changelog
+- 2026-07-14: §4 (quantity-adjustment GL) superseded/expanded by
+ `.ai/specs/2026-07-14-inventory-adjustment-gl-posting.md` — unified
+ `post-inventory-adjustment` edge function (Brad's decision), count/Rectify
+ posting, and a tie-out Reconcile action (draft adjusting journal); accounts
+ (5310) and valuation rules unchanged.
- 2026-07-04: Created — readiness finding GAP-3, tracking issue crbnos/carbon#1040. Grounded in code exploration (`itemCost`/cost layers/`calculate-cogs`, `post-receipt`/`post-purchase-invoice`/`post-production-event`/`close-job` posting paths, `20260315000000` chart reset) and `.ai/research/public-company-compliance.md` (ASC 330 / IAS 2). NRV auto-proposal + per-book reversal split resolved by Brad pre-writing.
diff --git a/.ai/specs/2026-07-14-inventory-adjustment-gl-posting.md b/.ai/specs/2026-07-14-inventory-adjustment-gl-posting.md
new file mode 100644
index 0000000000..841bfaa56d
--- /dev/null
+++ b/.ai/specs/2026-07-14-inventory-adjustment-gl-posting.md
@@ -0,0 +1,393 @@
+# Inventory Adjustment GL Posting — Unified Posting Path for Manual Adjustments, Counts, and Shop Floor
+
+> Status: draft
+> Author: Claude (with Brad Barbin)
+> Date: 2026-07-14
+> Research: `.ai/research/inventory-adjustment-gl-posting.md` (SAP / NetSuite / Fishbowl / Epicor survey)
+> Parent: `.ai/specs/2026-07-04-inventory-valuation-completeness.md` §4 ("Quantity-adjustment GL posting", PR 4) — this spec expands and supersedes that sketch
+> Companion: `.ai/specs/2026-07-14-inventory-value-report.md` (the tie-out panel whose known-noise caveat this feature removes)
+
+## TLDR
+
+Manual quantity adjustments write `itemLedger` rows only — no `costLedger`, no
+journal — so every cycle count silently breaks the inventory-account-to-subledger
+tie the valuation workbench now surfaces. This spec unifies all three adjustment
+writers (ERP quantities/item-master, MES shop floor, `post-inventory-count`)
+behind a new **`post-inventory-adjustment` edge function** running one Kysely
+transaction that books the item ledger, maintains cost layers (negative
+adjustments consume via `calculateCOGS`, positive adjustments create a layer at
+current cost), and posts a balanced journal — `Dr/Cr` inventory
+(`resolveInventoryAccount`: Raw Materials / Finished Goods) against
+`accountDefault.inventoryAdjustmentVarianceAccount` (5310, seeded, zero writers
+today). The ERP and MES service functions become thin wrappers with unchanged
+signatures; `post-inventory-count` reuses the same shared posting core so count
+variances and rectify corrections post identically. Storage-unit transfers stay
+GL-free (not valuation events). For history, a **Reconcile action** on the
+valuation tie-out panel generates a pre-populated **draft adjusting journal**
+for the residual variance that an accountant reviews and posts — no automated
+backfill. Design follows the SAP/NetSuite immediate-posting consensus (research
+§1) and Carbon's own `post-receipt`/`post-shipment` pattern.
+
+## Problem Statement
+
+Verified current state (paths from repo root):
+
+1. **Three independent adjustment writers, all quantity-only:**
+ - ERP `insertManualInventoryAdjustment`
+ (`apps/erp/app/modules/inventory/inventory.service.ts:1442`) — handles
+ Positive/Negative/Set Quantity, storage-unit transfers, tracked-entity
+ readableId/expiry, serial/batch resolution. Sequential supabase-client
+ writes, **no transaction**. Called from
+ `routes/x+/inventory+/quantities+/$itemId.adjustment.tsx`.
+ - MES `insertManualInventoryAdjustment`
+ (`apps/mes/app/services/inventory.service.ts:439`) — a separate, simpler
+ copy (sign-normalize + one insert). Called from `routes/x+/adjustment.tsx`.
+ - `post-inventory-count` edge function
+ (`packages/database/supabase/functions/post-inventory-count/index.ts`) —
+ posts count variances and rectify corrections as `Positive/Negative Adjmt.`
+ ledger rows in a Kysely transaction, explicitly commented *"item ledger
+ only … no GL journal lines"* (line 44).
+2. **No journal is ever written.** `inventoryAdjustmentVarianceAccount` (5310)
+ was seeded NOT NULL by the chart reset (`20260315000000`) and has **zero
+ writers**. The tie-out panel (`get_inventory_tie_out`,
+ `20260715021050_inventory-valuation-rpc.sql`) carries the permanent caveat
+ *"Manual quantity adjustments don't post to the GL yet…"*
+ (`InventoryValuationWorkbench.tsx`).
+3. **No cost-layer maintenance either.** Negative adjustments do not consume
+ FIFO/LIFO layers and positive adjustments do not create them — so after a
+ negative adjustment, open layers exceed physical stock: the valuation RPC's
+ effective unit cost is computed from layers that already left the building,
+ and later shipments relieve COGS from phantom layers.
+4. Every prerequisite already exists: `appliesToCostLedgerId` + child-aware
+ `calculateCOGS` (`20260710033458`, completeness PR 1),
+ `resolveInventoryAccount` (`shared/get-posting-group.ts:18`),
+ `getCurrentAccountingPeriod` + the `FOR SHARE` period-close posting guard
+ (`20260713235930`), and `journalEntrySourceType` already contains
+ `'Inventory Adjustment'` (`20260402000000`).
+
+## Resolved Questions (answered before writing, 2026-07-14)
+
+- [x] **Where does posting live?** — *(Brad)* **Unify inventory adjustments into
+ an edge function using a Kysely transaction, used by both ERP and MES.**
+ Supersedes the parent spec's service-level sketch, which predated
+ `post-inventory-count` and would have left three non-atomic implementations.
+- [x] **User-entered cost on positive adjustments?** — *(Brad)* **No cost input
+ in v1.** Positive adjustments always post at the item's current cost; the
+ future revaluation document (parent spec §2) is the price-correction tool.
+ Negative adjustments never take a cost (SAP/NetSuite consensus, research §2).
+- [x] **Historical unposted adjustments?** — *(Brad)* **Reconcile action in the
+ valuation workbench** (initially "true-up"; renamed per Brad, 2026-07-14 —
+ "Reconcile" is the widely understood verb; the journal it drafts is an
+ adjusting entry). A button on the tie-out panel generates a **draft** manual
+ journal for the residual per-account variance; a human reviews and posts it.
+ No automated backfill migration.
+
+Settled by codebase precedent / parent spec (recorded here, not re-asked):
+offset account is **5310 by id** (parent decision 8 + "never resolve control
+accounts by number" lesson); inventory side via **`resolveInventoryAccount`**;
+storage-unit transfers are **not valuation events** (no GL, no cost layers —
+layers are company-scoped, `costLedger` has no `locationId`); **no void path**
+for adjustments — corrections are opposite adjustments (SAP MI07 precedent;
+count Rectify already models this via `correctionOfItemLedgerId`); **reason
+codes deferred** (research §Recommended 7; flat defaults per the
+no-matrix-config lesson); **postingDate = current date** into the current open
+accounting period.
+
+## Proposed Solution
+
+### 1. New edge function: `post-inventory-adjustment`
+
+`packages/database/supabase/functions/post-inventory-adjustment/index.ts`,
+registered in `config.toml` (`verify_jwt = true`), authored per
+`.ai/rules/workflow-edge-function.md`:
+
+- **Payload** (zod): the current `inventoryAdjustmentValidator` contract —
+ `adjustmentType` (`Positive Adjmt.` | `Negative Adjmt.` | `Set Quantity`),
+ `itemId`, `locationId`, `storageUnitId`, `trackedEntityId?`, `quantity`,
+ `readableId?`, `originalStorageUnitId?`, `expirationDate?`, `comment?` — plus
+ `companyId`, `userId`, and optional `documentType`/`documentId`/
+ `correctionOfItemLedgerId` (used by the count path).
+- **Auth**: `requirePermissions(req, companyId, userId, { update: "inventory" })`.
+- **Body**, one `db.transaction()`:
+ 1. **Resolve intent** — the logic currently in the ERP service moves here
+ verbatim: `Set Quantity` → signed delta (no-op when unchanged);
+ storage-unit-transfer detection (negative+positive pair); serial/batch
+ stock-target resolution; tracked-entity quantity/status writes and
+ readableId/expiry handling (expiry override keeps routing through the
+ `updateTrackedEntityExpiry` semantics so `attributes.expiryOverrides`
+ traceability is preserved).
+ 2. **Item ledger** — insert the same row shapes as today (entry types,
+ comment, tracked-entity linkage, `correctionOfItemLedgerId` passthrough).
+ 3. **Cost layers** (always, even when accounting is disabled — the
+ `post-receipt` precedent):
+ - *Negative*: `calculateCOGS(trx, { itemId, quantity, companyId })` —
+ consumes FIFO/LIFO layers + adjustment children, decrements
+ `remainingQuantity`, falls back to `itemCost.unitCost` when layers are
+ insufficient; Average/Standard cost from `itemCost`.
+ - *Positive*: insert a `costLedger` layer (`itemLedgerType` = the entry
+ type, `costLedgerType 'Direct Cost'`, `quantity`, `remainingQuantity =
+ quantity`, `cost = quantity × currentUnitCost`) where `currentUnitCost`
+ is `standardCost` (Standard), `unitCost` (Average), or the
+ weighted-average of open layers incl. applied children with `unitCost`
+ fallback (FIFO/LIFO — the valuation RPC's carrying expression).
+ - *Storage-unit transfers*: none.
+ 4. **Journal** — only when `companySettings.accountingEnabled` AND the item
+ is valuated (`itemTrackingType !== 'Non-Inventory'`) AND the movement is
+ not a storage-unit transfer:
+ - `journal`: `sourceType 'Inventory Adjustment'`, `postingDate` = today,
+ `accountingPeriodId` via `getCurrentAccountingPeriod` (the `FOR SHARE`
+ period guard applies automatically), `status 'Posted'`.
+ - Two `journalLine`s sharing a `journalLineReference` (nanoid), amounts via
+ the `debit()`/`credit()` sign helpers, `accountId` (never number):
+ | Direction | Debit | Credit |
+ |---|---|---|
+ | Positive Adjmt. | inventory account (`resolveInventoryAccount`) | 5310 |
+ | Negative Adjmt. | 5310 | inventory account |
+ at the §1.3 cost. `documentType 'Inventory Adjustment'` (manual) or
+ `'Inventory Count'` (count path), `documentId` = the count id or the
+ item-ledger entry id, `quantity` = adjusted quantity. (The item-ledger
+ and cost-ledger rows keep their own `itemLedgerDocumentType` — NULL for
+ manual adjustments, as today; `costPostedToGL` no longer exists on
+ `costLedger`.) Every journal line is tagged with
+ `journalLineDimension` rows for the movement's **Item /
+ ItemPostingGroup / Location**, for whichever dimensions are active on
+ the company group (post-shipment precedent; Brad, 2026-07-15).
+- The posting core (steps 2–4) lives in a shared module
+ `functions/shared/post-adjustment.ts` so `post-inventory-count` reuses it.
+
+### 2. ERP + MES services become thin wrappers
+
+Both `insertManualInventoryAdjustment` functions keep their exact signatures
+and `{ data, error }` return shape but delegate to
+`client.functions.invoke("post-inventory-adjustment", { body })`. Route callers
+(`quantities+/$itemId.adjustment.tsx`, MES `x+/adjustment.tsx`) are untouched.
+One implementation of adjustment semantics replaces today's two-and-a-half.
+
+### 3. `post-inventory-count` gains the posting legs — including Rectify
+
+The count flow's snapshot-delta semantics are preserved exactly; only the
+posting legs are added:
+
+- **First post**: each counted line posts the reviewed variance —
+ `counted − frozen snapshot systemQuantity`, per `planInventoryCountPost` —
+ and the per-line loop calls the shared posting core instead of raw
+ `itemLedger` inserts, so each delta now maintains cost layers and adds a
+ journal-line pair (`documentType 'Inventory Count'`, `documentId` = count
+ id) inside the function's existing transaction and `FOR UPDATE` double-post
+ guard. A count post creates **ONE journal** shared by all its lines (Brad,
+ 2026-07-15) — created lazily on the first variance that carries value, so an
+ all-zero-cost post writes no empty journal. Each Rectify re-post likewise
+ gets one journal of its own.
+- **Rectify** (`rectifyInventoryCount`, `inventory.service.ts:2207`): reopening
+ a Posted count re-snapshots each line's `systemQuantity` to current live
+ on-hand and **posts nothing** by itself. The subsequent re-post sends the
+ *incremental* delta through the same core, linked to the line's prior
+ movement via `correctionOfItemLedgerId` (`postedItemLedgerId` bookkeeping and
+ the tracked-entity delta-apply are unchanged). A rectify correction is a new
+ adjustment, **not** a reversal of the original entry.
+- **Correction valuation**: each posting event is valued at cost at *its own
+ posting time* (layer consumption / current cost) — the original journal is
+ never mutated or reversed at its original amount. If cost moved between the
+ original post and the rectification, a residual correctly remains in 5310:
+ the interim period really carried that gain/loss. Movements stay linked for
+ audit via `correctionOfItemLedgerId`; all of a count's journals share its
+ `documentId`.
+- `getInventoryCountMovements` keeps working unchanged (same ledger
+ back-references, corrections included).
+
+### 4. Tie-out Reconcile action (cutover path)
+
+On the valuation workbench tie-out panel, a **"Reconcile"** action (visible
+when `accountingEnabled` and variance ≠ 0; gated by
+`permissions.can("create", "accounting")`). Naming: the *panel* stays the
+tie-out (the check); **Reconcile** is the action; the artifact is a draft
+**adjusting journal** — the QuickBooks/NetSuite reconcile-then-adjusting-entry
+pattern.
+
+- New route action `x+/inventory+/valuation.reconcile.tsx`
+ (`requirePermissions { create: "accounting" }`) calls a new
+ `createInventoryReconciliationJournal` service function that reuses the
+ existing manual-journal machinery (`upsertJournalEntry` /
+ `upsertJournalEntryLine`, `sourceType 'Manual'`): one **Draft** journal, one
+ line pair per account row with nonzero variance — `Dr/Cr` inventory account
+ vs 5310 — description stamped *"Inventory subledger reconciliation as of
+ {asOfDate}"*.
+- Redirects to the journals screen for review/edit/post. The tie-out already
+ excludes Draft journals, so the variance clears only when the accountant
+ posts.
+- Panel copy: the old caveat is removed entirely with **no replacement text**
+ (Brad, 2026-07-15) — when a variance exists the popover simply offers the
+ Reconcile button; at zero variance the button hides too.
+
+### 5. Documentation + parent-spec sync
+
+- Update parent spec §4 with a pointer to this spec; changelog entries in both.
+- `.ai/rules/inventory-system.md` gains the new posting path;
+ `docs/` inventory + accounting pages updated per the carbon-docs flow.
+
+### Design Decisions
+
+| # | Decision | Choice | Rationale |
+|---|----------|--------|-----------|
+| 1 | Multi-tenancy (heuristic 1) | No new tables. Every write carries `companyId` + audit fields; payload `userId` is required (zod) so `createdBy` is never NULL | House convention; "never feed a nullable user id into a NOT NULL audit column" lesson |
+| 2 | Service shape (heuristic 2) | Wrappers keep `client`-first `{data,error}` signatures; posting math in the edge function + `shared/post-adjustment.ts` | Brad's unification decision; matches the `post-*` family |
+| 3 | RLS (heuristic 3) | N/A — no new tables; edge function runs service-role behind `requirePermissions` | Same guard model as `post-receipt`/`post-inventory-count` |
+| 4 | Permissions (heuristic 4) | Edge fn: `update: "inventory"` (same as today's adjustment routes). Reconcile: `create: "accounting"` | Adjusting stock is an inventory action; creating journals is an accounting action |
+| 5 | Forms (heuristic 5) | Adjustment form unchanged (no cost input — resolved Q2); Reconcile reuses the existing journal-entry surface | Minimal UI delta; revaluation doc is the price tool |
+| 6 | Module layout (heuristic 6) | No new modules; service additions stay in `inventory.service.ts`; workbench edit in `ui/Valuation/` | One service/models file per module |
+| 7 | Backward compatibility (heuristic 7) | Additive enum values; wrapper signatures unchanged; `accountingEnabled = false` ⇒ itemLedger byte-identical + layers maintained (post-receipt precedent), no journal | No frozen surface touched |
+| 8 | Offset account | `accountDefault.inventoryAdjustmentVarianceAccount` (5310), resolved by id, both directions | Parent decision 8; account exists seeded NOT NULL; single quantity-variance account (SAP GBB-INV shape) |
+| 9 | Positive-adjustment cost | Current cost by method: `standardCost` / `unitCost` / weighted-avg open layers (fallback `unitCost`) | Resolved Q2; keeps journal = valuation RPC math |
+| 10 | Negative-adjustment cost | `calculateCOGS` consumption (layers + children; underwater fallback `unitCost`) | Single source of relief math with shipments/backflush |
+| 11 | Storage-unit transfers | No costLedger, no journal — ledger pair only | Value doesn't move between bins; naive posting would leak P&L when layer cost ≠ current cost |
+| 12 | Corrections/void | No void; corrections are new incremental adjustments valued at posting-time cost (count Rectify re-post links via `correctionOfItemLedgerId`; original journals immutable) | SAP PI precedent (no cancel of a posted difference); the Rectify flow (`20260713015508`) already models correction-as-new-movement |
+| 13 | Reason codes | Deferred; `comment` lands in journal/ledger descriptions as the seam | Research §Recommended 7; no-matrix-config lesson; scrap-vs-shrinkage split is the first future refinement |
+| 14 | Backfill | None automated; Reconcile draft adjusting journal (resolved Q3) | Fabricating history at current costs into the current period is worse than an explicit cutover entry |
+
+## Data Model Changes
+
+No new tables. One migration (`pnpm db:migrate:new inventory-adjustment-gl-posting`,
+HHMMSS randomized, idempotent):
+
+```sql
+-- Journal document linkage for adjustment postings (additive; enum ADD VALUE
+-- must not share a transaction with statements that use the value)
+ALTER TYPE "journalLineDocumentType" ADD VALUE IF NOT EXISTS 'Inventory Adjustment';
+ALTER TYPE "journalLineDocumentType" ADD VALUE IF NOT EXISTS 'Inventory Count';
+```
+
+`journalEntrySourceType` already contains `'Inventory Adjustment'` — no change.
+Plus `config.toml`: `[functions.post-inventory-adjustment] enabled = true,
+verify_jwt = true`. Run `pnpm run generate:types` before typechecking.
+
+## API / Service Changes
+
+- **New** edge function `post-inventory-adjustment` (§1) + shared
+ `functions/shared/post-adjustment.ts` posting core.
+- `post-inventory-count/index.ts`: per-line posting via the shared core (§3).
+- ERP `inventory.service.ts`: `insertManualInventoryAdjustment` → wrapper
+ invoking the edge function (signature unchanged); **new**
+ `createInventoryReconciliationJournal(client, companyId, { asOfDate, userId })`.
+- MES `services/inventory.service.ts`: `insertManualInventoryAdjustment` →
+ same wrapper.
+- **New route** `x+/inventory+/valuation.reconcile.tsx` (action only,
+ `create: "accounting"`).
+- No models changes (form contract unchanged). No Inngest.
+
+## UI Changes
+
+- `InventoryValuationWorkbench.tsx`: tie-out popover gains the Reconcile button
+ + replaced caveat copy (§4). All new strings through Lingui.
+- No changes to the adjustment forms (ERP `InventoryAdjustmentForm`, MES
+ `AdjustInventory`) or the count UI beyond what posting returns.
+
+## Acceptance Criteria
+
+- [ ] **Negative adjustment (numeric).** FIFO item with an open layer 20 @ $7.00:
+ a −10 adjustment posts Dr Inventory Adjustment (5310) $70.00 / Cr Raw
+ Materials $70.00; the layer's `remainingQuantity` drops 20 → 10; itemLedger
+ −10; journal `sourceType 'Inventory Adjustment'`, `documentType 'Inventory
+ Adjustment'`.
+- [ ] **Positive adjustment (numeric).** Same item, +5: Dr Raw Materials $35.00
+ / Cr 5310 $35.00; a new costLedger layer (qty 5, cost $35.00, remaining 5);
+ a later shipment of 15 consumes 10 from the old layer and 5 from the new one.
+- [ ] **Account routing.** A `Make` item's adjustment debits/credits Finished
+ Goods; a `Buy` item's hits Raw Materials — matching the tie-out's account rows.
+- [ ] **Set Quantity.** Setting on-hand 12 → 12 writes nothing; 12 → 9 posts a
+ −3 adjustment (delta semantics, layers preserved — the NetSuite worksheet
+ lesson).
+- [ ] **Storage-unit transfer.** Moving a tracked batch between bins writes the
+ ledger pair and zero costLedger/journal rows; tie-out variance unchanged.
+- [ ] **Count posting.** Posting a count with one +2 and one −4 variance line
+ writes **one journal** containing a balanced line pair per variance line
+ (four lines total), `documentType 'Inventory Count'` / `documentId` = count
+ id; the count's status/`postedItemLedgerId` bookkeeping and
+ `getInventoryCountMovements` behave exactly as today.
+- [ ] **Rectify (numeric).** A count posts −10 against a $7.00 layer
+ (Dr 5310 $70.00 / Cr Inventory $70.00). Rectify the count, re-count so the
+ line's delta is +4: the re-post writes a +4 movement linked via
+ `correctionOfItemLedgerId`, posts Dr Inventory / Cr 5310 at *current* cost
+ (not necessarily $7.00), never mutates the original journal, and
+ `getInventoryCountMovements` lists both movements linked.
+- [ ] **MES parity.** A shop-floor adjustment posts through the same edge
+ function with identical GL results.
+- [ ] **Accounting disabled.** With `accountingEnabled = false`: itemLedger
+ writes byte-identical to today, cost layers still maintained, zero journals.
+- [ ] **Non-valuated items.** `Non-Inventory` tracking-type adjustments never
+ write journals.
+- [ ] **Tie-out closes.** Fresh company, accounting enabled: receive 10 @ $8.00,
+ adjust −2 → subledger $64.00, GL $64.00, variance $0.00, and the old caveat
+ copy is gone.
+- [ ] **Reconcile.** A company with historical variance (RM −$120.00): the
+ Reconcile action creates a **Draft** journal Dr 5310 $120.00 / Cr Raw
+ Materials $120.00 stamped with the as-of date; the tie-out still shows the
+ variance until the journal is posted, then reads $0.00; the button hides at
+ zero variance and for users without `accounting_create`.
+- [ ] **Period guard.** Posting an adjustment while the current period is
+ Closed fails cleanly with no partial writes (no ledger row without its
+ journal).
+- [ ] **Atomicity.** Forcing a journal-insert failure mid-transaction leaves no
+ itemLedger/costLedger rows behind.
+- [ ] `pnpm run generate:types` then
+ `pnpm exec turbo run typecheck --filter=erp --filter=mes` passes; migration
+ re-runs safely.
+
+## Risks
+
+| Risk | Severity | Mitigation |
+|------|----------|------------|
+| Behavior drift porting the ERP function's tracked-entity/serial/bin logic into Deno | High | Port verbatim; keep wrapper signatures so every caller is unchanged; cover serial, batch, Set Quantity, and bin-transfer cases in acceptance testing + `/test` browser verification of the quantities page, MES adjustment, and count post |
+| Adjustments now deplete layers — later COGS changes vs today | Med | Correct by design (today's behavior is the bug); called out in docs; acceptance criterion pins the consumption order |
+| Underwater negatives (insufficient layers) valued at `unitCost` fallback | Low | Exact `calculateCOGS` precedent shipments already use; NetSuite documents the same estimate-and-correct semantics |
+| Count posting latency (per-line COGS in one txn) | Med | Single transaction, module-scope pool, batch line loop — same shape as `post-receipt`'s multi-line posting; measure on a seeded 100-line count |
+| Reconcile journal posted twice / stale amount | Low | Journal is Draft + human-reviewed; description stamps the as-of date; button recomputes variance live |
+| Edge-function invocation failure leaves UI ambiguous | Low | Wrappers surface `{ error }` unchanged; routes already flash errors; no optimistic ledger writes remain app-side |
+
+## Open Questions
+
+> HARD STOP: Do not proceed with implementation until these are answered.
+
+- [x] Posting architecture — **unified edge function with a Kysely transaction,
+ used by ERP and MES** (Brad, 2026-07-14).
+- [x] Cost input on positive adjustments — **none in v1; always current cost**
+ (Brad, 2026-07-14).
+- [x] Historical variance — **Reconcile action on the tie-out panel generating
+ a draft adjusting journal; no automated backfill** (Brad, 2026-07-14;
+ renamed from "true-up" same day).
+
+No new blocking questions surfaced while writing; judgment calls (transfer
+exemption, correction-not-void, deferred reason codes, count documentType) are
+baked as Design Decisions 11–13 and the §1.4 table, revisitable without schema
+churn.
+
+## Changelog
+
+- 2026-07-15: One journal per inventory count post (Brad) — the shared core
+ gains `accounting.getJournalId` so count lines append to a lazily created
+ shared journal; manual adjustments keep one journal per movement.
+ Post-review hardening: `companyId` scoping on applied-children queries,
+ `quantity.min(0)` on the payload, `getFunctionLogger` over `console.error`,
+ `msg`-wrapped Valuation breadcrumb.
+- 2026-07-15: Journal lines from adjustments and counts carry
+ Item/ItemPostingGroup/Location dimension tags (Brad) — same
+ `journalLineDimension` mechanism as post-shipment.
+- 2026-07-15: Tie-out popover carries no caveat text (Brad) — Reconcile button
+ only, shown when variance ≠ 0 and the user has `accounting_create`.
+- 2026-07-14: Created — after competitor research
+ (`.ai/research/inventory-adjustment-gl-posting.md`) and a 3-question grill
+ with Brad (resolutions inline). Grounded in code exploration: the three
+ adjustment writers (`inventory.service.ts:1442`, MES `inventory.service.ts:439`,
+ `post-inventory-count`), `calculateCOGS` + `appliesToCostLedgerId`
+ (`20260710033458`), `resolveInventoryAccount` + RM/FG split (`20260713190909`),
+ the 5310 seed (`20260315000000`), and the tie-out RPC (`20260715021050`).
+ Supersedes parent spec §4's service-level sketch per Brad's unification
+ decision.
+- 2026-07-14: Renamed the cutover action "true-up" → **Reconcile** (Brad) —
+ panel remains the tie-out (the check), Reconcile is the action, the artifact
+ is a draft adjusting journal; route/service renamed to
+ `valuation.reconcile.tsx` / `createInventoryReconciliationJournal`.
+- 2026-07-14: Expanded §3 with the count Rectify flow (Brad's note) — reopen
+ re-snapshots `systemQuantity` and posts nothing; the re-post posts the
+ incremental delta linked via `correctionOfItemLedgerId`, valued at
+ posting-time cost, original journals immutable (decision 12 + new numeric
+ acceptance criterion).
diff --git a/.ai/specs/2026-07-14-inventory-value-report.md b/.ai/specs/2026-07-14-inventory-value-report.md
new file mode 100644
index 0000000000..0dcfb33d8f
--- /dev/null
+++ b/.ai/specs/2026-07-14-inventory-value-report.md
@@ -0,0 +1,370 @@
+# Inventory Valuation Report — Interactive Value by Location and by Item
+
+> Status: in-progress
+> Author: Claude (with Brad Barbin)
+> Date: 2026-07-14
+> Research: `.ai/research/inventory-value-report.md` (SAP / NetSuite / BC / Fishbowl / Odoo survey + per-location-costing addendum)
+> Run record: `.ai/runs/2026-07-14-inventory-value-report.md`
+> Companions: `.ai/specs/2026-07-04-inventory-valuation-completeness.md` (costing engine — revaluation, LCNRV, adjustment GL; this report reads the layer math that spec defines) · `.ai/specs/2026-07-13-raw-materials-finished-goods-accounts.md` (the RM/FG account split the tie-out panel reads)
+
+## TLDR
+
+A new **Inventory Valuation** report at `/x/inventory/valuation`: an interactive,
+URL-state-driven screen showing inventory value grouped **by Location → items**
+(default) or **by Item → locations**, with group subtotals, a grand total, % of
+total, CSV export, an **as-of-date** selector (historical quantities exact from
+`itemLedger.postingDate`; costs always current — labeled, SAP-Fiori-style), and a
+**GL tie-out panel** (MB5L shape: one row per stock account — Raw Materials,
+Finished Goods — comparing subledger value to GL balance). Value is
+**method-faithful carrying cost**: FIFO/LIFO items use remaining cost-layer value
+(including `appliesToCostLedgerId` adjustment children), Average uses
+`itemCost.unitCost`, Standard uses `itemCost.standardCost`. All physical stock is
+valued — On Hold and Rejected quantities are included in value and broken out in
+their own columns (SAP MB52 stock-bucket precedent), because rejected stock remains
+an asset until a write-off posts. Backed by one new RPC
+(`get_inventory_valuation`), one service function pair, and one workbench component
+cloned from the AR/AP aging precedent. Gated by `accounting_view`. No new tables;
+the dead `get_inventory_value_by_location` RPC is kept (deprecated) for API
+compatibility.
+
+## Problem Statement
+
+Verified current state:
+
+1. **There is no inventory valuation surface anywhere in the app.** The only
+ artifact is the RPC `get_inventory_value_by_location`
+ (`packages/database/supabase/migrations/20260325031223_inventory-value-report.sql`)
+ with **zero app callers** — it appears only in generated types and the swagger
+ docs schema. Users cannot answer "what is our inventory worth, by site or by
+ item" without SQL.
+2. **The dead RPC's math is wrong for the books.** It values every item at
+ `itemCost.unitCost` — but FIFO/LIFO items are carried in **cost layers**
+ (`costLedger.remainingQuantity`, adjustment children via
+ `appliesToCostLedgerId`, per `20260504000000_cost-layers.sql` and the
+ completeness spec), and Standard items are costed at `standardCost`
+ (`calculate-cogs.ts:38-45`). It is also not status-aware and takes no date.
+3. **Every surveyed competitor ships this report** (research file §Key Consensus
+ Patterns): NetSuite Inventory Valuation Summary/Detail, BC report 1001 + Power
+ BI by-Item/by-Location, Fishbowl Inventory Valuation Summary (Group By =
+ exactly Location | Item), SAP MB52/MB5L. Carbon's `itemLedger` is
+ location-grained, so Carbon can do by-location valuation out of the box —
+ something core Odoo cannot.
+4. **The AR/AP workbench established the exact UI pattern** this report needs
+ (`apps/erp/app/routes/x+/invoicing+/receivables.tsx` +
+ `apps/erp/app/modules/invoicing/ui/Workbench/ARAPWorkbench.tsx`): URL-param
+ loader, grouped union-row table with expand/collapse, tie-out popover, date
+ picker — but nothing reuses it for inventory.
+
+## Resolved Questions (grill, answered before writing, 2026-07-14)
+
+- [x] **Valuation basis?** — **Method-faithful carrying cost.** FIFO/LIFO =
+ remaining layer value incl. applied adjustment children (fallback
+ `itemCost.unitCost` when an item has no layers); Average = `itemCost.unitCost`;
+ Standard = `itemCost.standardCost`. Per-location row value = location qty ×
+ company-level effective unit cost. Ties to the subledger and matches the
+ completeness spec's carrying-cost CTE.
+- [x] **Value Rejected / On Hold stock?** — **Yes, value all physical on-hand**,
+ with `quantityOnHold` / `quantityRejected` breakdown columns. Rejected stock is
+ an asset until written off (no write-off mechanism exists today); SAP MB52
+ values blocked stock the same way. Excluding it would create a permanent
+ unexplained gap vs the GL.
+- [x] **As-of-date in v1?** — **Yes (overrode the defer recommendation), with
+ explicitly labeled approximate-cost semantics**: quantities are exact
+ (`itemLedger.postingDate <= asOfDate`); unit costs are always **today's**
+ effective costs (SAP Fiori's documented "fast" semantics). Permanent UI label
+ when a past date is selected. Two labeled caveats: the `itemLedgerSnapshot`
+ matview has no date grain, so dated queries aggregate the raw ledger; the
+ status breakdown reflects *current* tracked-entity statuses even at past dates.
+- [x] **GL tie-out panel in v1?** — **Yes (overrode the defer recommendation).**
+ Per-account rows (SAP MB5L shape): Raw Materials and Finished Goods — subledger
+ value vs GL balance vs variance, plus total. Accounts resolve via
+ `accountDefault.rawMaterialsAccount` / `finishedGoodsAccount`
+ (`resolveInventoryAccount`, `shared/get-posting-group.ts:18`; split migration
+ `20260713190909`). Rendered only when `companySettings.accountingEnabled`. WIP
+ excluded. Panel copy carries a known-noise caveat: manual quantity adjustments
+ do not post GL until completeness-spec §4 lands, so variance is expected
+ nonzero for companies that cycle-count.
+- [x] **Drop the dead `get_inventory_value_by_location` RPC?** — **No — keep it,
+ deprecated.** Zero API-breakage risk accepted; the new `get_inventory_valuation`
+ ships alongside. Its swagger description gains a deprecation note.
+- [x] **Permission scope?** — **`accounting_view` gates the entire report**
+ (strictest option). The nav entry lives in the Inventory sidebar but renders
+ only for users with `accounting_view`; unit costs and GL balances never reach
+ ops-only roles.
+
+Pre-grill decision (recorded in the research addendum + run record):
+**`costLedger` does NOT gain `locationId`.** Layer consumption is company-wide
+(`calculate-cogs.ts:65` has no location filter), transfers write no cost entries
+(`post-stock-transfer`), revaluations are company-scoped — a stamped column would
+never balance per location. Per-location value is derived at report time as
+location qty × company-level effective unit cost (SAP below-plant / SAP B1
+company-level / Fishbowl semantics). True per-location costing (SAP per-plant,
+NetSuite MLI) is an industry-validated future spec of its own; this report's data
+contract keeps a per-row `unitCost` so a location-scoped cost can slot in later
+without reshaping the UI.
+
+## Proposed Solution
+
+### 1. Report semantics
+
+One screen, one RPC, two groupings:
+
+- **Group by Location** (default): location group rows (subtotal qty-value) →
+ item child rows. Fishbowl's default.
+- **Group by Item**: item group rows (total across locations) → location child
+ rows.
+
+Columns (research §7 consensus): Item (readableId + name) / Location, Costing
+Method, Qty On Hand, On Hold, Rejected, UoM, Unit Cost, Total Value, % of Total.
+Group rows show subtotal value + % of grand total; a footer row shows the grand
+total. Rows with zero on-hand are excluded (`HAVING SUM(quantity) <> 0`);
+negative on-hand rows are shown (data-quality signal), styled as destructive.
+
+**Effective unit cost** (company-level, per item):
+
+| Costing method | Basis |
+|---|---|
+| FIFO / LIFO | `Σ remainingQuantity × (layer.cost + Σ applied children) / layer.quantity` ÷ `Σ remainingQuantity` over layers with `remainingQuantity > 0`; fallback `itemCost.unitCost` when the item has no open layers |
+| Average | `itemCost.unitCost` |
+| Standard | `itemCost.standardCost` |
+
+The FIFO/LIFO expression is the completeness spec's carrying CTE (its §3 query).
+Implementation must stay consistent with how `calculate-cogs.ts` consumes
+adjustment children — a unit test pins the two together (see Risks).
+
+**As-of-date**: `asOfDate` URL param (default today). Quantities aggregate
+`itemLedger` rows with `postingDate <= asOfDate`. Costs are always current-state.
+When `asOfDate` < today the UI shows a persistent inline label:
+*"Values apply today's unit costs to historical quantities."*
+
+### 2. New RPC — `get_inventory_valuation`
+
+`get_inventory_valuation(company_id TEXT, as_of_date DATE DEFAULT NULL, location_id TEXT DEFAULT NULL)`
+
+Returns one row per (item, location) with non-zero quantity:
+`locationId, locationName, itemId, readableIdWithRevision, name, type,
+replenishmentSystem, unitOfMeasureCode, costingMethod, quantityOnHand,
+quantityOnHold, quantityRejected, unitCost, totalValue`.
+
+- `quantityOnHand` = full physical sum (all tracked-entity statuses included).
+ `quantityOnHold` / `quantityRejected` bucket by `itemLedger.trackedEntityStatus`
+ (denormalized, current — `20260420112047`).
+- **Current-date path** (`as_of_date IS NULL OR as_of_date >= CURRENT_DATE`):
+ snapshot + delta, exactly the `get_inventory_quantities` pattern
+ (`20260713235406_item-ledger-snapshot.sql`) — `itemLedgerSnapshot` for untracked
+ rows older than the cutoff, live delta for newer + all tracked rows. NOTE: the
+ snapshot's status-blind `quantity` is fine because untracked rows have no
+ status; buckets come only from tracked (live) rows.
+- **Dated path**: raw `itemLedger` aggregation filtered by `postingDate`.
+ Supported by the `20260713224517` ledger indexes; `location_id` narrows the
+ scan.
+- `replenishmentSystem` is returned so the app can classify each row to its stock
+ account (Make / Buy and Make → Finished Goods, else Raw Materials — mirroring
+ `resolveInventoryAccount`) for the tie-out's per-account subledger sums.
+- `SECURITY DEFINER`, same as `get_inventory_quantities` (required to read the
+ REVOKEd matview), `company_id` parameter scoping, `SET search_path = public`.
+
+The old `get_inventory_value_by_location` is untouched (kept per grill Q5) apart
+from a `COMMENT ON FUNCTION` deprecation note pointing at the new RPC.
+
+### 3. GL tie-out — `getInventoryValuationTieOut`
+
+Service function (precedent: `getArTieOut`, `invoicing.service.ts:2286`):
+
+- **Subledger side**: the report rows' `totalValue`, summed per account class
+ (RM / FG via `replenishmentSystem`), at the same `asOfDate`.
+- **GL side**: balance per account = `Σ journalLine.amount` for
+ `accountDefault.rawMaterialsAccount` and `accountDefault.finishedGoodsAccount`
+ where `postingDate <= asOfDate` (accounts resolved **by id** from
+ `accountDefault` — never by number, per `.ai/lessons.md`).
+- Output: `[{ accountKind: 'rawMaterials' | 'finishedGoods', accountId, accountName,
+ subledgerValue, glBalance, variance }]` + totals row.
+- Rendered as an ARAPWorkbench-style Popover panel; visible only when
+ `accountingEnabled`. Panel copy includes the caveat: *"Manual quantity
+ adjustments do not yet post to the GL — nonzero variance is expected if you
+ cycle-count."* (removable once completeness-spec §4 ships).
+
+### 4. Route, service, UI
+
+- **Route**: `apps/erp/app/routes/x+/inventory+/valuation.tsx`.
+ `requirePermissions(request, { view: "accounting" })`. Parses `asOfDate`,
+ `groupBy` (`location` | `item`, default `location`), `locationId` (optional
+ filter, default all locations). Parallel loads: `getInventoryValuation`,
+ `getInventoryValuationTieOut` (only when `accountingEnabled`), locations list.
+ Plain-object return (no `Response.json`).
+- **Service** (`inventory.service.ts`): `getInventoryValuation(client, companyId,
+ { asOfDate, locationId })` → RPC call; `getInventoryValuationTieOut(client,
+ companyId, asOfDate)`. Types flow via `Awaited<ReturnType<...>>` in
+ `types.ts`.
+- **UI**: `apps/erp/app/modules/inventory/ui/Valuation/InventoryValuationWorkbench.tsx`
+ cloned from `ARAPWorkbench.tsx`: union row type
+ `{ kind: "group" | "detail" }`, `expandedIds` state, expand/collapse chevrons,
+ group subtotal styling, grand-total footer; filter bar with `DatePicker`
+ (asOfDate → `setParams`), group-by `Select`, `Location` combobox, tie-out
+ `Popover`. Uses the ERP `Table` component → CSV export comes free
+ (`.ai/rules/table-csv-export.md`); currency via `useCurrencyFormatter`; all
+ strings through `useLingui`/`<Trans>`.
+- **Drill-through**: item detail rows link to
+ `path.to.inventoryItemActivity(itemId)` (the existing ledger activity page) —
+ the "Detail report" level every competitor pairs with the summary.
+- **Nav**: new entry **Valuation** in `useInventorySubmodules` "Track" group,
+ rendered only when `permissions.can("view", "accounting")`; `path.to.
+ inventoryValuation = ${x}/inventory/valuation` in `path.ts`.
+
+### Design Decisions
+
+| # | Decision | Choice | Rationale |
+|---|----------|--------|-----------|
+| 1 | Multi-tenancy (heuristic 1) | No new tables. RPC takes `company_id`, `SECURITY DEFINER` + explicit company scoping, mirroring `get_inventory_quantities` | Only correct way to read the REVOKEd `itemLedgerSnapshot`; the exact precedent this repo blessed in `20260713235406` |
+| 2 | Service shape (heuristic 2) | `getInventoryValuation` / `getInventoryValuationTieOut` in `inventory.service.ts`, client-first, `{data,error}` | One service file per module; RPC via `client.rpc()` returns `{data,error}` naturally |
+| 3 | RLS (heuristic 3) | N/A — no new tables; function follows the SECURITY DEFINER quantity-function pattern | Same guard model as `get_inventory_quantities` |
+| 4 | Permissions (heuristic 4) | `view: "accounting"` on the route; nav entry gated by `permissions.can("view", "accounting")` | Grill Q6 (Brad): strictest — costs never reach ops-only roles |
+| 5 | Forms (heuristic 5) | N/A — URL-param-driven report (`useUrlParams`/`setParams`), no ValidatedForm | AR/AP workbench precedent; no mutations on this screen |
+| 6 | Module layout (heuristic 6) | Report lives in the **inventory** module (`ui/Valuation/`), permission from accounting | Inventory is the domain home (Fishbowl/NetSuite/BC all file it under Inventory); lesson "features live inside existing permission modules" — no new module/permission family invented |
+| 7 | Backward compatibility (heuristic 7) | Everything additive: new RPC, new route, new nav entry; old RPC kept deprecated (grill Q5) | Zero breakage; swagger keeps both functions |
+| 8 | Valuation basis | Method-faithful carrying cost (grill Q1) | Ties to subledger/GL; single source of math with the completeness spec |
+| 9 | Per-location cost | Company-level effective unit cost × location qty; NO `costLedger.locationId` | Engine is company-scoped (consumption/transfers/revaluations); see research addendum — a stamped column would never balance |
+| 10 | Status scope | Value all physical stock; break out On Hold / Rejected (grill Q2) | GL-faithful (rejected stock is an un-written-off asset); SAP MB52 buckets |
+| 11 | As-of semantics | Historical qty exact, cost always current, permanently labeled (grill Q3) | SAP documents this exact fast-vs-accurate split; honesty beats false precision |
+| 12 | Tie-out shape | Per stock account (RM, FG) + total, MB5L-style (grill Q4) | Two actionable rows beat one blended number; accounts already split by `20260713190909` |
+| 13 | Group-by | Toggle Location ↔ Item, Location default | Fishbowl's exactly-two-groupings model; matches the verbatim feature request |
+| 14 | Zero/negative rows | Zero-qty rows excluded; negative rows shown styled destructive | Zero rows are noise; negatives are a data-quality signal the report should surface, not hide |
+| 15 | Drill-through | Item row → existing item activity (ledger) page; no new detail report | Summary→Detail consensus satisfied by an existing screen; scope discipline |
+
+## Data Model Changes
+
+No new tables. One migration (`pnpm db:migrate:new inventory-valuation-rpc`;
+timestamp HHMMSS randomized per house rule; idempotent):
+
+```sql
+-- get_inventory_valuation: method-faithful inventory value by (item, location).
+-- Follows get_inventory_quantities (20260713235406): SECURITY DEFINER to read
+-- itemLedgerSnapshot; snapshot+delta on the current-date path, raw ledger on the
+-- dated path. Sketch (final SQL forks from the NEWEST get_inventory_quantities
+-- definition at implementation time — never an older revision):
+
+DROP FUNCTION IF EXISTS get_inventory_valuation(TEXT, DATE, TEXT);
+CREATE FUNCTION get_inventory_valuation(
+ company_id TEXT,
+ as_of_date DATE DEFAULT NULL,
+ location_id TEXT DEFAULT NULL
+) RETURNS TABLE (
+ "locationId" TEXT, "locationName" TEXT,
+ "itemId" TEXT, "readableIdWithRevision" TEXT, "name" TEXT,
+ "type" "itemType", "replenishmentSystem" "itemReplenishmentSystem",
+ "unitOfMeasureCode" TEXT, "costingMethod" "itemCostingMethod",
+ "quantityOnHand" NUMERIC, "quantityOnHold" NUMERIC, "quantityRejected" NUMERIC,
+ "unitCost" NUMERIC, "totalValue" NUMERIC
+) LANGUAGE plpgsql STABLE SECURITY DEFINER SET search_path = public AS $$
+-- quantities CTE: snapshot+delta (as_of_date null/today) or raw postingDate
+-- filter (dated), grouped by item+location, HAVING SUM(quantity) <> 0;
+-- status buckets from trackedEntityStatus on tracked rows.
+-- carrying CTE (completeness-spec math): per item,
+-- FIFO/LIFO: SUM(cl."remainingQuantity" * (cl."cost" + COALESCE(adj.applied,0))
+-- / NULLIF(cl."quantity",0)) / NULLIF(SUM(cl."remainingQuantity"),0)
+-- over layers WHERE cl."remainingQuantity" > 0, with
+-- adj = LATERAL SUM(cost) of rows a WHERE a."appliesToCostLedgerId" = cl."id";
+-- fallback ic."unitCost" when no open layers.
+-- Average: ic."unitCost" Standard: ic."standardCost"
+-- final SELECT: quantities × carrying joined to item/location, company-scoped.
+$$;
+-- plpgsql (never LANGUAGE sql): internal ORDER BY must survive PostgREST (.ai/lessons.md)
+
+COMMENT ON FUNCTION get_inventory_value_by_location(TEXT) IS
+ 'Deprecated: superseded by get_inventory_valuation (method-faithful costs, status breakdown, as-of-date).';
+```
+
+Then `pnpm run generate:types` before any typechecking.
+
+## API / Service Changes
+
+- `inventory.service.ts`: `getInventoryValuation(client, companyId, { asOfDate?, locationId? })`
+ → `client.rpc("get_inventory_valuation", ...)`; `getInventoryValuationTieOut(client, companyId, asOfDate)`
+ → Kysely sums of `journalLine` per `accountDefault.rawMaterialsAccount`/`finishedGoodsAccount`
+ (by id) + subledger sums from the RPC rows (precedent `getArTieOut`).
+- `inventory/types.ts`: `InventoryValuationRow`, `InventoryValuationTieOut` via `Awaited<ReturnType<...>>`.
+- `path.ts`: `inventoryValuation: ${x}/inventory/valuation`.
+- No models changes (no forms). No edge functions. No Inngest.
+
+## UI Changes
+
+- New route `x+/inventory+/valuation.tsx` (loader described in §4; `handle` module inventory).
+- New `modules/inventory/ui/Valuation/InventoryValuationWorkbench.tsx` (+ barrel export)
+ cloned from `ARAPWorkbench.tsx`: grouped union-row table, expand/collapse,
+ subtotals + grand total, % of total, filter bar (DatePicker, group-by Select,
+ location combobox), tie-out Popover, as-of semantics label, CSV export via the
+ standard `Table`, destructive styling on negative rows, item drill-through links.
+- `useInventorySubmodules.tsx`: "Valuation" entry in the Track group, gated by
+ `permissions.can("view", "accounting")`.
+- New strings marked for i18n; `/translate` fills catalogs at commit time.
+
+## Acceptance Criteria
+
+- [ ] **FIFO carrying math (numeric).** Item F-1 (FIFO) with layers: 100 @ $10.00
+ (60 remaining) and 50 @ $12.00 (50 remaining) → effective unit cost
+ $(60×10 + 50×12)/110 = $10.9091$. On-hand 110 split 80 @ Location A / 30 @
+ Location B → row values $872.73 / $327.27; item total $1,200.00 equals the
+ layers' remaining value exactly.
+- [ ] **Adjustment children included.** A +$55.00 variance child
+ (`appliesToCostLedgerId` → the 60-remaining layer, quantity 100) raises that
+ layer's effective unit cost by $0.55 and the report total by 60 × $0.55 = $33.00.
+- [ ] **Standard method.** Item S-1 (`costingMethod = 'Standard'`,
+ `standardCost = 5.00`, `unitCost = 0`) with 10 on hand values at $50.00, not $0.
+- [ ] **Status breakdown.** Item T-1 with 120 physical (5 Rejected, 10 On Hold):
+ row shows Qty 120 / On Hold 10 / Rejected 5, value = 120 × unit cost.
+- [ ] **As-of-date.** After a receipt posted today, setting asOfDate = yesterday
+ removes today's quantity from the report, and the label "applies today's unit
+ costs to historical quantities" is visible; asOfDate = today shows no label.
+- [ ] **Group toggle.** By Location: location group rows with subtotals and item
+ children; by Item: mirrored. Grand total identical in both groupings; % of
+ total sums to 100%.
+- [ ] **Tie-out (numeric).** Fresh company, accounting enabled: receive 10 @ $8.00
+ of a Buy item → tie-out shows Raw Materials subledger $80.00, GL balance $80.00,
+ variance $0.00; Finished Goods row $0/$0/$0. Panel hidden when
+ `accountingEnabled = false`.
+- [ ] **Permissions.** A user with `inventory_view` but not `accounting_view` gets
+ no "Valuation" nav entry and a 403 on direct navigation; with `accounting_view`
+ both work.
+- [ ] **Deprecated RPC untouched.** `get_inventory_value_by_location` still
+ returns its old shape (API compatibility).
+- [ ] **CSV export** downloads the visible rows with item, location, quantities,
+ unit cost, total value.
+- [ ] `pnpm run generate:types` then
+ `pnpm exec turbo run typecheck --filter=@carbon/erp` passes; new RPC migration
+ applies idempotently (re-run safe).
+
+## Risks
+
+| Risk | Severity | Mitigation |
+|------|----------|------------|
+| Carrying-cost SQL drifts from `calculate-cogs.ts` layer semantics (adjustment-children handling) | High | The FIFO/LIFO expression is lifted from the completeness spec's carrying CTE; add a service-level test seeding layers + children and asserting the RPC's unitCost matches the COGS math; coordinate if completeness PR 1 changes the expression |
+| Dated-path performance on large ledgers (no snapshot) | Med | `20260713224517` indexes cover item/location aggregation; `location_id` param narrows; report is a deliberate pull, not a hot path — measure with `EXPLAIN ANALYZE` on seeded volume before ship |
+| Tie-out shows structural variance (unposted cycle-count adjustments) | Med | Known-noise caveat in panel copy (grill Q4 decision); resolves when completeness-spec §4 lands |
+| As-of numbers change retroactively as costs move | Med | Permanent semantics label (grill Q3); documented in the docs page for the report |
+| `itemLedgerSnapshot` status-blindness misread as a bug | Low | Untracked rows carry no status; buckets computed from tracked (live) rows only — noted in the migration comment |
+| Effective-cost fallback (`unitCost`) for layerless FIFO items misleads | Low | Fallback matches what COGS would charge today (`calculate-cogs` falls back the same way for Average); costingMethod column keeps provenance visible |
+
+## Open Questions
+
+> HARD STOP: Do not proceed with implementation until these are answered.
+
+- [x] Valuation basis — **method-faithful carrying cost** (Brad, 2026-07-14; grill Q1).
+- [x] Rejected/On-Hold stock — **valued, with breakdown columns** (Brad, 2026-07-14; grill Q2).
+- [x] As-of-date — **in v1, approximate cost + permanent label** (Brad, 2026-07-14; grill Q3, overrode defer recommendation).
+- [x] GL tie-out — **in v1, per-account MB5L shape + known-noise caveat** (Brad, 2026-07-14; grill Q4, overrode defer recommendation).
+- [x] Old RPC — **kept, deprecated** (Brad, 2026-07-14; grill Q5).
+- [x] Permissions — **accounting_view gates the report** (Brad, 2026-07-14; grill Q6).
+- [x] `costLedger.locationId` — **not added**; per-location costing deferred to its own future spec (Brad, 2026-07-14; pre-grill, research addendum).
+
+No new blocking questions surfaced while writing; judgment calls (zero/negative
+row handling, drill-through target, group-by default, nav placement) are baked as
+Design Decisions 13–15 and revisitable without schema churn.
+
+## Changelog
+
+- 2026-07-14: Created — after competitor research (`.ai/research/inventory-value-report.md`)
+ and a 6-question grill with Brad (all resolutions inline above). Grounded in
+ code exploration: dead RPC `20260325031223`, cost layers + `appliesToCostLedgerId`
+ (`20260504000000`, completeness spec), snapshot pattern `20260713235406`,
+ RM/FG account split `20260713190909`, AR/AP workbench precedent
+ (`receivables.tsx` / `ARAPWorkbench.tsx`).
diff --git a/README.md b/README.md
index a852f8ae5a..6a6518196f 100644
--- a/README.md
+++ b/README.md
@@ -307,6 +307,26 @@ $ pnpm dev # equivalent to `crbn up` — picker lets you choose E
Academy and starter still run on classic localhost ports via `pnpm dev:academy` / `pnpm dev:starter` (they are not part of the per-worktree stack).
+### Logging in
+
+For local development you don't need email or OAuth configured. `crbn up` seeds a
+smoke-test user (`[email protected]`) and writes `[email protected]`
+into `.env.local` for you. When that bypass email is set, signing in with it skips
+the magic link and logs you straight into the ERP:
+
+1. Open the ERP at the URL from the `crbn up` summary (e.g. `https://<worktree>.erp.dev/login`).
+2. Type `[email protected]` into the email field.
+3. Click **Sign in with Email**.
+
+You'll land on the authenticated dashboard (`/x`) — no inbox check required. The
+same session cookie works for the MES app at `https://<worktree>.mes.dev`.
+
+> The bypass only applies to the exact address in `DEV_BYPASS_EMAIL` and only when
+> that user is active — it's a dev convenience, not present in production. Any other
+> email falls back to the normal magic-link / verification flow (which needs Resend
+> configured). To sign in as your own account instead, use the magic link and read it
+> from the local mail catcher at `https://<worktree>.mail.dev`.
+
### Code Formatting
This project uses [Biome](https://biomejs.dev/) for code formatting and linting. To set up automatic formatting on save in VS Code:
diff --git a/apps/erp/app/components/Editable/EditableText.tsx b/apps/erp/app/components/Editable/EditableText.tsx
index 70c72b4e5b..2000254787 100644
--- a/apps/erp/app/components/Editable/EditableText.tsx
+++ b/apps/erp/app/components/Editable/EditableText.tsx
@@ -1,6 +1,6 @@
import { Input } from "@carbon/react";
import type { PostgrestSingleResponse } from "@supabase/supabase-js";
-import type { FocusEvent, KeyboardEvent } from "react";
+import type { FocusEvent } from "react";
import type { EditableTableCellComponentProps } from "~/components/Editable";
const EditableText =
@@ -36,16 +36,9 @@ const EditableText =
});
};
- const onKeyDown = (event: KeyboardEvent<HTMLInputElement>) => {
- // only run the update if they click enter
- if (event.key === "Enter" || event.key === "Tab") {
- if (event.currentTarget.value !== value) {
- updateText(event.currentTarget.value);
- }
- }
- };
-
- // run update if focus is lost
+ // Blur is the single commit path: the containers (Table/Grid) blur the
+ // input before navigating on Tab/Enter, and click-away blurs natively. A
+ // keydown commit on top of this would double-fire the mutation.
const onBlur = (event: FocusEvent<HTMLInputElement>) => {
if (event.currentTarget.value !== value) {
updateText(event.currentTarget.value);
@@ -60,7 +53,6 @@ const EditableText =
size="sm"
onFocus={(e) => e.currentTarget.select()}
onBlur={onBlur}
- onKeyDown={onKeyDown}
/>
);
};
diff --git a/apps/erp/app/components/Table/Table.tsx b/apps/erp/app/components/Table/Table.tsx
index 74f7a7449d..fbd0237139 100644
--- a/apps/erp/app/components/Table/Table.tsx
+++ b/apps/erp/app/components/Table/Table.tsx
@@ -531,6 +531,14 @@ const Table = <T extends object>({
const [isEditing, setIsEditing] = useState(false);
const [selectedCell, setSelectedCell] = useState<Position>(null);
+ // forceEditMode follows the document's state (e.g. Rectify flips a Posted
+ // count back to Draft via revalidation, without remounting the table) — and
+ // the Edit/Lock toggle is hidden while it's set, so a stale editMode would
+ // strand the table with no way to recover. Keep them in sync.
+ useEffect(() => {
+ setEditMode(forceEditMode);
+ }, [forceEditMode]);
+
/* Aggregate Functions */
const [columnAggregates, setColumnAggregates] = useState<
Record<string, AggregateFunction>
@@ -624,10 +632,24 @@ const Table = <T extends object>({
[table]
);
+ // Excel-like keyboard model, attached in the CAPTURE phase so navigation
+ // keys are handled before the cell editor sees them (react-aria's
+ // NumberField swallows Enter without propagation and steps the value on
+ // ArrowUp/Down — capture lets the table own those keys while editing).
// biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migration
const onKeyDown = useCallback(
(event: React.KeyboardEvent<HTMLDivElement>) => {
if (!selectedCell) return;
+ // Don't hijack keys aimed at a portaled overlay (a cell editor's
+ // combobox/date popover, a row context menu) — those own their keys.
+ if (event.nativeEvent.isComposing) return;
+ const target = event.target as HTMLElement | null;
+ if (
+ target?.closest(
+ "[data-radix-popper-content-wrapper],[role=menu],[role=listbox],[role=dialog]"
+ )
+ )
+ return;
const { code, shiftKey } = event;
@@ -694,8 +716,25 @@ const Table = <T extends object>({
return [x1, y1];
};
+ // Commit any in-flight edit before navigating away. Editors commit
+ // their value on blur — without this, the navigation's preventDefault
+ // keeps focus on the input until it unmounts and the blur never fires,
+ // silently dropping the typed value.
+ const commitActiveEdit = () => {
+ if (
+ isEditing &&
+ document.activeElement instanceof HTMLElement &&
+ document.activeElement !== document.body
+ ) {
+ document.activeElement.blur();
+ }
+ };
+
if (code in commandCodes) {
event.preventDefault();
+ // Keep the key away from the editor entirely (react-aria would
+ // otherwise run its own Enter commit on the input).
+ if (isEditing) event.stopPropagation();
if (
!isEditing &&
@@ -710,6 +749,9 @@ const Table = <T extends object>({
let direction = commandCodes[code];
if (shiftKey) direction = [-direction[0], -direction[1]];
const [x1, y1] = navigate(direction, code === "Tab");
+
+ commitActiveEdit();
+
setSelectedCell({
row: y1,
column: x1
@@ -718,10 +760,12 @@ const Table = <T extends object>({
setIsEditing(false);
}
} else if (code in navigationCodes) {
- // arrow key navigation should't work if we're editing
- if (isEditing) return;
event.preventDefault();
+ // Excel-like: while editing, an arrow commits the edit and moves the
+ // selection — it must not step the value or move the text cursor.
+ if (isEditing) event.stopPropagation();
const [x1, y1] = navigate(navigationCodes[code], code === "Tab");
+ commitActiveEdit();
setIsEditing(false);
setSelectedCell({
row: y1,
@@ -951,7 +995,7 @@ const Table = <T extends object>({
)}
style={{ contain: "strict" }}
ref={tableContainerRef}
- onKeyDown={editMode ? onKeyDown : undefined}
+ onKeyDownCapture={editMode ? onKeyDown : undefined}
>
<div className="flex max-w-full h-full">
{rows.length === 0 ? (
diff --git a/apps/erp/app/components/Table/components/Cell.tsx b/apps/erp/app/components/Table/components/Cell.tsx
index c489668fb8..e01f2bc64a 100644
--- a/apps/erp/app/components/Table/components/Cell.tsx
+++ b/apps/erp/app/components/Table/components/Cell.tsx
@@ -72,11 +72,13 @@ const Cell = <T extends object>({
isEditMode && !hasEditableTableCellComponent && "bg-muted/50",
isEditMode && "border-border border-r",
hasError && "ring-inset ring-2 ring-red-500",
- // Only ring editable cells — a ring on a read-only cell wrongly signals
- // it can be edited.
+ // Selection is always visible (Excel-like), or keyboard navigation
+ // has no landmark. Editable cells get the full-strength ring +
+ // background; read-only cells a muted ring so the selection doesn't
+ // signal "you can type here".
+ isSelected && "!ring-inset !ring-2",
isSelected &&
- hasEditableTableCellComponent &&
- "!ring-inset !ring-2 !ring-ring",
+ (hasEditableTableCellComponent ? "!ring-ring" : "!ring-ring/40"),
isSelected && hasEditableTableCellComponent && "!bg-background",
"transition-[left,right,box-shadow] duration-200",
isPinned && "bg-card"
diff --git a/apps/erp/app/modules/inventory/AGENTS.md b/apps/erp/app/modules/inventory/AGENTS.md
index ccd4dd11f4..dee42c22c9 100644
--- a/apps/erp/app/modules/inventory/AGENTS.md
+++ b/apps/erp/app/modules/inventory/AGENTS.md
@@ -35,8 +35,7 @@ Tracks item quantities across locations and storage units. Manages receipts, shi
## Validation Commands
```bash
-pnpm --filter @carbon/erp typecheck
-pnpm --filter @carbon/erp test
+pnpm exec turbo run typecheck --filter=erp # the app's package name is "erp", not "@carbon/erp"
```
## Key Data Model
@@ -60,7 +59,7 @@ pnpm --filter @carbon/erp test
- `getInventoryItems` / `getInventoryItemsCount` — calls `get_inventory_quantities` RPC for on-hand quantities
- `getItemLedgerPage` / `getItemLedgerActivity` — paginated ledger history
-- `insertManualInventoryAdjustment` — adjustments with tracked entity handling and ledger entries
+- `insertManualInventoryAdjustment` — adjustments with tracked entity handling; wraps the `post-inventory-adjustment` edge function, which also maintains cost layers and posts GL journals (5310 vs RM/FG) in one transaction when accounting is enabled
- `getStorageUnit(s)` / `getStorageUnitTree` / `getStorageUnitsTreeForLocation` — storage hierarchy
- `getAvailableTrackedEntities` — calls `get_available_tracked_entities` RPC
- `getReceipts` / `getReceiptLines` / `reconcileReceiptSerialEntities` — receipt management
diff --git a/apps/erp/app/modules/inventory/inventory.service.ts b/apps/erp/app/modules/inventory/inventory.service.ts
index 081384baa8..514c523aab 100644
--- a/apps/erp/app/modules/inventory/inventory.service.ts
+++ b/apps/erp/app/modules/inventory/inventory.service.ts
@@ -8,6 +8,7 @@ import { nanoid } from "nanoid";
import type { z } from "zod";
import { getNextSequence } from "~/modules/settings";
import type { StorageItem } from "~/types";
+import { getEdgeFunctionErrorMessage } from "~/utils/error";
import type { GenericQueryFilters } from "~/utils/query";
import { setGenericQueryFilters } from "~/utils/query";
import { sanitize } from "~/utils/supabase";
@@ -327,6 +328,133 @@ export async function getInventoryItemsCount(
return query;
}
+export async function getInventoryValuation(
+ client: SupabaseClient<Database>,
+ companyId: string,
+ args: { asOfDate?: string | null; locationId?: string | null }
+) {
+ return client.rpc("get_inventory_valuation", {
+ company_id: companyId,
+ as_of_date: args.asOfDate ?? undefined,
+ location_id: args.locationId ?? undefined
+ });
+}
+
+export async function getInventoryValuationTieOut(
+ client: SupabaseClient<Database>,
+ companyId: string,
+ asOfDate?: string | null
+) {
+ return client.rpc("get_inventory_tie_out", {
+ company_id: companyId,
+ as_of_date: asOfDate ?? undefined
+ });
+}
+
+// Draft adjusting journal that brings the GL inventory accounts to the
+// subledger valuation — the tie-out's Reconcile action (cutover path for
+// adjustments posted before GL posting existed). variance = subledger − GL,
+// so the inventory line is +variance and the offset −variance: positive on an
+// Asset = debit, negative on the (Expense) adjustment account = credit — raw
+// amounts sum to zero. The journal stays Draft: a human reviews and posts it
+// from the Journals screen, and the tie-out ignores Draft journals.
+// Posted on the tie-out's as-of date — the tie-out only counts journals with
+// postingDate <= asOfDate, so a today-dated journal could never resolve a
+// backdated variance. Posting may still be rejected if that period is Closed.
+export async function createInventoryReconciliationJournal(
+ client: SupabaseClient<Database>,
+ db: Kysely<KyselyDatabase>,
+ companyId: string,
+ args: { asOfDate: string; userId: string }
+) {
+ const [tieOut, accountDefaults] = await Promise.all([
+ getInventoryValuationTieOut(client, companyId, args.asOfDate),
+ client
+ .from("accountDefault")
+ .select("inventoryAdjustmentVarianceAccount")
+ .eq("companyId", companyId)
+ .single()
+ ]);
+ if (tieOut.error) return tieOut;
+ if (accountDefaults.error) return accountDefaults;
+
+ const rows = (tieOut.data ?? []).filter(
+ (row) => Math.abs(Number(row.variance)) > 0.005
+ );
+ if (rows.length === 0) {
+ return {
+ data: null,
+ error: { message: "Nothing to reconcile — variance is zero" }
+ };
+ }
+
+ const nextSequence = await getNextSequence(client, "journalEntry", companyId);
+ if (nextSequence.error) return nextSequence;
+ const journalEntryId = nextSequence.data;
+
+ // Header + lines in one transaction — a partial failure must not leave an
+ // orphaned Draft header behind.
+ try {
+ const journalId = await db.transaction().execute(async (trx) => {
+ const journal = await trx
+ .insertInto("journal")
+ .values({
+ journalEntryId,
+ description: `Inventory subledger reconciliation as of ${args.asOfDate}`,
+ postingDate: args.asOfDate,
+ sourceType: "Manual" as const,
+ status: "Draft" as const,
+ companyId,
+ createdBy: args.userId
+ })
+ .returning("id")
+ .executeTakeFirstOrThrow();
+
+ await trx
+ .insertInto("journalLine")
+ .values(
+ rows.flatMap((row) => {
+ const variance = Number(row.variance);
+ const journalLineReference = crypto.randomUUID();
+ return [
+ {
+ journalId: journal.id,
+ accountId: row.accountId,
+ description: `Reconcile ${row.accountName} to subledger`,
+ amount: variance,
+ journalLineReference,
+ companyId
+ },
+ {
+ journalId: journal.id,
+ accountId:
+ accountDefaults.data.inventoryAdjustmentVarianceAccount,
+ description: "Inventory Adjustment",
+ amount: -variance,
+ journalLineReference,
+ companyId
+ }
+ ];
+ })
+ )
+ .execute();
+
+ return journal.id;
+ });
+ return { data: { journalId }, error: null };
+ } catch (err) {
+ return {
+ data: null,
+ error: {
+ message:
+ err instanceof Error
+ ? err.message
+ : "Failed to create reconciliation journal"
+ }
+ };
+ }
+}
+
export async function getKanbans(
client: SupabaseClient<Database>,
locationId: string,
@@ -1416,6 +1544,11 @@ export async function getWarehouseTransferLines(
.eq("transferId", transferId);
}
+// Thin wrapper over the post-inventory-adjustment edge function — the single
+// write path for manual adjustments (shared with MES). The edge function owns
+// Set Quantity resolution, storage-unit transfers, serial/batch stock-target
+// resolution, tracked-entity updates, cost layers, and GL posting (only when
+// companySettings.accountingEnabled) in one transaction.
export async function insertManualInventoryAdjustment(
client: SupabaseClient<Database>,
// `requiresSerialTracking` is a form-only flag for the validator's serial
@@ -1428,386 +1561,28 @@ export async function insertManualInventoryAdjustment(
createdBy: string;
}
) {
- const {
- adjustmentType,
- readableId,
- originalStorageUnitId,
- comment,
- expirationDate: providedExpirationDate,
- ...rest
- } = inventoryAdjustment;
- const data = {
- ...rest,
- entryType:
- adjustmentType === "Set Quantity" ? "Positive Adjmt." : adjustmentType, // This will be overwritten below
- comment: comment || null
- };
-
- // For new tracked entities created here, fall back to the item's Fixed
- // Duration shelf-life policy when the user did not type an expiry. Other
- // modes (Calculated, Set on Receipt) intentionally stay NULL — they get
- // resolved at production / receipt time, not on a manual adjustment.
- const resolveExpirationForNewEntity = async (): Promise<string | null> => {
- if (providedExpirationDate) return providedExpirationDate;
- const shelfLife = await client
- .from("itemShelfLife")
- .select("mode, days")
- .eq("itemId", inventoryAdjustment.itemId)
- .maybeSingle();
- if (
- !shelfLife.error &&
- shelfLife.data?.mode === "Fixed Duration" &&
- shelfLife.data.days
- ) {
- return today(getLocalTimeZone())
- .add({ days: Number(shelfLife.data.days) })
- .toString();
- }
- return null;
- };
+ const { companyId, createdBy, ...adjustment } = inventoryAdjustment;
- // For existing tracked entities, only write when the user supplied a value
- // and it differs from the current row. Routes through updateTrackedEntityExpiry
- // so the override is captured in attributes.expiryOverrides for traceability.
- const applyExpirationOverride = async (trackedEntityId: string) => {
- if (!providedExpirationDate) return null;
- const current = await client
- .from("trackedEntity")
- .select("expirationDate")
- .eq("id", trackedEntityId)
- .single();
- if (
- !current.error &&
- current.data?.expirationDate === providedExpirationDate
- )
- return null;
- return updateTrackedEntityExpiry(client, {
- trackedEntityId,
- expirationDate: providedExpirationDate,
- reason: comment?.trim() || "Updated via inventory adjustment",
- source: "Inventory Adjustment",
- userId: data.createdBy
- });
- };
-
- const storageUnitQuantities = await client.rpc(
- "get_item_quantities_by_tracking_id",
- {
- item_id: data.itemId,
- company_id: data.companyId,
- location_id: data.locationId
- }
- );
+ const result = await client.functions.invoke<{
+ success: boolean;
+ itemLedger: { id: string } | null;
+ }>("post-inventory-adjustment", {
+ body: { ...adjustment, companyId, userId: createdBy }
+ });
- const currentQuantity = inventoryAdjustment.trackedEntityId
- ? storageUnitQuantities?.data?.find(
- (quantity) =>
- quantity.trackedEntityId == inventoryAdjustment.trackedEntityId
+ if (result.error) {
+ // Bare-string error, matching the old service's validation-branch
+ // contract — the adjustment route compares `error === "<message>"`.
+ return {
+ data: null,
+ error: await getEdgeFunctionErrorMessage(
+ result.error,
+ "Failed to create manual inventory adjustment"
)
- : storageUnitQuantities?.data?.find(
- // null == undefined - so we use a == instead of === here
- (quantity) => quantity.storageUnitId == data.storageUnitId
- );
-
- const currentQuantityOnHand = currentQuantity?.quantity ?? 0;
-
- // Check if this is a storage unit transfer for a tracked entity
- const isStorageUnitTransfer =
- inventoryAdjustment.trackedEntityId &&
- originalStorageUnitId &&
- originalStorageUnitId !== data.storageUnitId;
-
- if (isStorageUnitTransfer) {
- // Handle storage unit transfer: negative adjustment at original unit, positive at new unit
- // First, update the readableId if provided
- if (readableId !== undefined) {
- const trackedEntityUpdate = await client
- .from("trackedEntity")
- .update({ readableId })
- // @ts-expect-error TS2345 - TODO: fix type
- .eq("id", inventoryAdjustment.trackedEntityId);
-
- if (trackedEntityUpdate.error) {
- return trackedEntityUpdate;
- }
- }
-
- if (inventoryAdjustment.trackedEntityId) {
- const expiryOverride = await applyExpirationOverride(
- inventoryAdjustment.trackedEntityId
- );
- if (expiryOverride?.error) return expiryOverride;
- }
-
- // Create negative adjustment at original storage unit
- const negativeAdjustment = await client
- .from("itemLedger")
- .insert([
- {
- itemId: data.itemId,
- locationId: data.locationId,
- storageUnitId: originalStorageUnitId,
- trackedEntityId: inventoryAdjustment.trackedEntityId,
- entryType: "Negative Adjmt." as const,
- quantity: -currentQuantityOnHand,
- companyId: data.companyId,
- createdBy: data.createdBy,
- comment: data.comment
- }
- ])
- .select("*")
- .single();
-
- if (negativeAdjustment.error) {
- return negativeAdjustment;
- }
-
- // Create positive adjustment at new storage unit
- return client
- .from("itemLedger")
- .insert([
- {
- itemId: data.itemId,
- locationId: data.locationId,
- storageUnitId: data.storageUnitId,
- trackedEntityId: inventoryAdjustment.trackedEntityId,
- entryType: "Positive Adjmt." as const,
- quantity: currentQuantityOnHand,
- companyId: data.companyId,
- createdBy: data.createdBy,
- comment: data.comment
- }
- ])
- .select("*")
- .single();
- }
-
- if (adjustmentType === "Set Quantity" && currentQuantity) {
- const quantityDifference = data.quantity - currentQuantityOnHand;
- if (quantityDifference > 0) {
- data.entryType = "Positive Adjmt.";
- data.quantity = quantityDifference;
- } else if (quantityDifference < 0) {
- data.entryType = "Negative Adjmt.";
- data.quantity = -Math.abs(quantityDifference);
- } else {
- // No change in quantity, but readableId / expirationDate might have changed
- if (inventoryAdjustment.trackedEntityId && readableId !== undefined) {
- const trackedEntityUpdate = await client
- .from("trackedEntity")
- .update({ readableId })
- .eq("id", inventoryAdjustment.trackedEntityId);
- if (trackedEntityUpdate.error) return trackedEntityUpdate;
- }
- if (inventoryAdjustment.trackedEntityId) {
- const expiryOverride = await applyExpirationOverride(
- inventoryAdjustment.trackedEntityId
- );
- if (expiryOverride?.error) return expiryOverride;
- }
- return { data: null };
- }
- }
-
- // Resolve the correct stock target for a negative adjustment when:
- // - readableId is provided: always resolve via serial number (currentQuantity
- // may point to the wrong row due to loose null == undefined matching), OR
- // - No currentQuantity found at all: fall back to untracked (legacy) stock.
- //
- // 1. If readableId is provided, adjust the entity with that serial number that
- // has positive stock. If not found, return an error — never silently fall back.
- // 2. If no readableId, fall back to untracked (legacy) stock.
- if (
- data.entryType === "Negative Adjmt." &&
- (readableId || !currentQuantity)
- ) {
- if (readableId) {
- // storageUnitQuantities is scoped to this item + location.
- // Filter to positive-qty rows only — multiple entities can share a readableId
- // if the same serial was used across repeated positive adjustments.
- const resolvedQtyRow = storageUnitQuantities?.data?.find(
- (q) =>
- q.readableId === readableId &&
- q.trackedEntityId != null &&
- (q.quantity ?? 0) > 0
- );
- if (!resolvedQtyRow) {
- return { error: "Serial number not found" };
- }
- const resolvedId = resolvedQtyRow.trackedEntityId as string;
- const resolvedQty = resolvedQtyRow.quantity ?? 0;
- if (data.quantity > resolvedQty) {
- return { error: "Insufficient quantity for negative adjustment" };
- }
- const entityUpdate = await client
- .from("trackedEntity")
- .update({ quantity: resolvedQty - data.quantity, readableId })
- .eq("id", resolvedId);
- if (entityUpdate.error) return entityUpdate;
- return client
- .from("itemLedger")
- .insert([
- {
- ...data,
- trackedEntityId: resolvedId,
- quantity: -Math.abs(data.quantity)
- }
- ])
- .select("*")
- .single();
- }
- // No serial number provided. Prefer untracked (legacy) stock in this bin.
- const legacyRow = storageUnitQuantities?.data?.find(
- (q) => q.trackedEntityId == null && q.storageUnitId == data.storageUnitId
- );
- if (legacyRow) {
- const legacyQty = legacyRow.quantity ?? 0;
- if (data.quantity > legacyQty) {
- return { error: "Insufficient quantity for negative adjustment" };
- }
- return client
- .from("itemLedger")
- .insert([
- { ...data, trackedEntityId: null, quantity: -Math.abs(data.quantity) }
- ])
- .select("*")
- .single();
- }
-
- // No untracked stock in the bin — resolve a tracked entity sitting in the
- // same storage unit so a negative adjustment can decrement identifiable
- // tracked stock (e.g. serial/batch entities created without a serial number,
- // adjusted via the "Update Inventory" button where no trackedEntityId is
- // pre-selected). Ambiguous when more than one entity holds stock there.
- const trackedRowsInUnit = (storageUnitQuantities?.data ?? []).filter(
- (q) =>
- q.trackedEntityId != null &&
- q.storageUnitId == data.storageUnitId &&
- (q.quantity ?? 0) > 0
- );
- if (trackedRowsInUnit.length === 0) {
- return { error: "Insufficient quantity for negative adjustment" };
- }
- if (trackedRowsInUnit.length > 1) {
- return {
- error:
- "Multiple tracked entities in this storage unit — select a specific row to adjust"
- };
- }
- const targetRow = trackedRowsInUnit[0];
- const targetQty = targetRow.quantity ?? 0;
- if (data.quantity > targetQty) {
- return { error: "Insufficient quantity for negative adjustment" };
- }
- const targetId = targetRow.trackedEntityId as string;
- const entityUpdate = await client
- .from("trackedEntity")
- .update({ quantity: targetQty - data.quantity })
- .eq("id", targetId);
- if (entityUpdate.error) return entityUpdate;
- return client
- .from("itemLedger")
- .insert([
- {
- ...data,
- trackedEntityId: targetId,
- quantity: -Math.abs(data.quantity)
- }
- ])
- .select("*")
- .single();
- }
-
- // Check if it's a negative adjustment and if the quantity is sufficient
- if (data.entryType === "Negative Adjmt.") {
- if (data.quantity > currentQuantityOnHand) {
- return {
- error: "Insufficient quantity for negative adjustment"
- };
- }
- data.quantity = -Math.abs(data.quantity);
- }
-
- if (inventoryAdjustment.trackedEntityId) {
- if (currentQuantity) {
- // Update the existing tracked entity
- const trackedEntityUpdate = await client
- .from("trackedEntity")
- .update({
- quantity: data.quantity + currentQuantityOnHand,
- readableId: readableId
- })
- .eq("id", inventoryAdjustment.trackedEntityId);
-
- if (trackedEntityUpdate.error) {
- return trackedEntityUpdate;
- }
-
- const expiryOverride = await applyExpirationOverride(
- inventoryAdjustment.trackedEntityId
- );
- if (expiryOverride?.error) return expiryOverride;
- } else {
- const [item, expirationDate] = await Promise.all([
- client.from("item").select("*").eq("id", data.itemId).single(),
- resolveExpirationForNewEntity()
- ]);
-
- // Stamp the trace blob so the popover Source / Override steps can show
- // the entity originated from a manual inventory adjustment, by whom,
- // and when. Mirrors the receipt/job markers consumed by
- // ExpiryTracePopover (attrs.Receipt, attrs.Job).
- const adjustmentStamp = {
- userId: data.createdBy,
- at: now(getLocalTimeZone()).toAbsoluteString(),
- reason: comment?.trim() || "Created via inventory adjustment"
- };
- const attributes: Record<string, unknown> = {
- "Inventory Adjustment": adjustmentStamp,
- ...(expirationDate
- ? {
- expiryOverrides: [
- {
- previous: null,
- next: expirationDate,
- reason: adjustmentStamp.reason,
- source: "Inventory Adjustment",
- userId: adjustmentStamp.userId,
- at: adjustmentStamp.at
- }
- ]
- }
- : {})
- };
-
- // Create a new tracked entity
- const trackedEntityInsert = await client
- .from("trackedEntity")
- .insert([
- {
- id: inventoryAdjustment.trackedEntityId,
- sourceDocument: "Item",
- sourceDocumentId: data.itemId,
- sourceDocumentReadableId: item.data?.readableIdWithRevision,
- readableId: readableId,
- quantity: data.quantity,
- status: "Available",
- expirationDate,
- attributes: attributes as unknown as Json,
- companyId: data.companyId,
- createdBy: data.createdBy
- }
- ])
- .select("*")
- .single();
-
- if (trackedEntityInsert.error) {
- return trackedEntityInsert;
- }
- }
+ };
}
- return client.from("itemLedger").insert([data]).select("*").single();
+ return { data: result.data?.itemLedger ?? null, error: null };
}
// ===========================================================================
diff --git a/apps/erp/app/modules/inventory/types.ts b/apps/erp/app/modules/inventory/types.ts
index 22c6795957..f7c4fa7648 100644
--- a/apps/erp/app/modules/inventory/types.ts
+++ b/apps/erp/app/modules/inventory/types.ts
@@ -4,6 +4,8 @@ import type {
getInventoryCountLines,
getInventoryCounts,
getInventoryItems,
+ getInventoryValuation,
+ getInventoryValuationTieOut,
getItemLedgerPage,
getKanbans,
getReceiptLines,
@@ -29,6 +31,14 @@ export type InventoryItem = NonNullable<
Awaited<ReturnType<typeof getInventoryItems>>["data"]
>[number];
+export type InventoryValuationRow = NonNullable<
+ Awaited<ReturnType<typeof getInventoryValuation>>["data"]
+>[number];
+
+export type InventoryTieOutRow = NonNullable<
+ Awaited<ReturnType<typeof getInventoryValuationTieOut>>["data"]
+>[number];
+
export type ItemLedger = NonNullable<
Awaited<ReturnType<typeof getItemLedgerPage>>["data"]
>[number];
diff --git a/apps/erp/app/modules/inventory/ui/StockMovements/StockMovementsTable.tsx b/apps/erp/app/modules/inventory/ui/StockMovements/StockMovementsTable.tsx
index b1983730cd..10d2dca562 100644
--- a/apps/erp/app/modules/inventory/ui/StockMovements/StockMovementsTable.tsx
+++ b/apps/erp/app/modules/inventory/ui/StockMovements/StockMovementsTable.tsx
@@ -338,7 +338,7 @@ const StockMovementsTable = memo(
}}
renderExpandedRow={renderExpandedRow}
canExpandRow={canExpandRow}
- title={t`Stock Movements`}
+ title={t`Inventory Movements`}
table="itemLedger"
withSavedView
/>
diff --git a/apps/erp/app/modules/inventory/ui/Valuation/InventoryValuationWorkbench.tsx b/apps/erp/app/modules/inventory/ui/Valuation/InventoryValuationWorkbench.tsx
new file mode 100644
index 0000000000..748725d858
--- /dev/null
+++ b/apps/erp/app/modules/inventory/ui/Valuation/InventoryValuationWorkbench.tsx
@@ -0,0 +1,672 @@
+import {
+ Button,
+ cn,
+ DatePicker,
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuRadioGroup,
+ DropdownMenuRadioItem,
+ DropdownMenuTrigger,
+ HStack,
+ Popover,
+ PopoverContent,
+ PopoverHeader,
+ PopoverTrigger,
+ VStack
+} from "@carbon/react";
+import { parseDate } from "@internationalized/date";
+import { Trans, useLingui } from "@lingui/react/macro";
+import type { ColumnDef } from "@tanstack/react-table";
+import { useCallback, useMemo, useState } from "react";
+import {
+ LuChevronDown,
+ LuChevronRight,
+ LuInfo,
+ LuScale,
+ LuTriangleAlert
+} from "react-icons/lu";
+import { useFetcher } from "react-router";
+import { Hyperlink, ItemThumbnail, Table } from "~/components";
+import { Enumerable } from "~/components/Enumerable";
+import { useUnitOfMeasure } from "~/components/Form/UnitOfMeasure";
+import {
+ useCurrencyFormatter,
+ usePercentFormatter,
+ usePermissions,
+ useUrlParams
+} from "~/hooks";
+import type {
+ InventoryTieOutRow,
+ InventoryValuationRow
+} from "~/modules/inventory";
+import { path } from "~/utils/path";
+
+type InventoryValuationWorkbenchProps = {
+ rows: InventoryValuationRow[];
+ tieOut: InventoryTieOutRow[] | null;
+ // The tie-out query failed — distinct from "accounting disabled" (null).
+ tieOutError?: boolean;
+ asOfDate: string;
+ groupBy: "location" | "item";
+ locationId: string | null;
+ locations: { id: string; name: string }[];
+};
+
+// A group row is a location (default grouping) or an item; its details are the
+// rows of the other dimension. One union type so a single ColumnDef set renders
+// both, branching on `kind` — the ARAPWorkbench heterogeneous-tree pattern.
+type ValuationRow =
+ | {
+ kind: "group";
+ id: string;
+ label: string;
+ // Set when grouping by item — renders the standard ItemThumbnail +
+ // stacked readableId/name cell (InventoryTable precedent).
+ item?: Pick<
+ InventoryValuationRow,
+ "itemId" | "readableIdWithRevision" | "name" | "thumbnailPath" | "type"
+ >;
+ quantityOnHand: number;
+ quantityOnHold: number;
+ quantityRejected: number;
+ totalValue: number;
+ pctOfTotal: number;
+ }
+ | ({
+ kind: "detail";
+ rowId: string;
+ groupId: string;
+ pctOfTotal: number;
+ } & InventoryValuationRow);
+
+// Mirrors ARAPWorkbench: swallow floating-point dust in the subledger-vs-GL
+// comparison.
+const VARIANCE_EPSILON = 0.005;
+
+export function InventoryValuationWorkbench({
+ rows,
+ tieOut,
+ tieOutError,
+ asOfDate,
+ groupBy,
+ locationId,
+ locations
+}: InventoryValuationWorkbenchProps) {
+ const { t } = useLingui();
+ const [, setParams] = useUrlParams();
+ const currencyFormatter = useCurrencyFormatter();
+ const percentFormatter = usePercentFormatter();
+ const permissions = usePermissions();
+ const reconcileFetcher = useFetcher<object>();
+ const unitOfMeasures = useUnitOfMeasure();
+
+ const money = useCallback(
+ (n: number) => currencyFormatter.format(Number(n)),
+ [currencyFormatter]
+ );
+ const quantity = useCallback((n: number) => Number(n).toLocaleString(), []);
+
+ const isDated = asOfDate < new Date().toISOString().slice(0, 10);
+
+ const grandTotal = useMemo(
+ () => rows.reduce((acc, r) => acc + Number(r.totalValue), 0),
+ [rows]
+ );
+
+ // Group by the selected dimension; details are the other dimension's rows.
+ const { groups, childrenByGroup } = useMemo(() => {
+ const byGroup = new Map<
+ string,
+ { label: string; children: InventoryValuationRow[] }
+ >();
+ for (const r of rows) {
+ const key = groupBy === "location" ? r.locationId : r.itemId;
+ const label =
+ groupBy === "location"
+ ? r.locationName
+ : `${r.readableIdWithRevision} · ${r.name}`;
+ const entry = byGroup.get(key) ?? { label, children: [] };
+ entry.children.push(r);
+ byGroup.set(key, entry);
+ }
+ const sorted = [...byGroup.entries()].sort(([, a], [, b]) =>
+ a.label.localeCompare(b.label)
+ );
+ const groupRows = sorted.map(([id, { label, children }]) => ({
+ kind: "group" as const,
+ id,
+ label,
+ item:
+ groupBy === "item" && children[0]
+ ? {
+ itemId: children[0].itemId,
+ readableIdWithRevision: children[0].readableIdWithRevision,
+ name: children[0].name,
+ thumbnailPath: children[0].thumbnailPath,
+ type: children[0].type
+ }
+ : undefined,
+ quantityOnHand: children.reduce(
+ (s, c) => s + Number(c.quantityOnHand),
+ 0
+ ),
+ quantityOnHold: children.reduce(
+ (s, c) => s + Number(c.quantityOnHold),
+ 0
+ ),
+ quantityRejected: children.reduce(
+ (s, c) => s + Number(c.quantityRejected),
+ 0
+ ),
+ totalValue: children.reduce((s, c) => s + Number(c.totalValue), 0),
+ pctOfTotal:
+ grandTotal === 0
+ ? 0
+ : children.reduce((s, c) => s + Number(c.totalValue), 0) / grandTotal
+ }));
+ const childMap: Record<string, InventoryValuationRow[]> = {};
+ for (const [id, { children }] of sorted) childMap[id] = children;
+ return { groups: groupRows, childrenByGroup: childMap };
+ }, [rows, groupBy, grandTotal]);
+
+ const [expandedIds, setExpandedIds] = useState<Set<string>>(new Set());
+
+ const toggleExpand = useCallback((id: string) => {
+ setExpandedIds((prev) => {
+ const next = new Set(prev);
+ if (next.has(id)) next.delete(id);
+ else next.add(id);
+ return next;
+ });
+ }, []);
+
+ // Flatten groups (roots), expanded details, and a grand-total row.
+ const displayRows = useMemo<ValuationRow[]>(() => {
+ const out: ValuationRow[] = [];
+ for (const g of groups) {
+ out.push(g);
+ if (expandedIds.has(g.id)) {
+ for (const r of childrenByGroup[g.id] ?? []) {
+ out.push({
+ kind: "detail",
+ rowId: `${r.locationId}:${r.itemId}`,
+ groupId: g.id,
+ pctOfTotal:
+ grandTotal === 0 ? 0 : Number(r.totalValue) / grandTotal,
+ ...r
+ });
+ }
+ }
+ }
+ if (groups.length > 0) {
+ out.push({
+ kind: "group",
+ id: "grand-total",
+ label: t`Total`,
+ quantityOnHand: groups.reduce((s, g) => s + g.quantityOnHand, 0),
+ quantityOnHold: groups.reduce((s, g) => s + g.quantityOnHold, 0),
+ quantityRejected: groups.reduce((s, g) => s + g.quantityRejected, 0),
+ totalValue: grandTotal,
+ pctOfTotal: grandTotal === 0 ? 0 : 1
+ });
+ }
+ return out;
+ }, [groups, childrenByGroup, expandedIds, grandTotal, t]);
+
+ const detailLabel = useCallback(
+ (r: Extract<ValuationRow, { kind: "detail" }>) =>
+ groupBy === "location"
+ ? `${r.readableIdWithRevision} · ${r.name}`
+ : r.locationName,
+ [groupBy]
+ );
+
+ const columns = useMemo<ColumnDef<ValuationRow>[]>(() => {
+ return [
+ {
+ id: "label",
+ header:
+ groupBy === "location" ? t`Location / Item` : t`Item / Location`,
+ cell: ({ row }) => {
+ const r = row.original;
+ if (r.kind === "group") {
+ const kids = childrenByGroup[r.id] ?? [];
+ const isExpanded = expandedIds.has(r.id);
+ return (
+ <div className="flex items-center">
+ <div className="w-5 shrink-0 flex items-center justify-center self-center">
+ {kids.length > 0 ? (
+ <button
+ type="button"
+ aria-label={isExpanded ? t`Collapse` : t`Expand`}
+ className="text-muted-foreground hover:text-foreground"
+ onClick={(e) => {
+ e.stopPropagation();
+ toggleExpand(r.id);
+ }}
+ >
+ {isExpanded ? (
+ <LuChevronDown className="size-4" />
+ ) : (
+ <LuChevronRight className="size-4" />
+ )}
+ </button>
+ ) : null}
+ </div>
+ {r.item ? (
+ <HStack className="py-1">
+ <ItemThumbnail
+ size="sm"
+ thumbnailPath={r.item.thumbnailPath}
+ // @ts-expect-error
+ type={r.item.type}
+ />
+ <Hyperlink
+ to={path.to.inventoryItemActivity(r.item.itemId)}
+ >
+ <VStack spacing={0}>
+ {r.item.readableIdWithRevision}
+ <div className="w-full truncate text-muted-foreground text-xs">
+ {r.item.name}
+ </div>
+ </VStack>
+ </Hyperlink>
+ </HStack>
+ ) : (
+ <span className="font-semibold">{r.label}</span>
+ )}
+ </div>
+ );
+ }
+ return (
+ <div className="flex items-center">
+ <div
+ aria-hidden
+ className="w-5 shrink-0 border-l border-border -my-2"
+ />
+ <div className="flex items-center gap-2 pl-2 py-1">
+ {groupBy === "location" ? (
+ <HStack className="py-1">
+ <ItemThumbnail
+ size="sm"
+ thumbnailPath={r.thumbnailPath}
+ // @ts-expect-error
+ type={r.type}
+ />
+ <Hyperlink to={path.to.inventoryItemActivity(r.itemId)}>
+ <VStack spacing={0}>
+ {r.readableIdWithRevision}
+ <div className="w-full truncate text-muted-foreground text-xs">
+ {r.name}
+ </div>
+ </VStack>
+ </Hyperlink>
+ </HStack>
+ ) : (
+ <Enumerable value={r.locationName} />
+ )}
+ </div>
+ </div>
+ );
+ },
+ meta: {
+ exportValue: (row: ValuationRow) =>
+ row.kind === "group" ? row.label : detailLabel(row)
+ }
+ },
+ {
+ id: "method",
+ header: t`Costing Method`,
+ cell: ({ row }) =>
+ row.original.kind === "detail" ? (
+ <Enumerable value={row.original.costingMethod} />
+ ) : null,
+ meta: {
+ exportValue: (row: ValuationRow) =>
+ row.kind === "detail" ? row.costingMethod : null
+ }
+ },
+ {
+ id: "qtyOnHand",
+ header: t`Qty On Hand`,
+ cell: ({ row }) => (
+ <span
+ className={cn(
+ "tabular-nums",
+ Number(row.original.quantityOnHand) < 0 && "text-destructive"
+ )}
+ >
+ {quantity(row.original.quantityOnHand)}
+ </span>
+ ),
+ meta: {
+ exportValue: (row: ValuationRow) => row.quantityOnHand
+ }
+ },
+ {
+ id: "onHold",
+ header: t`On Hold`,
+ cell: ({ row }) =>
+ Number(row.original.quantityOnHold) !== 0 ? (
+ <span className="tabular-nums">
+ {quantity(row.original.quantityOnHold)}
+ </span>
+ ) : null,
+ meta: {
+ exportValue: (row: ValuationRow) => row.quantityOnHold
+ }
+ },
+ {
+ id: "rejected",
+ header: t`Rejected`,
+ cell: ({ row }) =>
+ Number(row.original.quantityRejected) !== 0 ? (
+ <span className="tabular-nums">
+ {quantity(row.original.quantityRejected)}
+ </span>
+ ) : null,
+ meta: {
+ exportValue: (row: ValuationRow) => row.quantityRejected
+ }
+ },
+ {
+ id: "uom",
+ header: t`Unit of Measure`,
+ cell: ({ row }) => {
+ const r = row.original;
+ if (r.kind !== "detail") return null;
+ const unitOfMeasure = unitOfMeasures.find(
+ (uom) => uom.value === r.unitOfMeasureCode
+ );
+ return (
+ <Enumerable value={unitOfMeasure?.label ?? r.unitOfMeasureCode} />
+ );
+ },
+ meta: {
+ exportValue: (row: ValuationRow) =>
+ row.kind === "detail"
+ ? (unitOfMeasures.find(
+ (uom) => uom.value === row.unitOfMeasureCode
+ )?.label ?? row.unitOfMeasureCode)
+ : null
+ }
+ },
+ {
+ id: "unitCost",
+ header: t`Unit Cost`,
+ cell: ({ row }) =>
+ row.original.kind === "detail" ? (
+ <span className="tabular-nums">{money(row.original.unitCost)}</span>
+ ) : null,
+ meta: {
+ exportValue: (row: ValuationRow) =>
+ row.kind === "detail" ? row.unitCost : null
+ }
+ },
+ {
+ id: "totalValue",
+ header: t`Total Value`,
+ cell: ({ row }) => {
+ const r = row.original;
+ return (
+ <span
+ className={cn(
+ "tabular-nums",
+ r.kind === "group" && "font-semibold",
+ Number(r.totalValue) < 0 && "text-destructive"
+ )}
+ >
+ {money(r.totalValue)}
+ </span>
+ );
+ },
+ meta: {
+ exportValue: (row: ValuationRow) => row.totalValue
+ }
+ },
+ {
+ id: "pctOfTotal",
+ header: t`% of Total`,
+ cell: ({ row }) => (
+ <span className="tabular-nums text-muted-foreground">
+ {percentFormatter.format(row.original.pctOfTotal)}
+ </span>
+ ),
+ meta: {
+ exportValue: (row: ValuationRow) => row.pctOfTotal
+ }
+ }
+ ];
+ }, [
+ t,
+ groupBy,
+ childrenByGroup,
+ expandedIds,
+ toggleExpand,
+ detailLabel,
+ money,
+ quantity,
+ percentFormatter,
+ unitOfMeasures
+ ]);
+
+ const hasVariance = (tieOut ?? []).some(
+ (row) => Math.abs(Number(row.variance)) > VARIANCE_EPSILON
+ );
+ const tieOutTotal = useMemo(() => {
+ const list = tieOut ?? [];
+ return {
+ subledgerValue: list.reduce((s, r) => s + Number(r.subledgerValue), 0),
+ glBalance: list.reduce((s, r) => s + Number(r.glBalance), 0),
+ variance: list.reduce((s, r) => s + Number(r.variance), 0)
+ };
+ }, [tieOut]);
+
+ const filters = (
+ <HStack>
+ {tieOutError ? (
+ // The tie-out query failed — say so; rendering nothing would read as
+ // "no variance" on a financial control surface.
+ <Button variant="destructive" leftIcon={<LuTriangleAlert />} isDisabled>
+ <Trans>Tie-Out unavailable</Trans>
+ </Button>
+ ) : null}
+ {tieOut && tieOut.length > 0 ? (
+ <Popover>
+ <PopoverTrigger asChild>
+ <Button
+ variant={hasVariance ? "destructive" : "secondary"}
+ leftIcon={hasVariance ? <LuTriangleAlert /> : <LuScale />}
+ >
+ <Trans>Tie-Out</Trans>
+ </Button>
+ </PopoverTrigger>
+ <PopoverContent side="bottom" align="end" className="w-96">
+ <PopoverHeader>
+ <Trans>GL Tie-Out</Trans>
+ </PopoverHeader>
+ <div className="flex flex-col gap-3 p-4">
+ {locationId ? (
+ // The tie-out (and its Reconcile journal) always covers the
+ // whole company — flag that while the table is filtered to a
+ // single location so the two aren't read as the same scope.
+ <span className="text-xs text-muted-foreground">
+ <Trans>Company-wide — includes all locations</Trans>
+ </span>
+ ) : null}
+ {tieOut.map((row) => {
+ const rowVariance =
+ Math.abs(Number(row.variance)) > VARIANCE_EPSILON;
+ return (
+ <div key={row.accountKind} className="flex flex-col gap-1">
+ <span className="text-sm font-medium">
+ {row.accountName ??
+ (row.accountKind === "rawMaterials"
+ ? t`Raw Materials`
+ : t`Finished Goods`)}
+ </span>
+ <div className="flex items-center justify-between text-sm">
+ <span className="text-muted-foreground">
+ <Trans>Subledger</Trans>
+ </span>
+ <span className="tabular-nums">
+ {money(row.subledgerValue)}
+ </span>
+ </div>
+ <div className="flex items-center justify-between text-sm">
+ <span className="text-muted-foreground">
+ <Trans>GL</Trans>
+ </span>
+ <span className="tabular-nums">
+ {money(row.glBalance)}
+ </span>
+ </div>
+ <div className="flex items-center justify-between text-sm">
+ <span className="text-muted-foreground">
+ <Trans>Variance</Trans>
+ </span>
+ <span
+ className={cn(
+ "tabular-nums font-semibold",
+ rowVariance
+ ? "text-red-600 dark:text-red-400"
+ : "text-emerald-600 dark:text-emerald-400"
+ )}
+ >
+ {money(row.variance)}
+ </span>
+ </div>
+ </div>
+ );
+ })}
+ <div className="flex items-center justify-between text-sm border-t border-border pt-3">
+ <span className="text-muted-foreground">
+ <Trans>Total Variance</Trans>
+ </span>
+ <span
+ className={cn(
+ "tabular-nums font-semibold flex items-center gap-1",
+ hasVariance
+ ? "text-red-600 dark:text-red-400"
+ : "text-emerald-600 dark:text-emerald-400"
+ )}
+ >
+ {hasVariance ? (
+ <LuTriangleAlert className="size-3.5" />
+ ) : null}
+ {money(tieOutTotal.variance)}
+ </span>
+ </div>
+ {hasVariance && permissions.can("create", "accounting") ? (
+ <reconcileFetcher.Form
+ method="post"
+ action={path.to.inventoryValuationReconcile}
+ >
+ <input type="hidden" name="asOfDate" value={asOfDate} />
+ <Button
+ type="submit"
+ variant="secondary"
+ className="w-full"
+ leftIcon={<LuScale />}
+ isLoading={reconcileFetcher.state !== "idle"}
+ isDisabled={reconcileFetcher.state !== "idle"}
+ >
+ <Trans>Reconcile</Trans>
+ </Button>
+ </reconcileFetcher.Form>
+ ) : null}
+ </div>
+ </PopoverContent>
+ </Popover>
+ ) : null}
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button variant="secondary" rightIcon={<LuChevronDown />}>
+ {groupBy === "location" ? (
+ <Trans>By Location</Trans>
+ ) : (
+ <Trans>By Item</Trans>
+ )}
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="start" className="w-48">
+ <DropdownMenuRadioGroup value={groupBy}>
+ <DropdownMenuRadioItem
+ value="location"
+ onClick={() => setParams({ groupBy: "location" })}
+ >
+ <Trans>By Location</Trans>
+ </DropdownMenuRadioItem>
+ <DropdownMenuRadioItem
+ value="item"
+ onClick={() => setParams({ groupBy: "item" })}
+ >
+ <Trans>By Item</Trans>
+ </DropdownMenuRadioItem>
+ </DropdownMenuRadioGroup>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button variant="secondary" rightIcon={<LuChevronDown />}>
+ {locations.find((location) => location.id === locationId)?.name ?? (
+ <Trans>All Locations</Trans>
+ )}
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="start" className="w-48">
+ <DropdownMenuRadioGroup value={locationId ?? "all"}>
+ <DropdownMenuRadioItem
+ value="all"
+ onClick={() => setParams({ locationId: undefined })}
+ >
+ <Trans>All Locations</Trans>
+ </DropdownMenuRadioItem>
+ {locations.map((location) => (
+ <DropdownMenuRadioItem
+ key={location.id}
+ value={location.id}
+ onClick={() => setParams({ locationId: location.id })}
+ >
+ {location.name}
+ </DropdownMenuRadioItem>
+ ))}
+ </DropdownMenuRadioGroup>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ <span className="text-sm text-muted-foreground whitespace-nowrap">
+ <Trans>As of:</Trans>
+ </span>
+ <DatePicker
+ size="sm"
+ value={parseDate(asOfDate)}
+ onChange={(value) =>
+ setParams({ asOfDate: value?.toString() ?? asOfDate })
+ }
+ />
+ </HStack>
+ );
+
+ return (
+ <VStack spacing={0} className="h-full">
+ {isDated ? (
+ <div className="w-full flex items-center gap-2 px-4 py-2 text-sm text-muted-foreground border-b border-border">
+ <LuInfo className="size-4 shrink-0" />
+ <Trans>
+ Values apply today's unit costs to historical quantities.
+ </Trans>
+ </div>
+ ) : null}
+ <div className="flex-1 w-full">
+ <Table<ValuationRow>
+ data={displayRows}
+ columns={columns}
+ count={displayRows.length}
+ title={t`Inventory Valuation`}
+ primaryAction={filters}
+ defaultColumnPinning={{ left: ["label"] }}
+ />
+ </div>
+ </VStack>
+ );
+}
diff --git a/apps/erp/app/modules/inventory/ui/Valuation/index.ts b/apps/erp/app/modules/inventory/ui/Valuation/index.ts
new file mode 100644
index 0000000000..0b96d7fccb
--- /dev/null
+++ b/apps/erp/app/modules/inventory/ui/Valuation/index.ts
@@ -0,0 +1 @@
+export * from "./InventoryValuationWorkbench";
diff --git a/apps/erp/app/modules/inventory/ui/index.ts b/apps/erp/app/modules/inventory/ui/index.ts
index 59178c4107..f5be59f0da 100644
--- a/apps/erp/app/modules/inventory/ui/index.ts
+++ b/apps/erp/app/modules/inventory/ui/index.ts
@@ -8,5 +8,6 @@ export * from "./Receipts";
export * from "./ShippingMethods";
export * from "./StorageTypes";
export * from "./StorageUnits";
+export * from "./Valuation";
export * from "./WarehouseTransfers";
export { useInventorySubmodules };
diff --git a/apps/erp/app/modules/inventory/ui/useInventorySubmodules.tsx b/apps/erp/app/modules/inventory/ui/useInventorySubmodules.tsx
index 22c7e1f578..61fe6e5813 100644
--- a/apps/erp/app/modules/inventory/ui/useInventorySubmodules.tsx
+++ b/apps/erp/app/modules/inventory/ui/useInventorySubmodules.tsx
@@ -2,6 +2,7 @@ import { useLingui } from "@lingui/react/macro";
import {
LuArrowDownUp,
LuArrowRightLeft,
+ LuChartBar,
LuClipboardCheck,
LuClipboardList,
LuHandCoins,
@@ -75,6 +76,13 @@ export default function useInventorySubmodules() {
role: "employee",
icon: <LuScanQrCode />
},
+ {
+ name: t`Movements`,
+ to: path.to.stockMovements,
+ role: "employee",
+ icon: <LuArrowDownUp />,
+ table: "itemLedger"
+ },
{
name: t`Quantities`,
to: path.to.inventory,
@@ -82,13 +90,6 @@ export default function useInventorySubmodules() {
icon: <LuTally5 />,
table: "inventory"
},
- {
- name: t`Stock Movements`,
- to: path.to.stockMovements,
- role: "employee",
- icon: <LuArrowDownUp />,
- table: "itemLedger"
- },
{
name: t`Tracked Entities`,
to: path.to.trackedEntities,
@@ -100,7 +101,19 @@ export default function useInventorySubmodules() {
to: path.to.traceability,
role: "employee",
icon: <LuNetwork />
- }
+ },
+ // Valuation exposes unit costs and GL balances — gated on accounting
+ // view, not just the employee role (spec: grill Q6).
+ ...(permissions.can("view", "accounting")
+ ? [
+ {
+ name: t`Valuation`,
+ to: path.to.inventoryValuation,
+ role: "employee" as const,
+ icon: <LuChartBar />
+ }
+ ]
+ : [])
]
},
{
diff --git a/apps/erp/app/modules/invoicing/ui/Workbench/ARAPWorkbench.tsx b/apps/erp/app/modules/invoicing/ui/Workbench/ARAPWorkbench.tsx
index 20e18c8d54..b433a55bb3 100644
--- a/apps/erp/app/modules/invoicing/ui/Workbench/ARAPWorkbench.tsx
+++ b/apps/erp/app/modules/invoicing/ui/Workbench/ARAPWorkbench.tsx
@@ -2,16 +2,16 @@ import {
Button,
cn,
DatePicker,
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuRadioGroup,
+ DropdownMenuRadioItem,
+ DropdownMenuTrigger,
HStack,
Popover,
PopoverContent,
PopoverHeader,
PopoverTrigger,
- Select,
- SelectContent,
- SelectItem,
- SelectTrigger,
- SelectValue,
Tooltip,
TooltipContent,
TooltipTrigger,
@@ -502,22 +502,33 @@ export function ARAPWorkbench({
</TooltipContent>
</Tooltip>
) : null}
- <Select
- value={agingMethod}
- onValueChange={(value) => setParams({ agingMethod: value })}
- >
- <SelectTrigger size="sm" className="w-[180px]">
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- <SelectItem value="dueDate">
- <Trans>By Due Date</Trans>
- </SelectItem>
- <SelectItem value="documentDate">
- <Trans>By Document Date</Trans>
- </SelectItem>
- </SelectContent>
- </Select>
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button variant="secondary" rightIcon={<LuChevronDown />}>
+ {agingMethod === "dueDate" ? (
+ <Trans>By Due Date</Trans>
+ ) : (
+ <Trans>By Document Date</Trans>
+ )}
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="start" className="w-48">
+ <DropdownMenuRadioGroup value={agingMethod}>
+ <DropdownMenuRadioItem
+ value="dueDate"
+ onClick={() => setParams({ agingMethod: "dueDate" })}
+ >
+ <Trans>By Due Date</Trans>
+ </DropdownMenuRadioItem>
+ <DropdownMenuRadioItem
+ value="documentDate"
+ onClick={() => setParams({ agingMethod: "documentDate" })}
+ >
+ <Trans>By Document Date</Trans>
+ </DropdownMenuRadioItem>
+ </DropdownMenuRadioGroup>
+ </DropdownMenuContent>
+ </DropdownMenu>
<span className="text-sm text-muted-foreground whitespace-nowrap">
<Trans>As of:</Trans>
</span>
diff --git a/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json b/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json
index a43ba9a135..1460d003e5 100644
--- a/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json
+++ b/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json
@@ -1,6 +1,6 @@
{
- "generated": "2026-07-15T04:00:40.500Z",
- "totalTools": 1331,
+ "generated": "2026-07-15T06:27:13.763Z",
+ "totalTools": 1334,
"modules": 15,
"tools": [
{
@@ -4433,6 +4433,93 @@
]
}
},
+ {
+ "name": "inventory_getInventoryValuation",
+ "module": "inventory",
+ "classification": "READ",
+ "description": "get inventory valuation",
+ "paramCount": 2,
+ "serviceParams": [
+ "client",
+ "companyId",
+ "args"
+ ],
+ "injectAuth": [
+ "companyId"
+ ],
+ "schema": {
+ "type": "object",
+ "properties": {
+ "asOfDate": {
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "locationId": {
+ "type": [
+ "string",
+ "null"
+ ]
+ }
+ }
+ }
+ },
+ {
+ "name": "inventory_getInventoryValuationTieOut",
+ "module": "inventory",
+ "classification": "READ",
+ "description": "get inventory valuation tie out",
+ "paramCount": 1,
+ "serviceParams": [
+ "client",
+ "companyId",
+ "asOfDate"
+ ],
+ "injectAuth": [
+ "companyId"
+ ],
+ "schema": {
+ "type": "object",
+ "properties": {
+ "asOfDate": {
+ "type": [
+ "string",
+ "null"
+ ]
+ }
+ }
+ }
+ },
+ {
+ "name": "inventory_createInventoryReconciliationJournal",
+ "module": "inventory",
+ "classification": "WRITE",
+ "description": "create inventory reconciliation journal",
+ "paramCount": 1,
+ "serviceParams": [
+ "client",
+ "db",
+ "companyId",
+ "args"
+ ],
+ "injectAuth": [
+ "companyId",
+ "createdBy",
+ "updatedBy"
+ ],
+ "schema": {
+ "type": "object",
+ "properties": {
+ "asOfDate": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "asOfDate"
+ ]
+ }
+ },
{
"name": "inventory_getKanbans",
"module": "inventory",
diff --git a/apps/erp/app/routes/x+/inventory+/stock-movements.tsx b/apps/erp/app/routes/x+/inventory+/stock-movements.tsx
index 1e683450ea..8eac108575 100644
--- a/apps/erp/app/routes/x+/inventory+/stock-movements.tsx
+++ b/apps/erp/app/routes/x+/inventory+/stock-movements.tsx
@@ -12,7 +12,7 @@ import { path } from "~/utils/path";
import { getGenericQueryFilters } from "~/utils/query";
export const handle: Handle = {
- breadcrumb: msg`Stock Movements`,
+ breadcrumb: msg`Movements`,
to: path.to.stockMovements
};
diff --git a/apps/erp/app/routes/x+/inventory+/valuation.reconcile.tsx b/apps/erp/app/routes/x+/inventory+/valuation.reconcile.tsx
new file mode 100644
index 0000000000..ac3ee1073c
--- /dev/null
+++ b/apps/erp/app/routes/x+/inventory+/valuation.reconcile.tsx
@@ -0,0 +1,48 @@
+import { assertIsPost, error, success } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import type { ActionFunctionArgs } from "react-router";
+import { data, redirect } from "react-router";
+import { createInventoryReconciliationJournal } from "~/modules/inventory";
+import { getDatabaseClient } from "~/services/database.server";
+import { path } from "~/utils/path";
+
+// Tie-out Reconcile action: drafts an adjusting journal that brings the GL
+// inventory accounts to the subledger valuation. The journal is Draft — the
+// accountant reviews and posts it from the Journals screen.
+export async function action({ request }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, companyId, userId } = await requirePermissions(request, {
+ create: "accounting"
+ });
+
+ const formData = await request.formData();
+ const asOfDate =
+ (formData.get("asOfDate") as string | null) ||
+ new Date().toISOString().slice(0, 10);
+
+ const result = await createInventoryReconciliationJournal(
+ client,
+ getDatabaseClient(),
+ companyId,
+ { asOfDate, userId }
+ );
+
+ if (result.error) {
+ return data(
+ {},
+ await flash(
+ request,
+ error(result.error, "Failed to create reconciliation journal")
+ )
+ );
+ }
+
+ throw redirect(
+ path.to.accountingJournals,
+ await flash(
+ request,
+ success("Draft reconciliation journal created — review and post it")
+ )
+ );
+}
diff --git a/apps/erp/app/routes/x+/inventory+/valuation.tsx b/apps/erp/app/routes/x+/inventory+/valuation.tsx
new file mode 100644
index 0000000000..325524bbb4
--- /dev/null
+++ b/apps/erp/app/routes/x+/inventory+/valuation.tsx
@@ -0,0 +1,90 @@
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { msg } from "@lingui/core/macro";
+import type { LoaderFunctionArgs } from "react-router";
+import { useLoaderData } from "react-router";
+import {
+ getInventoryValuation,
+ getInventoryValuationTieOut,
+ InventoryValuationWorkbench
+} from "~/modules/inventory";
+import { getCompanySettings } from "~/modules/settings";
+import type { Handle } from "~/utils/handle";
+import { path } from "~/utils/path";
+
+export const handle: Handle = {
+ breadcrumb: msg`Valuation`,
+ to: path.to.inventoryValuation,
+ module: "inventory"
+};
+
+export async function loader({ request }: LoaderFunctionArgs) {
+ const { client, companyId } = await requirePermissions(request, {
+ view: "accounting"
+ });
+
+ const url = new URL(request.url);
+ const asOfDate =
+ url.searchParams.get("asOfDate") ?? new Date().toISOString().slice(0, 10);
+ const groupBy: "location" | "item" =
+ url.searchParams.get("groupBy") === "item" ? "item" : "location";
+ const locationId = url.searchParams.get("locationId") || null;
+
+ // The tie-out only means something when journals are being posted — skip it
+ // entirely when accounting is disabled (tieOut: null hides the panel).
+ const companySettings = await getCompanySettings(client, companyId);
+ const accountingEnabled =
+ (companySettings.data as { accountingEnabled?: boolean } | null)
+ ?.accountingEnabled ?? false;
+
+ const [valuation, tieOut, locations] = await Promise.all([
+ getInventoryValuation(client, companyId, { asOfDate, locationId }),
+ accountingEnabled
+ ? getInventoryValuationTieOut(client, companyId, asOfDate)
+ : Promise.resolve({ data: null, error: null }),
+ client
+ .from("location")
+ .select("id, name")
+ .eq("companyId", companyId)
+ .order("name")
+ ]);
+
+ // A failed valuation query must surface, not render as an empty report.
+ if (valuation.error) {
+ throw new Error(valuation.error.message);
+ }
+
+ return {
+ asOfDate,
+ groupBy,
+ locationId,
+ rows: valuation.data ?? [],
+ tieOut: tieOut.data ?? null,
+ // A failed tie-out must read as "unavailable", not "nothing to tie out" —
+ // this is a financial control surface.
+ tieOutError: Boolean(tieOut.error),
+ locations: locations.data ?? []
+ };
+}
+
+export default function InventoryValuationRoute() {
+ const {
+ asOfDate,
+ groupBy,
+ locationId,
+ rows,
+ tieOut,
+ tieOutError,
+ locations
+ } = useLoaderData<typeof loader>();
+ return (
+ <InventoryValuationWorkbench
+ rows={rows}
+ tieOut={tieOut}
+ tieOutError={tieOutError}
+ asOfDate={asOfDate}
+ groupBy={groupBy}
+ locationId={locationId}
+ locations={locations}
+ />
+ );
+}
diff --git a/apps/erp/app/utils/path.ts b/apps/erp/app/utils/path.ts
index e639490371..8d7d99c340 100644
--- a/apps/erp/app/utils/path.ts
+++ b/apps/erp/app/utils/path.ts
@@ -1081,6 +1081,8 @@ export const path = {
inventoryItemAdjustment: (id: string) =>
generatePath(`${x}/inventory/quantities/${id}/adjustment`),
inventoryRoot: `${x}/inventory`,
+ inventoryValuation: `${x}/inventory/valuation`,
+ inventoryValuationReconcile: `${x}/inventory/valuation/reconcile`,
stockMovements: `${x}/inventory/stock-movements`,
inventorySettings: `${x}/settings/inventory`,
invoicing: `${x}/invoicing`,
diff --git a/apps/mes/app/services/inventory.service.ts b/apps/mes/app/services/inventory.service.ts
index 7e685f570f..1ccbe4f2ae 100644
--- a/apps/mes/app/services/inventory.service.ts
+++ b/apps/mes/app/services/inventory.service.ts
@@ -436,6 +436,10 @@ export async function getPickedTrackedEntitiesForMaterial(
return [...byEntity.values()];
}
+// Thin wrapper over the post-inventory-adjustment edge function — the same
+// unified write path the ERP uses. The edge function books the item ledger,
+// cost layers, and (when companySettings.accountingEnabled) the GL journal in
+// one transaction, and owns the insufficient-quantity guard.
export async function insertManualInventoryAdjustment(
client: SupabaseClient<Database>,
inventoryAdjustment: z.infer<typeof inventoryAdjustmentValidator> & {
@@ -443,14 +447,38 @@ export async function insertManualInventoryAdjustment(
createdBy: string;
}
) {
- // Check if it's a negative adjustment and if the quantity is sufficient
- if (inventoryAdjustment.entryType === "Negative Adjmt.") {
- inventoryAdjustment.quantity = -Math.abs(inventoryAdjustment.quantity);
+ const { companyId, createdBy, entryType, ...adjustment } =
+ inventoryAdjustment;
+
+ const result = await client.functions.invoke<{
+ success: boolean;
+ itemLedger: { id: string } | null;
+ }>("post-inventory-adjustment", {
+ body: {
+ ...adjustment,
+ adjustmentType: entryType,
+ companyId,
+ userId: createdBy
+ }
+ });
+
+ if (result.error) {
+ // Supabase wraps non-2xx edge-fn responses in FunctionsHttpError with the
+ // body on error.context — pull the real message out so the route's string
+ // match on "Insufficient quantity..." keeps working (same pattern as
+ // x+/issue-tracked-entity.tsx).
+ let message = "Failed to create manual inventory adjustment";
+ const ctx = (result.error as { context?: Response })?.context;
+ if (ctx && typeof ctx.clone === "function") {
+ try {
+ const body = await ctx.clone().json();
+ if (body && typeof body.message === "string") message = body.message;
+ } catch {
+ // body wasn't JSON — keep the fallback
+ }
+ }
+ return { data: null, error: { message } };
}
- return client
- .from("itemLedger")
- .insert([inventoryAdjustment])
- .select("*")
- .single();
+ return { data: result.data?.itemLedger ?? null, error: null };
}
diff --git a/docs/content/docs/reference/accounting.mdx b/docs/content/docs/reference/accounting.mdx
index b9a581e936..c8235e8494 100644
--- a/docs/content/docs/reference/accounting.mdx
+++ b/docs/content/docs/reference/accounting.mdx
@@ -23,6 +23,7 @@ Every <Term id="posting">posting</Term> is a **<Term>journal</Term>** with balan
| Sales Invoice | Posting a sales invoice: receivable against revenue. |
| Purchase Receipt | Posting a receipt: inventory or WIP against GR/IR. |
| Purchase Invoice | Posting a supplier bill: payables, clearing GR/IR. |
+| Inventory Adjustment | Manual adjustments and inventory count variances: stock gains and losses against the inventory adjustment account. |
| Job Consumption / Production Event / Job Receipt | A job consuming material, logging time, and finishing into inventory. |
| Job Close | Sweeping a job's residual work-in-process to variance. |
| Asset Depreciation / Asset Disposal | Depreciation runs and asset write-offs. |
diff --git a/docs/content/docs/reference/inventory.mdx b/docs/content/docs/reference/inventory.mdx
index 3d9e66a257..4faa271302 100644
--- a/docs/content/docs/reference/inventory.mdx
+++ b/docs/content/docs/reference/inventory.mdx
@@ -30,11 +30,11 @@ On hand can go **negative**. Shipping, issuing to a job, and picking all post th
## Movements
-Two kinds of transfer move stock. A **warehouse transfer** moves it between locations, and is carried out as a <Term id="shipment">shipment</Term> out of one and a receipt into the other. A **stock transfer** moves it within a single location, between storage units. A manual **adjustment** writes straight to the ledger as a positive or negative entry — or a *Set Quantity* that books the difference to a target.
+Two kinds of transfer move stock. A **warehouse transfer** moves it between locations, and is carried out as a <Term id="shipment">shipment</Term> out of one and a receipt into the other. A **stock transfer** moves it within a single location, between storage units. A manual **adjustment** posts a positive or negative entry to the ledger, or a *Set Quantity* that books the difference to a target. When accounting is enabled, every adjustment also posts a <Term id="journal">journal</Term>: a loss debits the inventory adjustment account and credits inventory, a gain is the mirror image, valued at the item's current cost. Inventory count variances post the same way. Moving stock between storage units posts no journal, because the value never left the location.
## Value
-Inventory value is on-hand quantity times the item's unit cost, summed per item and location.
+Inventory value is on-hand quantity times the item's unit cost, summed per item and location. The Valuation report shows it by location or by item, and its **"Tie-Out"** panel compares that subledger value to the GL inventory account balances. If the two disagree (adjustments made before the books were turned on are the usual reason), **"Reconcile"** drafts an adjusting journal for an accountant to review and post.
## Related
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index e5a5fc722a..ca7e84f7c1 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -4928,7 +4928,6 @@ export type Database = {
accountsReceivableEmail: string | null
assetTaxDepreciationEnabled: boolean
assetTaxRate: number | null
- autoStartOperationTimer: boolean
consoleEnabled: boolean
defaultCustomerCc: string[] | null
defaultSupplierCc: string[] | null
@@ -4972,7 +4971,6 @@ export type Database = {
accountsReceivableEmail?: string | null
assetTaxDepreciationEnabled?: boolean
assetTaxRate?: number | null
- autoStartOperationTimer?: boolean
consoleEnabled?: boolean
defaultCustomerCc?: string[] | null
defaultSupplierCc?: string[] | null
@@ -5016,7 +5014,6 @@ export type Database = {
accountsReceivableEmail?: string | null
assetTaxDepreciationEnabled?: boolean
assetTaxRate?: number | null
- autoStartOperationTimer?: boolean
consoleEnabled?: boolean
defaultCustomerCc?: string[] | null
defaultSupplierCc?: string[] | null
@@ -19754,50 +19751,6 @@ export type Database = {
},
]
}
- jobMaterialStep: {
- Row: {
- jobMaterialId: string
- jobOperationStepId: string
- }
- Insert: {
- jobMaterialId: string
- jobOperationStepId: string
- }
- Update: {
- jobMaterialId?: string
- jobOperationStepId?: string
- }
- Relationships: [
- {
- foreignKeyName: "jobMaterialStep_jobMaterialId_fkey"
- columns: ["jobMaterialId"]
- isOneToOne: false
- referencedRelation: "jobMaterial"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "jobMaterialStep_jobMaterialId_fkey"
- columns: ["jobMaterialId"]
- isOneToOne: false
- referencedRelation: "jobMaterialWithMakeMethodId"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "jobMaterialStep_jobMaterialId_fkey"
- columns: ["jobMaterialId"]
- isOneToOne: false
- referencedRelation: "openJobMaterialLines"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "jobMaterialStep_jobOperationStepId_fkey"
- columns: ["jobOperationStepId"]
- isOneToOne: false
- referencedRelation: "jobOperationStep"
- referencedColumns: ["id"]
- },
- ]
- }
jobOperation: {
Row: {
assemblyInstructionId: string | null
@@ -19820,7 +19773,6 @@ export type Database = {
machineTime: number
machineUnit: Database["public"]["Enums"]["factor"]
manuallyScheduled: boolean
- operationKind: Database["public"]["Enums"]["operationKind"]
operationLeadTime: number
operationMinimumCost: number
operationOrder: Database["public"]["Enums"]["methodOperationOrder"]
@@ -19869,7 +19821,6 @@ export type Database = {
machineTime?: number
machineUnit?: Database["public"]["Enums"]["factor"]
manuallyScheduled?: boolean
- operationKind?: Database["public"]["Enums"]["operationKind"]
operationLeadTime?: number
operationMinimumCost?: number
operationOrder?: Database["public"]["Enums"]["methodOperationOrder"]
@@ -19918,7 +19869,6 @@ export type Database = {
machineTime?: number
machineUnit?: Database["public"]["Enums"]["factor"]
manuallyScheduled?: boolean
- operationKind?: Database["public"]["Enums"]["operationKind"]
operationLeadTime?: number
operationMinimumCost?: number
operationOrder?: Database["public"]["Enums"]["methodOperationOrder"]
@@ -20938,157 +20888,6 @@ export type Database = {
},
]
}
- jobOperationStepSlide: {
- Row: {
- annotations: Json
- caption: string | null
- companyId: string
- createdAt: string
- createdBy: string
- id: string
- imagePath: string
- size: string
- sortOrder: number
- stepId: string
- updatedAt: string | null
- updatedBy: string | null
- }
- Insert: {
- annotations?: Json
- caption?: string | null
- companyId: string
- createdAt?: string
- createdBy: string
- id?: string
- imagePath: string
- size?: string
- sortOrder?: number
- stepId: string
- updatedAt?: string | null
- updatedBy?: string | null
- }
- Update: {
- annotations?: Json
- caption?: string | null
- companyId?: string
- createdAt?: string
- createdBy?: string
- id?: string
- imagePath?: string
- size?: string
- sortOrder?: number
- stepId?: string
- updatedAt?: string | null
- updatedBy?: string | null
- }
- Relationships: [
- {
- foreignKeyName: "jobOperationStepSlide_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "companies"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "jobOperationStepSlide_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "company"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "jobOperationStepSlide_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "customFieldTables"
- referencedColumns: ["companyId"]
- },
- {
- foreignKeyName: "jobOperationStepSlide_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "integrations"
- referencedColumns: ["companyId"]
- },
- {
- foreignKeyName: "jobOperationStepSlide_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "employees"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "jobOperationStepSlide_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "employeesAcrossCompanies"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "jobOperationStepSlide_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "employeeSummary"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "jobOperationStepSlide_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "user"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "jobOperationStepSlide_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "userDefaults"
- referencedColumns: ["userId"]
- },
- {
- foreignKeyName: "jobOperationStepSlide_stepId_fkey"
- columns: ["stepId"]
- isOneToOne: false
- referencedRelation: "jobOperationStep"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "jobOperationStepSlide_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "employees"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "jobOperationStepSlide_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "employeesAcrossCompanies"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "jobOperationStepSlide_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "employeeSummary"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "jobOperationStepSlide_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "user"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "jobOperationStepSlide_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "userDefaults"
- referencedColumns: ["userId"]
- },
- ]
- }
jobOperationTool: {
Row: {
companyId: string
@@ -21287,36 +21086,6 @@ export type Database = {
},
]
}
- jobOperationToolStep: {
- Row: {
- jobOperationStepId: string
- jobOperationToolId: string
- }
- Insert: {
- jobOperationStepId: string
- jobOperationToolId: string
- }
- Update: {
- jobOperationStepId?: string
- jobOperationToolId?: string
- }
- Relationships: [
- {
- foreignKeyName: "jobOperationToolStep_jobOperationStepId_fkey"
- columns: ["jobOperationStepId"]
- isOneToOne: false
- referencedRelation: "jobOperationStep"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "jobOperationToolStep_jobOperationToolId_fkey"
- columns: ["jobOperationToolId"]
- isOneToOne: false
- referencedRelation: "jobOperationTool"
- referencedColumns: ["id"]
- },
- ]
- }
journal: {
Row: {
accountingPeriodId: string | null
@@ -25667,36 +25436,6 @@ export type Database = {
},
]
}
- methodMaterialStep: {
- Row: {
- methodMaterialId: string
- methodOperationStepId: string
- }
- Insert: {
- methodMaterialId: string
- methodOperationStepId: string
- }
- Update: {
- methodMaterialId?: string
- methodOperationStepId?: string
- }
- Relationships: [
- {
- foreignKeyName: "methodMaterialStep_methodMaterialId_fkey"
- columns: ["methodMaterialId"]
- isOneToOne: false
- referencedRelation: "methodMaterial"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "methodMaterialStep_methodOperationStepId_fkey"
- columns: ["methodOperationStepId"]
- isOneToOne: false
- referencedRelation: "methodOperationStep"
- referencedColumns: ["id"]
- },
- ]
- }
methodOperation: {
Row: {
assemblyInstructionId: string | null
@@ -25711,7 +25450,6 @@ export type Database = {
machineTime: number
machineUnit: Database["public"]["Enums"]["factor"]
makeMethodId: string
- operationKind: Database["public"]["Enums"]["operationKind"]
operationLeadTime: number | null
operationMinimumCost: number | null
operationOrder: Database["public"]["Enums"]["methodOperationOrder"]
@@ -25742,7 +25480,6 @@ export type Database = {
machineTime?: number
machineUnit?: Database["public"]["Enums"]["factor"]
makeMethodId: string
- operationKind?: Database["public"]["Enums"]["operationKind"]
operationLeadTime?: number | null
operationMinimumCost?: number | null
operationOrder?: Database["public"]["Enums"]["methodOperationOrder"]
@@ -25773,7 +25510,6 @@ export type Database = {
machineTime?: number
machineUnit?: Database["public"]["Enums"]["factor"]
makeMethodId?: string
- operationKind?: Database["public"]["Enums"]["operationKind"]
operationLeadTime?: number | null
operationMinimumCost?: number | null
operationOrder?: Database["public"]["Enums"]["methodOperationOrder"]
@@ -26249,157 +25985,6 @@ export type Database = {
},
]
}
- methodOperationStepSlide: {
- Row: {
- annotations: Json
- caption: string | null
- companyId: string
- createdAt: string
- createdBy: string
- id: string
- imagePath: string
- size: string
- sortOrder: number
- stepId: string
- updatedAt: string | null
- updatedBy: string | null
- }
- Insert: {
- annotations?: Json
- caption?: string | null
- companyId: string
- createdAt?: string
- createdBy: string
- id?: string
- imagePath: string
- size?: string
- sortOrder?: number
- stepId: string
- updatedAt?: string | null
- updatedBy?: string | null
- }
- Update: {
- annotations?: Json
- caption?: string | null
- companyId?: string
- createdAt?: string
- createdBy?: string
- id?: string
- imagePath?: string
- size?: string
- sortOrder?: number
- stepId?: string
- updatedAt?: string | null
- updatedBy?: string | null
- }
- Relationships: [
- {
- foreignKeyName: "methodOperationStepSlide_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "companies"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "methodOperationStepSlide_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "company"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "methodOperationStepSlide_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "customFieldTables"
- referencedColumns: ["companyId"]
- },
- {
- foreignKeyName: "methodOperationStepSlide_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "integrations"
- referencedColumns: ["companyId"]
- },
- {
- foreignKeyName: "methodOperationStepSlide_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "employees"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "methodOperationStepSlide_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "employeesAcrossCompanies"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "methodOperationStepSlide_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "employeeSummary"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "methodOperationStepSlide_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "user"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "methodOperationStepSlide_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "userDefaults"
- referencedColumns: ["userId"]
- },
- {
- foreignKeyName: "methodOperationStepSlide_stepId_fkey"
- columns: ["stepId"]
- isOneToOne: false
- referencedRelation: "methodOperationStep"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "methodOperationStepSlide_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "employees"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "methodOperationStepSlide_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "employeesAcrossCompanies"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "methodOperationStepSlide_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "employeeSummary"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "methodOperationStepSlide_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "user"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "methodOperationStepSlide_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "userDefaults"
- referencedColumns: ["userId"]
- },
- ]
- }
methodOperationTool: {
Row: {
companyId: string
@@ -26584,36 +26169,6 @@ export type Database = {
},
]
}
- methodOperationToolStep: {
- Row: {
- methodOperationStepId: string
- methodOperationToolId: string
- }
- Insert: {
- methodOperationStepId: string
- methodOperationToolId: string
- }
- Update: {
- methodOperationStepId?: string
- methodOperationToolId?: string
- }
- Relationships: [
- {
- foreignKeyName: "methodOperationToolStep_methodOperationStepId_fkey"
- columns: ["methodOperationStepId"]
- isOneToOne: false
- referencedRelation: "methodOperationStep"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "methodOperationToolStep_methodOperationToolId_fkey"
- columns: ["methodOperationToolId"]
- isOneToOne: false
- referencedRelation: "methodOperationTool"
- referencedColumns: ["id"]
- },
- ]
- }
modelUpload: {
Row: {
autodeskUrn: string | null
@@ -39686,43 +39241,6 @@ export type Database = {
},
]
}
- quoteMaterialStep: {
- Row: {
- quoteMaterialId: string
- quoteOperationStepId: string
- }
- Insert: {
- quoteMaterialId: string
- quoteOperationStepId: string
- }
- Update: {
- quoteMaterialId?: string
- quoteOperationStepId?: string
- }
- Relationships: [
- {
- foreignKeyName: "quoteMaterialStep_quoteMaterialId_fkey"
- columns: ["quoteMaterialId"]
- isOneToOne: false
- referencedRelation: "quoteMaterial"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "quoteMaterialStep_quoteMaterialId_fkey"
- columns: ["quoteMaterialId"]
- isOneToOne: false
- referencedRelation: "quoteMaterialWithMakeMethodId"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "quoteMaterialStep_quoteOperationStepId_fkey"
- columns: ["quoteOperationStepId"]
- isOneToOne: false
- referencedRelation: "quoteOperationStep"
- referencedColumns: ["id"]
- },
- ]
- }
quoteOperation: {
Row: {
companyId: string
@@ -39737,7 +39255,6 @@ export type Database = {
machineRate: number | null
machineTime: number
machineUnit: Database["public"]["Enums"]["factor"]
- operationKind: Database["public"]["Enums"]["operationKind"]
operationLeadTime: number
operationMinimumCost: number
operationOrder: Database["public"]["Enums"]["methodOperationOrder"]
@@ -39772,7 +39289,6 @@ export type Database = {
machineRate?: number | null
machineTime?: number
machineUnit?: Database["public"]["Enums"]["factor"]
- operationKind?: Database["public"]["Enums"]["operationKind"]
operationLeadTime?: number
operationMinimumCost?: number
operationOrder?: Database["public"]["Enums"]["methodOperationOrder"]
@@ -39807,7 +39323,6 @@ export type Database = {
machineRate?: number | null
machineTime?: number
machineUnit?: Database["public"]["Enums"]["factor"]
- operationKind?: Database["public"]["Enums"]["operationKind"]
operationLeadTime?: number
operationMinimumCost?: number
operationOrder?: Database["public"]["Enums"]["methodOperationOrder"]
@@ -40322,157 +39837,6 @@ export type Database = {
},
]
}
- quoteOperationStepSlide: {
- Row: {
- annotations: Json
- caption: string | null
- companyId: string
- createdAt: string
- createdBy: string
- id: string
- imagePath: string
- size: string
- sortOrder: number
- stepId: string
- updatedAt: string | null
- updatedBy: string | null
- }
- Insert: {
- annotations?: Json
- caption?: string | null
- companyId: string
- createdAt?: string
- createdBy: string
- id?: string
- imagePath: string
- size?: string
- sortOrder?: number
- stepId: string
- updatedAt?: string | null
- updatedBy?: string | null
- }
- Update: {
- annotations?: Json
- caption?: string | null
- companyId?: string
- createdAt?: string
- createdBy?: string
- id?: string
- imagePath?: string
- size?: string
- sortOrder?: number
- stepId?: string
- updatedAt?: string | null
- updatedBy?: string | null
- }
- Relationships: [
- {
- foreignKeyName: "quoteOperationStepSlide_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "companies"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "quoteOperationStepSlide_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "company"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "quoteOperationStepSlide_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "customFieldTables"
- referencedColumns: ["companyId"]
- },
- {
- foreignKeyName: "quoteOperationStepSlide_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "integrations"
- referencedColumns: ["companyId"]
- },
- {
- foreignKeyName: "quoteOperationStepSlide_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "employees"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "quoteOperationStepSlide_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "employeesAcrossCompanies"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "quoteOperationStepSlide_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "employeeSummary"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "quoteOperationStepSlide_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "user"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "quoteOperationStepSlide_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "userDefaults"
- referencedColumns: ["userId"]
- },
- {
- foreignKeyName: "quoteOperationStepSlide_stepId_fkey"
- columns: ["stepId"]
- isOneToOne: false
- referencedRelation: "quoteOperationStep"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "quoteOperationStepSlide_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "employees"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "quoteOperationStepSlide_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "employeesAcrossCompanies"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "quoteOperationStepSlide_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "employeeSummary"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "quoteOperationStepSlide_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "user"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "quoteOperationStepSlide_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "userDefaults"
- referencedColumns: ["userId"]
- },
- ]
- }
quoteOperationTool: {
Row: {
companyId: string
@@ -40664,36 +40028,6 @@ export type Database = {
},
]
}
- quoteOperationToolStep: {
- Row: {
- quoteOperationStepId: string
- quoteOperationToolId: string
- }
- Insert: {
- quoteOperationStepId: string
- quoteOperationToolId: string
- }
- Update: {
- quoteOperationStepId?: string
- quoteOperationToolId?: string
- }
- Relationships: [
- {
- foreignKeyName: "quoteOperationToolStep_quoteOperationStepId_fkey"
- columns: ["quoteOperationStepId"]
- isOneToOne: false
- referencedRelation: "quoteOperationStep"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "quoteOperationToolStep_quoteOperationToolId_fkey"
- columns: ["quoteOperationToolId"]
- isOneToOne: false
- referencedRelation: "quoteOperationTool"
- referencedColumns: ["id"]
- },
- ]
- }
quotePayment: {
Row: {
companyId: string
@@ -45090,7 +44424,6 @@ export type Database = {
customFields: Json | null
fromDate: string | null
id: string
- itemId: string | null
serviceType: Database["public"]["Enums"]["serviceType"]
tags: string[] | null
toDate: string | null
@@ -45106,8 +44439,7 @@ export type Database = {
customFields?: Json | null
fromDate?: string | null
id?: string
- itemId?: string | null
- serviceType: Database["public"]["Enums"]["serviceType"]
+ serviceType?: Database["public"]["Enums"]["serviceType"]
tags?: string[] | null
toDate?: string | null
updatedAt?: string | null
@@ -45122,7 +44454,6 @@ export type Database = {
customFields?: Json | null
fromDate?: string | null
id?: string
- itemId?: string | null
serviceType?: Database["public"]["Enums"]["serviceType"]
tags?: string[] | null
toDate?: string | null
@@ -45228,48 +44559,6 @@ export type Database = {
referencedRelation: "userDefaults"
referencedColumns: ["userId"]
},
- {
- foreignKeyName: "service_itemId_fkey"
- columns: ["itemId"]
- isOneToOne: false
- referencedRelation: "consumables"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "service_itemId_fkey"
- columns: ["itemId"]
- isOneToOne: false
- referencedRelation: "item"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "service_itemId_fkey"
- columns: ["itemId"]
- isOneToOne: false
- referencedRelation: "materials"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "service_itemId_fkey"
- columns: ["itemId"]
- isOneToOne: false
- referencedRelation: "parts"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "service_itemId_fkey"
- columns: ["itemId"]
- isOneToOne: false
- referencedRelation: "services"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "service_itemId_fkey"
- columns: ["itemId"]
- isOneToOne: false
- referencedRelation: "tools"
- referencedColumns: ["id"]
- },
{
foreignKeyName: "service_updatedBy_fkey"
columns: ["updatedBy"]
@@ -59935,6 +59224,7 @@ export type Database = {
amount: number | null
companyId: string | null
createdAt: string | null
+ createdBy: string | null
customFields: Json | null
description: string | null
documentId: string | null
@@ -60002,6 +59292,41 @@ export type Database = {
referencedRelation: "integrations"
referencedColumns: ["companyId"]
},
+ {
+ foreignKeyName: "journalLine_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "journalLine_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "journalLine_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "journalLine_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "journalLine_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
{
foreignKeyName: "journalLine_intercompanyPartnerId_fkey"
columns: ["intercompanyPartnerId"]
@@ -67067,14 +66392,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["paymentCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["paymentCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -71078,6 +70403,37 @@ export type Database = {
usageLast90Days: number
}[]
}
+ get_inventory_tie_out: {
+ Args: { as_of_date?: string; company_id: string }
+ Returns: {
+ accountId: string
+ accountKind: string
+ accountName: string
+ glBalance: number
+ subledgerValue: number
+ variance: number
+ }[]
+ }
+ get_inventory_valuation: {
+ Args: { as_of_date?: string; company_id: string; location_id?: string }
+ Returns: {
+ costingMethod: Database["public"]["Enums"]["itemCostingMethod"]
+ itemId: string
+ locationId: string
+ locationName: string
+ name: string
+ quantityOnHand: number
+ quantityOnHold: number
+ quantityRejected: number
+ readableIdWithRevision: string
+ replenishmentSystem: Database["public"]["Enums"]["itemReplenishmentSystem"]
+ thumbnailPath: string
+ totalValue: number
+ type: Database["public"]["Enums"]["itemType"]
+ unitCost: number
+ unitOfMeasureCode: string
+ }[]
+ }
get_inventory_value_by_location: {
Args: { company_id: string }
Returns: {
@@ -71209,7 +70565,6 @@ export type Database = {
machineTime: number
machineUnit: Database["public"]["Enums"]["factor"]
operationDueDate: string
- operationKind: Database["public"]["Enums"]["operationKind"]
operationOrder: number
operationOrderType: Database["public"]["Enums"]["methodOperationOrder"]
operationQuantity: number
@@ -71481,7 +70836,6 @@ export type Database = {
makeMethodId: string
materialMakeMethodId: string
methodMaterialId: string
- methodOperationStepIds: Json
methodType: Database["public"]["Enums"]["methodType"]
operationId: string
order: number
@@ -72054,6 +71408,42 @@ export type Database = {
unitPrice: number
}[]
}
+ get_service_details: {
+ Args: { item_id: string }
+ Returns: {
+ active: boolean
+ assignee: string
+ companyId: string
+ createdAt: string
+ createdBy: string
+ customFields: Json
+ defaultMethodType: Database["public"]["Enums"]["methodType"]
+ description: string
+ id: string
+ itemPostingGroupId: string
+ itemTrackingType: Database["public"]["Enums"]["itemTrackingType"]
+ modelId: string
+ modelName: string
+ modelPath: string
+ modelSize: number
+ mpn: string
+ name: string
+ notes: Json
+ readableId: string
+ readableIdWithRevision: string
+ replenishmentSystem: Database["public"]["Enums"]["itemReplenishmentSystem"]
+ requiresInspection: boolean
+ revision: string
+ revisions: Json
+ sourcingType: Database["public"]["Enums"]["sourcingType"]
+ tags: string[]
+ thumbnailPath: string
+ unitOfMeasure: string
+ unitOfMeasureCode: string
+ updatedAt: string
+ updatedBy: string
+ }[]
+ }
get_supplier_ids_with_supplier_permission: {
Args: { permission: string }
Returns: string[]
@@ -73083,6 +72473,8 @@ export type Database = {
| "Job Close"
| "Payment"
| "Memo"
+ | "Inventory Adjustment"
+ | "Inventory Count"
kanbanOutput: "label" | "qrcode" | "url"
macrsConvention: "Half-Year" | "Mid-Quarter"
macrsPropertyClass: "3" | "5" | "7" | "10" | "15" | "20" | "27.5" | "39"
@@ -73167,7 +72559,6 @@ export type Database = {
| "Completed"
| "Skipped"
oeeImpact: "Down" | "Planned" | "Impact" | "No Impact"
- operationKind: "Operation" | "Assembly" | "Inspection"
operationType: "Inside" | "Outside"
payableLineType:
| "Comment"
@@ -74441,6 +73832,8 @@ export const Constants = {
"Job Close",
"Payment",
"Memo",
+ "Inventory Adjustment",
+ "Inventory Count",
],
kanbanOutput: ["label", "qrcode", "url"],
macrsConvention: ["Half-Year", "Mid-Quarter"],
@@ -74535,7 +73928,6 @@ export const Constants = {
"Skipped",
],
oeeImpact: ["Down", "Planned", "Impact", "No Impact"],
- operationKind: ["Operation", "Assembly", "Inspection"],
operationType: ["Inside", "Outside"],
payableLineType: [
"Comment",
diff --git a/packages/database/supabase/config.toml b/packages/database/supabase/config.toml
index 9448f39b94..fdb8b2f0cf 100644
--- a/packages/database/supabase/config.toml
+++ b/packages/database/supabase/config.toml
@@ -193,6 +193,11 @@ enabled = true
verify_jwt = true
entrypoint = "./functions/post-inventory-count/index.ts"
+[functions.post-inventory-adjustment]
+enabled = true
+verify_jwt = true
+entrypoint = "./functions/post-inventory-adjustment/index.ts"
+
[functions.transcription]
enabled = true
diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.ts
index e5a5fc722a..ca7e84f7c1 100644
--- a/packages/database/supabase/functions/lib/types.ts
+++ b/packages/database/supabase/functions/lib/types.ts
@@ -4928,7 +4928,6 @@ export type Database = {
accountsReceivableEmail: string | null
assetTaxDepreciationEnabled: boolean
assetTaxRate: number | null
- autoStartOperationTimer: boolean
consoleEnabled: boolean
defaultCustomerCc: string[] | null
defaultSupplierCc: string[] | null
@@ -4972,7 +4971,6 @@ export type Database = {
accountsReceivableEmail?: string | null
assetTaxDepreciationEnabled?: boolean
assetTaxRate?: number | null
- autoStartOperationTimer?: boolean
consoleEnabled?: boolean
defaultCustomerCc?: string[] | null
defaultSupplierCc?: string[] | null
@@ -5016,7 +5014,6 @@ export type Database = {
accountsReceivableEmail?: string | null
assetTaxDepreciationEnabled?: boolean
assetTaxRate?: number | null
- autoStartOperationTimer?: boolean
consoleEnabled?: boolean
defaultCustomerCc?: string[] | null
defaultSupplierCc?: string[] | null
@@ -19754,50 +19751,6 @@ export type Database = {
},
]
}
- jobMaterialStep: {
- Row: {
- jobMaterialId: string
- jobOperationStepId: string
- }
- Insert: {
- jobMaterialId: string
- jobOperationStepId: string
- }
- Update: {
- jobMaterialId?: string
- jobOperationStepId?: string
- }
- Relationships: [
- {
- foreignKeyName: "jobMaterialStep_jobMaterialId_fkey"
- columns: ["jobMaterialId"]
- isOneToOne: false
- referencedRelation: "jobMaterial"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "jobMaterialStep_jobMaterialId_fkey"
- columns: ["jobMaterialId"]
- isOneToOne: false
- referencedRelation: "jobMaterialWithMakeMethodId"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "jobMaterialStep_jobMaterialId_fkey"
- columns: ["jobMaterialId"]
- isOneToOne: false
- referencedRelation: "openJobMaterialLines"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "jobMaterialStep_jobOperationStepId_fkey"
- columns: ["jobOperationStepId"]
- isOneToOne: false
- referencedRelation: "jobOperationStep"
- referencedColumns: ["id"]
- },
- ]
- }
jobOperation: {
Row: {
assemblyInstructionId: string | null
@@ -19820,7 +19773,6 @@ export type Database = {
machineTime: number
machineUnit: Database["public"]["Enums"]["factor"]
manuallyScheduled: boolean
- operationKind: Database["public"]["Enums"]["operationKind"]
operationLeadTime: number
operationMinimumCost: number
operationOrder: Database["public"]["Enums"]["methodOperationOrder"]
@@ -19869,7 +19821,6 @@ export type Database = {
machineTime?: number
machineUnit?: Database["public"]["Enums"]["factor"]
manuallyScheduled?: boolean
- operationKind?: Database["public"]["Enums"]["operationKind"]
operationLeadTime?: number
operationMinimumCost?: number
operationOrder?: Database["public"]["Enums"]["methodOperationOrder"]
@@ -19918,7 +19869,6 @@ export type Database = {
machineTime?: number
machineUnit?: Database["public"]["Enums"]["factor"]
manuallyScheduled?: boolean
- operationKind?: Database["public"]["Enums"]["operationKind"]
operationLeadTime?: number
operationMinimumCost?: number
operationOrder?: Database["public"]["Enums"]["methodOperationOrder"]
@@ -20938,157 +20888,6 @@ export type Database = {
},
]
}
- jobOperationStepSlide: {
- Row: {
- annotations: Json
- caption: string | null
- companyId: string
- createdAt: string
- createdBy: string
- id: string
- imagePath: string
- size: string
- sortOrder: number
- stepId: string
- updatedAt: string | null
- updatedBy: string | null
- }
- Insert: {
- annotations?: Json
- caption?: string | null
- companyId: string
- createdAt?: string
- createdBy: string
- id?: string
- imagePath: string
- size?: string
- sortOrder?: number
- stepId: string
- updatedAt?: string | null
- updatedBy?: string | null
- }
- Update: {
- annotations?: Json
- caption?: string | null
- companyId?: string
- createdAt?: string
- createdBy?: string
- id?: string
- imagePath?: string
- size?: string
- sortOrder?: number
- stepId?: string
- updatedAt?: string | null
- updatedBy?: string | null
- }
- Relationships: [
- {
- foreignKeyName: "jobOperationStepSlide_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "companies"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "jobOperationStepSlide_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "company"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "jobOperationStepSlide_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "customFieldTables"
- referencedColumns: ["companyId"]
- },
- {
- foreignKeyName: "jobOperationStepSlide_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "integrations"
- referencedColumns: ["companyId"]
- },
- {
- foreignKeyName: "jobOperationStepSlide_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "employees"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "jobOperationStepSlide_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "employeesAcrossCompanies"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "jobOperationStepSlide_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "employeeSummary"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "jobOperationStepSlide_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "user"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "jobOperationStepSlide_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "userDefaults"
- referencedColumns: ["userId"]
- },
- {
- foreignKeyName: "jobOperationStepSlide_stepId_fkey"
- columns: ["stepId"]
- isOneToOne: false
- referencedRelation: "jobOperationStep"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "jobOperationStepSlide_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "employees"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "jobOperationStepSlide_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "employeesAcrossCompanies"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "jobOperationStepSlide_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "employeeSummary"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "jobOperationStepSlide_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "user"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "jobOperationStepSlide_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "userDefaults"
- referencedColumns: ["userId"]
- },
- ]
- }
jobOperationTool: {
Row: {
companyId: string
@@ -21287,36 +21086,6 @@ export type Database = {
},
]
}
- jobOperationToolStep: {
- Row: {
- jobOperationStepId: string
- jobOperationToolId: string
- }
- Insert: {
- jobOperationStepId: string
- jobOperationToolId: string
- }
- Update: {
- jobOperationStepId?: string
- jobOperationToolId?: string
- }
- Relationships: [
- {
- foreignKeyName: "jobOperationToolStep_jobOperationStepId_fkey"
- columns: ["jobOperationStepId"]
- isOneToOne: false
- referencedRelation: "jobOperationStep"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "jobOperationToolStep_jobOperationToolId_fkey"
- columns: ["jobOperationToolId"]
- isOneToOne: false
- referencedRelation: "jobOperationTool"
- referencedColumns: ["id"]
- },
- ]
- }
journal: {
Row: {
accountingPeriodId: string | null
@@ -25667,36 +25436,6 @@ export type Database = {
},
]
}
- methodMaterialStep: {
- Row: {
- methodMaterialId: string
- methodOperationStepId: string
- }
- Insert: {
- methodMaterialId: string
- methodOperationStepId: string
- }
- Update: {
- methodMaterialId?: string
- methodOperationStepId?: string
- }
- Relationships: [
- {
- foreignKeyName: "methodMaterialStep_methodMaterialId_fkey"
- columns: ["methodMaterialId"]
- isOneToOne: false
- referencedRelation: "methodMaterial"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "methodMaterialStep_methodOperationStepId_fkey"
- columns: ["methodOperationStepId"]
- isOneToOne: false
- referencedRelation: "methodOperationStep"
- referencedColumns: ["id"]
- },
- ]
- }
methodOperation: {
Row: {
assemblyInstructionId: string | null
@@ -25711,7 +25450,6 @@ export type Database = {
machineTime: number
machineUnit: Database["public"]["Enums"]["factor"]
makeMethodId: string
- operationKind: Database["public"]["Enums"]["operationKind"]
operationLeadTime: number | null
operationMinimumCost: number | null
operationOrder: Database["public"]["Enums"]["methodOperationOrder"]
@@ -25742,7 +25480,6 @@ export type Database = {
machineTime?: number
machineUnit?: Database["public"]["Enums"]["factor"]
makeMethodId: string
- operationKind?: Database["public"]["Enums"]["operationKind"]
operationLeadTime?: number | null
operationMinimumCost?: number | null
operationOrder?: Database["public"]["Enums"]["methodOperationOrder"]
@@ -25773,7 +25510,6 @@ export type Database = {
machineTime?: number
machineUnit?: Database["public"]["Enums"]["factor"]
makeMethodId?: string
- operationKind?: Database["public"]["Enums"]["operationKind"]
operationLeadTime?: number | null
operationMinimumCost?: number | null
operationOrder?: Database["public"]["Enums"]["methodOperationOrder"]
@@ -26249,157 +25985,6 @@ export type Database = {
},
]
}
- methodOperationStepSlide: {
- Row: {
- annotations: Json
- caption: string | null
- companyId: string
- createdAt: string
- createdBy: string
- id: string
- imagePath: string
- size: string
- sortOrder: number
- stepId: string
- updatedAt: string | null
- updatedBy: string | null
- }
- Insert: {
- annotations?: Json
- caption?: string | null
- companyId: string
- createdAt?: string
- createdBy: string
- id?: string
- imagePath: string
- size?: string
- sortOrder?: number
- stepId: string
- updatedAt?: string | null
- updatedBy?: string | null
- }
- Update: {
- annotations?: Json
- caption?: string | null
- companyId?: string
- createdAt?: string
- createdBy?: string
- id?: string
- imagePath?: string
- size?: string
- sortOrder?: number
- stepId?: string
- updatedAt?: string | null
- updatedBy?: string | null
- }
- Relationships: [
- {
- foreignKeyName: "methodOperationStepSlide_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "companies"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "methodOperationStepSlide_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "company"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "methodOperationStepSlide_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "customFieldTables"
- referencedColumns: ["companyId"]
- },
- {
- foreignKeyName: "methodOperationStepSlide_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "integrations"
- referencedColumns: ["companyId"]
- },
- {
- foreignKeyName: "methodOperationStepSlide_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "employees"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "methodOperationStepSlide_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "employeesAcrossCompanies"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "methodOperationStepSlide_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "employeeSummary"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "methodOperationStepSlide_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "user"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "methodOperationStepSlide_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "userDefaults"
- referencedColumns: ["userId"]
- },
- {
- foreignKeyName: "methodOperationStepSlide_stepId_fkey"
- columns: ["stepId"]
- isOneToOne: false
- referencedRelation: "methodOperationStep"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "methodOperationStepSlide_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "employees"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "methodOperationStepSlide_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "employeesAcrossCompanies"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "methodOperationStepSlide_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "employeeSummary"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "methodOperationStepSlide_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "user"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "methodOperationStepSlide_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "userDefaults"
- referencedColumns: ["userId"]
- },
- ]
- }
methodOperationTool: {
Row: {
companyId: string
@@ -26584,36 +26169,6 @@ export type Database = {
},
]
}
- methodOperationToolStep: {
- Row: {
- methodOperationStepId: string
- methodOperationToolId: string
- }
- Insert: {
- methodOperationStepId: string
- methodOperationToolId: string
- }
- Update: {
- methodOperationStepId?: string
- methodOperationToolId?: string
- }
- Relationships: [
- {
- foreignKeyName: "methodOperationToolStep_methodOperationStepId_fkey"
- columns: ["methodOperationStepId"]
- isOneToOne: false
- referencedRelation: "methodOperationStep"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "methodOperationToolStep_methodOperationToolId_fkey"
- columns: ["methodOperationToolId"]
- isOneToOne: false
- referencedRelation: "methodOperationTool"
- referencedColumns: ["id"]
- },
- ]
- }
modelUpload: {
Row: {
autodeskUrn: string | null
@@ -39686,43 +39241,6 @@ export type Database = {
},
]
}
- quoteMaterialStep: {
- Row: {
- quoteMaterialId: string
- quoteOperationStepId: string
- }
- Insert: {
- quoteMaterialId: string
- quoteOperationStepId: string
- }
- Update: {
- quoteMaterialId?: string
- quoteOperationStepId?: string
- }
- Relationships: [
- {
- foreignKeyName: "quoteMaterialStep_quoteMaterialId_fkey"
- columns: ["quoteMaterialId"]
- isOneToOne: false
- referencedRelation: "quoteMaterial"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "quoteMaterialStep_quoteMaterialId_fkey"
- columns: ["quoteMaterialId"]
- isOneToOne: false
- referencedRelation: "quoteMaterialWithMakeMethodId"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "quoteMaterialStep_quoteOperationStepId_fkey"
- columns: ["quoteOperationStepId"]
- isOneToOne: false
- referencedRelation: "quoteOperationStep"
- referencedColumns: ["id"]
- },
- ]
- }
quoteOperation: {
Row: {
companyId: string
@@ -39737,7 +39255,6 @@ export type Database = {
machineRate: number | null
machineTime: number
machineUnit: Database["public"]["Enums"]["factor"]
- operationKind: Database["public"]["Enums"]["operationKind"]
operationLeadTime: number
operationMinimumCost: number
operationOrder: Database["public"]["Enums"]["methodOperationOrder"]
@@ -39772,7 +39289,6 @@ export type Database = {
machineRate?: number | null
machineTime?: number
machineUnit?: Database["public"]["Enums"]["factor"]
- operationKind?: Database["public"]["Enums"]["operationKind"]
operationLeadTime?: number
operationMinimumCost?: number
operationOrder?: Database["public"]["Enums"]["methodOperationOrder"]
@@ -39807,7 +39323,6 @@ export type Database = {
machineRate?: number | null
machineTime?: number
machineUnit?: Database["public"]["Enums"]["factor"]
- operationKind?: Database["public"]["Enums"]["operationKind"]
operationLeadTime?: number
operationMinimumCost?: number
operationOrder?: Database["public"]["Enums"]["methodOperationOrder"]
@@ -40322,157 +39837,6 @@ export type Database = {
},
]
}
- quoteOperationStepSlide: {
- Row: {
- annotations: Json
- caption: string | null
- companyId: string
- createdAt: string
- createdBy: string
- id: string
- imagePath: string
- size: string
- sortOrder: number
- stepId: string
- updatedAt: string | null
- updatedBy: string | null
- }
- Insert: {
- annotations?: Json
- caption?: string | null
- companyId: string
- createdAt?: string
- createdBy: string
- id?: string
- imagePath: string
- size?: string
- sortOrder?: number
- stepId: string
- updatedAt?: string | null
- updatedBy?: string | null
- }
- Update: {
- annotations?: Json
- caption?: string | null
- companyId?: string
- createdAt?: string
- createdBy?: string
- id?: string
- imagePath?: string
- size?: string
- sortOrder?: number
- stepId?: string
- updatedAt?: string | null
- updatedBy?: string | null
- }
- Relationships: [
- {
- foreignKeyName: "quoteOperationStepSlide_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "companies"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "quoteOperationStepSlide_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "company"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "quoteOperationStepSlide_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "customFieldTables"
- referencedColumns: ["companyId"]
- },
- {
- foreignKeyName: "quoteOperationStepSlide_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "integrations"
- referencedColumns: ["companyId"]
- },
- {
- foreignKeyName: "quoteOperationStepSlide_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "employees"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "quoteOperationStepSlide_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "employeesAcrossCompanies"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "quoteOperationStepSlide_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "employeeSummary"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "quoteOperationStepSlide_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "user"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "quoteOperationStepSlide_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "userDefaults"
- referencedColumns: ["userId"]
- },
- {
- foreignKeyName: "quoteOperationStepSlide_stepId_fkey"
- columns: ["stepId"]
- isOneToOne: false
- referencedRelation: "quoteOperationStep"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "quoteOperationStepSlide_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "employees"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "quoteOperationStepSlide_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "employeesAcrossCompanies"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "quoteOperationStepSlide_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "employeeSummary"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "quoteOperationStepSlide_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "user"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "quoteOperationStepSlide_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "userDefaults"
- referencedColumns: ["userId"]
- },
- ]
- }
quoteOperationTool: {
Row: {
companyId: string
@@ -40664,36 +40028,6 @@ export type Database = {
},
]
}
- quoteOperationToolStep: {
- Row: {
- quoteOperationStepId: string
- quoteOperationToolId: string
- }
- Insert: {
- quoteOperationStepId: string
- quoteOperationToolId: string
- }
- Update: {
- quoteOperationStepId?: string
- quoteOperationToolId?: string
- }
- Relationships: [
- {
- foreignKeyName: "quoteOperationToolStep_quoteOperationStepId_fkey"
- columns: ["quoteOperationStepId"]
- isOneToOne: false
- referencedRelation: "quoteOperationStep"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "quoteOperationToolStep_quoteOperationToolId_fkey"
- columns: ["quoteOperationToolId"]
- isOneToOne: false
- referencedRelation: "quoteOperationTool"
- referencedColumns: ["id"]
- },
- ]
- }
quotePayment: {
Row: {
companyId: string
@@ -45090,7 +44424,6 @@ export type Database = {
customFields: Json | null
fromDate: string | null
id: string
- itemId: string | null
serviceType: Database["public"]["Enums"]["serviceType"]
tags: string[] | null
toDate: string | null
@@ -45106,8 +44439,7 @@ export type Database = {
customFields?: Json | null
fromDate?: string | null
id?: string
- itemId?: string | null
- serviceType: Database["public"]["Enums"]["serviceType"]
+ serviceType?: Database["public"]["Enums"]["serviceType"]
tags?: string[] | null
toDate?: string | null
updatedAt?: string | null
@@ -45122,7 +44454,6 @@ export type Database = {
customFields?: Json | null
fromDate?: string | null
id?: string
- itemId?: string | null
serviceType?: Database["public"]["Enums"]["serviceType"]
tags?: string[] | null
toDate?: string | null
@@ -45228,48 +44559,6 @@ export type Database = {
referencedRelation: "userDefaults"
referencedColumns: ["userId"]
},
- {
- foreignKeyName: "service_itemId_fkey"
- columns: ["itemId"]
- isOneToOne: false
- referencedRelation: "consumables"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "service_itemId_fkey"
- columns: ["itemId"]
- isOneToOne: false
- referencedRelation: "item"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "service_itemId_fkey"
- columns: ["itemId"]
- isOneToOne: false
- referencedRelation: "materials"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "service_itemId_fkey"
- columns: ["itemId"]
- isOneToOne: false
- referencedRelation: "parts"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "service_itemId_fkey"
- columns: ["itemId"]
- isOneToOne: false
- referencedRelation: "services"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "service_itemId_fkey"
- columns: ["itemId"]
- isOneToOne: false
- referencedRelation: "tools"
- referencedColumns: ["id"]
- },
{
foreignKeyName: "service_updatedBy_fkey"
columns: ["updatedBy"]
@@ -59935,6 +59224,7 @@ export type Database = {
amount: number | null
companyId: string | null
createdAt: string | null
+ createdBy: string | null
customFields: Json | null
description: string | null
documentId: string | null
@@ -60002,6 +59292,41 @@ export type Database = {
referencedRelation: "integrations"
referencedColumns: ["companyId"]
},
+ {
+ foreignKeyName: "journalLine_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "journalLine_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "journalLine_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "journalLine_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "journalLine_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
{
foreignKeyName: "journalLine_intercompanyPartnerId_fkey"
columns: ["intercompanyPartnerId"]
@@ -67067,14 +66392,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["paymentCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["paymentCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -71078,6 +70403,37 @@ export type Database = {
usageLast90Days: number
}[]
}
+ get_inventory_tie_out: {
+ Args: { as_of_date?: string; company_id: string }
+ Returns: {
+ accountId: string
+ accountKind: string
+ accountName: string
+ glBalance: number
+ subledgerValue: number
+ variance: number
+ }[]
+ }
+ get_inventory_valuation: {
+ Args: { as_of_date?: string; company_id: string; location_id?: string }
+ Returns: {
+ costingMethod: Database["public"]["Enums"]["itemCostingMethod"]
+ itemId: string
+ locationId: string
+ locationName: string
+ name: string
+ quantityOnHand: number
+ quantityOnHold: number
+ quantityRejected: number
+ readableIdWithRevision: string
+ replenishmentSystem: Database["public"]["Enums"]["itemReplenishmentSystem"]
+ thumbnailPath: string
+ totalValue: number
+ type: Database["public"]["Enums"]["itemType"]
+ unitCost: number
+ unitOfMeasureCode: string
+ }[]
+ }
get_inventory_value_by_location: {
Args: { company_id: string }
Returns: {
@@ -71209,7 +70565,6 @@ export type Database = {
machineTime: number
machineUnit: Database["public"]["Enums"]["factor"]
operationDueDate: string
- operationKind: Database["public"]["Enums"]["operationKind"]
operationOrder: number
operationOrderType: Database["public"]["Enums"]["methodOperationOrder"]
operationQuantity: number
@@ -71481,7 +70836,6 @@ export type Database = {
makeMethodId: string
materialMakeMethodId: string
methodMaterialId: string
- methodOperationStepIds: Json
methodType: Database["public"]["Enums"]["methodType"]
operationId: string
order: number
@@ -72054,6 +71408,42 @@ export type Database = {
unitPrice: number
}[]
}
+ get_service_details: {
+ Args: { item_id: string }
+ Returns: {
+ active: boolean
+ assignee: string
+ companyId: string
+ createdAt: string
+ createdBy: string
+ customFields: Json
+ defaultMethodType: Database["public"]["Enums"]["methodType"]
+ description: string
+ id: string
+ itemPostingGroupId: string
+ itemTrackingType: Database["public"]["Enums"]["itemTrackingType"]
+ modelId: string
+ modelName: string
+ modelPath: string
+ modelSize: number
+ mpn: string
+ name: string
+ notes: Json
+ readableId: string
+ readableIdWithRevision: string
+ replenishmentSystem: Database["public"]["Enums"]["itemReplenishmentSystem"]
+ requiresInspection: boolean
+ revision: string
+ revisions: Json
+ sourcingType: Database["public"]["Enums"]["sourcingType"]
+ tags: string[]
+ thumbnailPath: string
+ unitOfMeasure: string
+ unitOfMeasureCode: string
+ updatedAt: string
+ updatedBy: string
+ }[]
+ }
get_supplier_ids_with_supplier_permission: {
Args: { permission: string }
Returns: string[]
@@ -73083,6 +72473,8 @@ export type Database = {
| "Job Close"
| "Payment"
| "Memo"
+ | "Inventory Adjustment"
+ | "Inventory Count"
kanbanOutput: "label" | "qrcode" | "url"
macrsConvention: "Half-Year" | "Mid-Quarter"
macrsPropertyClass: "3" | "5" | "7" | "10" | "15" | "20" | "27.5" | "39"
@@ -73167,7 +72559,6 @@ export type Database = {
| "Completed"
| "Skipped"
oeeImpact: "Down" | "Planned" | "Impact" | "No Impact"
- operationKind: "Operation" | "Assembly" | "Inspection"
operationType: "Inside" | "Outside"
payableLineType:
| "Comment"
@@ -74441,6 +73832,8 @@ export const Constants = {
"Job Close",
"Payment",
"Memo",
+ "Inventory Adjustment",
+ "Inventory Count",
],
kanbanOutput: ["label", "qrcode", "url"],
macrsConvention: ["Half-Year", "Mid-Quarter"],
@@ -74535,7 +73928,6 @@ export const Constants = {
"Skipped",
],
oeeImpact: ["Down", "Planned", "Impact", "No Impact"],
- operationKind: ["Operation", "Assembly", "Inspection"],
operationType: ["Inside", "Outside"],
payableLineType: [
"Comment",
diff --git a/packages/database/supabase/functions/post-inventory-adjustment/index.ts b/packages/database/supabase/functions/post-inventory-adjustment/index.ts
new file mode 100644
index 0000000000..28087da4a5
--- /dev/null
+++ b/packages/database/supabase/functions/post-inventory-adjustment/index.ts
@@ -0,0 +1,589 @@
+import { format } from "https://deno.land/[email protected]/datetime/mod.ts";
+import { serve } from "https://deno.land/[email protected]/http/server.ts";
+import { z } from "https://deno.land/x/[email protected]/mod.ts";
+import { Transaction } from "kysely";
+import { DB, getConnectionPool, getDatabaseClient } from "../lib/database.ts";
+import { corsHeaders } from "../lib/headers.ts";
+import { getFunctionLogger } from "../lib/logging.ts";
+import { requirePermissions } from "../lib/supabase.ts";
+import type { Json } from "../lib/types.ts";
+import { getCurrentAccountingPeriod } from "../shared/get-accounting-period.ts";
+import { getDefaultPostingGroup } from "../shared/get-posting-group.ts";
+import { bookAdjustment } from "../shared/post-adjustment.ts";
+
+const pool = getConnectionPool(1);
+const db = getDatabaseClient<DB>(pool);
+const logger = getFunctionLogger("post-inventory-adjustment");
+
+// The single write path for manual inventory adjustments (ERP quantities page,
+// MES shop floor). Ports the former app-side insertManualInventoryAdjustment
+// semantics — Set Quantity resolution, storage-unit transfers, serial/batch
+// stock-target resolution, tracked-entity creation/updates — and books every
+// movement through the shared posting core in ONE transaction: item ledger +
+// cost layers + (when companySettings.accountingEnabled) a balanced journal
+// against the inventory adjustment variance account. Storage-unit transfers
+// move value-neutral stock and never post to the GL.
+const payloadValidator = z.object({
+ adjustmentType: z.enum(["Positive Adjmt.", "Negative Adjmt.", "Set Quantity"]),
+ itemId: z.string(),
+ locationId: z.string(),
+ storageUnitId: z.string().optional().nullable(),
+ trackedEntityId: z.string().optional().nullable(),
+ // 0 is legal for Set Quantity (set to zero); a negative magnitude is never
+ // valid — direction comes from adjustmentType, not the sign.
+ quantity: z.number().min(0),
+ readableId: z.string().optional().nullable(),
+ originalStorageUnitId: z.string().optional().nullable(),
+ expirationDate: z.string().optional().nullable(),
+ comment: z.string().optional().nullable(),
+ companyId: z.string(),
+ userId: z.string(),
+});
+
+// Business-validation failures are 400s with the exact message the app routes
+// string-match on; everything else is a 500 so real outages surface in
+// monitoring. Body key is `message` so getEdgeFunctionErrorMessage can pull
+// the real reason out of the response body.
+class ValidationError extends Error {}
+
+serve(async (req: Request) => {
+ if (req.method === "OPTIONS") {
+ return new Response("ok", { headers: corsHeaders });
+ }
+
+ try {
+ const payload = await req.json();
+ const {
+ adjustmentType,
+ itemId,
+ locationId,
+ storageUnitId,
+ trackedEntityId,
+ quantity,
+ readableId,
+ originalStorageUnitId,
+ expirationDate: providedExpirationDate,
+ comment,
+ companyId,
+ userId,
+ } = payloadValidator.parse(payload);
+
+ const client = await requirePermissions(req, companyId, userId, {
+ update: "inventory",
+ });
+
+ const today = format(new Date(), "yyyy-MM-dd");
+ const nowIso = new Date().toISOString();
+
+ const [
+ storageUnitQuantities,
+ itemResult,
+ itemCostResult,
+ accountingSettings,
+ shelfLife,
+ ] = await Promise.all([
+ client.rpc("get_item_quantities_by_tracking_id", {
+ item_id: itemId,
+ company_id: companyId,
+ location_id: locationId,
+ }),
+ client
+ .from("item")
+ .select("id, itemTrackingType, replenishmentSystem, readableIdWithRevision")
+ .eq("id", itemId)
+ .eq("companyId", companyId)
+ .single(),
+ client
+ .from("itemCost")
+ .select("costingMethod, unitCost, standardCost, itemPostingGroupId")
+ .eq("itemId", itemId)
+ .eq("companyId", companyId)
+ .single(),
+ client
+ .from("companySettings")
+ .select("accountingEnabled")
+ .eq("id", companyId)
+ .single(),
+ client
+ .from("itemShelfLife")
+ .select("mode, days")
+ .eq("itemId", itemId)
+ .eq("companyId", companyId)
+ .maybeSingle(),
+ ]);
+
+ if (itemResult.error) throw new Error("Failed to fetch item");
+ if (itemCostResult.error) throw new Error("Failed to fetch item cost");
+ // Fail closed: a failed quantity read must abort, not read as "no stock" —
+ // a Set Quantity against an empty snapshot would post the full target as
+ // new stock on top of whatever actually exists.
+ if (storageUnitQuantities.error) {
+ throw new Error("Failed to fetch current quantities");
+ }
+ if (shelfLife.error) throw new Error("Failed to fetch item shelf life");
+ const item = {
+ itemTrackingType: itemResult.data.itemTrackingType,
+ replenishmentSystem: itemResult.data.replenishmentSystem,
+ itemPostingGroupId: itemCostResult.data.itemPostingGroupId,
+ };
+ const itemCost = itemCostResult.data;
+
+ // The accountingEnabled flag gates ALL journal writes: when false the
+ // posting core receives accounting = null and books ledger + layers only.
+ // Fail closed: a failed settings read must not silently post without GL.
+ if (accountingSettings.error) {
+ throw new Error("Failed to fetch company settings");
+ }
+ const accountingEnabled =
+ accountingSettings.data?.accountingEnabled ?? false;
+ const accountDefaults = accountingEnabled
+ ? await getDefaultPostingGroup(client, companyId)
+ : null;
+ if (accountingEnabled && (accountDefaults?.error || !accountDefaults?.data)) {
+ throw new Error("Error getting account defaults");
+ }
+
+ // Active dimensions for the company group (post-shipment precedent) —
+ // journal lines get Item / ItemPostingGroup / Location tags.
+ const dimensionMap: Record<string, string> = {};
+ if (accountingEnabled) {
+ const companyRecord = await client
+ .from("company")
+ .select("companyGroupId")
+ .eq("id", companyId)
+ .single();
+ if (companyRecord.error) throw new Error("Failed to fetch company");
+ const dimensions = await client
+ .from("dimension")
+ .select("id, entityType")
+ .eq("companyGroupId", companyRecord.data.companyGroupId)
+ .eq("active", true)
+ .in("entityType", ["Item", "ItemPostingGroup", "Location"]);
+ // Fail closed: journal lines must not silently lose dimension tags.
+ if (dimensions.error) throw new Error("Failed to fetch dimensions");
+ for (const dim of dimensions.data ?? []) {
+ if (dim.entityType) dimensionMap[dim.entityType] = dim.id;
+ }
+ }
+ // Resolve the accounting period BEFORE opening the Kysely transaction —
+ // getCurrentAccountingPeriod uses the REST client and calling it
+ // mid-transaction parks the (size 1) pool in idle-in-transaction.
+ const accountingPeriodId = accountingEnabled
+ ? await getCurrentAccountingPeriod(client, companyId, db)
+ : null;
+ const accounting =
+ accountingEnabled && accountDefaults?.data && accountingPeriodId
+ ? {
+ accountingPeriodId,
+ accountDefaults: {
+ rawMaterialsAccount: accountDefaults.data.rawMaterialsAccount,
+ finishedGoodsAccount: accountDefaults.data.finishedGoodsAccount,
+ inventoryAdjustmentVarianceAccount:
+ accountDefaults.data.inventoryAdjustmentVarianceAccount,
+ },
+ description: comment?.trim()
+ ? `Inventory Adjustment — ${comment.trim()}`
+ : "Inventory Adjustment",
+ userId,
+ dimensions: dimensionMap,
+ }
+ : null;
+
+ // get_item_quantities_by_tracking_id rows (scoped to item + location);
+ // only the fields this function reads.
+ type TrackingQuantityRow = {
+ trackedEntityId: string | null;
+ storageUnitId: string | null;
+ quantity: number | null;
+ readableId: string | null;
+ };
+ const trackingRows = (storageUnitQuantities.data ??
+ []) as TrackingQuantityRow[];
+
+ const ledgerBase = {
+ postingDate: today,
+ itemId,
+ locationId,
+ storageUnitId: storageUnitId ?? null,
+ trackedEntityId: trackedEntityId ?? null,
+ documentType: null,
+ documentId: null,
+ comment: comment || null,
+ companyId,
+ createdBy: userId,
+ };
+
+ // null == undefined — loose equality is deliberate (ported behavior).
+ const currentQuantity = trackedEntityId
+ ? trackingRows.find((q) => q.trackedEntityId == trackedEntityId)
+ : trackingRows.find((q) => q.storageUnitId == storageUnitId);
+ const currentQuantityOnHand = currentQuantity?.quantity ?? 0;
+
+ // Fixed Duration shelf-life fallback for NEW tracked entities when the
+ // user did not type an expiry. Other modes stay NULL (resolved at
+ // production/receipt time, not on a manual adjustment).
+ const resolveExpirationForNewEntity = (): string | null => {
+ if (providedExpirationDate) return providedExpirationDate;
+ if (
+ !shelfLife.error &&
+ shelfLife.data?.mode === "Fixed Duration" &&
+ shelfLife.data.days
+ ) {
+ return format(
+ new Date(Date.now() + Number(shelfLife.data.days) * 86_400_000),
+ "yyyy-MM-dd"
+ );
+ }
+ return null;
+ };
+
+ // Existing-entity expiry override: only when the user supplied a value
+ // that differs from the current one. Ports updateTrackedEntityExpiry —
+ // appends to attributes.expiryOverrides so the override is traceable.
+ const applyExpirationOverride = async (
+ trx: Transaction<DB>,
+ targetEntityId: string
+ ) => {
+ if (!providedExpirationDate) return;
+ const existing = await trx
+ .selectFrom("trackedEntity")
+ .select(["expirationDate", "attributes", "status"])
+ .where("id", "=", targetEntityId)
+ .where("companyId", "=", companyId)
+ .executeTakeFirst();
+ if (!existing || existing.expirationDate === providedExpirationDate)
+ return;
+ if (existing.status === "Consumed") {
+ throw new ValidationError(
+ "Cannot edit expiry of a consumed tracked entity"
+ );
+ }
+ const prevAttrs =
+ (existing.attributes as Record<string, unknown> | null) ?? {};
+ const prevHistory = Array.isArray(prevAttrs.expiryOverrides)
+ ? (prevAttrs.expiryOverrides as Record<string, unknown>[])
+ : [];
+ const nextAttrs = {
+ ...prevAttrs,
+ expiryOverrides: [
+ ...prevHistory,
+ {
+ previous: existing.expirationDate ?? null,
+ next: providedExpirationDate,
+ reason: comment?.trim() || "Updated via inventory adjustment",
+ source: "Inventory Adjustment",
+ userId,
+ at: nowIso,
+ },
+ ],
+ };
+ await trx
+ .updateTable("trackedEntity")
+ .set({
+ expirationDate: providedExpirationDate,
+ attributes: nextAttrs as unknown as Json,
+ })
+ .where("id", "=", targetEntityId)
+ .execute();
+ };
+
+ let resultLedgerId: string | null = null;
+
+ // Storage-unit transfer for a tracked entity: negative at the original
+ // unit, positive at the new one. Value does not move — no GL, no layers.
+ const isStorageUnitTransfer =
+ trackedEntityId &&
+ originalStorageUnitId &&
+ originalStorageUnitId !== storageUnitId;
+
+ await db.transaction().execute(async (trx) => {
+ if (isStorageUnitTransfer) {
+ if (readableId !== undefined && readableId !== null) {
+ await trx
+ .updateTable("trackedEntity")
+ .set({ readableId })
+ .where("id", "=", trackedEntityId!)
+ .where("companyId", "=", companyId)
+ .execute();
+ }
+ await applyExpirationOverride(trx, trackedEntityId!);
+
+ await bookAdjustment(trx, {
+ ledger: {
+ ...ledgerBase,
+ storageUnitId: originalStorageUnitId!,
+ entryType: "Negative Adjmt.",
+ quantity: -currentQuantityOnHand,
+ },
+ item,
+ itemCost,
+ accounting,
+ skipValuation: true,
+ });
+ const positive = await bookAdjustment(trx, {
+ ledger: {
+ ...ledgerBase,
+ entryType: "Positive Adjmt.",
+ quantity: currentQuantityOnHand,
+ },
+ item,
+ itemCost,
+ accounting,
+ skipValuation: true,
+ });
+ resultLedgerId = positive.itemLedgerId;
+ return;
+ }
+
+ let entryType: "Positive Adjmt." | "Negative Adjmt." =
+ adjustmentType === "Set Quantity" ? "Positive Adjmt." : adjustmentType;
+ let adjustmentQuantity = quantity;
+
+ if (adjustmentType === "Set Quantity" && currentQuantity) {
+ const quantityDifference = quantity - currentQuantityOnHand;
+ if (quantityDifference > 0) {
+ entryType = "Positive Adjmt.";
+ adjustmentQuantity = quantityDifference;
+ } else if (quantityDifference < 0) {
+ entryType = "Negative Adjmt.";
+ adjustmentQuantity = Math.abs(quantityDifference);
+ } else {
+ // No quantity change — readableId / expirationDate may still change.
+ if (trackedEntityId && readableId !== undefined && readableId !== null) {
+ await trx
+ .updateTable("trackedEntity")
+ .set({ readableId })
+ .where("id", "=", trackedEntityId)
+ .where("companyId", "=", companyId)
+ .execute();
+ }
+ if (trackedEntityId) {
+ await applyExpirationOverride(trx, trackedEntityId);
+ }
+ resultLedgerId = null;
+ return;
+ }
+ }
+
+ // Resolve the stock target for a negative adjustment when a serial
+ // number is provided or nothing matched the loose lookup.
+ if (entryType === "Negative Adjmt." && (readableId || !currentQuantity)) {
+ if (readableId) {
+ const resolvedQtyRow = trackingRows.find(
+ (q) =>
+ q.readableId === readableId &&
+ q.trackedEntityId != null &&
+ (q.quantity ?? 0) > 0
+ );
+ if (!resolvedQtyRow) {
+ throw new ValidationError("Serial number not found");
+ }
+ const resolvedId = resolvedQtyRow.trackedEntityId as string;
+ const resolvedQty = resolvedQtyRow.quantity ?? 0;
+ if (adjustmentQuantity > resolvedQty) {
+ throw new ValidationError(
+ "Insufficient quantity for negative adjustment"
+ );
+ }
+ await trx
+ .updateTable("trackedEntity")
+ .set({ quantity: resolvedQty - adjustmentQuantity, readableId })
+ .where("id", "=", resolvedId)
+ .where("companyId", "=", companyId)
+ .execute();
+ const booked = await bookAdjustment(trx, {
+ ledger: {
+ ...ledgerBase,
+ trackedEntityId: resolvedId,
+ entryType,
+ quantity: -Math.abs(adjustmentQuantity),
+ },
+ item,
+ itemCost,
+ accounting,
+ });
+ resultLedgerId = booked.itemLedgerId;
+ return;
+ }
+
+ // No serial number provided. Prefer untracked (legacy) stock in this bin.
+ const legacyRow = trackingRows.find(
+ (q) => q.trackedEntityId == null && q.storageUnitId == storageUnitId
+ );
+ if (legacyRow) {
+ const legacyQty = legacyRow.quantity ?? 0;
+ if (adjustmentQuantity > legacyQty) {
+ throw new ValidationError(
+ "Insufficient quantity for negative adjustment"
+ );
+ }
+ const booked = await bookAdjustment(trx, {
+ ledger: {
+ ...ledgerBase,
+ trackedEntityId: null,
+ entryType,
+ quantity: -Math.abs(adjustmentQuantity),
+ },
+ item,
+ itemCost,
+ accounting,
+ });
+ resultLedgerId = booked.itemLedgerId;
+ return;
+ }
+
+ // No untracked stock in the bin — resolve a tracked entity sitting in
+ // the same storage unit. Ambiguous when more than one holds stock.
+ const trackedRowsInUnit = trackingRows.filter(
+ (q) =>
+ q.trackedEntityId != null &&
+ q.storageUnitId == storageUnitId &&
+ (q.quantity ?? 0) > 0
+ );
+ if (trackedRowsInUnit.length === 0) {
+ throw new ValidationError(
+ "Insufficient quantity for negative adjustment"
+ );
+ }
+ if (trackedRowsInUnit.length > 1) {
+ throw new ValidationError(
+ "Multiple tracked entities in this storage unit — select a specific row to adjust"
+ );
+ }
+ const targetRow = trackedRowsInUnit[0];
+ const targetQty = targetRow.quantity ?? 0;
+ if (adjustmentQuantity > targetQty) {
+ throw new ValidationError(
+ "Insufficient quantity for negative adjustment"
+ );
+ }
+ const targetId = targetRow.trackedEntityId as string;
+ await trx
+ .updateTable("trackedEntity")
+ .set({ quantity: targetQty - adjustmentQuantity })
+ .where("id", "=", targetId)
+ .where("companyId", "=", companyId)
+ .execute();
+ const booked = await bookAdjustment(trx, {
+ ledger: {
+ ...ledgerBase,
+ trackedEntityId: targetId,
+ entryType,
+ quantity: -Math.abs(adjustmentQuantity),
+ },
+ item,
+ itemCost,
+ accounting,
+ });
+ resultLedgerId = booked.itemLedgerId;
+ return;
+ }
+
+ let signedQuantity = adjustmentQuantity;
+ if (entryType === "Negative Adjmt.") {
+ if (adjustmentQuantity > currentQuantityOnHand) {
+ throw new ValidationError(
+ "Insufficient quantity for negative adjustment"
+ );
+ }
+ signedQuantity = -Math.abs(adjustmentQuantity);
+ }
+
+ if (trackedEntityId) {
+ if (currentQuantity) {
+ const entityUpdate: Record<string, unknown> = {
+ quantity: signedQuantity + currentQuantityOnHand,
+ };
+ if (readableId !== undefined && readableId !== null) {
+ entityUpdate.readableId = readableId;
+ }
+ await trx
+ .updateTable("trackedEntity")
+ .set(entityUpdate)
+ .where("id", "=", trackedEntityId)
+ .where("companyId", "=", companyId)
+ .execute();
+ await applyExpirationOverride(trx, trackedEntityId);
+ } else {
+ const expirationDate = resolveExpirationForNewEntity();
+ // Stamp the trace blob so the popover Source / Override steps can
+ // show the entity originated from a manual inventory adjustment.
+ const adjustmentStamp = {
+ userId,
+ at: nowIso,
+ reason: comment?.trim() || "Created via inventory adjustment",
+ };
+ const attributes: Record<string, unknown> = {
+ "Inventory Adjustment": adjustmentStamp,
+ ...(expirationDate
+ ? {
+ expiryOverrides: [
+ {
+ previous: null,
+ next: expirationDate,
+ reason: adjustmentStamp.reason,
+ source: "Inventory Adjustment",
+ userId: adjustmentStamp.userId,
+ at: adjustmentStamp.at,
+ },
+ ],
+ }
+ : {}),
+ };
+ await trx
+ .insertInto("trackedEntity")
+ .values({
+ id: trackedEntityId,
+ sourceDocument: "Item",
+ sourceDocumentId: itemId,
+ sourceDocumentReadableId:
+ itemResult.data.readableIdWithRevision ?? undefined,
+ readableId: readableId ?? null,
+ quantity: signedQuantity,
+ status: "Available",
+ expirationDate,
+ attributes: attributes as unknown as Json,
+ companyId,
+ createdBy: userId,
+ })
+ .execute();
+ }
+ }
+
+ const booked = await bookAdjustment(trx, {
+ ledger: {
+ ...ledgerBase,
+ entryType,
+ quantity: signedQuantity,
+ },
+ item,
+ itemCost,
+ accounting,
+ });
+ resultLedgerId = booked.itemLedgerId;
+ });
+
+ return new Response(
+ JSON.stringify({
+ success: true,
+ itemLedger: resultLedgerId ? { id: resultLedgerId } : null,
+ }),
+ {
+ headers: { ...corsHeaders, "Content-Type": "application/json" },
+ status: 200,
+ }
+ );
+ } catch (err) {
+ logger.error("post-inventory-adjustment failed", {
+ error: String((err as Error).stack ?? err),
+ });
+ const isValidationError = err instanceof ValidationError;
+ return new Response(
+ JSON.stringify({ message: (err as Error).message }),
+ {
+ headers: { ...corsHeaders, "Content-Type": "application/json" },
+ status: isValidationError ? 400 : 500,
+ }
+ );
+ }
+});
diff --git a/packages/database/supabase/functions/post-inventory-count/index.ts b/packages/database/supabase/functions/post-inventory-count/index.ts
index 60e9a89b3e..97e420d651 100644
--- a/packages/database/supabase/functions/post-inventory-count/index.ts
+++ b/packages/database/supabase/functions/post-inventory-count/index.ts
@@ -3,14 +3,20 @@ import { format } from "https://deno.land/[email protected]/datetime/mod.ts";
import { z } from "https://deno.land/x/[email protected]/mod.ts";
import { DB, getConnectionPool, getDatabaseClient } from "../lib/database.ts";
import { corsHeaders } from "../lib/headers.ts";
+import { getFunctionLogger } from "../lib/logging.ts";
import { requirePermissions } from "../lib/supabase.ts";
import type { Database } from "../lib/types.ts";
+import { getCurrentAccountingPeriod } from "../shared/get-accounting-period.ts";
+import { getDefaultPostingGroup } from "../shared/get-posting-group.ts";
+import {
+ bookAdjustment,
+ createAdjustmentJournal
+} from "../shared/post-adjustment.ts";
import { planInventoryCountPost } from "./plan-post.ts";
const pool = getConnectionPool(1);
const db = getDatabaseClient<DB>(pool);
-
-type ItemLedgerInsert = Database["public"]["Tables"]["itemLedger"]["Insert"];
+const logger = getFunctionLogger("post-inventory-count");
// Base for post-blocking validation errors. Carries the offending line ids so
// the response can hand them to the UI to highlight the rows.
@@ -40,10 +46,12 @@ class SerialQuantityError extends InvalidLinesError {
// reviewed — `counted - systemQuantity` (the FROZEN snapshot on the line), NOT
// `counted - live on-hand`. This preserves any stock movements that posted between
// the snapshot and the post (a receipt/shipment isn't clobbered; the correction is
-// applied on top of it). Like `insertManualInventoryAdjustment`, this writes to the
-// item ledger only (on-hand is derived from `itemLedger`); no GL journal lines.
+// applied on top of it). Each variance books through the shared posting core:
+// item ledger + cost layers + (when companySettings.accountingEnabled) a GL
+// journal against the inventory adjustment variance account.
// (Rectify re-snapshots `systemQuantity` to current live on-hand first, so for a
-// correction the same formula resolves to "set to counted".)
+// correction the same formula resolves to "set to counted". A correction is a
+// NEW movement valued at posting-time cost — the original journal is immutable.)
const payloadValidator = z.object({
type: z.literal("post"),
inventoryCountId: z.string(),
@@ -99,7 +107,7 @@ serve(async (req: Request) => {
const items = itemIds.length
? await client
.from("item")
- .select("id, itemTrackingType")
+ .select("id, itemTrackingType, replenishmentSystem")
.in("id", itemIds)
.eq("companyId", companyId)
: null;
@@ -108,6 +116,44 @@ serve(async (req: Request) => {
const trackingTypeByItem = new Map<string, string | null>(
(items?.data ?? []).map((item) => [item.id, item.itemTrackingType])
);
+ // Explicit row types: supabase-js generic inference fails under deno
+ // check for these selects (same pre-existing limitation as the maps above).
+ type CountItemRow = {
+ id: string;
+ replenishmentSystem:
+ | Database["public"]["Enums"]["itemReplenishmentSystem"]
+ | null;
+ };
+ type CountItemCostRow = {
+ itemId: string;
+ costingMethod: Database["public"]["Enums"]["itemCostingMethod"];
+ unitCost: number | null;
+ standardCost: number | null;
+ itemPostingGroupId: string | null;
+ };
+ const replenishmentByItem = new Map(
+ ((items?.data ?? []) as CountItemRow[]).map((item) => [
+ item.id,
+ item.replenishmentSystem
+ ])
+ );
+
+ const itemCosts = itemIds.length
+ ? await client
+ .from("itemCost")
+ .select(
+ "itemId, costingMethod, unitCost, standardCost, itemPostingGroupId"
+ )
+ .in("itemId", itemIds)
+ .eq("companyId", companyId)
+ : null;
+ if (itemCosts?.error) throw new Error(itemCosts.error.message);
+ const itemCostByItem = new Map(
+ ((itemCosts?.data ?? []) as CountItemCostRow[]).map((cost) => [
+ cost.itemId,
+ cost
+ ])
+ );
const serialInvalidLineIds = countedLines
.filter((line) => {
if (trackingTypeByItem.get(line.itemId) !== "Serial") return false;
@@ -122,6 +168,72 @@ serve(async (req: Request) => {
// Reconcile against the frozen snapshot — no live on-hand read needed.
const { planned } = planInventoryCountPost(countedLines);
+ // The accountingEnabled flag gates ALL journal writes; cost layers are
+ // maintained either way. Resolve settings + period BEFORE the transaction
+ // (REST hops mid-transaction park the size-1 pool in idle-in-transaction).
+ const accountingSettings = await client
+ .from("companySettings")
+ .select("accountingEnabled")
+ .eq("id", companyId)
+ .single();
+ // Fail closed: a failed settings read must not silently post without GL.
+ if (accountingSettings.error) {
+ throw new Error("Failed to fetch company settings");
+ }
+ const accountingEnabled =
+ accountingSettings.data?.accountingEnabled ?? false;
+ const accountDefaults = accountingEnabled
+ ? await getDefaultPostingGroup(client, companyId)
+ : null;
+ if (
+ accountingEnabled &&
+ (accountDefaults?.error || !accountDefaults?.data)
+ ) {
+ throw new Error("Error getting account defaults");
+ }
+ const accountingPeriodId = accountingEnabled
+ ? await getCurrentAccountingPeriod(client, companyId, db)
+ : null;
+
+ // Active dimensions for the company group (post-shipment precedent) —
+ // journal lines get Item / ItemPostingGroup / Location tags.
+ const dimensionMap: Record<string, string> = {};
+ if (accountingEnabled) {
+ const companyRecord = await client
+ .from("company")
+ .select("companyGroupId")
+ .eq("id", companyId)
+ .single();
+ if (companyRecord.error) throw new Error("Failed to fetch company");
+ const dimensions = await client
+ .from("dimension")
+ .select("id, entityType")
+ .eq("companyGroupId", companyRecord.data.companyGroupId)
+ .eq("active", true)
+ .in("entityType", ["Item", "ItemPostingGroup", "Location"]);
+ // Fail closed: journal lines must not silently lose dimension tags.
+ if (dimensions.error) throw new Error("Failed to fetch dimensions");
+ for (const dim of dimensions.data ?? []) {
+ if (dim.entityType) dimensionMap[dim.entityType] = dim.id;
+ }
+ }
+
+ const accounting =
+ accountingEnabled && accountDefaults?.data && accountingPeriodId
+ ? {
+ accountingPeriodId,
+ accountDefaults: {
+ rawMaterialsAccount: accountDefaults.data.rawMaterialsAccount,
+ finishedGoodsAccount: accountDefaults.data.finishedGoodsAccount,
+ inventoryAdjustmentVarianceAccount:
+ accountDefaults.data.inventoryAdjustmentVarianceAccount
+ },
+ description: comment,
+ userId,
+ dimensions: dimensionMap
+ }
+ : null;
+
await db.transaction().execute(async (trx) => {
// Concurrency guard: lock the header and re-assert it is still Pending so
// two concurrent posts can't both apply the delta (double-post). Mirrors
@@ -140,35 +252,65 @@ serve(async (req: Request) => {
throw new Error("Inventory count is no longer pending");
}
- // Post the reviewed variance for each line as an inventory adjustment.
+ // ONE journal per count post: created lazily on the first variance that
+ // carries value, then shared by every line's journal-line pair.
+ let sharedJournalId: string | null = null;
+ const accountingForLines = accounting
+ ? {
+ ...accounting,
+ getJournalId: async () => {
+ if (!sharedJournalId) {
+ sharedJournalId = await createAdjustmentJournal(trx, {
+ companyId,
+ accountingPeriodId: accounting.accountingPeriodId,
+ description: accounting.description,
+ postingDate: today,
+ userId
+ });
+ }
+ return sharedJournalId;
+ }
+ }
+ : null;
+
+ // Post the reviewed variance for each line as an inventory adjustment,
+ // booked through the shared core (ledger + cost layers + journal).
for (const { line, delta } of planned) {
if (delta === 0) continue;
- const ledgerEntry: ItemLedgerInsert = {
- postingDate: today,
- itemId: line.itemId,
- quantity: delta,
- locationId: line.locationId,
- storageUnitId: line.storageUnitId,
- trackedEntityId: line.trackedEntityId,
- entryType: delta > 0 ? "Positive Adjmt." : "Negative Adjmt.",
- documentType: "Inventory Count",
- documentId: inventoryCountId,
- // In-place rectify: if this line already posted a movement (the count
- // was rectified), link the new fix movement back to that prior one so
- // both stay visible and linked in the movements screens. Null on the
- // first post.
- correctionOfItemLedgerId: line.postedItemLedgerId ?? null,
- comment,
- companyId,
- createdBy: userId
- };
-
- const inserted = await trx
- .insertInto("itemLedger")
- .values(ledgerEntry)
- .returning(["id"])
- .executeTakeFirstOrThrow();
+ const itemCost = itemCostByItem.get(line.itemId);
+ if (!itemCost) {
+ throw new Error(`Missing item cost for item ${line.itemId}`);
+ }
+
+ const booked = await bookAdjustment(trx, {
+ ledger: {
+ postingDate: today,
+ itemId: line.itemId,
+ quantity: delta,
+ locationId: line.locationId,
+ storageUnitId: line.storageUnitId,
+ trackedEntityId: line.trackedEntityId,
+ entryType: delta > 0 ? "Positive Adjmt." : "Negative Adjmt.",
+ documentType: "Inventory Count",
+ documentId: inventoryCountId,
+ // In-place rectify: if this line already posted a movement (the count
+ // was rectified), link the new fix movement back to that prior one so
+ // both stay visible and linked in the movements screens. Null on the
+ // first post.
+ correctionOfItemLedgerId: line.postedItemLedgerId ?? null,
+ comment,
+ companyId,
+ createdBy: userId
+ },
+ item: {
+ itemTrackingType: trackingTypeByItem.get(line.itemId) ?? null,
+ replenishmentSystem: replenishmentByItem.get(line.itemId) ?? null,
+ itemPostingGroupId: itemCost.itemPostingGroupId
+ },
+ itemCost,
+ accounting: accountingForLines
+ });
// Tracked lines: apply the same delta to the entity's quantity (not a
// set-to-counted) so movements since the snapshot aren't overwritten.
@@ -183,7 +325,7 @@ serve(async (req: Request) => {
await trx
.updateTable("inventoryCountLine")
- .set({ postedItemLedgerId: inserted.id })
+ .set({ postedItemLedgerId: booked.itemLedgerId })
.where("id", "=", line.id)
.where("companyId", "=", companyId)
.execute();
@@ -217,7 +359,9 @@ serve(async (req: Request) => {
headers: { ...corsHeaders, "Content-Type": "application/json" }
});
} catch (err) {
- console.error("Error in post-inventory-count:", err);
+ logger.error("post-inventory-count failed", {
+ error: String((err as Error).stack ?? err)
+ });
// The post is a single atomic transaction, so a failure has already rolled
// back any ledger writes and the status change — the count is left exactly
// as it was (Pending). We do NOT touch the status here: reverting a failed
diff --git a/packages/database/supabase/functions/shared/calculate-cogs.ts b/packages/database/supabase/functions/shared/calculate-cogs.ts
index 2dd8bf0434..08ff7897b5 100644
--- a/packages/database/supabase/functions/shared/calculate-cogs.ts
+++ b/packages/database/supabase/functions/shared/calculate-cogs.ts
@@ -75,6 +75,10 @@ export async function calculateCOGS(
)
.orderBy("postingDate", orderDirection)
.orderBy("createdAt", orderDirection)
+ // Lock the layers for this transaction — two concurrent consumers
+ // would otherwise both read the same remainingQuantity and consume
+ // the layer twice (lost update).
+ .forUpdate()
.execute();
let remainingToConsume = quantity;
@@ -108,6 +112,7 @@ export async function calculateCOGS(
remainingQuantity: layerRemaining - quantityFromLayer,
})
.where("id", "=", layer.id)
+ .where("companyId", "=", companyId)
.execute();
// Consume the layer's cost-adjustment children (invoice-vs-receipt
@@ -117,8 +122,10 @@ export async function calculateCOGS(
.selectFrom("costLedger")
.selectAll()
.where("appliesToCostLedgerId", "=", layer.id)
+ .where("companyId", "=", companyId)
.where("remainingQuantity", ">", 0)
.orderBy("createdAt", "asc")
+ .forUpdate()
.execute();
let unappliedQuantity = quantityFromLayer;
@@ -136,6 +143,7 @@ export async function calculateCOGS(
.updateTable("costLedger")
.set({ remainingQuantity: childQty - applyQty })
.where("id", "=", child.id)
+ .where("companyId", "=", companyId)
.execute();
}
}
diff --git a/packages/database/supabase/functions/shared/post-adjustment-cost.ts b/packages/database/supabase/functions/shared/post-adjustment-cost.ts
new file mode 100644
index 0000000000..d2385d75d9
--- /dev/null
+++ b/packages/database/supabase/functions/shared/post-adjustment-cost.ts
@@ -0,0 +1,49 @@
+import { Database } from "../lib/types.ts";
+
+export interface AdjustmentItemCost {
+ costingMethod: Database["public"]["Enums"]["itemCostingMethod"];
+ unitCost: number | null;
+ standardCost: number | null;
+}
+
+export interface OpenCostLayer {
+ quantity: number;
+ remainingQuantity: number;
+ cost: number;
+ appliedChildCost: number;
+}
+
+// Current carrying unit cost for a POSITIVE adjustment's new layer / journal
+// value. Mirrors the valuation RPC's carrying CTE: FIFO/LIFO use the
+// weighted-average effective cost of open layers (including applied
+// invoice-vs-receipt children); Average/Standard come straight from itemCost.
+// Pure (no I/O) so it stays unit-testable with `deno test`.
+export function computeCurrentUnitCost(
+ itemCost: AdjustmentItemCost,
+ openLayers: OpenCostLayer[]
+): number {
+ switch (itemCost.costingMethod) {
+ case "Standard":
+ return Number(itemCost.standardCost ?? 0);
+ case "Average":
+ return Number(itemCost.unitCost ?? 0);
+ case "FIFO":
+ case "LIFO": {
+ let remaining = 0;
+ let value = 0;
+ for (const layer of openLayers) {
+ const quantity = Number(layer.quantity);
+ const layerRemaining = Number(layer.remainingQuantity);
+ if (quantity <= 0 || layerRemaining <= 0) continue;
+ const effectiveUnitCost =
+ (Number(layer.cost) + Number(layer.appliedChildCost)) / quantity;
+ remaining += layerRemaining;
+ value += layerRemaining * effectiveUnitCost;
+ }
+ if (remaining <= 0) return Number(itemCost.unitCost ?? 0);
+ return value / remaining;
+ }
+ default:
+ return Number(itemCost.unitCost ?? 0);
+ }
+}
diff --git a/packages/database/supabase/functions/shared/post-adjustment.test.ts b/packages/database/supabase/functions/shared/post-adjustment.test.ts
new file mode 100644
index 0000000000..57a4ba4ef8
--- /dev/null
+++ b/packages/database/supabase/functions/shared/post-adjustment.test.ts
@@ -0,0 +1,71 @@
+import { assertEquals } from "https://deno.land/[email protected]/testing/asserts.ts";
+import { computeCurrentUnitCost } from "./post-adjustment-cost.ts";
+
+const layer = (
+ quantity: number,
+ remainingQuantity: number,
+ cost: number,
+ appliedChildCost = 0
+) => ({ quantity, remainingQuantity, cost, appliedChildCost });
+
+Deno.test("Standard items use standardCost", () => {
+ assertEquals(
+ computeCurrentUnitCost(
+ { costingMethod: "Standard", unitCost: 3, standardCost: 5 },
+ [layer(100, 100, 1000)]
+ ),
+ 5
+ );
+});
+
+Deno.test("Average items use unitCost", () => {
+ assertEquals(
+ computeCurrentUnitCost(
+ { costingMethod: "Average", unitCost: 7.25, standardCost: 0 },
+ []
+ ),
+ 7.25
+ );
+});
+
+Deno.test("FIFO uses the weighted average of open layers", () => {
+ // 60 remaining @ $10 and 50 remaining @ $12 → (600 + 600) / 110
+ assertEquals(
+ computeCurrentUnitCost(
+ { costingMethod: "FIFO", unitCost: 1, standardCost: 0 },
+ [layer(100, 60, 1000), layer(50, 50, 600)]
+ ),
+ 1200 / 110
+ );
+});
+
+Deno.test("FIFO includes applied adjustment children in the layer cost", () => {
+ // base layer qty 100 cost $1000 + $55 applied child → effective $10.55/unit
+ assertEquals(
+ computeCurrentUnitCost(
+ { costingMethod: "FIFO", unitCost: 1, standardCost: 0 },
+ [layer(100, 60, 1000, 55)]
+ ),
+ 10.55
+ );
+});
+
+Deno.test("FIFO falls back to unitCost when no layers are open", () => {
+ assertEquals(
+ computeCurrentUnitCost(
+ { costingMethod: "FIFO", unitCost: 4.5, standardCost: 0 },
+ []
+ ),
+ 4.5
+ );
+});
+
+Deno.test("zero-quantity and fully-consumed layers are skipped", () => {
+ assertEquals(
+ computeCurrentUnitCost(
+ { costingMethod: "LIFO", unitCost: 9, standardCost: 0 },
+ [layer(0, 0, 500), layer(10, 0, 100), layer(10, 10, 100)]
+ ),
+ 10
+ );
+});
diff --git a/packages/database/supabase/functions/shared/post-adjustment.ts b/packages/database/supabase/functions/shared/post-adjustment.ts
new file mode 100644
index 0000000000..73be2649f5
--- /dev/null
+++ b/packages/database/supabase/functions/shared/post-adjustment.ts
@@ -0,0 +1,336 @@
+import { nanoid } from "https://deno.land/x/[email protected]/mod.ts";
+import { Transaction } from "kysely";
+import { DB } from "../lib/database.ts";
+import { Database } from "../lib/types.ts";
+import { credit, debit } from "../lib/utils.ts";
+import { calculateCOGS } from "./calculate-cogs.ts";
+import { getNextSequence } from "./get-next-sequence.ts";
+import { resolveInventoryAccount } from "./get-posting-group.ts";
+import {
+ AdjustmentItemCost,
+ computeCurrentUnitCost,
+} from "./post-adjustment-cost.ts";
+
+export { computeCurrentUnitCost } from "./post-adjustment-cost.ts";
+export type {
+ AdjustmentItemCost,
+ OpenCostLayer,
+} from "./post-adjustment-cost.ts";
+
+export interface BookAdjustmentArgs {
+ ledger: {
+ postingDate: string; // yyyy-MM-dd
+ itemId: string;
+ // SIGNED delta: > 0 for Positive Adjmt., < 0 for Negative Adjmt.
+ quantity: number;
+ locationId: string | null;
+ storageUnitId: string | null;
+ trackedEntityId: string | null;
+ entryType: "Positive Adjmt." | "Negative Adjmt.";
+ // itemLedgerDocumentType — manual adjustments stay NULL (ledger rows keep
+ // today's shape; 'Inventory Adjustment' exists only on journalLineDocumentType)
+ documentType?: "Inventory Count" | null;
+ documentId?: string | null;
+ correctionOfItemLedgerId?: string | null;
+ comment?: string | null;
+ companyId: string;
+ createdBy: string;
+ };
+ item: {
+ itemTrackingType: string | null;
+ replenishmentSystem:
+ | Database["public"]["Enums"]["itemReplenishmentSystem"]
+ | null;
+ itemPostingGroupId?: string | null;
+ };
+ itemCost: AdjustmentItemCost;
+ // null ⇒ accounting disabled: ledger + cost layers only, no journal
+ accounting: {
+ accountingPeriodId: string;
+ accountDefaults: {
+ rawMaterialsAccount: string;
+ finishedGoodsAccount: string;
+ inventoryAdjustmentVarianceAccount: string;
+ };
+ description: string;
+ userId: string;
+ // active dimensions for the company group, entityType → dimension id
+ // (Item / ItemPostingGroup / Location are consulted) — journal lines get
+ // journalLineDimension tags for whichever are configured
+ dimensions?: Record<string, string>;
+ // When set, lines append to this shared journal instead of the core
+ // creating one journal per movement — inventory counts post ONE journal
+ // per count with a line pair per variance. Lazy (called only when a
+ // movement actually carries value) so an all-zero-cost run never creates
+ // an empty journal.
+ getJournalId?: () => Promise<string>;
+ } | null;
+ // storage-unit-transfer legs move stock between bins without changing its
+ // value: ledger row only — no cost layers, no journal
+ skipValuation?: boolean;
+}
+
+export interface BookAdjustmentResult {
+ itemLedgerId: string;
+ journalId: string | null;
+ cost: number;
+}
+
+export interface CreateAdjustmentJournalArgs {
+ companyId: string;
+ accountingPeriodId: string;
+ description: string;
+ postingDate: string;
+ userId: string;
+}
+
+// One journal header for adjustment postings ('Inventory Adjustment' source,
+// posted immediately). Manual adjustments create one per movement; inventory
+// counts share ONE journal per count post via accounting.getJournalId.
+export async function createAdjustmentJournal(
+ trx: Transaction<DB>,
+ args: CreateAdjustmentJournalArgs
+): Promise<string> {
+ const journalEntryId = await getNextSequence(
+ trx,
+ "journalEntry",
+ args.companyId
+ );
+ const journal = await trx
+ .insertInto("journal")
+ .values({
+ journalEntryId,
+ accountingPeriodId: args.accountingPeriodId,
+ description: args.description,
+ postingDate: args.postingDate,
+ companyId: args.companyId,
+ sourceType: "Inventory Adjustment",
+ status: "Posted",
+ postedAt: new Date().toISOString(),
+ postedBy: args.userId,
+ createdBy: args.userId,
+ })
+ .returning(["id"])
+ .executeTakeFirstOrThrow();
+ return journal.id;
+}
+
+// Book one adjustment movement inside the caller's transaction: the item
+// ledger row, cost-layer maintenance (consume via calculateCOGS on decreases,
+// create a layer at current cost on increases), and — when accounting is
+// enabled and the movement carries value — a balanced journal against the
+// inventory adjustment variance account. Tracked-entity mutations are the
+// caller's responsibility.
+export async function bookAdjustment(
+ trx: Transaction<DB>,
+ args: BookAdjustmentArgs
+): Promise<BookAdjustmentResult> {
+ const { ledger, item, itemCost, accounting, skipValuation } = args;
+ const { companyId } = ledger;
+
+ const inserted = await trx
+ .insertInto("itemLedger")
+ .values({
+ postingDate: ledger.postingDate,
+ entryType: ledger.entryType,
+ documentType: ledger.documentType ?? null,
+ documentId: ledger.documentId ?? null,
+ correctionOfItemLedgerId: ledger.correctionOfItemLedgerId ?? null,
+ itemId: ledger.itemId,
+ locationId: ledger.locationId,
+ storageUnitId: ledger.storageUnitId,
+ trackedEntityId: ledger.trackedEntityId,
+ quantity: ledger.quantity,
+ comment: ledger.comment ?? null,
+ companyId,
+ createdBy: ledger.createdBy,
+ })
+ .returning(["id"])
+ .executeTakeFirstOrThrow();
+
+ if (
+ skipValuation ||
+ item.itemTrackingType === "Non-Inventory" ||
+ ledger.quantity === 0
+ ) {
+ return { itemLedgerId: inserted.id, journalId: null, cost: 0 };
+ }
+
+ const absQuantity = Math.abs(ledger.quantity);
+ const documentId = ledger.documentId ?? inserted.id;
+ let cost = 0;
+
+ if (ledger.quantity < 0) {
+ // Decrease: relieve carrying value exactly as shipments do — consume
+ // layers (FIFO/LIFO) / current cost (Average/Standard).
+ const cogs = await calculateCOGS(trx, {
+ itemId: ledger.itemId,
+ quantity: absQuantity,
+ companyId,
+ });
+ cost = cogs.totalCost;
+
+ await trx
+ .insertInto("costLedger")
+ .values({
+ itemLedgerType: ledger.entryType,
+ costLedgerType: "Direct Cost",
+ adjustment: false,
+ documentType: ledger.documentType ?? null,
+ documentId,
+ itemId: ledger.itemId,
+ quantity: -absQuantity,
+ cost: -cogs.totalCost,
+ remainingQuantity: 0,
+ companyId,
+ })
+ .execute();
+ } else {
+ // Increase: create a layer at the item's current carrying cost. Same
+ // open-layer filters as calculateCOGS so both sides of the math agree.
+ const openLayers = await trx
+ .selectFrom("costLedger")
+ .select(["id", "quantity", "remainingQuantity", "cost"])
+ .where("itemId", "=", ledger.itemId)
+ .where("companyId", "=", companyId)
+ .where("remainingQuantity", ">", 0)
+ .where("adjustment", "=", false)
+ .where("appliesToCostLedgerId", "is", null)
+ .where((eb) =>
+ eb.or([
+ eb("documentType", "is", null),
+ eb("documentType", "!=", "Purchase Order"),
+ ])
+ )
+ .execute();
+
+ const appliedChildCostByLayer = new Map<string, number>();
+ if (openLayers.length > 0) {
+ const children = await trx
+ .selectFrom("costLedger")
+ .select(["appliesToCostLedgerId", "cost"])
+ .where(
+ "appliesToCostLedgerId",
+ "in",
+ openLayers.map((layer) => layer.id)
+ )
+ .where("companyId", "=", companyId)
+ .execute();
+ for (const child of children) {
+ const key = child.appliesToCostLedgerId as string;
+ appliedChildCostByLayer.set(
+ key,
+ (appliedChildCostByLayer.get(key) ?? 0) + Number(child.cost)
+ );
+ }
+ }
+
+ const unitCost = computeCurrentUnitCost(
+ itemCost,
+ openLayers.map((layer) => ({
+ quantity: Number(layer.quantity),
+ remainingQuantity: Number(layer.remainingQuantity),
+ cost: Number(layer.cost),
+ appliedChildCost: appliedChildCostByLayer.get(layer.id) ?? 0,
+ }))
+ );
+ cost = absQuantity * unitCost;
+
+ await trx
+ .insertInto("costLedger")
+ .values({
+ itemLedgerType: ledger.entryType,
+ costLedgerType: "Direct Cost",
+ adjustment: false,
+ documentType: ledger.documentType ?? null,
+ documentId,
+ itemId: ledger.itemId,
+ quantity: absQuantity,
+ cost,
+ remainingQuantity: absQuantity,
+ companyId,
+ })
+ .execute();
+ }
+
+ // A zero-value movement posts no journal (nothing to tie out; a $0-net
+ // entry is noise).
+ if (!accounting || cost === 0) {
+ return { itemLedgerId: inserted.id, journalId: null, cost };
+ }
+
+ const journalId = accounting.getJournalId
+ ? await accounting.getJournalId()
+ : await createAdjustmentJournal(trx, {
+ companyId,
+ accountingPeriodId: accounting.accountingPeriodId,
+ description: accounting.description,
+ postingDate: ledger.postingDate,
+ userId: accounting.userId,
+ });
+
+ const inventoryAccount = resolveInventoryAccount(
+ item.replenishmentSystem,
+ accounting.accountDefaults
+ );
+ const journalLineReference = nanoid();
+ const journalLineDocumentType = ledger.documentType ?? "Inventory Adjustment";
+ const isGain = ledger.quantity > 0;
+
+ const journalLines = await trx
+ .insertInto("journalLine")
+ .values([
+ {
+ journalId,
+ accountId: inventoryAccount.account,
+ description: inventoryAccount.description,
+ amount: isGain ? debit("asset", cost) : credit("asset", cost),
+ quantity: absQuantity,
+ documentType: journalLineDocumentType,
+ documentId,
+ journalLineReference,
+ companyId,
+ },
+ {
+ journalId,
+ accountId: accounting.accountDefaults.inventoryAdjustmentVarianceAccount,
+ description: "Inventory Adjustment",
+ amount: isGain ? credit("expense", cost) : debit("expense", cost),
+ quantity: absQuantity,
+ documentType: journalLineDocumentType,
+ documentId,
+ journalLineReference,
+ companyId,
+ },
+ ])
+ .returning(["id"])
+ .execute();
+
+ // Dimension tags (post-shipment precedent): every line of the entry gets
+ // the movement's Item / ItemPostingGroup / Location, for whichever
+ // dimensions are active on the company group.
+ const dimensions = accounting.dimensions ?? {};
+ const dimensionValues: Array<[string, string | null | undefined]> = [
+ ["Item", ledger.itemId],
+ ["ItemPostingGroup", item.itemPostingGroupId],
+ ["Location", ledger.locationId],
+ ];
+ const journalLineDimensionInserts = journalLines.flatMap((line) =>
+ dimensionValues
+ .filter(([entityType, valueId]) => dimensions[entityType] && valueId)
+ .map(([entityType, valueId]) => ({
+ journalLineId: line.id,
+ dimensionId: dimensions[entityType],
+ valueId: valueId as string,
+ companyId,
+ }))
+ );
+ if (journalLineDimensionInserts.length > 0) {
+ await trx
+ .insertInto("journalLineDimension")
+ .values(journalLineDimensionInserts)
+ .execute();
+ }
+
+ return { itemLedgerId: inserted.id, journalId, cost };
+}
diff --git a/packages/database/supabase/migrations/20260715021050_inventory-valuation-rpc.sql b/packages/database/supabase/migrations/20260715021050_inventory-valuation-rpc.sql
new file mode 100644
index 0000000000..3bce3c0673
--- /dev/null
+++ b/packages/database/supabase/migrations/20260715021050_inventory-valuation-rpc.sql
@@ -0,0 +1,251 @@
+-- ============================================================
+-- get_inventory_valuation: method-faithful inventory value by (item, location).
+-- Spec: .ai/specs/2026-07-14-inventory-value-report.md
+--
+-- * quantityOnHand = ALL physical stock (On Hold + Rejected included; they are
+-- assets until written off). quantityOnHold / quantityRejected are additive
+-- breakdown columns from the denormalized itemLedger.trackedEntityStatus.
+-- * unitCost: FIFO/LIFO = remaining cost-layer value incl. applied adjustment
+-- children (appliesToCostLedgerId), fallback itemCost.unitCost when no open
+-- layers; Average = itemCost.unitCost; Standard = itemCost.standardCost.
+-- This is the completeness spec's carrying CTE
+-- (.ai/specs/2026-07-04-inventory-valuation-completeness.md §3).
+-- * as_of_date NULL/today: snapshot + delta (exact 20260713235406 pattern).
+-- as_of_date in the past: raw itemLedger scan filtered by postingDate —
+-- the snapshot has no date grain. Costs are ALWAYS current-state; the UI
+-- labels dated results accordingly.
+-- * Status buckets reflect CURRENT tracked-entity statuses even for past
+-- dates (statuses are rewritten in place by 20260420112047).
+-- ============================================================
+
+DROP FUNCTION IF EXISTS get_inventory_valuation(TEXT, DATE, TEXT);
+
+CREATE OR REPLACE FUNCTION get_inventory_valuation(
+ company_id TEXT,
+ as_of_date DATE DEFAULT NULL,
+ location_id TEXT DEFAULT NULL
+)
+RETURNS TABLE (
+ "locationId" TEXT,
+ "locationName" TEXT,
+ "itemId" TEXT,
+ "readableIdWithRevision" TEXT,
+ "name" TEXT,
+ "thumbnailPath" TEXT,
+ "type" "itemType",
+ "replenishmentSystem" "itemReplenishmentSystem",
+ "unitOfMeasureCode" TEXT,
+ "costingMethod" "itemCostingMethod",
+ "quantityOnHand" NUMERIC,
+ "quantityOnHold" NUMERIC,
+ "quantityRejected" NUMERIC,
+ "unitCost" NUMERIC,
+ "totalValue" NUMERIC
+) AS $$
+DECLARE
+ v_cutoff TIMESTAMPTZ;
+ v_dated BOOLEAN := as_of_date IS NOT NULL AND as_of_date < CURRENT_DATE;
+BEGIN
+ SELECT MAX("snapshotCutoff") INTO v_cutoff
+ FROM "itemLedgerSnapshot"
+ WHERE "companyId" = company_id;
+
+ RETURN QUERY
+ WITH quantities AS (
+ SELECT
+ combined."itemId",
+ combined."locationId",
+ SUM(combined."quantity") AS "quantityOnHand",
+ SUM(combined."onHold") AS "quantityOnHold",
+ SUM(combined."rejected") AS "quantityRejected"
+ FROM (
+ -- Arm 1: snapshot (untracked, immutable). Skipped on dated queries —
+ -- the snapshot has no postingDate grain.
+ SELECT
+ s."itemId",
+ NULLIF(s."locationId", '') AS "locationId",
+ s."quantity",
+ 0::NUMERIC AS "onHold",
+ 0::NUMERIC AS "rejected"
+ FROM "itemLedgerSnapshot" s
+ WHERE NOT v_dated
+ AND s."companyId" = company_id
+ AND (location_id IS NULL OR s."locationId" = location_id)
+
+ UNION ALL
+
+ -- Arm 2: tracked rows, always live (status flips in place).
+ SELECT
+ il."itemId",
+ il."locationId",
+ il."quantity",
+ CASE WHEN il."trackedEntityStatus" = 'On Hold' THEN il."quantity" ELSE 0 END,
+ CASE WHEN il."trackedEntityStatus" = 'Rejected' THEN il."quantity" ELSE 0 END
+ FROM "itemLedger" il
+ WHERE il."companyId" = company_id
+ AND il."trackedEntityId" IS NOT NULL
+ AND (location_id IS NULL OR il."locationId" = location_id)
+ AND (NOT v_dated OR il."postingDate" <= as_of_date)
+
+ UNION ALL
+
+ -- Arm 3: untracked delta past the cutoff (current path) OR the full
+ -- untracked history filtered by postingDate (dated path / no snapshot).
+ SELECT
+ il."itemId",
+ il."locationId",
+ il."quantity",
+ 0::NUMERIC,
+ 0::NUMERIC
+ FROM "itemLedger" il
+ WHERE il."companyId" = company_id
+ AND il."trackedEntityId" IS NULL
+ AND (location_id IS NULL OR il."locationId" = location_id)
+ AND (v_dated OR v_cutoff IS NULL OR il."createdAt" >= v_cutoff)
+ AND (NOT v_dated OR il."postingDate" <= as_of_date)
+ ) combined
+ GROUP BY combined."itemId", combined."locationId"
+ HAVING SUM(combined."quantity") <> 0
+ ),
+ carrying AS (
+ -- Company-level effective unit cost per item, by costing method.
+ SELECT
+ ic."itemId",
+ ic."costingMethod",
+ CASE ic."costingMethod"
+ WHEN 'Standard' THEN ic."standardCost"
+ WHEN 'Average' THEN ic."unitCost"
+ ELSE COALESCE(layers."layerUnitCost", ic."unitCost")
+ END AS "unitCost"
+ FROM "itemCost" ic
+ LEFT JOIN LATERAL (
+ SELECT
+ SUM(
+ cl."remainingQuantity"
+ * (cl."cost" + COALESCE(adj."applied", 0))
+ / NULLIF(cl."quantity", 0)
+ ) / NULLIF(SUM(cl."remainingQuantity"), 0) AS "layerUnitCost"
+ FROM "costLedger" cl
+ LEFT JOIN LATERAL (
+ SELECT SUM(a."cost") AS "applied"
+ FROM "costLedger" a
+ WHERE a."appliesToCostLedgerId" = cl."id"
+ AND a."companyId" = cl."companyId"
+ ) adj ON TRUE
+ WHERE cl."itemId" = ic."itemId"
+ AND cl."companyId" = ic."companyId"
+ AND cl."remainingQuantity" > 0
+ ) layers ON ic."costingMethod" IN ('FIFO', 'LIFO')
+ WHERE ic."companyId" = company_id
+ )
+ SELECT
+ l."id" AS "locationId",
+ l."name" AS "locationName",
+ i."id" AS "itemId",
+ i."readableIdWithRevision",
+ i."name",
+ CASE
+ WHEN i."thumbnailPath" IS NULL AND mu."thumbnailPath" IS NOT NULL THEN mu."thumbnailPath"
+ ELSE i."thumbnailPath"
+ END AS "thumbnailPath",
+ i."type",
+ i."replenishmentSystem",
+ i."unitOfMeasureCode",
+ c."costingMethod",
+ q."quantityOnHand",
+ q."quantityOnHold",
+ q."quantityRejected",
+ COALESCE(c."unitCost", 0) AS "unitCost",
+ q."quantityOnHand" * COALESCE(c."unitCost", 0) AS "totalValue"
+ FROM quantities q
+ INNER JOIN "item" i ON q."itemId" = i."id" AND i."companyId" = company_id
+ INNER JOIN "location" l ON q."locationId" = l."id" AND l."companyId" = company_id
+ LEFT JOIN "modelUpload" mu ON mu."id" = i."modelUploadId" AND mu."companyId" = company_id
+ LEFT JOIN carrying c ON c."itemId" = q."itemId"
+ ORDER BY l."name", i."readableIdWithRevision";
+END;
+$$ LANGUAGE plpgsql SECURITY DEFINER;
+
+-- ============================================================
+-- get_inventory_tie_out: subledger value vs GL balance per stock account
+-- (SAP MB5L shape). Subledger side calls get_inventory_valuation so the two
+-- surfaces can never disagree. Items classify to accounts exactly like
+-- resolveInventoryAccount (functions/shared/get-posting-group.ts):
+-- Make / Buy and Make -> finishedGoodsAccount, else rawMaterialsAccount.
+-- GL side follows the newest balance convention (20260713233919):
+-- journal.status <> 'Draft', journal.postingDate <= as-of, journalLine.accountId.
+-- ============================================================
+
+DROP FUNCTION IF EXISTS get_inventory_tie_out(TEXT, DATE);
+
+CREATE OR REPLACE FUNCTION get_inventory_tie_out(
+ company_id TEXT,
+ as_of_date DATE DEFAULT NULL
+)
+RETURNS TABLE (
+ "accountKind" TEXT,
+ "accountId" TEXT,
+ "accountName" TEXT,
+ "subledgerValue" NUMERIC,
+ "glBalance" NUMERIC,
+ "variance" NUMERIC
+) AS $$
+DECLARE
+ v_as_of DATE := COALESCE(as_of_date, CURRENT_DATE);
+ v_rm_account TEXT;
+ v_fg_account TEXT;
+BEGIN
+ SELECT ad."rawMaterialsAccount", ad."finishedGoodsAccount"
+ INTO v_rm_account, v_fg_account
+ FROM "accountDefault" ad
+ WHERE ad."companyId" = company_id;
+
+ IF v_rm_account IS NULL OR v_fg_account IS NULL THEN
+ RETURN; -- company has no account defaults (accounting never configured)
+ END IF;
+
+ RETURN QUERY
+ WITH subledger AS (
+ SELECT
+ CASE WHEN v."replenishmentSystem" IN ('Make', 'Buy and Make')
+ THEN 'finishedGoods' ELSE 'rawMaterials' END AS "kind",
+ SUM(v."totalValue") AS "value"
+ FROM get_inventory_valuation(company_id, as_of_date, NULL) v
+ GROUP BY 1
+ ),
+ gl AS (
+ SELECT jl."accountId" AS "account", SUM(jl."amount") AS "balance"
+ FROM "journal" j
+ INNER JOIN "journalLine" jl
+ ON jl."journalId" = j."id" AND jl."companyId" = j."companyId"
+ WHERE j."companyId" = company_id
+ AND j."status" <> 'Draft'
+ AND j."postingDate" <= v_as_of
+ AND jl."accountId" IN (v_rm_account, v_fg_account)
+ GROUP BY jl."accountId"
+ ),
+ accounts AS (
+ SELECT 'rawMaterials' AS "kind", v_rm_account AS "account"
+ UNION ALL
+ SELECT 'finishedGoods' AS "kind", v_fg_account AS "account"
+ )
+ SELECT
+ a."kind" AS "accountKind",
+ a."account" AS "accountId",
+ acc."name" AS "accountName",
+ COALESCE(s."value", 0) AS "subledgerValue",
+ COALESCE(g."balance", 0) AS "glBalance",
+ COALESCE(s."value", 0) - COALESCE(g."balance", 0) AS "variance"
+ -- account is companyGroup-scoped (no companyId); the ids come from the
+ -- company-scoped accountDefault row, so joining by id alone is correct.
+ FROM accounts a
+ LEFT JOIN "account" acc ON acc."id" = a."account"
+ LEFT JOIN subledger s ON s."kind" = a."kind"
+ LEFT JOIN gl g ON g."account" = a."account"
+ ORDER BY a."kind" DESC; -- rawMaterials first
+END;
+$$ LANGUAGE plpgsql SECURITY DEFINER;
+
+-- Kept per spec decision (grill Q5): superseded but not dropped.
+COMMENT ON FUNCTION get_inventory_value_by_location(TEXT) IS
+ 'Deprecated: superseded by get_inventory_valuation (method-faithful costs, status breakdown, as-of-date). Kept for API compatibility.';
diff --git a/packages/database/supabase/migrations/20260715040904_inventory-adjustment-gl-posting.sql b/packages/database/supabase/migrations/20260715040904_inventory-adjustment-gl-posting.sql
new file mode 100644
index 0000000000..af5e248b97
--- /dev/null
+++ b/packages/database/supabase/migrations/20260715040904_inventory-adjustment-gl-posting.sql
@@ -0,0 +1,5 @@
+-- Inventory adjustments and inventory counts now post GL journals
+-- (spec: .ai/specs/2026-07-14-inventory-adjustment-gl-posting.md).
+-- journalEntrySourceType already contains 'Inventory Adjustment' (20260402000000).
+ALTER TYPE "journalLineDocumentType" ADD VALUE IF NOT EXISTS 'Inventory Adjustment';
+ALTER TYPE "journalLineDocumentType" ADD VALUE IF NOT EXISTS 'Inventory Count';
diff --git a/packages/locale/locales/de/erp.po b/packages/locale/locales/de/erp.po
index 04a22556c7..1f74c46f74 100644
--- a/packages/locale/locales/de/erp.po
+++ b/packages/locale/locales/de/erp.po
@@ -137,6 +137,9 @@ msgstr "{variances, plural, one {# Zeile weicht von der erwarteten Menge ab} oth
msgid "/month/user"
msgstr "/Monat/Benutzer"
+msgid "% of Total"
+msgstr "% der Gesamtsumme"
+
#. placeholder {0}: numberFormatter.format(redirectedTotal)
#. placeholder {1}: redirectedParts.join(", ")
msgid "↩ {0} redirected from superseded {1}"
@@ -785,6 +788,9 @@ msgstr "Alle Artikel"
msgid "All jobs completed"
msgstr "Alle Aufträge abgeschlossen"
+msgid "All Locations"
+msgstr "Alle Standorte"
+
msgid "All members of selected groups and selected individuals will be able to approve requests"
msgstr "Alle Mitglieder der ausgewählten Gruppen und ausgewählten Personen können Anfragen genehmigen"
@@ -1827,6 +1833,12 @@ msgstr "Nach Dokumentdatum"
msgid "By Due Date"
msgstr "Nach Fälligkeitsdatum"
+msgid "By Item"
+msgstr "Nach Artikel"
+
+msgid "By Location"
+msgstr "Nach Standort"
+
msgid "By signing in, you agree to the <0>Terms of Service</0> and <1>Privacy Policy.</1>"
msgstr "Durch die Anmeldung stimmen Sie den <0>Nutzungsbedingungen</0> und der <1>Datenschutzrichtlinie</1> zu."
@@ -2257,6 +2269,9 @@ msgstr "Unternehmensname"
msgid "Company policy asks for a different person to inspect inbound items than the one who received them."
msgstr "Unternehmensrichtlinie verlangt, dass eine andere Person eingehende Artikel inspiziert als diejenige, die sie erhalten hat."
+msgid "Company-wide — includes all locations"
+msgstr "Unternehmensübergreifend – beinhaltet alle Standorte"
+
msgid "Compare and Order"
msgstr "Vergleichen und Bestellen"
@@ -6259,6 +6274,9 @@ msgstr "Bestandsverlauf"
msgid "Inventory Job Notifications"
msgstr "Bestandsverwaltungs-Jobbenachrichtigungen"
+msgid "Inventory Movements"
+msgstr "Bestandsbewegungen"
+
msgid "Inventory Qty"
msgstr "Bestandsmenge"
@@ -6268,6 +6286,9 @@ msgstr "Bestandsverfolgung"
msgid "Inventory Unit of Measure"
msgstr "Bestandseinheit"
+msgid "Inventory Valuation"
+msgstr "Bestandsbewertung"
+
msgid "Invite"
msgstr "Einladen"
@@ -6394,6 +6415,9 @@ msgstr "Artikel"
msgid "Item {scannedItem} is not the same as the item {expectedItem}"
msgstr "Artikel {scannedItem} ist nicht derselbe wie der Artikel {expectedItem}"
+msgid "Item / Location"
+msgstr "Artikel / Standort"
+
msgid "Item filters"
msgstr "Artikelfilter"
@@ -6777,6 +6801,9 @@ msgstr "Ort"
msgid "Location"
msgstr "Standort"
+msgid "Location / Item"
+msgstr "Standort / Artikel"
+
msgid "Location Name"
msgstr "Standortname"
@@ -7375,6 +7402,9 @@ msgstr "In den Papierkorb verschieben"
msgid "Moved {0} to {1} bucket"
msgstr "Verschoben {0} zu {1} Bucket"
+msgid "Movements"
+msgstr "Bewegungen"
+
msgid "MRP (planning)"
msgstr "MRP (Planung)"
@@ -9284,6 +9314,9 @@ msgstr "QR-Code zum Starten des nächsten Vorgangs für diesen Kanban"
msgid "Qty"
msgstr "Menge"
+msgid "Qty On Hand"
+msgstr "Bestandsmenge"
+
msgid "Qty to Order"
msgstr "Bestellmenge"
@@ -9583,6 +9616,9 @@ msgstr "Kürzliche Zahlungen"
msgid "Recently Created"
msgstr "Kürzlich erstellt"
+msgid "Reconcile"
+msgstr "Abstimmen"
+
msgid "Reconciling a purchase order against what was received and invoiced — implicit in Carbon, via the line quantities and GR/IR balance."
msgstr "Abschreibungsdauer"
@@ -11162,9 +11198,6 @@ msgstr "Schritte"
msgid "Steps"
msgstr "Schritte"
-msgid "Stock Movements"
-msgstr "Lagerbewegungen"
-
msgid "Stock Transfer ID"
msgstr "Lagerbestandstransfer-ID"
@@ -12486,6 +12519,9 @@ msgstr "Lieferungen direkt mit einer Rechnung verknüpfen ohne erneute Eingabe"
msgid "Tie-Out"
msgstr "Abstimmung"
+msgid "Tie-Out unavailable"
+msgstr "Tie-Out nicht verfügbar"
+
msgid "Tightened"
msgstr "Gestrafft"
@@ -12621,6 +12657,12 @@ msgstr "Gesamtbestand des Artikels über alle Lagereinheiten an diesem Standort.
msgid "Total quantity required across all active jobs and sales orders at this location — not just this job."
msgstr "Gesamtmenge, die über alle aktiven Aufträge und Kundenaufträge an diesem Standort benötigt wird – nicht nur für diesen Auftrag."
+msgid "Total Value"
+msgstr "Gesamtwert"
+
+msgid "Total Variance"
+msgstr "Gesamtabweichung"
+
msgid "Total:"
msgstr "Gesamt:"
@@ -13123,6 +13165,9 @@ msgstr "Validiert"
msgid "Validating job..."
msgstr "Auftrag wird validiert..."
+msgid "Valuation"
+msgstr "Bewertung"
+
msgid "Value"
msgstr "Wert"
@@ -13138,6 +13183,9 @@ msgstr "Umsatzsteuer-Identifikationsnummer; erforderlich auf EU-Rechnungen für
msgid "Values"
msgstr "Werte"
+msgid "Values apply today's unit costs to historical quantities."
+msgstr "Die Werte wenden die heutigen Stückkosten auf historische Mengen an."
+
msgid "Variance"
msgstr "Abweichung"
diff --git a/packages/locale/locales/en/erp.po b/packages/locale/locales/en/erp.po
index 7425e3636e..73a5facf5e 100644
--- a/packages/locale/locales/en/erp.po
+++ b/packages/locale/locales/en/erp.po
@@ -137,6 +137,9 @@ msgstr "{variances, plural, one {# line differs from the expected quantity} othe
msgid "/month/user"
msgstr "/month/user"
+msgid "% of Total"
+msgstr "% of Total"
+
#. placeholder {0}: numberFormatter.format(redirectedTotal)
#. placeholder {1}: redirectedParts.join(", ")
msgid "↩ {0} redirected from superseded {1}"
@@ -785,6 +788,9 @@ msgstr "All Items"
msgid "All jobs completed"
msgstr "All jobs completed"
+msgid "All Locations"
+msgstr "All Locations"
+
msgid "All members of selected groups and selected individuals will be able to approve requests"
msgstr "All members of selected groups and selected individuals will be able to approve requests"
@@ -1827,6 +1833,12 @@ msgstr "By Document Date"
msgid "By Due Date"
msgstr "By Due Date"
+msgid "By Item"
+msgstr "By Item"
+
+msgid "By Location"
+msgstr "By Location"
+
msgid "By signing in, you agree to the <0>Terms of Service</0> and <1>Privacy Policy.</1>"
msgstr "By signing in, you agree to the <0>Terms of Service</0> and <1>Privacy Policy.</1>"
@@ -2257,6 +2269,9 @@ msgstr "Company Name"
msgid "Company policy asks for a different person to inspect inbound items than the one who received them."
msgstr "Company policy asks for a different person to inspect inbound items than the one who received them."
+msgid "Company-wide — includes all locations"
+msgstr "Company-wide — includes all locations"
+
msgid "Compare and Order"
msgstr "Compare and Order"
@@ -6259,6 +6274,9 @@ msgstr "Inventory History"
msgid "Inventory Job Notifications"
msgstr "Inventory Job Notifications"
+msgid "Inventory Movements"
+msgstr "Inventory Movements"
+
msgid "Inventory Qty"
msgstr "Inventory Qty"
@@ -6268,6 +6286,9 @@ msgstr "Inventory Tracking"
msgid "Inventory Unit of Measure"
msgstr "Inventory Unit of Measure"
+msgid "Inventory Valuation"
+msgstr "Inventory Valuation"
+
msgid "Invite"
msgstr "Invite"
@@ -6394,6 +6415,9 @@ msgstr "Item"
msgid "Item {scannedItem} is not the same as the item {expectedItem}"
msgstr "Item {scannedItem} is not the same as the item {expectedItem}"
+msgid "Item / Location"
+msgstr "Item / Location"
+
msgid "Item filters"
msgstr "Item filters"
@@ -6777,6 +6801,9 @@ msgstr "location"
msgid "Location"
msgstr "Location"
+msgid "Location / Item"
+msgstr "Location / Item"
+
msgid "Location Name"
msgstr "Location Name"
@@ -7375,6 +7402,9 @@ msgstr "Move to Trash"
msgid "Moved {0} to {1} bucket"
msgstr "Moved {0} to {1} bucket"
+msgid "Movements"
+msgstr "Movements"
+
msgid "MRP (planning)"
msgstr "MRP (planning)"
@@ -9284,6 +9314,9 @@ msgstr "QR Code to start the next operation for this kanban"
msgid "Qty"
msgstr "Qty"
+msgid "Qty On Hand"
+msgstr "Qty On Hand"
+
msgid "Qty to Order"
msgstr "Qty to Order"
@@ -9583,6 +9616,9 @@ msgstr "Recent payments"
msgid "Recently Created"
msgstr "Recently Created"
+msgid "Reconcile"
+msgstr "Reconcile"
+
msgid "Reconciling a purchase order against what was received and invoiced — implicit in Carbon, via the line quantities and GR/IR balance."
msgstr "Reconciling a purchase order against what was received and invoiced — implicit in Carbon, via the line quantities and GR/IR balance."
@@ -11162,9 +11198,6 @@ msgstr "steps"
msgid "Steps"
msgstr "Steps"
-msgid "Stock Movements"
-msgstr "Stock Movements"
-
msgid "Stock Transfer ID"
msgstr "Stock Transfer ID"
@@ -12486,6 +12519,9 @@ msgstr "Tie shipments through to an invoice with no re-keying"
msgid "Tie-Out"
msgstr "Tie-Out"
+msgid "Tie-Out unavailable"
+msgstr "Tie-Out unavailable"
+
msgid "Tightened"
msgstr "Tightened"
@@ -12621,6 +12657,12 @@ msgstr "Total quantity on hand for the item across all storage units at this loc
msgid "Total quantity required across all active jobs and sales orders at this location — not just this job."
msgstr "Total quantity required across all active jobs and sales orders at this location — not just this job."
+msgid "Total Value"
+msgstr "Total Value"
+
+msgid "Total Variance"
+msgstr "Total Variance"
+
msgid "Total:"
msgstr "Total:"
@@ -13123,6 +13165,9 @@ msgstr "Validated"
msgid "Validating job..."
msgstr "Validating job..."
+msgid "Valuation"
+msgstr "Valuation"
+
msgid "Value"
msgstr "Value"
@@ -13138,6 +13183,9 @@ msgstr "Value-added-tax registration number; required on EU invoices for reverse
msgid "Values"
msgstr "Values"
+msgid "Values apply today's unit costs to historical quantities."
+msgstr "Values apply today's unit costs to historical quantities."
+
msgid "Variance"
msgstr "Variance"
diff --git a/packages/locale/locales/es/erp.po b/packages/locale/locales/es/erp.po
index 1f076a8401..578b97149c 100644
--- a/packages/locale/locales/es/erp.po
+++ b/packages/locale/locales/es/erp.po
@@ -137,6 +137,9 @@ msgstr "{variances, plural, one {# línea difiere de la cantidad esperada} other
msgid "/month/user"
msgstr "/mes/usuario"
+msgid "% of Total"
+msgstr "% del Total"
+
#. placeholder {0}: numberFormatter.format(redirectedTotal)
#. placeholder {1}: redirectedParts.join(", ")
msgid "↩ {0} redirected from superseded {1}"
@@ -785,6 +788,9 @@ msgstr "Todos los artículos"
msgid "All jobs completed"
msgstr "Todos los trabajos completados"
+msgid "All Locations"
+msgstr "Todas las Ubicaciones"
+
msgid "All members of selected groups and selected individuals will be able to approve requests"
msgstr "Todos los miembros de los grupos seleccionados e individuos seleccionados podrán aprobar solicitudes"
@@ -1827,6 +1833,12 @@ msgstr "Por Fecha de Documento"
msgid "By Due Date"
msgstr "Por Fecha de Vencimiento"
+msgid "By Item"
+msgstr "Por Artículo"
+
+msgid "By Location"
+msgstr "Por Ubicación"
+
msgid "By signing in, you agree to the <0>Terms of Service</0> and <1>Privacy Policy.</1>"
msgstr "Al iniciar sesión, aceptas los <0>Términos de Servicio</0> y la <1>Política de Privacidad.</1>"
@@ -2257,6 +2269,9 @@ msgstr "Nombre de la Empresa"
msgid "Company policy asks for a different person to inspect inbound items than the one who received them."
msgstr "La política de la empresa requiere que una persona diferente inspeccione los artículos recibidos que la que los recibió."
+msgid "Company-wide — includes all locations"
+msgstr "Toda la empresa — incluye todas las ubicaciones"
+
msgid "Compare and Order"
msgstr "Comparar y Ordenar"
@@ -6259,6 +6274,9 @@ msgstr "Historial de Inventario"
msgid "Inventory Job Notifications"
msgstr "Notificaciones de Trabajos de Inventario"
+msgid "Inventory Movements"
+msgstr "Movimientos de Inventario"
+
msgid "Inventory Qty"
msgstr "Cantidad de Inventario"
@@ -6268,6 +6286,9 @@ msgstr "Seguimiento de Inventario"
msgid "Inventory Unit of Measure"
msgstr "Unidad de Medida de Inventario"
+msgid "Inventory Valuation"
+msgstr "Valoración de Inventario"
+
msgid "Invite"
msgstr "Invitar"
@@ -6394,6 +6415,9 @@ msgstr "Artículo"
msgid "Item {scannedItem} is not the same as the item {expectedItem}"
msgstr "El artículo {scannedItem} no es el mismo que el artículo {expectedItem}"
+msgid "Item / Location"
+msgstr "Artículo / Ubicación"
+
msgid "Item filters"
msgstr "Filtros de artículos"
@@ -6777,6 +6801,9 @@ msgstr "ubicación"
msgid "Location"
msgstr "Ubicación"
+msgid "Location / Item"
+msgstr "Ubicación / Artículo"
+
msgid "Location Name"
msgstr "Nombre de Ubicación"
@@ -7375,6 +7402,9 @@ msgstr "Mover a la papelera"
msgid "Moved {0} to {1} bucket"
msgstr "Movido {0} al bucket {1}"
+msgid "Movements"
+msgstr "Movimientos"
+
msgid "MRP (planning)"
msgstr "MRP (planificación)"
@@ -9284,6 +9314,9 @@ msgstr "Código QR para iniciar la siguiente operación para este kanban"
msgid "Qty"
msgstr "Cant."
+msgid "Qty On Hand"
+msgstr "Cantidad Disponible"
+
msgid "Qty to Order"
msgstr "Cantidad a Pedir"
@@ -9583,6 +9616,9 @@ msgstr "Pagos recientes"
msgid "Recently Created"
msgstr "Creado Recientemente"
+msgid "Reconcile"
+msgstr "Reconciliar"
+
msgid "Reconciling a purchase order against what was received and invoiced — implicit in Carbon, via the line quantities and GR/IR balance."
msgstr "Período de Recuperación"
@@ -11162,9 +11198,6 @@ msgstr "pasos"
msgid "Steps"
msgstr "Pasos"
-msgid "Stock Movements"
-msgstr "Movimientos de Inventario"
-
msgid "Stock Transfer ID"
msgstr "ID de Transferencia de Inventario"
@@ -12486,6 +12519,9 @@ msgstr "Vincular envíos a una factura sin re-ingreso de datos"
msgid "Tie-Out"
msgstr "Conciliación"
+msgid "Tie-Out unavailable"
+msgstr "Conciliación no disponible"
+
msgid "Tightened"
msgstr "Apretado"
@@ -12621,6 +12657,12 @@ msgstr "Cantidad total disponible del artículo en todas las unidades de almacen
msgid "Total quantity required across all active jobs and sales orders at this location — not just this job."
msgstr "Cantidad total requerida en todos los trabajos activos y órdenes de venta en esta ubicación, no solo en este trabajo."
+msgid "Total Value"
+msgstr "Valor Total"
+
+msgid "Total Variance"
+msgstr "Varianza Total"
+
msgid "Total:"
msgstr "Total:"
@@ -13123,6 +13165,9 @@ msgstr "Validado"
msgid "Validating job..."
msgstr "Validando trabajo..."
+msgid "Valuation"
+msgstr "Valoración"
+
msgid "Value"
msgstr "Valor"
@@ -13138,6 +13183,9 @@ msgstr "Número de registro del impuesto al valor agregado; requerido en factura
msgid "Values"
msgstr "Valores"
+msgid "Values apply today's unit costs to historical quantities."
+msgstr "Los valores aplican los costos unitarios de hoy a las cantidades históricas."
+
msgid "Variance"
msgstr "Variación"
diff --git a/packages/locale/locales/fr/erp.po b/packages/locale/locales/fr/erp.po
index b3d78cfab4..c0d793f84e 100644
--- a/packages/locale/locales/fr/erp.po
+++ b/packages/locale/locales/fr/erp.po
@@ -137,6 +137,9 @@ msgstr "{variances, plural, one {# ligne diffère de la quantité attendue} othe
msgid "/month/user"
msgstr "/mois/utilisateur"
+msgid "% of Total"
+msgstr "% du Total"
+
#. placeholder {0}: numberFormatter.format(redirectedTotal)
#. placeholder {1}: redirectedParts.join(", ")
msgid "↩ {0} redirected from superseded {1}"
@@ -785,6 +788,9 @@ msgstr "Tous les articles"
msgid "All jobs completed"
msgstr "Tous les travaux sont terminés"
+msgid "All Locations"
+msgstr "Tous les Emplacements"
+
msgid "All members of selected groups and selected individuals will be able to approve requests"
msgstr "Tous les membres des groupes sélectionnés et les individus sélectionnés pourront approuver les demandes"
@@ -1827,6 +1833,12 @@ msgstr "Par date du document"
msgid "By Due Date"
msgstr "Par date d'échéance"
+msgid "By Item"
+msgstr "Par Article"
+
+msgid "By Location"
+msgstr "Par Emplacement"
+
msgid "By signing in, you agree to the <0>Terms of Service</0> and <1>Privacy Policy.</1>"
msgstr "En vous connectant, vous acceptez les <0>Conditions d'utilisation</0> et la <1>Politique de confidentialité.</1>"
@@ -2257,6 +2269,9 @@ msgstr "Nom de l'entreprise"
msgid "Company policy asks for a different person to inspect inbound items than the one who received them."
msgstr "La politique de l'entreprise exige qu'une personne différente inspecte les articles entrants de celle qui les a reçus."
+msgid "Company-wide — includes all locations"
+msgstr "À l'échelle de l'entreprise — inclut tous les emplacements"
+
msgid "Compare and Order"
msgstr "Comparer et commander"
@@ -6259,6 +6274,9 @@ msgstr "Historique d'inventaire"
msgid "Inventory Job Notifications"
msgstr "Notifications de travaux d'inventaire"
+msgid "Inventory Movements"
+msgstr "Mouvements d'inventaire"
+
msgid "Inventory Qty"
msgstr "Quantité Inventaire"
@@ -6268,6 +6286,9 @@ msgstr "Suivi des stocks"
msgid "Inventory Unit of Measure"
msgstr "Unité de mesure d'inventaire"
+msgid "Inventory Valuation"
+msgstr "Évaluation des Stocks"
+
msgid "Invite"
msgstr "Inviter"
@@ -6394,6 +6415,9 @@ msgstr "Article"
msgid "Item {scannedItem} is not the same as the item {expectedItem}"
msgstr "L'article {scannedItem} n'est pas le même que l'article {expectedItem}"
+msgid "Item / Location"
+msgstr "Article / Emplacement"
+
msgid "Item filters"
msgstr "Filtres d'articles"
@@ -6777,6 +6801,9 @@ msgstr "localisation"
msgid "Location"
msgstr "Emplacement"
+msgid "Location / Item"
+msgstr "Emplacement / Article"
+
msgid "Location Name"
msgstr "Nom du lieu"
@@ -7375,6 +7402,9 @@ msgstr "Déplacer vers la corbeille"
msgid "Moved {0} to {1} bucket"
msgstr "Déplacé {0} vers le bucket {1}"
+msgid "Movements"
+msgstr "Mouvements"
+
msgid "MRP (planning)"
msgstr "MRP (planification)"
@@ -9284,6 +9314,9 @@ msgstr "Code QR pour démarrer l'opération suivante pour ce kanban"
msgid "Qty"
msgstr "Qté"
+msgid "Qty On Hand"
+msgstr "Quantité Disponible"
+
msgid "Qty to Order"
msgstr "Qté à commander"
@@ -9583,6 +9616,9 @@ msgstr "Paiements récents"
msgid "Recently Created"
msgstr "Récemment créé"
+msgid "Reconcile"
+msgstr "Rapprocher"
+
msgid "Reconciling a purchase order against what was received and invoiced — implicit in Carbon, via the line quantities and GR/IR balance."
msgstr "Durée d'Amortissement"
@@ -11162,9 +11198,6 @@ msgstr "étapes"
msgid "Steps"
msgstr "Étapes"
-msgid "Stock Movements"
-msgstr "Mouvements de Stock"
-
msgid "Stock Transfer ID"
msgstr "ID de transfert de stock"
@@ -12486,6 +12519,9 @@ msgstr "Lier les expéditions à une facture sans ressaisie"
msgid "Tie-Out"
msgstr "Rapprochement"
+msgid "Tie-Out unavailable"
+msgstr "Rapprochement indisponible"
+
msgid "Tightened"
msgstr "Serré"
@@ -12621,6 +12657,12 @@ msgstr "Quantité totale disponible de l'article sur toutes les unités de stock
msgid "Total quantity required across all active jobs and sales orders at this location — not just this job."
msgstr "Quantité totale requise sur toutes les tâches actives et commandes clients à cet emplacement — pas seulement cette tâche."
+msgid "Total Value"
+msgstr "Valeur Totale"
+
+msgid "Total Variance"
+msgstr "Variance Totale"
+
msgid "Total:"
msgstr "Total :"
@@ -13123,6 +13165,9 @@ msgstr "Validé"
msgid "Validating job..."
msgstr "Validation du travail en cours..."
+msgid "Valuation"
+msgstr "Évaluation"
+
msgid "Value"
msgstr "Valeur"
@@ -13138,6 +13183,9 @@ msgstr "Numéro d'enregistrement de la taxe sur la valeur ajoutée ; requis sur
msgid "Values"
msgstr "Valeurs"
+msgid "Values apply today's unit costs to historical quantities."
+msgstr "Les valeurs appliquent les coûts unitaires d'aujourd'hui aux quantités historiques."
+
msgid "Variance"
msgstr "Écart"
diff --git a/packages/locale/locales/hi/erp.po b/packages/locale/locales/hi/erp.po
index eb5d4b8fad..65303d2ece 100644
--- a/packages/locale/locales/hi/erp.po
+++ b/packages/locale/locales/hi/erp.po
@@ -137,6 +137,9 @@ msgstr "{variances, plural, one {# लाइन अपेक्षित मा
msgid "/month/user"
msgstr "/माह/उपयोगकर्ता"
+msgid "% of Total"
+msgstr "कुल का %"
+
#. placeholder {0}: numberFormatter.format(redirectedTotal)
#. placeholder {1}: redirectedParts.join(", ")
msgid "↩ {0} redirected from superseded {1}"
@@ -785,6 +788,9 @@ msgstr "सभी आइटम"
msgid "All jobs completed"
msgstr "सभी नौकरियां पूरी हुईं"
+msgid "All Locations"
+msgstr "सभी स्थान"
+
msgid "All members of selected groups and selected individuals will be able to approve requests"
msgstr "चयनित समूहों के सभी सदस्य और चयनित व्यक्ति अनुरोधों को मंजूरी दे सकेंगे"
@@ -1827,6 +1833,12 @@ msgstr "दस्तावेज़ तारीख के अनुसार"
msgid "By Due Date"
msgstr "देय तारीख के अनुसार"
+msgid "By Item"
+msgstr "आइटम के अनुसार"
+
+msgid "By Location"
+msgstr "स्थान के अनुसार"
+
msgid "By signing in, you agree to the <0>Terms of Service</0> and <1>Privacy Policy.</1>"
msgstr "साइन इन करके, आप <0>सेवा की शर्तें</0> और <1>गोपनीयता नीति</1> से सहमत हैं।"
@@ -2257,6 +2269,9 @@ msgstr "कंपनी का नाम"
msgid "Company policy asks for a different person to inspect inbound items than the one who received them."
msgstr "कंपनी की नीति के अनुसार, इनबाउंड आइटम्स का निरीक्षण उस व्यक्ति के अलावा किसी और को करना चाहिए जिसने उन्हें प्राप्त किया है।"
+msgid "Company-wide — includes all locations"
+msgstr "कंपनी-व्यापी — सभी स्थानों को शामिल करता है"
+
msgid "Compare and Order"
msgstr "तुलना करें और ऑर्डर करें"
@@ -6259,6 +6274,9 @@ msgstr "इन्वेंटरी इतिहास"
msgid "Inventory Job Notifications"
msgstr "इन्वेंटरी जॉब नोटिफिकेशन"
+msgid "Inventory Movements"
+msgstr "इन्वेंटरी मूवमेंट्स"
+
msgid "Inventory Qty"
msgstr "इन्वेंटरी मात्रा"
@@ -6268,6 +6286,9 @@ msgstr "इन्वेंटरी ट्रैकिंग"
msgid "Inventory Unit of Measure"
msgstr "इन्वेंटरी माप की इकाई"
+msgid "Inventory Valuation"
+msgstr "इन्वेंटरी मूल्यांकन"
+
msgid "Invite"
msgstr "आमंत्रित करें"
@@ -6394,6 +6415,9 @@ msgstr "आइटम"
msgid "Item {scannedItem} is not the same as the item {expectedItem}"
msgstr "आइटम {scannedItem} आइटम {expectedItem} के समान नहीं है"
+msgid "Item / Location"
+msgstr "आइटम / स्थान"
+
msgid "Item filters"
msgstr "आइटम फ़िल्टर"
@@ -6777,6 +6801,9 @@ msgstr "स्थान"
msgid "Location"
msgstr "स्थान"
+msgid "Location / Item"
+msgstr "स्थान / आइटम"
+
msgid "Location Name"
msgstr "स्थान का नाम"
@@ -7375,6 +7402,9 @@ msgstr "ट्रैश में स्थानांतरित करें
msgid "Moved {0} to {1} bucket"
msgstr "{0} को {1} बकेट में स्थानांतरित किया गया"
+msgid "Movements"
+msgstr "मूवमेंट्स"
+
msgid "MRP (planning)"
msgstr "MRP (योजना)"
@@ -9284,6 +9314,9 @@ msgstr "इस कनबन के लिए अगली ऑपरेशन श
msgid "Qty"
msgstr "मात्रा"
+msgid "Qty On Hand"
+msgstr "हाथ में मात्रा"
+
msgid "Qty to Order"
msgstr "ऑर्डर करने की मात्रा"
@@ -9583,6 +9616,9 @@ msgstr "हाल के भुगतान"
msgid "Recently Created"
msgstr "हाल ही में बनाया गया"
+msgid "Reconcile"
+msgstr "सुलह करें"
+
msgid "Reconciling a purchase order against what was received and invoiced — implicit in Carbon, via the line quantities and GR/IR balance."
msgstr "वसूली अवधि"
@@ -11162,9 +11198,6 @@ msgstr "कदम"
msgid "Steps"
msgstr "चरण"
-msgid "Stock Movements"
-msgstr "स्टॉक मूवमेंट्स"
-
msgid "Stock Transfer ID"
msgstr "स्टॉक ट्रांसफर आईडी"
@@ -12486,6 +12519,9 @@ msgstr "शिपमेंट को बिना पुनः-कुंजी
msgid "Tie-Out"
msgstr "टाई-आउट"
+msgid "Tie-Out unavailable"
+msgstr "Tie-Out उपलब्ध नहीं है"
+
msgid "Tightened"
msgstr "कड़ा"
@@ -12621,6 +12657,12 @@ msgstr "इस स्थान पर सभी भंडारण इकाइ
msgid "Total quantity required across all active jobs and sales orders at this location — not just this job."
msgstr "इस स्थान पर सभी सक्रिय कार्यों और बिक्री आदेशों में आवश्यक कुल मात्रा — केवल इस कार्य के लिए नहीं।"
+msgid "Total Value"
+msgstr "कुल मूल्य"
+
+msgid "Total Variance"
+msgstr "कुल भिन्नता"
+
msgid "Total:"
msgstr "कुल:"
@@ -13123,6 +13165,9 @@ msgstr "सत्यापित"
msgid "Validating job..."
msgstr "नौकरी को मान्य कर रहे हैं..."
+msgid "Valuation"
+msgstr "मूल्यांकन"
+
msgid "Value"
msgstr "मान"
@@ -13138,6 +13183,9 @@ msgstr "मूल्य वर्धित कर पंजीकरण सं
msgid "Values"
msgstr "मूल्य"
+msgid "Values apply today's unit costs to historical quantities."
+msgstr "मान ऐतिहासिक मात्राओं पर आज की इकाई लागत को लागू करते हैं।"
+
msgid "Variance"
msgstr "विचरण"
diff --git a/packages/locale/locales/it/erp.po b/packages/locale/locales/it/erp.po
index 1eed573835..f51760c9c8 100644
--- a/packages/locale/locales/it/erp.po
+++ b/packages/locale/locales/it/erp.po
@@ -137,6 +137,9 @@ msgstr "{variances, plural, one {# riga differisce dalla quantità prevista} oth
msgid "/month/user"
msgstr "/mese/utente"
+msgid "% of Total"
+msgstr "% del Totale"
+
#. placeholder {0}: numberFormatter.format(redirectedTotal)
#. placeholder {1}: redirectedParts.join(", ")
msgid "↩ {0} redirected from superseded {1}"
@@ -785,6 +788,9 @@ msgstr "Tutti gli articoli"
msgid "All jobs completed"
msgstr "Tutti i lavori completati"
+msgid "All Locations"
+msgstr "Tutte le Ubicazioni"
+
msgid "All members of selected groups and selected individuals will be able to approve requests"
msgstr "Tutti i membri dei gruppi selezionati e gli individui selezionati potranno approvare le richieste"
@@ -1827,6 +1833,12 @@ msgstr "Per Data Documento"
msgid "By Due Date"
msgstr "Per Data di Scadenza"
+msgid "By Item"
+msgstr "Per Articolo"
+
+msgid "By Location"
+msgstr "Per Ubicazione"
+
msgid "By signing in, you agree to the <0>Terms of Service</0> and <1>Privacy Policy.</1>"
msgstr "Accedendo, accetti i <0>Termini di Servizio</0> e l'<1>Informativa sulla Privacy.</1>"
@@ -2257,6 +2269,9 @@ msgstr "Nome Azienda"
msgid "Company policy asks for a different person to inspect inbound items than the one who received them."
msgstr "La politica aziendale richiede che una persona diversa ispezionare gli articoli in entrata rispetto a quella che li ha ricevuti."
+msgid "Company-wide — includes all locations"
+msgstr "A livello aziendale — include tutte le sedi"
+
msgid "Compare and Order"
msgstr "Confronta e Ordina"
@@ -6259,6 +6274,9 @@ msgstr "Cronologia Inventario"
msgid "Inventory Job Notifications"
msgstr "Notifiche Lavoro Inventario"
+msgid "Inventory Movements"
+msgstr "Movimenti di magazzino"
+
msgid "Inventory Qty"
msgstr "Quantità Inventario"
@@ -6268,6 +6286,9 @@ msgstr "Tracciamento Inventario"
msgid "Inventory Unit of Measure"
msgstr "Unità di Misura Inventario"
+msgid "Inventory Valuation"
+msgstr "Valutazione Inventario"
+
msgid "Invite"
msgstr "Invita"
@@ -6394,6 +6415,9 @@ msgstr "Articolo"
msgid "Item {scannedItem} is not the same as the item {expectedItem}"
msgstr "L'articolo {scannedItem} non è lo stesso dell'articolo {expectedItem}"
+msgid "Item / Location"
+msgstr "Articolo / Ubicazione"
+
msgid "Item filters"
msgstr "Filtri articoli"
@@ -6777,6 +6801,9 @@ msgstr "ubicazione"
msgid "Location"
msgstr "Ubicazione"
+msgid "Location / Item"
+msgstr "Ubicazione / Articolo"
+
msgid "Location Name"
msgstr "Nome Ubicazione"
@@ -7375,6 +7402,9 @@ msgstr "Sposta nel Cestino"
msgid "Moved {0} to {1} bucket"
msgstr "Spostato {0} nel bucket {1}"
+msgid "Movements"
+msgstr "Movimenti"
+
msgid "MRP (planning)"
msgstr "MRP (pianificazione)"
@@ -9284,6 +9314,9 @@ msgstr "Codice QR per avviare l'operazione successiva per questo kanban"
msgid "Qty"
msgstr "Qtà"
+msgid "Qty On Hand"
+msgstr "Qtà a Magazzino"
+
msgid "Qty to Order"
msgstr "Qtà da ordinare"
@@ -9583,6 +9616,9 @@ msgstr "Pagamenti recenti"
msgid "Recently Created"
msgstr "Creato di recente"
+msgid "Reconcile"
+msgstr "Riconcilia"
+
msgid "Reconciling a purchase order against what was received and invoiced — implicit in Carbon, via the line quantities and GR/IR balance."
msgstr "Periodo di Recupero"
@@ -11162,9 +11198,6 @@ msgstr "passaggi"
msgid "Steps"
msgstr "Passaggi"
-msgid "Stock Movements"
-msgstr "Movimenti di Magazzino"
-
msgid "Stock Transfer ID"
msgstr "ID Trasferimento Magazzino"
@@ -12486,6 +12519,9 @@ msgstr "Collegare le spedizioni a una fattura senza reinserimento dati"
msgid "Tie-Out"
msgstr "Riconciliazione"
+msgid "Tie-Out unavailable"
+msgstr "Riconciliazione non disponibile"
+
msgid "Tightened"
msgstr "Stretto"
@@ -12621,6 +12657,12 @@ msgstr "Quantità totale disponibile dell'articolo su tutte le unità di stoccag
msgid "Total quantity required across all active jobs and sales orders at this location — not just this job."
msgstr "Quantità totale richiesta su tutti i lavori attivi e gli ordini di vendita in questa posizione, non solo questo lavoro."
+msgid "Total Value"
+msgstr "Valore Totale"
+
+msgid "Total Variance"
+msgstr "Varianza Totale"
+
msgid "Total:"
msgstr "Totale:"
@@ -13123,6 +13165,9 @@ msgstr "Convalidato"
msgid "Validating job..."
msgstr "Convalida processo..."
+msgid "Valuation"
+msgstr "Valutazione"
+
msgid "Value"
msgstr "Valore"
@@ -13138,6 +13183,9 @@ msgstr "Numero di registrazione dell'imposta sul valore aggiunto; richiesto sull
msgid "Values"
msgstr "Valori"
+msgid "Values apply today's unit costs to historical quantities."
+msgstr "I valori applicano i costi unitari odierni alle quantità storiche."
+
msgid "Variance"
msgstr "Varianza"
diff --git a/packages/locale/locales/ja/erp.po b/packages/locale/locales/ja/erp.po
index 50d1810804..c5e85dd7eb 100644
--- a/packages/locale/locales/ja/erp.po
+++ b/packages/locale/locales/ja/erp.po
@@ -137,6 +137,9 @@ msgstr "{variances, plural, one {# 行が予想数量と異なります} other {
msgid "/month/user"
msgstr "/月/ユーザー"
+msgid "% of Total"
+msgstr "総量比"
+
#. placeholder {0}: numberFormatter.format(redirectedTotal)
#. placeholder {1}: redirectedParts.join(", ")
msgid "↩ {0} redirected from superseded {1}"
@@ -785,6 +788,9 @@ msgstr "すべてのアイテム"
msgid "All jobs completed"
msgstr "すべてのジョブが完了しました"
+msgid "All Locations"
+msgstr "すべての場所"
+
msgid "All members of selected groups and selected individuals will be able to approve requests"
msgstr "選択されたグループのすべてのメンバーと選択された個人が承認リクエストを承認できます"
@@ -1827,6 +1833,12 @@ msgstr "ドキュメント日付別"
msgid "By Due Date"
msgstr "支払期日別"
+msgid "By Item"
+msgstr "品目別"
+
+msgid "By Location"
+msgstr "場所別"
+
msgid "By signing in, you agree to the <0>Terms of Service</0> and <1>Privacy Policy.</1>"
msgstr "サインインすることで、<0>利用規約</0>および<1>プライバシーポリシー</1>に同意するものとします。"
@@ -2257,6 +2269,9 @@ msgstr "会社名"
msgid "Company policy asks for a different person to inspect inbound items than the one who received them."
msgstr "会社のポリシーでは、受け取った人とは異なる人が受け入れ品を検査することが求められています。"
+msgid "Company-wide — includes all locations"
+msgstr "会社全体 — すべての場所を含む"
+
msgid "Compare and Order"
msgstr "比較して注文"
@@ -6259,6 +6274,9 @@ msgstr "在庫履歴"
msgid "Inventory Job Notifications"
msgstr "在庫ジョブ通知"
+msgid "Inventory Movements"
+msgstr "在庫移動"
+
msgid "Inventory Qty"
msgstr "在庫数量"
@@ -6268,6 +6286,9 @@ msgstr "在庫追跡"
msgid "Inventory Unit of Measure"
msgstr "在庫単位"
+msgid "Inventory Valuation"
+msgstr "在庫評価"
+
msgid "Invite"
msgstr "招待"
@@ -6394,6 +6415,9 @@ msgstr "アイテム"
msgid "Item {scannedItem} is not the same as the item {expectedItem}"
msgstr "アイテム {scannedItem} は、アイテム {expectedItem} と同じではありません"
+msgid "Item / Location"
+msgstr "品目 / 場所"
+
msgid "Item filters"
msgstr "アイテムフィルター"
@@ -6777,6 +6801,9 @@ msgstr "場所"
msgid "Location"
msgstr "ロケーション"
+msgid "Location / Item"
+msgstr "場所 / 品目"
+
msgid "Location Name"
msgstr "ロケーション名"
@@ -7375,6 +7402,9 @@ msgstr "ゴミ箱に移動"
msgid "Moved {0} to {1} bucket"
msgstr "{0}を{1}バケットに移動しました"
+msgid "Movements"
+msgstr "移動"
+
msgid "MRP (planning)"
msgstr "MRP (計画)"
@@ -9284,6 +9314,9 @@ msgstr "このカンバンの次の操作を開始するためのQRコード"
msgid "Qty"
msgstr "数量"
+msgid "Qty On Hand"
+msgstr "手持数量"
+
msgid "Qty to Order"
msgstr "注文数量"
@@ -9583,6 +9616,9 @@ msgstr "最近の支払い"
msgid "Recently Created"
msgstr "最近作成"
+msgid "Reconcile"
+msgstr "調整"
+
msgid "Reconciling a purchase order against what was received and invoiced — implicit in Carbon, via the line quantities and GR/IR balance."
msgstr "回収期間"
@@ -11162,9 +11198,6 @@ msgstr "ステップ"
msgid "Steps"
msgstr "ステップ"
-msgid "Stock Movements"
-msgstr "在庫移動"
-
msgid "Stock Transfer ID"
msgstr "在庫移動ID"
@@ -12486,6 +12519,9 @@ msgstr "出荷を請求書に結びつけ、再入力なしで処理する"
msgid "Tie-Out"
msgstr "照合"
+msgid "Tie-Out unavailable"
+msgstr "Tie-Outは利用できません"
+
msgid "Tightened"
msgstr "厳しい"
@@ -12621,6 +12657,12 @@ msgstr "このロケーションのすべての保管単位における品目の
msgid "Total quantity required across all active jobs and sales orders at this location — not just this job."
msgstr "このロケーションのすべての進行中ジョブおよび受注で必要とされる総数量 — このジョブだけではありません。"
+msgid "Total Value"
+msgstr "合計価値"
+
+msgid "Total Variance"
+msgstr "合計差異"
+
msgid "Total:"
msgstr "合計:"
@@ -13123,6 +13165,9 @@ msgstr "検証済み"
msgid "Validating job..."
msgstr "ジョブを検証中..."
+msgid "Valuation"
+msgstr "評価"
+
msgid "Value"
msgstr "値"
@@ -13138,6 +13183,9 @@ msgstr "付加価値税登録番号;EUの請求書でのリバースチャージ
msgid "Values"
msgstr "値"
+msgid "Values apply today's unit costs to historical quantities."
+msgstr "値は今日の単価を履歴数量に適用します。"
+
msgid "Variance"
msgstr "差異"
diff --git a/packages/locale/locales/ko/erp.po b/packages/locale/locales/ko/erp.po
index 0577542771..e9309242ad 100644
--- a/packages/locale/locales/ko/erp.po
+++ b/packages/locale/locales/ko/erp.po
@@ -137,6 +137,9 @@ msgstr "예상 수량과 다른 라인 {variances}개"
msgid "/month/user"
msgstr "/월/사용자"
+msgid "% of Total"
+msgstr "전체의 %"
+
#. placeholder {0}: numberFormatter.format(redirectedTotal)
#. placeholder {1}: redirectedParts.join(", ")
msgid "↩ {0} redirected from superseded {1}"
@@ -785,6 +788,9 @@ msgstr "모든 품목"
msgid "All jobs completed"
msgstr "모든 작업 완료됨"
+msgid "All Locations"
+msgstr "모든 위치"
+
msgid "All members of selected groups and selected individuals will be able to approve requests"
msgstr "선택한 그룹의 모든 구성원과 선택한 개인이 요청을 승인할 수 있습니다"
@@ -1827,6 +1833,12 @@ msgstr "문서 날짜 기준"
msgid "By Due Date"
msgstr "만기일 기준"
+msgid "By Item"
+msgstr "항목별"
+
+msgid "By Location"
+msgstr "위치별"
+
msgid "By signing in, you agree to the <0>Terms of Service</0> and <1>Privacy Policy.</1>"
msgstr "로그인하면 <0>서비스 약관</0> 및 <1>개인정보 처리방침</1>에 동의하는 것으로 간주됩니다."
@@ -2257,6 +2269,9 @@ msgstr "회사명"
msgid "Company policy asks for a different person to inspect inbound items than the one who received them."
msgstr "회사 정책상 입고 품목을 받은 사람과 검사하는 사람이 달라야 합니다."
+msgid "Company-wide — includes all locations"
+msgstr "회사 전체 — 모든 위치 포함"
+
msgid "Compare and Order"
msgstr "비교 후 주문"
@@ -6259,6 +6274,9 @@ msgstr "재고 이력"
msgid "Inventory Job Notifications"
msgstr "재고 작업 알림"
+msgid "Inventory Movements"
+msgstr "재고 이동"
+
msgid "Inventory Qty"
msgstr "재고 수량"
@@ -6268,6 +6286,9 @@ msgstr "재고 추적"
msgid "Inventory Unit of Measure"
msgstr "재고 측정 단위"
+msgid "Inventory Valuation"
+msgstr "재고 평가"
+
msgid "Invite"
msgstr "초대"
@@ -6394,6 +6415,9 @@ msgstr "품목"
msgid "Item {scannedItem} is not the same as the item {expectedItem}"
msgstr "품목 {scannedItem}이(가) 품목 {expectedItem}과(와) 일치하지 않습니다"
+msgid "Item / Location"
+msgstr "항목 / 위치"
+
msgid "Item filters"
msgstr "품목 필터"
@@ -6777,6 +6801,9 @@ msgstr "위치"
msgid "Location"
msgstr "위치"
+msgid "Location / Item"
+msgstr "위치 / 항목"
+
msgid "Location Name"
msgstr "위치 이름"
@@ -7375,6 +7402,9 @@ msgstr "휴지통으로 이동"
msgid "Moved {0} to {1} bucket"
msgstr "{0}을(를) {1} 버킷으로 이동함"
+msgid "Movements"
+msgstr "이동"
+
msgid "MRP (planning)"
msgstr "MRP(계획)"
@@ -9284,6 +9314,9 @@ msgstr "이 칸반의 다음 공정작업을 시작하는 QR 코드"
msgid "Qty"
msgstr "수량"
+msgid "Qty On Hand"
+msgstr "현재고"
+
msgid "Qty to Order"
msgstr "주문 수량"
@@ -9583,6 +9616,9 @@ msgstr "최근 결제"
msgid "Recently Created"
msgstr "최근 생성됨"
+msgid "Reconcile"
+msgstr "조정"
+
msgid "Reconciling a purchase order against what was received and invoiced — implicit in Carbon, via the line quantities and GR/IR balance."
msgstr "구매주문을 실제 입고 및 청구 내역과 대조하는 작업 — Carbon에서는 라인 수량과 GR/IR 잔액을 통해 암묵적으로 처리됩니다."
@@ -11162,9 +11198,6 @@ msgstr "단계"
msgid "Steps"
msgstr "단계"
-msgid "Stock Movements"
-msgstr "재고 이동"
-
msgid "Stock Transfer ID"
msgstr "재고 이동 ID"
@@ -12486,6 +12519,9 @@ msgstr "재입력 없이 출하를 인보이스까지 연결"
msgid "Tie-Out"
msgstr "대사"
+msgid "Tie-Out unavailable"
+msgstr "동적 대조 불가능"
+
msgid "Tightened"
msgstr "강화됨"
@@ -12621,6 +12657,12 @@ msgstr "이 위치의 모든 저장 단위에 걸친 해당 품목의 총 재고
msgid "Total quantity required across all active jobs and sales orders at this location — not just this job."
msgstr "이 작업뿐 아니라 이 위치의 모든 진행 중인 작업과 판매주문에서 필요한 총 수량입니다."
+msgid "Total Value"
+msgstr "총 가치"
+
+msgid "Total Variance"
+msgstr "총 차이"
+
msgid "Total:"
msgstr "합계:"
@@ -13123,6 +13165,9 @@ msgstr "검증됨"
msgid "Validating job..."
msgstr "작업 검증 중..."
+msgid "Valuation"
+msgstr "평가"
+
msgid "Value"
msgstr "값"
@@ -13138,6 +13183,9 @@ msgstr "부가가치세 등록번호로, 대리납부(리버스차지) 또는
msgid "Values"
msgstr "값"
+msgid "Values apply today's unit costs to historical quantities."
+msgstr "값은 오늘의 단가를 이전 수량에 적용합니다."
+
msgid "Variance"
msgstr "차이"
diff --git a/packages/locale/locales/pl/erp.po b/packages/locale/locales/pl/erp.po
index 9e499fb29c..85730efce0 100644
--- a/packages/locale/locales/pl/erp.po
+++ b/packages/locale/locales/pl/erp.po
@@ -137,6 +137,9 @@ msgstr "{variances, plural, one {# linia różni się od oczekiwanej ilości} ot
msgid "/month/user"
msgstr "/miesiąc/użytkownik"
+msgid "% of Total"
+msgstr "% całości"
+
#. placeholder {0}: numberFormatter.format(redirectedTotal)
#. placeholder {1}: redirectedParts.join(", ")
msgid "↩ {0} redirected from superseded {1}"
@@ -785,6 +788,9 @@ msgstr "Wszystkie elementy"
msgid "All jobs completed"
msgstr "Wszystkie zadania ukończone"
+msgid "All Locations"
+msgstr "Wszystkie lokalizacje"
+
msgid "All members of selected groups and selected individuals will be able to approve requests"
msgstr "Wszyscy członkowie wybranych grup i wybrane osoby będą mogły zatwierdzać żądania"
@@ -1827,6 +1833,12 @@ msgstr "Według daty dokumentu"
msgid "By Due Date"
msgstr "Według daty wymagalności"
+msgid "By Item"
+msgstr "Wg pozycji"
+
+msgid "By Location"
+msgstr "Wg lokalizacji"
+
msgid "By signing in, you agree to the <0>Terms of Service</0> and <1>Privacy Policy.</1>"
msgstr "Logując się, wyrażasz zgodę na <0>Warunki korzystania z usługi</0> i <1>Politykę prywatności.</1>"
@@ -2257,6 +2269,9 @@ msgstr "Nazwa Firmy"
msgid "Company policy asks for a different person to inspect inbound items than the one who received them."
msgstr "Polityka firmy wymaga, aby przedmioty przychodzące były sprawdzane przez inną osobę niż ta, która je odebrała."
+msgid "Company-wide — includes all locations"
+msgstr "Całej firmy — obejmuje wszystkie lokalizacje"
+
msgid "Compare and Order"
msgstr "Porównaj i zamów"
@@ -6259,6 +6274,9 @@ msgstr "Historia Inwentarza"
msgid "Inventory Job Notifications"
msgstr "Powiadomienia o zadaniach inwentaryzacyjnych"
+msgid "Inventory Movements"
+msgstr "Ruchy Magazynowe"
+
msgid "Inventory Qty"
msgstr "Ilość w magazynie"
@@ -6268,6 +6286,9 @@ msgstr "Śledzenie zapasów"
msgid "Inventory Unit of Measure"
msgstr "Jednostka miary zapasów"
+msgid "Inventory Valuation"
+msgstr "Wycena zapasów"
+
msgid "Invite"
msgstr "Zaproś"
@@ -6394,6 +6415,9 @@ msgstr "Przedmiot"
msgid "Item {scannedItem} is not the same as the item {expectedItem}"
msgstr "Pozycja {scannedItem} nie jest taka sama jak pozycja {expectedItem}"
+msgid "Item / Location"
+msgstr "Pozycja / Lokalizacja"
+
msgid "Item filters"
msgstr "Filtry elementów"
@@ -6777,6 +6801,9 @@ msgstr "lokalizacja"
msgid "Location"
msgstr "Lokalizacja"
+msgid "Location / Item"
+msgstr "Lokalizacja / Pozycja"
+
msgid "Location Name"
msgstr "Nazwa lokalizacji"
@@ -7375,6 +7402,9 @@ msgstr "Przenieś do kosza"
msgid "Moved {0} to {1} bucket"
msgstr "Przeniesiono {0} do zasobnika {1}"
+msgid "Movements"
+msgstr "Ruchy"
+
msgid "MRP (planning)"
msgstr "MRP (planowanie)"
@@ -9284,6 +9314,9 @@ msgstr "Kod QR do rozpoczęcia następnej operacji dla tego kanbanu"
msgid "Qty"
msgstr "Ilość"
+msgid "Qty On Hand"
+msgstr "Ilość na magazynie"
+
msgid "Qty to Order"
msgstr "Ilość do zamówienia"
@@ -9583,6 +9616,9 @@ msgstr "Ostatnie płatności"
msgid "Recently Created"
msgstr "Niedawno utworzone"
+msgid "Reconcile"
+msgstr "Reconcile"
+
msgid "Reconciling a purchase order against what was received and invoiced — implicit in Carbon, via the line quantities and GR/IR balance."
msgstr "Okres Odzysku"
@@ -11162,9 +11198,6 @@ msgstr "kroki"
msgid "Steps"
msgstr "Kroki"
-msgid "Stock Movements"
-msgstr "Ruchy Zapasów"
-
msgid "Stock Transfer ID"
msgstr "Identyfikator Transferu Zapasów"
@@ -12486,6 +12519,9 @@ msgstr "Powiąż przesyłki z fakturą bez ponownego wprowadzania danych"
msgid "Tie-Out"
msgstr "Uzgodnienie"
+msgid "Tie-Out unavailable"
+msgstr "Uzgodnienie niedostępne"
+
msgid "Tightened"
msgstr "Ścisły"
@@ -12621,6 +12657,12 @@ msgstr "Łączna ilość dostępna dla pozycji we wszystkich jednostkach magazyn
msgid "Total quantity required across all active jobs and sales orders at this location — not just this job."
msgstr "Łączna ilość wymagana we wszystkich aktywnych zadaniach i zamówieniach sprzedaży w tej lokalizacji — nie tylko w tym zadaniu."
+msgid "Total Value"
+msgstr "Wartość całkowita"
+
+msgid "Total Variance"
+msgstr "Wariancja całkowita"
+
msgid "Total:"
msgstr "Razem:"
@@ -13123,6 +13165,9 @@ msgstr "Zweryfikowane"
msgid "Validating job..."
msgstr "Walidacja zadania..."
+msgid "Valuation"
+msgstr "Wycena"
+
msgid "Value"
msgstr "Wartość"
@@ -13138,6 +13183,9 @@ msgstr "Numer rejestracyjny podatku od wartości dodanej; wymagany na fakturach
msgid "Values"
msgstr "Wartości"
+msgid "Values apply today's unit costs to historical quantities."
+msgstr "Wartości stosują dzisiejsze koszty jednostkowe do historycznych ilości."
+
msgid "Variance"
msgstr "Odchylenie"
diff --git a/packages/locale/locales/pt/erp.po b/packages/locale/locales/pt/erp.po
index bc1cfac11a..6fc0c5b994 100644
--- a/packages/locale/locales/pt/erp.po
+++ b/packages/locale/locales/pt/erp.po
@@ -137,6 +137,9 @@ msgstr "{variances, plural, one {# linha difere da quantidade esperada} other {#
msgid "/month/user"
msgstr "/mês/utilizador"
+msgid "% of Total"
+msgstr "% do Total"
+
#. placeholder {0}: numberFormatter.format(redirectedTotal)
#. placeholder {1}: redirectedParts.join(", ")
msgid "↩ {0} redirected from superseded {1}"
@@ -785,6 +788,9 @@ msgstr "Todos os Itens"
msgid "All jobs completed"
msgstr "Todos os trabalhos concluídos"
+msgid "All Locations"
+msgstr "Todos os Locais"
+
msgid "All members of selected groups and selected individuals will be able to approve requests"
msgstr "Todos os membros dos grupos selecionados e indivíduos selecionados poderão aprovar solicitações"
@@ -1827,6 +1833,12 @@ msgstr "Por Data do Documento"
msgid "By Due Date"
msgstr "Por Data de Vencimento"
+msgid "By Item"
+msgstr "Por Item"
+
+msgid "By Location"
+msgstr "Por Local"
+
msgid "By signing in, you agree to the <0>Terms of Service</0> and <1>Privacy Policy.</1>"
msgstr "Ao fazer login, você concorda com os <0>Termos de Serviço</0> e a <1>Política de Privacidade.</1>"
@@ -2257,6 +2269,9 @@ msgstr "Nome da Empresa"
msgid "Company policy asks for a different person to inspect inbound items than the one who received them."
msgstr "A política da empresa exige que uma pessoa diferente inspecione os itens recebidos do que aquela que os recebeu."
+msgid "Company-wide — includes all locations"
+msgstr "Em toda a empresa — inclui todas as localidades"
+
msgid "Compare and Order"
msgstr "Comparar e Encomendar"
@@ -6259,6 +6274,9 @@ msgstr "Histórico de Inventário"
msgid "Inventory Job Notifications"
msgstr "Notificações de Trabalho de Inventário"
+msgid "Inventory Movements"
+msgstr "Movimentações de Inventário"
+
msgid "Inventory Qty"
msgstr "Qtd. Inventário"
@@ -6268,6 +6286,9 @@ msgstr "Rastreamento de Inventário"
msgid "Inventory Unit of Measure"
msgstr "Unidade de Medida do Inventário"
+msgid "Inventory Valuation"
+msgstr "Avaliação de Inventário"
+
msgid "Invite"
msgstr "Convidar"
@@ -6394,6 +6415,9 @@ msgstr "Item"
msgid "Item {scannedItem} is not the same as the item {expectedItem}"
msgstr "Item {scannedItem} não é o mesmo que o item {expectedItem}"
+msgid "Item / Location"
+msgstr "Item / Local"
+
msgid "Item filters"
msgstr "Filtros de itens"
@@ -6777,6 +6801,9 @@ msgstr "localização"
msgid "Location"
msgstr "Localização"
+msgid "Location / Item"
+msgstr "Local / Item"
+
msgid "Location Name"
msgstr "Nome da Localização"
@@ -7375,6 +7402,9 @@ msgstr "Mover para Lixo"
msgid "Moved {0} to {1} bucket"
msgstr "Movido {0} para o bucket {1}"
+msgid "Movements"
+msgstr "Movimentações"
+
msgid "MRP (planning)"
msgstr "MRP (planejamento)"
@@ -9284,6 +9314,9 @@ msgstr "Código QR para iniciar a próxima operação para este kanban"
msgid "Qty"
msgstr "Qtd"
+msgid "Qty On Hand"
+msgstr "Qtd. em Mãos"
+
msgid "Qty to Order"
msgstr "Qtd a Encomendar"
@@ -9583,6 +9616,9 @@ msgstr "Pagamentos recentes"
msgid "Recently Created"
msgstr "Criado Recentemente"
+msgid "Reconcile"
+msgstr "Reconciliar"
+
msgid "Reconciling a purchase order against what was received and invoiced — implicit in Carbon, via the line quantities and GR/IR balance."
msgstr "Período de Recuperação"
@@ -11162,9 +11198,6 @@ msgstr "passos"
msgid "Steps"
msgstr "Etapas"
-msgid "Stock Movements"
-msgstr "Movimentos de Estoque"
-
msgid "Stock Transfer ID"
msgstr "ID de Transferência de Estoque"
@@ -12486,6 +12519,9 @@ msgstr "Vincular remessas a uma fatura sem re-digitação"
msgid "Tie-Out"
msgstr "Reconciliação"
+msgid "Tie-Out unavailable"
+msgstr "Conciliação indisponível"
+
msgid "Tightened"
msgstr "Apertado"
@@ -12621,6 +12657,12 @@ msgstr "Quantidade total disponível do item em todas as unidades de armazenamen
msgid "Total quantity required across all active jobs and sales orders at this location — not just this job."
msgstr "Quantidade total exigida em todos os trabalhos ativos e pedidos de venda neste local — não apenas neste trabalho."
+msgid "Total Value"
+msgstr "Valor Total"
+
+msgid "Total Variance"
+msgstr "Variância Total"
+
msgid "Total:"
msgstr "Total:"
@@ -13123,6 +13165,9 @@ msgstr "Validado"
msgid "Validating job..."
msgstr "Validando trabalho..."
+msgid "Valuation"
+msgstr "Avaliação"
+
msgid "Value"
msgstr "Valor"
@@ -13138,6 +13183,9 @@ msgstr "Número de registro de imposto sobre valor agregado; obrigatório em fat
msgid "Values"
msgstr "Valores"
+msgid "Values apply today's unit costs to historical quantities."
+msgstr "Os valores aplicam os custos unitários de hoje às quantidades históricas."
+
msgid "Variance"
msgstr "Variação"
diff --git a/packages/locale/locales/ru/erp.po b/packages/locale/locales/ru/erp.po
index 42a75fa259..639c1c5e35 100644
--- a/packages/locale/locales/ru/erp.po
+++ b/packages/locale/locales/ru/erp.po
@@ -137,6 +137,9 @@ msgstr "{variances, plural, one {# строка отличается от ожи
msgid "/month/user"
msgstr "/месяц/пользователь"
+msgid "% of Total"
+msgstr "% от всего"
+
#. placeholder {0}: numberFormatter.format(redirectedTotal)
#. placeholder {1}: redirectedParts.join(", ")
msgid "↩ {0} redirected from superseded {1}"
@@ -785,6 +788,9 @@ msgstr "Все элементы"
msgid "All jobs completed"
msgstr "Все работы завершены"
+msgid "All Locations"
+msgstr "Все местоположения"
+
msgid "All members of selected groups and selected individuals will be able to approve requests"
msgstr "Все члены выбранных групп и выбранные лица смогут одобрять запросы"
@@ -1827,6 +1833,12 @@ msgstr "По дате документа"
msgid "By Due Date"
msgstr "По дате платежа"
+msgid "By Item"
+msgstr "По товару"
+
+msgid "By Location"
+msgstr "По местоположению"
+
msgid "By signing in, you agree to the <0>Terms of Service</0> and <1>Privacy Policy.</1>"
msgstr "Подписываясь, вы соглашаетесь с <0>Условиями обслуживания</0> и <1>Политикой конфиденциальности.</1>"
@@ -2257,6 +2269,9 @@ msgstr "Название компании"
msgid "Company policy asks for a different person to inspect inbound items than the one who received them."
msgstr "Политика компании требует, чтобы входящие товары проверял другой сотрудник, а не тот, кто их получил."
+msgid "Company-wide — includes all locations"
+msgstr "Во всей компании — включает все местоположения"
+
msgid "Compare and Order"
msgstr "Сравнить и заказать"
@@ -6259,6 +6274,9 @@ msgstr "История инвентаря"
msgid "Inventory Job Notifications"
msgstr "Уведомления о завершении работ по инвентаризации"
+msgid "Inventory Movements"
+msgstr "Движения по товарно-материальным ценностям"
+
msgid "Inventory Qty"
msgstr "Кол-во в инвентаре"
@@ -6268,6 +6286,9 @@ msgstr "Отслеживание запасов"
msgid "Inventory Unit of Measure"
msgstr "Единица измерения запасов"
+msgid "Inventory Valuation"
+msgstr "Оценка товарно-материального запаса"
+
msgid "Invite"
msgstr "Пригласить"
@@ -6394,6 +6415,9 @@ msgstr "Товар"
msgid "Item {scannedItem} is not the same as the item {expectedItem}"
msgstr "Товар {scannedItem} не совпадает с товаром {expectedItem}"
+msgid "Item / Location"
+msgstr "Товар / Местоположение"
+
msgid "Item filters"
msgstr "Фильтры товаров"
@@ -6777,6 +6801,9 @@ msgstr "расположение"
msgid "Location"
msgstr "Местоположение"
+msgid "Location / Item"
+msgstr "Местоположение / Товар"
+
msgid "Location Name"
msgstr "Название местоположения"
@@ -7375,6 +7402,9 @@ msgstr "Переместить в корзину"
msgid "Moved {0} to {1} bucket"
msgstr "Перемещено {0} в хранилище {1}"
+msgid "Movements"
+msgstr "Движения"
+
msgid "MRP (planning)"
msgstr "MRP (планирование)"
@@ -9284,6 +9314,9 @@ msgstr "QR-код для начала следующей операции для
msgid "Qty"
msgstr "Кол-во"
+msgid "Qty On Hand"
+msgstr "Кол-во в наличии"
+
msgid "Qty to Order"
msgstr "Кол-во для заказа"
@@ -9583,6 +9616,9 @@ msgstr "Недавние платежи"
msgid "Recently Created"
msgstr "Недавно созданные"
+msgid "Reconcile"
+msgstr "Согласовать"
+
msgid "Reconciling a purchase order against what was received and invoiced — implicit in Carbon, via the line quantities and GR/IR balance."
msgstr "Период восстановления"
@@ -11162,9 +11198,6 @@ msgstr "шаги"
msgid "Steps"
msgstr "Шаги"
-msgid "Stock Movements"
-msgstr "Движения запасов"
-
msgid "Stock Transfer ID"
msgstr "ID передачи запасов"
@@ -12486,6 +12519,9 @@ msgstr "Связать отправки с счетом без повторно
msgid "Tie-Out"
msgstr "Сверка"
+msgid "Tie-Out unavailable"
+msgstr "Сверка недоступна"
+
msgid "Tightened"
msgstr "Ужесточенный"
@@ -12621,6 +12657,12 @@ msgstr "Общее наличное количество позиции по в
msgid "Total quantity required across all active jobs and sales orders at this location — not just this job."
msgstr "Общее требуемое количество по всем активным заданиям и заказам на продажу в этом местоположении — не только по этому заданию."
+msgid "Total Value"
+msgstr "Общая стоимость"
+
+msgid "Total Variance"
+msgstr "Общее отклонение"
+
msgid "Total:"
msgstr "Итого:"
@@ -13123,6 +13165,9 @@ msgstr "Проверено"
msgid "Validating job..."
msgstr "Проверка задания..."
+msgid "Valuation"
+msgstr "Оценка"
+
msgid "Value"
msgstr "Значение"
@@ -13138,6 +13183,9 @@ msgstr "Номер регистрации налога на добавленну
msgid "Values"
msgstr "Значения"
+msgid "Values apply today's unit costs to historical quantities."
+msgstr "Значения применяют текущие цены за единицу к историческим количествам."
+
msgid "Variance"
msgstr "Расхождение"
diff --git a/packages/locale/locales/tr/erp.po b/packages/locale/locales/tr/erp.po
index 3e7c8f6642..cc876bba7f 100644
--- a/packages/locale/locales/tr/erp.po
+++ b/packages/locale/locales/tr/erp.po
@@ -137,6 +137,9 @@ msgstr "{variances, plural, one {# satır beklenen miktardan farklı} other {# s
msgid "/month/user"
msgstr "/ay/kullanıcı"
+msgid "% of Total"
+msgstr "% Toplam"
+
#. placeholder {0}: numberFormatter.format(redirectedTotal)
#. placeholder {1}: redirectedParts.join(", ")
msgid "↩ {0} redirected from superseded {1}"
@@ -785,6 +788,9 @@ msgstr "Tüm Öğeler"
msgid "All jobs completed"
msgstr "Tüm işler tamamlandı"
+msgid "All Locations"
+msgstr "Tüm Konumlar"
+
msgid "All members of selected groups and selected individuals will be able to approve requests"
msgstr "Seçilen gruplardaki ve bireylerdeki tüm üyeler talepleri onaylayabilecektir"
@@ -1827,6 +1833,12 @@ msgstr "Belge Tarihine Göre"
msgid "By Due Date"
msgstr "Vade Tarihine Göre"
+msgid "By Item"
+msgstr "Ürüne Göre"
+
+msgid "By Location"
+msgstr "Konuma Göre"
+
msgid "By signing in, you agree to the <0>Terms of Service</0> and <1>Privacy Policy.</1>"
msgstr "Oturum açarak <0>Hizmet Şartları</0> ve <1>Gizlilik Politikası</1>'na katılıyorsunuz."
@@ -2257,6 +2269,9 @@ msgstr "Şirket Adı"
msgid "Company policy asks for a different person to inspect inbound items than the one who received them."
msgstr "Şirket politikası, gelen ürünleri kontrol edecek kişinin, onları alan kişi olmamasını gerektirir."
+msgid "Company-wide — includes all locations"
+msgstr "Şirket genelinde — tüm konumları içerir"
+
msgid "Compare and Order"
msgstr "Karşılaştır ve Sipariş Ver"
@@ -6259,6 +6274,9 @@ msgstr "Envanter Geçmişi"
msgid "Inventory Job Notifications"
msgstr "Envanter İş Bildirimleri"
+msgid "Inventory Movements"
+msgstr "Envanter Hareketleri"
+
msgid "Inventory Qty"
msgstr "Stok Miktarı"
@@ -6268,6 +6286,9 @@ msgstr "Stok Takibi"
msgid "Inventory Unit of Measure"
msgstr "Stok Birimi"
+msgid "Inventory Valuation"
+msgstr "Envanter Değerlemesi"
+
msgid "Invite"
msgstr "Davet et"
@@ -6394,6 +6415,9 @@ msgstr "Ürün"
msgid "Item {scannedItem} is not the same as the item {expectedItem}"
msgstr "Ürün {scannedItem}, ürün {expectedItem} ile aynı değil"
+msgid "Item / Location"
+msgstr "Ürün / Konum"
+
msgid "Item filters"
msgstr "Ürün filtreleri"
@@ -6777,6 +6801,9 @@ msgstr "konum"
msgid "Location"
msgstr "Konum"
+msgid "Location / Item"
+msgstr "Konum / Ürün"
+
msgid "Location Name"
msgstr "Konum Adı"
@@ -7375,6 +7402,9 @@ msgstr "Çöp Sepetine Taşı"
msgid "Moved {0} to {1} bucket"
msgstr "{0} dosyası {1} klasörüne taşındı"
+msgid "Movements"
+msgstr "Hareketler"
+
msgid "MRP (planning)"
msgstr "MRP (planlama)"
@@ -9284,6 +9314,9 @@ msgstr "Bu kanban için bir sonraki işlemi başlatmak üzere QR kod"
msgid "Qty"
msgstr "Miktar"
+msgid "Qty On Hand"
+msgstr "Elde Bulunan Miktar"
+
msgid "Qty to Order"
msgstr "Sipariş Edilecek Miktar"
@@ -9583,6 +9616,9 @@ msgstr "Son ödemeler"
msgid "Recently Created"
msgstr "Son Oluşturulanlar"
+msgid "Reconcile"
+msgstr "Uzlaştır"
+
msgid "Reconciling a purchase order against what was received and invoiced — implicit in Carbon, via the line quantities and GR/IR balance."
msgstr "Geri Kazanım Süresi"
@@ -11162,9 +11198,6 @@ msgstr "adımlar"
msgid "Steps"
msgstr "Adımlar"
-msgid "Stock Movements"
-msgstr "Stok Hareketleri"
-
msgid "Stock Transfer ID"
msgstr "Stok Transfer Kimliği"
@@ -12486,6 +12519,9 @@ msgstr "Sevkiyatları faturaya bağlayın, yeniden veri girişi olmadan"
msgid "Tie-Out"
msgstr "Mutabakat Kontrolü"
+msgid "Tie-Out unavailable"
+msgstr "Uzlaştırma kullanılamıyor"
+
msgid "Tightened"
msgstr "Sıkı"
@@ -12621,6 +12657,12 @@ msgstr "Bu konumdaki tüm depolama birimlerinde öğenin toplam eldeki miktarı.
msgid "Total quantity required across all active jobs and sales orders at this location — not just this job."
msgstr "Bu konumdaki tüm aktif işler ve satış siparişleri genelinde gereken toplam miktar — yalnızca bu iş için değil."
+msgid "Total Value"
+msgstr "Toplam Değer"
+
+msgid "Total Variance"
+msgstr "Toplam Fark"
+
msgid "Total:"
msgstr "Toplam:"
@@ -13123,6 +13165,9 @@ msgstr "Doğrulandı"
msgid "Validating job..."
msgstr "İş doğrulanıyor..."
+msgid "Valuation"
+msgstr "Değerleme"
+
msgid "Value"
msgstr "Değer"
@@ -13138,6 +13183,9 @@ msgstr "Katma değer vergisi kayıt numarası; AB faturalarında ters ücretlend
msgid "Values"
msgstr "Değerler"
+msgid "Values apply today's unit costs to historical quantities."
+msgstr "Değerler, tarihsel miktarlara bugünün birim maliyetlerini uygular."
+
msgid "Variance"
msgstr "Varyans"
diff --git a/packages/locale/locales/zh/erp.po b/packages/locale/locales/zh/erp.po
index 7bb94f9abf..355effb578 100644
--- a/packages/locale/locales/zh/erp.po
+++ b/packages/locale/locales/zh/erp.po
@@ -137,6 +137,9 @@ msgstr "{variances, plural, one {# 行与预期数量不同} other {# 行与预
msgid "/month/user"
msgstr "/月/用户"
+msgid "% of Total"
+msgstr "占总数的 %"
+
#. placeholder {0}: numberFormatter.format(redirectedTotal)
#. placeholder {1}: redirectedParts.join(", ")
msgid "↩ {0} redirected from superseded {1}"
@@ -785,6 +788,9 @@ msgstr "所有项目"
msgid "All jobs completed"
msgstr "所有工作已完成"
+msgid "All Locations"
+msgstr "所有位置"
+
msgid "All members of selected groups and selected individuals will be able to approve requests"
msgstr "所选组的所有成员和所选个人将能够批准请求"
@@ -1827,6 +1833,12 @@ msgstr "按单据日期"
msgid "By Due Date"
msgstr "按到期日期"
+msgid "By Item"
+msgstr "按物品"
+
+msgid "By Location"
+msgstr "按位置"
+
msgid "By signing in, you agree to the <0>Terms of Service</0> and <1>Privacy Policy.</1>"
msgstr "通过登录,您同意<0>服务条款</0>和<1>隐私政策。</1>"
@@ -2257,6 +2269,9 @@ msgstr "公司名称"
msgid "Company policy asks for a different person to inspect inbound items than the one who received them."
msgstr "公司政策要求由与收货人不同的人员检验入库物品。"
+msgid "Company-wide — includes all locations"
+msgstr "公司范围 — 包括所有地点"
+
msgid "Compare and Order"
msgstr "比较并订购"
@@ -6259,6 +6274,9 @@ msgstr "库存历史"
msgid "Inventory Job Notifications"
msgstr "库存工作通知"
+msgid "Inventory Movements"
+msgstr "库存移动"
+
msgid "Inventory Qty"
msgstr "库存数量"
@@ -6268,6 +6286,9 @@ msgstr "库存追踪"
msgid "Inventory Unit of Measure"
msgstr "库存计量单位"
+msgid "Inventory Valuation"
+msgstr "库存估值"
+
msgid "Invite"
msgstr "邀请"
@@ -6394,6 +6415,9 @@ msgstr "物品"
msgid "Item {scannedItem} is not the same as the item {expectedItem}"
msgstr "项目 {scannedItem} 与项目 {expectedItem} 不相同"
+msgid "Item / Location"
+msgstr "物品 / 位置"
+
msgid "Item filters"
msgstr "项目筛选器"
@@ -6777,6 +6801,9 @@ msgstr "位置"
msgid "Location"
msgstr "位置"
+msgid "Location / Item"
+msgstr "位置 / 物品"
+
msgid "Location Name"
msgstr "位置名称"
@@ -7375,6 +7402,9 @@ msgstr "移至垃圾箱"
msgid "Moved {0} to {1} bucket"
msgstr "已将 {0} 移至 {1} 存储桶"
+msgid "Movements"
+msgstr "移动"
+
msgid "MRP (planning)"
msgstr "MRP (计划)"
@@ -9284,6 +9314,9 @@ msgstr "二维码用于启动此看板的下一个操作"
msgid "Qty"
msgstr "数量"
+msgid "Qty On Hand"
+msgstr "现有数量"
+
msgid "Qty to Order"
msgstr "订购数量"
@@ -9583,6 +9616,9 @@ msgstr "最近的付款"
msgid "Recently Created"
msgstr "最近创建"
+msgid "Reconcile"
+msgstr "对账"
+
msgid "Reconciling a purchase order against what was received and invoiced — implicit in Carbon, via the line quantities and GR/IR balance."
msgstr "回收期"
@@ -11162,9 +11198,6 @@ msgstr "步骤"
msgid "Steps"
msgstr "步骤"
-msgid "Stock Movements"
-msgstr "库存移动"
-
msgid "Stock Transfer ID"
msgstr "库存转移ID"
@@ -12486,6 +12519,9 @@ msgstr "将发货与发票关联,无需重新输入"
msgid "Tie-Out"
msgstr "对账"
+msgid "Tie-Out unavailable"
+msgstr "结账检验不可用"
+
msgid "Tightened"
msgstr "紧张"
@@ -12621,6 +12657,12 @@ msgstr "此地点所有存储单元中该物料的现有总数量。当现有数
msgid "Total quantity required across all active jobs and sales orders at this location — not just this job."
msgstr "此地点所有活动作业和销售订单所需的总数量——而不仅仅是此作业。"
+msgid "Total Value"
+msgstr "总价值"
+
+msgid "Total Variance"
+msgstr "总差异"
+
msgid "Total:"
msgstr "总计:"
@@ -13123,6 +13165,9 @@ msgstr "已验证"
msgid "Validating job..."
msgstr "正在验证工作..."
+msgid "Valuation"
+msgstr "估值"
+
msgid "Value"
msgstr "值"
@@ -13138,6 +13183,9 @@ msgstr "增值税注册号;欧盟发票中反向收费或零税率供应所需
msgid "Values"
msgstr "值"
+msgid "Values apply today's unit costs to historical quantities."
+msgstr "价值采用今日的单位成本应用于历史数量。"
+
msgid "Variance"
msgstr "差异"
diff --git a/packages/react/src/Date/DatePicker.tsx b/packages/react/src/Date/DatePicker.tsx
index 36b209b26f..15ffefee34 100644
--- a/packages/react/src/Date/DatePicker.tsx
+++ b/packages/react/src/Date/DatePicker.tsx
@@ -5,6 +5,7 @@ import type { DatePickerProps } from "@react-types/datepicker";
import type { ReactNode } from "react";
import { useRef } from "react";
import { LuBan, LuCalendarClock, LuInfo } from "react-icons/lu";
+import { cn } from "..";
import { Button } from "../Button";
import { HStack } from "../HStack";
import { IconButton } from "../IconButton";
@@ -114,8 +115,17 @@ const DatePicker = (
{/* Anchor (not Trigger) so the calendar button isn't wrapped
in a second <button>; the popover open state is driven by
react-aria's buttonProps on FieldButton. */}
+ {/* -mt/-mr let the button overlay the group's own 1px border
+ exactly — without -mr-px its rounded corner sits 1px inside
+ the group's corner and both edges show. The sm field is
+ shorter, so the button needs a deeper pull-up. */}
<PopoverAnchor asChild>
- <div className="flex-shrink-0 -mt-px">
+ <div
+ className={cn(
+ "flex-shrink-0 -mr-px",
+ props.size === "sm" ? "mt-[-3px]" : "-mt-px"
+ )}
+ >
<FieldButton
{...buttonProps}
size={props.size}
diff --git a/packages/react/src/Date/DateTimePicker.tsx b/packages/react/src/Date/DateTimePicker.tsx
index 8b8fa2203e..2b7072dbe5 100644
--- a/packages/react/src/Date/DateTimePicker.tsx
+++ b/packages/react/src/Date/DateTimePicker.tsx
@@ -103,7 +103,12 @@ const DateTimePicker = (
)}
</div>
{props.withButton !== false && (
- <div className="flex-shrink-0 -mt-px">
+ <div
+ className={cn(
+ "flex-shrink-0 -mr-px",
+ props.size === "sm" ? "mt-[-3px]" : "-mt-px"
+ )}
+ >
<PopoverTrigger tabIndex={-1}>
<FieldButton
{...buttonProps}