Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
fix(accounting): complete intercompany invoice posting, matching, and elimination (#1402)
Brad Barbin9f8d61b8f2cb
diff --git a/apps/erp/app/modules/accounting/accounting.ee.service.ts b/apps/erp/app/modules/accounting/accounting.ee.service.tsindex 80a8a79dce..b7e135a144 100644--- a/apps/erp/app/modules/accounting/accounting.ee.service.ts+++ b/apps/erp/app/modules/accounting/accounting.ee.service.ts@@ -4400,8 +4400,7 @@ export async function createIntercompanyTransaction(amount: input.amount,journalLineReference: journalLineRef,intercompanyPartnerId: input.targetCompanyId,- companyId: input.sourceCompanyId,- companyGroupId: input.companyGroupId+ companyId: input.sourceCompanyId},{journalId,@@ -4410,8 +4409,7 @@ export async function createIntercompanyTransaction(amount: -input.amount,journalLineReference: journalLineRef,intercompanyPartnerId: input.targetCompanyId,- companyId: input.sourceCompanyId,- companyGroupId: input.companyGroupId+ companyId: input.sourceCompanyId}]).select("id");diff --git a/apps/erp/app/modules/agent/kb/docs/reference/intercompany.md b/apps/erp/app/modules/agent/kb/docs/reference/intercompany.mdindex b5ad31e8f5..e22d7c1782 100644--- a/apps/erp/app/modules/agent/kb/docs/reference/intercompany.md+++ b/apps/erp/app/modules/agent/kb/docs/reference/intercompany.md@@ -8,9 +8,20 @@ The whole feature is scoped to a **company group**, and it only appears once a g## What a transaction is-An intercompany transaction records that one company in the group owes or is owed by another. You create one from the accounting **Intercompany** screen with **New IC Transaction**, choosing a **source company** and a **target company** (they must be different), an amount, a description, and the two accounts to hit.+An intercompany transaction records that one company in the group owes or is owed by another. Most are created for you: when you post a sales or purchase invoice whose customer or supplier is a **sibling company in the group**, Carbon writes the matching intercompany transaction as part of posting the invoice.-Creating it does real bookkeeping on the source company. Carbon writes a balanced journal on the source: a **debit** line to the account you pick and a matching **credit** line, both tagged with the target company as the **intercompany partner**. The currency defaults to the source company's base currency. So an intercompany transaction is not a note. It is a posted journal on one company, plus a tracking record that remembers which sibling it was with.+A customer or supplier counts as a sibling when it is linked to another company in the group. Carbon creates those links the moment a company joins the group, so a normal invoice between two group members is intercompany without any extra flagging.++- Posting an **intercompany sales invoice** books the receivable to the group's **Inter-Company Receivables** control account instead of regular AR, and records a transaction from the seller to the buyer for the invoice's pre-tax total.+- Posting an **intercompany purchase invoice** books the payable to the **Inter-Company Payables** control account instead of regular AP, and records the mirror transaction from the buyer to the seller for the invoice's pre-tax total.++Both control accounts come from the group's accounting defaults, so members that have them configured post against the same two accounts. A company that hasn't configured them falls back to its regular receivables or payables account.++The transaction is a byproduct of posting the invoice, not a separate step. The receivable or payable is already on the ledger the moment the invoice posts. The transaction record just remembers which sibling it was with, so matching and elimination can find the pair later.++### Recording one by hand++You can also create a transaction directly from the accounting **Intercompany** screen with **New IC Transaction**, choosing a **source company** and a **target company** (they must be different), an amount, a description, and the two accounts to hit. This posts a balanced journal on the source company — a debit line to one account and a matching credit to the other, both tagged with the target as the **intercompany partner** — plus the tracking record. Use it for an adjustment, or for a position no invoice created.The source and target are picked from the group's active companies, and **elimination entities are excluded** from that list. You transact between real operating companies. The elimination entity is where the cancelling entries land later, not a party to the trade.@@ -30,7 +41,7 @@ Matching is a manual, run-on-demand step, not something that happens as you postThe rule is deliberately strict. Two **Unmatched** transactions match only when they are true mirror images: company A → B pairs with company B → A, for the **exact same amount**, within the same group. When Carbon finds such a pair it sets both to **"Matched"** in one step and links each to the other's journal line. The result toast tells you how many matched and how many are still unmatched.-If a transaction stays **Unmatched** after a run, its mirror does not exist yet. The usual cause is that the sibling company has not booked its side, or booked it for a different amount. Create or correct the counterpart, then run matching again.+If a transaction stays **Unmatched** after a run, its mirror does not exist yet. The usual cause is that the sibling company has not posted its invoice yet, or the two invoices are for different amounts. Post or correct the counterpart, then run matching again.Matching pairs the two sides. It does **not** post anything new or touch either company's ledger. The journals were written when you created each transaction; matching only records that they belong together and advances their status.@@ -38,7 +49,9 @@ Matching pairs the two sides. It does **not** post anything new or touch eitherMatching sets the stage. **Elimination** is what actually removes the double-count for consolidated reporting. It, too, is a manual sweep: **Generate Eliminations** processes every **Matched** pair in the group.-For each matched pair, Carbon posts a single **elimination journal** whose lines are the sign-reversed copies of both sides' original journal lines. That journal is booked not on either operating company but on a dedicated **elimination entity** — a special company in the group flagged for this purpose. Carbon routes the entry to the elimination entity belonging to the **lowest common parent** of the two transacting companies, which is what makes multi-tier hierarchies (parent-child, sibling, cousin) consolidate correctly; if there isn't one at that level it falls back to any elimination entity in the group, and if the group has none the run fails.+For each matched pair, Carbon posts a single **elimination journal** that reverses the intercompany control-account entries on both sides. Each transaction points at one control line; from it, Carbon takes that line's account and document and reverses every line the same invoice posted to that account — the seller's **Inter-Company Receivables** and the buyer's **Inter-Company Payables** — booking the sign-reversed amounts. Because it reverses the actual ledger lines for the whole document, a multi-line invoice is cleared in full, not just its first line, and both control accounts clear to their exact balance with no rounding residual. The seller's receivable and the buyer's payable are equal and opposite, so the elimination journal balances. Each reciprocal pair is processed once.++That journal is booked not on either operating company but on a dedicated **elimination entity** — a special company in the group flagged for this purpose. Carbon routes the entry to the elimination entity belonging to the **lowest common parent** of the two transacting companies, which is what makes multi-tier hierarchies (parent-child, sibling, cousin) consolidate correctly; if there isn't one at that level it falls back to any elimination entity in the group, and if the group has none the run fails.Once the reversing journal is posted, the pair flips to **"Eliminated"** and the elimination journal is recorded on each transaction. The run returns a count of the journals it created.@@ -79,4 +92,4 @@ An intercompany transaction is between two companies. Pick a target company otheRunning matching or elimination requires being an employee of a company in the group with accounting-create permission. Both actions sweep the entire group, so the check is against group membership, not just the active company.### A transaction stays "Unmatched" after Run Matching-No mirror-image transaction exists. Matching only pairs an A → B transaction with a B → A transaction for the **exact same amount** in the same group. Confirm the sibling company has booked its side for the identical amount, then run matching again.+No mirror-image transaction exists. Matching only pairs an A → B transaction with a B → A transaction for the **exact same amount** in the same group. Confirm the sibling company has posted its invoice for the identical amount (or booked a manual counterpart), then run matching again.diff --git a/apps/erp/app/modules/agent/kb/manifest.json b/apps/erp/app/modules/agent/kb/manifest.jsonindex dc00f51bc5..016ea59c34 100644--- a/apps/erp/app/modules/agent/kb/manifest.json+++ b/apps/erp/app/modules/agent/kb/manifest.json@@ -694,6 +694,7 @@"keywords": ["intercompany", "accounting", "docs", "reference"],"headings": ["What a transaction is",+ "Recording one by hand","The matching lifecycle","How a pair gets matched","Elimination",diff --git a/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json b/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.jsonindex 2774859990..29221a7e48 100644--- a/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json+++ b/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json@@ -1,5 +1,5 @@{- "generated": "2026-08-15T21:38:08.771Z",+ "generated": "2026-08-16T23:17:39.255Z","totalTools": 1442,"modules": 15,"tools": [diff --git a/docs/content/docs/reference/intercompany.mdx b/docs/content/docs/reference/intercompany.mdxindex 6ee9c96d8a..368bc9c351 100644--- a/docs/content/docs/reference/intercompany.mdx+++ b/docs/content/docs/reference/intercompany.mdx@@ -9,9 +9,22 @@ The whole feature is scoped to a **<Term>company group</Term>**, and it only app## What a transaction is-An intercompany transaction records that one company in the group owes or is owed by another. You create one from the accounting **Intercompany** screen with **New IC Transaction**, choosing a **source company** and a **target company** (they must be different), an amount, a description, and the two accounts to hit.+An intercompany transaction records that one company in the group owes or is owed by another. Most are created for you: when you post a sales or purchase invoice whose customer or supplier is a **sibling company in the group**, Carbon writes the matching intercompany transaction as part of posting the invoice.-Creating it does real bookkeeping on the source company. Carbon writes a balanced <Term>journal</Term> on the source: a **debit** line to the account you pick and a matching **credit** line, both tagged with the target company as the **intercompany partner**. The currency defaults to the source company's base currency. So an intercompany transaction is not a note. It is a posted journal on one company, plus a tracking record that remembers which sibling it was with.+A customer or supplier counts as a sibling when it is linked to another company in the group. Carbon creates those links the moment a company joins the group, so a normal invoice between two group members is intercompany without any extra flagging.++- Posting an **intercompany sales invoice** books the receivable to the group's **Inter-Company Receivables** control account instead of regular AR, and records a transaction from the seller to the buyer for the invoice's pre-tax total.+- Posting an **intercompany purchase invoice** books the payable to the **Inter-Company Payables** control account instead of regular AP, and records the mirror transaction from the buyer to the seller for the invoice's pre-tax total.++Both control accounts come from the group's accounting defaults, so members that have them configured post against the same two accounts. A company that hasn't configured them falls back to its regular receivables or payables account.++<Callout type="note" title="The invoice posting is the source of truth">+The transaction is a byproduct of posting the invoice, not a separate step. The receivable or payable is already on the ledger the moment the invoice posts. The transaction record just remembers which sibling it was with, so matching and elimination can find the pair later.+</Callout>++### Recording one by hand++You can also create a transaction directly from the accounting **Intercompany** screen with **New IC Transaction**, choosing a **source company** and a **target company** (they must be different), an amount, a description, and the two accounts to hit. This posts a balanced <Term>journal</Term> on the source company — a debit line to one account and a matching credit to the other, both tagged with the target as the **intercompany partner** — plus the tracking record. Use it for an adjustment, or for a position no invoice created.<Callout type="note">The source and target are picked from the group's active companies, and **elimination entities are excluded** from that list. You transact between real operating companies. The <Term id="elimination-entity">elimination entity</Term> is where the cancelling entries land later, not a party to the trade.@@ -35,7 +48,7 @@ Matching is a manual, run-on-demand step, not something that happens as you postThe rule is deliberately strict. Two **Unmatched** transactions match only when they are true mirror images: company A → B pairs with company B → A, for the **exact same amount**, within the same group. When Carbon finds such a pair it sets both to **"Matched"** in one step and links each to the other's journal line. The result toast tells you how many matched and how many are still unmatched.-If a transaction stays **Unmatched** after a run, its mirror does not exist yet. The usual cause is that the sibling company has not booked its side, or booked it for a different amount. Create or correct the counterpart, then run matching again.+If a transaction stays **Unmatched** after a run, its mirror does not exist yet. The usual cause is that the sibling company has not posted its invoice yet, or the two invoices are for different amounts. Post or correct the counterpart, then run matching again.<Callout type="note">Matching pairs the two sides. It does **not** post anything new or touch either company's ledger. The journals were written when you created each transaction; matching only records that they belong together and advances their status.@@ -45,7 +58,9 @@ Matching pairs the two sides. It does **not** post anything new or touch eitherMatching sets the stage. **Elimination** is what actually removes the double-count for consolidated reporting. It, too, is a manual sweep: **Generate Eliminations** processes every **Matched** pair in the group.-For each matched pair, Carbon posts a single **elimination journal** whose lines are the sign-reversed copies of both sides' original journal lines. That journal is booked not on either operating company but on a dedicated **elimination entity** — a special company in the group flagged for this purpose. Carbon routes the entry to the elimination entity belonging to the **lowest common parent** of the two transacting companies, which is what makes multi-tier hierarchies (parent-child, sibling, cousin) consolidate correctly; if there isn't one at that level it falls back to any elimination entity in the group, and if the group has none the run fails.+For each matched pair, Carbon posts a single **elimination journal** that reverses the intercompany control-account entries on both sides. Each transaction points at one control line; from it, Carbon takes that line's account and document and reverses every line the same invoice posted to that account — the seller's **Inter-Company Receivables** and the buyer's **Inter-Company Payables** — booking the sign-reversed amounts. Because it reverses the actual ledger lines for the whole document, a multi-line invoice is cleared in full, not just its first line, and both control accounts clear to their exact balance with no rounding residual. The seller's receivable and the buyer's payable are equal and opposite, so the elimination journal balances. Each reciprocal pair is processed once.++That journal is booked not on either operating company but on a dedicated **elimination entity** — a special company in the group flagged for this purpose. Carbon routes the entry to the elimination entity belonging to the **lowest common parent** of the two transacting companies, which is what makes multi-tier hierarchies (parent-child, sibling, cousin) consolidate correctly; if there isn't one at that level it falls back to any elimination entity in the group, and if the group has none the run fails.Once the reversing journal is posted, the pair flips to **"Eliminated"** and the elimination journal is recorded on each transaction. The run returns a count of the journals it created.@@ -95,5 +110,5 @@ An intercompany transaction is between two companies. Pick a target company otheRunning matching or elimination requires being an employee of a company in the group with accounting-create permission. Both actions sweep the entire group, so the check is against group membership, not just the active company.### A transaction stays "Unmatched" after Run Matching-No mirror-image transaction exists. Matching only pairs an A → B transaction with a B → A transaction for the **exact same amount** in the same group. Confirm the sibling company has booked its side for the identical amount, then run matching again.+No mirror-image transaction exists. Matching only pairs an A → B transaction with a B → A transaction for the **exact same amount** in the same group. Confirm the sibling company has posted its invoice for the identical amount (or booked a manual counterpart), then run matching again.</AgentContext>diff --git a/packages/database/src/swagger-docs-schema.ts b/packages/database/src/swagger-docs-schema.tsindex 2acf642b04..3b9871c422 100644--- a/packages/database/src/swagger-docs-schema.ts+++ b/packages/database/src/swagger-docs-schema.ts@@ -37476,6 +37476,9 @@ export default {{$ref: "#/parameters/rowFilter.accountDefault.scrapAccount"},+ {+ $ref: "#/parameters/rowFilter.accountDefault.intercompanyPayablesAccount"+ },{$ref: "#/parameters/select"},@@ -37691,6 +37694,9 @@ export default {{$ref: "#/parameters/rowFilter.accountDefault.scrapAccount"},+ {+ $ref: "#/parameters/rowFilter.accountDefault.intercompanyPayablesAccount"+ },{$ref: "#/parameters/preferReturn"}@@ -37860,6 +37866,9 @@ export default {{$ref: "#/parameters/rowFilter.accountDefault.scrapAccount"},+ {+ $ref: "#/parameters/rowFilter.accountDefault.intercompanyPayablesAccount"+ },{$ref: "#/parameters/body.accountDefault"},@@ -104329,7 +104338,7 @@ export default {properties: {id: {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"},@@ -104378,7 +104387,7 @@ export default {},supplierLocationId: {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"},@@ -116345,6 +116354,12 @@ export default {"Note:\nThis is a Foreign Key to `account.id`.<fk table='account' column='id'/>",format: "text",type: "string"+ },+ intercompanyPayablesAccount: {+ description:+ "Note:\nThis is a Foreign Key to `account.id`.<fk table='account' column='id'/>",+ format: "text",+ type: "string"}},type: "object"@@ -159855,6 +159870,12 @@ export default {in: "query",type: "string"},+ "rowFilter.accountDefault.intercompanyPayablesAccount": {+ name: "intercompanyPayablesAccount",+ required: false,+ in: "query",+ type: "string"+ },"body.warehouse": {name: "warehouse",description: "warehouse",diff --git a/packages/database/src/types.ts b/packages/database/src/types.tsindex da6f1c484c..87593646c2 100644--- a/packages/database/src/types.ts+++ b/packages/database/src/types.ts@@ -349,6 +349,7 @@ export type Database = {finishedGoodsAccount: stringgoodsReceivedNotInvoicedAccount: stringindirectCostAccount: string+ intercompanyPayablesAccount: string | nullintercompanyReceivablesAccount: string | nullinterestAccount: stringinventoryAdjustmentVarianceAccount: string@@ -403,6 +404,7 @@ export type Database = {finishedGoodsAccount: stringgoodsReceivedNotInvoicedAccount: stringindirectCostAccount: string+ intercompanyPayablesAccount?: string | nullintercompanyReceivablesAccount?: string | nullinterestAccount: stringinventoryAdjustmentVarianceAccount: string@@ -457,6 +459,7 @@ export type Database = {finishedGoodsAccount?: stringgoodsReceivedNotInvoicedAccount?: stringindirectCostAccount?: string+ intercompanyPayablesAccount?: string | nullintercompanyReceivablesAccount?: string | nullinterestAccount?: stringinventoryAdjustmentVarianceAccount?: string@@ -785,6 +788,20 @@ export type Database = {referencedRelation: "accounts"referencedColumns: ["id"]},+ {+ foreignKeyName: "accountDefault_intercompanyPayablesAccount_fkey"+ columns: ["intercompanyPayablesAccount"]+ isOneToOne: false+ referencedRelation: "account"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "accountDefault_intercompanyPayablesAccount_fkey"+ columns: ["intercompanyPayablesAccount"]+ isOneToOne: false+ referencedRelation: "accounts"+ referencedColumns: ["id"]+ },{foreignKeyName: "accountDefault_intercompanyReceivablesAccount_fkey"columns: ["intercompanyReceivablesAccount"]@@ -68325,14 +68342,14 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey"- columns: ["supplierCountryCode"]+ columns: ["customerCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["customerCountryCode"]+ columns: ["supplierCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]@@ -71751,21 +71768,21 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey"- columns: ["invoiceCountryCode"]+ columns: ["shipmentCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["shipmentCountryCode"]+ columns: ["customerCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["customerCountryCode"]+ columns: ["invoiceCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]@@ -72312,14 +72329,14 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey"- columns: ["customerCountryCode"]+ columns: ["paymentCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["paymentCountryCode"]+ columns: ["customerCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]diff --git a/packages/database/supabase/functions/lib/seed.data.ts b/packages/database/supabase/functions/lib/seed.data.tsindex 6fbaac8f0f..aae9aad1aa 100644--- a/packages/database/supabase/functions/lib/seed.data.ts+++ b/packages/database/supabase/functions/lib/seed.data.ts@@ -799,6 +799,7 @@ export const accountDefaults = {prepaymentAccount: "2110",supplierPrepaymentAccount: "1150",payablesAccount: "2010",+ intercompanyPayablesAccount: "2020",goodsReceivedNotInvoicedAccount: "2125",salesTaxPayableAccount: "2210",purchaseTaxPayableAccount: "2220",diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.tsindex da6f1c484c..87593646c2 100644--- a/packages/database/supabase/functions/lib/types.ts+++ b/packages/database/supabase/functions/lib/types.ts@@ -349,6 +349,7 @@ export type Database = {finishedGoodsAccount: stringgoodsReceivedNotInvoicedAccount: stringindirectCostAccount: string+ intercompanyPayablesAccount: string | nullintercompanyReceivablesAccount: string | nullinterestAccount: stringinventoryAdjustmentVarianceAccount: string@@ -403,6 +404,7 @@ export type Database = {finishedGoodsAccount: stringgoodsReceivedNotInvoicedAccount: stringindirectCostAccount: string+ intercompanyPayablesAccount?: string | nullintercompanyReceivablesAccount?: string | nullinterestAccount: stringinventoryAdjustmentVarianceAccount: string@@ -457,6 +459,7 @@ export type Database = {finishedGoodsAccount?: stringgoodsReceivedNotInvoicedAccount?: stringindirectCostAccount?: string+ intercompanyPayablesAccount?: string | nullintercompanyReceivablesAccount?: string | nullinterestAccount?: stringinventoryAdjustmentVarianceAccount?: string@@ -785,6 +788,20 @@ export type Database = {referencedRelation: "accounts"referencedColumns: ["id"]},+ {+ foreignKeyName: "accountDefault_intercompanyPayablesAccount_fkey"+ columns: ["intercompanyPayablesAccount"]+ isOneToOne: false+ referencedRelation: "account"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "accountDefault_intercompanyPayablesAccount_fkey"+ columns: ["intercompanyPayablesAccount"]+ isOneToOne: false+ referencedRelation: "accounts"+ referencedColumns: ["id"]+ },{foreignKeyName: "accountDefault_intercompanyReceivablesAccount_fkey"columns: ["intercompanyReceivablesAccount"]@@ -68325,14 +68342,14 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey"- columns: ["supplierCountryCode"]+ columns: ["customerCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["customerCountryCode"]+ columns: ["supplierCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]@@ -71751,21 +71768,21 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey"- columns: ["invoiceCountryCode"]+ columns: ["shipmentCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["shipmentCountryCode"]+ columns: ["customerCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["customerCountryCode"]+ columns: ["invoiceCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]@@ -72312,14 +72329,14 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey"- columns: ["customerCountryCode"]+ columns: ["paymentCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["paymentCountryCode"]+ columns: ["customerCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]diff --git a/packages/database/supabase/functions/post-purchase-invoice/index.ts b/packages/database/supabase/functions/post-purchase-invoice/index.tsindex bf33b40339..d7e6f6aa81 100644--- a/packages/database/supabase/functions/post-purchase-invoice/index.ts+++ b/packages/database/supabase/functions/post-purchase-invoice/index.ts@@ -632,6 +632,32 @@ serve(async (req: Request) => {throw new Error("Failed to fetch purchase order lines");if (supplier.error) throw new Error("Failed to fetch supplier");+ // Detect the buyer side of an intercompany transaction. The sister supplier+ // row carries intercompanyCompanyId when both companies belong to a group.+ // post-sales-invoice records the seller side; this records the buyer side,+ // so runIntercompanyMatching can pair them for consolidation.+ const isIntercompany = supplier.data.intercompanyCompanyId != null;+ const intercompanyPartnerId = isIntercompany+ ? supplier.data.intercompanyCompanyId+ : null;++ // Pre-tax value of the intercompany document. Mirrors the sales side's basis+ // (quantity * unitPrice + line shippingCost over non-comment lines) so the two+ // rows match on amount. Tax is excluded — the sales side excludes it too — and+ // purchaseInvoiceLine has no addOnCost column. This is NOT totalLinesCost above,+ // which folds in taxAmount for the shipping allocation and would never match.+ const intercompanyAmount = purchaseInvoiceLines.data.reduce(+ (acc, invoiceLine) => {+ if (invoiceLine.invoiceLineType === "Comment") return acc;+ return (+ acc ++ (invoiceLine.quantity ?? 0) * (invoiceLine.unitPrice ?? 0) ++ (invoiceLine.shippingCost ?? 0)+ );+ },+ 0+ );+const purchaseOrders = await client.from("purchaseOrder").select("*")@@ -791,6 +817,22 @@ serve(async (req: Request) => {throw new Error("Error getting account defaults");}+ // For IC transactions, book the payable to Inter-Company Payables instead of+ // regular AP — the mirror of post-sales-invoice's IC Receivables swap. Resolve+ // it from accountDefault (stable id), not by account number, and fall back to+ // regular payables if the IC default isn't configured. Cast because the deno+ // types may lag the accountDefault column added by the payables-default+ // migration (same reason the sales side casts intercompanyReceivablesAccount).+ const icPayablesAccount = (+ accountDefaults?.data as unknown as {+ intercompanyPayablesAccount?: string | null;+ }+ )?.intercompanyPayablesAccount;+ const payablesAccountId: string | undefined =+ isIntercompany && icPayablesAccount+ ? icPayablesAccount+ : accountDefaults?.data?.payablesAccount;+// Invoice exchange rate (defaults to 1 for base-currency invoices).// The payment chain (post-payment/build-payment-journal) relieves AP at// `applied × exchangeRate`, so posting applies the same multiplier to the@@ -955,7 +997,7 @@ serve(async (req: Request) => {});journalLineInserts.push({- accountId: accountDefaults.data.payablesAccount,+ accountId: payablesAccountId,description: "Accounts Payable",amount: round(credit("liability", totalLineCostWithWeightedShipping)),quantity: round(invoiceLineQuantityInInventoryUnit),@@ -1325,7 +1367,7 @@ serve(async (req: Request) => {// CR Accounts Payable at invoice costjournalLineInserts.push({- accountId: accountDefaults.data.payablesAccount,+ accountId: payablesAccountId,description: "Accounts Payable",amount: round(credit("liability", invoiceCostForReversedQty)),quantity: round(quantityToReverse),@@ -1416,7 +1458,7 @@ serve(async (req: Request) => {// CR Accounts PayablejournalLineInserts.push({- accountId: accountDefaults.data.payablesAccount,+ accountId: payablesAccountId,description: "Accounts Payable",accrual: isService ? undefined : true,amount: round(credit("liability", accrualCost)),@@ -1551,7 +1593,7 @@ serve(async (req: Request) => {// CR Payables at invoice costjournalLineInserts.push({- accountId: accountDefaults.data.payablesAccount,+ accountId: payablesAccountId,description: "Accounts Payable",amount: round(credit("liability", invoiceCost)),quantity: round(invoiceLineQuantityInInventoryUnit),@@ -1620,7 +1662,7 @@ serve(async (req: Request) => {});journalLineInserts.push({- accountId: accountDefaults.data.payablesAccount,+ accountId: payablesAccountId,description: "Accounts Payable",amount: round(credit("liability", totalLineCostWithWeightedShipping)),quantity: round(invoiceLineQuantityInInventoryUnit),@@ -1713,7 +1755,7 @@ serve(async (req: Request) => {});journalLineInserts.push({- accountId: accountDefaults.data.payablesAccount,+ accountId: payablesAccountId,description: "Accounts Payable",amount: round(credit("liability", totalLineCostWithWeightedShipping)),quantity: round(invoiceLineQuantityInInventoryUnit),@@ -2010,6 +2052,46 @@ serve(async (req: Request) => {.execute();}}++ // Record the buyer side of an intercompany transaction (mirrors the+ // seller-side insert in post-sales-invoice) so runIntercompanyMatching can+ // pair the two and generateEliminationEntries can eliminate them for+ // consolidated reporting. Uses the first journal line as the reference,+ // exactly as the sales side does.+ // Reference the IC payable line (not [0], which is the asset/expense line)+ // so generateEliminationEntries reverses the Inter-Company Payables control+ // account and clears it against the seller's IC Receivables. journalLineInserts+ // is inserted 1:1 into journalLineResults, so the index aligns.+ const icPayableIdx = journalLineInserts.findIndex(+ (line) => line.accountId === payablesAccountId+ );+ // If no payable line was posted, leave this null so the guard below skips+ // the insert: referencing another line (asset/expense) would make+ // elimination reverse the wrong account and leave the control balance.+ const icJournalLineId =+ icPayableIdx >= 0 ? journalLineResults[icPayableIdx]?.id ?? null : null;+ if (+ isIntercompany &&+ intercompanyPartnerId &&+ companyGroupId &&+ icJournalLineId+ ) {+ await trx+ .insertInto("intercompanyTransaction")+ .values({+ companyGroupId,+ sourceCompanyId: companyId,+ targetCompanyId: intercompanyPartnerId,+ sourceJournalLineId: icJournalLineId,+ amount: round(intercompanyAmount),+ currencyCode: purchaseInvoice.data?.currencyCode ?? "USD",+ description: `Purchase Invoice ${purchaseInvoice.data?.invoiceId}`,+ documentType: "Invoice",+ documentId: purchaseInvoice.data?.id,+ status: "Unmatched",+ })+ .execute();+ }}if (itemLedgerInserts.length > 0) {diff --git a/packages/database/supabase/functions/post-sales-invoice/index.ts b/packages/database/supabase/functions/post-sales-invoice/index.tsindex d396d096e0..e1913aa173 100644--- a/packages/database/supabase/functions/post-sales-invoice/index.ts+++ b/packages/database/supabase/functions/post-sales-invoice/index.ts@@ -1225,25 +1225,53 @@ serve(async (req: Request) => {// Create intercompany transaction record if ICif (accountingEnabled && isIntercompany && intercompanyPartnerId) {- const icJournalLineId = journalLineResults.length > 0- ? journalLineResults[0].id- : null;+ // Reference the IC receivable line (not [0], which is the revenue line)+ // so generateEliminationEntries reverses the Inter-Company Receivables+ // control account and clears it against the buyer's IC Payables.+ // journalLineInserts is inserted 1:1 into journalLineResults. If no+ // receivable line was posted, skip: referencing another line would make+ // elimination reverse the wrong account and leave the control balance.+ const icReceivableIdx = journalLineInserts.findIndex(+ (line) => line.accountId === receivablesAccountId+ );+ const icJournalLineId =+ icReceivableIdx >= 0+ ? journalLineResults[icReceivableIdx]?.id ?? null+ : null;++ // Match on the same pre-tax basis the buyer computes+ // (quantity * unitPrice + shippingCost over non-comment lines).+ // addOnCost is excluded because purchaseInvoiceLine has no such column,+ // so including it here would break matching on lines that carry one.+ const intercompanyAmount = salesInvoiceLines.data.reduce(+ (acc, invoiceLine) => {+ if (invoiceLine.invoiceLineType === "Comment") return acc;+ return (+ acc ++ (invoiceLine.quantity ?? 0) * (invoiceLine.unitPrice ?? 0) ++ (invoiceLine.shippingCost ?? 0)+ );+ },+ 0+ );- await trx- .insertInto("intercompanyTransaction")- .values({- companyGroupId: companyGroupId!,- sourceCompanyId: companyId,- targetCompanyId: intercompanyPartnerId,- sourceJournalLineId: icJournalLineId,- amount: round(totalLinesCost),- currencyCode: salesInvoice.data?.currencyCode ?? "USD",- description: `Sales Invoice ${salesInvoice.data?.invoiceId}`,- documentType: "Invoice",- documentId: salesInvoice.data?.id,- status: "Unmatched",- })- .execute();+ if (icJournalLineId) {+ await trx+ .insertInto("intercompanyTransaction")+ .values({+ companyGroupId: companyGroupId!,+ sourceCompanyId: companyId,+ targetCompanyId: intercompanyPartnerId,+ sourceJournalLineId: icJournalLineId,+ amount: round(intercompanyAmount),+ currencyCode: salesInvoice.data?.currencyCode ?? "USD",+ description: `Sales Invoice ${salesInvoice.data?.invoiceId}`,+ documentType: "Invoice",+ documentId: salesInvoice.data?.id,+ status: "Unmatched",+ })+ .execute();+ }}// Apply deferred fixed-asset disposal writes inside the transaction sodiff --git a/packages/database/supabase/migrations/20260816143722_fix-intercompany-journalline-companygroupid.sql b/packages/database/supabase/migrations/20260816143722_fix-intercompany-journalline-companygroupid.sqlnew file mode 100644index 0000000000..d8bf2b0c24--- /dev/null+++ b/packages/database/supabase/migrations/20260816143722_fix-intercompany-journalline-companygroupid.sql@@ -0,0 +1,152 @@+-- The intercompany manual-transaction service (createIntercompanyTransaction) and+-- this elimination RPC both wrote a "companyGroupId" value into "journalLine",+-- but "journalLine" has no such column (it lives on "account", never on the ledger+-- line). PostgREST rejected the manual insert ("Failed to create IC Transaction"),+-- and this function would have failed identically at elimination time. Nothing+-- reads journalLine.companyGroupId — every line is already scoped by companyId and+-- the group is derivable via company.companyGroupId — so the fix is to drop the+-- stray writes. This redefinition removes "companyGroupId" from both+-- INSERT INTO "journalLine" statements; everything else is unchanged from+-- 20260403120000_intercompany-tracking.sql.++CREATE OR REPLACE FUNCTION "generateEliminationEntries" (+ p_company_group_id TEXT,+ p_user_id TEXT+)+RETURNS INTEGER -- returns count of journals created+LANGUAGE "plpgsql"+SECURITY INVOKER+SET search_path = public+AS $$+DECLARE+ v_rec RECORD;+ v_lca_id TEXT;+ v_elim_id TEXT;+ v_journal_id INTEGER;+ v_period_id TEXT;+ v_journals_created INTEGER := 0;+ v_journals_by_elim RECORD;+BEGIN+ -- Check that user belongs to at least one company in this group+ IF NOT EXISTS (+ SELECT 1+ FROM "userToCompany" utc+ INNER JOIN "company" c ON c."id" = utc."companyId"+ WHERE utc."userId" = auth.uid()::text+ AND utc."role" = 'employee'+ AND c."companyGroupId" = p_company_group_id+ ) THEN+ RAISE EXCEPTION 'Insufficient permissions to generate elimination entries';+ END IF;++ -- Process each matched IC transaction pair, routing to the correct elimination entity+ -- Group matched transactions by their lowest common parent's elimination entity+ FOR v_rec IN+ SELECT DISTINCT+ ict."sourceCompanyId",+ ict."targetCompanyId"+ FROM "intercompanyTransaction" ict+ WHERE ict."companyGroupId" = p_company_group_id+ AND ict."status" = 'Matched'+ LOOP+ -- Find the lowest common parent+ v_lca_id := "findLowestCommonParent"(v_rec."sourceCompanyId", v_rec."targetCompanyId");++ -- Find the elimination entity for this LCA+ 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 no elimination entity at the LCA level, fall back to any in the group+ 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;++ -- Get active accounting period for elimination entity+ SELECT "id" INTO v_period_id+ FROM "accountingPeriod"+ WHERE "companyId" = v_elim_id+ AND "status" = 'Active'+ LIMIT 1;++ -- Create elimination journal on this elimination entity+ INSERT INTO "journal" ("description", "accountingPeriodId", "companyId", "postingDate")+ VALUES (+ 'IC Elimination: ' || v_rec."sourceCompanyId" || ' ↔ ' || v_rec."targetCompanyId",+ v_period_id,+ v_elim_id,+ CURRENT_DATE+ )+ RETURNING "id" INTO v_journal_id;++ v_journals_created := v_journals_created + 1;++ -- Generate reversing entries from source journal lines+ INSERT INTO "journalLine" (+ "journalId", "accountId", "description", "amount",+ "documentType", "journalLineReference",+ "companyId"+ )+ SELECT+ v_journal_id,+ jl."accountId",+ 'IC Elimination: ' || COALESCE(jl."description", ''),+ -jl."amount",+ jl."documentType",+ 'ic-elim-' || ict."id",+ v_elim_id+ FROM "intercompanyTransaction" ict+ INNER JOIN "journalLine" jl ON jl."id" = ict."sourceJournalLineId"+ WHERE ict."companyGroupId" = p_company_group_id+ AND ict."status" = 'Matched'+ AND ict."sourceCompanyId" = v_rec."sourceCompanyId"+ AND ict."targetCompanyId" = v_rec."targetCompanyId";++ -- Also reverse the matched counterpart entries+ INSERT INTO "journalLine" (+ "journalId", "accountId", "description", "amount",+ "documentType", "journalLineReference",+ "companyId"+ )+ SELECT+ v_journal_id,+ jl."accountId",+ 'IC Elimination: ' || COALESCE(jl."description", ''),+ -jl."amount",+ jl."documentType",+ 'ic-elim-' || ict."id",+ v_elim_id+ FROM "intercompanyTransaction" ict+ INNER JOIN "journalLine" jl ON jl."id" = ict."targetJournalLineId"+ WHERE ict."companyGroupId" = p_company_group_id+ AND ict."status" = 'Matched'+ AND ict."sourceCompanyId" = v_rec."sourceCompanyId"+ AND ict."targetCompanyId" = v_rec."targetCompanyId"+ AND ict."targetJournalLineId" IS NOT NULL;++ -- Update these IC transactions to Eliminated+ UPDATE "intercompanyTransaction"+ SET "status" = 'Eliminated',+ "eliminationJournalId" = v_journal_id,+ "updatedAt" = NOW()+ WHERE "companyGroupId" = p_company_group_id+ AND "status" = 'Matched'+ AND "sourceCompanyId" = v_rec."sourceCompanyId"+ AND "targetCompanyId" = v_rec."targetCompanyId";++ END LOOP;++ RETURN v_journals_created;+END;+$$;diff --git a/packages/database/supabase/migrations/20260816144210_intercompany-payables-account-default.sql b/packages/database/supabase/migrations/20260816144210_intercompany-payables-account-default.sqlnew file mode 100644index 0000000000..a6a52c0777--- /dev/null+++ b/packages/database/supabase/migrations/20260816144210_intercompany-payables-account-default.sql@@ -0,0 +1,33 @@+-- Mirror of intercompanyReceivablesAccount (migration 20260702181547): the buyer+-- side of an intercompany invoice must book its payable to the Inter-Company+-- Payables control account (number 2020) instead of regular Accounts Payable, so+-- the group's IC receivable (seller) and IC payable (buyer) sit in matching+-- control accounts and the elimination can clear them against each other.+--+-- Store the account id on accountDefault (authoritative by id, resolved once from+-- the seeded number). post-purchase-invoice swaps payablesAccount ->+-- intercompanyPayablesAccount when the supplier is an intercompany partner,+-- exactly as post-sales-invoice swaps receivablesAccount ->+-- intercompanyReceivablesAccount.++ALTER TABLE "accountDefault"+ ADD COLUMN IF NOT EXISTS "intercompanyPayablesAccount" TEXT;++ALTER TABLE "accountDefault"+ DROP CONSTRAINT IF EXISTS "accountDefault_intercompanyPayablesAccount_fkey";+ALTER TABLE "accountDefault"+ ADD CONSTRAINT "accountDefault_intercompanyPayablesAccount_fkey"+ FOREIGN KEY ("intercompanyPayablesAccount") REFERENCES "account"("id")+ ON UPDATE CASCADE ON DELETE RESTRICT;++-- Backfill existing companies from the seeded Inter-Company Payables account+-- (number 2020 within the company's group). One-time resolution: from here the+-- stored id survives number/name changes. Nullable — companies that don't use+-- intercompany simply leave it unset and fall back to regular payables.+UPDATE "accountDefault" ad+SET "intercompanyPayablesAccount" = a."id"+FROM "account" a+JOIN "company" c ON c."companyGroupId" = a."companyGroupId"+WHERE c."id" = ad."companyId"+ AND a."number" = '2020'+ AND ad."intercompanyPayablesAccount" IS NULL;diff --git a/packages/database/supabase/migrations/20260816150312_fix-intercompany-elimination.sql b/packages/database/supabase/migrations/20260816150312_fix-intercompany-elimination.sqlnew file mode 100644index 0000000000..41072db41e--- /dev/null+++ b/packages/database/supabase/migrations/20260816150312_fix-intercompany-elimination.sql@@ -0,0 +1,177 @@+-- Authoritative redefinition of generateEliminationEntries. Fixes three defects+-- (supersedes 20260816143722):+--+-- 1. companyGroupId write — the function wrote a non-existent journalLine+-- "companyGroupId" column, which failed at elimination time. Dropped.+--+-- 2. Reciprocal double-count — a matched pair has TWO rows (A->B seller, B->A+-- buyer), so the per-ordered-pair loop ran twice and reversed both legs twice.+-- Now iterates each UNORDERED pair once (sourceCompanyId < targetCompanyId) and+-- marks BOTH directions Eliminated.+--+-- 3. Multi-line — the reversal copied the single referenced journal line, so a+-- multi-line IC invoice under-eliminated (only the first line cleared). Now it+-- reverses EVERY journal line in the IC control account for the transaction's+-- document (matched by the referenced line's accountId + documentId + company),+-- which clears the actual GL balance exactly regardless of line count and needs+-- no stored-total arithmetic (no rounding dust). This relies on both edge+-- functions pointing sourceJournalLineId/targetJournalLineId at the IC control+-- line (IC Receivables on the seller, IC Payables on the buyer), not at line 0.++CREATE OR REPLACE FUNCTION "generateEliminationEntries" (+ p_company_group_id TEXT,+ p_user_id TEXT+)+RETURNS INTEGER -- returns count of journals created+LANGUAGE "plpgsql"+SECURITY INVOKER+SET search_path = public+AS $$+DECLARE+ v_rec RECORD;+ v_lca_id TEXT;+ v_elim_id TEXT;+ v_journal_id INTEGER;+ v_period_id TEXT;+ v_journals_created INTEGER := 0;+ v_journals_by_elim RECORD;+BEGIN+ -- Check that user belongs to at least one company in this group+ IF NOT EXISTS (+ SELECT 1+ FROM "userToCompany" utc+ INNER JOIN "company" c ON c."id" = utc."companyId"+ WHERE utc."userId" = auth.uid()::text+ AND utc."role" = 'employee'+ AND c."companyGroupId" = p_company_group_id+ ) THEN+ RAISE EXCEPTION 'Insufficient permissions to generate elimination entries';+ END IF;++ -- Process each matched IC transaction pair ONCE, routing to the correct+ -- elimination entity. Restrict to sourceCompanyId < targetCompanyId so each+ -- unordered pair yields a single representative; the reciprocal (B->A) rows are+ -- picked up below via targetJournalLineId and marked Eliminated together.+ FOR v_rec IN+ SELECT DISTINCT+ ict."sourceCompanyId",+ ict."targetCompanyId"+ FROM "intercompanyTransaction" ict+ WHERE ict."companyGroupId" = p_company_group_id+ AND ict."status" = 'Matched'+ AND ict."sourceCompanyId" < ict."targetCompanyId"+ LOOP+ -- Find the lowest common parent+ v_lca_id := "findLowestCommonParent"(v_rec."sourceCompanyId", v_rec."targetCompanyId");++ -- Find the elimination entity for this LCA+ 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 no elimination entity at the LCA level, fall back to any in the group+ 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;++ -- Get active accounting period for elimination entity+ SELECT "id" INTO v_period_id+ FROM "accountingPeriod"+ WHERE "companyId" = v_elim_id+ AND "status" = 'Active'+ LIMIT 1;++ -- Create elimination journal on this elimination entity+ INSERT INTO "journal" ("description", "accountingPeriodId", "companyId", "postingDate")+ VALUES (+ 'IC Elimination: ' || v_rec."sourceCompanyId" || ' ↔ ' || v_rec."targetCompanyId",+ v_period_id,+ v_elim_id,+ CURRENT_DATE+ )+ RETURNING "id" INTO v_journal_id;++ v_journals_created := v_journals_created + 1;++ -- Reverse the seller-side IC control lines. Reverse EVERY line posted to that+ -- control account for the source document (multi-line), identified by the+ -- referenced line's accountId + documentId + company, not just the one line.+ INSERT INTO "journalLine" (+ "journalId", "accountId", "description", "amount",+ "documentType", "journalLineReference",+ "companyId"+ )+ SELECT+ v_journal_id,+ jl."accountId",+ 'IC Elimination: ' || COALESCE(jl."description", ''),+ -jl."amount",+ jl."documentType",+ 'ic-elim-' || ict."id",+ v_elim_id+ FROM "intercompanyTransaction" ict+ INNER JOIN "journalLine" ref ON ref."id" = ict."sourceJournalLineId"+ INNER JOIN "journalLine" jl+ ON jl."documentId" = ref."documentId"+ AND jl."accountId" = ref."accountId"+ AND jl."companyId" = ict."sourceCompanyId"+ WHERE ict."companyGroupId" = p_company_group_id+ AND ict."status" = 'Matched'+ AND ict."sourceCompanyId" = v_rec."sourceCompanyId"+ AND ict."targetCompanyId" = v_rec."targetCompanyId";++ -- Reverse the buyer-side IC control lines (the reciprocal B->A leg, reached+ -- through targetJournalLineId), same document-scoped multi-line reversal.+ INSERT INTO "journalLine" (+ "journalId", "accountId", "description", "amount",+ "documentType", "journalLineReference",+ "companyId"+ )+ SELECT+ v_journal_id,+ jl."accountId",+ 'IC Elimination: ' || COALESCE(jl."description", ''),+ -jl."amount",+ jl."documentType",+ 'ic-elim-' || ict."id",+ v_elim_id+ FROM "intercompanyTransaction" ict+ INNER JOIN "journalLine" ref ON ref."id" = ict."targetJournalLineId"+ INNER JOIN "journalLine" jl+ ON jl."documentId" = ref."documentId"+ AND jl."accountId" = ref."accountId"+ AND jl."companyId" = ict."targetCompanyId"+ WHERE ict."companyGroupId" = p_company_group_id+ AND ict."status" = 'Matched'+ AND ict."sourceCompanyId" = v_rec."sourceCompanyId"+ AND ict."targetCompanyId" = v_rec."targetCompanyId"+ AND ict."targetJournalLineId" IS NOT NULL;++ -- Update BOTH directions of this pair to Eliminated+ UPDATE "intercompanyTransaction"+ SET "status" = 'Eliminated',+ "eliminationJournalId" = v_journal_id,+ "updatedAt" = NOW()+ WHERE "companyGroupId" = p_company_group_id+ AND "status" = 'Matched'+ AND (+ ("sourceCompanyId" = v_rec."sourceCompanyId" AND "targetCompanyId" = v_rec."targetCompanyId")+ OR ("sourceCompanyId" = v_rec."targetCompanyId" AND "targetCompanyId" = v_rec."sourceCompanyId")+ );++ END LOOP;++ RETURN v_journals_created;+END;+$$;diff --git a/packages/database/supabase/migrations/20260816154722_intercompany-elimination-matching-hardening.sql b/packages/database/supabase/migrations/20260816154722_intercompany-elimination-matching-hardening.sqlnew file mode 100644index 0000000000..b0d495d846--- /dev/null+++ b/packages/database/supabase/migrations/20260816154722_intercompany-elimination-matching-hardening.sql@@ -0,0 +1,243 @@+-- Hardening pass on the intercompany functions, fixing review findings on+-- 20260816150312 (fix-forward, since that migration is already applied).+--+-- generateEliminationEntries:+-- * Normalize each company pair with LEAST/GREATEST instead of+-- sourceCompanyId < targetCompanyId. Matching updates both reciprocal rows,+-- but nothing enforces that invariant; a lone reverse-direction Matched row+-- was silently excluded and never eliminated. The pair predicate now catches+-- every matched row regardless of direction.+-- * Reverse each matched row's OWN intercompany control line (both legs are+-- covered because both directions are processed), deduplicated by journal+-- line id, instead of also walking targetJournalLineId — that removes the+-- duplicate-reversal risk.+-- * Refuse to post an elimination journal with no active accounting period+-- (nullable journal.accountingPeriodId would otherwise leave it unlinked).+-- * Refuse to mark a pair Eliminated when no control lines were reversed (e.g.+-- a referenced line with a null documentId), rather than recording an empty+-- journal and retiring the transaction.+--+-- matchIntercompanyTransactions:+-- * Also require equal currencyCode, so two same-number amounts in different+-- currencies do not match.++CREATE OR REPLACE FUNCTION "matchIntercompanyTransactions" (+ p_company_group_id TEXT+)+RETURNS TABLE (+ "id" TEXT,+ "sourceCompanyId" TEXT,+ "targetCompanyId" TEXT,+ "amount" NUMERIC,+ "status" TEXT,+ "matchedWithId" TEXT+)+LANGUAGE "plpgsql"+SECURITY INVOKER+SET search_path = public+AS $$+BEGIN+ -- Check that user belongs to at least one company in this group+ IF NOT EXISTS (+ SELECT 1+ FROM "userToCompany" utc+ INNER JOIN "company" c ON c."id" = utc."companyId"+ WHERE utc."userId" = auth.uid()::text+ AND utc."role" = 'employee'+ AND c."companyGroupId" = p_company_group_id+ ) THEN+ RAISE EXCEPTION 'Insufficient permissions to match intercompany transactions';+ END IF;++ -- Match unmatched IC transactions:+ -- Source's receivable against target's payable for the same amount, currency,+ -- and partner.+ WITH matches AS (+ SELECT+ src."id" AS "sourceId",+ tgt."id" AS "targetId"+ FROM "intercompanyTransaction" src+ INNER JOIN "intercompanyTransaction" tgt+ ON src."sourceCompanyId" = tgt."targetCompanyId"+ AND src."targetCompanyId" = tgt."sourceCompanyId"+ AND src."amount" = tgt."amount"+ AND src."currencyCode" = tgt."currencyCode"+ AND src."companyGroupId" = tgt."companyGroupId"+ WHERE src."companyGroupId" = p_company_group_id+ AND src."status" = 'Unmatched'+ AND tgt."status" = 'Unmatched'+ AND src."sourceJournalLineId" < tgt."sourceJournalLineId"+ )+ UPDATE "intercompanyTransaction" ict+ SET+ "status" = 'Matched',+ "targetJournalLineId" = CASE+ WHEN ict."id" = m."sourceId" THEN (SELECT t."sourceJournalLineId" FROM "intercompanyTransaction" t WHERE t."id" = m."targetId")+ ELSE (SELECT t."sourceJournalLineId" FROM "intercompanyTransaction" t WHERE t."id" = m."sourceId")+ END,+ "updatedAt" = NOW()+ FROM matches m+ WHERE ict."id" IN (m."sourceId", m."targetId");++ -- Return current state+ RETURN QUERY+ SELECT+ ict."id",+ ict."sourceCompanyId",+ ict."targetCompanyId",+ ict."amount",+ ict."status",+ ict."targetJournalLineId" AS "matchedWithId"+ FROM "intercompanyTransaction" ict+ WHERE ict."companyGroupId" = p_company_group_id+ ORDER BY ict."createdAt" DESC;+END;+$$;++CREATE OR REPLACE FUNCTION "generateEliminationEntries" (+ p_company_group_id TEXT,+ p_user_id TEXT+)+RETURNS INTEGER -- returns count of journals created+LANGUAGE "plpgsql"+SECURITY INVOKER+SET search_path = public+AS $$+DECLARE+ v_rec RECORD;+ v_lca_id TEXT;+ v_elim_id TEXT;+ v_journal_id INTEGER;+ v_period_id TEXT;+ v_journals_created INTEGER := 0;+ v_line_count INTEGER;+BEGIN+ -- Check that user belongs to at least one company in this group+ IF NOT EXISTS (+ SELECT 1+ FROM "userToCompany" utc+ INNER JOIN "company" c ON c."id" = utc."companyId"+ WHERE utc."userId" = auth.uid()::text+ AND utc."role" = 'employee'+ AND c."companyGroupId" = p_company_group_id+ ) THEN+ RAISE EXCEPTION 'Insufficient permissions to generate elimination entries';+ END IF;++ -- One elimination journal per UNORDERED company pair. LEAST/GREATEST make the+ -- pair direction-independent, so a matched row in either (or only one)+ -- direction is processed exactly once.+ 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+ -- Find the lowest common parent (symmetric in its arguments)+ v_lca_id := "findLowestCommonParent"(v_rec."companyA", v_rec."companyB");++ -- Find the elimination entity for this LCA+ 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 no elimination entity at the LCA level, fall back to any in the group+ 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;++ -- Get active accounting period for elimination entity; refuse to post an+ -- unlinked journal if there isn't one.+ SELECT "id" INTO v_period_id+ FROM "accountingPeriod"+ WHERE "companyId" = v_elim_id+ AND "status" = 'Active'+ LIMIT 1;++ IF v_period_id IS NULL THEN+ RAISE EXCEPTION 'No active accounting period for elimination entity %', v_elim_id;+ END IF;++ -- Create elimination journal on this elimination entity+ INSERT INTO "journal" ("description", "accountingPeriodId", "companyId", "postingDate")+ VALUES (+ 'IC Elimination: ' || v_rec."companyA" || ' ↔ ' || v_rec."companyB",+ v_period_id,+ v_elim_id,+ CURRENT_DATE+ )+ RETURNING "id" INTO v_journal_id;++ -- Reverse every intercompany control line for this pair. Each matched row+ -- references its own control line; from that line's account + document we+ -- sweep every line the same invoice posted to that control account (so+ -- multi-line invoices clear in full). DISTINCT dedupes journal line ids so a+ -- line is never reversed twice.+ WITH "controlLines" AS (+ SELECT DISTINCT+ jl."id",+ jl."accountId",+ jl."description",+ jl."amount",+ jl."documentType"+ FROM "intercompanyTransaction" ict+ INNER JOIN "journalLine" ref ON ref."id" = ict."sourceJournalLineId"+ INNER JOIN "journalLine" jl+ ON jl."documentId" = ref."documentId"+ AND jl."accountId" = ref."accountId"+ AND jl."companyId" = ict."sourceCompanyId"+ 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 ref."documentId" IS NOT NULL+ )+ INSERT INTO "journalLine" (+ "journalId", "accountId", "description", "amount",+ "documentType", "journalLineReference", "companyId"+ )+ SELECT+ v_journal_id,+ cl."accountId",+ 'IC Elimination: ' || COALESCE(cl."description", ''),+ -cl."amount",+ cl."documentType",+ 'ic-elim-' || v_journal_id::text,+ v_elim_id+ FROM "controlLines" cl;++ GET DIAGNOSTICS v_line_count = ROW_COUNT;+ IF v_line_count = 0 THEN+ RAISE EXCEPTION 'No intercompany control lines to eliminate for pair % / % (missing documentId on a referenced line?)',+ v_rec."companyA", v_rec."companyB";+ END IF;++ -- Retire every matched row of the pair (both directions)+ UPDATE "intercompanyTransaction"+ SET "status" = 'Eliminated',+ "eliminationJournalId" = v_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";++ v_journals_created := v_journals_created + 1;+ END LOOP;++ RETURN v_journals_created;+END;+$$;