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(accounting): capture-driven intercompany elimination engine + consolidated reporting (#1406)

Brad Barbin9f781bf54ecc
diff --git a/.ai/lessons.md b/.ai/lessons.md
index 8192fe76df..20ffbe2ff9 100644
--- a/.ai/lessons.md
+++ b/.ai/lessons.md
@@ -1024,6 +1024,26 @@ canvas hosting Radix popovers/selects.
**Applies to:** `packages/form/src/components/InputOTP.tsx`, `packages/form/src/ValidatedForm.tsx`, any auto-submitting form field.
+## Dating a synthetic-entity journal with company_today() drops it out of the "as of" report window
+
+**Context:** Intercompany elimination journals post to a synthetic "elimination entity" company (no user membership, no location). `generateEliminationEntries` dated them `company_today(elimination_entity)`. Because the elimination entity has no location, `company_today` fell back to UTC — and on an evening-Pacific boundary UTC had already rolled to the next day. The eliminations posted on Aug 18 while the invoices they eliminate posted Aug 17. The consolidated balance sheet ("Aug 2026 to date", cutoff = today = Aug 17) then showed Inter-Company Payables/Receivables = 100 (un-eliminated), while the account drill-down ("all time") correctly netted to 0 — a confusing split where the row and its own drill-down disagree.
+
+**Problem:** A consolidation adjustment must fall in the SAME reporting period/date window as the transactions it adjusts. Deriving its date from a synthetic entity's own timezone (UTC fallback) is unmoored from the operating companies' business calendar and drifts a day — or a MONTH at a month-end boundary, which would misfile the whole adjustment.
+
+**Rule:** Date a derived/adjusting journal (elimination, allocation, reversal) to the business date of the source transactions it references — e.g. `MAX(sourceJournal.postingDate)` — not to `company_today()` of a synthetic or parent entity that may resolve to a different day. Date a reversal to its original journal's `postingDate` so the two net in one window. When a balance-sheet ROW and its drill-down "Closing" disagree, suspect an out-of-window posting date, not a summing/RLS bug. Fixed in `20260817122328_intercompany-revenue-cogs-elimination.sql`.
+
+**Applies to:** `generateEliminationEntries` and any DB function posting to `isEliminationEntity` companies; any consolidation/allocation/reversal journal; `company_today()` callers where the company may lack a location.
+
+## Consolidation eliminations must allocate per transaction, not per company pair
+
+**Context:** `generateEliminationEntries` looped over company PAIRS (LEAST/GREATEST of the two companies), summed all intragroup revenue/COGS across the pair into one margin, and split the unrealized-profit writedown across the buyer capitalization lines proportional to captured value. A deterministic SQL test harness seeded two trades between the same pair with different margins capitalizing to different accounts (Machinery margin 40, another asset margin 10) and asserted each asset landed at its own group cost — it did not (both drifted to a proportional 75).
+
+**Problem:** Pair-level aggregation preserves the TOTAL (net income and total assets stay correct) but mis-allocates the writedown ACROSS accounts when trades in the pair have different margins. Two companies trade repeatedly in a real ERP, so this is a normal case, not a corner. It was invisible in single-trade tests and only surfaced when regenerate re-matched a second trade into the same pair.
+
+**Rule:** Eliminate/allocate at the grain of the TRANSACTION (the matched seller↔buyer document), not the company pair. Matching links the two sides via `targetJournalLineId` = the other side's `sourceJournalLineId`; use that to pull each trade's own revenue/COGS (seller side) and capitalization (buyer side) and write each asset down by ITS margin. Any consolidation adjustment that aggregates then re-splits proportionally is suspect — prove per-item allocation with a multi-trade, mixed-margin, mixed-account test. The harness (`packages/database/supabase/tests/intercompany-elimination.test.sql`) pins this.
+
+**Applies to:** `generateEliminationEntries`; any margin/cost allocation that groups by counterparty rather than by document.
+
## Batched PostgREST `.in()` with hundreds of ids blows the gateway URL limit — use Kysely for big id-list reads in edge functions
**Context:** Fixing the N+1 traversal in `get-method`'s `itemToJob` by prefetching `itemReplenishment` for a whole method tree (260 item ids) with `client.from(...).in("itemId", ids)` chunked at 200 ids per request.
diff --git a/.ai/plans/2026-08-17-intercompany-elimination-engine.md b/.ai/plans/2026-08-17-intercompany-elimination-engine.md
new file mode 100644
index 0000000000..292af7940c
--- /dev/null
+++ b/.ai/plans/2026-08-17-intercompany-elimination-engine.md
@@ -0,0 +1,202 @@
+# Plan — Intercompany Elimination Engine (structured capture)
+
+> Spec: `.ai/specs/2026-08-17-intercompany-elimination-engine.md`
+> Branch: `fix-elimination-journal-sequence`
+> Approach: capture role-tagged elimination lines at posting time; rewrite the
+> elimination RPC to read them; keep the balance elimination; retire the heuristic
+> revenue/COGS/unrealized-profit reconstruction. **No backfill.**
+
+## Grounding (current code — verified)
+
+- **IC transaction rows** are created only by `post-sales-invoice` (seller) and
+ `post-purchase-invoice` (buyer), each in the same Kysely transaction as its
+ journal lines, with `documentType='Invoice'`, `documentId`=invoiceId,
+ `sourceJournalLineId`=the IC **control** line (receivable/payable), `status='Unmatched'`.
+ `matchIntercompanyTransactions` pairs seller↔buyer by `LEAST/GREATEST(company)` + amount.
+ So **each trade has two IC-txn rows**; a matched pair spans both.
+- `post-shipment` posts SO-based seller COGS (one `costOfGoodsSoldAccount` expense
+ leg + one inventory-relief asset leg via `calculateCOGS`; **no** absorption/variance
+ legs) and creates **no** IC txn.
+- `post-receipt` posts the buyer capitalization debit (`resolveInventoryAccount` →
+ Finished Goods / Raw Materials, or `workInProgressAccount`/`indirectCostAccount`,
+ or `fixedAssetClass.assetAccountId` for FA lines) and creates **no** IC txn.
+- Newest `generateEliminationEntries`:
+ `20260817150538_intercompany-revenue-cogs-from-shipment.sql`. Newest
+ `matchIntercompanyTransactions`: `20260816154722`. `findLowestCommonParent`:
+ original `20260403120000` (unchanged). `eliminationKind` enum + `journal.eliminationKind`:
+ `20260817122328`.
+- Service: `accounting.ee.service.ts` — `createIntercompanyTransaction` (:4573),
+ `runIntercompanyMatching` (:4653), `generateEliminations` (:4662),
+ `getIntercompanyTransactions` (:4550). Routes: `x+/accounting+/intercompany*.tsx`
+ (`eliminate.tsx` uses `bypassRls:true` service role).
+- In each edge fn, after the `journalLine … .returning(["id"])` insert,
+ `journalLineResults[i].id` is 1:1 index-aligned with `journalLineInserts[i]`
+ (which holds `accountId`, `amount`, `quantity`); `itemId` is in the parallel
+ `journalLineDimensionsMeta[i]`. This is the FK handle for capture rows (same
+ index-alignment pattern the existing `journalLineDimension` insert uses).
+
+## Capture data model
+
+`intercompanyEliminationLine` (child of `intercompanyTransaction`):
+
+| col | type | notes |
+|---|---|---|
+| `id` | TEXT `id('icel')` | |
+| `companyId` | TEXT NOT NULL | the company that POSTED the line (seller or buyer) |
+| `intercompanyTransactionId` | TEXT NOT NULL | FK → `intercompanyTransaction("id")` (single-col PK) ON DELETE CASCADE |
+| `role` | `intercompanyEliminationRole` | `Control` / `Revenue` / `COGS` / `Capitalization` |
+| `journalLineId` | TEXT NOT NULL | the actual posted line (FK → `journalLine("id")`) |
+| `accountId` | TEXT NOT NULL | captured for fast elimination reads |
+| `amount` | NUMERIC NOT NULL | posted natural-balance-signed amount |
+| `itemId` | TEXT | COGS / Capitalization rows |
+| `quantity` | NUMERIC | Capitalization (for on-hand realization) |
+| audit | | `createdBy/At`, `updatedBy/At` (per conventions) |
+
+Composite PK `("id","companyId")`, `companyId` FK → `company` CASCADE, indexes on
+`companyId`, `intercompanyTransactionId`, `createdBy`. Four RLS policies
+(`accounting_*`). Enum via `CREATE TYPE`.
+
+## Phases
+
+### Phases 1+2 — DONE, consolidated into ONE existing migration (no new files)
+The branch's elimination SQL is unmerged and the DB is reset for retests, so
+(per Brad) edit in place — do **not** stack a new migration. The whole engine now
+lives in **`20260817122328_intercompany-revenue-cogs-elimination.sql`**: the
+`eliminationKind` enum + `journal.eliminationKind` column + `intercompanyTransaction.amount`
+widen (kept) **plus** the new `intercompanyEliminationRole` enum, the
+`intercompanyEliminationLine` table (+RLS/indexes), and the capture-driven
+`generateEliminationEntries` (+`p_regenerate`). `20260817150538_...from-shipment.sql`
+(the heuristic v2) is **deleted**; no separate capture-table migration.
+`accounting.models.ts` gains `intercompanyEliminationRoles`.
+
+The RPC keeps the permission check, pair loop
+(`LEAST/GREATEST`), LCA→elimination-entity resolution, and period get-or-create
+**verbatim** (they're sound). Replace the two elimination bodies:
+
+- **IC Balance journal** — reverse every `role='Control'` capture line across both
+ IC txns of the pair (`-amount`, same account). Replaces the `controlLines` CTE.
+ Fail loudly if zero Control lines (same guard intent as today).
+- **IC Revenue journal** — per pair (one journal):
+ - Reverse every `role='Revenue'` and `role='COGS'` capture line (`-amount`, same account).
+ - `M = Σ|Revenue| − Σ|COGS|` (margin).
+ - For each `role='Capitalization'` buyer line: credit **its** `accountId` by
+ `M_share × onHandFraction`. `onHandFraction` = `LEAST(onhand, quantity)/quantity`
+ from the buyer's `itemLedger` sum for `itemId`; `itemId IS NULL` (FA) → fraction 1.
+ Split `M` across capitalization lines proportional to their `amount` when several.
+ - Skip the writedown (keep balance + P&L) when no Capitalization line resolves; never guess.
+- Set `eliminationKind` on each journal; retire the pair's IC txns to `Eliminated`.
+- **`p_regenerate BOOLEAN DEFAULT false`**: when true, first post reversing journals
+ for every existing `eliminationKind IS NOT NULL` journal on the group's
+ elimination entities and flip those IC txns `Eliminated → Matched` (immutability:
+ reverse, never delete), then run the normal pass. Satisfies re-runnability without
+ touching the common path.
+
+Retire the account-class sweeps and the invoice→SO→shipment traversal from the RPC
+(they move to capture). No fallback to the old logic (OQ-5).
+
+### Phase 3 — Capture at posting (two invoice edge functions)
+**`post-sales-invoice`** — inside the existing transaction, after
+`journalLineResults` and the `intercompanyTransaction` insert, when
+`isIntercompany && icJournalLineId` (capture the just-created seller txn id — insert
+it with `.returning(["id"])`):
+- `Control`: the receivable line (`icReceivableIdx` → `journalLineResults`).
+- `Revenue`: each line pushed as revenue (`accountId === salesAccount`).
+- `COGS` (direct sale): the `costOfGoodsSoldAccount` line (+ itemId/qty from meta).
+- `COGS` (SO-based): one deterministic query — shipments where
+ `sourceDocument='Sales Order' AND sourceDocumentId IN (this invoice's line salesOrderIds)
+ AND companyId=seller`, then their `journalLine`s on `costOfGoodsSoldAccount`
+ (already posted at shipment); capture those `journalLineId`s (+ itemId/qty).
+
+**`post-purchase-invoice`** — inside the transaction, after `journalLineResults` and
+the `intercompanyTransaction` insert, when `isIntercompany && icJournalLineId`:
+- `Control`: the payable line (`icPayableIdx` → `journalLineResults`).
+- `Capitalization` (not-yet-received / FA-at-invoice): the inventory/WIP/asset debit
+ pushed inline (account + itemId/assetId + qty).
+- `Capitalization` (already-received): the receipt's capitalization `journalLine`
+ (the DR line whose account ≠ `goodsReceivedNotInvoicedAccount`), found from the
+ receipt records the GR/IR-reversal path already resolves in scope.
+
+Track roles via a small parallel `captureMeta` array pushed alongside
+`journalLineInserts` (index-aligned), so capture reads `journalLineResults[i].id`
+without re-deriving by class — the edge fn *knows* each line's role.
+
+`post-shipment` / `post-receipt`: **no change** (invoices look their lines up).
+
+### Phase 4 — Service + UI
+- `accounting.ee.service.ts`: `getIntercompanyEliminationLines(client, companyGroupId, txnIds?)`
+ read helper (join to show roles/amounts). Extend `generateEliminations` to pass
+ `p_regenerate` (add an optional arg + a "Regenerate" action variant on the route).
+- Workbench: extend `getIntercompanyTransactions` row / add a getter surfacing
+ `eliminationKind` + the pair's captured lines by role, and render them (a
+ per-pair expando or a detail column in `IntercompanyTransactionTable`), so a
+ reviewer can trace a consolidated 0 to the operating lines. Surface `eliminationKind`
+ in the consolidated `AccountLedgerLine`/drawer (add the column to `getAccountLedger`
+ select + `AccountLedgerDrawer`).
+
+### Phase 5 — Types + verify
+`pnpm run generate:types` → scoped typechecks (`@carbon/database`, `@carbon/erp`
+via turbo filter) → `pnpm --filter @carbon/erp test -- --testPathPattern=accounting`.
+Fix hits. Edge-function runtime + browser verification and DB apply wait on the user
+(can't rebuild DB or boot the stack here). Note in the PR what's proven vs pending.
+
+### Phase 6 — Consolidate specs + plans
+Per the user's instruction: merge this branch's specs into **one** spec and its
+plans into **one** plan, dropping stale/superseded content, so the branch carries a
+single coherent spec + plan. (`2026-07-04-intercompany-maturity.md` is prior art for
+a different, unshipped feature — keep it separate unless it's this branch's work; it
+is not. Fold together only the elimination-scope lineage that belongs to this branch.)
+
+## Risks / watch-items
+- **Big edge functions.** Capture blocks are additive and gated on `isIntercompany`;
+ never alter existing GL postings. Add after the IC-txn insert.
+- **Already-received buyer capitalization lookup.** Use the receipt data already in
+ scope in the GR/IR-reversal path; if it can't be resolved, skip capitalization
+ capture (balance + P&L still eliminate) and let the RPC skip the writedown.
+- **`intercompanyTransaction` single-col PK** — capture FK is single-column
+ (`intercompanyTransactionId` → `intercompanyTransaction("id")`), not composite.
+- **Regenerate double-post** — reverse existing eliminations before regenerating;
+ reversing entries (not deletes) respect immutability.
+- Two committed migrations (`122328`, `150538`) still reference the deleted scope
+ spec in comments; they're on `main`/pushed — leave them (fix-forward rule); the
+ new spec supersedes.
+```
+
+## Progress
+- [x] Phases 1+2 — capture table + capture-driven RPC, consolidated into `20260817122328` (150538 deleted)
+- [x] Phase 3 — edge-function capture (`post-sales-invoice`, `post-purchase-invoice`)
+- [x] Phase 4 — service (`generateEliminations(regenerate)`, `getIntercompanyEliminationLines`, manual-path Control capture) + workbench "Regenerate" button
+- [x] Phase 5 — verify: erp typecheck **0 errors**, **123 accounting tests pass** (3 pre-existing period-close mock failures, unrelated). ⏳ DB apply + `generate:types` + edge-function runtime + browser retest wait on Brad (no DB rebuild / Docker here).
+- [x] Phase 6 — this branch carries a single spec + single plan (scope spec deleted; maturity spec is separate/on-main)
+
+## Applied + verified on the live dev DB (this session)
+- **Overload bug caught on the reset and fixed in the migration.** Adding the
+ `p_regenerate DEFAULT` param makes `CREATE OR REPLACE` build a SIBLING of the
+ 2-arg `generateEliminationEntries` from the earlier (on-`main`) `20260817012947`,
+ so even a fresh reset left TWO overloads and a 2-arg call was ambiguous.
+ `20260817122328` now `DROP FUNCTION IF EXISTS "generateEliminationEntries"(TEXT, TEXT)`
+ before the `CREATE OR REPLACE`, so exactly one function survives a fresh reset.
+- After the reset: `pnpm db:migrate` (schema up to date), applied the DROP to the
+ live DB, regenerated types. Exactly one 3-arg function remains.
+- `erp` typecheck **0 errors** against the regenerated types; RPC smoke-tested via
+ psql: 2-arg call (default) → `0`, `p_regenerate=true` → `0`, non-employee → refused
+ — all resolving unambiguously to the single 3-arg function.
+
+## Deterministic proof without manual data entry
+- `packages/database/supabase/tests/intercompany-elimination.test.sql` seeds trades
+ at the journal+capture level, runs the RPC, and asserts the consolidated result
+ in a rolled-back transaction. Run:
+ `psql "$SUPABASE_DB_URL" -v ON_ERROR_STOP=1 -f packages/database/supabase/tests/intercompany-elimination.test.sql`
+- 6 scenarios PASS: fixed-asset buyer, inventory fully held, partial realization,
+ transaction-dated posting, regenerate idempotency, multi-trade-per-pair.
+- It caught a real bug — **pair-level margin aggregation mis-allocated the writedown**
+ across capitalization accounts. Fixed to **per-trade** allocation (link seller↔buyer
+ via `targetJournalLineId` from matching). Net income was always right; per-account
+ asset allocation now is too.
+
+## Outcome / hand-off
+- **Data-driven retest (Brad):** with a two-company intercompany scenario, post the
+ seller invoice + buyer receipt/invoice (edge functions now write capture), Run
+ Matching, Generate Eliminations, and check the consolidated scenario (Machinery &
+ Equipment = group cost, Finished Goods = 0, Sales/COGS = 0, IC Receivable/Payable = 0).
+- **After a correction:** use **Regenerate** (reverses existing eliminations via reversing entries, re-derives from current capture + on-hand).
+- **Deferred nicety:** per-pair captured-line detail in the workbench UI (`getIntercompanyEliminationLines` is wired for it); needs browser verification.
diff --git a/.ai/research/intercompany-eliminations.md b/.ai/research/intercompany-eliminations.md
new file mode 100644
index 0000000000..3550a7f929
--- /dev/null
+++ b/.ai/research/intercompany-eliminations.md
@@ -0,0 +1,480 @@
+# Intercompany Eliminations Research: Best Practices Survey
+
+## Summary
+
+Surveyed how best-in-class ERPs and the governing accounting standards handle
+**intercompany elimination for group consolidation**, to feed a holistic design
+for Carbon. Researched SAP S/4HANA Group Reporting, NetSuite OneWorld, Oracle
+FCCS/EPM, Microsoft Dynamics 365 Finance, Sage Intacct, the QuickBooks/Xero SMB
+tier (+ consolidation add-ons), and the canonical US GAAP (ASC 810) / IFRS 10
+mechanics with textbook journal entries.
+
+**The dominant finding is a universal *automatic-vs-manual gradient* that every
+platform shares**, and it maps almost exactly onto complexity of realization:
+
+| Elimination type | Auto in enterprise ERPs? | Carbon today |
+|---|---|---|
+| IC receivables/payables (due-to/due-from, loans, notes) | **Always automatic** | ✅ Done (`generateEliminationEntries`) |
+| IC revenue ↔ COGS/expense (intragroup sales gross-up) | Auto-capable, **opt-in config** | ❌ Not eliminated |
+| Unrealized profit in **inventory** | **Manual top-side everywhere** (SAP's IPI is the lone rule-based exception) | ❌ Not eliminated |
+| Unrealized profit in **transferred fixed assets** (+ depreciation catch-up) | **Manual top-side everywhere** | ❌ Not eliminated |
+| Investment-in-subsidiary / equity + **NCI** | Separate rules layer, ownership-% driven | ❌ Not modeled |
+
+Carbon has already built the hard *infrastructure* (transaction-time IC partner
+tagging, matched `intercompanyTransaction` pairs, a synthetic per-parent
+elimination entity routed by lowest-common-parent) — the same primitives the
+enterprise systems use and that QuickBooks/Xero conspicuously lack. What's
+missing is the **elimination scope beyond the AR/AP control wash**. The
+recommendation is a phased engine: complete the P&L (revenue↔COGS) elimination
+now, add guided unrealized-profit-in-inventory next, and defer fixed-asset-gain
+and investment/NCI to later phases (they are manual even in NetSuite/D365).
+
+The single most important architectural idea to adopt from SAP: eliminations are
+their own **classified ledger layer keyed by (unit, partner)**, never a mutation
+of source documents — which Carbon already does. The second: **don't assume both
+legs are trading-partner-tagged** (the buyer's COGS usually isn't), so support
+**one-sided** elimination.
+
+---
+
+## Competitors Surveyed
+
+- **SAP S/4HANA Group Reporting** (+ legacy EC-CS / SEM-BCS) — the enterprise
+ reference; established the trading-partner + posting-level data model and the
+ only mainstream *rule-based* unrealized-inventory-profit (IPI) automation.
+- **NetSuite OneWorld** — closest architectural analog to Carbon: a flagged
+ **elimination subsidiary** at the lowest common parent, account-level
+ "Eliminate Intercompany Transactions" flag, period-close auto-elimination that
+ reverses next period. Explicitly leaves unrealized inventory/FA profit manual.
+- **Oracle FCCS / EPM** — the "consolidation-dimension overlay" camp (elimination
+ is a cube member, not a journal); strong ownership-%/NCI rules model.
+- **Microsoft Dynamics 365 Finance** — elimination *legal entity* + rule-based
+ elimination journals (Source/Destination/Consolidated LE roles); due-to/due-from.
+- **Sage Intacct** — cleanest SMB auto/manual line: auto-eliminates inter-entity
+ AR/AP (IER/IEP mapping); everything else is opt-in account config.
+- **QuickBooks / Xero + add-ons (Joiin, LiveFlow, Fathom)** — the SMB reality:
+ no native elimination; report-layer overlays; account-name matching (no partner
+ tag). Defines the *floor* Carbon should beat.
+- **US GAAP ASC 810-10-45-1 / IFRS 10 B86** — eliminate intragroup items **in
+ full (100%)** regardless of ownership; ownership % only splits *unrealized
+ profit* between controlling interest and NCI (upstream vs downstream).
+
+---
+
+## Key Consensus Patterns
+
+### 1. Eliminations are a separate, classified ledger layer — never posted to operating books
+
+- **SAP**: consolidation journal entries in a totals table, stamped with two
+ orthogonal classifiers — **posting level** (which consolidation step produced
+ it: `00` loaded · `10` manual group · `20` two-sided unit-pair elimination ·
+ `30` group-dependent C/I & NCI) and **document type** (method + number range,
+ e.g. `2G`). Never touches the subsidiary FI ledger.
+- **NetSuite**: elimination journals post **only** to the elimination subsidiary;
+ operating subsidiaries' GLs are untouched.
+- **D365 / Intacct**: post to a dedicated elimination legal entity / elimination
+ account that only exists in the consolidated view.
+- **Oracle FCCS**: not "posted" at all — written to a reserved `Elimination`
+ Consolidation-dimension member computed on the fly.
+- **GAAP/IFRS theory**: these are *worksheet entries*, re-derived every period
+ from trial balances; they never persist in any legal entity's books.
+- **Rationale**: audit trail + the single-economic-entity assumption. The group
+ can't sell to / lend to / profit from itself, but the individual entities'
+ standalone books must stay pristine for statutory/tax reporting.
+- **Carbon already does this** — the synthetic `isEliminationEntity` company holds
+ the elimination journal; operating companies are untouched.
+
+### 2. Elimination entity sits at the lowest common parent of the transacting pair
+
+- **NetSuite**: elimination subsidiary must be a direct child of the parent that
+ has children; NetSuite walks up from both transacting subs to their nearest
+ shared ancestor and uses that ancestor's elimination child. Multi-tier
+ structures need one elimination sub per consolidation level. Locked to the
+ parent's base currency; consolidated rate of 1 to its parent.
+- **SAP**: posting level 20 (unit-pair) entries land on a "consolidation unit for
+ elimination"; level 30 entries are specific to a group-hierarchy node.
+- **Carbon already does this** — `findLowestCommonParent(a, b)` + the per-parent
+ elimination entity (matches the project's `elimination_entity_lca` note).
+
+### 3. Intercompany transactions are identified at transaction time by a partner tag — not reconstructed at close
+
+- **SAP**: **trading partner** (Handelspartner) = counterparty company ID stamped
+ on the source document; becomes the **partner unit** dimension in consolidation.
+ Elimination does **not** require special IC accounts — the *partner dimension*
+ is the criterion (IC accounts merely scope which items to consider).
+- **NetSuite**: **Represents Subsidiary** links a customer/vendor to the sub it
+ stands for → enables **Paired Intercompany Transactions** matching. Plus
+ account-level **"Eliminate Intercompany Transactions"** flag.
+- **D365 / Intacct**: due-to/due-from accounts auto-generated at posting + a
+ trading-partner dimension / entity tag.
+- **QuickBooks/Xero add-ons**: the *weak* model — match by account name/code
+ across charts, no partner tag. This is exactly the gap SMBs pay to fill.
+- **Carbon already does this well** — `customer/supplier.intercompanyCompanyId`,
+ `journalLine.intercompanyPartnerId`, and matched `intercompanyTransaction`
+ pairs. This is Carbon's biggest head start over the SMB tier.
+
+### 4. The automatic-vs-manual gradient is identical across every platform
+
+Ranked by how universally automated (see Summary table). AR/AP is always
+automatic; revenue/expense is auto-capable but opt-in; **unrealized profit in
+inventory and fixed-asset transfers is manual top-side everywhere** except SAP's
+rule-based IPI; investment/NCI is a separate ownership-%-driven rules layer.
+**Design consequence**: phase the engine along this gradient; don't try to
+auto-detect unrealized profit on day one (nobody else does, except SAP).
+
+### 5. Don't assume both legs carry the partner tag — support one-sided elimination
+
+- **SAP** eliminates IC revenue **one-sided** because the seller records revenue
+ *with* a trading partner but the buyer's **COGS is derived from inventory
+ issue and usually carries no trading partner**. It reclassifies against a
+ matching cost item rather than requiring both legs tagged.
+- **Implication for Carbon**: the revenue↔COGS elimination can't rely on a
+ matched `intercompanyTransaction` pair for the *COGS* side — the COGS on the
+ buyer's books isn't an IC-tagged line. The seller's revenue line and its
+ own COGS (on the seller's books) are the identifiable pair to eliminate.
+
+### 6. Unrealized-profit eliminations are standing entries recomputed each period against current on-hand balances, backed by a carried opening balance
+
+- **SAP**: IPI recomputed each period on current closing inventory; the eliminated
+ profit sits in a balance-sheet inventory-writedown position that **carries
+ forward** as an opening balance; realizes when goods leave the group.
+- **GAAP theory (Entry G / \*G)**: Year 1 defers profit (Dr COGS / Cr Inventory);
+ Year 2 realizes it as inventory sells externally (Dr **beginning** Retained
+ Earnings / Cr COGS), then re-defers whatever is unsold at the new year-end. Net
+ over two periods = zero; the profit is time-shifted to the period of the
+ outside sale.
+- **Fixed assets (Entry TA / \*TA / ED)**: full gain eliminated on transfer, asset
+ restated to original cost/accum. depreciation, and the deferred gain
+ **self-liquidates** via a recurring excess-depreciation reversal (Dr Accum.
+ Dep / Cr Depreciation Expense) over the remaining life — or immediately on
+ external sale/disposal.
+- **Design consequence**: unrealized-profit eliminations need a **deferred-profit
+ sub-ledger** keyed to the unsold inventory / undepreciated asset basis, with
+ **realization triggers** (external sale, each depreciation period, disposal,
+ deconsolidation) and a **beginning-RE snapshot** — this is fundamentally more
+ than a per-period reversing journal.
+
+### 7. Elimination differences split into "real" vs "currency" (FX residual → CTA)
+
+- **SAP**: translate to group currency **first**, then eliminate. Two matched IC
+ balances translated at different rates (B/S at closing, P&L at average) won't
+ net to zero; the residual is split into a **real difference** (genuine mismatch
+ → difference/P&L account) and a **currency difference** (FX → CTA / translation
+ reserve, FS item 314800).
+- **NetSuite**: a system **CTA-E** (Cumulative Translation Adjustment –
+ Elimination) account absorbs the consolidation-rate FX residual between the
+ original entry and its elimination.
+- **Design consequence for Carbon**: Carbon's consolidation already translates
+ per company and computes a CTA (`translateCompanyBalances` → `ctaByBucket`).
+ Elimination in a multi-currency group needs a CTA-E-equivalent plug; **for a
+ single-currency group (Carbon's common case) this is a no-op** and can be
+ deferred, but the design should reserve the account.
+
+### 8. Reversal timing: period-specific auto-reversing (balances) vs standing (profit deferrals)
+
+- **NetSuite**: elimination journals are period-dated by the period-close task;
+ balance-sheet IC lines **auto-reverse next period**; re-runnable (reverses prior
+ + regenerates).
+- **SAP**: balance carryforward rolls B/S closing → next-year opening; P&L is not
+ carried (closes to RE) — which is *why* profit deferrals need the beginning-RE
+ treatment.
+- **Design consequence**: model AR/AP + revenue/COGS eliminations as
+ **period-scoped, regenerable** entries (recompute on re-run, like Carbon's
+ current pair-based generate); model profit deferrals as **carried** with
+ explicit realization triggers.
+
+---
+
+## Answers to Research Questions
+
+1. **What's the standard taxonomy, and which does a manufacturing SMB need?** —
+ Five layers: (1) IC balances AR/AP/loans/notes, (2) IC revenue↔COGS, (3)
+ unrealized profit in inventory, (4) unrealized profit in transferred fixed
+ assets, (5) investment/equity + NCI. **SMB manufacturing needs 1–2 day one**
+ (SAP/NetSuite/Intacct automate these); **3 is the manufacturing differentiator**
+ (IC-transferred WIP/components — worth a *guided* entry, not full auto); **4–5
+ are manual even in NetSuite/D365** and should be deferred/manual-journal-only.
+
+2. **Where do eliminations post, and at what hierarchy level?** — A dedicated
+ elimination entity/ledger layer (NetSuite/D365/Intacct/SAP) — never operating
+ books — at the **lowest common parent** of the transacting pair for unit-pair
+ eliminations (posting level 20); a **group-hierarchy node** for
+ ownership-dependent entries (level 30). **Carbon already matches this.**
+
+3. **How is unrealized profit in inventory/FA tracked and realized?** — Via a
+ deferred-profit position carried on the balance sheet, **recomputed each
+ period on current on-hand balances**, realized when: inventory is sold
+ externally, a fixed asset depreciates (excess-depreciation reversal each
+ period) or is disposed, or the sub is deconsolidated. Manual everywhere except
+ SAP's rule-based IPI (Percent-from-Partner / standard % / actual group cost).
+
+4. **How are IC transactions identified — auto vs manual?** — Transaction-time
+ **partner tag** (SAP trading partner, NetSuite Represents Subsidiary, D365/
+ Intacct due-to/due-from) + account-level IC flag. Auto-matched into pairs.
+ Manual only in the QuickBooks/Xero tier (account-name matching). **Carbon is
+ already in the "auto" camp.**
+
+5. **Recurring vs one-time, and reversal at period roll?** — AR/AP + revenue/COGS
+ = **recurring/regenerable, period-scoped** (NetSuite auto-reverses next
+ period). Profit deferrals (inventory, FA) = **carried forward** until the
+ underlying item leaves the group, re-made each period against current balances
+ with a beginning-RE snapshot. Investment/goodwill allocation = **one-time
+ measurement carried forward + amortized**.
+
+6. **Multi-currency / CTA and partial ownership / NCI?** — Translate first, then
+ eliminate in group currency; FX residual → CTA-E. **100% elimination
+ regardless of ownership**; ownership % only splits *unrealized profit* between
+ controlling interest and NCI, and only for **upstream** (sub→parent)
+ transactions (downstream is 100% controlling, NCI untouched). NCI is a
+ separate rules layer (SAP level 30 / FCCS NCI rules).
+
+---
+
+## Competitor-Specific Details
+
+### SAP S/4HANA Group Reporting
+- **Posting levels** (adopt as a classifier): `00` reported · `01` standardizing ·
+ `10` manual group / rule-based goodwill · `20` two-sided unit-pair elimination ·
+ `21/22` two-sided w/ group change · `30` group-dependent (C/I, NCI).
+- **Document types** under levels (e.g. `2G` IC elimination) own number ranges =
+ audit trail.
+- **IPI feature** — the only mainstream rule-based unrealized-inventory-profit
+ automation. Profit = inventory book value on hand − group COGM; writes inventory
+ down to group cost (lower-of). Markup sources: **Percent from Partner** / fixed
+ % / actual group cost. Guards: profit was recorded, both units in group, group
+ still owns the asset.
+- **ICMR** (Intercompany Matching & Reconciliation) — pre-close rule-based
+ matching so elimination runs on reconciled data. Carbon's
+ `matchIntercompanyTransactions` is a lightweight ICMR.
+- **C/I tasks 2100/2101**; **Consolidation of Investments** with purchase vs
+ equity method; first vs subsequent consolidation.
+
+### NetSuite OneWorld
+- **Elimination subsidiary** (flagged), lowest-common-parent placement, base-
+ currency-locked, JE-only, free (not counted to the 250-sub cap).
+- **Automated Intercompany Management** (⚠️ irreversible once enabled) adds the
+ account-level "Eliminate Intercompany Transactions" flag, the journal-line
+ **Eliminate** box, **Represents Subsidiary**, **CTA-E** account, and a
+ period-close **"Eliminate Intercompany Transactions"** task.
+- **Auto**: IC AR/AP, IC revenue/expense, IC FX revaluation. **Manual**: unrealized
+ inventory profit, FA transfer gains, OCI reclass, NCI. Known gap: for
+ arm's-length IC inventory transfers the automated task **does not zero the IC
+ clearing accounts** — a manufacturing ERP that closes this is a differentiator.
+- Balance-sheet IC eliminations **auto-reverse next period**; re-runnable.
+
+### Oracle FCCS / EPM
+- Elimination = a reserved **Consolidation-dimension member** + Data Source member;
+ two entries (reversal + **Plug** to a clearing account) net to zero by
+ construction. No ledger journal. Recomputed every consolidation (no reversal).
+- Auto when: account flagged IC with a Plug account + valid ICP partner + common
+ ancestor at >0%. **NCI is a separate rules layer** (required even at 100%).
+
+### Microsoft Dynamics 365 Finance
+- **Elimination legal entity** ("Use for financial elimination process"); roles
+ Source / Destination / Consolidated LE. Rule-based **Elimination journals**
+ (net-change or fixed amount) via **Elimination proposal**, or during
+ **Consolidate online**. Match on source account (wildcards) + trading-partner
+ dimension. Markup on IC sales explicitly called out as *your* problem (no
+ auto profit-in-inventory).
+
+### Sage Intacct
+- Elimination entity/account per consolidation **book**. **Auto**: inter-entity
+ receivable (IER) / payable (IEP) per the mapping. **Opt-in**: investment,
+ inter-entity sales, IC loans, other IC income/expense (add the GL accounts to
+ the elimination set). Due-to/due-from auto-generated at journal entry. Cleanest
+ SMB model: **the account mapping *is* the config** (no pairwise rule authoring).
+
+### QuickBooks / Xero + add-ons
+- **No native elimination.** Add-ons (Joiin, LiveFlow, Fathom) do report-layer
+ eliminations by account-name matching; Joiin supports %-ownership per entity.
+ SMB threshold to adopt tooling: **~3+ entities / manual close / >1 day per
+ period reconciling**. Below that, spreadsheet elimination of **IC AR/AP + IC
+ revenue/expense only** is considered adequate; unrealized-profit and NCI are
+ where SMBs stop.
+
+### Canonical GAAP/IFRS entries (the mechanics to model)
+- **Case 1 — AR/AP**: `Dr IC Payable / Cr IC Receivable`. Pure B/S wash, recurring.
+ *(Carbon does this.)*
+- **Case 2 — Revenue↔COGS**: `Dr Sales (IC) / Cr COGS` at full transfer price,
+ recurring on each period's IC sales. If fully resold externally, this is the
+ *only* entry.
+- **Case 3 — Unrealized profit in ending inventory**: deferred profit = IC gross
+ profit rate × transfer-price cost still in buyer's ending inventory.
+ Year 1 `Dr COGS / Cr Inventory`; Year 2 realize `Dr beginning Retained Earnings
+ (or Investment) / Cr COGS`. **Upstream** (sub→parent) splits the deferral with
+ NCI in the ownership ratio; **downstream** is 100% controlling, NCI untouched.
+ Elimination is always 100% either way.
+- **Case 4 — FA transfer**: Year of transfer `Dr Gain, Dr Equipment / Cr Accum.
+ Dep` (restate to original gross/accum) + `Dr Accum. Dep / Cr Depreciation
+ Expense` (reverse current-year excess dep). Subsequent years `Dr beginning RE,
+ Dr Equipment / Cr Accum. Dep` (shrinking RE debit) + the annual excess-dep
+ reversal until fully depreciated/sold. Upstream shares with NCI.
+- **Case 5 — Loans/interest**: `Dr Notes Payable / Cr Notes Receivable` +
+ `Dr Interest Income / Cr Interest Expense`; accrued interest is a Case-1
+ reciprocal. No profit deferral (unless interest was capitalized into an asset).
+- **Case 6 — Investment/equity + NCI**: Entry S (eliminate beginning sub equity
+ vs investment, set NCI), Entry A (fair-value step-ups + goodwill), recurring
+ Entry I/D/E. Ownership-%-driven; largely one-time measurement carried forward.
+
+---
+
+## Recommended Approach for Carbon
+
+**Adopt SAP's classifier + NetSuite's elimination-entity model (Carbon already
+has both), and phase the scope along the industry auto/manual gradient.** Carbon's
+infrastructure (transaction-time IC tagging, matched pairs, LCA-routed elimination
+entity) is already the enterprise pattern — the work is scope, not re-architecture.
+
+### Phase 0 — Foundation hardening (do alongside the display fixes already made)
+1. **Classify elimination journals** with a posting-level-equivalent + method tag
+ (SAP posting level / NetSuite document type). Today every elimination is
+ `sourceType: 'Manual'` with description `IC Elimination: A ↔ B`. Add an
+ explicit elimination **kind** (`balance` / `revenue-cogs` / `unrealized-inv` /
+ `fixed-asset` / `investment`) so reports can show/audit the layer and
+ re-runs can target one kind. This is the enabling refactor for everything else.
+2. **Close the two grounded gaps** the Carbon investigation surfaced: (a) the
+ buyer-side payment in `post-payment` does **not** relieve
+ `intercompanyPayablesAccount` (only the AR side relieves its IC account);
+ (b) `intercompanyTransaction.amount` is still `NUMERIC(19,4)` — violates the
+ bare-`NUMERIC` convention. Both are small, independent, and worth fixing first.
+3. **Make elimination re-runnable/idempotent per period** — reverse-and-regenerate
+ (NetSuite semantics) rather than append, so re-matching after a correction is
+ safe.
+
+### Phase 1 — IC Revenue ↔ COGS elimination (the immediate correctness gap)
+This is what makes the consolidated **income statement** correct (today it shows
+$100 of phantom intragroup revenue). Model the **seller's** IC revenue line and
+its matching COGS as the eliminable pair (one-sided per SAP — the buyer's COGS
+isn't IC-tagged). Elimination entry on the LCA elimination entity:
+`Dr IC Revenue / Cr COGS` at the full transfer amount. Drive it off the
+`intercompanyPartnerId`-tagged revenue lines already stamped by
+`post-sales-invoice`, extending `generateEliminationEntries` to sweep the revenue
+(and seller COGS) lines — not just the receivable control line. Requires
+account-default mappings for the IC revenue/COGS accounts (mirror
+`intercompanyReceivablesAccount`).
+
+### Phase 2 — Guided unrealized profit in inventory (the manufacturing differentiator)
+NetSuite leaves this manual and even leaves IC clearing non-zero; SAP's IPI is the
+gold standard. Carbon uniquely owns both the IC sale **and** the buyer's inventory
+(`itemLedger`/`costLedger`), so it can compute the embedded margin on *still-on-hand*
+IC-sourced inventory. Build a **deferred-profit sub-ledger** keyed to unsold
+quantity, recomputed each period, realized as inventory sells externally
+(Entry G / \*G). Ship it as a **guided/reviewable** entry first (surface the
+computed margin, let the user confirm), not silent automation — matching how every
+platform treats this as high-review-risk. **This is the highest-value net-new
+capability** and where Carbon can beat NetSuite. Requires cross-company cost
+visibility (today `costLedger` is per-company with zero IC awareness) — the main
+new infrastructure.
+
+### Phase 3+ — Defer (manual-journal-only for now)
+- **Fixed-asset transfer gain** + depreciation catch-up (Entry TA/\*TA/ED) —
+ manual even in NetSuite/D365; multi-year carryforward. Provide a guided manual
+ elimination journal, not an engine.
+- **Investment-in-subsidiary / equity + NCI** — over-engineering for SMB day one;
+ needs an ownership-% model. A simple per-entity ownership % + manual investment
+ elimination is the SMB-appropriate stopping point (Joiin/D365 pattern).
+- **Multi-currency CTA-E** — reserve the account; no-op for single-currency groups
+ (Carbon's common case), implement when a group spans currencies.
+
+### Design principles to encode (from the consensus)
+- Eliminations are a **classified ledger layer keyed by (unit, partner)**, on the
+ LCA elimination entity, never mutating operating books. *(Carbon has this.)*
+- **Don't assume both legs are partner-tagged** — support one-sided elimination.
+- **100% elimination regardless of ownership**; ownership % only splits unrealized
+ profit (upstream vs downstream) — encode a **direction flag** on every profit
+ deferral even before NCI is built, so the data is right when NCI lands.
+- **Profit deferrals carry forward** with explicit realization triggers + a
+ beginning-RE snapshot; balance/revenue eliminations are period-scoped and
+ regenerable.
+- **Split elimination differences into real vs currency**; route FX residual to a
+ CTA-E account.
+- **Terminology to adopt**: *trading partner* (already `intercompanyPartnerId`),
+ *interunit (IU) elimination*, *unrealized profit in inventory*, *elimination
+ entity*, *posting level / elimination kind*, *upstream/downstream*,
+ *non-controlling interest (NCI)*, *CTA-E*.
+
+### Scope recommendation (headline)
+**Phases 1 + 2 are the target for a holistic-but-SMB-right design.** Phase 1
+fixes a real correctness bug (phantom IC revenue in consolidated P&L); Phase 2 is
+the manufacturing differentiator no SMB competitor automates. Phases 3+ are
+manual-journal-only until there's demand, matching where NetSuite/D365/Intacct
+themselves draw the line.
+
+---
+
+## Open Questions (carry into the spec)
+
+1. **Fixed-asset intragroup transfer** in Carbon currently flows through ordinary
+ two-step disposal with no IC awareness — does the design intercept it at
+ posting (tag the disposal gain) or handle it purely at elimination? (Affects
+ whether Phase 3 needs edge-function changes.)
+2. **Cross-company cost basis** for Phase 2: does Carbon introduce a shared/group
+ cost layer, or compute the margin from the seller's `costLedger` at elimination
+ time? (The latter is less invasive.)
+3. **IC revenue/COGS account defaults**: add dedicated `intercompanyRevenueAccount`
+ / `intercompanyCogsAccount` to `accountDefault` (mirroring the AR/AP pattern),
+ or derive from the posted revenue lines' accounts?
+4. **Ownership model**: is any Carbon group ever partially owned, or is 100%
+ wholly-owned assumed (making NCI moot and Phase 3 investment-elimination
+ trivial)? Determines whether the direction flag / ownership % is needed at all.
+5. **Realization trigger for inventory**: Carbon knows external sales via
+ `itemLedger`/shipments — is per-period recompute-on-current-on-hand (SAP IPI
+ style) acceptable, or is lot-level FIFO tracing of which IC-sourced units left
+ required?
+6. **Re-run / period-close integration**: should elimination be a period-close
+ checklist task (NetSuite/SAP) tied to `accountingPeriod`, with reverse-and-
+ regenerate on re-run?
+
+---
+
+## Sources
+
+### SAP
+- https://learning.sap.com/learning-journeys/performing-consolidation-with-sap-s-4hana-cloud-for-group-reporting/outlining-intercompany-elimination-possibilities_e52d704e-44d0-4ea9-a630-73dc4529271e
+- https://learning.sap.com/learning-journeys/performing-consolidation-with-sap-s-4hana-cloud-for-group-reporting/eliminating-intercompany-payables-and-receivables_de0d1447-34c8-47ef-8e05-112f40a604ab
+- https://learning.sap.com/learning-journeys/performing-consolidation-with-sap-s-4hana-cloud-for-group-reporting/eliminating-intercompany-revenue-and-cost_bf0684be-4502-4f31-86ad-85dd3d2d04a2
+- https://learning.sap.com/learning-journeys/implementing-sap-s-4hana-cloud-for-group-reporting/eliminating-intercompany-profit-in-inventory_e614ce07-fc6f-43c3-99a9-3f57a4d4fedd
+- https://learning.sap.com/learning-journeys/implementing-sap-s-4hana-cloud-for-group-reporting/configuring-profit-in-inventory-elimination-methods_d6e948d8-07fe-4ba4-b360-5d0813e41040
+- https://learning.sap.com/learning-journeys/performing-consolidation-with-sap-s-4hana-cloud-for-group-reporting/describing-posting-levels-and-document-types_ab40ffc2-fe6e-4116-a497-d4a0ba1ada4f
+- https://help.sap.com/doc/eba6c6535e601e4be10000000a174cb4/700_SFIN20%20006/en-US/4b72e3a4a6b3584de10000000a42189c.html
+- https://help.sap.com/doc/eba6c6535e601e4be10000000a174cb4/700_SFIN20%20006/en-US/3ea6c6535e601e4be10000000a174cb4.html
+- https://help.sap.com/docs/SAP_S4HANA_CLOUD/90c07e91c7a64f328be3fd6b48955b13/a8172f85383947bd8538bf778e771874.html (ICMR)
+- https://learning.sap.com/learning-journeys/consolidating-investments-with-sap-s-4hana-cloud-for-group-reporting/defining-consolidation-of-investments
+- https://blog.sap-press.com/intercompany-elimination-analysis-use-cases-in-sap-s4hana
+
+### NetSuite
+- https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_N268759.html (Elimination Subsidiaries)
+- https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_N1498385.html (IC Elimination Overview)
+- https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_N1486610.html (Automated IC Management setup)
+- https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_N1486928.html (Intercompany Accounts)
+- https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_N1501565.html (Elimination via Automated IC Management)
+- https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_N1498982.html (IC Elimination multi-currency example / CTA-E)
+- https://timdietrich.me/blog/netsuite-intercompany-transactions-eliminations/
+- https://www.houseblend.io/articles/netsuite-intercompany-eliminations-guide
+- https://suiterep.com/2023/11/01/the-netsuite-intercompany-framework-feature/
+
+### Oracle FCCS / Dynamics / Intacct / QuickBooks-Xero
+- https://docs.oracle.com/en/cloud/saas/financial-consolidation-cloud/agfcc/intercompany_eliminations.html
+- https://docs.oracle.com/en/cloud/saas/financial-consolidation-cloud/toutorial-fcc-partner-elimination/index.html
+- https://docs.oracle.com/cd/E41507_01/epm91pbr3/eng/epm/pgcs/task_DefiningNon-ControllingInterestRules-399848.html
+- https://learn.microsoft.com/en-us/dynamics365/finance/general-ledger/elimination-rules
+- https://learn.microsoft.com/en-us/dynamics365/finance/budgeting/consolidation-elimination-overview
+- https://www.randgroup.com/insights/microsoft/dynamics-365/finance-operations/intercompany-accounting-in-dynamics-365-finance-setup-steps-common-errors-and-best-practices/
+- https://www.intacct.com/ia/docs/en_GB/help_action/Multi-entity/Inter-entity_transactions/interentity-txn-overview.htm
+- https://www.intacct.com/ia/docs/en_AU/help_action/Consolidations/Global_Consolidations/Consolidations/about-inter-entity-eliminations.htm
+- https://www.intacct.com/ia/docs/en_US/help_action/Consolidations/Global_Consolidations/Book_setup/elimination-accounts-tab.htm
+- https://liveflow.com/blog/intercompany-eliminations-what-they-are-how-they-work-and-how-to-automate-them
+- https://liveflow.com/blog/best-multi-entity-consolidation-software-6-tools-compared
+- https://www.joiin.co/features/intercompany-management/
+- https://www.intuit.com/enterprise/blog/financials/intercompany-eliminations/
+
+### GAAP / IFRS theory
+- https://viewpoint.pwc.com/dt/us/en/pwc/accounting_guides/consolidation_and_eq/consolidation_and_eq_US/chapter_8_intercomp_US/82_intercomp_tran_US.html
+- https://viewpoint.pwc.com/dt/us/en/pwc/accounting_guides/equity_method_of_accounting/Equity_method_account/chapter_4/42_elimination_of.html
+- https://www.deloitte.com/us/en/services/consulting/articles/profit-in-inventory-elimination-intercompany-accounting.html
+- https://www.accountingtools.com/articles/what-are-intercompany-eliminations.html
+- https://www.becker.com/accounting-terms/intercompany-profit-fixed-assets
+- https://fiveable.me/financial-accounting-ii/unit-14/intercompany-inventory-fixed-asset-transactions/study-guide/nMKk058IpxWCfvqY
+- https://www.houseblend.io/articles/asc-810-intercompany-elimination-rules
+- https://softledger.com/blog/intercompany-eliminations-noncontrolling-interest-guide
+- Governing standards: FASB ASC 810-10-45-1; IFRS 10 para B86. Textbook frameworks: Hoyle/Schaefer/Doupnik *Advanced Accounting* Ch. 4–6; Beams *Advanced Accounting* Ch. 5–6.
diff --git a/.ai/specs/2026-08-17-intercompany-elimination-engine.md b/.ai/specs/2026-08-17-intercompany-elimination-engine.md
new file mode 100644
index 0000000000..73cec21d5f
--- /dev/null
+++ b/.ai/specs/2026-08-17-intercompany-elimination-engine.md
@@ -0,0 +1,383 @@
+# Intercompany Elimination Engine — Structured Capture (not GL reconstruction)
+
+> Status: implemented — applied to the live dev DB, RPC verified to run; pending a
+> data-driven edge-function/browser retest with a real intercompany scenario
+> Author: Claude (with Brad)
+> Date: 2026-08-17
+> Research: `.ai/research/intercompany-eliminations.md`
+> Plan: `.ai/plans/2026-08-17-intercompany-elimination-engine.md`
+> Supersedes: `2026-08-17-intercompany-elimination-scope.md` (deleted — described the
+> heuristic reconstruction approach this replaces)
+> Sibling (matching maturity / tolerance / FX / netting / NCI-deferral):
+> `2026-07-04-intercompany-maturity.md` (separate, unshipped; owns matching brittleness)
+
+> **This is the single, canonical spec for this branch's intercompany elimination
+> work.** The branch's earlier commits (consolidated-reporting fixes, elimination-
+> entity sequence seeding, intercompany-partner repair, the consolidated account
+> drill-down) are the supporting fixes that made this engine observable and
+> postable; they are retained as sound and summarised in the changelog.
+
+## As-built (delta from the proposal above)
+
+- **One migration, edited in place — no new migrations.** The whole engine (the
+ `eliminationKind` enum + `journal.eliminationKind` column + `intercompanyTransaction.amount`
+ widen, the `intercompanyEliminationRole` enum, the `intercompanyEliminationLine`
+ table + RLS, and the capture-driven `generateEliminationEntries`) lives in
+ `20260817122328_intercompany-revenue-cogs-elimination.sql`. The heuristic v2
+ `20260817150538_...from-shipment.sql` is deleted. (Branch SQL is unmerged and the
+ DB is reset for retests, so editing in place is correct — not fix-forward.)
+- **Balanced partial realization.** Revenue and COGS reversal are scaled by the
+ same buyer-on-hand weighted fraction as the writedown, so the IC Revenue journal
+ balances at any realization level. Fixed-asset buyers and fully-held inventory
+ give fraction 1 → exact full elimination (the retest case). Partially-resold
+ inventory is the item-level approximation the spec already scopes.
+- **Manual path captures too.** `createIntercompanyTransaction` writes a `Control`
+ capture line so a matched manual pair eliminates like an invoice-posted one.
+- **Regenerate is a button.** `generateEliminationEntries` takes `p_regenerate`;
+ the workbench exposes "Regenerate" alongside "Generate Eliminations".
+- **Verification:** erp typecheck 0 errors; 123 accounting unit tests pass (3
+ pre-existing period-close mock failures are unrelated). DB apply, types regen,
+ edge-function runtime, and the browser retest wait on Brad (no DB rebuild here).
+
+## TLDR
+
+`generateEliminationEntries` today reverse-engineers each intragroup trade from the
+GL at consolidation time — it sweeps journal lines by **account class** and walks
+the **document graph** (invoice → sales order → shipment) to guess what was
+revenue, what was COGS, and which account holds the unrealized margin. That
+reconstruction is fragile by construction: every new transaction shape breaks a
+heuristic (COGS at shipment, COGS split across absorption/variance accounts,
+**buyer capitalizing a fixed asset instead of inventory** → the margin written
+down against the wrong account → negative Finished Goods). This spec replaces the
+reconstruction with **structured capture**: when each side of an intercompany
+trade posts — where the edge function *knows exactly* what every line is — it
+records role-classified references to the actual journal lines plus the traded
+item, quantity, and the account the buyer capitalized to. The elimination then
+reverses precisely those captured lines and writes down precisely the account the
+buyer holds, with no account-class guessing and no document-graph walking. The
+**balance elimination** (IC Receivable/Payable) is already data-driven and is
+kept. This is the "transaction-time intercompany capture" the research names as
+the enterprise systems' core advantage over the QuickBooks/Xero tier.
+
+## Problem Statement
+
+`generateEliminationEntries` (`20260817122328`, `20260817150538`) does three things
+per matched company pair:
+
+1. **Balance elimination** — reverse the reciprocal IC Receivable/Payable control
+ lines. This is **sound**: it references the matched pair's actual
+ `sourceJournalLineId` and reverses the real posted amounts. **Keep it.**
+2. **Revenue/COGS elimination** — reverse the intragroup sale's P&L. Currently:
+ find Revenue-class lines on the invoice document, Expense-class lines on the
+ invoice *and* the shipment(s) linked via the sales order, sum them, reverse.
+3. **Unrealized-profit writedown** — write the buyer's inventory down to group
+ cost. Currently: pick the **seller's** inventory-relief line (`class='Asset'`,
+ `amount<0`) and credit it by the margin.
+
+Parts 2 and 3 are **GL reconstruction**, and it fails predictably:
+
+- **SO-based sales** post COGS at *shipment*, not the invoice → needed a
+ document-graph patch (`20260817150538`).
+- **COGS splits** across `Cost of Goods Sold – Direct` + `Labor & Machine
+ Absorption` variance → needed "sum all Expense-class lines" patch.
+- **Buyer capitalizes a fixed asset** (verified in the retest: seller sold
+ manufactured inventory for 100 at group cost 30.28; buyer posted `Dr Machinery
+ & Equipment 100`). The writedown credited the **seller's Finished Goods** (which
+ the seller's own postings net to zero) → consolidated **Finished Goods = −69.72
+ (negative)**, and the buyer's Machinery stayed overstated at 100 instead of
+ 30.28.
+
+Each fix is a heuristic on the previous heuristic. Because the elimination
+reconstructs the trade from its GL *output*, it cannot be made robust — the space
+of transaction shapes is open-ended (direct vs SO, inventory vs fixed-asset buyer,
+multi-line, multi-account, partial invoicing, drop-ship, services). The research
+(`.ai/research/intercompany-eliminations.md` §3, §5) is explicit: enterprise
+systems **capture intercompany economics when the transaction posts** (trading
+partner + role-classified accounts), and reconstructing at close is exactly what
+QuickBooks/Xero-tier tools do and pay add-ons to fix.
+
+## Proposed Solution
+
+Capture the trade's economics as **structured, role-classified data** at posting
+time, and make elimination a pure read over those records.
+
+### 1. Capture table — `intercompanyEliminationLine`
+
+A child of `intercompanyTransaction` recording, per side of the trade, the
+role-classified journal lines the elimination will act on. Written by the posting
+edge functions (which know each line's role exactly), never inferred later.
+
+```sql
+CREATE TYPE "intercompanyEliminationRole" AS ENUM (
+ 'Control', -- IC Receivable / IC Payable (the balance elimination)
+ 'Revenue', -- seller intragroup revenue
+ 'COGS', -- seller cost of the goods (Direct + absorption/variance)
+ 'Capitalization' -- buyer's asset the profit is embedded in (inventory OR fixed asset)
+);
+
+CREATE TABLE "intercompanyEliminationLine" (
+ "id" TEXT NOT NULL DEFAULT id('icel'),
+ "companyId" TEXT NOT NULL, -- the company that posted the line
+ "intercompanyTransactionId" TEXT NOT NULL,
+ "role" "intercompanyEliminationRole" NOT NULL,
+ "journalLineId" TEXT NOT NULL, -- the ACTUAL posted line (source of truth)
+ "accountId" TEXT NOT NULL, -- captured for fast elimination reads
+ "amount" NUMERIC NOT NULL, -- the posted (natural-balance-signed) amount
+ "itemId" TEXT, -- Capitalization/COGS rows: the traded item
+ "quantity" NUMERIC, -- traded quantity (for on-hand realization)
+
+ "createdBy" TEXT NOT NULL REFERENCES "user"("id"),
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "updatedBy" TEXT REFERENCES "user"("id"),
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+
+ CONSTRAINT "intercompanyEliminationLine_pkey" PRIMARY KEY ("id", "companyId"),
+ CONSTRAINT "intercompanyEliminationLine_companyId_fkey"
+ FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT "intercompanyEliminationLine_ictId_fkey"
+ FOREIGN KEY ("intercompanyTransactionId") REFERENCES "intercompanyTransaction"("id") ON DELETE CASCADE
+);
+
+CREATE INDEX "intercompanyEliminationLine_companyId_idx" ON "intercompanyEliminationLine"("companyId");
+CREATE INDEX "intercompanyEliminationLine_ictId_idx" ON "intercompanyEliminationLine"("intercompanyTransactionId");
+CREATE INDEX "intercompanyEliminationLine_createdBy_idx" ON "intercompanyEliminationLine"("createdBy");
+-- RLS: gated read for group employees; writes by accounting_create/update/delete
+-- (standard four policies; SELECT via get_companies_with_employee_role()).
+```
+
+Why line-level (not columns/arrays on `intercompanyTransaction`): a document can
+trade several items, the buyer can capitalize different items to different
+accounts (inventory vs fixed asset), and on-hand realization is **per item**.
+Roles + a real `journalLineId` per row make the elimination exact and auditable —
+each elimination line traces to the operating line it reverses.
+
+### 2. Capture points (posting edge functions)
+
+`intercompanyTransaction` rows already exist; the edge functions additionally
+write `intercompanyEliminationLine` rows when `isIntercompany`:
+
+- **`post-sales-invoice`** (seller): one `Control` row (the IC Receivable line —
+ already the `sourceJournalLineId`) + one `Revenue` row per revenue line. For the
+ seller's **COGS**, capture from the linked shipment(s): if COGS posted on the
+ invoice (direct sale) capture those lines; otherwise resolve the shipment(s) via
+ `salesInvoiceLine.salesOrderId → shipment.sourceDocumentId` and capture their
+ COGS/absorption lines as `COGS` rows. This is the *same* lookup the current RPC
+ does — but performed **once, at posting**, and stored, instead of on every
+ elimination run.
+- **`post-shipment`** (seller, SO-based): when it posts COGS for an intercompany
+ sales order, it may capture the `COGS` rows directly (the IC transaction is
+ created later at invoice; the invoice-time capture links them). Design decision
+ below (OQ-2) picks invoice-time lookup vs shipment-time write.
+- **`post-purchase-invoice`** / **`post-receipt`** (buyer): one `Control` row (IC
+ Payable) + one `Capitalization` row per received item, capturing the account the
+ buyer **actually debited** (inventory, WIP, or a **fixed-asset** account) with
+ `itemId` + `quantity`. The capitalization is on the receipt (`Dr inventory/asset`);
+ resolve it via `purchaseInvoiceLine → PO → receipt` (mirror of the seller lookup).
+
+Role classification is exact here because the edge function is the code that
+*chose* each account.
+
+### 3. Elimination = pure read over captured lines
+
+`generateEliminationEntries` reads `intercompanyEliminationLine` for the matched
+pair and posts, on the LCA elimination entity:
+
+- **`IC Balance`** journal — reverse every `Control` line (`-amount`, same
+ account). *(Unchanged behavior; already sound.)*
+- **`IC Revenue`** journal — reverse every `Revenue` and `COGS` line (`-amount`,
+ same account). Margin `M = Σ Revenue − Σ COGS` (in absolute terms).
+- **Unrealized-profit writedown** (same `IC Revenue` journal) — for each buyer
+ `Capitalization` row, credit **that row's account** (inventory OR fixed asset)
+ by `M_item × onHandFraction(itemId, buyerCompany)`. Writing down the *buyer's
+ captured account* is what fixes the negative-Finished-Goods bug: the profit is
+ removed from wherever the buyer actually holds it.
+
+`onHandFraction` = `LEAST(buyer on-hand of item, traded quantity) / traded
+quantity` from the buyer's `itemLedger` (item-level approximation, per the prior
+resolution). For a fixed-asset capitalization there is no `itemLedger` on-hand;
+the asset is "held" until disposed, so fraction = 1 until the fixed asset leaves
+the group (realization via depreciation is a later phase — see Non-Goals).
+
+No account-class guessing, no document-graph walking at elimination time.
+
+### 4. Reverse-and-regenerate (re-runnability)
+
+Because the balance and revenue eliminations are period-scoped and the capture
+lines are the source of truth, re-running elimination must be idempotent:
+**reverse the prior period's elimination journals (post reversing entries, per the
+immutability rule — never delete posted lines) and regenerate** from the current
+capture + on-hand. Resets an `Eliminated` pair to re-eliminable. This is what lets
+a correction (or a fixed heuristic) re-flow without manual DB surgery — the gap the
+retest hit.
+
+### Design Decisions
+
+| # | Decision | Choice | Rationale |
+|---|----------|--------|-----------|
+| 1 | Architecture | Structured capture at posting time; elimination is a pure read | Reconstruction from GL output is open-endedly fragile (retest bugs); research §3/§5 consensus |
+| 2 | Keep balance elimination | Yes, unchanged | Already reverses actual control lines via matched pair; sound |
+| 3 | Capture grain | Line-level child table `intercompanyEliminationLine` (role-tagged) | Multi-item, per-item on-hand, buyer accounts differ; arrays on the txn can't express it |
+| 4 | Role classification | At posting time (the edge function that chose the account) | Exact, not inferred; kills account-class heuristics |
+| 5 | Writedown target | The **buyer's** `Capitalization` account (whatever it is) | Fixes negative Finished Goods; correct economically (asset at group cost) |
+| 6 | Fixed-asset **buyer** | In scope — write down the fixed-asset account like any capitalization | Falls out of the capture model; the retest case; economically correct |
+| 7 | Fixed-asset **seller disposal** (gain + depreciation catch-up) | Still deferred (manual) | Multi-year deferred-gain sub-ledger; unchanged from prior scope |
+| 8 | On-hand realization | Item-level fraction from buyer `itemLedger`; fixed assets fraction = 1 until disposed | Prior resolution; SAP IPI style; lot-level FIFO deferred |
+| 9 | Re-runnability | Reverse-and-regenerate (reversing journals, not deletes) | Immutability rule; lets corrections re-flow; the retest gap |
+| 10 | Matching brittleness (shipping/FX/rounding) | **Out of scope here** — owned by `2026-07-04-intercompany-maturity.md` (tolerance + document-currency matching) | Separable concern; this spec assumes a matched pair exists |
+| 11 | Multi-tenancy | `intercompanyEliminationLine` = `id('icel')` + `companyId` + composite PK + four RLS policies | conventions-database.md |
+| 12 | Control-account resolution | By id / captured `journalLineId` — never account number/name | `.ai/lessons.md` |
+
+## Data Model Changes
+
+- New enum `intercompanyEliminationRole` and table `intercompanyEliminationLine`
+ (above).
+- No change to `intercompanyTransaction` structure beyond the child FK; `amount`
+ stays the match key (owned by the maturity spec).
+- `journal.eliminationKind` (`20260817122328`) is kept as the classifier
+ (`'IC Balance' | 'IC Revenue'`).
+
+## API / Service Changes
+
+- **Edge functions** (`post-sales-invoice`, `post-shipment`,
+ `post-purchase-invoice`, `post-receipt`): on the intercompany path, insert
+ `intercompanyEliminationLine` rows for the roles each posts. These already
+ compute the accounts/amounts (revenue, COGS, inventory, IC control) — the change
+ is persisting the role-tagged line refs, not new arithmetic.
+- **`generateEliminationEntries`** (migration, `CREATE OR REPLACE`): rewritten to
+ read `intercompanyEliminationLine` and post the reversals + writedown; add
+ reverse-and-regenerate. Drops the account-class sweeps and the invoice→SO→shipment
+ traversal from the elimination path.
+- **`accounting.ee.service.ts`**: read helpers for the capture lines (for the
+ workbench / audit), plus the reverse-and-regenerate wrapper.
+
+## UI Changes
+
+- The intercompany workbench shows, per matched pair, the captured elimination
+ lines by role (Control / Revenue / COGS / Capitalization) and the resulting
+ elimination journal(s) — so a reviewer can trace a consolidated 0 to the exact
+ operating lines that produced it. Complements the consolidated account
+ drill-down (already shows elimination entries via the service-role read).
+- No operating-company UI change.
+
+## Acceptance Criteria
+
+- [ ] The retest scenario (seller manufactures inventory, sells for 100 at group
+ cost 30.28; **buyer capitalizes `Machinery & Equipment` 100**) after Match +
+ Generate Eliminations: consolidated **Machinery & Equipment = 30.28** (group
+ cost), **Finished Goods = 0** (no negative), **Sales/COGS = 0**, IC
+ Receivable/Payable = 0, and consolidated net income excludes the intragroup
+ profit (only real production variances remain).
+- [ ] An inventory-to-inventory intragroup sale (buyer holds it as inventory) nets
+ to 0 across every consolidated account.
+- [ ] Selling the buyer's on-hand externally next period and re-running reduces the
+ deferred writedown proportionally (realization).
+- [ ] SO-based, direct-invoice, and multi-account-COGS sales all eliminate
+ correctly **without** any account-class sweep or document-graph walk in the
+ elimination RPC (the capture carries it).
+- [ ] Re-running `generateEliminations` after a correction reverses the prior
+ elimination journals (via reversing entries) and regenerates — idempotent, no
+ posted-line deletes, no manual DB surgery.
+- [ ] Every elimination journal line traces to a captured `intercompanyEliminationLine`
+ (auditable), and each carries a non-null `eliminationKind`.
+- [ ] Scoped `erp` typecheck + accounting tests green; edge-function change verified
+ by an intercompany posting exercising each capture path.
+
+## Risks
+
+| Risk | Severity | Mitigation |
+|------|----------|------------|
+| Edge-function change to production posting paths | High | Capture is additive (insert rows), never alters the existing GL postings; behind `isIntercompany`; per-function verified |
+| No backfill: pairs posted before capture existed have no lines | Low (accepted) | **Decided: no backfill** — the engine is capture-only from day one. Trades posted before this ship don't gain new-engine eliminations; already-generated heuristic journals stay as posted history. Acceptable because the retest group is reset before verification, so all its trades post through the capture path |
+| Buyer capitalization not resolvable (drop-ship, service, no receipt) | Med | Capture what exists; if no `Capitalization` row, skip the writedown (balance + P&L still eliminate); log the gap, don't guess |
+| Fixed-asset writedown vs the deferred seller-disposal case | Low | Buyer-capitalizes is a *purchase* capitalization (in scope); seller *disposing* a fixed asset stays deferred — distinct paths |
+| Reverse-and-regenerate double-posting | Med | Reversing journals keyed to the prior elimination journal id; regenerate only after reversal committed; period lock respected |
+
+## Resolved Decisions (was Open Questions)
+
+Resolved with Brad 2026-08-17.
+
+- [x] **OQ-1 — Capture grain.** ✅ **Line-level child table
+ `intercompanyEliminationLine`** (Decision 3) — only it expresses per-item buyer
+ accounts + on-hand. The whole engine reads from this shape.
+- [x] **OQ-2 — COGS capture point for SO-based sales.** ✅ **Invoice-time lookup** —
+ the IC transaction is created at the invoice, so capture is single-sited and
+ there's no "orphan shipment rows" lifecycle.
+- [x] **OQ-3 — Fixed-asset *buyer* capitalization in scope?** ✅ **Yes**
+ (Decisions 5/6) — the retest bug; write the buyer's asset to group cost. The
+ still-deferred case is the *seller* disposing a fixed asset (gain + multi-year
+ depreciation catch-up).
+- [x] **OQ-4 — Backfill existing eliminated pairs.** ❌ **No backfill** — the engine
+ is capture-only from day one. Trades posted before this ships don't gain
+ new-engine eliminations; already-generated heuristic journals stay as posted
+ history. The retest group is reset before verification, so its trades all post
+ through the capture path.
+- [x] **OQ-5 — Retire the heuristic RPC or keep as fallback?** ✅ **Retire it** — a
+ guessing fallback is the thing we're removing; if capture is missing for a pair,
+ skip that layer explicitly and surface it, don't silently reconstruct. No two
+ code paths that can disagree.
+
+## Changelog
+
+- 2026-08-17: Created. Replaces the heuristic reconstruction approach
+ (`2026-08-17-intercompany-elimination-scope.md`, deleted) after the retest
+ exposed its open-ended fragility (buyer-capitalizes-fixed-asset → negative
+ Finished Goods). Design: structured role-tagged capture at posting time
+ (`intercompanyEliminationLine`), elimination as a pure read, reverse-and-
+ regenerate. Balance elimination + `eliminationKind` + the reporting/RLS/drill-down
+ fixes are retained (sound). Matching brittleness stays with the maturity spec.
+- 2026-08-17: Open questions resolved with Brad (OQ-1 child table, OQ-2 invoice-time
+ capture, OQ-3 fixed-asset buyer in scope, OQ-4 **no backfill**, OQ-5 retire the
+ heuristic RPC).
+- 2026-08-17: Implemented. Consolidated the engine into a single edited-in-place
+ migration (`20260817122328`; `20260817150538` deleted). Capture added to
+ `post-sales-invoice` (Control/Revenue/direct-COGS + SO-based COGS via the
+ shipment lookup), `post-purchase-invoice` (Control + Capitalization from inline
+ asset debits and linked receipts), and `createIntercompanyTransaction` (Control).
+ `generateEliminationEntries` rewritten capture-driven with a balanced weighted
+ on-hand fraction and `p_regenerate`; service `generateEliminations(regenerate)`
+ + read helper `getIntercompanyEliminationLines`; workbench "Regenerate" button.
+ Verified: erp typecheck 0 errors, 123 accounting tests pass. Pending Brad: DB
+ apply + types regen + edge-function/browser retest. Deferred nicety: per-pair
+ captured-line detail in the workbench UI (read helper is in place for it).
+
+- 2026-08-17: Audit fix — **elimination date window.** The consolidated balance
+ sheet showed Inter-Company Payables/Receivables = 100 (un-eliminated) while the
+ drill-down netted to 0. Cause: `generateEliminationEntries` dated the elimination
+ journal with `company_today(elimination_entity)`, but the synthetic elimination
+ entity has no location so `company_today` falls back to UTC and sat a day ahead
+ (Aug 18) of the operating companies (Aug 17) at an evening-Pacific boundary — so
+ the adjustment landed outside the balance sheet's "as of today" window. Fixed:
+ date each elimination to the MAX posting date of the transactions it eliminates
+ (and reversals to their original journal's date). Also caught + fixed the
+ overload trap (added-`DEFAULT` sibling; `DROP FUNCTION IF EXISTS ...(TEXT,TEXT)`).
+
+- 2026-08-17: **Deterministic test harness** added at
+ `packages/database/supabase/tests/intercompany-elimination.test.sql` — seeds
+ intercompany trades at the journal+capture level, runs `generateEliminationEntries`,
+ and ASSERTS the consolidated result in a rolled-back transaction (no UI data entry).
+ Run: `psql "$SUPABASE_DB_URL" -v ON_ERROR_STOP=1 -f packages/database/supabase/tests/intercompany-elimination.test.sql`.
+ It found — and now guards — a real bug: the elimination aggregated margin at the
+ **company-pair** level and split the writedown proportionally by capitalized
+ value, mis-allocating across capitalization accounts when a pair had multiple
+ trades with different margins (net income stayed correct; per-account asset
+ allocation drifted). Fixed by allocating **per trade** — each seller transaction
+ is linked to its matched buyer transaction via `targetJournalLineId` (set by
+ matching), so each buyer capitalization is written down by ITS OWN trade's margin.
+ Covered scenarios: fixed-asset buyer, inventory fully held, partial realization,
+ transaction-dated posting, regenerate idempotency, and multi-trade-per-pair.
+
+## This branch's supporting fixes (retained, not superseded)
+
+These shipped earlier on the branch and remain correct; they are the substrate the
+engine posts onto and is observed through:
+
+- **Consolidated reporting** — `translatedNetChange` / Net Income injection so the
+ consolidated income statement and balance sheet tie out across companies.
+- **Elimination-entity sequences** — `seed-company` + a backfill so the synthetic
+ elimination entities have `journalEntry` sequences (the original "Sequence not
+ found" failure).
+- **Intercompany-partner repair** — sibling companies resolve each other as
+ supplier/customer for matching.
+- **Consolidated account drill-down** — `getConsolidatedAccountLedger` reads the
+ elimination entities via service role (scoped to the group) so elimination
+ journal lines appear when drilling `?companies=all`.
diff --git a/apps/erp/app/modules/accounting/AGENTS.md b/apps/erp/app/modules/accounting/AGENTS.md
index 6aeff2d95e..cd2aa59e84 100644
--- a/apps/erp/app/modules/accounting/AGENTS.md
+++ b/apps/erp/app/modules/accounting/AGENTS.md
@@ -16,7 +16,7 @@ The **Executive P&L** (`executive-pnl.tsx`) shares the income statement's loader
- **Dimensions** — analytical tags on journal lines (Location, Department, Project, etc.). Entity-type dimensions resolve values from their source table; Custom dimensions use `dimensionValue`.
- **Cost Centers** — hierarchical organizational units for cost allocation via `parentCostCenterId`.
- **Fixed Assets** — capital assets with depreciation. Supports straight-line, declining balance, MACRS, and units-of-production methods. Depreciation runs generate journal entries. See `.claude/rules/fixed-asset-lifecycle.md`.
-- **Intercompany** — transactions between companies in a group. `runIntercompanyMatching` pairs them; `generateEliminations` creates reversing entries for consolidation.
+- **Intercompany** — transactions between companies in a group. `runIntercompanyMatching` pairs them; `generateEliminations` creates reversing entries on the lowest-common-parent elimination entity, classified by `journal.eliminationKind`: `'IC Balance'` (reverse IC Receivable/Payable) and `'IC Revenue'` (reverse an intragroup sale's revenue + COGS and write the buyer's capitalized asset down to group cost — removes intragroup profit from consolidated income). The engine is **capture-driven, not GL reconstruction**: the posting edge functions (`post-sales-invoice`, `post-purchase-invoice`) record role-tagged references (`intercompanyEliminationLine`: `Control`/`Revenue`/`COGS`/`Capitalization`) when each side posts, and `generateEliminationEntries` reads them — so it writes down whatever account the BUYER capitalized (inventory OR a **fixed asset** — the latter is now in scope, was the negative-Finished-Goods bug). The writedown scales by the buyer's on-hand fraction (fixed assets: full until disposed); revenue/COGS reversal scale by the same fraction so the entry balances. `p_regenerate` reverses existing eliminations (reversing entries, never deletes) and re-derives — the workbench "Regenerate" button. Investment/NCI and seller fixed-asset disposal (deferred gain) remain out of scope. See `.ai/specs/2026-08-17-intercompany-elimination-engine.md`.
- **Net Income** — computed equity line on the balance sheet, never a posted account. Uses synthetic `NET_INCOME_ACCOUNT_ID` constant.
## Safety
diff --git a/apps/erp/app/modules/accounting/accounting.ee.server.ts b/apps/erp/app/modules/accounting/accounting.ee.server.ts
index 96eb36b29a..80b0f3bf34 100644
--- a/apps/erp/app/modules/accounting/accounting.ee.server.ts
+++ b/apps/erp/app/modules/accounting/accounting.ee.server.ts
@@ -1,8 +1,104 @@
+import { getCarbonServiceRole } from "@carbon/auth/client.server";
+import type { Database } from "@carbon/database";
import type { Kysely, KyselyDatabase } from "@carbon/database/client";
import { getNextSequence } from "@carbon/database/sequence";
+import type { ReportPeriodBucket } from "@carbon/utils";
import { toStoredAmount } from "@carbon/utils";
+import type { SupabaseClient } from "@supabase/supabase-js";
+import {
+ getAccountLedger,
+ getAccountLedgerSummary,
+ getConsolidatedBalances,
+ getConsolidatedPeriodSeries
+} from "./accounting.ee.service";
import { acquisitionLines } from "./accounting.utils";
+// Report loaders consolidate a group the user is authorized for, but the
+// synthetic elimination entities are read via service role (no user is a member
+// of them — see the consolidation service). These thin wrappers own that
+// privileged-client decision in ONE server-only place so the loaders never
+// thread a `getCarbonServiceRole()` argument through their call sites. The RLS
+// `client` still reads every operating company; only elimination entities are
+// read privileged.
+export function getConsolidatedPeriodSeriesForReport(
+ client: SupabaseClient<Database>,
+ companyGroupId: string,
+ companyIds: string[],
+ targetCurrency: string,
+ args: { buckets: ReportPeriodBucket[]; includeCurrentYearEarnings?: boolean }
+) {
+ return getConsolidatedPeriodSeries(
+ client,
+ companyGroupId,
+ companyIds,
+ targetCurrency,
+ args,
+ getCarbonServiceRole()
+ );
+}
+
+export function getConsolidatedBalancesForReport(
+ client: SupabaseClient<Database>,
+ companyGroupId: string,
+ companyIds: string[],
+ targetCurrency: string,
+ periodEnd: string,
+ periodStart?: string
+) {
+ return getConsolidatedBalances(
+ client,
+ companyGroupId,
+ companyIds,
+ targetCurrency,
+ periodEnd,
+ periodStart,
+ getCarbonServiceRole()
+ );
+}
+
+// Consolidated account drill-down ("All Companies"). Reads via service role so
+// the synthetic elimination entities' journal lines (invisible to the user's
+// RLS session — no user is a member of them) appear in the ledger and the
+// summary ties to the consolidated report. Scoped to the group's own companies
+// so a service-role read cannot cross tenants.
+export async function getConsolidatedAccountLedger(
+ companyGroupId: string,
+ args: {
+ accountId: string;
+ startDate: string | null;
+ endDate: string | null;
+ limit: number;
+ offset: number;
+ }
+) {
+ const serviceRole = getCarbonServiceRole();
+ const { data: groupCompanies } = await serviceRole
+ .from("company")
+ .select("id")
+ .eq("companyGroupId", companyGroupId)
+ .eq("active", true);
+ const companyIds = (groupCompanies ?? []).map((c) => c.id);
+
+ const [ledger, summary] = await Promise.all([
+ getAccountLedger(serviceRole, {
+ accountId: args.accountId,
+ companyId: null,
+ companyIds,
+ startDate: args.startDate,
+ endDate: args.endDate,
+ limit: args.limit,
+ offset: args.offset
+ }),
+ getAccountLedgerSummary(serviceRole, companyGroupId, null, {
+ accountId: args.accountId,
+ startDate: args.startDate,
+ endDate: args.endDate
+ })
+ ]);
+
+ return { ledger, summary };
+}
+
export async function postDisposal(
db: Kysely<KyselyDatabase>,
args: {
diff --git a/apps/erp/app/modules/accounting/accounting.ee.service.ts b/apps/erp/app/modules/accounting/accounting.ee.service.ts
index b7e135a144..108c337db1 100644
--- a/apps/erp/app/modules/accounting/accounting.ee.service.ts
+++ b/apps/erp/app/modules/accounting/accounting.ee.service.ts
@@ -162,6 +162,10 @@ export async function getAccountLedger(
args: {
accountId: string;
companyId: string | null;
+ // Consolidated drill-down: restrict to an explicit set of companies (the
+ // group's operating companies + elimination entities) so a service-role read
+ // doesn't leak across tenants. Ignored when companyId is set.
+ companyIds?: string[];
startDate: string | null;
endDate: string | null;
limit: number;
@@ -185,6 +189,8 @@ export async function getAccountLedger(
if (args.companyId) {
query = query.eq("companyId", args.companyId);
+ } else if (args.companyIds && args.companyIds.length > 0) {
+ query = query.in("companyId", args.companyIds);
}
const result = await query
@@ -435,6 +441,97 @@ function applyRootSignCorrectionToSeries<
});
}
+// Roll translated leaf values up onto INTERMEDIATE group rows (subtotals).
+// Per-company translation (translateCompanyBalances) stamps translated values on
+// LEAVES only — it deliberately skips group accounts so the CTA total isn't
+// double-counted — and applyRootSignCorrectionToSeries only recomputes ROOT rows.
+// Without this pass every subtotal (Revenue, Receivables, …) renders "-" in any
+// translated view (all consolidated reports, plus single-company foreign
+// currency), since it carries no translatedBalance/translatedNetChange. Raw
+// netChange/balanceAtDate already roll up in the SQL RPC; this is the translated
+// counterpart. Intermediate groups sum their children WITHOUT a sign flip — a
+// group's children share a class (hence a normal balance), so no correction
+// applies until the class boundary at the root, which the root-sign pass owns.
+function rollUpTranslatedGroups<
+ T extends {
+ id: string;
+ parentId: string | null;
+ isSystem?: boolean | null;
+ periods: Record<string, PeriodCell>;
+ }
+>(accounts: T[], bucketKeys: string[]): T[] {
+ const childrenByParent = new Map<string, T[]>();
+ for (const account of accounts) {
+ if (account.parentId) {
+ const list = childrenByParent.get(account.parentId) ?? [];
+ list.push(account);
+ childrenByParent.set(account.parentId, list);
+ }
+ }
+
+ // Post-order sum of translated leaf values, memoized (each node visited once).
+ const memo = new Map<
+ string,
+ Record<string, { tb: number; tnc: number; has: boolean }>
+ >();
+ const compute = (
+ node: T
+ ): Record<string, { tb: number; tnc: number; has: boolean }> => {
+ const cached = memo.get(node.id);
+ if (cached) return cached;
+ const children = childrenByParent.get(node.id) ?? [];
+ const out: Record<string, { tb: number; tnc: number; has: boolean }> = {};
+ for (const key of bucketKeys) {
+ if (children.length === 0) {
+ const cell = node.periods[key];
+ out[key] = {
+ tb: cell?.translatedBalance ?? 0,
+ tnc: cell?.translatedNetChange ?? 0,
+ has:
+ typeof cell?.translatedBalance === "number" ||
+ typeof cell?.translatedNetChange === "number"
+ };
+ } else {
+ let tb = 0;
+ let tnc = 0;
+ let has = false;
+ for (const child of children) {
+ const childCell = compute(child)[key]!;
+ if (childCell.has) {
+ has = true;
+ tb += childCell.tb;
+ tnc += childCell.tnc;
+ }
+ }
+ out[key] = { tb, tnc, has };
+ }
+ }
+ memo.set(node.id, out);
+ return out;
+ };
+
+ return accounts.map((account) => {
+ const isRoot = account.isSystem ?? account.parentId === null;
+ const hasChildren = (childrenByParent.get(account.id) ?? []).length > 0;
+ // Leaves already carry their own translated values; roots are recomputed
+ // (with sign) by applyRootSignCorrectionToSeries, which runs after this.
+ if (isRoot || !hasChildren) return account;
+ const rolled = compute(account);
+ const periods = { ...account.periods };
+ for (const key of bucketKeys) {
+ const cell = rolled[key]!;
+ if (!cell.has) continue;
+ const existing = periods[key] ?? { netChange: 0, balanceAtDate: 0 };
+ periods[key] = {
+ ...existing,
+ translatedBalance: cell.tb,
+ translatedNetChange: cell.tnc
+ };
+ }
+ return { ...account, periods };
+ });
+}
+
// Overlay per-bucket translated leaf balances onto the series rows.
function overlayTranslationOnSeries<
T extends { id: string; periods: Record<string, PeriodCell> }
@@ -701,7 +798,7 @@ export async function getFinancialStatementPeriodSeries(
return {
data: applyRootSignCorrectionToSeries(
- mapped,
+ rollUpTranslatedGroups(mapped, bucketKeys),
bucketKeys
) as unknown as ChartPeriodSeries[],
ctaByBucket,
@@ -720,22 +817,52 @@ export async function getConsolidatedPeriodSeries(
companyGroupId: string,
companyIds: string[],
targetCurrency: string,
- args: { buckets: ReportPeriodBucket[] }
+ args: {
+ buckets: ReportPeriodBucket[];
+ // Balance sheet only: append a computed "Net Income" equity line (current
+ // year earnings) so consolidated assets tie to liabilities + equity.
+ includeCurrentYearEarnings?: boolean;
+ },
+ // Privileged (service-role) client used ONLY to read elimination entities.
+ // Those are synthetic consolidation companies that no user is a member of, so
+ // their ledger is invisible to the RLS-scoped `client` and their reversing
+ // entries would silently drop out of the consolidation (intercompany balances
+ // never eliminate). The route already authorized the user for this group, and
+ // reads stay scoped to `companyGroupId`. Operating companies still read via the
+ // RLS `client`. Defaults to `client` (no elimination visibility) when omitted.
+ eliminationClient: SupabaseClient<Database> = client
): Promise<{
data: ChartPeriodSeries[];
ctaByBucket: Record<string, number>;
}> {
const bucketKeys = args.buckets.map((b) => b.key);
const allIds = await resolveConsolidationCompanyIds(
- client,
+ eliminationClient,
companyGroupId,
companyIds
);
+ // Elimination-entity ids in this group — read privileged, everything else RLS.
+ // Fail loudly on a read error: an empty set here silently routes the
+ // elimination entity through the RLS client (which can't see it), dropping the
+ // reversing entries and reporting un-eliminated intercompany balances as real.
+ const { data: elimRows, error: elimError } = await eliminationClient
+ .from("company")
+ .select("id")
+ .eq("companyGroupId", companyGroupId)
+ .eq("isEliminationEntity", true);
+ if (elimError) {
+ throw new Error(
+ `Failed to resolve elimination entities for consolidation: ${elimError.message}`
+ );
+ }
+ const elimIds = new Set((elimRows ?? []).map((c) => c.id));
+
const results = await Promise.all(
allIds.map(async (id) => {
+ const readClient = elimIds.has(id) ? eliminationClient : client;
const series = await getFinancialStatementPeriodSeries(
- client,
+ readClient,
companyGroupId,
id,
{ buckets: args.buckets }
@@ -751,7 +878,7 @@ export async function getConsolidatedPeriodSeries(
error: series.error?.message ?? "Failed to load balances"
}
: await translateCompanyPeriodSeries(
- client,
+ readClient,
companyGroupId,
id,
targetCurrency,
@@ -785,17 +912,41 @@ export async function getConsolidatedPeriodSeries(
}
}
- // Sum translated leaf balances per (account, bucket) and CTA per bucket
+ // Sum translated leaf balances per (account, bucket) and CTA per bucket.
+ // translatedNetChange is summed here too: translateCompanyBalances only
+ // returns translatedBalance (derived from balanceAtDate), but the Income
+ // Statement and Executive P&L read the translated period FLOW
+ // (translatedNetChange). Compute it per company as netChange × that account's
+ // rate — the same formula overlayTranslationOnSeries uses on the single-company
+ // path — then sum across companies. Without it the consolidated Income
+ // Statement renders every cell as "-" (translatedNetChange undefined).
const translatedByAccount = new Map<
string,
- Record<string, { translatedBalance: number; exchangeRate: number }>
+ Record<
+ string,
+ {
+ translatedBalance: number;
+ translatedNetChange: number;
+ exchangeRate: number;
+ }
+ >
>();
const ctaByBucket: Record<string, number> = Object.fromEntries(
bucketKeys.map((key) => [key, 0])
);
- for (const { translation } of results) {
+ for (const { series, translation } of results) {
if (translation.error) continue;
+ // This company's raw netChange per (account, bucket) — the flow that the
+ // per-account rate below translates.
+ const netChangeByAccount = new Map<string, Record<string, number>>();
+ for (const row of series.data ?? []) {
+ const rec: Record<string, number> = {};
+ for (const key of bucketKeys) {
+ rec[key] = row.periods[key]?.netChange ?? 0;
+ }
+ netChangeByAccount.set(row.id, rec);
+ }
for (const [key, bucket] of Object.entries(translation.byBucket)) {
ctaByBucket[key] = (ctaByBucket[key] ?? 0) + bucket.cta;
for (const row of bucket.balances) {
@@ -804,16 +955,22 @@ export async function getConsolidatedPeriodSeries(
record = {};
translatedByAccount.set(row.accountId, record);
}
+ const rate = Number(row.exchangeRate);
+ const netChange = netChangeByAccount.get(row.accountId)?.[key] ?? 0;
+ const translatedNetChange = round(netChange * rate);
const existing = record[key];
record[key] = existing
? {
translatedBalance:
existing.translatedBalance + Number(row.translatedBalance),
+ translatedNetChange:
+ existing.translatedNetChange + translatedNetChange,
exchangeRate: existing.exchangeRate
}
: {
translatedBalance: Number(row.translatedBalance),
- exchangeRate: Number(row.exchangeRate)
+ translatedNetChange,
+ exchangeRate: rate
};
}
}
@@ -837,8 +994,69 @@ export async function getConsolidatedPeriodSeries(
return { ...account, periods };
});
+ // Balance sheet: inject the consolidated "Net Income" (current year earnings)
+ // as an equity leaf so the sheet balances. The leaf carries both raw and
+ // TRANSLATED period values (translated summed from the already-translated
+ // income-statement leaves). Pushed as a leaf child of Equity BEFORE
+ // rollUpTranslatedGroups, which propagates only the TRANSLATED values into the
+ // Equity subtotal and root — so the TRANSLATED consolidated balance sheet
+ // balances, and the multi-company balance sheet always renders translated
+ // (showTranslated: true). Unlike the single-company path in
+ // getFinancialStatementPeriodSeries, the RAW Equity subtotal is intentionally
+ // left unadjusted here (it would double-count against the rolled-up leaf); a
+ // consumer that needs the raw Net Income reads it from this leaf, not the
+ // subtotal.
+ if (args.includeCurrentYearEarnings) {
+ const balanceSheetRoot = consolidated.find(
+ (a) =>
+ a.incomeBalance === "Balance Sheet" &&
+ (a.isSystem ?? a.parentId === null)
+ );
+ const equityGroup = consolidated.find(
+ (a) =>
+ a.class === "Equity" && a.isGroup && a.parentId === balanceSheetRoot?.id
+ );
+ if (balanceSheetRoot && equityGroup) {
+ const netIncomePeriods: Record<string, PeriodCell> = {};
+ for (const key of bucketKeys) {
+ let netChange = 0;
+ let balanceAtDate = 0;
+ let translatedBalance = 0;
+ let translatedNetChange = 0;
+ for (const a of consolidated) {
+ if (a.incomeBalance !== "Income Statement" || a.isGroup) continue;
+ const sign = rootSignMultiplier(a.class);
+ const cell = a.periods[key];
+ netChange += sign * (cell?.netChange ?? 0);
+ balanceAtDate += sign * (cell?.balanceAtDate ?? 0);
+ translatedBalance += sign * (cell?.translatedBalance ?? 0);
+ translatedNetChange += sign * (cell?.translatedNetChange ?? 0);
+ }
+ netIncomePeriods[key] = {
+ netChange,
+ balanceAtDate,
+ translatedBalance,
+ translatedNetChange,
+ exchangeRate: 1
+ };
+ }
+ consolidated.push({
+ ...equityGroup,
+ id: NET_INCOME_ACCOUNT_ID,
+ name: "Net Income",
+ isGroup: false,
+ isSystem: false,
+ parentId: equityGroup.id,
+ periods: netIncomePeriods
+ });
+ }
+ }
+
return {
- data: applyRootSignCorrectionToSeries(consolidated, bucketKeys),
+ data: applyRootSignCorrectionToSeries(
+ rollUpTranslatedGroups(consolidated, bucketKeys),
+ bucketKeys
+ ),
ctaByBucket
};
}
@@ -4198,21 +4416,41 @@ export async function getConsolidatedBalances(
companyIds: string[],
targetCurrency: string,
periodEnd: string,
- periodStart?: string
+ periodStart?: string,
+ // Privileged (service-role) client used ONLY for elimination entities — see
+ // getConsolidatedPeriodSeries. Without it their reversing entries are hidden by
+ // RLS and intercompany balances never eliminate. Defaults to `client`.
+ eliminationClient: SupabaseClient<Database> = client
) {
// All companies whose balances we need (operating + elimination entities)
const allIds = await resolveConsolidationCompanyIds(
- client,
+ eliminationClient,
companyGroupId,
companyIds
);
+ // Fail loudly on a read error (see getConsolidatedPeriodSeries): an empty set
+ // silently routes the elimination entity through the RLS client, dropping the
+ // reversing entries and over-reporting intercompany balances.
+ const { data: elimRows, error: elimError } = await eliminationClient
+ .from("company")
+ .select("id")
+ .eq("companyGroupId", companyGroupId)
+ .eq("isEliminationEntity", true);
+ if (elimError) {
+ throw new Error(
+ `Failed to resolve elimination entities for consolidation: ${elimError.message}`
+ );
+ }
+ const elimIds = new Set((elimRows ?? []).map((c) => c.id));
+
// Get balances for all companies, then translate the already-computed
// balances to the target currency (one ledger scan per company, not two).
const results = await Promise.all(
allIds.map(async (id) => {
+ const readClient = elimIds.has(id) ? eliminationClient : client;
const balances = await getFinancialStatementBalances(
- client,
+ readClient,
companyGroupId,
id,
{
@@ -4229,7 +4467,7 @@ export async function getConsolidatedBalances(
error: balances.error?.message ?? "Failed to load balances"
}
: await translateCompanyBalances(
- client,
+ readClient,
companyGroupId,
id,
targetCurrency,
@@ -4417,7 +4655,7 @@ export async function createIntercompanyTransaction(
if (journalLines.error) return journalLines;
// Create intercompany transaction record
- return client
+ const intercompanyTransaction = await client
.from("intercompanyTransaction")
.insert({
companyGroupId: input.companyGroupId,
@@ -4431,6 +4669,36 @@ export async function createIntercompanyTransaction(
})
.select("id")
.single();
+
+ if (intercompanyTransaction.error) return intercompanyTransaction;
+
+ // Capture the control line so generateEliminationEntries reverses it by
+ // reference like an invoice-posted trade. The manual entry posts a single
+ // balanced Dr/Cr on the source company; its debit line is the control account.
+ await client.from("intercompanyEliminationLine").insert({
+ companyId: input.sourceCompanyId,
+ intercompanyTransactionId: intercompanyTransaction.data.id,
+ role: "Control",
+ journalLineId: journalLines.data[0].id,
+ accountId: input.debitAccountId,
+ amount: input.amount,
+ createdBy: input.userId
+ });
+
+ return intercompanyTransaction;
+}
+
+export async function getIntercompanyEliminationLines(
+ client: SupabaseClient<Database>,
+ transactionIds: string[]
+) {
+ if (transactionIds.length === 0) {
+ return { data: [], error: null };
+ }
+ return client
+ .from("intercompanyEliminationLine")
+ .select("*")
+ .in("intercompanyTransactionId", transactionIds);
}
export async function runIntercompanyMatching(
@@ -4445,11 +4713,13 @@ export async function runIntercompanyMatching(
export async function generateEliminations(
client: SupabaseClient<Database>,
companyGroupId: string,
- userId: string
+ userId: string,
+ regenerate = false
) {
return client.rpc("generateEliminationEntries", {
p_company_group_id: companyGroupId,
- p_user_id: userId
+ p_user_id: userId,
+ p_regenerate: regenerate
});
}
diff --git a/apps/erp/app/modules/accounting/accounting.models.ts b/apps/erp/app/modules/accounting/accounting.models.ts
index 4793f94b14..0ebf300b5d 100644
--- a/apps/erp/app/modules/accounting/accounting.models.ts
+++ b/apps/erp/app/modules/accounting/accounting.models.ts
@@ -635,6 +635,13 @@ export const intercompanyTransactionStatuses = [
"Eliminated"
] as const;
+export const intercompanyEliminationRoles = [
+ "Control",
+ "Revenue",
+ "COGS",
+ "Capitalization"
+] as const;
+
export const intercompanyTransactionValidator = z
.object({
sourceCompanyId: z
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 293196dd61..b31bc43a57 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-08-17T12:34:03.161Z",
- "totalTools": 1442,
+ "generated": "2026-08-18T03:22:37.309Z",
+ "totalTools": 1443,
"modules": 15,
"tools": [
{
@@ -370,7 +370,7 @@
"module": "accounting",
"classification": "READ",
"description": "get account ledger",
- "paramCount": 5,
+ "paramCount": 6,
"serviceParams": [
"client",
"args"
@@ -384,6 +384,12 @@
"accountId": {
"type": "string"
},
+ "companyIds": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ },
"startDate": {
"type": [
"string",
@@ -610,13 +616,16 @@
"module": "accounting",
"classification": "READ",
"description": "get consolidated period series",
- "paramCount": 3,
+ "paramCount": 6,
"serviceParams": [
"client",
"companyGroupId",
"companyIds",
"targetCurrency",
- "args"
+ "args",
+ "// Privileged (service-role) client used ONLY to read elimination entities.\n // Those are synthetic consolidation companies that no user is a member of",
+ "so\n // their ledger is invisible to the RLS-scoped `client` and their reversing\n // entries would silently drop out of the consolidation (intercompany balances\n // never eliminate). The route already authorized the user for this group",
+ "and\n // reads stay scoped to `companyGroupId`. Operating companies still read via the\n // RLS `client`. Defaults to `client` (no elimination visibility) when omitted.\n eliminationClient"
],
"injectAuth": [
"companyId"
@@ -639,17 +648,26 @@
"buckets": {
"type": "array",
"items": {}
+ },
+ "includeCurrentYearEarnings": {
+ "type": "boolean"
}
},
"required": [
"buckets"
]
- }
+ },
+ "// Privileged (service-role) client used ONLY to read elimination entities.\n // Those are synthetic consolidation companies that no user is a member of": {},
+ "so\n // their ledger is invisible to the RLS-scoped `client` and their reversing\n // entries would silently drop out of the consolidation (intercompany balances\n // never eliminate). The route already authorized the user for this group": {},
+ "and\n // reads stay scoped to `companyGroupId`. Operating companies still read via the\n // RLS `client`. Defaults to `client` (no elimination visibility) when omitted.\n eliminationClient": {}
},
"required": [
"companyIds",
"targetCurrency",
- "args"
+ "args",
+ "// Privileged (service-role) client used ONLY to read elimination entities.\n // Those are synthetic consolidation companies that no user is a member of",
+ "so\n // their ledger is invisible to the RLS-scoped `client` and their reversing\n // entries would silently drop out of the consolidation (intercompany balances\n // never eliminate). The route already authorized the user for this group",
+ "and\n // reads stay scoped to `companyGroupId`. Operating companies still read via the\n // RLS `client`. Defaults to `client` (no elimination visibility) when omitted.\n eliminationClient"
]
}
},
@@ -2942,14 +2960,15 @@
"module": "accounting",
"classification": "READ",
"description": "get consolidated balances",
- "paramCount": 4,
+ "paramCount": 5,
"serviceParams": [
"client",
"companyGroupId",
"companyIds",
"targetCurrency",
"periodEnd",
- "periodStart"
+ "periodStart",
+ "// Privileged (service-role) client used ONLY for elimination entities — see\n // getConsolidatedPeriodSeries. Without it their reversing entries are hidden by\n // RLS and intercompany balances never eliminate. Defaults to `client`.\n eliminationClient"
],
"injectAuth": [
"companyId"
@@ -2971,12 +2990,14 @@
},
"periodStart": {
"type": "string"
- }
+ },
+ "// Privileged (service-role) client used ONLY for elimination entities — see\n // getConsolidatedPeriodSeries. Without it their reversing entries are hidden by\n // RLS and intercompany balances never eliminate. Defaults to `client`.\n eliminationClient": {}
},
"required": [
"companyIds",
"targetCurrency",
- "periodEnd"
+ "periodEnd",
+ "// Privileged (service-role) client used ONLY for elimination entities — see\n // getConsolidatedPeriodSeries. Without it their reversing entries are hidden by\n // RLS and intercompany balances never eliminate. Defaults to `client`.\n eliminationClient"
]
}
},
@@ -3044,6 +3065,34 @@
]
}
},
+ {
+ "name": "accounting_getIntercompanyEliminationLines",
+ "module": "accounting",
+ "classification": "READ",
+ "description": "get intercompany elimination lines",
+ "paramCount": 1,
+ "serviceParams": [
+ "client",
+ "transactionIds"
+ ],
+ "injectAuth": [
+ "companyId"
+ ],
+ "schema": {
+ "type": "object",
+ "properties": {
+ "transactionIds": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ }
+ },
+ "required": [
+ "transactionIds"
+ ]
+ }
+ },
{
"name": "accounting_runIntercompanyMatching",
"module": "accounting",
@@ -3068,11 +3117,12 @@
"module": "accounting",
"classification": "WRITE",
"description": "generate eliminations",
- "paramCount": 0,
+ "paramCount": 1,
"serviceParams": [
"client",
"companyGroupId",
- "userId"
+ "userId",
+ "regenerate = false"
],
"injectAuth": [
"companyId",
@@ -3081,7 +3131,12 @@
],
"schema": {
"type": "object",
- "properties": {}
+ "properties": {
+ "regenerate = false": {}
+ },
+ "required": [
+ "regenerate = false"
+ ]
}
},
{
diff --git a/apps/erp/app/routes/x+/accounting+/intercompany.eliminate.tsx b/apps/erp/app/routes/x+/accounting+/intercompany.eliminate.tsx
index c66d84f1ae..8547df0afc 100644
--- a/apps/erp/app/routes/x+/accounting+/intercompany.eliminate.tsx
+++ b/apps/erp/app/routes/x+/accounting+/intercompany.eliminate.tsx
@@ -19,7 +19,18 @@ export async function action({ request }: ActionFunctionArgs) {
bypassRls: true
});
- const result = await generateEliminations(client, companyGroupId, userId);
+ // Regenerate reverses the group's existing eliminations (reversing entries,
+ // never deletes) and re-derives them from current capture + on-hand, so a
+ // correction can re-flow without manual surgery.
+ const formData = await request.formData();
+ const regenerate = formData.get("regenerate") === "true";
+
+ const result = await generateEliminations(
+ client,
+ companyGroupId,
+ userId,
+ regenerate
+ );
if (result.error) {
throw redirect(
@@ -33,6 +44,13 @@ export async function action({ request }: ActionFunctionArgs) {
throw redirect(
`${path.to.intercompany}?${getParams(request)}`,
- await flash(request, success("Elimination entries generated"))
+ await flash(
+ request,
+ success(
+ regenerate
+ ? "Elimination entries regenerated"
+ : "Elimination entries generated"
+ )
+ )
);
}
diff --git a/apps/erp/app/routes/x+/accounting+/intercompany.tsx b/apps/erp/app/routes/x+/accounting+/intercompany.tsx
index 357cb81475..a4ce7f1c08 100644
--- a/apps/erp/app/routes/x+/accounting+/intercompany.tsx
+++ b/apps/erp/app/routes/x+/accounting+/intercompany.tsx
@@ -52,6 +52,7 @@ export default function IntercompanyRoute() {
const permissions = usePermissions();
const matchFetcher = useFetcher();
const eliminateFetcher = useFetcher();
+ const regenerateFetcher = useFetcher();
return (
<VStack spacing={0} className="h-full">
@@ -79,6 +80,16 @@ export default function IntercompanyRoute() {
Generate Eliminations
</Button>
</eliminateFetcher.Form>
+ <regenerateFetcher.Form method="post" action="eliminate">
+ <input type="hidden" name="regenerate" value="true" />
+ <Button
+ variant="secondary"
+ type="submit"
+ isLoading={regenerateFetcher.state !== "idle"}
+ >
+ Regenerate
+ </Button>
+ </regenerateFetcher.Form>
<New label="IC Transaction" to={`new?${params.toString()}`} />
</div>
)
diff --git a/apps/erp/app/routes/x+/reports+/balance-sheet.$accountId.tsx b/apps/erp/app/routes/x+/reports+/balance-sheet.$accountId.tsx
index 6a64567339..7afa3be80c 100644
--- a/apps/erp/app/routes/x+/reports+/balance-sheet.$accountId.tsx
+++ b/apps/erp/app/routes/x+/reports+/balance-sheet.$accountId.tsx
@@ -8,6 +8,7 @@ import {
getAccountLedger,
getAccountLedgerSummary
} from "~/modules/accounting";
+import { getConsolidatedAccountLedger } from "~/modules/accounting/accounting.ee.server";
import { AccountLedgerDrawer } from "~/modules/accounting/ui/Reports";
import { path } from "~/utils/path";
@@ -33,25 +34,42 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
const endDate = searchParams.get("endDate") || null;
const offset = Math.max(0, Number(searchParams.get("offset")) || 0);
- const selectedCompanyId =
- companiesParam === "all" ? null : (companiesParam ?? companyId);
+ // "All Companies" drills into the consolidated ledger — including the
+ // elimination entities, which the user's RLS session can't see. Reading them
+ // via service role (scoped to this group) makes the elimination journal
+ // entries appear and the drawer summary tie to the consolidated report.
+ const isConsolidated = companiesParam === "all";
+ const selectedCompanyId = isConsolidated
+ ? null
+ : (companiesParam ?? companyId);
- const [account, ledger, summary] = await Promise.all([
+ const [account, drill] = await Promise.all([
getAccount(client, accountId),
- getAccountLedger(client, {
- accountId,
- companyId: selectedCompanyId,
- startDate,
- endDate,
- limit: LEDGER_PAGE_SIZE,
- offset
- }),
- getAccountLedgerSummary(client, companyGroupId, selectedCompanyId, {
- accountId,
- startDate,
- endDate
- })
+ isConsolidated
+ ? getConsolidatedAccountLedger(companyGroupId, {
+ accountId,
+ startDate,
+ endDate,
+ limit: LEDGER_PAGE_SIZE,
+ offset
+ })
+ : Promise.all([
+ getAccountLedger(client, {
+ accountId,
+ companyId: selectedCompanyId,
+ startDate,
+ endDate,
+ limit: LEDGER_PAGE_SIZE,
+ offset
+ }),
+ getAccountLedgerSummary(client, companyGroupId, selectedCompanyId, {
+ accountId,
+ startDate,
+ endDate
+ })
+ ]).then(([ledger, summary]) => ({ ledger, summary }))
]);
+ const { ledger, summary } = drill;
if (account.error || !account.data) {
throw redirect(
diff --git a/apps/erp/app/routes/x+/reports+/balance-sheet.tsx b/apps/erp/app/routes/x+/reports+/balance-sheet.tsx
index 8aaabcf813..9a3195659f 100644
--- a/apps/erp/app/routes/x+/reports+/balance-sheet.tsx
+++ b/apps/erp/app/routes/x+/reports+/balance-sheet.tsx
@@ -16,10 +16,10 @@ import type { ChartPeriodSeries } from "~/modules/accounting";
import {
financialReportParamsValidator,
getCompaniesInGroup,
- getConsolidatedPeriodSeries,
getFinancialStatementPeriodSeries,
getFiscalYearSettings
} from "~/modules/accounting";
+import { getConsolidatedPeriodSeriesForReport } from "~/modules/accounting/accounting.ee.server";
import {
exportPeriodReport,
getPeriodColumnLabel,
@@ -120,12 +120,12 @@ export async function loader({ request }: LoaderFunctionArgs) {
);
if (isMultiCompany && parentCurrency) {
- const consolidated = await getConsolidatedPeriodSeries(
+ const consolidated = await getConsolidatedPeriodSeriesForReport(
client,
companyGroupId,
selectedCompanyIds,
parentCurrency,
- { buckets }
+ { buckets, includeCurrentYearEarnings: true }
);
const balanceSheetAccounts = consolidated.data.filter(
diff --git a/apps/erp/app/routes/x+/reports+/executive-pnl.tsx b/apps/erp/app/routes/x+/reports+/executive-pnl.tsx
index c39a7206d1..1432e686e2 100644
--- a/apps/erp/app/routes/x+/reports+/executive-pnl.tsx
+++ b/apps/erp/app/routes/x+/reports+/executive-pnl.tsx
@@ -15,10 +15,10 @@ import { redirect, useLoaderData } from "react-router";
import {
financialReportParamsValidator,
getCompaniesInGroup,
- getConsolidatedPeriodSeries,
getFinancialStatementPeriodSeries,
getFiscalYearSettings
} from "~/modules/accounting";
+import { getConsolidatedPeriodSeriesForReport } from "~/modules/accounting/accounting.ee.server";
import type { ExecutivePnlRowKey } from "~/modules/accounting/ui/Reports";
import {
ExecutivePnlSummary,
@@ -100,7 +100,7 @@ export async function loader({ request }: LoaderFunctionArgs) {
);
if (isMultiCompany && parentCurrency) {
- const consolidated = await getConsolidatedPeriodSeries(
+ const consolidated = await getConsolidatedPeriodSeriesForReport(
client,
companyGroupId,
selectedCompanyIds,
diff --git a/apps/erp/app/routes/x+/reports+/income-statement.$accountId.tsx b/apps/erp/app/routes/x+/reports+/income-statement.$accountId.tsx
index 5488a6da6a..c8f76d3757 100644
--- a/apps/erp/app/routes/x+/reports+/income-statement.$accountId.tsx
+++ b/apps/erp/app/routes/x+/reports+/income-statement.$accountId.tsx
@@ -8,6 +8,7 @@ import {
getAccountLedger,
getAccountLedgerSummary
} from "~/modules/accounting";
+import { getConsolidatedAccountLedger } from "~/modules/accounting/accounting.ee.server";
import { AccountLedgerDrawer } from "~/modules/accounting/ui/Reports";
import { path } from "~/utils/path";
@@ -32,25 +33,42 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
const endDate = searchParams.get("endDate") || null;
const offset = Math.max(0, Number(searchParams.get("offset")) || 0);
- const selectedCompanyId =
- companiesParam === "all" ? null : (companiesParam ?? companyId);
+ // "All Companies" drills into the consolidated ledger — including the
+ // elimination entities, which the user's RLS session can't see. Reading them
+ // via service role (scoped to this group) makes the elimination journal
+ // entries appear and the drawer summary tie to the consolidated report.
+ const isConsolidated = companiesParam === "all";
+ const selectedCompanyId = isConsolidated
+ ? null
+ : (companiesParam ?? companyId);
- const [account, ledger, summary] = await Promise.all([
+ const [account, drill] = await Promise.all([
getAccount(client, accountId),
- getAccountLedger(client, {
- accountId,
- companyId: selectedCompanyId,
- startDate,
- endDate,
- limit: LEDGER_PAGE_SIZE,
- offset
- }),
- getAccountLedgerSummary(client, companyGroupId, selectedCompanyId, {
- accountId,
- startDate,
- endDate
- })
+ isConsolidated
+ ? getConsolidatedAccountLedger(companyGroupId, {
+ accountId,
+ startDate,
+ endDate,
+ limit: LEDGER_PAGE_SIZE,
+ offset
+ })
+ : Promise.all([
+ getAccountLedger(client, {
+ accountId,
+ companyId: selectedCompanyId,
+ startDate,
+ endDate,
+ limit: LEDGER_PAGE_SIZE,
+ offset
+ }),
+ getAccountLedgerSummary(client, companyGroupId, selectedCompanyId, {
+ accountId,
+ startDate,
+ endDate
+ })
+ ]).then(([ledger, summary]) => ({ ledger, summary }))
]);
+ const { ledger, summary } = drill;
if (account.error || !account.data) {
throw redirect(
diff --git a/apps/erp/app/routes/x+/reports+/income-statement.tsx b/apps/erp/app/routes/x+/reports+/income-statement.tsx
index 1280661c6e..5e7dbf637c 100644
--- a/apps/erp/app/routes/x+/reports+/income-statement.tsx
+++ b/apps/erp/app/routes/x+/reports+/income-statement.tsx
@@ -15,10 +15,10 @@ import { Outlet, redirect, useLoaderData } from "react-router";
import {
financialReportParamsValidator,
getCompaniesInGroup,
- getConsolidatedPeriodSeries,
getFinancialStatementPeriodSeries,
getFiscalYearSettings
} from "~/modules/accounting";
+import { getConsolidatedPeriodSeriesForReport } from "~/modules/accounting/accounting.ee.server";
import {
exportPeriodReport,
getPeriodColumnLabel,
@@ -99,7 +99,7 @@ export async function loader({ request }: LoaderFunctionArgs) {
);
if (isMultiCompany && parentCurrency) {
- const consolidated = await getConsolidatedPeriodSeries(
+ const consolidated = await getConsolidatedPeriodSeriesForReport(
client,
companyGroupId,
selectedCompanyIds,
diff --git a/apps/erp/app/routes/x+/reports+/trial-balance.$accountId.tsx b/apps/erp/app/routes/x+/reports+/trial-balance.$accountId.tsx
index 977c23be03..6e9f13ca2a 100644
--- a/apps/erp/app/routes/x+/reports+/trial-balance.$accountId.tsx
+++ b/apps/erp/app/routes/x+/reports+/trial-balance.$accountId.tsx
@@ -8,6 +8,7 @@ import {
getAccountLedger,
getAccountLedgerSummary
} from "~/modules/accounting";
+import { getConsolidatedAccountLedger } from "~/modules/accounting/accounting.ee.server";
import { AccountLedgerDrawer } from "~/modules/accounting/ui/Reports";
import { path } from "~/utils/path";
@@ -34,25 +35,42 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
// Mirrors the parent page: a single selected company filters lines; "all"
// matches the RPC's null company filter (every company in the group)
- const selectedCompanyId =
- companiesParam === "all" ? null : (companiesParam ?? companyId);
+ // "All Companies" drills into the consolidated ledger — including the
+ // elimination entities, which the user's RLS session can't see. Reading them
+ // via service role (scoped to this group) makes the elimination journal
+ // entries appear and the drawer summary tie to the consolidated report.
+ const isConsolidated = companiesParam === "all";
+ const selectedCompanyId = isConsolidated
+ ? null
+ : (companiesParam ?? companyId);
- const [account, ledger, summary] = await Promise.all([
+ const [account, drill] = await Promise.all([
getAccount(client, accountId),
- getAccountLedger(client, {
- accountId,
- companyId: selectedCompanyId,
- startDate,
- endDate,
- limit: LEDGER_PAGE_SIZE,
- offset
- }),
- getAccountLedgerSummary(client, companyGroupId, selectedCompanyId, {
- accountId,
- startDate,
- endDate
- })
+ isConsolidated
+ ? getConsolidatedAccountLedger(companyGroupId, {
+ accountId,
+ startDate,
+ endDate,
+ limit: LEDGER_PAGE_SIZE,
+ offset
+ })
+ : Promise.all([
+ getAccountLedger(client, {
+ accountId,
+ companyId: selectedCompanyId,
+ startDate,
+ endDate,
+ limit: LEDGER_PAGE_SIZE,
+ offset
+ }),
+ getAccountLedgerSummary(client, companyGroupId, selectedCompanyId, {
+ accountId,
+ startDate,
+ endDate
+ })
+ ]).then(([ledger, summary]) => ({ ledger, summary }))
]);
+ const { ledger, summary } = drill;
if (account.error || !account.data) {
throw redirect(
diff --git a/apps/erp/app/routes/x+/reports+/trial-balance.tsx b/apps/erp/app/routes/x+/reports+/trial-balance.tsx
index 2515502a7d..4b6364dace 100644
--- a/apps/erp/app/routes/x+/reports+/trial-balance.tsx
+++ b/apps/erp/app/routes/x+/reports+/trial-balance.tsx
@@ -11,11 +11,11 @@ import type { Chart } from "~/modules/accounting";
import {
financialReportParamsValidator,
getCompaniesInGroup,
- getConsolidatedBalances,
getFinancialStatementBalances,
getFiscalYearSettings,
translateCompanyBalances
} from "~/modules/accounting";
+import { getConsolidatedBalancesForReport } from "~/modules/accounting/accounting.ee.server";
import {
exportTrialBalance,
ReportFilters,
@@ -87,7 +87,7 @@ export async function loader({ request }: LoaderFunctionArgs) {
const endDate = endDateParam ?? range.endDate;
if (isMultiCompany && parentCurrency) {
- const consolidated = await getConsolidatedBalances(
+ const consolidated = await getConsolidatedBalancesForReport(
client,
companyGroupId,
selectedCompanyIds,
diff --git a/packages/database/src/swagger-docs-schema.ts b/packages/database/src/swagger-docs-schema.ts
index 3b9871c422..4f098a3eac 100644
--- a/packages/database/src/swagger-docs-schema.ts
+++ b/packages/database/src/swagger-docs-schema.ts
@@ -2751,6 +2751,213 @@ export default {
tags: ["assemblyInstructionStepSlide"]
}
},
+ "/intercompanyEliminationLine": {
+ get: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.intercompanyEliminationLine.id"
+ },
+ {
+ $ref: "#/parameters/rowFilter.intercompanyEliminationLine.companyId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.intercompanyEliminationLine.intercompanyTransactionId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.intercompanyEliminationLine.role"
+ },
+ {
+ $ref: "#/parameters/rowFilter.intercompanyEliminationLine.journalLineId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.intercompanyEliminationLine.accountId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.intercompanyEliminationLine.amount"
+ },
+ {
+ $ref: "#/parameters/rowFilter.intercompanyEliminationLine.itemId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.intercompanyEliminationLine.quantity"
+ },
+ {
+ $ref: "#/parameters/rowFilter.intercompanyEliminationLine.createdBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.intercompanyEliminationLine.createdAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.intercompanyEliminationLine.updatedBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.intercompanyEliminationLine.updatedAt"
+ },
+ {
+ $ref: "#/parameters/select"
+ },
+ {
+ $ref: "#/parameters/order"
+ },
+ {
+ $ref: "#/parameters/range"
+ },
+ {
+ $ref: "#/parameters/rangeUnit"
+ },
+ {
+ $ref: "#/parameters/offset"
+ },
+ {
+ $ref: "#/parameters/limit"
+ },
+ {
+ $ref: "#/parameters/preferCount"
+ }
+ ],
+ responses: {
+ "200": {
+ description: "OK",
+ schema: {
+ items: {
+ $ref: "#/definitions/intercompanyEliminationLine"
+ },
+ type: "array"
+ }
+ },
+ "206": {
+ description: "Partial Content"
+ }
+ },
+ tags: ["intercompanyEliminationLine"]
+ },
+ post: {
+ parameters: [
+ {
+ $ref: "#/parameters/body.intercompanyEliminationLine"
+ },
+ {
+ $ref: "#/parameters/select"
+ },
+ {
+ $ref: "#/parameters/preferPost"
+ }
+ ],
+ responses: {
+ "201": {
+ description: "Created"
+ }
+ },
+ tags: ["intercompanyEliminationLine"]
+ },
+ delete: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.intercompanyEliminationLine.id"
+ },
+ {
+ $ref: "#/parameters/rowFilter.intercompanyEliminationLine.companyId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.intercompanyEliminationLine.intercompanyTransactionId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.intercompanyEliminationLine.role"
+ },
+ {
+ $ref: "#/parameters/rowFilter.intercompanyEliminationLine.journalLineId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.intercompanyEliminationLine.accountId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.intercompanyEliminationLine.amount"
+ },
+ {
+ $ref: "#/parameters/rowFilter.intercompanyEliminationLine.itemId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.intercompanyEliminationLine.quantity"
+ },
+ {
+ $ref: "#/parameters/rowFilter.intercompanyEliminationLine.createdBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.intercompanyEliminationLine.createdAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.intercompanyEliminationLine.updatedBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.intercompanyEliminationLine.updatedAt"
+ },
+ {
+ $ref: "#/parameters/preferReturn"
+ }
+ ],
+ responses: {
+ "204": {
+ description: "No Content"
+ }
+ },
+ tags: ["intercompanyEliminationLine"]
+ },
+ patch: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.intercompanyEliminationLine.id"
+ },
+ {
+ $ref: "#/parameters/rowFilter.intercompanyEliminationLine.companyId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.intercompanyEliminationLine.intercompanyTransactionId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.intercompanyEliminationLine.role"
+ },
+ {
+ $ref: "#/parameters/rowFilter.intercompanyEliminationLine.journalLineId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.intercompanyEliminationLine.accountId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.intercompanyEliminationLine.amount"
+ },
+ {
+ $ref: "#/parameters/rowFilter.intercompanyEliminationLine.itemId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.intercompanyEliminationLine.quantity"
+ },
+ {
+ $ref: "#/parameters/rowFilter.intercompanyEliminationLine.createdBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.intercompanyEliminationLine.createdAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.intercompanyEliminationLine.updatedBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.intercompanyEliminationLine.updatedAt"
+ },
+ {
+ $ref: "#/parameters/body.intercompanyEliminationLine"
+ },
+ {
+ $ref: "#/parameters/preferReturn"
+ }
+ ],
+ responses: {
+ "204": {
+ description: "No Content"
+ }
+ },
+ tags: ["intercompanyEliminationLine"]
+ }
+ },
"/changeOrderType": {
get: {
parameters: [
@@ -8766,6 +8973,9 @@ export default {
{
$ref: "#/parameters/rowFilter.journal.updatedBy"
},
+ {
+ $ref: "#/parameters/rowFilter.journal.eliminationKind"
+ },
{
$ref: "#/parameters/select"
},
@@ -8879,6 +9089,9 @@ export default {
{
$ref: "#/parameters/rowFilter.journal.updatedBy"
},
+ {
+ $ref: "#/parameters/rowFilter.journal.eliminationKind"
+ },
{
$ref: "#/parameters/preferReturn"
}
@@ -8946,6 +9159,9 @@ export default {
{
$ref: "#/parameters/rowFilter.journal.updatedBy"
},
+ {
+ $ref: "#/parameters/rowFilter.journal.eliminationKind"
+ },
{
$ref: "#/parameters/body.journal"
},
@@ -95273,6 +95489,10 @@ export default {
format: "text",
type: "string"
},
+ p_regenerate: {
+ format: "boolean",
+ type: "boolean"
+ },
p_user_id: {
format: "text",
type: "string"
@@ -99716,6 +99936,86 @@ export default {
},
type: "object"
},
+ intercompanyEliminationLine: {
+ required: [
+ "id",
+ "companyId",
+ "intercompanyTransactionId",
+ "role",
+ "journalLineId",
+ "accountId",
+ "amount",
+ "createdBy",
+ "createdAt"
+ ],
+ properties: {
+ id: {
+ default: "public.id('icel'::text)",
+ description: "Note:\nThis is a Primary Key.<pk/>",
+ format: "text",
+ type: "string"
+ },
+ companyId: {
+ description:
+ "Note:\nThis is a Primary Key.<pk/>\nThis is a Foreign Key to `company.id`.<fk table='company' column='id'/>",
+ format: "text",
+ type: "string"
+ },
+ intercompanyTransactionId: {
+ description:
+ "Note:\nThis is a Foreign Key to `intercompanyTransaction.id`.<fk table='intercompanyTransaction' column='id'/>",
+ format: "text",
+ type: "string"
+ },
+ role: {
+ enum: ["Control", "Revenue", "COGS", "Capitalization"],
+ format: 'public."intercompanyEliminationRole"',
+ type: "string"
+ },
+ journalLineId: {
+ format: "text",
+ type: "string"
+ },
+ accountId: {
+ format: "text",
+ type: "string"
+ },
+ amount: {
+ format: "numeric",
+ type: "number"
+ },
+ itemId: {
+ format: "text",
+ type: "string"
+ },
+ quantity: {
+ format: "numeric",
+ type: "number"
+ },
+ createdBy: {
+ description:
+ "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",
+ format: "text",
+ type: "string"
+ },
+ createdAt: {
+ default: "now()",
+ format: "timestamp with time zone",
+ type: "string"
+ },
+ updatedBy: {
+ description:
+ "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",
+ format: "text",
+ type: "string"
+ },
+ updatedAt: {
+ format: "timestamp with time zone",
+ type: "string"
+ }
+ },
+ type: "object"
+ },
changeOrderType: {
required: ["id", "name", "companyId", "createdAt", "createdBy"],
properties: {
@@ -102599,6 +102899,13 @@ export default {
"Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",
format: "text",
type: "string"
+ },
+ eliminationKind: {
+ description:
+ "Classifies an elimination journal by the intercompany layer it removes (SAP posting-level analog); NULL for ordinary journals",
+ enum: ["IC Balance", "IC Revenue"],
+ format: 'public."eliminationKind"',
+ type: "string"
}
},
type: "object"
@@ -104338,7 +104645,7 @@ export default {
properties: {
id: {
description:
- "Note:\nThis is a Primary Key.<pk/>\nThis is a Foreign Key to `supplierLocation.id`.<fk table='supplierLocation' column='id'/>",
+ "Note:\nThis is a Foreign Key to `supplierLocation.id`.<fk table='supplierLocation' column='id'/>",
format: "text",
type: "string"
},
@@ -104387,7 +104694,7 @@ export default {
},
supplierLocationId: {
description:
- "Note:\nThis is a Foreign Key to `supplierLocation.id`.<fk table='supplierLocation' column='id'/>",
+ "Note:\nThis is a Primary Key.<pk/>\nThis is a Foreign Key to `supplierLocation.id`.<fk table='supplierLocation' column='id'/>",
format: "text",
type: "string"
},
@@ -141277,6 +141584,93 @@ export default {
in: "query",
type: "string"
},
+ "body.intercompanyEliminationLine": {
+ name: "intercompanyEliminationLine",
+ description: "intercompanyEliminationLine",
+ required: false,
+ in: "body",
+ schema: {
+ $ref: "#/definitions/intercompanyEliminationLine"
+ }
+ },
+ "rowFilter.intercompanyEliminationLine.id": {
+ name: "id",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.intercompanyEliminationLine.companyId": {
+ name: "companyId",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.intercompanyEliminationLine.intercompanyTransactionId": {
+ name: "intercompanyTransactionId",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.intercompanyEliminationLine.role": {
+ name: "role",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.intercompanyEliminationLine.journalLineId": {
+ name: "journalLineId",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.intercompanyEliminationLine.accountId": {
+ name: "accountId",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.intercompanyEliminationLine.amount": {
+ name: "amount",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.intercompanyEliminationLine.itemId": {
+ name: "itemId",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.intercompanyEliminationLine.quantity": {
+ name: "quantity",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.intercompanyEliminationLine.createdBy": {
+ name: "createdBy",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.intercompanyEliminationLine.createdAt": {
+ name: "createdAt",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.intercompanyEliminationLine.updatedBy": {
+ name: "updatedBy",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.intercompanyEliminationLine.updatedAt": {
+ name: "updatedAt",
+ required: false,
+ in: "query",
+ type: "string"
+ },
"body.changeOrderType": {
name: "changeOrderType",
description: "changeOrderType",
@@ -144526,6 +144920,14 @@ export default {
in: "query",
type: "string"
},
+ "rowFilter.journal.eliminationKind": {
+ name: "eliminationKind",
+ description:
+ "Classifies an elimination journal by the intercompany layer it removes (SAP posting-level analog); NULL for ordinary journals",
+ required: false,
+ in: "query",
+ type: "string"
+ },
"body.tableView": {
name: "tableView",
description: "tableView",
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index 87593646c2..009c1f9d80 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -18277,6 +18277,160 @@ export type Database = {
}
Relationships: []
}
+ intercompanyEliminationLine: {
+ Row: {
+ accountId: string
+ amount: number
+ companyId: string
+ createdAt: string
+ createdBy: string
+ id: string
+ intercompanyTransactionId: string
+ itemId: string | null
+ journalLineId: string
+ quantity: number | null
+ role: Database["public"]["Enums"]["intercompanyEliminationRole"]
+ updatedAt: string | null
+ updatedBy: string | null
+ }
+ Insert: {
+ accountId: string
+ amount: number
+ companyId: string
+ createdAt?: string
+ createdBy: string
+ id?: string
+ intercompanyTransactionId: string
+ itemId?: string | null
+ journalLineId: string
+ quantity?: number | null
+ role: Database["public"]["Enums"]["intercompanyEliminationRole"]
+ updatedAt?: string | null
+ updatedBy?: string | null
+ }
+ Update: {
+ accountId?: string
+ amount?: number
+ companyId?: string
+ createdAt?: string
+ createdBy?: string
+ id?: string
+ intercompanyTransactionId?: string
+ itemId?: string | null
+ journalLineId?: string
+ quantity?: number | null
+ role?: Database["public"]["Enums"]["intercompanyEliminationRole"]
+ updatedAt?: string | null
+ updatedBy?: string | null
+ }
+ Relationships: [
+ {
+ foreignKeyName: "intercompanyEliminationLine_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "companies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "intercompanyEliminationLine_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "intercompanyEliminationLine_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "intercompanyEliminationLine_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "integrations"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "intercompanyEliminationLine_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "intercompanyEliminationLine_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "intercompanyEliminationLine_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "intercompanyEliminationLine_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "intercompanyEliminationLine_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ {
+ foreignKeyName: "intercompanyEliminationLine_intercompanyTransactionId_fkey"
+ columns: ["intercompanyTransactionId"]
+ isOneToOne: false
+ referencedRelation: "intercompanyTransaction"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "intercompanyEliminationLine_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "intercompanyEliminationLine_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "intercompanyEliminationLine_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "intercompanyEliminationLine_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "intercompanyEliminationLine_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ ]
+ }
intercompanyTransaction: {
Row: {
amount: number
@@ -24488,6 +24642,7 @@ export type Database = {
createdBy: string | null
customFields: Json | null
description: string | null
+ eliminationKind: Database["public"]["Enums"]["eliminationKind"] | null
id: string
journalEntryId: string
postedAt: string | null
@@ -24510,6 +24665,9 @@ export type Database = {
createdBy?: string | null
customFields?: Json | null
description?: string | null
+ eliminationKind?:
+ | Database["public"]["Enums"]["eliminationKind"]
+ | null
id?: string
journalEntryId: string
postedAt?: string | null
@@ -24532,6 +24690,9 @@ export type Database = {
createdBy?: string | null
customFields?: Json | null
description?: string | null
+ eliminationKind?:
+ | Database["public"]["Enums"]["eliminationKind"]
+ | null
id?: string
journalEntryId?: string
postedAt?: string | null
@@ -66696,14 +66857,14 @@ export type Database = {
},
{
foreignKeyName: "partner_id_fkey"
- columns: ["id"]
+ columns: ["supplierLocationId"]
isOneToOne: false
referencedRelation: "supplierLocation"
referencedColumns: ["id"]
},
{
foreignKeyName: "partner_id_fkey"
- columns: ["supplierLocationId"]
+ columns: ["id"]
isOneToOne: false
referencedRelation: "supplierLocation"
referencedColumns: ["id"]
@@ -68342,14 +68503,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["supplierCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["supplierCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -71768,21 +71929,21 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["shipmentCountryCode"]
+ columns: ["invoiceCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["shipmentCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["invoiceCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -72329,14 +72490,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["paymentCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["paymentCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -75867,7 +76028,11 @@ export type Database = {
Returns: string
}
generateEliminationEntries: {
- Args: { p_company_group_id: string; p_user_id: string }
+ Args: {
+ p_company_group_id: string
+ p_regenerate?: boolean
+ p_user_id: string
+ }
Returns: number
}
get_action_tasks_by_item_and_process: {
@@ -78473,6 +78638,7 @@ export type Database = {
| "Audio"
| "Other"
| "Model"
+ eliminationKind: "IC Balance" | "IC Revenue"
employeeTypeSystemType: "Admin" | "Console Operator"
externalLinkDocumentType:
| "Quote"
@@ -78540,6 +78706,11 @@ export type Database = {
| "Passed"
| "Failed"
| "Partial"
+ intercompanyEliminationRole:
+ | "Control"
+ | "Revenue"
+ | "COGS"
+ | "Capitalization"
inventoryCountStatus: "Draft" | "Pending" | "Posted"
itemCostingMethod: "Standard" | "Average" | "LIFO" | "FIFO"
itemLedgerDocumentType:
@@ -79854,6 +80025,7 @@ export const Constants = {
"Other",
"Model",
],
+ eliminationKind: ["IC Balance", "IC Revenue"],
employeeTypeSystemType: ["Admin", "Console Operator"],
externalLinkDocumentType: [
"Quote",
@@ -79928,6 +80100,12 @@ export const Constants = {
"Failed",
"Partial",
],
+ intercompanyEliminationRole: [
+ "Control",
+ "Revenue",
+ "COGS",
+ "Capitalization",
+ ],
inventoryCountStatus: ["Draft", "Pending", "Posted"],
itemCostingMethod: ["Standard", "Average", "LIFO", "FIFO"],
itemLedgerDocumentType: [
diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.ts
index 87593646c2..009c1f9d80 100644
--- a/packages/database/supabase/functions/lib/types.ts
+++ b/packages/database/supabase/functions/lib/types.ts
@@ -18277,6 +18277,160 @@ export type Database = {
}
Relationships: []
}
+ intercompanyEliminationLine: {
+ Row: {
+ accountId: string
+ amount: number
+ companyId: string
+ createdAt: string
+ createdBy: string
+ id: string
+ intercompanyTransactionId: string
+ itemId: string | null
+ journalLineId: string
+ quantity: number | null
+ role: Database["public"]["Enums"]["intercompanyEliminationRole"]
+ updatedAt: string | null
+ updatedBy: string | null
+ }
+ Insert: {
+ accountId: string
+ amount: number
+ companyId: string
+ createdAt?: string
+ createdBy: string
+ id?: string
+ intercompanyTransactionId: string
+ itemId?: string | null
+ journalLineId: string
+ quantity?: number | null
+ role: Database["public"]["Enums"]["intercompanyEliminationRole"]
+ updatedAt?: string | null
+ updatedBy?: string | null
+ }
+ Update: {
+ accountId?: string
+ amount?: number
+ companyId?: string
+ createdAt?: string
+ createdBy?: string
+ id?: string
+ intercompanyTransactionId?: string
+ itemId?: string | null
+ journalLineId?: string
+ quantity?: number | null
+ role?: Database["public"]["Enums"]["intercompanyEliminationRole"]
+ updatedAt?: string | null
+ updatedBy?: string | null
+ }
+ Relationships: [
+ {
+ foreignKeyName: "intercompanyEliminationLine_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "companies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "intercompanyEliminationLine_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "intercompanyEliminationLine_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "intercompanyEliminationLine_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "integrations"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "intercompanyEliminationLine_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "intercompanyEliminationLine_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "intercompanyEliminationLine_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "intercompanyEliminationLine_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "intercompanyEliminationLine_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ {
+ foreignKeyName: "intercompanyEliminationLine_intercompanyTransactionId_fkey"
+ columns: ["intercompanyTransactionId"]
+ isOneToOne: false
+ referencedRelation: "intercompanyTransaction"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "intercompanyEliminationLine_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "intercompanyEliminationLine_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "intercompanyEliminationLine_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "intercompanyEliminationLine_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "intercompanyEliminationLine_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ ]
+ }
intercompanyTransaction: {
Row: {
amount: number
@@ -24488,6 +24642,7 @@ export type Database = {
createdBy: string | null
customFields: Json | null
description: string | null
+ eliminationKind: Database["public"]["Enums"]["eliminationKind"] | null
id: string
journalEntryId: string
postedAt: string | null
@@ -24510,6 +24665,9 @@ export type Database = {
createdBy?: string | null
customFields?: Json | null
description?: string | null
+ eliminationKind?:
+ | Database["public"]["Enums"]["eliminationKind"]
+ | null
id?: string
journalEntryId: string
postedAt?: string | null
@@ -24532,6 +24690,9 @@ export type Database = {
createdBy?: string | null
customFields?: Json | null
description?: string | null
+ eliminationKind?:
+ | Database["public"]["Enums"]["eliminationKind"]
+ | null
id?: string
journalEntryId?: string
postedAt?: string | null
@@ -66696,14 +66857,14 @@ export type Database = {
},
{
foreignKeyName: "partner_id_fkey"
- columns: ["id"]
+ columns: ["supplierLocationId"]
isOneToOne: false
referencedRelation: "supplierLocation"
referencedColumns: ["id"]
},
{
foreignKeyName: "partner_id_fkey"
- columns: ["supplierLocationId"]
+ columns: ["id"]
isOneToOne: false
referencedRelation: "supplierLocation"
referencedColumns: ["id"]
@@ -68342,14 +68503,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["supplierCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["supplierCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -71768,21 +71929,21 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["shipmentCountryCode"]
+ columns: ["invoiceCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["shipmentCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["invoiceCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -72329,14 +72490,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["paymentCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["paymentCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -75867,7 +76028,11 @@ export type Database = {
Returns: string
}
generateEliminationEntries: {
- Args: { p_company_group_id: string; p_user_id: string }
+ Args: {
+ p_company_group_id: string
+ p_regenerate?: boolean
+ p_user_id: string
+ }
Returns: number
}
get_action_tasks_by_item_and_process: {
@@ -78473,6 +78638,7 @@ export type Database = {
| "Audio"
| "Other"
| "Model"
+ eliminationKind: "IC Balance" | "IC Revenue"
employeeTypeSystemType: "Admin" | "Console Operator"
externalLinkDocumentType:
| "Quote"
@@ -78540,6 +78706,11 @@ export type Database = {
| "Passed"
| "Failed"
| "Partial"
+ intercompanyEliminationRole:
+ | "Control"
+ | "Revenue"
+ | "COGS"
+ | "Capitalization"
inventoryCountStatus: "Draft" | "Pending" | "Posted"
itemCostingMethod: "Standard" | "Average" | "LIFO" | "FIFO"
itemLedgerDocumentType:
@@ -79854,6 +80025,7 @@ export const Constants = {
"Other",
"Model",
],
+ eliminationKind: ["IC Balance", "IC Revenue"],
employeeTypeSystemType: ["Admin", "Console Operator"],
externalLinkDocumentType: [
"Quote",
@@ -79928,6 +80100,12 @@ export const Constants = {
"Failed",
"Partial",
],
+ intercompanyEliminationRole: [
+ "Control",
+ "Revenue",
+ "COGS",
+ "Capitalization",
+ ],
inventoryCountStatus: ["Draft", "Pending", "Posted"],
itemCostingMethod: ["Standard", "Average", "LIFO", "FIFO"],
itemLedgerDocumentType: [
diff --git a/packages/database/supabase/functions/post-purchase-invoice/index.ts b/packages/database/supabase/functions/post-purchase-invoice/index.ts
index d7e6f6aa81..509ae13fe5 100644
--- a/packages/database/supabase/functions/post-purchase-invoice/index.ts
+++ b/packages/database/supabase/functions/post-purchase-invoice/index.ts
@@ -2076,7 +2076,7 @@ serve(async (req: Request) => {
companyGroupId &&
icJournalLineId
) {
- await trx
+ const icTxn = await trx
.insertInto("intercompanyTransaction")
.values({
companyGroupId,
@@ -2090,7 +2090,136 @@ serve(async (req: Request) => {
documentId: purchaseInvoice.data?.id,
status: "Unmatched",
})
+ .returning(["id"])
+ .executeTakeFirstOrThrow();
+
+ // Capture the buyer side's role-classified elimination lines. The
+ // profit the consolidation defers is embedded in whatever ASSET the
+ // buyer capitalized the goods into — inventory OR a fixed asset — so
+ // capture the buyer's actual capitalization account (not the seller's
+ // inventory relief, which was the negative-Finished-Goods bug).
+ const eliminationLineInserts: Database["public"]["Tables"]["intercompanyEliminationLine"]["Insert"][] =
+ [];
+
+ // Control: the IC payable line.
+ eliminationLineInserts.push({
+ companyId,
+ intercompanyTransactionId: icTxn.id,
+ role: "Control",
+ journalLineId: icJournalLineId,
+ accountId: payablesAccountId!,
+ amount: journalLineInserts[icPayableIdx]?.amount ?? 0,
+ itemId: null,
+ quantity: null,
+ createdBy: userId,
+ });
+
+ // Capitalization is any Asset-class DEBIT the buyer posted for the
+ // goods — which excludes GR/IR clearing (a liability) and expensed
+ // indirect cost by construction. It lands in two places: on THIS
+ // invoice for not-yet-received / fixed-asset-at-invoice lines, and on
+ // the linked RECEIPT posting for goods already received (the common
+ // path — the invoice only trues up the price variance there).
+ const poLineToItem = new Map<string, string | null>();
+ for (const line of purchaseInvoiceLines.data) {
+ if (line.purchaseOrderLineId)
+ poLineToItem.set(line.purchaseOrderLineId, line.itemId ?? null);
+ }
+ const jlIdToItem = new Map<string, string | null>();
+ journalLineResults.forEach((jl, index) => {
+ jlIdToItem.set(jl.id, journalLineDimensionsMeta[index]?.itemId ?? null);
+ });
+
+ // (i) inline capitalization on this invoice's journal
+ const invoiceCapLines = await trx
+ .selectFrom("journalLine as jl")
+ .innerJoin("account as a", "a.id", "jl.accountId")
+ .select([
+ "jl.id as id",
+ "jl.accountId as accountId",
+ "jl.amount as amount",
+ "jl.quantity as quantity",
+ ])
+ .where("jl.journalId", "=", journalId)
+ .where("a.class", "=", "Asset")
+ .where("jl.amount", ">", 0)
.execute();
+ for (const cap of invoiceCapLines) {
+ eliminationLineInserts.push({
+ companyId,
+ intercompanyTransactionId: icTxn.id,
+ role: "Capitalization",
+ journalLineId: cap.id,
+ accountId: cap.accountId,
+ amount: cap.amount ?? 0,
+ itemId: jlIdToItem.get(cap.id) ?? null,
+ quantity: cap.quantity ?? null,
+ createdBy: userId,
+ });
+ }
+
+ // (ii) receipt capitalization (goods received before invoicing)
+ const poLineIds = [...poLineToItem.keys()];
+ if (poLineIds.length > 0) {
+ const receiptLineRows = await trx
+ .selectFrom("receiptLine")
+ .select(["receiptId", "lineId"])
+ .where("lineId", "in", poLineIds)
+ .where("companyId", "=", companyId)
+ .execute();
+ const receiptIds = [
+ ...new Set(
+ receiptLineRows
+ .map((row) => row.receiptId)
+ .filter((id): id is string => !!id)
+ ),
+ ];
+ if (receiptIds.length > 0) {
+ const receiptCapLines = await trx
+ .selectFrom("journalLine as jl")
+ .innerJoin("account as a", "a.id", "jl.accountId")
+ .select([
+ "jl.id as id",
+ "jl.accountId as accountId",
+ "jl.amount as amount",
+ "jl.quantity as quantity",
+ "jl.documentLineReference as documentLineReference",
+ ])
+ .where("jl.companyId", "=", companyId)
+ .where("jl.documentId", "in", receiptIds)
+ .where("a.class", "=", "Asset")
+ .where("jl.amount", ">", 0)
+ .execute();
+ for (const cap of receiptCapLines) {
+ // documentLineReference is `receipt:<purchaseOrderLineId>`; map
+ // it back to the item so on-hand realization can scale the
+ // writedown. Fixed assets carry no item -> full deferral.
+ let itemId: string | null = null;
+ const ref = cap.documentLineReference ?? "";
+ if (ref.startsWith("receipt:")) {
+ itemId = poLineToItem.get(ref.slice("receipt:".length)) ?? null;
+ }
+ eliminationLineInserts.push({
+ companyId,
+ intercompanyTransactionId: icTxn.id,
+ role: "Capitalization",
+ journalLineId: cap.id,
+ accountId: cap.accountId,
+ amount: cap.amount ?? 0,
+ itemId,
+ quantity: cap.quantity ?? null,
+ createdBy: userId,
+ });
+ }
+ }
+ }
+
+ if (eliminationLineInserts.length > 0) {
+ await trx
+ .insertInto("intercompanyEliminationLine")
+ .values(eliminationLineInserts)
+ .execute();
+ }
}
}
diff --git a/packages/database/supabase/functions/post-sales-invoice/index.ts b/packages/database/supabase/functions/post-sales-invoice/index.ts
index e1913aa173..c30084d498 100644
--- a/packages/database/supabase/functions/post-sales-invoice/index.ts
+++ b/packages/database/supabase/functions/post-sales-invoice/index.ts
@@ -1256,7 +1256,7 @@ serve(async (req: Request) => {
);
if (icJournalLineId) {
- await trx
+ const icTxn = await trx
.insertInto("intercompanyTransaction")
.values({
companyGroupId: companyGroupId!,
@@ -1270,7 +1270,92 @@ serve(async (req: Request) => {
documentId: salesInvoice.data?.id,
status: "Unmatched",
})
- .execute();
+ .returning(["id"])
+ .executeTakeFirstOrThrow();
+
+ // Capture the seller side's role-classified elimination lines so
+ // consolidation reverses them by reference instead of reconstructing
+ // the trade from the GL. The edge function knows each line's role
+ // exactly (Control = IC receivable, Revenue = sales account, COGS =
+ // cost-of-goods account), so no account-class guessing is needed.
+ const eliminationLineInserts: Database["public"]["Tables"]["intercompanyEliminationLine"]["Insert"][] =
+ [];
+ const salesAccount = accountDefaults?.data?.salesAccount;
+ const cogsAccount = accountDefaults?.data?.costOfGoodsSoldAccount;
+
+ journalLineInserts.forEach((line, index) => {
+ const jlId = journalLineResults[index]?.id;
+ if (!jlId) return;
+ let role: "Control" | "Revenue" | "COGS" | null = null;
+ if (index === icReceivableIdx) role = "Control";
+ else if (salesAccount && line.accountId === salesAccount)
+ role = "Revenue";
+ else if (cogsAccount && line.accountId === cogsAccount)
+ role = "COGS";
+ if (!role) return;
+ eliminationLineInserts.push({
+ companyId,
+ intercompanyTransactionId: icTxn.id,
+ role,
+ journalLineId: jlId,
+ accountId: line.accountId!,
+ amount: line.amount ?? 0,
+ itemId: journalLineDimensionsMeta[index]?.itemId ?? null,
+ quantity: line.quantity ?? null,
+ createdBy: userId,
+ });
+ });
+
+ // Sales-order-based sales post COGS at SHIPMENT (a prior posting),
+ // not on this invoice, so it is not in journalLineInserts. Capture
+ // those shipment COGS lines via the deterministic invoice ->
+ // salesInvoiceLine.salesOrderId -> shipment(sourceDocument = 'Sales
+ // Order') link. Done once, here, and stored — never re-derived per
+ // elimination run.
+ const salesOrderIds = [
+ ...new Set(
+ salesInvoiceLines.data
+ .map((line) => line.salesOrderId)
+ .filter((id): id is string => !!id)
+ ),
+ ];
+ if (cogsAccount && salesOrderIds.length > 0) {
+ const shipmentCogsLines = await trx
+ .selectFrom("journalLine as jl")
+ .innerJoin("shipment as s", "s.id", "jl.documentId")
+ .select([
+ "jl.id as id",
+ "jl.accountId as accountId",
+ "jl.amount as amount",
+ "jl.quantity as quantity",
+ ])
+ .where("jl.companyId", "=", companyId)
+ .where("jl.accountId", "=", cogsAccount)
+ .where("s.companyId", "=", companyId)
+ .where("s.sourceDocument", "=", "Sales Order")
+ .where("s.sourceDocumentId", "in", salesOrderIds)
+ .execute();
+ for (const cogs of shipmentCogsLines) {
+ eliminationLineInserts.push({
+ companyId,
+ intercompanyTransactionId: icTxn.id,
+ role: "COGS",
+ journalLineId: cogs.id,
+ accountId: cogs.accountId,
+ amount: cogs.amount ?? 0,
+ itemId: null,
+ quantity: cogs.quantity ?? null,
+ createdBy: userId,
+ });
+ }
+ }
+
+ if (eliminationLineInserts.length > 0) {
+ await trx
+ .insertInto("intercompanyEliminationLine")
+ .values(eliminationLineInserts)
+ .execute();
+ }
}
}
diff --git a/packages/database/supabase/functions/seed-company/index.ts b/packages/database/supabase/functions/seed-company/index.ts
index e214a4e2d9..d5e680d6b3 100644
--- a/packages/database/supabase/functions/seed-company/index.ts
+++ b/packages/database/supabase/functions/seed-company/index.ts
@@ -120,14 +120,19 @@ serve(async (req: Request) => {
.execute();
}
- // For subsidiaries: set companyGroupId and parentCompanyId
- if (parentCompanyId) {
- await trx
- .updateTable("company")
- .set({ companyGroupId, parentCompanyId })
- .where("id", "=", companyId)
- .execute();
- }
+ // For subsidiaries, companyGroupId + parentCompanyId are set LATER (just
+ // before the elimination-entity block), not here. Setting companyGroupId
+ // fires the `company_sync_ic_partners` trigger, which inserts an
+ // intercompany supplier/customer row in this company for each sibling. Those
+ // inserts rely on the `set_{supplier,customer}_readable_id_on_insert`
+ // triggers to stamp a readableId from the company's sequence — and the
+ // sequences aren't seeded until the reference-data block below. Firing the
+ // trigger here left every intercompany row with readableId '' (the auto-fill
+ // no-ops when no sequence row exists yet). Since
+ // `supplier_readableId_companyId_unique` treats '' as a real value, only the
+ // FIRST sibling's row survived; every later sibling collided on
+ // (companyId, '') and was silently dropped by ON CONFLICT DO NOTHING — so a
+ // company created into a group of 3+ only ever saw one sibling.
await trx
.withSchema("storage")
@@ -491,6 +496,19 @@ serve(async (req: Request) => {
.eq("id", userId);
if (error) throw new Error(error.message);
+ // For subsidiaries: set companyGroupId + parentCompanyId now that the
+ // reference data (including the supplier/customer sequences) has been
+ // seeded. This is what fires `company_sync_ic_partners`; running it here
+ // guarantees the readableId auto-fill triggers can stamp a real id on every
+ // intercompany partner row, so no two siblings collide on (companyId, '').
+ if (parentCompanyId) {
+ await trx
+ .updateTable("company")
+ .set({ companyGroupId, parentCompanyId })
+ .where("id", "=", companyId)
+ .execute();
+ }
+
// Auto-create elimination entity if this is a subsidiary
if (parentCompanyId && companyGroupId) {
const siblings = await trx
@@ -511,7 +529,7 @@ serve(async (req: Request) => {
.where("id", "=", parentCompanyId)
.executeTakeFirst();
- await trx
+ const eliminationCompany = await trx
.insertInto("company")
.values({
name: `Elimination - ${parent?.name ?? "Unknown"}`,
@@ -528,7 +546,25 @@ serve(async (req: Request) => {
isEliminationEntity: true,
companyGroupId,
})
- .execute();
+ .returning(["id"])
+ .executeTakeFirst();
+
+ // Seed sequences for the elimination entity. It is otherwise a bare
+ // consolidation shell, but generateEliminationEntries posts an
+ // elimination journal on it and stamps journalEntryId from
+ // get_next_sequence('journalEntry', <elim>) — without its own
+ // sequence rows that raises "Sequence not found".
+ if (eliminationCompany?.id) {
+ await trx
+ .insertInto("sequence")
+ .values(
+ sequences.map((s) => ({
+ ...s,
+ companyId: eliminationCompany.id,
+ }))
+ )
+ .execute();
+ }
}
}
});
diff --git a/packages/database/supabase/migrations/20260817023814_elimination-entity-sequences.sql b/packages/database/supabase/migrations/20260817023814_elimination-entity-sequences.sql
new file mode 100644
index 0000000000..d864fbf99e
--- /dev/null
+++ b/packages/database/supabase/migrations/20260817023814_elimination-entity-sequences.sql
@@ -0,0 +1,26 @@
+-- Elimination entities are auto-created as bare company shells in seed-company
+-- (isEliminationEntity = true) with no reference data — in particular no
+-- `sequence` rows. generateEliminationEntries posts an elimination journal on
+-- that entity and stamps journalEntryId from
+-- get_next_sequence('journalEntry', <elim>)
+-- which raised P0001 "Sequence not found for table journalEntry and company
+-- <elim>" the moment the earlier RLS / accounting-period fixes let execution
+-- reach it.
+--
+-- Backfill the missing sequences for every existing elimination entity by
+-- copying its parent company's sequences (a real, fully-seeded company), with
+-- `next` reset to 0 so the entity starts its own counters. seed-company is fixed
+-- in the same change to seed these going forward. Idempotent: ON CONFLICT on the
+-- ("table", "companyId") primary key means re-running over already-seeded
+-- entities is a no-op, and any sequence a parent lacks is simply skipped.
+
+INSERT INTO "sequence" (
+ "table", "name", "prefix", "suffix", "next", "size", "step", "companyId"
+)
+SELECT
+ s."table", s."name", s."prefix", s."suffix", 0, s."size", s."step", elim."id"
+FROM "company" elim
+JOIN "sequence" s ON s."companyId" = elim."parentCompanyId"
+WHERE elim."isEliminationEntity" = true
+ AND elim."parentCompanyId" IS NOT NULL
+ON CONFLICT ("table", "companyId") DO NOTHING;
diff --git a/packages/database/supabase/migrations/20260817032651_backfill-intercompany-partners.sql b/packages/database/supabase/migrations/20260817032651_backfill-intercompany-partners.sql
new file mode 100644
index 0000000000..abb331924e
--- /dev/null
+++ b/packages/database/supabase/migrations/20260817032651_backfill-intercompany-partners.sql
@@ -0,0 +1,76 @@
+-- Backfill intercompany supplier/customer partner rows that were silently
+-- dropped at seed time.
+--
+-- `sync_intercompany_partners` (20260403120000) inserts a supplier + customer
+-- row in each company for every sibling in its group, WITHOUT a readableId,
+-- using ON CONFLICT DO NOTHING. seed-company set the subsidiary's companyGroupId
+-- (which fires that trigger) BEFORE it seeded the company's `sequence` rows, so
+-- `set_{supplier,customer}_readable_id_on_insert` (20260521124731) — which only
+-- stamps an id when the sequence row already exists — left readableId ''. Because
+-- `supplier_readableId_companyId_unique` / `customer_readableId_companyId_unique`
+-- treat '' as a real value, only the FIRST sibling's partner row survived; every
+-- later sibling collided on (companyId, '') and was swallowed. A company created
+-- into a group of 3+ therefore saw only one sibling as an intercompany partner.
+--
+-- seed-company now sets companyGroupId AFTER seeding sequences, so new companies
+-- are provisioned correctly. This migration repairs already-seeded groups.
+-- Idempotent: blank-id backfill only touches rows still missing an id, and the
+-- inserts are guarded by NOT EXISTS + ON CONFLICT DO NOTHING.
+
+-- 1. Give the surviving intercompany rows a real readableId (frees the '' slot
+-- so step 2's inserts can't recreate the collision, and stops them rendering
+-- blank in the UI). Only where the company actually has the sequence.
+UPDATE "supplier"
+SET "readableId" = get_next_sequence('supplier', "companyId")
+WHERE "intercompanyCompanyId" IS NOT NULL
+ AND ("readableId" IS NULL OR "readableId" = '')
+ AND EXISTS (
+ SELECT 1 FROM "sequence" s
+ WHERE s."table" = 'supplier' AND s."companyId" = "supplier"."companyId"
+ );
+
+UPDATE "customer"
+SET "readableId" = get_next_sequence('customer', "companyId")
+WHERE "intercompanyCompanyId" IS NOT NULL
+ AND ("readableId" IS NULL OR "readableId" = '')
+ AND EXISTS (
+ SELECT 1 FROM "sequence" s
+ WHERE s."table" = 'customer' AND s."companyId" = "customer"."companyId"
+ );
+
+-- 2. Insert the missing partner rows for every active, non-elimination company
+-- pair within a group. The BEFORE INSERT readableId triggers stamp a real id
+-- per row (sequences now exist), so no two siblings collide on (companyId, '').
+INSERT INTO "supplier" ("name", "companyId", "intercompanyCompanyId")
+SELECT partner."name", own."id", partner."id"
+FROM "company" own
+JOIN "company" partner
+ ON partner."companyGroupId" = own."companyGroupId"
+ AND partner."id" <> own."id"
+ AND partner."isEliminationEntity" = false
+ AND partner."active" = true
+WHERE own."isEliminationEntity" = false
+ AND own."active" = true
+ AND own."companyGroupId" IS NOT NULL
+ AND NOT EXISTS (
+ SELECT 1 FROM "supplier" s
+ WHERE s."companyId" = own."id" AND s."intercompanyCompanyId" = partner."id"
+ )
+ON CONFLICT DO NOTHING;
+
+INSERT INTO "customer" ("name", "companyId", "intercompanyCompanyId")
+SELECT partner."name", own."id", partner."id"
+FROM "company" own
+JOIN "company" partner
+ ON partner."companyGroupId" = own."companyGroupId"
+ AND partner."id" <> own."id"
+ AND partner."isEliminationEntity" = false
+ AND partner."active" = true
+WHERE own."isEliminationEntity" = false
+ AND own."active" = true
+ AND own."companyGroupId" IS NOT NULL
+ AND NOT EXISTS (
+ SELECT 1 FROM "customer" c
+ WHERE c."companyId" = own."id" AND c."intercompanyCompanyId" = partner."id"
+ )
+ON CONFLICT DO NOTHING;
diff --git a/packages/database/supabase/migrations/20260817122328_intercompany-revenue-cogs-elimination.sql b/packages/database/supabase/migrations/20260817122328_intercompany-revenue-cogs-elimination.sql
new file mode 100644
index 0000000000..3020304909
--- /dev/null
+++ b/packages/database/supabase/migrations/20260817122328_intercompany-revenue-cogs-elimination.sql
@@ -0,0 +1,539 @@
+-- Intercompany elimination engine: structured capture, not GL reconstruction.
+--
+-- The elimination no longer reverse-engineers each intragroup trade from the GL
+-- at consolidation time (sweeping journal lines by account class and walking the
+-- invoice -> sales order -> shipment document graph). That reconstruction was
+-- open-endedly fragile: COGS at shipment, COGS split across accounts, and a buyer
+-- capitalizing a FIXED ASSET instead of inventory all broke a heuristic (the last
+-- produced negative consolidated Finished Goods).
+--
+-- Instead, each side of an intragroup trade records role-classified references to
+-- the journal lines the elimination will act on WHEN IT POSTS (where the edge
+-- function knows each line's role exactly) into "intercompanyEliminationLine".
+-- The elimination is then a pure read over those records:
+--
+-- * journal.eliminationKind — classifies each elimination journal by the layer
+-- it removes (SAP posting-level analog): 'IC Balance' (the AR/AP wash) or
+-- 'IC Revenue' (the intragroup P&L + unrealized-profit writedown).
+--
+-- * IC Balance: reverse every captured 'Control' line (the reciprocal IC
+-- Receivable / IC Payable), netting the intercompany balance to zero.
+--
+-- * IC Revenue: for each matched pair with an intragroup sale, reverse the
+-- seller's captured 'Revenue' and 'COGS' lines and write the BUYER's captured
+-- 'Capitalization' account (inventory OR fixed asset — whatever the buyer
+-- actually debited) down to group cost by the margin M = Revenue - COGS. For a
+-- sale at transfer price R, seller group cost C, margin M = R - C:
+-- Dr Sales revenue R (reverse the seller's revenue)
+-- Cr Cost of goods sold C (reverse the seller's COGS)
+-- Cr Buyer capitalization M (remove the unrealized margin from the
+-- asset the buyer holds it in)
+-- Balances by construction; net income effect = 0 for goods the group still
+-- holds. Writing the BUYER's account (not the seller's inventory relief) is
+-- what makes a fixed-asset buyer correct and fixes the negative-FG bug.
+--
+-- * On-hand realization: the writedown is scaled by the buyer's on-hand fraction
+-- of the traded item (fixed assets: fraction 1 until disposed). Revenue and
+-- COGS reversal are scaled by the same weighted fraction so the journal stays
+-- balanced at any realization level; re-running in a later period after the
+-- buyer sells externally reduces the deferred profit proportionally.
+--
+-- * p_regenerate: reverse existing eliminations (reversing entries, never
+-- deletes — the immutability rule) and flip the pair back to Matched, then
+-- regenerate from current capture + on-hand. Idempotent re-runs after a fix.
+--
+-- Tracking spec: .ai/specs/2026-08-17-intercompany-elimination-engine.md
+
+-- 1. Classifiers ------------------------------------------------------------
+DO $$ BEGIN
+ IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'eliminationKind') THEN
+ CREATE TYPE "eliminationKind" AS ENUM ('IC Balance', 'IC Revenue');
+ END IF;
+END $$;
+
+ALTER TABLE "journal" ADD COLUMN IF NOT EXISTS "eliminationKind" "eliminationKind";
+COMMENT ON COLUMN "journal"."eliminationKind" IS
+ 'Classifies an elimination journal by the intercompany layer it removes (SAP posting-level analog); NULL for ordinary journals';
+
+DO $$ BEGIN
+ IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'intercompanyEliminationRole') THEN
+ CREATE TYPE "intercompanyEliminationRole" AS ENUM (
+ 'Control', -- IC Receivable / IC Payable (the balance elimination)
+ 'Revenue', -- seller intragroup revenue
+ 'COGS', -- seller cost of the goods sold
+ 'Capitalization' -- the asset the buyer capitalized the profit into (inventory OR fixed asset)
+ );
+ END IF;
+END $$;
+
+-- 2. Widen intercompanyTransaction.amount to bare NUMERIC (numeric-precision
+-- convention; grounded gap — was NUMERIC(19,4)).
+ALTER TABLE "intercompanyTransaction" ALTER COLUMN "amount" TYPE NUMERIC;
+
+-- 3. Capture table ----------------------------------------------------------
+-- Role-classified references to the actual posted journal lines, written by the
+-- posting edge functions on the intercompany path. Child of intercompanyTransaction
+-- (single-column PK), scoped to the company that POSTED the line (seller or buyer).
+CREATE TABLE IF NOT EXISTS "intercompanyEliminationLine" (
+ "id" TEXT NOT NULL DEFAULT id('icel'),
+ "companyId" TEXT NOT NULL,
+ "intercompanyTransactionId" TEXT NOT NULL,
+ "role" "intercompanyEliminationRole" NOT NULL,
+ "journalLineId" TEXT NOT NULL,
+ "accountId" TEXT NOT NULL,
+ "amount" NUMERIC NOT NULL,
+ "itemId" TEXT,
+ "quantity" NUMERIC,
+
+ "createdBy" TEXT NOT NULL REFERENCES "user"("id"),
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "updatedBy" TEXT REFERENCES "user"("id"),
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+
+ PRIMARY KEY ("id", "companyId"),
+ FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE,
+ FOREIGN KEY ("intercompanyTransactionId") REFERENCES "intercompanyTransaction"("id") ON DELETE CASCADE
+);
+
+CREATE INDEX IF NOT EXISTS "intercompanyEliminationLine_companyId_idx"
+ ON "intercompanyEliminationLine" ("companyId");
+CREATE INDEX IF NOT EXISTS "intercompanyEliminationLine_intercompanyTransactionId_idx"
+ ON "intercompanyEliminationLine" ("intercompanyTransactionId");
+CREATE INDEX IF NOT EXISTS "intercompanyEliminationLine_createdBy_idx"
+ ON "intercompanyEliminationLine" ("createdBy");
+
+ALTER TABLE "public"."intercompanyEliminationLine" ENABLE ROW LEVEL SECURITY;
+
+CREATE POLICY "SELECT" ON "public"."intercompanyEliminationLine"
+FOR SELECT USING (
+ "companyId" = ANY ((SELECT get_companies_with_employee_role())::text[])
+);
+
+CREATE POLICY "INSERT" ON "public"."intercompanyEliminationLine"
+FOR INSERT WITH CHECK (
+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('accounting_create'))::text[])
+);
+
+CREATE POLICY "UPDATE" ON "public"."intercompanyEliminationLine"
+FOR UPDATE USING (
+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('accounting_update'))::text[])
+);
+
+CREATE POLICY "DELETE" ON "public"."intercompanyEliminationLine"
+FOR DELETE USING (
+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('accounting_delete'))::text[])
+);
+
+-- 4. Elimination engine (capture-driven) ------------------------------------
+-- Drop the prior 2-arg version (20260817012947) before recreating: adding the
+-- p_regenerate DEFAULT parameter makes CREATE OR REPLACE build a SIBLING rather
+-- than replace it, and a 2-arg call would then be ambiguous against the new
+-- overload's default. Drop first so exactly one function remains.
+DROP FUNCTION IF EXISTS "generateEliminationEntries"(TEXT, TEXT);
+
+CREATE OR REPLACE FUNCTION "generateEliminationEntries" (
+ p_company_group_id TEXT,
+ p_user_id TEXT,
+ p_regenerate BOOLEAN DEFAULT false
+)
+RETURNS INTEGER
+LANGUAGE "plpgsql"
+SECURITY INVOKER
+SET search_path = public
+AS $$
+DECLARE
+ v_rec RECORD;
+ v_cap RECORD;
+ v_reg RECORD;
+ v_sale RECORD;
+ v_buyer_ict TEXT;
+ v_lca_id TEXT;
+ v_elim_id TEXT;
+ v_journal_id TEXT;
+ v_balance_journal_id TEXT;
+ v_rev_journal_id TEXT;
+ v_period_id TEXT;
+ v_journals_created INTEGER := 0;
+ v_line_count INTEGER;
+ v_today DATE;
+ v_period_status "accountingPeriodStatus";
+ v_close_status "periodCloseStatus";
+ v_period_start DATE;
+ v_period_end DATE;
+ v_start_month "month";
+ v_start_month_num INTEGER;
+ v_year INTEGER;
+ v_month INTEGER;
+ v_period_number INTEGER;
+ v_fiscal_year INTEGER;
+ -- revenue elimination locals
+ v_revenue NUMERIC;
+ v_cogs NUMERIC;
+ v_margin NUMERIC;
+ v_cap_total NUMERIC;
+ v_cap_realized NUMERIC;
+ v_fraction NUMERIC;
+ v_onhand NUMERIC;
+BEGIN
+ IF NOT EXISTS (
+ SELECT 1
+ FROM "userToCompany" utc
+ INNER JOIN "company" c ON c."id" = utc."companyId"
+ WHERE utc."userId" = p_user_id
+ AND utc."role" = 'employee'
+ AND c."companyGroupId" = p_company_group_id
+ ) THEN
+ RAISE EXCEPTION 'Insufficient permissions to generate elimination entries';
+ END IF;
+
+ -- Serialize per company group: two concurrent runs would both read the same
+ -- 'Matched' rows (not locked until the flip at the end) and double-post every
+ -- elimination journal. A transaction-scoped advisory lock makes the second
+ -- caller wait for the first to commit, after which it finds no Matched rows.
+ PERFORM pg_advisory_xact_lock(hashtext(p_company_group_id));
+
+ -- Regenerate: reverse every existing elimination journal on the group's
+ -- elimination entities that has not already been reversed (post reversing
+ -- entries — never delete, the immutability rule), then flip the pairs back to
+ -- Matched so the pass below regenerates them from current capture + on-hand.
+ IF p_regenerate THEN
+ FOR v_reg IN
+ SELECT j."id", j."accountingPeriodId", j."companyId", j."eliminationKind", j."postingDate"
+ FROM "journal" j
+ INNER JOIN "company" c ON c."id" = j."companyId"
+ LEFT JOIN "accountingPeriod" ap ON ap."id" = j."accountingPeriodId"
+ WHERE c."companyGroupId" = p_company_group_id
+ AND c."isEliminationEntity" = true
+ AND j."eliminationKind" IS NOT NULL
+ AND j."description" NOT LIKE 'Reversal:%'
+ AND (ap."closeStatus" IS NULL OR ap."closeStatus" = 'Open')
+ AND NOT EXISTS (
+ SELECT 1 FROM "journal" r WHERE r."description" = 'Reversal: ' || j."id"
+ )
+ LOOP
+ -- Reverse into the same period AND date as the original so the two net in
+ -- the same reporting window (the regenerated entry re-dates to the current
+ -- transactions below).
+ INSERT INTO "journal" (
+ "description", "accountingPeriodId", "companyId", "postingDate",
+ "journalEntryId", "sourceType", "eliminationKind"
+ ) VALUES (
+ 'Reversal: ' || v_reg."id",
+ v_reg."accountingPeriodId", v_reg."companyId", v_reg."postingDate",
+ get_next_sequence('journalEntry', v_reg."companyId"), 'Manual', v_reg."eliminationKind"
+ ) RETURNING "id" INTO v_rev_journal_id;
+
+ INSERT INTO "journalLine" (
+ "journalId", "accountId", "description", "amount",
+ "documentType", "journalLineReference", "companyId"
+ )
+ SELECT v_rev_journal_id, jl."accountId",
+ 'Reversal: ' || COALESCE(jl."description", ''),
+ -jl."amount", jl."documentType", 'ic-elim-rev-' || v_rev_journal_id::text, jl."companyId"
+ FROM "journalLine" jl
+ WHERE jl."journalId" = v_reg."id";
+
+ v_journals_created := v_journals_created + 1;
+ END LOOP;
+
+ UPDATE "intercompanyTransaction"
+ SET "status" = 'Matched', "eliminationJournalId" = NULL, "updatedAt" = NOW()
+ WHERE "companyGroupId" = p_company_group_id
+ AND "status" = 'Eliminated';
+ END IF;
+
+ FOR v_rec IN
+ SELECT DISTINCT
+ LEAST(ict."sourceCompanyId", ict."targetCompanyId") AS "companyA",
+ GREATEST(ict."sourceCompanyId", ict."targetCompanyId") AS "companyB"
+ FROM "intercompanyTransaction" ict
+ WHERE ict."companyGroupId" = p_company_group_id
+ AND ict."status" = 'Matched'
+ LOOP
+ v_lca_id := "findLowestCommonParent"(v_rec."companyA", v_rec."companyB");
+
+ SELECT c."id" INTO v_elim_id
+ FROM "company" c
+ WHERE c."parentCompanyId" = v_lca_id
+ AND c."isEliminationEntity" = true
+ AND c."companyGroupId" = p_company_group_id
+ LIMIT 1;
+
+ IF v_elim_id IS NULL THEN
+ SELECT c."id" INTO v_elim_id
+ FROM "company" c
+ WHERE c."companyGroupId" = p_company_group_id
+ AND c."isEliminationEntity" = true
+ LIMIT 1;
+ END IF;
+
+ IF v_elim_id IS NULL THEN
+ RAISE EXCEPTION 'No elimination entity found for company group %', p_company_group_id;
+ END IF;
+
+ -- Date the elimination to the latest posting date among the transactions it
+ -- eliminates — NOT the synthetic elimination entity's "today". The
+ -- elimination entity has no location, so company_today() falls back to UTC
+ -- and can sit a day ahead of the operating companies (or roll into the next
+ -- month) at a day boundary. That would post the adjustment outside the
+ -- reporting window the transactions fall in, so an as-of balance sheet shows
+ -- the intercompany balance un-eliminated even though the drill-down (all
+ -- time) nets to zero. Anchor to the transactions' own business date.
+ SELECT MAX(j."postingDate") INTO v_today
+ FROM "intercompanyEliminationLine" iel
+ INNER JOIN "intercompanyTransaction" ict ON ict."id" = iel."intercompanyTransactionId"
+ INNER JOIN "journalLine" jl ON jl."id" = iel."journalLineId"
+ INNER JOIN "journal" j ON j."id" = jl."journalId"
+ WHERE ict."companyGroupId" = p_company_group_id
+ AND ict."status" = 'Matched'
+ AND LEAST(ict."sourceCompanyId", ict."targetCompanyId") = v_rec."companyA"
+ AND GREATEST(ict."sourceCompanyId", ict."targetCompanyId") = v_rec."companyB"
+ AND iel."role" = 'Control';
+
+ IF v_today IS NULL THEN
+ v_today := company_today(v_elim_id);
+ END IF;
+
+ SELECT ap."id", ap."status", ap."closeStatus"
+ INTO v_period_id, v_period_status, v_close_status
+ FROM "accountingPeriod" ap
+ WHERE ap."companyId" = v_elim_id
+ AND ap."startDate" <= v_today
+ AND ap."endDate" >= v_today
+ ORDER BY ap."startDate" DESC
+ LIMIT 1;
+
+ IF v_period_id IS NOT NULL THEN
+ IF v_close_status = 'Closed' THEN
+ RAISE EXCEPTION 'The elimination entity''s accounting period is closed. Reopen it before generating eliminations.';
+ END IF;
+ IF v_close_status = 'Locked' THEN
+ RAISE EXCEPTION 'The elimination entity''s accounting period is locked. Unlock it before generating eliminations.';
+ END IF;
+ IF v_period_status = 'Inactive' THEN
+ UPDATE "accountingPeriod" SET "status" = 'Inactive'
+ WHERE "companyId" = v_elim_id AND "status" = 'Active';
+ UPDATE "accountingPeriod" SET "status" = 'Active' WHERE "id" = v_period_id;
+ END IF;
+ ELSE
+ v_period_start := date_trunc('month', v_today)::date;
+ v_period_end := (date_trunc('month', v_today) + INTERVAL '1 month - 1 day')::date;
+ SELECT fys."startMonth" INTO v_start_month
+ FROM "fiscalYearSettings" fys WHERE fys."companyId" = v_elim_id;
+ v_start_month_num := COALESCE(array_position(enum_range(NULL::"month"), v_start_month), 1);
+ v_year := EXTRACT(YEAR FROM v_today)::integer;
+ v_month := EXTRACT(MONTH FROM v_today)::integer;
+ v_period_number := ((v_month - v_start_month_num + 12) % 12) + 1;
+ v_fiscal_year := CASE
+ WHEN v_start_month_num = 1 THEN v_year
+ WHEN v_month >= v_start_month_num THEN v_year + 1
+ ELSE v_year END;
+ UPDATE "accountingPeriod" SET "status" = 'Inactive'
+ WHERE "companyId" = v_elim_id AND "status" = 'Active';
+ BEGIN
+ INSERT INTO "accountingPeriod" (
+ "startDate", "endDate", "companyId", "status", "closeStatus",
+ "fiscalYear", "periodNumber", "createdBy"
+ ) VALUES (
+ v_period_start, v_period_end, v_elim_id, 'Active', 'Open',
+ v_fiscal_year, v_period_number, p_user_id
+ ) RETURNING "id" INTO v_period_id;
+ EXCEPTION WHEN unique_violation THEN
+ SELECT ap."id" INTO v_period_id FROM "accountingPeriod" ap
+ WHERE ap."companyId" = v_elim_id AND ap."startDate" <= v_today AND ap."endDate" >= v_today
+ ORDER BY ap."startDate" DESC LIMIT 1;
+ END;
+ END IF;
+
+ IF v_period_id IS NULL THEN
+ RAISE EXCEPTION 'Could not resolve an accounting period for elimination entity %', v_elim_id;
+ END IF;
+
+ -- (a) IC Balance: reverse every captured Control line (the reciprocal IC
+ -- Receivable / IC Payable) across both sides of the matched pair.
+ INSERT INTO "journal" (
+ "description", "accountingPeriodId", "companyId", "postingDate",
+ "journalEntryId", "sourceType", "eliminationKind"
+ ) VALUES (
+ 'IC Elimination: ' || v_rec."companyA" || ' ↔ ' || v_rec."companyB",
+ v_period_id, v_elim_id, v_today,
+ get_next_sequence('journalEntry', v_elim_id), 'Manual', 'IC Balance'
+ ) RETURNING "id" INTO v_journal_id;
+ v_balance_journal_id := v_journal_id; -- canonical elimination journal for the pair
+
+ INSERT INTO "journalLine" (
+ "journalId", "accountId", "description", "amount",
+ "documentType", "journalLineReference", "companyId"
+ )
+ SELECT v_journal_id, iel."accountId",
+ 'IC Elimination: ' || COALESCE(jl."description", ''),
+ -iel."amount", jl."documentType", 'ic-elim-' || v_journal_id::text, v_elim_id
+ FROM "intercompanyEliminationLine" iel
+ INNER JOIN "intercompanyTransaction" ict ON ict."id" = iel."intercompanyTransactionId"
+ INNER JOIN "journalLine" jl ON jl."id" = iel."journalLineId"
+ WHERE ict."companyGroupId" = p_company_group_id
+ AND ict."status" = 'Matched'
+ AND LEAST(ict."sourceCompanyId", ict."targetCompanyId") = v_rec."companyA"
+ AND GREATEST(ict."sourceCompanyId", ict."targetCompanyId") = v_rec."companyB"
+ AND iel."role" = 'Control';
+
+ GET DIAGNOSTICS v_line_count = ROW_COUNT;
+ IF v_line_count = 0 THEN
+ RAISE EXCEPTION 'No intercompany control lines to eliminate for pair % / % (capture missing — was the trade posted through the capture path?)',
+ v_rec."companyA", v_rec."companyB";
+ END IF;
+
+ v_journals_created := v_journals_created + 1;
+
+ -- (b) IC Revenue: eliminate PER TRADE (per matched seller<->buyer document),
+ -- not aggregated across the pair — so each buyer capitalization is written
+ -- down by ITS OWN trade's margin even when the pair has several trades with
+ -- different margins hitting different capitalization accounts. Matching set
+ -- each side's targetJournalLineId to the other's sourceJournalLineId, which
+ -- is the per-trade link.
+ FOR v_sale IN
+ SELECT DISTINCT s_ict."id" AS seller_ict, s_ict."targetJournalLineId" AS buyer_link
+ FROM "intercompanyTransaction" s_ict
+ INNER JOIN "intercompanyEliminationLine" rev
+ ON rev."intercompanyTransactionId" = s_ict."id" AND rev."role" = 'Revenue'
+ WHERE s_ict."companyGroupId" = p_company_group_id
+ AND s_ict."status" = 'Matched'
+ AND LEAST(s_ict."sourceCompanyId", s_ict."targetCompanyId") = v_rec."companyA"
+ AND GREATEST(s_ict."sourceCompanyId", s_ict."targetCompanyId") = v_rec."companyB"
+ LOOP
+ -- The matched buyer transaction carries this trade's Capitalization capture.
+ v_buyer_ict := NULL;
+ IF v_sale.buyer_link IS NOT NULL THEN
+ SELECT b."id" INTO v_buyer_ict
+ FROM "intercompanyTransaction" b
+ WHERE b."companyGroupId" = p_company_group_id
+ AND b."sourceJournalLineId" = v_sale.buyer_link
+ LIMIT 1;
+ END IF;
+
+ SELECT COALESCE(SUM(iel."amount"), 0) INTO v_revenue
+ FROM "intercompanyEliminationLine" iel
+ WHERE iel."intercompanyTransactionId" = v_sale.seller_ict AND iel."role" = 'Revenue';
+
+ SELECT COALESCE(SUM(iel."amount"), 0) INTO v_cogs
+ FROM "intercompanyEliminationLine" iel
+ WHERE iel."intercompanyTransactionId" = v_sale.seller_ict AND iel."role" = 'COGS';
+
+ -- Capitalized value + realized-weighted portion still on hand, for THIS
+ -- trade's buyer transaction. Fixed-asset / untracked lines count as fully
+ -- held (fraction 1); inventory lines use the buyer's current on-hand.
+ v_cap_total := 0;
+ v_cap_realized := 0;
+ IF v_buyer_ict IS NOT NULL THEN
+ FOR v_cap IN
+ SELECT iel."amount", iel."itemId", iel."quantity", iel."companyId" AS buyer
+ FROM "intercompanyEliminationLine" iel
+ WHERE iel."intercompanyTransactionId" = v_buyer_ict AND iel."role" = 'Capitalization'
+ LOOP
+ v_cap_total := v_cap_total + v_cap."amount";
+ IF v_cap."itemId" IS NULL OR v_cap."quantity" IS NULL OR v_cap."quantity" <= 0 THEN
+ v_cap_realized := v_cap_realized + v_cap."amount";
+ ELSE
+ SELECT COALESCE(SUM(il."quantity"), 0) INTO v_onhand
+ FROM "itemLedger" il
+ WHERE il."itemId" = v_cap."itemId" AND il."companyId" = v_cap."buyer";
+ v_cap_realized := v_cap_realized
+ + v_cap."amount" * (LEAST(GREATEST(v_onhand, 0), v_cap."quantity") / v_cap."quantity");
+ END IF;
+ END LOOP;
+ END IF;
+
+ -- Only eliminate a trade we can fully resolve (positive margin + a captured
+ -- buyer capitalization still partly on hand). Otherwise the IC Balance
+ -- elimination stands alone; never guess a writedown target.
+ CONTINUE WHEN NOT (v_revenue > 0 AND v_cap_total > 0 AND v_cap_realized > 0);
+
+ v_fraction := v_cap_realized / v_cap_total; -- (0, 1]
+ v_margin := v_revenue - v_cogs;
+
+ INSERT INTO "journal" (
+ "description", "accountingPeriodId", "companyId", "postingDate",
+ "journalEntryId", "sourceType", "eliminationKind"
+ ) VALUES (
+ 'IC Revenue Elimination: ' || v_rec."companyA" || ' ↔ ' || v_rec."companyB",
+ v_period_id, v_elim_id, v_today,
+ get_next_sequence('journalEntry', v_elim_id), 'Manual', 'IC Revenue'
+ ) RETURNING "id" INTO v_journal_id;
+
+ -- Reverse this trade's revenue (Dr Revenue), scaled by the on-hand fraction
+ -- so the entry balances against a partial writedown.
+ INSERT INTO "journalLine" (
+ "journalId", "accountId", "description", "amount",
+ "documentType", "journalLineReference", "companyId"
+ )
+ SELECT v_journal_id, iel."accountId",
+ 'IC Revenue Elimination: ' || COALESCE(jl."description", ''),
+ -iel."amount" * v_fraction, jl."documentType", 'ic-rev-' || v_journal_id::text, v_elim_id
+ FROM "intercompanyEliminationLine" iel
+ INNER JOIN "journalLine" jl ON jl."id" = iel."journalLineId"
+ WHERE iel."intercompanyTransactionId" = v_sale.seller_ict AND iel."role" = 'Revenue';
+
+ -- Reverse this trade's COGS (Cr COGS), same scaling.
+ INSERT INTO "journalLine" (
+ "journalId", "accountId", "description", "amount",
+ "documentType", "journalLineReference", "companyId"
+ )
+ SELECT v_journal_id, iel."accountId",
+ 'IC Revenue Elimination: reverse COGS',
+ -iel."amount" * v_fraction, jl."documentType", 'ic-rev-' || v_journal_id::text, v_elim_id
+ FROM "intercompanyEliminationLine" iel
+ INNER JOIN "journalLine" jl ON jl."id" = iel."journalLineId"
+ WHERE iel."intercompanyTransactionId" = v_sale.seller_ict AND iel."role" = 'COGS';
+
+ -- Write THIS trade's buyer capitalization down by ITS own unrealized margin,
+ -- split across the buyer's capitalization lines by captured value x on-hand
+ -- (total = margin x weighted fraction, so the journal balances).
+ FOR v_cap IN
+ SELECT iel."accountId", iel."amount", iel."itemId", iel."quantity", iel."companyId" AS buyer,
+ jl."description" AS jl_desc, jl."documentType" AS jl_doctype
+ FROM "intercompanyEliminationLine" iel
+ INNER JOIN "journalLine" jl ON jl."id" = iel."journalLineId"
+ WHERE iel."intercompanyTransactionId" = v_buyer_ict AND iel."role" = 'Capitalization'
+ LOOP
+ IF v_cap."itemId" IS NULL OR v_cap."quantity" IS NULL OR v_cap."quantity" <= 0 THEN
+ v_onhand := NULL; -- fixed asset / untracked → fraction 1
+ ELSE
+ SELECT COALESCE(SUM(il."quantity"), 0) INTO v_onhand
+ FROM "itemLedger" il
+ WHERE il."itemId" = v_cap."itemId" AND il."companyId" = v_cap."buyer";
+ END IF;
+
+ INSERT INTO "journalLine" (
+ "journalId", "accountId", "description", "amount",
+ "documentType", "journalLineReference", "companyId"
+ ) VALUES (
+ v_journal_id, v_cap."accountId",
+ 'IC Revenue Elimination: unrealized profit in ' || COALESCE(v_cap."jl_desc", 'buyer capitalization'),
+ -(v_margin
+ * (v_cap."amount" / v_cap_total)
+ * CASE
+ WHEN v_onhand IS NULL THEN 1
+ ELSE LEAST(GREATEST(v_onhand, 0), v_cap."quantity") / v_cap."quantity"
+ END),
+ v_cap."jl_doctype", 'ic-rev-' || v_journal_id::text, v_elim_id
+ );
+ END LOOP;
+
+ v_journals_created := v_journals_created + 1;
+ END LOOP;
+
+ -- Retire every matched row of the pair (both directions). Point
+ -- eliminationJournalId at the pair's IC Balance journal (the canonical
+ -- reversal of the control lines) — NOT the last IC Revenue journal, which
+ -- v_journal_id now holds and which is loop-order-dependent.
+ UPDATE "intercompanyTransaction"
+ SET "status" = 'Eliminated', "eliminationJournalId" = v_balance_journal_id, "updatedAt" = NOW()
+ WHERE "companyGroupId" = p_company_group_id
+ AND "status" = 'Matched'
+ AND LEAST("sourceCompanyId", "targetCompanyId") = v_rec."companyA"
+ AND GREATEST("sourceCompanyId", "targetCompanyId") = v_rec."companyB";
+ END LOOP;
+
+ RETURN v_journals_created;
+END;
+$$;
diff --git a/packages/database/supabase/tests/intercompany-elimination.test.sql b/packages/database/supabase/tests/intercompany-elimination.test.sql
new file mode 100644
index 0000000000..cc8e7d1517
--- /dev/null
+++ b/packages/database/supabase/tests/intercompany-elimination.test.sql
@@ -0,0 +1,278 @@
+-- Intercompany elimination — deterministic assertion harness.
+--
+-- Proves generateEliminationEntries across every bug class we have hit, WITHOUT
+-- any manual UI data entry: it seeds an intercompany trade at the journal +
+-- capture-line level (exactly what the posting edge functions write), runs the
+-- elimination, and ASSERTS the consolidated result — all inside one transaction
+-- that ROLLS BACK, so it touches no real data and re-runs in seconds.
+--
+-- Run against the local dev DB (reads existing companies/accounts by name/number
+-- so it survives resets):
+-- psql "$SUPABASE_DB_URL" -v ON_ERROR_STOP=1 \
+-- -f packages/database/supabase/tests/intercompany-elimination.test.sql
+--
+-- Any failed ASSERT aborts with the scenario name. "ALL SCENARIOS PASSED" at the
+-- end means the elimination engine is correct for: fixed-asset buyer (the
+-- negative-Finished-Goods bug), inventory buyer fully held, partial on-hand
+-- realization, transaction-dated posting (the out-of-window bug), balanced
+-- journals, and regenerate idempotency.
+
+\set ON_ERROR_STOP on
+BEGIN;
+
+-- Seed one matched intercompany trade + its capture lines, mirroring the edge
+-- functions. Seller books Dr IC-Receivable / Cr Sales / Dr COGS / Cr Finished
+-- Goods; buyer books Dr <capitalization> / Cr IC-Payable. Capitalization is
+-- posted to Machinery & Equipment (1350) so the assertions are isolated from any
+-- existing data (which nets to zero on 1130/2020/4010/5010 and never touches 1350).
+CREATE FUNCTION pg_temp.seed_ic_trade(
+ p_grp text,
+ p_seller text,
+ p_buyer text,
+ p_user text,
+ p_revenue numeric,
+ p_cogs numeric,
+ p_cap_item text, -- NULL = fixed asset (no on-hand tracking -> fully held)
+ p_cap_qty numeric,
+ p_onhand numeric, -- desired buyer on-hand of p_cap_item (ignored when NULL)
+ p_date date,
+ p_cap_num text DEFAULT '1350' -- account the buyer capitalizes into
+) RETURNS void AS $fn$
+DECLARE
+ a_icrec text; a_icpay text; a_sales text; a_cogs text; a_fg text; a_cap text;
+ j_s text; j_b text;
+ l_icrec text; l_sales text; l_cogs text; l_fg text; l_icpay text; l_cap text;
+ t_s text; t_b text;
+ ref text := 'harness-' || id();
+BEGIN
+ SELECT id INTO a_icrec FROM "account" WHERE "companyGroupId"=p_grp AND "number"='1130';
+ SELECT id INTO a_icpay FROM "account" WHERE "companyGroupId"=p_grp AND "number"='2020';
+ SELECT id INTO a_sales FROM "account" WHERE "companyGroupId"=p_grp AND "number"='4010';
+ SELECT id INTO a_cogs FROM "account" WHERE "companyGroupId"=p_grp AND "number"='5010';
+ SELECT id INTO a_fg FROM "account" WHERE "companyGroupId"=p_grp AND "number"='1220';
+ SELECT id INTO a_cap FROM "account" WHERE "companyGroupId"=p_grp AND "number"=p_cap_num;
+
+ -- Seller sale journal
+ INSERT INTO "journal"("companyId","journalEntryId","postingDate","description","sourceType")
+ VALUES (p_seller,'HS-'||ref,p_date,'Harness sale','Sales Invoice') RETURNING id INTO j_s;
+ INSERT INTO "journalLine"("journalId","accountId","amount","journalLineReference","companyId","documentType","documentId")
+ VALUES (j_s,a_icrec, p_revenue, ref,p_seller,'Invoice','HARNESS-SALE') RETURNING id INTO l_icrec;
+ INSERT INTO "journalLine"("journalId","accountId","amount","journalLineReference","companyId","documentType","documentId")
+ VALUES (j_s,a_sales, p_revenue, ref,p_seller,'Invoice','HARNESS-SALE') RETURNING id INTO l_sales;
+ INSERT INTO "journalLine"("journalId","accountId","amount","journalLineReference","companyId","documentType","documentId")
+ VALUES (j_s,a_cogs, p_cogs, ref,p_seller,'Invoice','HARNESS-SALE') RETURNING id INTO l_cogs;
+ INSERT INTO "journalLine"("journalId","accountId","amount","journalLineReference","companyId","documentType","documentId")
+ VALUES (j_s,a_fg, -p_cogs, ref,p_seller,'Invoice','HARNESS-SALE') RETURNING id INTO l_fg;
+
+ -- Buyer purchase journal (capitalizes the goods at the transfer price)
+ INSERT INTO "journal"("companyId","journalEntryId","postingDate","description","sourceType")
+ VALUES (p_buyer,'HB-'||ref,p_date,'Harness purchase','Purchase Invoice') RETURNING id INTO j_b;
+ INSERT INTO "journalLine"("journalId","accountId","amount","journalLineReference","companyId","documentType","documentId")
+ VALUES (j_b,a_cap, p_revenue, ref,p_buyer,'Invoice','HARNESS-PURCH') RETURNING id INTO l_cap;
+ INSERT INTO "journalLine"("journalId","accountId","amount","journalLineReference","companyId","documentType","documentId")
+ VALUES (j_b,a_icpay, p_revenue, ref,p_buyer,'Invoice','HARNESS-PURCH') RETURNING id INTO l_icpay;
+
+ -- Matched intercompany transactions (both directions). targetJournalLineId is
+ -- the per-trade seller<->buyer link that matchIntercompanyTransactions sets:
+ -- each side points at the other's sourceJournalLineId.
+ INSERT INTO "intercompanyTransaction"("companyGroupId","sourceCompanyId","targetCompanyId","sourceJournalLineId","targetJournalLineId","amount","currencyCode","status","documentType","documentId")
+ VALUES (p_grp,p_seller,p_buyer,l_icrec,l_icpay,p_revenue,'USD','Matched','Invoice','HARNESS-SALE') RETURNING id INTO t_s;
+ INSERT INTO "intercompanyTransaction"("companyGroupId","sourceCompanyId","targetCompanyId","sourceJournalLineId","targetJournalLineId","amount","currencyCode","status","documentType","documentId")
+ VALUES (p_grp,p_buyer,p_seller,l_icpay,l_icrec,p_revenue,'USD','Matched','Invoice','HARNESS-PURCH') RETURNING id INTO t_b;
+
+ -- Capture lines (what the edge functions record)
+ INSERT INTO "intercompanyEliminationLine"("companyId","intercompanyTransactionId","role","journalLineId","accountId","amount","itemId","quantity","createdBy") VALUES
+ (p_seller,t_s,'Control',l_icrec,a_icrec,p_revenue,NULL,NULL,p_user),
+ (p_seller,t_s,'Revenue',l_sales,a_sales,p_revenue,NULL,NULL,p_user),
+ (p_seller,t_s,'COGS', l_cogs, a_cogs, p_cogs, NULL,NULL,p_user),
+ (p_buyer, t_b,'Control',l_icpay,a_icpay,p_revenue,NULL,NULL,p_user),
+ (p_buyer, t_b,'Capitalization',l_cap,a_cap,p_revenue,p_cap_item,p_cap_qty,p_user);
+
+ -- Buyer on-hand for realization (only when the buyer holds a tracked item).
+ -- Set net on-hand to exactly p_onhand regardless of any existing ledger.
+ IF p_cap_item IS NOT NULL THEN
+ INSERT INTO "itemLedger"("entryType","itemId","companyId","quantity")
+ VALUES ('Positive Adjmt.', p_cap_item, p_buyer,
+ p_onhand - COALESCE((SELECT SUM("quantity") FROM "itemLedger" WHERE "itemId"=p_cap_item AND "companyId"=p_buyer),0));
+ END IF;
+END $fn$ LANGUAGE plpgsql;
+
+-- Shared: assert every elimination journal dated p_date balances (debits=credits).
+CREATE FUNCTION pg_temp.assert_balanced(p_grp text, p_date date, p_label text) RETURNS void AS $fn$
+DECLARE r record;
+BEGIN
+ FOR r IN
+ SELECT j."id",
+ round(sum(CASE WHEN a."class" IN ('Asset','Expense') THEN jl."amount" ELSE -jl."amount" END),5) AS debit_minus_credit
+ FROM "journal" j
+ JOIN "company" c ON c."id"=j."companyId"
+ JOIN "journalLine" jl ON jl."journalId"=j."id"
+ JOIN "account" a ON a."id"=jl."accountId"
+ WHERE c."companyGroupId"=p_grp AND c."isEliminationEntity" AND j."eliminationKind" IS NOT NULL
+ AND j."postingDate"=p_date
+ GROUP BY j."id"
+ LOOP
+ ASSERT r.debit_minus_credit = 0, p_label || ': elimination journal '||r.id||' is unbalanced ('||r.debit_minus_credit||')';
+ END LOOP;
+END $fn$ LANGUAGE plpgsql;
+
+-- Consolidated (group-wide, incl. elimination entity) net for an account number,
+-- optionally as-of a date.
+CREATE FUNCTION pg_temp.consol(p_grp text, p_num text, p_asof date DEFAULT NULL) RETURNS numeric AS $fn$
+ SELECT round(COALESCE(sum(jl."amount"),0),5)
+ FROM "journalLine" jl
+ JOIN "journal" j ON j."id"=jl."journalId"
+ JOIN "company" c ON c."id"=jl."companyId"
+ JOIN "account" a ON a."id"=jl."accountId"
+ WHERE c."companyGroupId"=p_grp AND a."number"=p_num
+ AND (p_asof IS NULL OR j."postingDate" <= p_asof);
+$fn$ LANGUAGE sql;
+
+DO $main$
+DECLARE
+ v_grp text; v_seller text; v_buyer text; v_user text; v_item text;
+ v_parent text; v_elim text; v_ref text;
+ d date := DATE '2026-03-15'; -- distinct from any existing data
+ n int;
+ -- SQLSTATE 22000 is our sentinel to unwind a scenario's data via the block's
+ -- implicit savepoint. A real ASSERT failure raises P0004, which is NOT caught
+ -- and therefore propagates and aborts the whole run.
+BEGIN
+ -- Self-provision an isolated intercompany group so the harness does not depend
+ -- on any manually-built scenario (a DB reset wipes those). Reuse an existing
+ -- company as the BUYER — it already has the group's shared chart of accounts,
+ -- items, and an employee — and provision parent/seller/elimination siblings by
+ -- copying its row. Everything rolls back with the outer transaction.
+ v_ref := id();
+ SELECT c."id", c."companyGroupId" INTO v_buyer, v_grp
+ FROM "company" c WHERE c."isEliminationEntity" = false
+ ORDER BY c."createdAt" LIMIT 1;
+ SELECT utc."userId" INTO v_user FROM "userToCompany" utc
+ JOIN "company" c ON c."id" = utc."companyId"
+ WHERE c."companyGroupId" = v_grp AND utc."role" = 'employee' LIMIT 1;
+ SELECT i."id" INTO v_item FROM "item" i WHERE i."companyId" = v_buyer LIMIT 1;
+
+ v_parent := id(); v_seller := id(); v_elim := id();
+ CREATE TEMP TABLE _co ON COMMIT DROP AS SELECT * FROM "company" WHERE "id" = v_buyer;
+ UPDATE _co SET "id"=v_parent, "name"='Harness Parent '||v_ref, "parentCompanyId"=NULL, "isEliminationEntity"=false;
+ INSERT INTO "company" SELECT * FROM _co;
+ UPDATE _co SET "id"=v_seller, "name"='Harness Seller '||v_ref, "parentCompanyId"=v_parent;
+ INSERT INTO "company" SELECT * FROM _co;
+ UPDATE _co SET "id"=v_elim, "name"='Harness Elim '||v_ref, "isEliminationEntity"=true;
+ INSERT INTO "company" SELECT * FROM _co;
+ UPDATE "company" SET "parentCompanyId"=v_parent WHERE "id"=v_buyer; -- buyer under the parent
+
+ -- The elimination entity needs its own journalEntry sequence + fiscal settings
+ -- (the RPC calls get_next_sequence and get-or-creates a period on it).
+ -- sequence.id is a generated column, so copy explicit columns and let it regenerate.
+ INSERT INTO "sequence" ("table","name","prefix","suffix","next","size","step","companyId","updatedBy")
+ SELECT "table","name","prefix","suffix","next","size","step", v_elim, "updatedBy"
+ FROM "sequence" WHERE "table"='journalEntry' AND "companyId"=v_buyer LIMIT 1;
+ CREATE TEMP TABLE _fys ON COMMIT DROP AS
+ SELECT * FROM "fiscalYearSettings" WHERE "companyId"=v_buyer LIMIT 1;
+ UPDATE _fys SET "companyId"=v_elim;
+ INSERT INTO "fiscalYearSettings" SELECT * FROM _fys;
+
+ -- Scenario 1: FIXED-ASSET buyer, fully held (the negative-Finished-Goods bug).
+ -- revenue 100, cost 60, margin 40; buyer capitalizes a fixed asset (no item).
+ -- IC accounts + Sales + COGS eliminate to 0; the buyer's asset lands at group
+ -- cost 60 (not overstated at 100, not driven negative).
+ BEGIN
+ PERFORM pg_temp.seed_ic_trade(v_grp,v_seller,v_buyer,v_user, 100,60, NULL,NULL,NULL, d);
+ PERFORM "generateEliminationEntries"(v_grp,v_user);
+ ASSERT pg_temp.consol(v_grp,'1130')=0, 'S1 fixed-asset: IC Receivables not eliminated';
+ ASSERT pg_temp.consol(v_grp,'2020')=0, 'S1 fixed-asset: IC Payables not eliminated';
+ ASSERT pg_temp.consol(v_grp,'4010')=0, 'S1 fixed-asset: Sales not eliminated';
+ ASSERT pg_temp.consol(v_grp,'5010')=0, 'S1 fixed-asset: COGS not eliminated';
+ ASSERT pg_temp.consol(v_grp,'1350')=60, 'S1 fixed-asset: buyer asset not at group cost (expected 60, got '||pg_temp.consol(v_grp,'1350')||')';
+ PERFORM pg_temp.assert_balanced(v_grp,d,'S1 fixed-asset');
+ -- eliminationJournalId must point to the pair's IC Balance journal, not the
+ -- last IC Revenue journal (loop-order-dependent).
+ ASSERT (
+ SELECT bool_and(j."eliminationKind" = 'IC Balance')
+ FROM "intercompanyTransaction" ict
+ JOIN "journal" j ON j."id" = ict."eliminationJournalId"
+ WHERE ict."companyGroupId"=v_grp AND ict."status"='Eliminated'
+ AND ict."documentId" IN ('HARNESS-SALE','HARNESS-PURCH')
+ ), 'S1 fixed-asset: eliminationJournalId does not point to the IC Balance journal';
+ RAISE NOTICE 'S1 fixed-asset buyer, fully held ....... PASS';
+ RAISE SQLSTATE '22000';
+ EXCEPTION WHEN SQLSTATE '22000' THEN NULL; END;
+
+ -- Scenario 2: INVENTORY buyer, fully held (on-hand >= traded qty -> fraction 1).
+ BEGIN
+ PERFORM pg_temp.seed_ic_trade(v_grp,v_seller,v_buyer,v_user, 100,60, v_item,5,5, d);
+ PERFORM "generateEliminationEntries"(v_grp,v_user);
+ ASSERT pg_temp.consol(v_grp,'4010')=0, 'S2 inventory-held: Sales not fully eliminated';
+ ASSERT pg_temp.consol(v_grp,'5010')=0, 'S2 inventory-held: COGS not fully eliminated';
+ ASSERT pg_temp.consol(v_grp,'1350')=60, 'S2 inventory-held: buyer inventory not at group cost';
+ PERFORM pg_temp.assert_balanced(v_grp,d,'S2 inventory-held');
+ RAISE NOTICE 'S2 inventory buyer, fully held ......... PASS';
+ RAISE SQLSTATE '22000';
+ EXCEPTION WHEN SQLSTATE '22000' THEN NULL; END;
+
+ -- Scenario 3: INVENTORY buyer, PARTIAL realization (on-hand 2 of qty 5 -> 0.4).
+ -- margin 40; defer only 40*0.4 = 16. Reversal scales by 0.4: Sales left 60,
+ -- COGS left 36, asset = 100 - 16 = 84. Journal still balances.
+ BEGIN
+ PERFORM pg_temp.seed_ic_trade(v_grp,v_seller,v_buyer,v_user, 100,60, v_item,5,2, d);
+ PERFORM "generateEliminationEntries"(v_grp,v_user);
+ ASSERT pg_temp.consol(v_grp,'4010')=60, 'S3 partial: Sales expected 60, got '||pg_temp.consol(v_grp,'4010');
+ ASSERT pg_temp.consol(v_grp,'5010')=36, 'S3 partial: COGS expected 36, got '||pg_temp.consol(v_grp,'5010');
+ ASSERT pg_temp.consol(v_grp,'1350')=84, 'S3 partial: buyer asset expected 84, got '||pg_temp.consol(v_grp,'1350');
+ PERFORM pg_temp.assert_balanced(v_grp,d,'S3 partial');
+ RAISE NOTICE 'S3 inventory buyer, partial realization PASS';
+ RAISE SQLSTATE '22000';
+ EXCEPTION WHEN SQLSTATE '22000' THEN NULL; END;
+
+ -- Scenario 4: DATE WINDOW (the IC-payables-summing-wrong bug). The elimination
+ -- must be dated to the transaction (2026-03-15), not the elimination entity's
+ -- today. As-of the transaction date the balance is 0.
+ BEGIN
+ PERFORM pg_temp.seed_ic_trade(v_grp,v_seller,v_buyer,v_user, 100,60, NULL,NULL,NULL, d);
+ PERFORM "generateEliminationEntries"(v_grp,v_user);
+ SELECT count(*) INTO n FROM "journal" j JOIN "company" c ON c."id"=j."companyId"
+ WHERE c."companyGroupId"=v_grp AND c."isEliminationEntity" AND j."eliminationKind" IS NOT NULL AND j."postingDate"=d;
+ ASSERT n >= 1, 'S4 date-window: no elimination journal dated to the transaction ('||d||')';
+ ASSERT pg_temp.consol(v_grp,'2020',d)=0, 'S4 date-window: IC Payables not 0 as-of the transaction date';
+ ASSERT pg_temp.consol(v_grp,'1130',d)=0, 'S4 date-window: IC Receivables not 0 as-of the transaction date';
+ RAISE NOTICE 'S4 elimination dated to transaction .... PASS';
+ RAISE SQLSTATE '22000';
+ EXCEPTION WHEN SQLSTATE '22000' THEN NULL; END;
+
+ -- Scenario 5: REGENERATE idempotency. Generate, then regenerate (reverses +
+ -- re-derives). The consolidated result must be unchanged — no double counting.
+ BEGIN
+ PERFORM pg_temp.seed_ic_trade(v_grp,v_seller,v_buyer,v_user, 100,60, NULL,NULL,NULL, d);
+ PERFORM "generateEliminationEntries"(v_grp,v_user);
+ PERFORM "generateEliminationEntries"(v_grp,v_user, true); -- regenerate
+ ASSERT pg_temp.consol(v_grp,'1130')=0, 'S5 regenerate: IC Receivables drifted';
+ ASSERT pg_temp.consol(v_grp,'2020')=0, 'S5 regenerate: IC Payables drifted';
+ ASSERT pg_temp.consol(v_grp,'4010')=0, 'S5 regenerate: Sales drifted';
+ ASSERT pg_temp.consol(v_grp,'1350')=60, 'S5 regenerate: buyer asset drifted from group cost';
+ RAISE NOTICE 'S5 regenerate idempotency ............. PASS';
+ RAISE SQLSTATE '22000';
+ EXCEPTION WHEN SQLSTATE '22000' THEN NULL; END;
+
+ -- Scenario 6: MULTI-TRADE per pair with DIFFERENT margins and DIFFERENT
+ -- capitalization accounts (the per-trade-allocation fix). Two fixed-asset
+ -- trades between the same pair: A (margin 40 -> Machinery 1350) and B (margin
+ -- 10 -> Fixed Asset Acquisition Cost 1310). Each asset must land at ITS OWN
+ -- group cost (60 and 90). Pair-level aggregation would wrongly give 75 / 75.
+ BEGIN
+ PERFORM pg_temp.seed_ic_trade(v_grp,v_seller,v_buyer,v_user, 100,60, NULL,NULL,NULL, d, '1350');
+ PERFORM pg_temp.seed_ic_trade(v_grp,v_seller,v_buyer,v_user, 100,90, NULL,NULL,NULL, d, '1310');
+ PERFORM "generateEliminationEntries"(v_grp,v_user);
+ ASSERT pg_temp.consol(v_grp,'4010')=0, 'S6 multi-trade: Sales not fully eliminated';
+ ASSERT pg_temp.consol(v_grp,'5010')=0, 'S6 multi-trade: COGS not fully eliminated';
+ ASSERT pg_temp.consol(v_grp,'1350')=60, 'S6 multi-trade: trade A asset expected 60 (per-trade), got '||pg_temp.consol(v_grp,'1350');
+ ASSERT pg_temp.consol(v_grp,'1310')=90, 'S6 multi-trade: trade B asset expected 90 (per-trade), got '||pg_temp.consol(v_grp,'1310');
+ PERFORM pg_temp.assert_balanced(v_grp,d,'S6 multi-trade');
+ RAISE NOTICE 'S6 multi-trade, per-trade allocation ... PASS';
+ RAISE SQLSTATE '22000';
+ EXCEPTION WHEN SQLSTATE '22000' THEN NULL; END;
+
+ RAISE NOTICE '================= ALL SCENARIOS PASSED =================';
+END $main$;
+
+ROLLBACK;
diff --git a/packages/react/src/Card.tsx b/packages/react/src/Card.tsx
index b9bc53d13a..fbbbe07614 100644
--- a/packages/react/src/Card.tsx
+++ b/packages/react/src/Card.tsx
@@ -46,7 +46,7 @@ const Card = forwardRef<HTMLDivElement, CardProps>(
<div
ref={ref}
className={cn(
- "relative flex flex-col rounded-lg shadow-button-base dark:shadow-[inset_0_0.5px_0_rgb(255_255_255_/_0.08),_inset_0_0_1px_rgb(255_255_255_/_0.24),_0_0_0_0.5px_rgb(0,0,0,1),0px_0px_4px_rgba(0,_0,_0,_0.08)] bg-accent dark:bg-card text-card-foreground p-0 w-full",
+ "relative flex flex-col rounded-xl shadow-button-base dark:shadow-[inset_0_0.5px_0_rgb(255_255_255_/_0.08),_inset_0_0_1px_rgb(255_255_255_/_0.24),_0_0_0_0.5px_rgb(0,0,0,1),0px_0px_4px_rgba(0,_0,_0,_0.08)] bg-accent dark:bg-card text-card-foreground p-0 w-full",
className
)}
{...props}
@@ -198,7 +198,7 @@ const CardContent = forwardRef<HTMLDivElement, HTMLAttributes<HTMLDivElement>>(
<div
ref={ref}
className={cn(
- "flex flex-col flex-1 p-6 rounded-lg border border-border bg-card dark:bg-muted/40",
+ "flex flex-col flex-1 p-6 rounded-xl border border-border bg-card dark:bg-muted/40",
className
)}
{...props}
diff --git a/packages/react/src/Modal.tsx b/packages/react/src/Modal.tsx
index 3508bdd55d..33788bb14f 100644
--- a/packages/react/src/Modal.tsx
+++ b/packages/react/src/Modal.tsx
@@ -49,7 +49,7 @@ const ModalContentVariants = cva(
"data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95",
"data-[state=closed]:slide-out-to-left-[0%] data-[state=closed]:slide-out-to-top-[0%",
"data-[state=open]:slide-in-from-left-[0%] data-[state=open]:slide-in-from-top-[0%]",
- "sm:rounded-xl md:w-full",
+ "sm:rounded-2xl md:w-full",
"bg-background focus-visible:outline-none focus-visible:ring-0",
"dark:shadow-[inset_0_0.5px_0_rgb(255_255_255_/_0.08),_inset_0_0_1px_rgb(255_255_255_/_0.24),_0_0_0_0.5px_rgb(0,0,0,1),0px_0px_4px_rgba(0,_0,_0,_0.08)]"
),
@@ -130,7 +130,7 @@ const ModalFooter = ({
}: HTMLAttributes<HTMLDivElement>) => (
<div
className={cn(
- "flex flex-col-reverse sm:flex-row sm:justify-end gap-2 px-6 py-3 border-t border-border bg-muted/40 sm:rounded-b-xl",
+ "flex flex-col-reverse sm:flex-row sm:justify-end gap-2 px-6 py-3 border-t border-border bg-muted/40 sm:rounded-b-2xl",
className
)}
{...props}