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.

fix(accounting): correct posting, FX settlement, and consolidation (#1599)

Brad Barbin5d8d45925067
diff --git a/.ai/lessons.md b/.ai/lessons.md
index 24a19fafb2..84aadb14ee 100644
--- a/.ai/lessons.md
+++ b/.ai/lessons.md
@@ -1416,3 +1416,61 @@ full-screen ERP route.
**Rule:** When triaging sweep failures, grep the response bodies for known fallback strings (`"Failed to *"` service fallbacks, `getEdgeFunctionErrorMessage` second arguments) and treat each match as a defect to root-cause: either the advertised schema disagrees with the actual acceptor (enum/shape drift between a `.models.ts` validator and an edge function's `payloadValidator`), or an error-sanitization layer is eating a legible message. Published-schema enums must be exactly what the write path accepts — never a wider "domain" enum reused for convenience.
**Applies to:** API/MCP sweep scripts, `apps/erp/app/modules/*/[a-z]*.models.ts` validators that feed `client.functions.invoke` wrappers, `packages/database/supabase/functions/lib/response.ts`, `apps/erp/app/utils/error.ts`.
+
+## Resolve adoption assumptions before designing accounting migration machinery
+
+**Context:** The accounting posting-corrections spec raised legacy open-balance migration concerns; the user clarified that accounting can be assumed unused.
+
+**Problem:** Designing calculation versions, correction journals, and cutover tooling before resolving adoption added unnecessary scope to a correctness fix.
+
+**Rule:** Use the user's explicit adoption premise to size compatibility work. For this spec, correct the monetary contract directly; do not add legacy-accounting machinery. An unused accounting module does not imply permission to delete operational records or reset a database.
+
+**Applies to:** `.ai/specs/2026-09-07-accounting-posting-corrections.md` and its implementation; other modules require their own adoption evidence.
+
+
+## Accounting review: carrying balances and source principal
+
+- **Context:** Mixed positive and negative invoice lines, high FX rates, and changes to account defaults during settlement and provider replay.
+- **Problem:** Summing control magnitudes invented FX; recovering document units from rounded base lost valid minor-unit balances; current defaults rewrote original account provenance.
+- **Rule:** Sum signed original control amounts, preserve exact document principal independently of carrying base, and identify original journal roles through the shared exhaustive vocabulary (including intercompany roles). Reject unknown effective principal rather than infer it; retain Draft reservation policy separately from Posted effectiveness.
+- **Applies to:** Invoice/payment/memo posting, open-balance readers, and accounting provider replay.
+
+## Apportion a document total, never concentrate its rounding residual
+
+**Context:** Sales invoices push to QuickBooks/Xero/Rillet as components (merchandise, add-ons, line shipping, header shipping), each rounded at the document currency's precision, and the sum must equal the authoritative document total.
+
+**Problem:** Rounding N components independently leaves a residual of up to N/2 minor units. Assigning that whole residual to one component broke that component's own percent/amount pair — a 20 x $1.99 @ 8.25% invoice gave one line $0.24 tax on $1.99 net (12.06% against a stated 8.25%). QuickBooks re-derives `round(net x percent)` within one minor unit and refused the invoice with `UNMAPPED_TAX_CODES`, a message blaming the customer's QuickBooks configuration, which they cannot act on. A randomised sweep put this at 1.6% of invoices; some cases produced a negative tax on positive revenue, which Xero accepts and posts.
+
+**Rule:** Use `distributeRoundingResidual` (`@carbon/utils`) whenever a total is apportioned across parts — largest remainder, at most one minor unit moved per part. Never hand-roll "assign the difference to the biggest line". Order the parts by a stable business key (component id) before distributing, because the distributor's own tie-break is positional and the same invoice must allocate identically whatever order its lines arrive in. Where a derived value must reproduce the reconciled amount (a unit price times its quantity), derive it and then VERIFY — refuse when no representable value works, rather than emitting an inconsistent one.
+
+**Applies to:** `packages/ee/src/accounting/core/sales-document-components.ts`, `packages/database/supabase/functions/shared/sales-posting-amounts.ts`, `packages/ee/src/accounting/core/document-costing.ts`, and any future provider document mapper.
+
+## Two halves of an intercompany trade must round at the same scale
+
+**Context:** `post-sales-invoice` and `post-purchase-invoice` each write an `intercompanyTransaction` row, and `generate_intercompany_matches` pairs them with `src."amount" = tgt."amount"` — exact NUMERIC equality, no tolerance.
+
+**Problem:** The seller began rounding its half at the document currency's settlement precision (2dp) while the buyer kept internal `SCALE` (5dp). A trade of 3 x 100.005 stored 300.02 against 300.015, so the pair sat `Unmatched` forever and eliminations silently never ran — consolidated income kept the intragroup profit, with no error anywhere.
+
+**Rule:** An amount used as a MATCHING KEY is not a settlement amount. Round both halves at internal `SCALE`. Before changing rounding anywhere, check whether the value is compared for equality by something else — a matcher, a tie-out, or a reconciliation — and change both sides together.
+
+**Applies to:** `calculateSalesIntercompanyAmount`, `post-purchase-invoice`'s IC amount, `generate_intercompany_matches`.
+
+## Prove provider accounting against its independent journal
+
+**Context:** The live Rillet E2E run accepted invoice payloads while ignoring their FX override and crediting deferred revenue.
+
+**Problem:** Request shape and HTTP success did not prove economic parity. AR_ONLY used provider FX; the supported REVENUE_RECOGNITION_ONLY scope accepted fixed document-to-base rates and same-day recognition.
+
+**Rule:** Verify returned account effects in the provider's independent GL, including recognition and voids. Treat Carbon's rate as document units per base unit, invert it for Rillet, and align recognition and FX dates with Carbon's posting date. Check voided mappings before create-idempotency shortcuts and retain durable deletion markers.
+
+**Applies to:** Rillet invoice/bill/payment adapters, native-void reconciliation, and future provider acceptance tests.
+
+## Seed UI-only controlled fields through the form defaults
+
+**Context:** Payment type choices combine counterparty and cash direction while the persisted paymentType remains Receipt or Disbursement.
+
+**Problem:** Passing only SelectControlled.value left the initial registered paymentKind empty in the real browser; unit mocks did not model form initialization. A composer also retained old targets after a saved header identity changed.
+
+**Rule:** Include a UI-only field's initial value in ValidatedForm defaults, and key stateful composers by the document/party/currency/direction identity whose data they hold. Verify the initial label and actual submitted fields in the browser.
+
+**Applies to:** PaymentForm, PaymentApplyTable, and other forms using derived presentation choices.
diff --git a/.ai/plans/2026-09-07-accounting-posting-corrections.md b/.ai/plans/2026-09-07-accounting-posting-corrections.md
new file mode 100644
index 0000000000..49bbb99980
--- /dev/null
+++ b/.ai/plans/2026-09-07-accounting-posting-corrections.md
@@ -0,0 +1,1695 @@
+# Accounting Posting Corrections — implementation plan
+
+**Spec:** [.ai/specs/2026-09-07-accounting-posting-corrections.md](../specs/2026-09-07-accounting-posting-corrections.md)
+**Research:** [.ai/research/accounting-posting-corrections.md](../research/accounting-posting-corrections.md)
+**Branch:** `assess-issue-against-code`; base `origin/main`
+**Source baseline:** `0a9aef2444b04f0a0f0ade6f99dcd8e60aa3ec30`
+**Status:** implementation complete; PR review corrections and final validation tracked in [the review-corrections plan](2026-09-08-accounting-review-corrections.md).
+
+The user approved Shipping Revenue account/default/backfill and explicitly allowed assuming accounting has no users. Implement one corrected contract. Do not add legacy calculation versions, historical correction tools, France/e-invoicing, a tax engine, or new refund/cross-currency workflows. Preserve operational records and the existing database.
+
+All commands run from the repository root unless their command selects a package directory. Run red → green numerical regressions for each monetary change. Package name is `erp`, not `@carbon/erp`; the ERP/database packages have no `test` script. Never use a passing empty test run as verification. Do not publish a partially normalized posting chain.
+
+Read before execution: the linked spec, `.ai/lessons.md`, `BACKWARD_COMPATIBILITY.md`, `apps/erp/app/modules/accounting/AGENTS.md`, `packages/database/AGENTS.md`, `packages/ee/AGENTS.md`, and the accounting/numeric/database/service/form rules in `.claude/rules/`. Current edge-to-Node precision re-export is `packages/utils/src/precision.ts`.
+
+## Progress
+
+- [x] Task 1: Establish the accounting regression baseline.
+- [x] Task 2: Add shipping defaults and settlement funding schema.
+- [x] Task 3: Generate types after the schema migration.
+- [x] Task 4: Wire shipping defaults and company seeding.
+- [x] Task 5: Implement exact currency and funding calculations.
+- [x] Task 6: Split sales invoice postings and seller IC captures.
+- [x] Task 7: Normalize purchase postings and buyer IC captures.
+- [x] Task 8: Post payments and memos with authoritative funding.
+- [x] Task 9: Normalize the payment composer and service readers.
+- [x] Task 10: Normalize AP provider and inbound-payment boundaries.
+- [x] Task 11: Export sales components through provider-native mappings.
+- [x] Task 12: Correct translation arithmetic and error handling.
+- [x] Task 13: Apply CTA by configured account and reroll report totals.
+- [x] Task 14: Normalize invoice balances and AR/AP reporting SQL.
+- [x] Task 15: Generate types after the reporting migration.
+- [x] Task 16: Prove database and posting transaction invariants.
+- [x] Task 17: Run integration gates and update technical guidance.
+- [x] Task 18: Verify the user workflows in the browser.
+
+## Dependencies
+
+`1 → 2 → 3`; Tasks 4 and 5 follow 3 and can run independently. Task 6 follows 4–5; Task 7 follows 6 for the shared IC helper. Task 8 follows 5–7. Tasks 9 and 10 follow 8 and can run independently; Task 11 follows 10. Tasks 12–13 are independent of the posting work, but share `accounting.ee.service.ts` with Task 4: serialize edits to that file. Task 14 follows 8–9; Task 15 immediately follows 14. Task 16 follows 4–15; Task 17 follows 16; Task 18 is the final verification.
+
+Only the final integrated result is deployable. Per-task commits are local review units, not independent monetary releases. Use `/check-and-commit` during approved execution, commit only the task's files, and retain failures as unfinished checklist items.
+
+## Task 1: Establish the accounting regression baseline
+
+**Depends on:** none
+**Files:**
+- Modify: `apps/erp/app/modules/accounting/accounting.periods.test.ts` — repair missing timezone lookup mocks.
+- Create: `scripts/run-local-accounting-check.ts` — tracked command launcher for local SQL/concurrency checks.
+- Read: `apps/erp/vitest.config.ts`, `packages/config/vitest.mts`, `packages/config/package.json`.
+
+**Steps:**
+1. Record `git status --short` and `git rev-parse HEAD`. Preserve pre-existing audit/spec/research edits. If posting code has changed since the source baseline, review that diff before applying this plan; do not overwrite concurrent work.
+2. Build the already-declared shared test configuration with `pnpm --filter @carbon/config build` so `@carbon/ee` can resolve its Vitest config.
+3. Run the period tests and record the existing failures. Add the mocked `.maybeSingle()` company-timezone lookup and active-integration response required by the real period helper; retain the expected timezone and period behavior. Do not replace period calls with a stub that bypasses the behavior under test.
+4. Run the baseline below. Existing payment tests currently encode wrong FX expectations; their current pass is a baseline, not a correctness verdict.
+5. Save the following launcher to the path above. It loads the same environment files as the generator, refuses a nonlocal database, and passes credentials only in the child environment. Every database verification command below uses it; an unavailable local stack is a prerequisite failure.
+
+```ts
+import { spawnSync } from "node:child_process";
+import { config } from "dotenv";
+
+config({ path: ".env" });
+config({ path: ".env.local", override: true });
+const dbUrl = process.env.SUPABASE_DB_URL;
+if (!dbUrl) throw new Error("An existing local SUPABASE_DB_URL is required");
+const connection = new URL(dbUrl);
+if (!["localhost", "127.0.0.1", "[::1]"].includes(connection.hostname)) {
+ throw new Error("An existing local SUPABASE_DB_URL is required");
+}
+const [command, ...args] = process.argv.slice(2);
+if (!["psql", "deno", "pnpm", "git"].includes(command ?? "")) throw new Error("Expected a local accounting verification command");
+const result = spawnSync(command, args, {
+ env: {
+ ...process.env,
+ PGHOST: connection.hostname,
+ PGPORT: connection.port || "5432",
+ PGUSER: decodeURIComponent(connection.username),
+ PGPASSWORD: decodeURIComponent(connection.password),
+ PGDATABASE: decodeURIComponent(connection.pathname.slice(1)),
+ PGCONNECT_TIMEOUT: "5"
+ },
+ stdio: "inherit"
+});
+if (result.error) throw new Error("Could not launch local accounting check");
+process.exit(result.status ?? 1);
+```
+
+**Verify:**
+```bash
+pnpm --filter @carbon/config build
+pnpm --dir apps/erp exec vitest run app/modules/accounting/accounting.periods.test.ts app/modules/accounting/ui/Reports/executivePnl.test.ts app/modules/accounting/ui/Reports/pivotData.test.ts
+deno test --no-check --no-lock --config packages/database/supabase/functions/deno.json packages/database/supabase/functions/post-payment/post-payment.test.ts packages/database/supabase/functions/post-memo/post-memo.test.ts
+# Expected: config builds; all selected tests pass, including all 31 period tests.
+```
+
+**Out of scope:** unrelated period redesign, broad test cleanup, database resets.
+
+## Task 2: Add shipping defaults and settlement funding schema
+
+**Depends on:** Task 1
+**Files:**
+- Create: the migration emitted in `packages/database/supabase/migrations/` by `pnpm db:migrate:new accounting_posting_corrections`; record its actual CLI-generated path in this task when executing.
+- Create: `packages/database/supabase/tests/accounting-shipping-backfill.test.sql` — rollback-only schema/backfill cases.
+- Copy from (precedent): `packages/database/supabase/migrations/20260717031529_split-asset-gain-loss-disposal-accounts.sql` for existing account fields; `packages/database/supabase/tests/intercompany-elimination.test.sql` for rollback assertions only.
+
+**Steps:**
+1. Create the migration with the command above. Do not hand-pick/backdate its timestamp. If that suffix already exists, inspect and reuse the task's existing file instead of creating a second migration. Its version must sort after the newest migration on `origin/main`.
+2. Copy the **complete SQL in Appendix A** into that file. The exact extraction command below identifies the unique CLI-created file, so the plan does not invent a future timestamp.
+3. Before changing a constraint, confirm the current table shape agrees with Appendix A. If the tables/keys differ, STOP and report the exact difference; do not drop an existing constraint to force this SQL through.
+4. Write rollback fixtures for fresh charts, two companies sharing a chart, a custom-number Shipping Revenue leaf, occupied 4040, rerun/custom-default preservation, and ambiguous/incompatible parent/name errors. Assert that one failed group rolls back all account/default changes. Exercise new same-company funding FK, self-funding check, nonfinite/negative source amount refusal, and a source-only minor-unit settlement.
+5. In the test, isolate setup in a transaction and execute the backfill portion in a nested transaction/savepoint; do not run an embedded migration COMMIT inside the fixture. Copy the seed mechanism, not the old harness's hardcoded customer/account selection. Never test by changing a real company's defaults.
+6. Apply with `pnpm db:migrate` against the existing local development stack. If the local database is unavailable, report that prerequisite; do not reset it or substitute a production connection. Continue immediately to Task 3 before typechecking.
+
+**Verify:**
+```bash
+python3 - <<'SQL_COPY'
+from pathlib import Path
+import re
+p=Path('.ai/plans/2026-09-07-accounting-posting-corrections.md').read_text()
+matches=re.findall(r'^<!-- schema-sql:start -->\n```sql\n(.*?)\n```\n<!-- schema-sql:end -->$',p,re.M|re.S)
+assert len(matches)==1
+sql=matches[0]+'\n'
+targets=list(Path('packages/database/supabase/migrations').glob('*_accounting_posting_corrections.sql'))
+assert len(targets)==1, targets
+targets[0].write_text(sql)
+print(targets[0])
+SQL_COPY
+pnpm db:migrate
+# Expected: one forward migration applied; shipping accounts/defaults populated without changing existing accounts.
+```
+
+**Out of scope:** NOT NULL on the shipping default, historical settlement backfill, new tables, changes to RLS/permission scopes, operational-data deletion.
+
+## Task 3: Generate types after the schema migration
+
+**Depends on:** Task 2
+**Files:**
+- Regenerate: `packages/database/src/types.ts` and `packages/database/supabase/functions/lib/types.ts` through the repository generator; include any other files it actually emits.
+- Read: `scripts/generate-db-types.ts` — authoritative output paths, not hand-edited type declarations.
+
+**Steps:**
+1. Run generation after the migration. Verify output includes `salesShippingRevenueAccount`, `sourcePaymentId`, `sourceAmount`, and writable `fxGainLossAmount`.
+2. Do not change nullable generated fields to required by hand. Posting requirements belong in validators and server code.
+3. Run the rollback fixture from Task 2, with the existing local connection loaded through the project's environment tooling. Never print the connection string.
+
+**Verify:**
+```bash
+pnpm run generate:types
+rg -n 'salesShippingRevenueAccount|sourcePaymentId|sourceAmount' packages/database/src/types.ts packages/database/supabase/functions/lib/types.ts
+pnpm exec tsx scripts/run-local-accounting-check.ts psql -v ON_ERROR_STOP=1 -f packages/database/supabase/tests/accounting-shipping-backfill.test.sql
+# Expected: generated fields found; named PASS notices, ALL SCENARIOS PASSED, ROLLBACK, exit 0.
+```
+
+**Out of scope:** hand-edited generated types; skipping generation because `db:migrate` may also run it.
+
+## Task 4: Wire shipping defaults and company seeding
+
+**Depends on:** Task 3
+**Files:**
+- Modify: `packages/database/supabase/functions/lib/seed.data.ts` — 4040 account and default.
+- Modify: `packages/database/supabase/functions/seed-company/index.ts` — existing-group semantic/default resolution.
+- Create: `packages/database/supabase/functions/seed-company/shipping-default.ts`, `packages/database/supabase/functions/seed-company/shipping-default.test.ts` — pure validated selection from batch-loaded records.
+- Modify: `apps/erp/app/modules/accounting/accounting.models.ts`, `apps/erp/app/modules/accounting/accounting.ee.service.ts`, `apps/erp/app/routes/x+/accounting+/defaults.tsx`.
+- Modify: `apps/erp/app/modules/accounting/ui/AccountDefaults/AccountDefaultsForm.tsx`.
+- Create: `apps/erp/app/modules/accounting/accounting.defaults.test.ts`.
+- Copy from (precedent): `apps/erp/app/modules/accounting/ui/AccountDefaults/AccountDefaultsForm.tsx` Sales & Revenue section and `apps/erp/app/components/Form/CurrencyNumber.tsx`/existing Combobox usage; no new form component.
+
+**Steps:**
+1. Seed Shipping Revenue with key/number `4040`, `parentKey: "revenue"`, class Revenue, type Income, Income Statement, Average, active leaf. Add `salesShippingRevenueAccount: "4040"` to `accountDefaults`.
+2. For existing-group seeding, batch-load the parent's default and chart once. Add `resolveShippingDefault({parentDefaultId, accounts, companyGroupId}): string` in the edge helper: use the valid parent's mapping first; otherwise require exactly one compatible Shipping Revenue leaf. Never select an unrelated 4040 or fall back to Sales. Test a parent mapped to a custom-number leaf.
+3. Add the optional incoming field to `defaultIncomeAcountValidator` (merged full validator inherits it). Older payload omission preserves the stored mapping. A present empty/invalid mapping is a validation error. On the new form require a selection.
+4. Extend `updateDefaultIncomeAccounts(client, defaultAccounts)` in place: resolve company group and proposed account, validate active Revenue/Income Statement leaf in that group and distinct from the effective sales default; return a normal data/error result. Validate before either defaults write in the route so an invalid shipping account does not partially save the other section.
+5. Add the Shipping Revenue row to the current Sales & Revenue group. Use existing eligible leaf data and exclude the currently selected Sales account; retain authoritative server validation.
+6. Test default omission, valid save/reload, invalid class/tenant/group/inactive/same-as-sales, new-group seed and custom-number existing-group seed. Verify dataset bootstrap consumes the new canonical seed data without a special duplicated default map.
+
+**Verify:**
+```bash
+deno test --no-lock --config packages/database/supabase/functions/deno.json packages/database/supabase/functions/seed-company/shipping-default.test.ts
+pnpm --dir apps/erp exec vitest run app/modules/accounting/accounting.defaults.test.ts
+pnpm db:check:datasets
+# Expected: both focused suites pass; every dataset actually runs and applies successfully, not a skipped check.
+```
+
+**Out of scope:** replacing the account-defaults UI, new carrier-expense configuration, rewriting other custom account mappings.
+
+## Task 5: Implement exact currency and funding calculations
+
+**Depends on:** Task 3
+**Files:**
+- Create: `packages/database/supabase/functions/shared/accounting-currency.ts`, `packages/database/supabase/functions/shared/accounting-currency.test.ts`.
+- Create: `packages/database/supabase/functions/shared/payment-funding.ts`, `packages/database/supabase/functions/shared/payment-funding.test.ts`.
+- Create: `packages/utils/src/accounting-currency.ts`, `packages/utils/src/payment-funding.ts`.
+- Modify: `packages/utils/src/index.ts` to re-export the corresponding pure edge helpers using the existing precision re-export pattern.
+- Copy from (precedent): `packages/database/supabase/functions/shared/precision.ts`, `packages/utils/src/precision.ts`.
+
+**Steps:**
+1. Add `toBaseAmount(documentAmount: number, foreignPerBaseRate: number): number` and `toDocumentAmount(baseAmount: number, foreignPerBaseRate: number, currencyDecimals: number): number`. Validate finite inputs/positive rate. Use shared `round` at named internal/document boundaries; never infer the rate's direction from its magnitude.
+2. Define the funding API below. Inputs are already company/party/currency-validated by the caller. The helper rechecks positive finite rates, nonnegative finite amounts, unique IDs, document precision and target/source caps. `requestedDocumentPrincipal` carries an exact full-remainder choice through the base-currency UI; it is never trusted without authoritative target validation. Return `newOnAccountDocument` from unused current cash only.
+3. Allocate current cash first, prior sources by `(postingDate,id)`; split by source and invoice. Full allocations use exact document remainder and authoritative remaining carrying base. Track both source and target carrying remainders independently; partial releases round document/rate, and final exhaustion releases the recorded remainingBase. Assign discount/write-off once; allow a final positive document principal whose rounded base relief is zero. Do not infer remaining document principal from rounded base.
+4. Add `calculateSettlementFx({appliedAmount, sourceAmount, sourceExchangeRate, isAR, sourceBaseAmount?}): number`; compare the recorded target-base principal with funding base, round once, and return the signed snapshot. The optional sourceBaseAmount defaults to rounded sourceAmount/sourceExchangeRate; the allocator supplies the actual released carrying base, using remainingBase on final source exhaustion. Keep source/memo current-currency equality a validated precondition.
+5. Tests cover every numerical payment example in the spec, source amount 160.01 at rate 16000, multiple partial allocations, two prior rates, mixed current cash/credit, discount-only rows, invalid inputs, and deterministic input-order-independent source selection.
+
+```ts
+type FundingSource = {
+ paymentId: string;
+ postingDate: string; // ISO date; stable lexical ordering, then paymentId
+ exchangeRate: number;
+ remainingDocument: number;
+ remainingBase: number; // original rounded source carrying value minus recorded releases
+};
+type FundingRequest = {
+ targetId: string;
+ targetExchangeRate: number;
+ remainingDocument: number;
+ remainingBase: number;
+ requestedDocumentPrincipal: number;
+ discountAmount: number; // target base
+ writeOffAmount: number; // target base
+};
+type FundingApplication = {
+ targetId: string;
+ sourcePaymentId: string | null;
+ sourceAmount: number;
+ sourceExchangeRate: number;
+ targetExchangeRate: number;
+ appliedAmount: number;
+ discountAmount: number;
+ writeOffAmount: number;
+ fxGainLossAmount: number;
+};
+declare function allocatePaymentFunding(input: {
+ currentPayment: FundingSource;
+ priorSources: FundingSource[];
+ requests: FundingRequest[];
+ currencyDecimals: number;
+ isAR: boolean;
+}): {
+ applications: FundingApplication[];
+ newOnAccountDocument: number;
+ sourceRemainders: Array<{paymentId: string; remainingDocument: number; remainingBase: number}>;
+};
+```
+
+**Verify:**
+```bash
+deno test --no-lock --config packages/database/supabase/functions/deno.json packages/database/supabase/functions/shared/accounting-currency.test.ts packages/database/supabase/functions/shared/payment-funding.test.ts
+# Expected: all economic/precision fixtures pass, including exact exhaustion and restoration of 160.01 source units.
+```
+
+**Out of scope:** a second rounding library, new currency-store semantics, cross-currency allocation.
+
+## Task 6: Split sales invoice postings and seller IC captures
+
+**Depends on:** Tasks 4–5
+**Files:**
+- Modify: `packages/database/supabase/functions/post-sales-invoice/index.ts`.
+- Create: `packages/database/supabase/functions/shared/sales-posting-amounts.ts`, `packages/database/supabase/functions/shared/sales-posting-amounts.test.ts`.
+- Create: `packages/utils/src/sales-posting-amounts.ts`.
+- Modify: `packages/utils/src/index.ts` to re-export the shared pure amount helper for provider use.
+- Create: `packages/database/supabase/functions/shared/intercompany-capture.ts`, `packages/database/supabase/functions/shared/intercompany-capture.test.ts`.
+- Copy from (precedent): `packages/database/supabase/functions/post-payment/build-payment-journal.ts` for pure construction and natural debit/credit helpers.
+
+**Steps:**
+1. Add `calculateSalesPostingAmounts({quantity,unitPrice,shippingCost,addOnCost,nonTaxableAddOnCost,taxPercent,allocatedHeaderShipping}): {salesRevenueBase,shippingRevenueBase,salesTaxBase,grossReceivableBase}` and a deterministic header allocator. Preserve current line/header tax bases and zero-weight equal allocation.
+2. Replace gross-to-sales posting in all supported sales branches with the component breakdown. Remove the extra invoice-rate multiplication. Require Sales/Shipping/Tax defaults only for nonzero relevant components and validate their account classes before writing.
+3. Keep gross AR. Asset sale proceeds exclude shipping/tax; preserve direct disposal versus shipment-owned enrichment, acquisition/depreciation removal, and gain/loss accounts. Do not add sales G/L lines or asset-lifecycle void repair.
+4. Keep a common line+metadata construction path so references/dimensions and returned IDs stay aligned despite added rows. Void still negates recorded rows exactly.
+5. Add `classifyIntercompanyPostingLines(lines, metadata, accounts)` returning references/roles from actual emitted rows. Seller Revenue includes Sales and Shipping; every IC AR row is Control; Tax is excluded from Revenue. Preserve the first control ID as the trade matching anchor. Test this helper through the poster's actual line inputs; do not reconstruct roles from a blanket account-class guess.
+6. The seller's `intercompanyTransaction.amount` is labeled with invoice currency while its current quantity × unit-price + shipping inputs are base. Convert that existing matching basis once to document currency; preserve which components the matching basis includes. Test its amount/currency against the buyer capture.
+7. Prove the 151/123/15/13 fixture, disposal 121/100/10/11/gain30, zero components, header residuals, supported line types, dimensions and multiple control captures. The production helper must construct the actual charge journal rows/metadata consumed by the poster, so tests can assert their account/debit/credit effects; testing a disconnected arithmetic function alone is insufficient.
+
+**Verify:**
+```bash
+deno test --no-lock --config packages/database/supabase/functions/deno.json packages/database/supabase/functions/shared/sales-posting-amounts.test.ts packages/database/supabase/functions/shared/intercompany-capture.test.ts
+# Expected: component, disposal, allocation, metadata and seller capture regressions pass through imported production helpers.
+```
+
+**Out of scope:** new tax policy, carrier expense accruals, sales G/L-account support, general asset void repair.
+
+## Task 7: Normalize purchase postings and buyer IC captures
+
+**Depends on:** Tasks 4–6
+**Files:**
+- Modify: `packages/database/supabase/functions/post-purchase-invoice/index.ts`.
+- Create: `packages/database/supabase/functions/post-purchase-invoice/purchase-posting-amounts.ts`, `packages/database/supabase/functions/post-purchase-invoice/purchase-posting-amounts.test.ts`.
+- Modify: `packages/database/supabase/functions/shared/intercompany-capture.test.ts` for buyer inputs.
+- Read: `packages/database/supabase/functions/post-receipt/index.ts`, `packages/database/supabase/functions/shared/purchase-cost-adjustment.ts`.
+
+**Steps:**
+1. Extract a pure `calculatePurchasePostingAmounts` input using existing generated base unit/shipping/tax fields, quantity/UOM conversion, and allocated header supplier freight. Convert only supplier/document amounts; delete the second multiplication on already-base amounts.
+2. Apply those same base amounts to AP, GR/IR/PPV, direct/indirect expense, cost ledger, and fixed-asset acquisition. Preserve purchase tax and freight cost treatment.
+3. Keep the already-correct receipt header divide. Trace the matched receipt amount and prove identical rate/price/freight/UOM produces zero PPV; retain an independent nonzero true-price-variance case.
+4. Capture every actual IC payable row as Control using the shared helper, with the existing first matching anchor. Preserve receipt-owned capitalization captures and per-trade references.
+5. Test purchased stock/service/fixture/fixed-asset/G/L branches, non-1 conversion factor, header shipping allocation, and buyer control row completeness.
+
+**Verify:**
+```bash
+deno test --no-lock --config packages/database/supabase/functions/deno.json packages/database/supabase/functions/post-purchase-invoice/purchase-posting-amounts.test.ts packages/database/supabase/functions/shared/purchase-cost-adjustment.test.ts packages/database/supabase/functions/shared/intercompany-capture.test.ts
+# Expected: true-base cost/asset/control amounts and zero-PPV matching cases pass; all buyer control rows are captured.
+```
+
+**Out of scope:** recoverable input tax, new inventory valuation methods, changing receipt/PO quantity semantics.
+
+## Task 8: Post payments and memos with authoritative funding
+
+**Depends on:** Tasks 5–7
+**Files:**
+- Modify: `packages/database/supabase/functions/post-payment/build-payment-journal.ts`, `packages/database/supabase/functions/post-payment/post-payment.test.ts`, `packages/database/supabase/functions/post-payment/index.ts`.
+- Create: `packages/database/supabase/functions/post-payment/post-payment-transaction.ts`, `packages/database/supabase/functions/post-payment/post-payment-transaction.test.ts`, `packages/database/supabase/functions/post-payment/payment-test-fixture.ts`.
+- Create: `packages/database/supabase/functions/post-memo/post-memo-transaction.ts`, `packages/database/supabase/functions/post-memo/post-memo-transaction.test.ts` for the endpoint transaction seam.
+- Modify: `packages/database/supabase/functions/post-memo/build-memo-journal.ts`, `packages/database/supabase/functions/post-memo/post-memo.test.ts`, `packages/database/supabase/functions/post-memo/index.ts`.
+- Copy from (precedent): current index's transaction/row-lock/void implementation; retain the HTTP authorization wrapper.
+
+**Steps:**
+1. Extend `PaymentJournalApplicationInput` with `sourceAmount`, `sourcePaymentId`, and the authoritative FX snapshot. Bank/fees divide by current payment rate; target control/discount/write-off use base amounts; prior-credit rows release original funding base; unused current cash alone creates new credit. Aggregate persisted row FX rather than independently recalculating a plug.
+2. Extract the existing transaction body to `postPaymentTransaction(db, args)` in the edge-local file, taking the DB/client/context as arguments. `index.ts` continues to authenticate and resolve request inputs. This seam must be called by the real endpoint and be importable in tests without starting `serve()` or constructing a pool.
+3. Inside the transaction lock current payment, target invoices, staged memos and eligible source payments in deterministic order. Re-read status/party/currency/rates/amounts under locks. Reject unsupported source/target combinations and all cross-company references.
+4. Recalculate funding with Task 5's helper after locks. Derive target remainingBase from its original posted carrying total minus recorded effective base relief, rather than the document-derived view balance. Derive prior source remainingBase from its original rounded gross base minus recorded releases (appliedAmount + FX for AR, appliedAmount - FX for AP); current cash begins at rounded gross/paymentRate. New on-account base is the current source's returned remainingBase. Then persist split settlements, exact source amounts, FX snapshots, journals/references, and status atomically. Move journal construction from its current pre-transaction location. When accounting is disabled, settlement source amounts and caps still use the corrected contract.
+5. Availability sums posted applying rows under the actual source identity. Reject double consumption. Refuse source void with effective consumers; applying-payment void reverses actual lines and releases source usage. Preserve idempotent post/void behavior and existing accounting-period guards.
+6. Normalize memo posting amount by division, all memo remaining/cap calculations by exact source document amounts, and memo-to-invoice currency/equal-rate requirements. Same-rate memo applications store FX 0.
+7. Red → green tests cover the spec's cash, fee, discounts, write-offs, new credit, prior credit, zero-cash application, forced transaction rollback, changed source rates, and forged submitted values. Transaction tests assert no writes survive failure; actual concurrent DB proof belongs in Task 16.
+
+**Verify:**
+```bash
+deno test --no-lock --config packages/database/supabase/functions/deno.json packages/database/supabase/functions/post-payment/post-payment.test.ts packages/database/supabase/functions/post-payment/post-payment-transaction.test.ts packages/database/supabase/functions/post-memo/post-memo.test.ts
+# Expected: all corrected economic fixtures and transaction-failure tests pass; stored FX sum equals the journal FX amount.
+```
+
+**Out of scope:** new refund UI, targetless refund support, legacy-version dispatch, weakening authorization or period locks.
+
+## Task 9: Normalize the payment composer and service readers
+
+**Depends on:** Task 8
+**Files:**
+- Modify: `apps/erp/app/modules/invoicing/invoicing.models.ts`, `apps/erp/app/modules/invoicing/invoicing.service.ts`.
+- Modify: `apps/erp/app/routes/x+/payments+/new.tsx`, `apps/erp/app/routes/x+/payments+/$paymentId.tsx`, `apps/erp/app/routes/x+/payments+/$paymentId.applications.set.tsx`, `apps/erp/app/routes/x+/payments+/$paymentId.credits.set.tsx`.
+- Modify: `apps/erp/app/modules/invoicing/ui/Payment/PaymentApplyTable.tsx`, `apps/erp/app/modules/invoicing/ui/Payment/PaymentApplications.tsx`, `apps/erp/app/modules/invoicing/ui/Payment/InvoicePaymentsPanel.tsx`, `apps/erp/app/modules/invoicing/ui/Payment/AvailableCreditsTable.tsx`.
+- Modify: `apps/erp/app/modules/invoicing/invoicing.models.test.ts`, `apps/erp/app/modules/invoicing/invoicing.reports.test.ts`.
+- Create: `apps/erp/app/modules/invoicing/invoicing.settlements.test.ts`, `apps/erp/app/modules/invoicing/ui/Payment/PaymentApplyTable.test.tsx`.
+- Copy from (precedent): the existing payment composer and `apps/erp/app/components/Form/CurrencyNumber.tsx` using `INPUT_FORMAT`/named kinds.
+
+**Steps:**
+1. Extend `invoiceSettlementBase` input for optional draft document principal; source selection and FX remain server-authoritative. Preserve `paymentId` as applying owner. Update `replaceInvoiceSettlements(db,args)` to validate currency and rates from batch-loaded parents and normalize drafts without accepting a forged funding source.
+2. Add `getAvailableOnAccountCreditSources(client: SupabaseClient<Database>, companyId: string, party: {paymentType: "Receipt"; customerId: string} | {paymentType: "Disbursement"; supplierId: string}, currencyCode: string): Promise<{data: {sources: FundingSource[]; availableDocumentAmount: number; availableBaseAmount: number} | null; error: {message: string} | null}>` in the existing service. Batch-load matching posted payments and effective consumption rows and use Task 5's source type/calculations, including independently tracked remainingBase from original rounded gross less recorded carrying releases. Update every composer caller to use this typed result; preserve the existing `getAvailableOnAccountCredit(...): Promise<number>` base-total contract for other callers, sharing the normalized company-scoped calculation. The composer spends document totals directly, not base totals revalued at the new payment rate.
+3. Seed payment cash from exact remaining document amounts; for full application retain the source amount even when rounded base is zero. Select only matching-currency invoices/sources. Replace `INVOICE_DUST_THRESHOLD` and all mirrored `0.0001` base predicates in save/post/composer eligibility with document-currency completion. Resolve currency decimals from the company group's configured currency; refuse invalid/missing configuration on save/post.
+4. Keep base application/discount/write-off inputs labeled in company base; show invoice/payment document amounts alongside. Use Task 5 helpers for auto-apply and total/credit display. Aggregate split rows by invoice and display FX in base currency. Preserve source allocation on draft reopen/re-save.
+5. Fix memo available/staged-credit amounts, `getInvoicePayments`/application history reads, and all mirrored post/save caps. Foreign-currency amount displays must no longer use the payment currency formatter for a base value.
+6. Tests cover two invoice snapshots, foreign symbol/amount consistency, saved/reopened split rows, forged payloads, partial/large-rate eligibility, zero-cash credits, and memo status gates. Use `@internationalized/date`/Carbon datetime helpers for touched date code.
+
+**Verify:**
+```bash
+pnpm --dir apps/erp exec vitest run app/modules/invoicing/invoicing.settlements.test.ts app/modules/invoicing/invoicing.models.test.ts app/modules/invoicing/invoicing.reports.test.ts app/modules/invoicing/ui/Payment/PaymentApplyTable.test.tsx
+pnpm exec turbo run typecheck --filter=erp
+# Expected: corrected seeding/auto-apply/service/history tests and scoped typecheck pass.
+```
+
+**Out of scope:** a new payment screen, additional currency-pair support, arbitrary number-format constants.
+
+## Task 10: Normalize AP provider and inbound-payment boundaries
+
+**Depends on:** Tasks 5–8
+**Files:**
+- Modify: `packages/ee/src/accounting/core/document-costing.ts`.
+- Modify: `packages/ee/src/accounting/core/document-costing.test.ts`.
+- Modify: `packages/ee/src/accounting/core/payment-application.ts`.
+- Create: `packages/ee/src/accounting/core/payment-application.test.ts`.
+- Modify: `packages/ee/src/accounting/core/payment-syncer.ts`.
+- Modify: `packages/ee/src/accounting/providers/xero/entities/bill.ts`.
+- Modify: `packages/ee/src/accounting/providers/xero/entities/__tests__/bill.test.ts`.
+- Modify: `packages/ee/src/accounting/providers/xero/entities/__tests__/payment.test.ts`.
+- Modify: `packages/ee/src/accounting/providers/quickbooks-online/entities/bill.ts`.
+- Modify: `packages/ee/src/accounting/providers/quickbooks-online/entities/payment.ts`.
+- Modify: `packages/ee/src/accounting/providers/quickbooks-online/entities/__tests__/bill.test.ts`.
+- Modify: `packages/ee/src/accounting/providers/quickbooks-online/entities/__tests__/payment.test.ts`.
+- Modify: `packages/ee/src/accounting/providers/rillet/entities/bill.ts`.
+- Modify: `packages/ee/src/accounting/providers/rillet/entities/shared.ts`.
+- Modify: `packages/ee/src/accounting/providers/rillet/models.ts`.
+- Modify: `packages/ee/src/accounting/providers/rillet/entities/__tests__/bill.test.ts`.
+- Modify: `packages/ee/src/accounting/providers/rillet/entities/__tests__/payment.test.ts`.
+- Modify: `packages/ee/src/accounting/providers/rillet/entities/__tests__/payment-push.test.ts`.
+- Copy from (precedent): `packages/ee/src/accounting/core/document-costing.test.ts` for journal-read stubs; `packages/ee/src/accounting/providers/rillet/entities/__tests__/payment.test.ts` for transaction/payment mapping stubs; `packages/ee/src/accounting/providers/xero/serialize.ts` for named external precision.
+
+**Steps:**
+1. Replace the positional conversion signature with `toTransactionCurrencyLines(lines: CostingLine[], args: {exchangeRate: number; documentTotal: number; decimalPlaces: number}): CostingLine[]`. Validate finite amounts, positive finite rate and supported decimal scale. Convert each base amount by multiplication, then round to the passed document boundary. Preserve negative variance lines, account IDs, source-item labels and dimensions. Reconcile against the supplied authoritative document total using deterministic largest-magnitude-line residual assignment. Do not round the base sum to cents first; do not use this residual to conceal an economic discrepancy larger than the rounding envelope of the source/internal and destination scales. Apply the same reconciliation at rate 1; an identity rate is not permission to skip document rounding.
+2. Extend `BillCostingResult` and `loadBillCostingLines` with `documentTotal`, `decimalPlaces`, `baseCurrencyCode` and `postingDate`. Load company/base and invoice currency metadata with company-scoped header reads, and compute the authoritative document total from non-comment purchase lines' `quantity * supplierUnitPrice + supplierShippingCost + supplierTaxAmount`, plus `purchaseInvoiceDelivery.supplierShippingCost`, rounded once to document decimals. Preserve generated unprefixed purchase fields as base. Missing currency/rate/precision is an error, not a USD/rate-1 fallback. Keep the existing posted-journal selection, AP-control exclusion, account-class debit conversion and dimension loading.
+3. Update **all three production callers**: Xero `BillSyncer.mapToRemote`, QBO `QboBillSyncer.mapToRemote`, and Rillet `mapBillToRilletBill` through `RilletBillSyncer.mapToRemote`. Pass the new explicit object and carry costing-result metadata into the Rillet pure mapper's argument. Update every existing test invocation of the helper/mapper. Check the resulting provider bill total against `documentTotal` before its create/update API call; AP replay stays tax-neutral because tax is already in the costing lines.
+4. Xero bill `CurrencyRate` remains Carbon `r`. QBO bill `ExchangeRate` becomes `1/r`; QBO `mapToLocal` must also return `currencyCode` from `CurrencyRef` and the reciprocal of remote `ExchangeRate` before local supplier fields are populated. QBO payment `mapToNormalized` performs the same reciprocal conversion. Missing remote rate is identity only when the authoritative currencies identify a base-currency document. Tests must assert both outbound payloads and inbound stored snapshots.
+5. Add `Rillet.ExchangeRateSchema`/type with required `{base: string; target: string; rate: string; date: string}` and use it for the bill request/response schema. Add pure `toRilletExchangeRate(args: {baseCurrencyCode: string; documentCurrencyCode: string; foreignPerBaseRate: number; date: string}): Rillet.ExchangeRate | undefined` in `rillet/entities/shared.ts`. Omit on identical currencies after validating identity; otherwise produce `{base: baseCurrencyCode, target: documentCurrencyCode, rate: String(foreignPerBaseRate), date}` without numeric-string rounding to money precision. Pass the invoice posting date through the existing date helpers.
+6. **Rillet direction evidence:** the official [Create Bill schema](https://docs.api.rillet.com/reference/create-a-bill-1.md) proves the object fields/types, not the arithmetic direction. `base=company currency`, `target=document currency`, `rate=r` is an explicitly labeled directed-pair inference. Pin the schema-valid USD→EUR/r0.8 fixture and the intended economic result (80 EUR carrying 100 USD); independently verify the provider's directed-pair behavior against a provider-returned fixture/read-only sandbox evidence before declaring the integration verified. If the provider requires the reverse pair, invert both pair and rate together in this helper and document that evidence. A self-authored serializer test is not independent provider verification. Do not send `exchange_rate` on `AR_ONLY`: the published AR_ONLY create schema does not contain it; Task 11 preserves that scope.
+7. Change `toRilletMoney` to accept an explicit document decimal scale on the corrected bill/invoice paths, while preserving existing unrelated callers until their own scopes are changed: `toRilletMoney(amount: number, currency: string, decimalPlaces?: number): Rillet.MonetaryAmount`. Corrected callers always supply DB currency decimals and serialize the rounded decimal string at that scale. Add 0/3-decimal bill fixtures; do not globally change unrelated contact/product/payment serialization in this task.
+8. Update the actual shared inbound function, `upsertLocalPaymentDraft(tx: KyselyTx, args: UpsertPaymentDraftArgs): Promise<UpsertPaymentDraftResult>`. Batch-load document mappings, then the resolved invoices with company, party, currency, rate and authoritative totals before payment/settlement mutations. Retain the documented ownership skip for remote documents without any Carbon mapping; a mapping pointing to a missing/cross-company invoice, an invalid rate, a mixed party, or an unsupported currency pair is an error. Keep payment `totalAmount` in remote/payment currency. For each linked document store exact remote principal as `sourceAmount`, derive target-base `appliedAmount` through Task 5's helpers, set current-cash `sourcePaymentId:null`, and store authoritative source/target snapshots; remove `targetExchangeRate:1`.
+9. Preserve existing mapping identity, draft replacement, posted-payment/void idempotency, `withTriggersDisabled` around local sync writes, and subsequent invocation of `post-payment`. Re-read targets in the posting transaction as required by Task 8; adapter previews do not replace authoritative posting validation.
+10. Extend `PaymentSyncerBase.loadLocalPaymentForPush` and its internal payment/settlement types to select `sourceAmount`/`sourcePaymentId`. Keep existing FX/discount/write-off/fee capability gates, reject credit-funded rows before remote payment creation, and compare/send supported cash principal in document currency. Existing base-currency cash fan-out remains supported; do not coalesce prior-credit consumption into a fictitious remote cash payment.
+11. Add fixtures for base100→document80 at r0.8, negative PPV, largest-line residual, authoritative-total mismatch, 0/3 decimals, QBO reciprocal inbound/outbound rates, Rillet object shape, and remote principal110 with invoice r1.25/payment r1.10 storing source110/base88. Include source160.01/r16000 and assert invalid pairs/mappings produce zero draft/settlement mutations; credit-funded outbound cases produce zero remote payment writes.
+
+**Verify:**
+```bash
+pnpm --filter @carbon/ee exec vitest run --config ../config/vitest.mts src/accounting/core/document-costing.test.ts src/accounting/core/payment-application.test.ts src/accounting/providers/xero/entities/__tests__/bill.test.ts src/accounting/providers/xero/entities/__tests__/payment.test.ts src/accounting/providers/quickbooks-online/entities/__tests__/bill.test.ts src/accounting/providers/quickbooks-online/entities/__tests__/payment.test.ts src/accounting/providers/rillet/entities/__tests__/bill.test.ts src/accounting/providers/rillet/entities/__tests__/payment.test.ts src/accounting/providers/rillet/entities/__tests__/payment-push.test.ts
+# Expected: every selected suite passes; amount/rate/residual and no-write failure fixtures pass. Source-config override avoids the currently absent @carbon/config/dist/vitest.mjs.
+```
+
+**Out of scope:** live provider writes during unit tests, new FX payment capabilities, historical corrections, changing PO/SO representations, treating Rillet rate-direction inference as verified API behavior.
+
+## Task 11: Export sales components through provider-native mappings
+
+**Depends on:** Tasks 4, 6 and 10
+**Files:**
+- Modify: `packages/ee/src/accounting/core/models.ts`.
+- Modify: `packages/ee/src/accounting/core/posting.ts` — add the structured `UNMAPPED_TAX_CODES` preflight warning code.
+- Create: `packages/ee/src/accounting/core/sales-document-components.ts`.
+- Create: `packages/ee/src/accounting/core/sales-document-components.test.ts`.
+- Read/reuse: `packages/utils/src/sales-posting-amounts.ts`, `packages/utils/src/index.ts` — Task 6 supplies this Node re-export.
+- Modify: `packages/ee/src/accounting/providers/xero/entities/invoice.ts`.
+- Modify: `packages/ee/src/accounting/providers/xero/entities/__tests__/invoice.test.ts`.
+- Modify: `packages/ee/src/accounting/providers/quickbooks-online/entities/invoice.ts`.
+- Modify: `packages/ee/src/accounting/providers/quickbooks-online/entities/item.ts`.
+- Modify: `packages/ee/src/accounting/providers/quickbooks-online/models.ts`.
+- Create: `packages/ee/src/accounting/providers/quickbooks-online/entities/invoice-tax.ts`.
+- Create: `packages/ee/src/accounting/providers/quickbooks-online/entities/__tests__/invoice-tax.test.ts`.
+- Modify: `packages/ee/src/accounting/providers/quickbooks-online/entities/__tests__/invoice.test.ts`.
+- Modify: `packages/ee/src/accounting/providers/quickbooks-online/entities/__tests__/item.test.ts`.
+- Modify: `packages/ee/src/accounting/providers/rillet/entities/invoice.ts`.
+- Modify: `packages/ee/src/accounting/providers/rillet/entities/item.ts`.
+- Modify: `packages/ee/src/accounting/providers/rillet/models.ts`.
+- Modify: `packages/ee/src/accounting/providers/rillet/entities/__tests__/invoice.test.ts`.
+- Create: `packages/ee/src/accounting/providers/rillet/entities/__tests__/item.test.ts` — this test file does not currently exist.
+- Read/reuse: `packages/ee/src/accounting/core/external-mapping.ts`, `packages/ee/src/accounting/core/account-mapping.ts`, `packages/ee/src/accounting/core/sync.ts`, `packages/ee/src/accounting/providers/quickbooks-online/entities/shared.ts`, `packages/ee/src/accounting/providers/quickbooks-online/provider.ts`, `packages/ee/src/accounting/providers/rillet/entities/shared.ts`, `packages/ee/src/accounting/providers/rillet/provider.ts`.
+- Copy from (precedent): the existing QBO item tests/mappers, Rillet `mapItemToRilletProduct`, `buildRilletIdempotencyKey`, account-code/ref resolvers, and the `dimensionValue` mapping pattern for non-entity helper identities.
+
+**Steps:**
+1. Extend `SalesInvoiceLineSchema` with base `shippingCost`, `addOnCost`, `nonTaxableAddOnCost` (zero-defaulted for old normalized fixtures); retain fractional `taxPercent` and optional `convertedUnitPrice`. Extend `SalesInvoiceSchema` with base `headerShippingCost`, `baseCurrencyCode`, `baseCurrencyDecimalPlaces` and authoritative `currencyDecimalPlaces`. Update each provider's local header/line row types and **all three `fetchLocalBatch` implementations**: select the charge columns and `convertedUnitPrice`, left-join/batch-load `salesInvoiceShipment.shippingCost`, company base currency, and document `currency.decimalPlaces`. Use the authoritative `salesInvoices` view for base totals/balance, scope source rows to company, and avoid per-line/header queries. Missing currency metadata must fail rather than become guessed precision/rate.
+2. Define `SalesDocumentComponent = {id: string; sourceLineId: string | null; kind: "Merchandise" | "TaxableAddOn" | "NonTaxableAddOn" | "LineShipping" | "HeaderShipping"; itemId: string | null; itemCode: string | null; description: string; quantity: number; unitAmount: number; netAmount: number; taxPercent: number; taxAmount: number}` and `SalesDocumentComponents = {currencyCode: string; decimalPlaces: number; components: SalesDocumentComponent[]; subtotal: number; totalTax: number; totalAmount: number; balance: number}`. Export `buildSalesDocumentComponents(invoice: Accounting.SalesInvoice): SalesDocumentComponents`. Import the Task 6 pure breakdown/allocator through the new utils re-export so tax bases/allocation are shared with posting. Ignore comments. Preserve merchandise quantity/item identity; add-ons and shipping become quantity-one rows. Line shipping and taxable add-ons retain the source fractional rate; header shipping/non-taxable add-ons have zero tax. Tax is metadata/native tax, never another net/revenue component. Use stable IDs derived from source line plus component kind; header shipping uses a stable invoice-derived ID.
+3. Convert base amounts once with Task 5 helpers and currency decimals. Prefer the stored document unit mirror for merchandise when present; validate consistency with the rate snapshot. Reconcile line net/tax rounding deterministically to authoritative document subtotal/tax/gross derived from the source invoice contract. Do not force agreement by altering a tax rate or adding an unclassified sales charge. Preserve exact source references; zero amounts omit empty components. Tests cover zero quantity with a positive add-on, zero weights, header residuals, and 0/3-decimal documents.
+4. Refactor Xero's `SalesInvoiceSyncer.mapToRemote` to consume the component result. Add a pure `buildXeroSalesInvoiceLines(args: {document: SalesDocumentComponents; salesAccountCode: string; shippingAccountCode: string | null}): Xero.InvoiceLineItem[]`. Merchandise/add-ons use mapped Sales; line/header shipping use mapped Shipping Revenue. Keep merchandise ItemCode dependency mapping. Set native `TaxAmount` from the component's document tax and remove the extra `/100`; preserve `LineAmountTypes:"Exclusive"` and current Xero taxable/zero-tax types. Header shipping stays untaxed. Populate subtotal/tax/total/amount due/paid from reconciled document values, and retain `CurrencyRate:r`. Require shipping mapping only when a nonzero shipping component exists.
+5. Add public `QboItemSyncer.ensureShippingItem(args: {shippingAccountId: string}): Promise<string>` and `RilletItemSyncer.ensureShippingProduct(args: {shippingAccountId: string; baseCurrencyCode: string; baseCurrencyDecimals: number}): Promise<string>`. Resolve these existing syncer classes through `SyncFactory.getSyncer` in `core/sync.ts` using the current provider/client/database/company context (dynamic import after preflight to preserve the existing module-cycle boundary), and narrow to the concrete item syncer before calling its new method; do not register a new entity syncer. Resolve/validate the Carbon shipping default and its external account mapping before dependency writes. Reuse current account-ref/code loaders and provider create/read/update methods. Cache by helper identity per syncer instance/batch; do not issue a lookup for every component.
+6. Store helper identity using `createMappingService.link("shippingItem", helperId, providerId, remoteId, {metadata: {accountId: shippingAccountId, kind: "shipping"}})` inside existing trigger-suppressed mapping writes. QBO `helperId=shippingAccountId`; Rillet `helperId=shippingAccountId + ":" + baseCurrencyCode`. Never link it under `entityType:"item"` to a nonexistent local item. Include company scope through the mapping service. A changed shipping default selects a different helper identity without repointing merchandise products.
+7. QBO helper payload is a sales-only `{Name, Description, Type:"Service", Active:true, UnitPrice:0, IncomeAccountRef:mappedShippingRef}` with no inventory or purchase fields. Use deterministic name `Carbon Shipping <shippingAccountId>` within QBO's name limit. Recover a missing local link by exact remote name query; only reuse a compatible active Service with the expected account. An incompatible name/account is a structured `UNMAPPED_ACCOUNTS` Warning; do not overwrite an unrelated match. Recover duplicate-name races by re-reading and validating that same name, then link; use existing SyncToken retry only for a helper already owned by its mapping. QBO's [IncomeAccountRef contract](https://static.developer.intuit.com/sdkdocs/qbv3doc/ippdotnetdevkitv3/html/e53f8d57-d526-2cee-9c6b-03359cfaae37.htm) makes that service's revenue account authoritative.
+8. Rillet helper reuses the existing product mapper with explicit shipping account mapping: deterministic name `Carbon Shipping <shippingAccountId> <baseCurrencyCode>`, ONE_TIME nominal zero price in base currency, `include_in_arr_mrr:false`, `revenue_pattern:"EVEN_PERIOD"`, `status:"ACTIVE"`, and mapped shipping `account_code`. Persist/read the `shippingItem` mapping and reuse entity-scoped `buildRilletIdempotencyKey({companyId,operation:"product",localId:helperId})` for create recovery; never make the key payload-sensitive. Use existing external-reference retry behavior. Existing mapped-product updates must retrieve/merge the full product before PUT, preserving unrelated fields; do not smart-match and mutate an unrelated product by name. The [official product schema](https://docs.api.rillet.com/reference/create-a-product-1.md) supplies the valid fields.
+9. Add QBO `TaxCode`, `TaxRate`, `TaxLineDetail`, and `TxnTaxDetail` schemas/types from the official contracts; extend `SalesItemLineDetailSchema` with `TaxCodeRef` and invoice schema with `TxnTaxDetail`, `CurrencyRef`, `ExchangeRate`, and the supported global-tax calculation field. Add `loadQboInvoiceTaxCatalog(provider: QboProvider): Promise<{country: string; taxCodes: Qbo.TaxCode[]; taxRates: Qbo.TaxRate[]}>` in `invoice-tax.ts`. Reuse `provider.getCompanyInfo()` and paginated `provider.query<Qbo.TaxCode>("TaxCode")`/`provider.query<Qbo.TaxRate>("TaxRate")`; fetch once per syncer batch, filter inactive records, and propagate fetch failures. Do not call TaxService/create tax codes or infer jurisdiction from company base currency.
+10. Export pure `resolveQboInvoiceTax(args: {document: SalesDocumentComponents; catalog: {country: string; taxCodes: readonly Qbo.TaxCode[]; taxRates: readonly Qbo.TaxRate[]}}): {lineTaxCodeRefs: ReadonlyMap<string, Qbo.Ref>; txnTaxDetail: Qbo.TxnTaxDetail | undefined}`. Resolve every distinct nonzero Carbon fractional rate through an active **sales** `TaxCode.SalesTaxRateList` and its existing `TaxRateRef` rows; compare Carbon fraction×100 with the remote percentage value at rate precision. Support a unique simple percentage rate/code; reject missing references, duplicate compatible choices, compound/tax-on-tax requirements, or dated/locale rules that cannot reproduce the supplied tax from the catalog. Resolve zero-tax line markers/codes from the provider's actual catalog/locale contract; never fabricate remote IDs. For US use the single resolved transaction tax code and applicable line taxable/non-taxable markers; incompatible multiple transaction codes fail before send. For global tax use the resolved line codes and tax detail referencing only rates belonging to them. Group tax detail by real TaxRateRef, with native `Amount`, `NetAmountTaxable`, `PercentBased:true`, `TaxPercent` in percentage points, and `TotalTax` from the source component totals. [Native tax detail](https://static.developer.intuit.com/sdkdocs/qbv3doc/ippdotnetdevkitv3/html/7328bab2-a9ed-621e-41fa-188e45aaac65.htm) and [rate membership/percentage rules](https://static.developer.intuit.com/sdkdocs/qbv3doc/ippdotnetdevkitv3/html/9a4b9306-4684-179c-4b74-3896047aa53b.htm) are the contract. This resolver translates existing tax facts; it does not calculate a new tax policy.
+11. Missing/ambiguous/unsupported QBO tax resolution throws `JournalEntrySyncError({errorCode:"UNMAPPED_TAX_CODES", warning:true, message, metadata:{invoiceId, requestedRates, candidateTaxCodeIds, reason}})` before customer/item/helper provisioning or invoice create/update. The message names the requested percentage and unresolved remote tax configuration. Add that code to the existing structured error union in `core/posting.ts`. No fallback to a first tax code, a generated numeric ID, untaxed export, or tax-as-revenue is allowed.
+12. Change `buildQboInvoiceLines` to `buildQboInvoiceLines(args: {document: SalesDocumentComponents; itemRemoteIds: ReadonlyMap<string,string>; shippingItemRemoteId: string | null; lineTaxCodeRefs: ReadonlyMap<string,Qbo.Ref>}): Array<Omit<Qbo.InvoiceLine,"Id">>`. Merchandise/add-ons retain the source item's mapping; shipping uses the helper ItemRef, Qty1 and document UnitPrice/Amount. Require an actual item mapping for any provider line that needs one; retain each provider's existing no-item capability gate and never attach an unrelated product as a fallback. Wire the tax resolver and builder into `QboSalesInvoiceSyncer.mapToRemote`, attach native `TxnTaxDetail`, document `CurrencyRef`, and reciprocal `ExchangeRate:1/r`. Test the locale-specific tax fixture through the actual `mapToRemote` call and assert invoice total equals component net plus native tax; tax must not also appear in the ordinary Line array.
+13. Extend `mapSalesInvoiceToRilletInvoice` arguments with `document: SalesDocumentComponents`, `shippingProductRemoteId: string | null`, and `shippingAccountCode: string | null`, preserving its current customer/item/subsidiary/company/documentUrl arguments. Merchandise/add-ons use existing product IDs, shipping uses its helper product; every AR_ONLY row carries `product_id`, description, quantity, document `total_amount`, and the existing required external references keyed by component identity. Add the documented optional `revenue:{account_code}` to Rillet invoice-item schema and set it for shipping. Use **native header `tax_amount` exactly once**, equal to the reconciled document tax; do not also add a tax product or duplicate it in every item. The [AR_ONLY schema](https://docs.api.rillet.com/reference/create-an-invoice-1.md) permits header/item native tax and requires products; its AR_ONLY request has no `exchange_rate`. Keep AR_ONLY and omit that field. This task does not claim provider support for pinning a custom AR_ONLY FX rate; foreign invoice component-currency correctness and provider-owned base translation must be distinguished in tests/reporting, and the Task 10 bill-rate helper must not be copied onto AR_ONLY.
+14. Preflight all account/tax/currency/component requirements before any provider document write. Add real-call-site query fixtures proving all three `fetchLocalBatch` implementations supply shipping/add-ons and authoritative decimals/totals. Add the base151/r0.8→document120.80 fixture (net98.40 Sales, net12 Shipping, tax10.40), mixed taxable/non-taxable charges, source/header references, native tax once, schema-valid Rillet product lines, and documented AR_ONLY FX limitation. Test helper mapping reuse, remote-create/local-link retry, duplicate-name race, incompatible helper, unmapped shipping, zero shipping, and missing/ambiguous QBO tax catalogs. Assert zero remote invoice writes on every preflight failure and no provisioning on a zero shipping amount.
+
+**Verify:**
+```bash
+pnpm --filter @carbon/ee exec vitest run --config ../config/vitest.mts src/accounting/core/sales-document-components.test.ts src/accounting/providers/xero/entities/__tests__/invoice.test.ts src/accounting/providers/quickbooks-online/entities/__tests__/invoice-tax.test.ts src/accounting/providers/quickbooks-online/entities/__tests__/invoice.test.ts src/accounting/providers/quickbooks-online/entities/__tests__/item.test.ts src/accounting/providers/rillet/entities/__tests__/invoice.test.ts src/accounting/providers/rillet/entities/__tests__/item.test.ts
+# Expected: every selected suite passes; real fetch→map fixtures retain document totals, shipping account effects and native tax, retry does not duplicate helpers, and missing/ambiguous tax/account mappings cause zero remote invoice writes.
+```
+
+**Out of scope:** new provider entity syncers, local inventory shipping items, tracked remote products, tax-code creation/tax determination, silently changing Rillet revenue-recognition scope or promising a custom FX snapshot on AR_ONLY.
+
+## Task 12: Correct translation arithmetic and error handling
+
+**Depends on:** Task 1; independent of posting tasks
+**Files:**
+- Modify: `apps/erp/app/modules/accounting/accounting.ee.service.ts`.
+- Create: `apps/erp/app/modules/accounting/accounting.translation.test.ts`.
+- Copy from (precedent): import/settings/glossary mocks in `accounting.periods.test.ts`; current precision helpers and `packages/utils/src/accounting.ts`.
+
+**Steps:**
+1. Keep `translateCompanyBalances(client,companyGroupId,companyId,targetCurrency,periodEnd,periodStart,balances)` and its result shape. Reject invalid classes/nonfinite balances and source debit-minus-credit imbalance after excluding groups and synthetic net income. Use the service's existing `isBalanced` helper with `JOURNAL_BALANCE_TOLERANCE` (currently 0.001), not a new unrelated cent threshold; this source validation does not change journal posting tolerances.
+2. Compute CTA with Asset/Expense positive and Liability/Equity/Revenue negative. Preserve negative balances. Do not use `rootSignMultiplier` for this sum.
+3. Replace successful-empty-RPC fallback1 with an error. Require source currency and positive finite applicable rates. Preserve same-currency identity, RPC error propagation, and September target/source SQL policy.
+4. Mock RPC by name/arguments, because bucket/company calls run concurrently. Test the real exported service with identity80/100/20→CTA0; negative cash; closing2/average1.5→CTA40; source79/100/20 failure; unknown class; malformed rates; group/synthetic exclusion; failed bucket returning no partial report.
+
+**Verify:**
+```bash
+pnpm --dir apps/erp exec vitest run app/modules/accounting/accounting.translation.test.ts
+# Expected: all translation/source-validation/error fixtures pass using the real service.
+```
+
+**Out of scope:** rate RPC rewrites, posted CTA, historical equity layers, fiscal-year earnings redesign.
+
+## Task 13: Apply CTA by configured account and reroll report totals
+
+**Depends on:** Task 12; serialize with Task 4's service edits
+**Files:**
+- Modify: `apps/erp/app/modules/accounting/accounting.ee.service.ts`, `apps/erp/app/routes/x+/reports+/balance-sheet.tsx`.
+- Extend: `apps/erp/app/modules/accounting/accounting.translation.test.ts`.
+- Create: `apps/erp/app/routes/x+/reports+/balance-sheet.test.ts`.
+- Copy from (precedent): `apps/erp/app/routes/x+/inspection+/$id.reject.test.ts` for route tests; existing `rollUpTranslatedGroups` and `applyRootSignCorrectionToSeries`.
+
+**Steps:**
+1. Add `applyCtaToReportPeriodSeries(client, companyGroupId, reportingCompanyId, args: {accounts: ChartPeriodSeries[]; bucketKeys: string[]; ctaByBucket: Record<string,number>}): Promise<{data: ChartPeriodSeries[] | null; error: {message:string} | null}>` in the existing service.
+2. Read `getDefaultAccounts(client,reportingCompanyId)`, resolve CTA by ID, and validate active Balance Sheet Equity leaf/group ownership. If the supplied chart lacks fields needed to validate ownership/active state, batch-fetch that account through the client rather than assuming the fields exist.
+3. Clone rows/cells, add each bucket's CTA once, then rerun existing translated rollups/root correction. These helpers recompute groups/roots from children; do not multiply already-presented rows by a second sign. Missing mapping/cell yields an explicit error. Preserve booked CTA and do not mutate caller input.
+4. Remove hardcoded3200 and route-local `applyCtaByBucket`. Both translated branches pass the resolved root company ID and full chart to the helper before Balance Sheet filtering. Preserve nontranslated flow and existing redirect/flash errors. CSV already consumes loader rows; use the corrected rows unchanged.
+5. Tests cover custom number/name, different active/child default, invalid mapping, two buckets, repeated calculation on original inputs, subsidiary failure, and leaf/intermediate/root/export agreement.
+
+**Verify:**
+```bash
+pnpm --dir apps/erp exec vitest run app/modules/accounting/accounting.translation.test.ts app/routes/x+/reports+/balance-sheet.test.ts
+# Expected: configured parent account used in both translated branches; Cash160/NI120/CTA40 produces Equity160 and Balance Sheet root0, with CTA applied exactly once.
+```
+
+**Out of scope:** report route renames, UI redesign, applying CTA to un-translated reports.
+
+## Task 14: Normalize invoice balances and AR/AP reporting SQL
+
+**Depends on:** Tasks 8–9
+**Files:**
+- Create: the unique migration emitted by `pnpm db:migrate:new accounting_balances_and_reports` in `packages/database/supabase/migrations/`; record the generated path here during execution.
+- Create: `packages/database/supabase/tests/accounting-balances-and-reports.test.sql`.
+- Read: `packages/database/supabase/migrations/20260702224219_fix-ar-ap-legacy-paid.sql`, `packages/database/supabase/migrations/20260811123616_widen-purchasing-scale.sql`.
+
+**Steps:**
+1. Write the full latest invoice-view corrections and six RPC definitions from Appendix B into the CLI-created forward migration. Preserve existing view column order and RPC signatures; use SECURITY INVOKER. If a newer definition landed, STOP and reconcile the diff before replacing it.
+2. Replace base-cent forgiveness with document-currency settlement completion. Positive foreign minor units must remain payable even when base value is below0.01 or rounds to zero at ledger scale. Use exact stored source principal and document equivalents of noncash relief; preserve raw generated purchase amounts and legacy base-table Paid/datePaid guards.
+3. Normalize all six functions: `get_ar_tie_out`, `get_ap_tie_out`, `get_ar_open_by_customer`, `get_ap_open_by_supplier`, `get_ar_aging`, `get_ap_aging`. Invoice carrying amounts are base; memo/payment source amounts divide to base. Include effective memo applications and prior-credit attribution exactly once with applying-status/cutoff gates. Drill-down `openInCurrency` is document and `openInBase` is base.
+4. Add rollback SQL fixtures for AR/AP partial/full payment, memo application, unapplied/current/prior cash, two snapshots, cutoff before/after consumption, source/application void behavior, legacy Paid guard, and large-rate document remainder. Assert aging total = open items + unapplied = control GL within the configured precision.
+5. Apply to the existing local database and immediately continue to Task 15 before typechecking.
+
+**Verify:**
+```bash
+pnpm db:migrate
+# Expected: forward report migration applies; no dropped columns/signature overloads and no PostgREST schema-cache error.
+```
+
+**Out of scope:** new aging UI, rewriting historical documents, excluding legitimate memo/source credit balances to make a tie-out pass.
+
+## Task 15: Generate types after the reporting migration
+
+**Depends on:** Task 14
+**Files:**
+- Regenerate: outputs of `scripts/generate-db-types.ts`.
+- Verify: `packages/database/supabase/tests/accounting-balances-and-reports.test.sql`.
+
+**Steps:**
+1. Regenerate types and verify the existing six RPC signatures remain stable.
+2. Run the SQL fixtures against the migrated local stack. Any missing source principal in a posted fixture is a fixture failure, not a reason to reinstate the old arithmetic.
+
+**Verify:**
+```bash
+pnpm run generate:types
+pnpm exec tsx scripts/run-local-accounting-check.ts psql -v ON_ERROR_STOP=1 -f packages/database/supabase/tests/accounting-balances-and-reports.test.sql
+# Expected: every AR/AP/source/cutoff/precision assertion passes, ALL SCENARIOS PASSED, ROLLBACK, exit 0.
+```
+
+**Out of scope:** manually adjusting generated RPC types.
+
+## Task 16: Prove database and posting transaction invariants
+
+**Depends on:** Tasks 4–15
+**Files:**
+- Create: `packages/database/supabase/tests/accounting-posting-corrections.test.sql`.
+- Modify: `packages/database/supabase/tests/intercompany-elimination.test.sql` to add multiline taxed/shipping captures without stale Draft-counting assumptions.
+- Create: `packages/database/supabase/functions/post-payment/post-payment-concurrency.test.ts`.
+- Extend: sales/purchase helper and payment transaction tests from Tasks 6–8.
+- Copy from (precedent): rollback harness in `intercompany-elimination.test.sql`; transaction cleanup mechanics in `packages/database/src/datasets/verify.ts`.
+
+**Steps:**
+1. SQL fixtures use an isolated test company/group, explicit fixture/default account IDs, current Posted status, valid periods and audit fields. Wrap in BEGIN/ROLLBACK. Execute `SET LOCAL "app.sync_in_progress" = 'true'` before fixture bootstrap, as in `packages/database/src/datasets/verify.ts`; apply it within every independent concurrency connection/transaction as well. Rollback cannot undo already-dispatched `pg_net` requests from another connection. Do not copy hardcoded business-company names.
+2. Prove generated invoice denominations, all sourceAmount/sourcePaymentId constraints, exact source availability, and real consolidation pair rates. Seed/capture a multiline IC trade, invoke the real elimination RPC, and assert all IC control/revenue rows eliminate while external tax/group cost remain.
+3. Import the production `postPaymentTransaction` with independent local DB connections for simultaneous consumers of one test credit source. Only affordable allocations may commit; no overspend/duplicate journals. Test a fault after settlement writes and before journal completion, asserting full rollback. Cleanup only records created by this test, never broad table/company deletes.
+4. Run the actual local post-sales-invoice/post-purchase-invoice/post-payment endpoints on isolated test documents in Task 18. Pure builders/seeded SQL capture tests cannot claim the HTTP posting wiring is proven.
+5. Verify direct versus receipt/shipment-owned postings, metadata row alignment, complete IC controls, unchanged booked-value reversals, and persisted FX sum equality. Record exact failed/passed scenario names.
+
+**Verify:**
+```bash
+pnpm exec tsx scripts/run-local-accounting-check.ts psql -v ON_ERROR_STOP=1 -f packages/database/supabase/tests/accounting-posting-corrections.test.sql
+pnpm exec tsx scripts/run-local-accounting-check.ts psql -v ON_ERROR_STOP=1 -f packages/database/supabase/tests/intercompany-elimination.test.sql
+pnpm exec tsx scripts/run-local-accounting-check.ts deno test --no-lock --allow-env --allow-net --config packages/database/supabase/functions/deno.json packages/database/supabase/functions/post-payment/post-payment-concurrency.test.ts
+# Expected: both SQL harnesses report ALL SCENARIOS PASSED and ROLLBACK; actual concurrency/rollback tests pass against local DB.
+```
+
+**Out of scope:** a database rebuild, production fixtures, live provider writes, claiming seeded SQL alone executes TypeScript posting code.
+
+## Task 17: Run integration gates and update technical guidance
+
+**Depends on:** Task 16
+**Files:**
+- Modify: `.claude/rules/accounting-sync-handlers.md`, `.claude/rules/numeric-precision.md` — corrected denominations/provider boundaries and source precision.
+- Modify: `apps/erp/app/modules/accounting/AGENTS.md` — current natural-balance sign/test commands and CTA integration facts.
+- Update: the linked spec's implementation changelog and this progress checklist with actual evidence.
+- Regenerate: affected `packages/locale/locales/` catalogs through `/translate`; no hand-invented glossary terms.
+
+**Steps:**
+1. Run `/translate` for new UI strings after extraction using current locale tooling. Keep new money inputs on named precision kinds.
+2. Update stale technical guidance: base→document costing multiplies; Xero rate passes through/QBO reciprocates; source principal is distinct from base relief; CTA uses natural debit/credit signs and configured root account. Do not leave docs claiming the old multiply convention or a nonexistent package name.
+3. Run the focused tests from Tasks 4–16, then the scoped typechecks/gates below once. All dataset/backup checks must actually run against the migrated schema; skip messages are not passing evidence.
+4. Run scoped Biome on touched source/UI files via the check-and-commit skill's changed-file selection. Do not format unrelated files. Check the final diff for changes outside the spec, credentials, generated-type hand edits, or operational data writes.
+5. Use `/self-review` on the integrated branch. Resolve must-fix findings, rerun affected checks, and record material limitations. Do not mark the spec implemented or promise deployment before the final workflow proof.
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=erp --filter=@carbon/ee --filter=@carbon/database --filter=@carbon/utils
+pnpm db:check:datasets
+pnpm db:check:backups
+git diff --check
+# Expected: all scoped gates exit0; datasets/backups produce actual success; no whitespace errors.
+```
+
+**Out of scope:** whole-repository typecheck/build merely for completeness, unrelated lint cleanup, auto-merging/publishing.
+
+## Task 18: Verify the user workflows in the browser
+
+**Depends on:** Task 17; existing local stack running and migrated
+**Files:**
+- Create/update after PASS: `.ai/playbooks/accounting-posting-corrections.md`.
+- Read precedents: `.ai/playbooks/create-sales-invoice.md`, `.ai/playbooks/create-purchase-invoice.md`, `.ai/playbooks/create-and-apply-payment.md`, `.ai/playbooks/account-ledger-drilldown.md`.
+
+**Steps:**
+1. Use `/test` and `/auth` once browser verification is authorized by execution. Use local isolated test documents/accounts. Current report URLs are `/x/reports/balance-sheet`, `/x/reports/income-statement`, `/x/reports/trial-balance`; do not copy stale playbook routes or claims that Draft journals count.
+2. Workflow A: save Shipping Revenue default, create/post the sales 151-base/120.80-EUR fixture, inspect actual ledger accounts/dimensions, receive the correct foreign payment, confirm paid status/tie-out, void payment and invoice, and inspect exact reversing lines. Repeat purchase receipt/invoice matching with a non-1 UOM factor and verify zero PPV.
+3. Workflow B: create an unapplied foreign payment; apply partial credit with a later snapshot and a zero-cash applying payment. Confirm available document credit, FX, source-void refusal and applying-payment void restoration. Cover 160.01 source units/rate16000 across partial and final application; no premature Paid status.
+4. Workflow C: with posted balanced fixtures, verify identity Cash80/Income80/CTA0. For foreign closing2/average1.5 verify Cash160/Income120/CTA40 using the parent's custom-number CTA default. Switch single-subsidiary/All Companies, expand Equity and download CSV; leaf, subtotal/root and exported buckets agree.
+5. Use click→snapshot→option for custom selectors, fill→blur for numeric/date fields, and `form.requestSubmit(submitter)` for ValidatedForm. Capture `/error` evidence for failures; record PASS/FAIL/SKIP per workflow. A missing prerequisite is unfinished verification, not a PASS.
+6. Cache only successful flows, record source document/journal IDs and screenshots/CSV evidence, and close the browser. Final report states changes, tests, limitations, and implementation status without claiming full accounting compliance.
+
+**Verify:**
+```text
+/test accounting posting corrections
+Expected: PASS for all three workflows, actual posting/void records inspected,
+matching report CSV, and a successful playbook with current selectors.
+```
+
+**Out of scope:** production or provider-account transactions, altering real customer defaults, unrequested deployment.
+
+## Acceptance coverage
+
+| Spec acceptance group | Tasks |
+| --- | --- |
+| Default creation, backfill, settings, tenant/account validation | 2–4, 16, 18 |
+| Sales/tax/shipping amounts, allocation, disposal, metadata, exact reversal | 5–6, 16, 18 |
+| Purchase FX/cost/PPV and buyer control capture | 7, 16, 18 |
+| IC multiline controls, shipping elimination and per-trade cost | 6–7, 16 |
+| Cash/discount/write-off/fee, prior credit and exact source precision | 5, 8–9, 14–16, 18 |
+| Invalid rates/pairs, concurrency, rollback, retry and void | 5, 8–10, 16, 18 |
+| Aging/tie-out and cutoff/status/currency consistency | 9, 14–16, 18 |
+| Provider account effects, rates, source amounts and mapping reuse | 10–11 |
+| CTA signs, source/rate errors, configured account and report/export totals | 12–13, 16, 18 |
+
+## Execution notes
+
+- Task 18 passed in the existing local stack. Workflow A: shipping account 4040 saved/reloaded; real sales invoice posts AR 151 / Sales 123 / Shipping 15 / Tax 13; UI-created EUR 120.80 payment clears 151 base with FX 0, and payment/invoice voids exactly reverse all original account amounts. Workflow B: normal prior-credit FX 25 and source-void refusal/restoration pass; actual high-rate manual 160.00 leaves 0.01 document units and zero base carrying and Partially Paid, then final 0.01 closes Paid with FX 0. Workflow C: identity/foreign ×subsidiary/AllCompanies UI and all 54 CSV rows over two periods match, including custom CTA 40 / intermediate Equity 160 / root 0. Browser playbooks record setup and evidence paths. Final ERP payment suites pass 78 tests across 5 files, and ERP typecheck passed after the browser-driven fixes.
+
+- Task 9 high-rate browser regression: `9f217ca4e9` removes the inference that equal rounded base values mean full document settlement. Manual base .01 at r16000 now requests 160.00, while checkbox/Auto apply retain exact 160.01; zero discount/write-off edits preserve the partial selection. Four new component failures went red→green; 20 form/composer tests, ERP typecheck and Biome pass. Actual partial posting leaves invoice and source 0.01 document units with zero carrying base.
+
+- Task 9 browser verification found the payment cash input still used the company currency symbol/decimals. Added `PaymentForm.tsx` and its component test to the task: `e772107d48` selects formatting from the actual document currency and handles selection changes. Six new cases went red→green; all 11 form/composer cases, ERP typecheck and Biome pass, and browser EUR120.80 now shows the correct symbol. No UI strings were added.
+- Task 17 self-review corrected stale precision tolerances, posting-group account claims, the AP conversion helper signature and the provider FX-parity caveat. The generated backup manifest's unchanged columns retain baseline ordering, reducing its overall diff to the actual schema additions/version.
+
+- Tasks 8/9 committed as `51f5980dea` and `ec40c988d0`; historical control-account correction `22509cb934` retains the original invoice/source account after defaults change. Final focused payment runs pass 38 tests including independent concurrency; memo integration tests also pass. Nullable original account references fail explicitly. Full edge static checks retain eight reproduced shared Node/Deno diagnostics; there are no new diagnostics in the owned payment implementation.
+- Task 11 committed as `b247a4ecae`: 104 focused provider/component tests and all 904 EE tests pass, with scoped typecheck, Biome and 100 conformance tests. Native tax and shipping helpers are verified through real fetch/map call sites with mocked provider transport. No live provider writes were made; Rillet AR_ONLY still owns its base translation and its bill rate direction needs connected-provider confirmation.
+- Tasks 14/15 committed as `7d5795c5fd`: 84 live AR/AP SQL cases pass, including changed defaults, historical invoice/payment/memo controls, source cutoff and direct memo appliedDate. Type generation completed without changes, database typecheck and workflow catalog pass, and all four datasets plus actual backup compatibility checks pass. The backup hook staged its manifest under a wrong root-relative path; corrected the latest local commit and preserved existing generated column ordering after verifying identical column sets.
+- Task 7 HTTP verification caught a second UOM conversion during void; `bff40c8791` removes it. A fresh factor-5 receipt/invoice/void run passes eight ledger/quantity assertions. Direct inventory, received/direct asset and buyer IC HTTP fixtures also pass their monetary assertions; direct-asset lifecycle rollback remains a separate follow-up.
+- Task 16 committed as `8ad5c588ab`; schema and IC SQL suites pass all nine/seven scenario groups with rollback, and two independent database-connection payment races pass. No database reset or rebuild was used.
+- Task 17 full `pnpm run test` passes all 27 Turbo tasks. Earlier dev supervisor test timeouts coincided with measured Mac sleep intervals; its 65 tests pass in seven seconds while awake. Verification uses a bounded local keep-awake process. Docker clock lag after sleep caused browser session refresh loops; runtime recovery preserves database volumes.
+
+- Tasks 6/7/10 committed as `6a23f5e74d`, `a48586c98e`, `41e0617b1d`; 43 combined sales/purchase runtime tests, typed pure purchase helpers, 156 provider boundary tests, utils and EE scoped typechecks passed. Existing Deno Node/Pool driver diagnostics were reproduced on the baseline; runtime edge tests are explicit `--no-check`.
+- Task 8 internal seams include a reusable local DB fixture and the memo transaction entrypoint. Both endpoints retain their HTTP authorization wrappers. DB tests use `pnpm exec tsx scripts/run-local-accounting-check.ts deno test --no-lock --no-check --allow-env --allow-net --config packages/database/supabase/functions/deno.json <tests>`; typed pure tests run separately. The local fixture suppresses outbound triggers on every independent connection and removes only its own company and generated tenant tables.
+- Task 14 reporting correction: `openInBase` retains original posted control carrying less effective A/D/W; source carrying retains original rounded gross less recorded A±FX releases. A 100.004 control must remain 100.004 despite document rounding to 80 at r0.8. Document completion is tracked independently; a positive document/zero-base remainder stays visible with base zero. Appendix B includes this verified correction.
+
+- Task 10 represents a provider-omitted rate as `NormalizedPayment.exchangeRate: number | null`, resolving identity only after authoritative base/document currency reads. Persisted rates remain positive finite numbers; all three provider normalization callers carry omission faithfully.
+
+- Task 5 committed as `68cfee0b2a`: 42 Deno regressions, 177 existing utils tests, scoped utils typecheck and Biome passed. Exhausted sources cannot retain carrying base, and discount-only document closure must release the entire remaining target carrying value.
+- Tasks 4 and 13 share gated commit `a6b147100c`: both change the accounting service and account-mapping validation; the hook also stages all extracted UI catalogs, so their completed changes and translations ship together. Focused verification remains separate: 12 defaults/route tests, 6 seed tests, 49 consolidation/loader/export tests, 4 datasets, ERP typecheck, and 24 translations with no missing entries. Seed-company Deno check has 11 errors reproduced on baseline, with no new diagnostics; unchanged Node/Deno pool/storage typing remains out of scope.
+- Task 6 queues direct fixed-asset disposal writes in the existing posting transaction and batches its reads, preventing a later posting failure from leaving a partial disposal. Lifecycle ownership and void behavior are unchanged.
+
+- Tasks 2–3 committed together as `34228bee73` because schema gates require generated types in the same commit; live migration, shipping/settlement SQL assertions, four datasets, real backup compatibility check, workflow catalog and database typecheck passed. Task 12 committed as `09a4b0a4f1`; 32 translation regressions, Biome and ERP typecheck passed.
+- Local verification launcher supplies explicit libpq fields and an absolute `GIT_WORK_TREE` for git, preserving the correct workspace in nested package hooks. Generated DB types retain generator formatting.
+
+- Task 5 contract clarification: FundingSource and returned sourceRemainders carry remainingBase as well as document units. At source3/r3, three releases of1 must total base1 (.33333, .33333, .33334). The final release uses remaining carrying value; stored appliedAmount ± FX recovers it without adding a persisted column. Task8/9 callers supply these authoritative remainders.
+
+- Task 2 live migration binding found no `accountDefault.updatedAt` column. The failed transaction rolled back; removed that nonexistent assignment while retaining `updatedBy`, synchronized Appendix A, and migration then applied successfully.
+- Task 2 migration: `packages/database/supabase/migrations/20260908021155_accounting_posting_corrections.sql` (CLI-generated).
+
+- Task 1 committed as `5fb7356dfa`: 57 ERP tests, 40 Deno runtime tests, Biome and scoped ERP typecheck pass. React Router type generation resolved the missing `+types/root` prerequisite. Local stack booted normally without resetting a database.
+- Corrected Appendix A placement/extraction before any migration was created; the original unanchored marker split had matched text inside the extraction script. SQL content/design is unchanged.
+
+- Task 1: the configured Deno check reproduces six existing cross-runtime type errors in unchanged `functions/lib/postgres/index.ts`; runtime payment/memo verification uses `--no-check`, with static checks tracked separately. No production type-check suppression was added.
+- Task 1: corrected the local verification launcher to pass parsed libpq connection fields; putting a URI in `PGDATABASE` alone did not select the configured host/port.
+
+## Plan review evidence
+
+Checked on 2026-09-07 against the source baseline above:
+
+- All 18 task structures, existing/predecessor file paths, 28 relative artifact links, fenced examples, embedded Python syntax and whitespace checks pass. Both migration tasks have an immediate type-generation follow-up.
+- Offline PostgreSQL ECPG syntax checks pass for 27 schema statements, two view declarations, six RPC declarations and six extracted query bodies: 41 checks. View names/order remain 40 sales columns and 36 purchase columns; RPC signatures, defaults and result columns match the latest definitions.
+- ECPG does not bind live relations/types or compile the procedural DO bodies. Those bodies received static review; applying migrations and running the rollback/concurrency suites remain implementation work.
+- Eleven independent Decimal/integer reference assertions pass for sales components, FX, exact foreign minor-unit remainders, source-only completion and CTA/root signs.
+- The existing seven provider/costing suites pass all 51 tests using Task 10's source-config override. This records the current baseline; these existing expectations do not prove the proposed corrections.
+- No implementation tasks, schema applications, database resets or live provider writes were performed while authoring this plan. Rillet's directed bill-rate arithmetic still requires the independent evidence specified in Task 10.
+
+## Appendix A: Complete schema and account-backfill SQL
+
+The migration generator supplies the filename; this SQL supplies the entire body.
+
+<!-- schema-sql:start -->
+```sql
+-- Planning appendix only. Copy into the CLI-created forward migration.
+BEGIN;
+
+ALTER TABLE "accountDefault"
+ ADD COLUMN IF NOT EXISTS "salesShippingRevenueAccount" TEXT;
+ALTER TABLE "invoiceSettlement"
+ ADD COLUMN IF NOT EXISTS "sourcePaymentId" TEXT,
+ ADD COLUMN IF NOT EXISTS "sourceAmount" NUMERIC;
+ALTER TABLE "invoiceSettlement"
+ ALTER COLUMN "fxGainLossAmount" DROP EXPRESSION IF EXISTS;
+ALTER TABLE "invoiceSettlement"
+ ALTER COLUMN "fxGainLossAmount" SET DEFAULT 0;
+ALTER TABLE "invoiceSettlement"
+ DROP CONSTRAINT IF EXISTS "invoiceSettlement_anyComponent_check";
+ALTER TABLE "invoiceSettlement"
+ ADD CONSTRAINT "invoiceSettlement_anyComponent_check" CHECK (
+ "appliedAmount" + "discountAmount" + "writeOffAmount" > 0
+ OR COALESCE("sourceAmount", 0) > 0
+ );
+
+DO $constraints$
+BEGIN
+ IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conrelid='"accountDefault"'::regclass AND conname='accountDefault_salesShippingRevenueAccount_fkey') THEN
+ ALTER TABLE "accountDefault" ADD CONSTRAINT "accountDefault_salesShippingRevenueAccount_fkey"
+ FOREIGN KEY ("salesShippingRevenueAccount") REFERENCES "account"(id)
+ ON DELETE RESTRICT ON UPDATE CASCADE;
+ END IF;
+ IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conrelid='"payment"'::regclass AND conname='payment_id_companyId_key') THEN
+ ALTER TABLE "payment" ADD CONSTRAINT "payment_id_companyId_key" UNIQUE (id, "companyId");
+ END IF;
+ IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conrelid='"invoiceSettlement"'::regclass AND conname='invoiceSettlement_sourcePaymentId_companyId_fkey') THEN
+ ALTER TABLE "invoiceSettlement" ADD CONSTRAINT "invoiceSettlement_sourcePaymentId_companyId_fkey"
+ FOREIGN KEY ("sourcePaymentId", "companyId") REFERENCES "payment"(id, "companyId")
+ ON DELETE RESTRICT ON UPDATE CASCADE;
+ END IF;
+ IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conrelid='"invoiceSettlement"'::regclass AND conname='invoiceSettlement_sourcePaymentId_check') THEN
+ ALTER TABLE "invoiceSettlement" ADD CONSTRAINT "invoiceSettlement_sourcePaymentId_check"
+ CHECK ("sourcePaymentId" IS NULL OR (
+ "paymentId" IS NOT NULL AND "memoId" IS NULL AND "sourcePaymentId" <> "paymentId"
+ ));
+ END IF;
+ IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conrelid='"invoiceSettlement"'::regclass AND conname='invoiceSettlement_sourceAmount_check') THEN
+ ALTER TABLE "invoiceSettlement" ADD CONSTRAINT "invoiceSettlement_sourceAmount_check"
+ CHECK ("sourceAmount" IS NULL OR (
+ "sourceAmount" >= 0 AND "sourceAmount" NOT IN ('NaN'::numeric, 'Infinity'::numeric, '-Infinity'::numeric)
+ ));
+ END IF;
+END;
+$constraints$;
+
+CREATE INDEX IF NOT EXISTS "accountDefault_salesShippingRevenueAccount_idx"
+ ON "accountDefault"("salesShippingRevenueAccount");
+CREATE INDEX IF NOT EXISTS "invoiceSettlement_sourcePaymentId_companyId_idx"
+ ON "invoiceSettlement"("sourcePaymentId", "companyId") WHERE "sourcePaymentId" IS NOT NULL;
+
+-- Serialize chart/default resolution while choosing unused numbers and IDs.
+LOCK TABLE "account", "accountDefault" IN SHARE ROW EXCLUSIVE MODE;
+
+DO $existing_defaults$
+DECLARE bad text;
+BEGIN
+ SELECT string_agg(ad."companyId", ', ' ORDER BY ad."companyId") INTO bad
+ FROM "accountDefault" ad
+ JOIN "company" c ON c.id=ad."companyId"
+ LEFT JOIN "account" a ON a.id=ad."salesShippingRevenueAccount"
+ WHERE ad."salesShippingRevenueAccount" IS NOT NULL AND (
+ a.id IS NULL OR a."companyGroupId" IS DISTINCT FROM c."companyGroupId"
+ OR a.active IS DISTINCT FROM true OR a."isGroup" IS DISTINCT FROM false
+ OR a.class IS DISTINCT FROM 'Revenue' OR a."incomeBalance" IS DISTINCT FROM 'Income Statement'
+ OR a.id=ad."salesAccount"
+ );
+ IF bad IS NOT NULL THEN RAISE EXCEPTION 'Invalid shipping defaults for companies: %', bad; END IF;
+END;
+$existing_defaults$;
+
+CREATE TEMP TABLE accounting_shipping_resolution ON COMMIT DROP AS
+WITH groups AS (
+ SELECT DISTINCT c."companyGroupId"
+ FROM "company" c JOIN "accountDefault" ad ON ad."companyId"=c.id
+ WHERE ad."salesShippingRevenueAccount" IS NULL
+), sales_parents AS (
+ SELECT c."companyGroupId", min(p.id) AS parent_id, count(DISTINCT p.id) AS parent_count
+ FROM "company" c
+ JOIN "accountDefault" ad ON ad."companyId"=c.id
+ JOIN "account" sales ON sales.id=ad."salesAccount" AND sales."companyGroupId"=c."companyGroupId"
+ JOIN "account" p ON p.id=sales."parentId" AND p."companyGroupId"=c."companyGroupId"
+ WHERE p.active AND p."isGroup" AND p.class='Revenue'
+ AND p."incomeBalance"='Income Statement' AND p."accountType"='Income'
+ GROUP BY c."companyGroupId"
+)
+SELECT g."companyGroupId",
+ CASE WHEN named_parent.id IS NOT NULL THEN named_parent.id
+ WHEN sp.parent_count=1 THEN sp.parent_id END AS parent_id,
+ named_parent.id IS NOT NULL AND (
+ named_parent.active IS DISTINCT FROM true OR named_parent.class IS DISTINCT FROM 'Revenue'
+ OR named_parent."incomeBalance" IS DISTINCT FROM 'Income Statement'
+ OR named_parent."accountType" IS DISTINCT FROM 'Income'
+ ) AS invalid_named_parent,
+ existing.id AS existing_id,
+ COALESCE(existing.id, id('acct')) AS account_id,
+ COALESCE(existing.number, free_number.number) AS account_number
+FROM groups g
+LEFT JOIN "account" named_parent ON named_parent."companyGroupId"=g."companyGroupId"
+ AND named_parent.name='Revenue' AND named_parent."isGroup"=true
+LEFT JOIN sales_parents sp ON sp."companyGroupId"=g."companyGroupId"
+LEFT JOIN "account" existing ON existing."companyGroupId"=g."companyGroupId"
+ AND existing.name='Shipping Revenue' AND existing."isGroup"=false
+LEFT JOIN LATERAL (
+ SELECT n::text AS number FROM generate_series(4040,4990,10) n
+ WHERE NOT EXISTS (SELECT 1 FROM "account" a
+ WHERE a."companyGroupId"=g."companyGroupId" AND a.number=n::text)
+ ORDER BY n LIMIT 1
+) free_number ON true;
+
+DO $resolved$
+DECLARE bad text;
+BEGIN
+ SELECT string_agg(r."companyGroupId", ', ' ORDER BY r."companyGroupId") INTO bad
+ FROM accounting_shipping_resolution r
+ LEFT JOIN "account" a ON a.id=r.existing_id
+ WHERE r.parent_id IS NULL OR r.invalid_named_parent IS TRUE
+ OR (r.existing_id IS NULL AND r.account_number IS NULL)
+ OR EXISTS (
+ SELECT 1 FROM "account" conflicting
+ WHERE conflicting."companyGroupId"=r."companyGroupId"
+ AND conflicting.name='Shipping Revenue' AND conflicting."isGroup" IS DISTINCT FROM false
+ )
+ OR EXISTS (
+ SELECT 1 FROM "company" c JOIN "accountDefault" ad ON ad."companyId"=c.id
+ WHERE c."companyGroupId"=r."companyGroupId"
+ AND ad."salesShippingRevenueAccount" IS NULL AND ad."salesAccount"=r.account_id
+ )
+ OR (r.existing_id IS NOT NULL AND (
+ a.active IS DISTINCT FROM true OR a.class IS DISTINCT FROM 'Revenue'
+ OR a."accountType" IS DISTINCT FROM 'Income' OR a."incomeBalance" IS DISTINCT FROM 'Income Statement'
+ OR a."consolidatedRate" IS DISTINCT FROM 'Average' OR a."parentId" IS DISTINCT FROM r.parent_id
+ ));
+ IF bad IS NOT NULL THEN
+ RAISE EXCEPTION 'Cannot resolve Shipping Revenue parent/account/number for groups: %', bad;
+ END IF;
+END;
+$resolved$;
+
+INSERT INTO "account"(id,number,name,class,"accountType","incomeBalance","consolidatedRate",
+ "parentId","isGroup",active,"isSystem","companyGroupId","createdBy")
+SELECT account_id,account_number,'Shipping Revenue','Revenue','Income','Income Statement','Average',
+ parent_id,false,true,false,"companyGroupId",'system'
+FROM accounting_shipping_resolution WHERE existing_id IS NULL;
+
+UPDATE "accountDefault" ad SET "salesShippingRevenueAccount"=r.account_id,
+ "updatedBy"='system'
+FROM "company" c JOIN accounting_shipping_resolution r ON r."companyGroupId"=c."companyGroupId"
+WHERE ad."companyId"=c.id AND ad."salesShippingRevenueAccount" IS NULL;
+
+COMMENT ON COLUMN "accountDefault"."salesShippingRevenueAccount" IS 'Revenue account for shipping charged to customers; account belongs to the company group.';
+COMMENT ON COLUMN "invoiceSettlement"."sourcePaymentId" IS 'Prior posted payment supplying on-account credit; paymentId remains the applying/void owner. NULL means current payment cash.';
+COMMENT ON COLUMN "invoiceSettlement"."sourceAmount" IS 'Principal consumed in the funding source document currency, stored independently of target-base appliedAmount.';
+COMMENT ON COLUMN "invoiceSettlement"."appliedAmount" IS 'Target-document principal relieved in company base currency.';
+COMMENT ON COLUMN "invoiceSettlement"."discountAmount" IS 'Target-document discount relief in company base currency.';
+COMMENT ON COLUMN "invoiceSettlement"."writeOffAmount" IS 'Target-document write-off relief in company base currency.';
+COMMENT ON COLUMN "invoiceSettlement"."fxGainLossAmount" IS 'Server-calculated posting snapshot in company base currency: positive gain, negative loss.';
+COMMENT ON COLUMN "payment"."totalAmount" IS 'Gross cash amount in payment currency; divide by foreign-per-base exchangeRate for company base.';
+COMMENT ON COLUMN "memo"."amount" IS 'Memo amount in memo currency; divide by foreign-per-base exchangeRate for company base.';
+NOTIFY pgrst, 'reload schema';
+COMMIT;
+```
+<!-- schema-sql:end -->
+
+## Appendix B: Complete invoice-view and reporting SQL
+
+```sql
+BEGIN;
+
+-- Invoice balances and reporting normalized to the document/source currency contract.
+-- Requires new sourceAmount column. No historical fallback/backfill.
+-- Currency precision is group configuration, never a hardcoded two decimals.
+-- Save/post refuse missing config/rates; the LEFT JOIN keeps operational draft rows visible.
+-- Read balances preserve sub-internal-unit foreign remainders; only ledger lines use internal rounding.
+
+-- Latest source: packages/database/supabase/migrations/20260702224219_fix-ar-ap-legacy-paid.sql
+CREATE OR REPLACE VIEW "salesInvoices" WITH(SECURITY_INVOKER=true) AS
+ WITH settled AS (
+ SELECT s."targetSalesInvoiceId", s."companyId",
+ SUM(COALESCE(s."sourceAmount", 0) + round(
+ (s."discountAmount" + s."writeOffAmount") * target."exchangeRate",
+ target_currency."decimalPlaces")) AS amount_document,
+ MAX(s."appliedDate") AS "lastSettlementDate"
+ FROM "invoiceSettlement" s
+ JOIN "salesInvoice" target ON target."id" = s."targetSalesInvoiceId"
+ AND target."companyId" = s."companyId"
+ LEFT JOIN "company" target_company ON target_company."id" = target."companyId"
+ LEFT JOIN "currency" target_currency ON target_currency."code" = target."currencyCode"
+ AND target_currency."companyGroupId" = target_company."companyGroupId"
+ LEFT JOIN "payment" p ON p."id" = s."paymentId" AND p."companyId" = s."companyId"
+ LEFT JOIN "memo" m ON m."id" = s."memoId" AND m."companyId" = s."companyId"
+ LEFT JOIN "payment" vp ON vp."id" = s."appliedViaPaymentId" AND vp."companyId" = s."companyId"
+ WHERE s."targetSalesInvoiceId" IS NOT NULL
+ AND ((s."paymentId" IS NOT NULL AND p."status" = 'Posted')
+ OR (s."memoId" IS NOT NULL AND m."status" = 'Posted'
+ AND (s."appliedViaPaymentId" IS NULL OR vp."status" = 'Posted')))
+ GROUP BY s."targetSalesInvoiceId", s."companyId"
+ )
+ SELECT
+ si."id",
+ si."invoiceId",
+ CASE
+ WHEN si."status" IN ('Draft','Pending','Voided','Return','Credit Note Issued') THEN si."status"::TEXT
+ WHEN si."status" = 'Paid' THEN 'Paid'
+ WHEN COALESCE(s.amount_document, 0) > 0
+ AND amounts.total_document > 0 AND remaining.amount_document <= 0 THEN 'Paid'
+ WHEN COALESCE(s.amount_document, 0) > 0 THEN 'Partially Paid'
+ WHEN si."dateDue" < CURRENT_DATE AND si."status" = 'Submitted' THEN 'Overdue'
+ ELSE si."status"::TEXT
+ END AS status,
+ si."customerId",
+ si."customerReference",
+ si."invoiceCustomerId",
+ si."invoiceCustomerLocationId",
+ si."invoiceCustomerContactId",
+ si."paymentTermId",
+ si."postingDate",
+ si."dateIssued",
+ si."dateDue",
+ CASE
+ WHEN si."status" = 'Paid' THEN si."datePaid"
+ WHEN COALESCE(s.amount_document, 0) > 0
+ AND amounts.total_document > 0 AND remaining.amount_document <= 0
+ THEN COALESCE(s."lastSettlementDate", si."datePaid")
+ ELSE si."datePaid"
+ END AS "datePaid",
+ si."locationId",
+ si."currencyCode",
+ COALESCE(sil."subtotal", 0) AS "subtotal",
+ si."totalDiscount",
+ COALESCE(sil."subtotal", 0) + COALESCE(sil."totalTax", 0) + COALESCE(ss."shippingCost", 0) AS "totalAmount",
+ COALESCE(sil."totalTax", 0) AS "totalTax",
+ CASE
+ WHEN si."status" = 'Paid' THEN 0
+ ELSE remaining.amount_document / NULLIF(si."exchangeRate", 0)
+ END AS "balance",
+ si."exchangeRate",
+ si."exchangeRateUpdatedAt",
+ si."opportunityId",
+ si."shipmentId",
+ si."assignee",
+ si."companyId",
+ si."customFields",
+ si."internalNotes",
+ si."externalNotes",
+ si."tags",
+ si."createdAt",
+ si."createdBy",
+ si."updatedAt",
+ si."updatedBy",
+ sil."thumbnailPath",
+ sil."itemType",
+ COALESCE(sil."subtotal", 0) + COALESCE(sil."totalTax", 0) + COALESCE(ss."shippingCost", 0) AS "invoiceTotal",
+ sil."lines",
+ pt."name" AS "paymentTermName",
+ si."status" AS "baseStatus"
+ FROM "salesInvoice" si
+ LEFT JOIN (
+ SELECT
+ sil."invoiceId",
+ MIN(CASE
+ WHEN i."thumbnailPath" IS NULL AND mu."thumbnailPath" IS NOT NULL THEN mu."thumbnailPath"
+ ELSE i."thumbnailPath"
+ END) AS "thumbnailPath",
+ SUM(
+ COALESCE(sil."quantity", 0)*COALESCE(sil."unitPrice", 0)
+ + COALESCE(sil."addOnCost", 0)
+ + COALESCE(sil."nonTaxableAddOnCost", 0)
+ + COALESCE(sil."shippingCost", 0)
+ ) AS "subtotal",
+ SUM(
+ COALESCE(sil."taxPercent", 0) * (
+ COALESCE(sil."quantity", 0)*COALESCE(sil."unitPrice", 0)
+ + COALESCE(sil."addOnCost", 0)
+ + COALESCE(sil."shippingCost", 0)
+ )
+ ) AS "totalTax",
+ MIN(i."type") AS "itemType",
+ ARRAY_AGG(
+ json_build_object(
+ 'id', sil.id,
+ 'invoiceLineType', sil."invoiceLineType",
+ 'quantity', sil."quantity",
+ 'unitPrice', sil."unitPrice",
+ 'itemId', sil."itemId"
+ )
+ ) AS "lines"
+ FROM "salesInvoiceLine" sil
+ LEFT JOIN "item" i
+ ON i."id" = sil."itemId"
+ LEFT JOIN "modelUpload" mu ON mu.id = i."modelUploadId"
+ GROUP BY sil."invoiceId"
+ ) sil ON sil."invoiceId" = si."id"
+ -- LEFT JOIN (was INNER): an invoice missing its shipment row must not
+ -- vanish from the view — post-payment would read its balance as 0 and
+ -- reject every application. shippingCost is already COALESCEd.
+ LEFT JOIN "salesInvoiceShipment" ss ON ss."id" = si."id"
+ LEFT JOIN "paymentTerm" pt ON pt."id" = si."paymentTermId"
+ LEFT JOIN settled s ON s."targetSalesInvoiceId" = si."id" AND s."companyId" = si."companyId"
+ LEFT JOIN "company" invoice_company ON invoice_company."id" = si."companyId"
+ LEFT JOIN "currency" invoice_currency ON invoice_currency."code" = si."currencyCode"
+ AND invoice_currency."companyGroupId" = invoice_company."companyGroupId"
+ CROSS JOIN LATERAL (
+ SELECT round((COALESCE(sil."subtotal", 0) + COALESCE(sil."totalTax", 0) + COALESCE(ss."shippingCost", 0)) * si."exchangeRate", invoice_currency."decimalPlaces") AS total_document
+ ) amounts
+ CROSS JOIN LATERAL (
+ SELECT amounts.total_document - COALESCE(s.amount_document, 0) AS amount_document
+ ) remaining;
+
+-- Latest source: packages/database/supabase/migrations/20260811123616_widen-purchasing-scale.sql
+CREATE OR REPLACE VIEW "purchaseInvoices" WITH(SECURITY_INVOKER=true) AS
+ WITH settled AS (
+ SELECT s."targetPurchaseInvoiceId", s."companyId",
+ SUM(COALESCE(s."sourceAmount", 0) + round(
+ (s."discountAmount" + s."writeOffAmount") * target."exchangeRate",
+ target_currency."decimalPlaces")) AS amount_document,
+ MAX(s."appliedDate") AS "lastSettlementDate"
+ FROM "invoiceSettlement" s
+ JOIN "purchaseInvoice" target ON target."id" = s."targetPurchaseInvoiceId"
+ AND target."companyId" = s."companyId"
+ LEFT JOIN "company" target_company ON target_company."id" = target."companyId"
+ LEFT JOIN "currency" target_currency ON target_currency."code" = target."currencyCode"
+ AND target_currency."companyGroupId" = target_company."companyGroupId"
+ LEFT JOIN "payment" p ON p."id" = s."paymentId" AND p."companyId" = s."companyId"
+ LEFT JOIN "memo" m ON m."id" = s."memoId" AND m."companyId" = s."companyId"
+ LEFT JOIN "payment" vp ON vp."id" = s."appliedViaPaymentId" AND vp."companyId" = s."companyId"
+ WHERE s."targetPurchaseInvoiceId" IS NOT NULL
+ AND ((s."paymentId" IS NOT NULL AND p."status" = 'Posted')
+ OR (s."memoId" IS NOT NULL AND m."status" = 'Posted'
+ AND (s."appliedViaPaymentId" IS NULL OR vp."status" = 'Posted')))
+ GROUP BY s."targetPurchaseInvoiceId", s."companyId"
+ )
+ SELECT
+ pi."id",
+ pi."invoiceId",
+ pi."supplierId",
+ pi."invoiceSupplierId",
+ pi."supplierInteractionId",
+ pi."supplierReference",
+ pi."invoiceSupplierContactId",
+ pi."invoiceSupplierLocationId",
+ pi."locationId",
+ pi."postingDate",
+ pi."dateIssued",
+ pi."dateDue",
+ CASE
+ WHEN pi."status" = 'Paid' THEN pi."datePaid"
+ WHEN COALESCE(s.amount_document, 0) > 0
+ AND amounts.total_document > 0 AND remaining.amount_document <= 0
+ THEN COALESCE(s."lastSettlementDate", pi."datePaid")
+ ELSE pi."datePaid"
+ END AS "datePaid",
+ pi."paymentTermId",
+ pi."currencyCode",
+ pi."exchangeRate",
+ pi."exchangeRateUpdatedAt",
+ COALESCE(pl."subtotal", 0) AS "subtotal",
+ pi."totalDiscount",
+ (COALESCE(pl."orderTotal", 0) + COALESCE(pid."supplierShippingCost", 0) / CASE WHEN pi."exchangeRate" = 0 THEN 1 ELSE pi."exchangeRate" END) AS "totalAmount",
+ COALESCE(pl."totalTax", 0) AS "totalTax",
+ CASE
+ WHEN pi."status" = 'Paid' THEN 0
+ ELSE remaining.amount_document / NULLIF(pi."exchangeRate", 0)
+ END AS "balance",
+ pi."assignee",
+ pi."createdBy",
+ pi."createdAt",
+ pi."updatedBy",
+ pi."updatedAt",
+ pi."internalNotes",
+ pi."customFields",
+ pi."companyId",
+ pl."thumbnailPath",
+ pl."itemType",
+ COALESCE(pl."orderTotal", 0) + COALESCE(pid."supplierShippingCost", 0) / CASE WHEN pi."exchangeRate" = 0 THEN 1 ELSE pi."exchangeRate" END AS "orderTotal",
+ CASE
+ WHEN pi."status" IN ('Draft','Pending','Voided','Return','Debit Note Issued') THEN pi."status"::TEXT
+ WHEN pi."status" = 'Paid' THEN 'Paid'
+ WHEN COALESCE(s.amount_document, 0) > 0
+ AND amounts.total_document > 0 AND remaining.amount_document <= 0 THEN 'Paid'
+ WHEN COALESCE(s.amount_document, 0) > 0 THEN 'Partially Paid'
+ WHEN pi."dateDue" < CURRENT_DATE AND pi."status" = 'Open' THEN 'Overdue'
+ ELSE pi."status"::TEXT
+ END AS status,
+ pt."name" AS "paymentTermName",
+ pi."status" AS "baseStatus"
+ FROM "purchaseInvoice" pi
+ LEFT JOIN (
+ SELECT
+ pol."invoiceId",
+ MIN(CASE
+ WHEN i."thumbnailPath" IS NULL AND mu."thumbnailPath" IS NOT NULL THEN mu."thumbnailPath"
+ ELSE i."thumbnailPath"
+ END) AS "thumbnailPath",
+ SUM(
+ COALESCE(pol."quantity", 0)*COALESCE(pol."unitPrice", 0) + COALESCE(pol."shippingCost", 0)
+ ) AS "subtotal",
+ SUM(COALESCE(pol."taxAmount", 0)) AS "totalTax",
+ SUM(
+ COALESCE(pol."quantity", 0)*COALESCE(pol."unitPrice", 0) + COALESCE(pol."shippingCost", 0) + COALESCE(pol."taxAmount", 0)
+ ) AS "orderTotal",
+ MIN(i."type") AS "itemType"
+ FROM "purchaseInvoiceLine" pol
+ LEFT JOIN "item" i
+ ON i."id" = pol."itemId"
+ LEFT JOIN "modelUpload" mu ON mu.id = i."modelUploadId"
+ GROUP BY pol."invoiceId"
+ ) pl ON pl."invoiceId" = pi."id"
+ LEFT JOIN "paymentTerm" pt ON pt."id" = pi."paymentTermId"
+ LEFT JOIN "purchaseInvoiceDelivery" pid ON pid."id" = pi."id"
+ LEFT JOIN settled s ON s."targetPurchaseInvoiceId" = pi."id" AND s."companyId" = pi."companyId"
+ LEFT JOIN "company" invoice_company ON invoice_company."id" = pi."companyId"
+ LEFT JOIN "currency" invoice_currency ON invoice_currency."code" = pi."currencyCode"
+ AND invoice_currency."companyGroupId" = invoice_company."companyGroupId"
+ CROSS JOIN LATERAL (
+ SELECT round((COALESCE(pl."orderTotal", 0) + COALESCE(pid."supplierShippingCost", 0) / CASE WHEN pi."exchangeRate" = 0 THEN 1 ELSE pi."exchangeRate" END) * pi."exchangeRate", invoice_currency."decimalPlaces") AS total_document
+ ) amounts
+ CROSS JOIN LATERAL (
+ SELECT amounts.total_document - COALESCE(s.amount_document, 0) AS amount_document
+ ) remaining;
+
+-- Report replacements retain all six RPC signatures.
+-- Latest behavior source: 20260702224219_fix-ar-ap-legacy-paid.sql, all six RPCs.
+-- CREATE OR REPLACE preserves argument/return signatures, ownership and ACLs.
+-- Existing views also need the separate document-remainder/sourceAmount update.
+-- No reset, legacy version, historical posted-row backfill, or new public RPC.
+
+CREATE OR REPLACE FUNCTION get_ar_open_by_customer(
+ _company_id TEXT,
+ _as_of_date DATE
+)
+RETURNS TABLE (
+ "customerId" TEXT,
+ "documentId" TEXT,
+ "documentNumber" TEXT,
+ "documentType" TEXT,
+ "dateDue" DATE,
+ "currencyCode" TEXT,
+ "exchangeRate" NUMERIC,
+ "totalAmount" NUMERIC,
+ "settled" NUMERIC,
+ "openInCurrency" NUMERIC,
+ "openInBase" NUMERIC
+)
+LANGUAGE SQL
+SECURITY INVOKER
+AS $$
+ WITH effective_settlements AS (
+ SELECT s.*
+ FROM "invoiceSettlement" s
+ LEFT JOIN "payment" p ON p."id" = s."paymentId"
+ AND p."companyId" = s."companyId"
+ LEFT JOIN "memo" source_memo ON source_memo."id" = s."memoId"
+ AND source_memo."companyId" = s."companyId"
+ LEFT JOIN "payment" applying ON applying."id" = s."appliedViaPaymentId"
+ AND applying."companyId" = s."companyId"
+ WHERE s."companyId" = _company_id
+ AND (
+ (s."paymentId" IS NOT NULL AND p."status" = 'Posted'
+ AND p."postingDate" <= _as_of_date)
+ OR (s."memoId" IS NOT NULL AND source_memo."status" = 'Posted'
+ AND source_memo."postingDate" <= _as_of_date
+ AND ((s."appliedViaPaymentId" IS NULL AND s."appliedDate" <= _as_of_date) OR
+ (applying."status" = 'Posted' AND applying."postingDate" <= _as_of_date)))
+ )
+ ), invoice_settled AS (
+ SELECT s."targetSalesInvoiceId" AS invoice_id,
+ SUM(s."appliedAmount" + s."discountAmount" + s."writeOffAmount") AS settled_base,
+ SUM(COALESCE(s."sourceAmount", 0) + round(
+ (s."discountAmount" + s."writeOffAmount") * target."exchangeRate",
+ target_currency."decimalPlaces")) AS settled_document
+ FROM effective_settlements s
+ JOIN "salesInvoice" target ON target."id" = s."targetSalesInvoiceId"
+ AND target."companyId" = s."companyId"
+ LEFT JOIN "company" target_company ON target_company."id" = target."companyId"
+ LEFT JOIN "currency" target_currency ON target_currency."code" = target."currencyCode"
+ AND target_currency."companyGroupId" = target_company."companyGroupId"
+ WHERE s."targetSalesInvoiceId" IS NOT NULL
+ GROUP BY s."targetSalesInvoiceId"
+ ), memo_source_consumed AS (
+ SELECT s."memoId" AS memo_id, SUM(s."sourceAmount") AS settled_document,
+ SUM(s."appliedAmount" + s."fxGainLossAmount") AS settled_base
+ FROM effective_settlements s
+ WHERE s."memoId" IS NOT NULL
+ GROUP BY s."memoId"
+ ), memo_target_settled AS (
+ -- Preserve existing cash-to-memo rows without adding a new refund workflow.
+ -- These fields relieve the TARGET memo in base, unlike sourceAmount.
+ SELECT s."targetMemoId" AS memo_id, SUM(s."appliedAmount") AS settled_base
+ FROM effective_settlements s
+ WHERE s."targetMemoId" IS NOT NULL AND s."paymentId" IS NOT NULL
+ GROUP BY s."targetMemoId"
+ ), invoice_carrying AS (
+ -- Same original control snapshots used by post-payment; a document rate
+ -- conversion cannot reconstruct carrying value after document rounding.
+ SELECT line."documentId" AS invoice_id, SUM(abs(line."amount")) AS original_base
+ FROM "journalLine" line
+ JOIN "journal" j ON j."id"=line."journalId" AND j."companyId"=line."companyId"
+ WHERE line."companyId"=_company_id AND line."documentType"='Invoice'
+ AND line."description"='Accounts Receivable' AND j."sourceType"='Sales Invoice'
+ AND j."status"='Posted' AND j."postingDate"<=_as_of_date
+ GROUP BY line."documentId"
+ ), invoice_open AS (
+ SELECT i.*, COALESCE(s.settled_base, 0) AS settled_base,
+ amounts.remaining_document,
+ COALESCE(c.original_base, round(i."totalAmount",5)) - COALESCE(s.settled_base,0) AS remaining_base
+ FROM "salesInvoices" i
+ JOIN "salesInvoice" ib ON ib."id" = i."id" AND ib."companyId" = i."companyId"
+ LEFT JOIN invoice_settled s ON s.invoice_id = i."id"
+ LEFT JOIN invoice_carrying c ON c.invoice_id = i."id"
+ LEFT JOIN "company" invoice_company ON invoice_company."id" = i."companyId"
+ LEFT JOIN "currency" invoice_currency ON invoice_currency."code" = i."currencyCode"
+ AND invoice_currency."companyGroupId" = invoice_company."companyGroupId"
+ CROSS JOIN LATERAL (
+ SELECT round(i."totalAmount" * i."exchangeRate", invoice_currency."decimalPlaces")
+ - COALESCE(s.settled_document, 0) AS remaining_document
+ ) amounts
+ WHERE i."companyId" = _company_id
+ AND i."postingDate" <= _as_of_date
+ AND i."status" NOT IN ('Draft', 'Pending', 'Voided')
+ AND NOT (ib."status" = 'Paid'
+ AND (ib."datePaid" IS NULL OR ib."datePaid" <= _as_of_date))
+ ), memo_open AS (
+ SELECT m.*,
+ round(m."amount"/m."exchangeRate",5) - COALESCE(s.settled_base,0) - COALESCE(t.settled_base,0) AS remaining_base,
+ COALESCE(s.settled_document, 0) + COALESCE(t.settled_base, 0) * m."exchangeRate" AS settled_document,
+ m."amount" - COALESCE(s.settled_document, 0)
+ - COALESCE(t.settled_base, 0) * m."exchangeRate" AS remaining_document
+ FROM "memo" m
+ LEFT JOIN memo_source_consumed s ON s.memo_id = m."id"
+ LEFT JOIN memo_target_settled t ON t.memo_id = m."id"
+ WHERE m."companyId" = _company_id AND m."customerId" IS NOT NULL
+ AND m."status" = 'Posted' AND m."postingDate" <= _as_of_date
+ )
+ -- Preserve totalAmount/settled's existing per-document denomination:
+ -- invoices carry base; memo amount/settled carry memo currency.
+ SELECT i."customerId", i."id" AS "documentId", i."invoiceId" AS "documentNumber",
+ 'Invoice'::TEXT AS "documentType", i."dateDue", i."currencyCode", i."exchangeRate",
+ i."totalAmount", i.settled_base AS "settled",
+ i.remaining_document AS "openInCurrency",
+ i.remaining_base AS "openInBase"
+ FROM invoice_open i
+ WHERE i.remaining_document <> 0 OR i.remaining_base <> 0
+ UNION ALL
+ SELECT m."customerId", m."id", m."memoId", m."direction" || ' Memo',
+ NULL::DATE, m."currencyCode", m."exchangeRate", m."amount", m.settled_document,
+ (CASE WHEN m."direction" = 'Credit' THEN -1 ELSE 1 END) * m.remaining_document,
+ (CASE WHEN m."direction" = 'Credit' THEN -1 ELSE 1 END)
+ * m.remaining_base
+ FROM memo_open m
+ WHERE m.remaining_document <> 0 OR m.remaining_base <> 0
+ ORDER BY 1, 5 NULLS LAST;
+$$;
+
+CREATE OR REPLACE FUNCTION get_ap_open_by_supplier(
+ _company_id TEXT,
+ _as_of_date DATE
+)
+RETURNS TABLE (
+ "supplierId" TEXT,
+ "documentId" TEXT,
+ "documentNumber" TEXT,
+ "documentType" TEXT,
+ "dateDue" DATE,
+ "currencyCode" TEXT,
+ "exchangeRate" NUMERIC,
+ "totalAmount" NUMERIC,
+ "settled" NUMERIC,
+ "openInCurrency" NUMERIC,
+ "openInBase" NUMERIC
+)
+LANGUAGE SQL
+SECURITY INVOKER
+AS $$
+ WITH effective_settlements AS (
+ SELECT s.*
+ FROM "invoiceSettlement" s
+ LEFT JOIN "payment" p ON p."id" = s."paymentId"
+ AND p."companyId" = s."companyId"
+ LEFT JOIN "memo" source_memo ON source_memo."id" = s."memoId"
+ AND source_memo."companyId" = s."companyId"
+ LEFT JOIN "payment" applying ON applying."id" = s."appliedViaPaymentId"
+ AND applying."companyId" = s."companyId"
+ WHERE s."companyId" = _company_id
+ AND (
+ (s."paymentId" IS NOT NULL AND p."status" = 'Posted'
+ AND p."postingDate" <= _as_of_date)
+ OR (s."memoId" IS NOT NULL AND source_memo."status" = 'Posted'
+ AND source_memo."postingDate" <= _as_of_date
+ AND ((s."appliedViaPaymentId" IS NULL AND s."appliedDate" <= _as_of_date) OR
+ (applying."status" = 'Posted' AND applying."postingDate" <= _as_of_date)))
+ )
+ ), invoice_settled AS (
+ SELECT s."targetPurchaseInvoiceId" AS invoice_id,
+ SUM(s."appliedAmount" + s."discountAmount" + s."writeOffAmount") AS settled_base,
+ SUM(COALESCE(s."sourceAmount", 0) + round(
+ (s."discountAmount" + s."writeOffAmount") * target."exchangeRate",
+ target_currency."decimalPlaces")) AS settled_document
+ FROM effective_settlements s
+ JOIN "purchaseInvoice" target ON target."id" = s."targetPurchaseInvoiceId"
+ AND target."companyId" = s."companyId"
+ LEFT JOIN "company" target_company ON target_company."id" = target."companyId"
+ LEFT JOIN "currency" target_currency ON target_currency."code" = target."currencyCode"
+ AND target_currency."companyGroupId" = target_company."companyGroupId"
+ WHERE s."targetPurchaseInvoiceId" IS NOT NULL
+ GROUP BY s."targetPurchaseInvoiceId"
+ ), memo_source_consumed AS (
+ SELECT s."memoId" AS memo_id, SUM(s."sourceAmount") AS settled_document,
+ SUM(s."appliedAmount" - s."fxGainLossAmount") AS settled_base
+ FROM effective_settlements s
+ WHERE s."memoId" IS NOT NULL
+ GROUP BY s."memoId"
+ ), memo_target_settled AS (
+ -- Preserve existing cash-to-memo rows without adding a new refund workflow.
+ -- These fields relieve the TARGET memo in base, unlike sourceAmount.
+ SELECT s."targetMemoId" AS memo_id, SUM(s."appliedAmount") AS settled_base
+ FROM effective_settlements s
+ WHERE s."targetMemoId" IS NOT NULL AND s."paymentId" IS NOT NULL
+ GROUP BY s."targetMemoId"
+ ), invoice_carrying AS (
+ -- Same original control snapshots used by post-payment; a document rate
+ -- conversion cannot reconstruct carrying value after document rounding.
+ SELECT line."documentId" AS invoice_id, SUM(abs(line."amount")) AS original_base
+ FROM "journalLine" line
+ JOIN "journal" j ON j."id"=line."journalId" AND j."companyId"=line."companyId"
+ WHERE line."companyId"=_company_id AND line."documentType"='Invoice'
+ AND line."description"='Accounts Payable' AND j."sourceType"='Purchase Invoice'
+ AND j."status"='Posted' AND j."postingDate"<=_as_of_date
+ GROUP BY line."documentId"
+ ), invoice_open AS (
+ SELECT i.*, COALESCE(s.settled_base, 0) AS settled_base,
+ amounts.remaining_document,
+ COALESCE(c.original_base, round(i."totalAmount",5)) - COALESCE(s.settled_base,0) AS remaining_base
+ FROM "purchaseInvoices" i
+ JOIN "purchaseInvoice" ib ON ib."id" = i."id" AND ib."companyId" = i."companyId"
+ LEFT JOIN invoice_settled s ON s.invoice_id = i."id"
+ LEFT JOIN invoice_carrying c ON c.invoice_id = i."id"
+ LEFT JOIN "company" invoice_company ON invoice_company."id" = i."companyId"
+ LEFT JOIN "currency" invoice_currency ON invoice_currency."code" = i."currencyCode"
+ AND invoice_currency."companyGroupId" = invoice_company."companyGroupId"
+ CROSS JOIN LATERAL (
+ SELECT round(i."totalAmount" * i."exchangeRate", invoice_currency."decimalPlaces")
+ - COALESCE(s.settled_document, 0) AS remaining_document
+ ) amounts
+ WHERE i."companyId" = _company_id
+ AND i."postingDate" <= _as_of_date
+ AND i."status" NOT IN ('Draft', 'Pending', 'Voided')
+ AND NOT (ib."status" = 'Paid'
+ AND (ib."datePaid" IS NULL OR ib."datePaid" <= _as_of_date))
+ ), memo_open AS (
+ SELECT m.*,
+ round(m."amount"/m."exchangeRate",5) - COALESCE(s.settled_base,0) - COALESCE(t.settled_base,0) AS remaining_base,
+ COALESCE(s.settled_document, 0) + COALESCE(t.settled_base, 0) * m."exchangeRate" AS settled_document,
+ m."amount" - COALESCE(s.settled_document, 0)
+ - COALESCE(t.settled_base, 0) * m."exchangeRate" AS remaining_document
+ FROM "memo" m
+ LEFT JOIN memo_source_consumed s ON s.memo_id = m."id"
+ LEFT JOIN memo_target_settled t ON t.memo_id = m."id"
+ WHERE m."companyId" = _company_id AND m."supplierId" IS NOT NULL
+ AND m."status" = 'Posted' AND m."postingDate" <= _as_of_date
+ )
+ -- Preserve totalAmount/settled's existing per-document denomination:
+ -- invoices carry base; memo amount/settled carry memo currency.
+ SELECT i."supplierId", i."id" AS "documentId", i."invoiceId" AS "documentNumber",
+ 'Invoice'::TEXT AS "documentType", i."dateDue", i."currencyCode", i."exchangeRate",
+ i."totalAmount", i.settled_base AS "settled",
+ i.remaining_document AS "openInCurrency",
+ i.remaining_base AS "openInBase"
+ FROM invoice_open i
+ WHERE i.remaining_document <> 0 OR i.remaining_base <> 0
+ UNION ALL
+ SELECT m."supplierId", m."id", m."memoId", m."direction" || ' Memo',
+ NULL::DATE, m."currencyCode", m."exchangeRate", m."amount", m.settled_document,
+ (CASE WHEN m."direction" = 'Debit' THEN -1 ELSE 1 END) * m.remaining_document,
+ (CASE WHEN m."direction" = 'Debit' THEN -1 ELSE 1 END)
+ * m.remaining_base
+ FROM memo_open m
+ WHERE m.remaining_document <> 0 OR m.remaining_base <> 0
+ ORDER BY 1, 5 NULLS LAST;
+$$;
+
+CREATE OR REPLACE FUNCTION get_ar_tie_out(
+ _company_id TEXT,
+ _as_of_date DATE
+)
+RETURNS TABLE (
+ "subledgerBalance" NUMERIC,
+ "glBalance" NUMERIC,
+ "variance" NUMERIC
+)
+LANGUAGE SQL
+SECURITY INVOKER
+AS $$
+ WITH funding_consumed AS (
+ SELECT COALESCE(s."sourcePaymentId", s."paymentId") AS source_payment_id,
+ SUM(s."appliedAmount" + s."fxGainLossAmount") AS source_base_amount
+ FROM "invoiceSettlement" s
+ JOIN "payment" applying ON applying."id" = s."paymentId"
+ AND applying."companyId" = s."companyId"
+ WHERE s."companyId" = _company_id
+ AND s."paymentId" IS NOT NULL
+ AND applying."status" = 'Posted'
+ AND applying."postingDate" <= _as_of_date
+ GROUP BY COALESCE(s."sourcePaymentId", s."paymentId")
+ ), payment_unapplied AS (
+ SELECT (round(p."totalAmount" / p."exchangeRate",5) - COALESCE(c.source_base_amount,0)) AS open_base
+ FROM "payment" p
+ LEFT JOIN funding_consumed c ON c.source_payment_id = p."id"
+ WHERE p."companyId" = _company_id AND p."paymentType" = 'Receipt'
+ AND p."status" = 'Posted' AND p."postingDate" <= _as_of_date
+ ), subledger AS (
+ SELECT COALESCE((SELECT SUM(o."openInBase")
+ FROM get_ar_open_by_customer(_company_id, _as_of_date) o), 0)
+ - COALESCE((SELECT SUM(open_base) FROM payment_unapplied), 0) AS amount
+ ), control_account AS (
+ -- A default change affects future postings; historical invoice, payment
+ -- and memo control accounts remain part of this company's subledger.
+ -- UNION deduplicates repeated control rows and overlap with current defaults.
+ SELECT unnest(ARRAY["receivablesAccount", "intercompanyReceivablesAccount"]) AS account_id
+ FROM "accountDefault" WHERE "companyId" = _company_id
+ UNION
+ SELECT line."accountId"
+ FROM "journalLine" line
+ JOIN "journal" j ON j."id" = line."journalId" AND j."companyId" = line."companyId"
+ WHERE line."companyId" = _company_id
+ AND j."status" = 'Posted' AND j."postingDate" <= _as_of_date
+ AND (
+ (j."sourceType" = 'Sales Invoice' AND line."documentType" = 'Invoice'
+ AND line."description" = 'Accounts Receivable')
+ OR (j."sourceType" = 'Payment' AND line."documentType" = 'Payment'
+ AND line."description" IN ('Accounts Receivable',
+ 'Accounts Receivable (on-account credit)', 'Accounts Receivable (credit applied)'))
+ OR (j."sourceType" IN ('Credit Memo', 'Debit Memo') AND line."documentType" = 'Memo'
+ AND line."description" = 'Accounts Receivable')
+ )
+ ), gl AS (
+ SELECT COALESCE(SUM(jl."amount"), 0) AS amount
+ FROM "journalLine" jl
+ JOIN "journal" j ON j."id" = jl."journalId" AND j."companyId" = jl."companyId"
+ JOIN control_account a ON a.account_id = jl."accountId"
+ WHERE jl."companyId" = _company_id
+ AND j."postingDate" <= _as_of_date AND j."status" = 'Posted'
+ )
+ SELECT subledger.amount AS "subledgerBalance", gl.amount AS "glBalance",
+ subledger.amount - gl.amount AS "variance"
+ FROM subledger, gl;
+$$;
+
+CREATE OR REPLACE FUNCTION get_ap_tie_out(
+ _company_id TEXT,
+ _as_of_date DATE
+)
+RETURNS TABLE (
+ "subledgerBalance" NUMERIC,
+ "glBalance" NUMERIC,
+ "variance" NUMERIC
+)
+LANGUAGE SQL
+SECURITY INVOKER
+AS $$
+ WITH funding_consumed AS (
+ SELECT COALESCE(s."sourcePaymentId", s."paymentId") AS source_payment_id,
+ SUM(s."appliedAmount" - s."fxGainLossAmount") AS source_base_amount
+ FROM "invoiceSettlement" s
+ JOIN "payment" applying ON applying."id" = s."paymentId"
+ AND applying."companyId" = s."companyId"
+ WHERE s."companyId" = _company_id
+ AND s."paymentId" IS NOT NULL
+ AND applying."status" = 'Posted'
+ AND applying."postingDate" <= _as_of_date
+ GROUP BY COALESCE(s."sourcePaymentId", s."paymentId")
+ ), payment_unapplied AS (
+ SELECT (round(p."totalAmount" / p."exchangeRate",5) - COALESCE(c.source_base_amount,0)) AS open_base
+ FROM "payment" p
+ LEFT JOIN funding_consumed c ON c.source_payment_id = p."id"
+ WHERE p."companyId" = _company_id AND p."paymentType" = 'Disbursement'
+ AND p."status" = 'Posted' AND p."postingDate" <= _as_of_date
+ ), subledger AS (
+ SELECT COALESCE((SELECT SUM(o."openInBase")
+ FROM get_ap_open_by_supplier(_company_id, _as_of_date) o), 0)
+ - COALESCE((SELECT SUM(open_base) FROM payment_unapplied), 0) AS amount
+ ), control_account AS (
+ SELECT unnest(ARRAY["payablesAccount", "intercompanyPayablesAccount"]) AS account_id
+ FROM "accountDefault" WHERE "companyId" = _company_id
+ UNION
+ SELECT line."accountId"
+ FROM "journalLine" line
+ JOIN "journal" j ON j."id" = line."journalId" AND j."companyId" = line."companyId"
+ WHERE line."companyId" = _company_id
+ AND j."status" = 'Posted' AND j."postingDate" <= _as_of_date
+ AND (
+ (j."sourceType" = 'Purchase Invoice' AND line."documentType" = 'Invoice'
+ AND line."description" = 'Accounts Payable')
+ OR (j."sourceType" = 'Payment' AND line."documentType" = 'Payment'
+ AND line."description" IN ('Accounts Payable',
+ 'Accounts Payable (on-account credit)', 'Accounts Payable (credit applied)'))
+ OR (j."sourceType" IN ('Credit Memo', 'Debit Memo') AND line."documentType" = 'Memo'
+ AND line."description" = 'Accounts Payable')
+ )
+ ), gl AS (
+ SELECT COALESCE(SUM(jl."amount"), 0) AS amount
+ FROM "journalLine" jl
+ JOIN "journal" j ON j."id" = jl."journalId" AND j."companyId" = jl."companyId"
+ JOIN control_account a ON a.account_id = jl."accountId"
+ WHERE jl."companyId" = _company_id
+ AND j."postingDate" <= _as_of_date AND j."status" = 'Posted'
+ )
+ SELECT subledger.amount AS "subledgerBalance", gl.amount AS "glBalance",
+ subledger.amount - gl.amount AS "variance"
+ FROM subledger, gl;
+$$;
+
+CREATE OR REPLACE FUNCTION get_ar_aging(
+ _company_id TEXT,
+ _as_of_date DATE,
+ _aging_method TEXT DEFAULT 'dueDate',
+ _bucket1 INTEGER DEFAULT 30,
+ _bucket2 INTEGER DEFAULT 60,
+ _bucket3 INTEGER DEFAULT 90
+)
+RETURNS TABLE (
+ "customerId" TEXT,
+ "paymentTerm" TEXT,
+ "current" NUMERIC,
+ "bucket1" NUMERIC,
+ "bucket2" NUMERIC,
+ "bucket3" NUMERIC,
+ "bucket4" NUMERIC,
+ "unapplied" NUMERIC,
+ "total" NUMERIC
+)
+LANGUAGE SQL
+SECURITY INVOKER
+AS $$
+ WITH funding_consumed AS (
+ SELECT COALESCE(s."sourcePaymentId", s."paymentId") AS source_payment_id,
+ SUM(s."appliedAmount" + s."fxGainLossAmount") AS source_base_amount
+ FROM "invoiceSettlement" s
+ JOIN "payment" applying ON applying."id" = s."paymentId"
+ AND applying."companyId" = s."companyId"
+ WHERE s."companyId" = _company_id
+ AND s."paymentId" IS NOT NULL
+ AND applying."status" = 'Posted'
+ AND applying."postingDate" <= _as_of_date
+ GROUP BY COALESCE(s."sourcePaymentId", s."paymentId")
+ ), open_items AS (
+ SELECT o."customerId",
+ CASE WHEN o."documentType" = 'Invoice' THEN
+ CASE WHEN _aging_method = 'documentDate' THEN COALESCE(i."dateIssued", i."postingDate")
+ ELSE o."dateDue" END
+ ELSE m."memoDate" END AS age_date,
+ o."openInBase" AS open_base
+ FROM get_ar_open_by_customer(_company_id, _as_of_date) o
+ LEFT JOIN "salesInvoice" i ON i."id" = o."documentId"
+ AND i."companyId" = _company_id AND o."documentType" = 'Invoice'
+ LEFT JOIN "memo" m ON m."id" = o."documentId"
+ AND m."companyId" = _company_id AND o."documentType" <> 'Invoice'
+ ),
+ buckets AS (
+ SELECT
+ "customerId",
+ COALESCE(SUM(open_base) FILTER (WHERE age_date IS NULL OR age_date >= _as_of_date), 0) AS "current",
+ COALESCE(SUM(open_base) FILTER (WHERE age_date < _as_of_date AND _as_of_date - age_date BETWEEN 1 AND _bucket1), 0) AS "bucket1",
+ COALESCE(SUM(open_base) FILTER (WHERE _as_of_date - age_date BETWEEN _bucket1 + 1 AND _bucket2), 0) AS "bucket2",
+ COALESCE(SUM(open_base) FILTER (WHERE _as_of_date - age_date BETWEEN _bucket2 + 1 AND _bucket3), 0) AS "bucket3",
+ COALESCE(SUM(open_base) FILTER (WHERE _as_of_date - age_date > _bucket3), 0) AS "bucket4"
+ FROM open_items
+ WHERE open_base <> 0
+ GROUP BY "customerId"
+ ),
+ unapplied AS (
+ SELECT p."customerId",
+ -COALESCE(SUM((round(p."totalAmount" / p."exchangeRate",5) - COALESCE(c.source_base_amount,0))), 0) AS "unapplied"
+ FROM "payment" p
+ LEFT JOIN funding_consumed c ON c.source_payment_id = p."id"
+ WHERE p."companyId" = _company_id AND p."paymentType" = 'Receipt'
+ AND p."status" = 'Posted' AND p."postingDate" <= _as_of_date
+ AND p."customerId" IS NOT NULL
+ GROUP BY p."customerId"
+ )
+ SELECT
+ COALESCE(ib."customerId", u."customerId") AS "customerId",
+ pt."name" AS "paymentTerm",
+ COALESCE(ib."current", 0) AS "current",
+ COALESCE(ib."bucket1", 0) AS "bucket1",
+ COALESCE(ib."bucket2", 0) AS "bucket2",
+ COALESCE(ib."bucket3", 0) AS "bucket3",
+ COALESCE(ib."bucket4", 0) AS "bucket4",
+ COALESCE(u."unapplied", 0) AS "unapplied",
+ COALESCE(ib."current", 0) + COALESCE(ib."bucket1", 0)
+ + COALESCE(ib."bucket2", 0) + COALESCE(ib."bucket3", 0)
+ + COALESCE(ib."bucket4", 0) + COALESCE(u."unapplied", 0) AS "total"
+ FROM buckets ib
+ FULL OUTER JOIN unapplied u ON u."customerId" = ib."customerId"
+ LEFT JOIN "customerPayment" cp
+ ON cp."customerId" = COALESCE(ib."customerId", u."customerId")
+ AND cp."companyId" = _company_id
+ LEFT JOIN "paymentTerm" pt ON pt."id" = cp."paymentTermId"
+ WHERE
+ COALESCE(ib."current", 0) + COALESCE(ib."bucket1", 0)
+ + COALESCE(ib."bucket2", 0) + COALESCE(ib."bucket3", 0)
+ + COALESCE(ib."bucket4", 0) + COALESCE(u."unapplied", 0) <> 0
+ ORDER BY "total" DESC;
+$$;
+
+CREATE OR REPLACE FUNCTION get_ap_aging(
+ _company_id TEXT,
+ _as_of_date DATE,
+ _aging_method TEXT DEFAULT 'dueDate',
+ _bucket1 INTEGER DEFAULT 30,
+ _bucket2 INTEGER DEFAULT 60,
+ _bucket3 INTEGER DEFAULT 90
+)
+RETURNS TABLE (
+ "supplierId" TEXT,
+ "paymentTerm" TEXT,
+ "current" NUMERIC,
+ "bucket1" NUMERIC,
+ "bucket2" NUMERIC,
+ "bucket3" NUMERIC,
+ "bucket4" NUMERIC,
+ "unapplied" NUMERIC,
+ "total" NUMERIC
+)
+LANGUAGE SQL
+SECURITY INVOKER
+AS $$
+ WITH funding_consumed AS (
+ SELECT COALESCE(s."sourcePaymentId", s."paymentId") AS source_payment_id,
+ SUM(s."appliedAmount" - s."fxGainLossAmount") AS source_base_amount
+ FROM "invoiceSettlement" s
+ JOIN "payment" applying ON applying."id" = s."paymentId"
+ AND applying."companyId" = s."companyId"
+ WHERE s."companyId" = _company_id
+ AND s."paymentId" IS NOT NULL
+ AND applying."status" = 'Posted'
+ AND applying."postingDate" <= _as_of_date
+ GROUP BY COALESCE(s."sourcePaymentId", s."paymentId")
+ ), open_items AS (
+ SELECT o."supplierId",
+ CASE WHEN o."documentType" = 'Invoice' THEN
+ CASE WHEN _aging_method = 'documentDate' THEN COALESCE(i."dateIssued", i."postingDate")
+ ELSE o."dateDue" END
+ ELSE m."memoDate" END AS age_date,
+ o."openInBase" AS open_base
+ FROM get_ap_open_by_supplier(_company_id, _as_of_date) o
+ LEFT JOIN "purchaseInvoice" i ON i."id" = o."documentId"
+ AND i."companyId" = _company_id AND o."documentType" = 'Invoice'
+ LEFT JOIN "memo" m ON m."id" = o."documentId"
+ AND m."companyId" = _company_id AND o."documentType" <> 'Invoice'
+ ),
+ buckets AS (
+ SELECT
+ "supplierId",
+ COALESCE(SUM(open_base) FILTER (WHERE age_date IS NULL OR age_date >= _as_of_date), 0) AS "current",
+ COALESCE(SUM(open_base) FILTER (WHERE age_date < _as_of_date AND _as_of_date - age_date BETWEEN 1 AND _bucket1), 0) AS "bucket1",
+ COALESCE(SUM(open_base) FILTER (WHERE _as_of_date - age_date BETWEEN _bucket1 + 1 AND _bucket2), 0) AS "bucket2",
+ COALESCE(SUM(open_base) FILTER (WHERE _as_of_date - age_date BETWEEN _bucket2 + 1 AND _bucket3), 0) AS "bucket3",
+ COALESCE(SUM(open_base) FILTER (WHERE _as_of_date - age_date > _bucket3), 0) AS "bucket4"
+ FROM open_items
+ WHERE open_base <> 0
+ GROUP BY "supplierId"
+ ),
+ unapplied AS (
+ SELECT p."supplierId",
+ -COALESCE(SUM((round(p."totalAmount" / p."exchangeRate",5) - COALESCE(c.source_base_amount,0))), 0) AS "unapplied"
+ FROM "payment" p
+ LEFT JOIN funding_consumed c ON c.source_payment_id = p."id"
+ WHERE p."companyId" = _company_id AND p."paymentType" = 'Disbursement'
+ AND p."status" = 'Posted' AND p."postingDate" <= _as_of_date
+ AND p."supplierId" IS NOT NULL
+ GROUP BY p."supplierId"
+ )
+ SELECT
+ COALESCE(ib."supplierId", u."supplierId") AS "supplierId",
+ pt."name" AS "paymentTerm",
+ COALESCE(ib."current", 0) AS "current",
+ COALESCE(ib."bucket1", 0) AS "bucket1",
+ COALESCE(ib."bucket2", 0) AS "bucket2",
+ COALESCE(ib."bucket3", 0) AS "bucket3",
+ COALESCE(ib."bucket4", 0) AS "bucket4",
+ COALESCE(u."unapplied", 0) AS "unapplied",
+ COALESCE(ib."current", 0) + COALESCE(ib."bucket1", 0)
+ + COALESCE(ib."bucket2", 0) + COALESCE(ib."bucket3", 0)
+ + COALESCE(ib."bucket4", 0) + COALESCE(u."unapplied", 0) AS "total"
+ FROM buckets ib
+ FULL OUTER JOIN unapplied u ON u."supplierId" = ib."supplierId"
+ LEFT JOIN "supplierPayment" sp
+ ON sp."supplierId" = COALESCE(ib."supplierId", u."supplierId")
+ AND sp."companyId" = _company_id
+ LEFT JOIN "paymentTerm" pt ON pt."id" = sp."paymentTermId"
+ WHERE
+ COALESCE(ib."current", 0) + COALESCE(ib."bucket1", 0)
+ + COALESCE(ib."bucket2", 0) + COALESCE(ib."bucket3", 0)
+ + COALESCE(ib."bucket4", 0) + COALESCE(u."unapplied", 0) <> 0
+ ORDER BY "total" DESC;
+$$;
+
+NOTIFY pgrst, 'reload schema';
+COMMIT;
+```
diff --git a/.ai/plans/2026-09-08-accounting-review-corrections.md b/.ai/plans/2026-09-08-accounting-review-corrections.md
new file mode 100644
index 0000000000..ea84ebc634
--- /dev/null
+++ b/.ai/plans/2026-09-08-accounting-review-corrections.md
@@ -0,0 +1,61 @@
+# Accounting PR review corrections
+
+- PR: https://github.com/crbnos/carbon/pull/1599
+- Branch: assess-issue-against-code; base: origin/main
+- Request: after making the PR, wait for the coderabbit review, and then solve the problems
+- Status: corrections validated and pushed in de7ab3bbdb; refreshed remote checks pending
+- Scope: approved accounting posting corrections, confirmed nuclear-review findings, and verified CodeRabbit findings
+- Exclusions remain: France/e-invoicing, historical cutover machinery, live provider writes, new production dependencies, database reset/rebuild
+
+## Progress
+
+- [x] Create PR and push reviewed branch
+- [x] Restore existing workspace PostgreSQL container without changing its data volume
+- [x] Establish live baseline: 84 report cases and 15 payment/memo/concurrency tests pass
+- [x] Capture completed CodeRabbit review and classify every finding against code
+- [x] Signed original control amounts, exhaustive invoice posting roles, and shared remaining-balance arithmetic (M1, M7, R4)
+- [x] Complete invoice reads and preserve manual memo principal (M4, M5)
+- [x] Original provider accounts, canonical invoice source loader, provider contract fixes and errors (M2, M3, M7, R1/R2/R3, S2)
+- [x] Narrow subsidiary CTA resolution, atomic defaults update, and historical chart completeness (M6, M8, R5, S3)
+- [x] Address additional confirmed CodeRabbit findings
+- [x] Update docs/test runner and remove duplicate SQL regression ownership where warranted (D1-D4, S1)
+- [x] Run ordered scoped validation, review integrated diff, commit and push fixes
+- [x] Check resulting PR review/check state and update PR description with final evidence
+
+## Implementation slices
+
+- Invoicing: `apps/erp/app/modules/invoicing/invoicing.service.ts` and its settlement/component tests. Page invoice, settlement and control reads with stable ordering and ID batches; preserve manual document principal; reuse the shared reducers while retaining Draft reservation eligibility at query boundaries.
+- Providers: `packages/ee/src/accounting/core/sales-invoice-source.ts`, `document-costing.ts`, and Xero/QBO/Rillet invoice/bill adapters and tests. Normalize invoice sources once, preserve original shipping/AP account roles, represent Xero lines as exact monetary units with native tax and explicit foreign 1:1 rates, recover failed QBO tax cache reads, and retain structured missing-account warnings.
+- Reporting: `apps/erp/app/modules/accounting/accounting.ee.{service,server}.ts`, defaults/balance-sheet routes and tests. Write defaults in one statement, resolve only the authorized group's root CTA configuration, and preserve inactive historical accounts with complete chart/RPC paging.
+- Root: pure edge utilities, payment/memo transactions, both unshipped SQL migrations, database regressions, tracked verification runner and documentation. Existing role vocabulary is exhaustive; tenant/source/status filters remain in transport queries.
+
+Behavior changes require failing regressions followed by the same tests passing. Scoped commands: `pnpm --filter @carbon/ee test`, `pnpm --filter @carbon/ee typecheck`, and `pnpm --dir apps/erp exec vitest run app/modules/invoicing app/modules/accounting/accounting.defaults.test.ts app/modules/accounting/accounting.translation.test.ts app/routes/x+/reports+/balance-sheet.test.ts`. Expected: all scoped tests and typechecks pass; unauthorized CTA roots, malformed source principal, late-page failures and invalid mapping writes fail without partial state.
+
+## Root slice implementation and verification
+
+1. Extend `packages/database/supabase/functions/post-payment/post-payment-transaction.test.ts` and `packages/database/supabase/tests/accounting-balances-and-reports.test.sql` with mixed positive/negative AR/AP originals and IC original-account fixtures; assert actual original GL relief, no invented FX, correct open/aging balances, and correct account after defaults change.
+2. Run new tests red before changing the production reducer or SQL; use the existing local wrapper until a tracked safe runner is introduced.
+3. Add a pure exhaustive invoice posting-role selector under `packages/database/supabase/functions/shared/`, with a `packages/utils/src/` re-export and barrel entry; share the existing immutable journal description vocabulary across readers and keep company/source/status filtering in transport queries.
+4. Extend the existing `shared/payment-funding.ts` with canonical settlement effectiveness, invoice remaining amounts, and funding-source remaining amounts; remove duplicate economic reductions from edge and ERP call sites while preserving Draft reservation policy separately.
+5. Replace magnitude sums in the unshipped branch report migration with signed natural sums and include exhaustive IC controls; reapply only the existing read-model definitions locally, reload PostgREST if needed, and regenerate DB types before typechecking. No schema/role column or legacy calculation mode is required.
+6. Run corrected SQL and actual posting transaction suites green, then validate remaining edge helpers and utility exports.
+
+Commands (from repository root):
+
+```sh
+pnpm exec tsx scripts/run-local-accounting-check.ts psql -X -v ON_ERROR_STOP=1 -f packages/database/supabase/tests/accounting-balances-and-reports.test.sql
+pnpm exec tsx scripts/run-local-accounting-check.ts deno test --no-lock --no-check --allow-env --allow-net --config packages/database/supabase/functions/deno.json packages/database/supabase/functions/post-payment/post-payment-transaction.test.ts packages/database/supabase/functions/post-payment/post-payment-concurrency.test.ts packages/database/supabase/functions/post-memo/post-memo-transaction.test.ts
+pnpm run generate:types
+pnpm exec tsx scripts/run-local-accounting-check.ts psql -X -v ON_ERROR_STOP=1 -f packages/database/supabase/tests/accounting-defaults-report-access.test.sql
+pnpm --filter @carbon/database typecheck
+pnpm --filter @carbon/utils typecheck
+pnpm --filter @carbon/utils test
+pnpm db:check:datasets
+pnpm exec tsx scripts/run-local-accounting-check.ts pnpm db:check:backups
+```
+
+Expected: new economic regressions fail for their claimed amounts before the fix, then pass through actual production paths; generated types are untouched manually; database compatibility checks inspect the existing local schema and pass. Pure Deno helpers are typechecked separately from the known Node/Deno Postgres typing baseline.
+
+## Integration gate
+
+Follow check-and-commit: generated types/catalog if required, scoped Biome, package typechecks, scoped meaningful tests, build only when export changes require it, i18n extraction/verification, then explicit-file conventional commits and push. Record every command/outcome in the run log; do not mark unresolved provider sandbox evidence as passed.
diff --git a/.ai/plans/2026-09-09-accounting-e2e-fixes.md b/.ai/plans/2026-09-09-accounting-e2e-fixes.md
new file mode 100644
index 0000000000..fd5437d11b
--- /dev/null
+++ b/.ai/plans/2026-09-09-accounting-e2e-fixes.md
@@ -0,0 +1,20 @@
+# Fix the accounting E2E findings selected by the user
+
+User request: “fix 1, 3, and 4” from the previous final summary: Rillet provider correctness; payments/memos/refunds/published settlement API; historical reports/pagination. Integration configuration (item 2) and the pre-existing asset master void gap remain outside this requested fix.
+
+Evidence: [executed E2E report](../runs/2026-09-09-accounting-e2e.md). Root causes are proven against code and real local/provider API responses. Work autonomously through focused failing regression → minimal integrated fix → scoped checks → fresh live verification. Preserve existing workspace changes, no database rebuild, no credentials in artifacts. No new commit or push requested for this turn.
+
+- [x] Rillet bill FX: fix directed pair and reciprocal; unit and live provider GL proof.
+- [x] Rillet lifecycle: propagate invoice, bill and payment voids through operation creation/drain, handle retries and actual provider refusal states; verify remote documents and GL.
+- [x] Rillet AR FX/revenue: establish supported representation from primary docs/live API, implement exact book fidelity, verify independent remote GL. Do not silently skip discrepant cases or count provider HTTP success as fidelity.
+- [x] Memo principal: round remaining source-document currency before comparison, customer and supplier final-cent regressions and fresh post/void.
+- [x] Refunds: keep ledger party independent of cash direction across UI, application service, posting, aging/tie-out; exact source memo/prior-payment relief and reversal.
+- [x] Published API: derive required createdBy injection from service argument contract; regression uses actual dispatch and auth context, then real scoped HTTP request.
+- [x] Reports: include inactive historical leaves/ancestors; reject out-of-group report selections; preserve valid child-only parent CTA.
+- [x] Application lists: page all results and fail closed on late-page errors; real max_rows1000 browser proof for payment/invoice.
+- [x] Apply new migrations together, regenerate types, format/lint changed files, scoped ERP/EE/jobs typechecks and tests, dataset/backup checks.
+- [x] Review final diff, refresh durable rules/playbooks and produce final proof report.
+
+Ownership: Rillet agent owns EE/jobs provider flow; payment agent owns invoicing/payment service and edge logic; reports agent owns report/refund SQL and only the two invoice-settlement read functions in invoicing.service.ts. Root owns API metadata/dispatch contract tests, payment form/composer/route, integration review, migration application/type generation and broad gates. Agents coordinate patches in the shared service file; no generated artifacts edited manually.
+
+Completed locally. Evidence and validation exceptions are recorded in [the final verification report](../runs/2026-09-09-accounting-e2e-fixes.md#final-verification).
diff --git a/.ai/plans/2026-09-09-accounting-e2e-verification.md b/.ai/plans/2026-09-09-accounting-e2e-verification.md
new file mode 100644
index 0000000000..ff60f275e2
--- /dev/null
+++ b/.ai/plans/2026-09-09-accounting-e2e-verification.md
@@ -0,0 +1,16 @@
+# Accounting priorities 1 and 2: end-to-end verification
+
+User authorized /test, database/API setup and the configured Rillet integration. Test the merged branch beginning at84abeb3e3d. Preserve all existing operational records and isolate fixture ownership; no database reset. No Xero/QBO success claim without actual connections.
+
+- [x] Rillet actual sync and independent returned document/ledger comparison: invoices, bills, payments, tax, shipping, original accounts, FX, precision, retries and reversals.
+- [x] UI payment creation, discounts/write-offs, credits, memos, refunds and post/void restoration for customer/supplier sides.
+- [x] High-rate manual160/160.01 and final0.01 document-unit settlement, including memo credit.
+- [x] Actual intercompany seller/buyer posting with300.015 matching key, matching/elimination, partial realization and regeneration.
+- [x] Subsidiary-only authenticated report access, parent CTA, inactive historical chart, period columns and CSV parity.
+- [x] Sales and purchase invoice posting with tax/shipping/mixed signs, changed defaults, settlement and void with zero tie-out variance.
+- [x] Default account setup/save/reload/rejection atomicity, new-company shipping account and >1000-row boundaries.
+- [x] Record failures with UI/API/database evidence, continue independent workflows, refresh only successful playbooks and publish a complete report.
+
+Evidence is isolated under `.context/accounting/e2e-20260909/` and `.ai/scratch/e2e/accounting-20260909/`. Root owns payments and sales UI. Disjoint agents own Rillet, reports/defaults/large datasets, and purchasing/intercompany. Each records exact owned local/remote IDs and expected versus actual values. Credentials never enter evidence or tool output.
+
+Completed means executed and adjudicated, not that every test passed. Results and next fixes: [September 9 run](../runs/2026-09-09-accounting-e2e.md).
diff --git a/.ai/plans/2026-09-09-accounting-nuclear-review-fixes.md b/.ai/plans/2026-09-09-accounting-nuclear-review-fixes.md
new file mode 100644
index 0000000000..0a0f9ac707
--- /dev/null
+++ b/.ai/plans/2026-09-09-accounting-nuclear-review-fixes.md
@@ -0,0 +1,231 @@
+# Accounting nuclear-review fixes
+
+Fixes the eight confirmed Must-fix defects from the 2026-09-09 nuclear self-review of
+PR #1599, plus the low-risk "cheap win" items. Review record:
+[.ai/reviews/2026-09-09-accounting-nuclear-review.md](../reviews/2026-09-09-accounting-nuclear-review.md).
+
+## User decisions (2026-09-09)
+
+- Scope: **Must fix (8) + cheap wins**. Structural extractions and the Risks section
+ are out of scope for this pass.
+- Refund applications: **restore support**. The `cashIn !== isAR` refusal is treated as
+ an accidental regression, not a deliberate scope reduction.
+- `sourceAmount` backfill: **premise holds, no change**. Accounting is unused, so the
+ deliberate no-backfill design stays. This closes review findings that depended on
+ historical settlement data; they are not defects under the premise.
+
+## Tasks
+
+### T1 — Largest-remainder residual distribution (Must fix #1, #4)
+
+- [x] Add `distributeRoundingResidual(exactValues, target, scale)` to
+ `packages/database/supabase/functions/shared/precision.ts`. Hamilton/largest-remainder:
+ each part moves at most one minor unit; refuses when the residual exceeds one unit
+ per part. `precision.ts` is the sanctioned home (it is exempt from `no-raw-rounding`
+ as the implementation of rounding).
+- [x] Unit tests in `shared/precision.test.ts`.
+- [x] Rewrite `reconcileDocument` in `packages/ee/src/accounting/core/sales-document-components.ts`
+ to allocate net and tax through the new helper instead of concentrating the whole
+ residual on one component.
+- [x] Derive `unitAmount` from the reconciled `netAmount` instead of throwing when the
+ stored `convertedUnitPrice` mirror and the computed net straddle a rounding tie.
+- Verify: `pnpm --dir packages/ee exec vitest run src/accounting` and a regression test
+ proving 20 × $1.99 @ 8.25% keeps every component within one minor unit of
+ `round(net × taxPercent)`.
+
+### T2 — Intercompany matching scale (Must fix #2)
+
+- [x] `shared/sales-posting-amounts.ts` — `calculateSalesIntercompanyAmount` rounds at
+ `SCALE`, matching the buyer's `round(...)` in `post-purchase-invoice/index.ts:2022`.
+ The IC amount is an exact matching key, not a settlement amount.
+- [x] Drop the now-unused `currencyDecimals` parameter and update the call site.
+- Verify: new test asserting both sides agree on a 5dp document amount.
+
+### T3 — Restore refund applications (Must fix #3)
+
+- [x] Remove the `cashIn !== isAR` refusal in
+ `post-payment/post-payment-transaction.ts`; the two-axis journal logic in
+ `build-payment-journal.ts` already handles it.
+- [x] Regression test covering a Disbursement settling a sales invoice and a Receipt
+ settling a purchase invoice.
+
+### T4 — Rillet money precision (Must fix #5)
+
+- [x] `providers/rillet/entities/shared.ts` — remove the `decimalPlaces = 2` default so
+ the scale is always supplied; replace the `toDocumentAmount(0, rate, 2)` scale
+ literal in `toRilletExchangeRate`.
+- [x] Thread real `decimalPlaces` through `entities/payment.ts` and `entities/item.ts`.
+
+### T5 — On-account control description (Must fix #6)
+
+- [x] Add the on-account credit role to `shared/accounting-posting.ts` and use it from
+ both `post-payment-transaction.ts` and `build-payment-journal.ts`.
+
+### T6 — Report SQL (Must fix #7, #8)
+
+- [x] New migration: align the AR/AP tie-out `payment_unapplied` party filters with
+ their aging counterparts.
+- [x] `ALTER COLUMN "fxGainLossAmount" SET NOT NULL` (safe: the column was
+ `GENERATED ALWAYS` so no row can be NULL).
+- [x] Replace the eight bare `round(x,5)` scale literals with a named
+ `accounting_internal_scale()` helper.
+
+### T7 — Cheap wins
+
+- [x] Delete dead defaults writers `updateDefaultBalanceSheetAccounts` (zero callers)
+ and `updateDefaultIncomeAccounts` (test-only), both still MCP-exposed as
+ unvalidated/duplicate `WRITE` tools.
+- [x] Delete dead `getSettledInvoiceStatus` and its baselined raw-rounding violations.
+- [x] Export `assertExchangeRate` / `assertCurrencyDecimals` from
+ `shared/accounting-currency.ts` and replace the discarded-conversion validation
+ sites with named assertions.
+- [x] Docs freshness: `payments.mdx` (settlement field table, the CHECK sentence, the
+ FX plug sentence), `accounting.mdx` (shipping revenue), glossary term, and the two
+ unsupported `packages/utils/AGENTS.md` claims.
+
+## Verification gates
+
+`pnpm run lint` · scoped typechecks (`erp`, `@carbon/ee`, `@carbon/utils`, `@carbon/database`)
+· `@carbon/utils`, `@carbon/ee` accounting, ERP accounting/invoicing/reports, `@carbon/checks`
+· `deno test` for the pure edge helpers · `pnpm run generate:types` after the migration
+· `pnpm db:check:datasets` and `pnpm db:check:backups` before committing.
+
+## Verification results (2026-09-09)
+
+A local database was reachable, so the DB-backed regressions that normally cannot run
+were executed via the tracked runner.
+
+| Gate | Result |
+|---|---|
+| `pnpm run lint` | 35/35 tasks |
+| Scoped typecheck (erp, ee, utils, database, glossary, checks, workflows) | 8/8 tasks |
+| Edge functions (`deno test`, **with** `SUPABASE_DB_URL`) | **195 passed, 0 failed** (was 163 passed / 20 env-failed) |
+| `@carbon/utils` | 177 passed |
+| `@carbon/ee` accounting | 665 passed |
+| ERP accounting + invoicing + reports | 312 passed |
+| `@carbon/checks` conformance | 100 passed |
+| SQL suites (5) | 93 + 10 + 13 + 4 + 8 pass notices, all `ROLLBACK` |
+| `pnpm db:check:datasets` | 4/4 |
+| `pnpm db:check:backups` | restorable |
+| `pnpm run check:workflow-catalog` | ok |
+
+Red→green proofs recorded for the residual allocator (4/5 cases fail on the old code with
+deviations of 0.08/0.11/0.20/0.07 against a 0.01 envelope), the Rillet decimals fix
+(4 tests, JPY/BHD), the SQL party-filter fix, and the de-tautologised defaults test.
+
+## Deliberately NOT done (still open from the review)
+
+- The whole **Risks / questions** section — invoice-poster TOCTOU and row locks, the
+ purchase-side fixed-asset writes outside the Kysely transaction, payment-UI stale
+ `rows` state and raw engine errors surfaced to users, `new.tsx` loader/action
+ asymmetry, `getCompanyHasOpenCredits` regression, unbounded `FOR UPDATE`, the Xero
+ explicit `CurrencyRate: 1` reversal and 3-decimal refusal, the inbound Xero
+ `taxPercent` 100x, and the two questionable new MCP tools.
+- The **structural** items — edge-function extraction, `invoicing.service.ts` (3,188 lines)
+ and `accounting.ee.service.ts` (6,849 lines) splits, the duplicated currency-decimals
+ loader and double-spend block, and wiring `apps/erp` + `packages/database` into CI's
+ `turbo run test` (today `pnpm test` runs neither, so ~7,400 lines of this branch's
+ tests are unenforced — the single highest-leverage follow-up).
+- `sourceAmount` backfill — the user's "accounting is unused" premise holds, so the
+ deliberate no-backfill design stays.
+
+## Follow-up: the pre-existing failing tests (2026-09-09)
+
+Turning CI on required both suites to be green first. They were not. All were
+**pre-existing** — none caused by this branch.
+
+| Suite | Before | After |
+|---|---|---|
+| `apps/erp` (vitest) | 978 passed / **11 failed** (4 files) | **990 passed / 0 failed** (80 files) |
+| `packages/database` (deno, no DB) | 254 passed / **21 failed** | **257 passed / 0 failed / 20 ignored** |
+| `packages/database` (deno, with DB) | — | **277 passed / 0 failed** |
+
+### Root causes
+
+- **9 of the 11 ERP failures trace to ONE commit**, `7f5f1d2145` (#1151, the
+ `x/schedule` → `x/priority` route move plus in-process scheduling). It renamed
+ `path.to.scheduleDatesUpdate` → `priorityDatesUpdate` and replaced
+ `invoke("schedule")` with `runLocationSchedule`. Two test files were never
+ re-pointed. In `drag-lifecycle.test.tsx` the stale `~/utils/path` mock made
+ `path.to.priorityDatesUpdate` `undefined`, which both blanked the submitted
+ `action` AND silently disabled the pending-fetcher merge, so two guard tests
+ had quietly become no-ops. Both fixes are test-side; the production ordering
+ and routing are correct, proven by mutation (reordering the route, or reverting
+ the mock, makes them fail again).
+- **`lib/response.test.ts`** asserted a ZodError is suppressed entirely. The code
+ deliberately surfaces a compact `zodIssueSummary` instead — documented at
+ length in `response.ts`, and matching the existing lesson about sanitization
+ eating legible messages. Stale test; replaced with three assertions covering
+ the summary, the five-issue cap and the empty-issues case.
+- **`i18n-react-macros.test.ts`** banned the `@lingui/core/macro` MODULE, flagging
+ **284** files for importing `msg` — the exact pattern
+ `.claude/rules/i18n-lingui-system.md` prescribes for route breadcrumbs. The gate
+ contradicted the documented convention, so it could never pass. Narrowed to what
+ the rule actually prohibits: `t` from `core/macro` (0 offenders) and unwrapping a
+ literal at runtime, `i18n._(msg`…`)` (3 offenders, fixed — `i18n._(dynamicDescriptor)`
+ from a lookup map, as in `workflows/ui/Builder/catalog.ts`, is legitimate and is
+ deliberately not matched).
+- **`localized-submodule-ui.test.ts`** had two bugs. `.test()` on a shared `/g`
+ regex is stateful, so a match in one file made the next start mid-string and
+ under-report. And the `>Label<` patterns match `<Trans>Edit</Trans>`, because
+ that string *contains* `>Edit<` — so they flagged correctly-localized JSX, and
+ the suite could only be satisfied by UNDOING the localization it exists to
+ enforce. Fixed by resetting `lastIndex`, stripping `<Trans>…</Trans>` before
+ scanning, and requiring non-whitespace content in the card-attribute pattern.
+ One genuinely raw label (`CustomerHeader` "Tax Status") was localized. Mutation-
+ tested: a raw `<span>Edit</span>` and a raw `<CardAttributeLabel>` are still caught.
+- **The 20 deno failures** were the `SUPABASE_DB_URL` gate throwing. They now SKIP
+ via `databaseTest` (`ignore: !hasLocalDatabase`) — a bare `deno test` is green on
+ a clean checkout, which is the prerequisite for ever putting it in CI.
+
+### Still blocking full CI adoption
+
+`deno task test` typechecks and fails with **8 pre-existing type errors** (6 from
+the kysely/deno-postgres `Pool` impedance in `lib/postgres/index.ts`, plus a TS2589
+in `get-next-sequence.ts`). `packages/database/tsconfig.json` includes only `src`
+and `supabase/functions/lib/postgres/**`, so **the rest of the edge-function tree —
+all of the accounting posting logic — is typechecked by nothing in CI.** Running
+the deno tests with `--no-check` gets the tests into CI today; closing the type gap
+is separate work.
+
+## CI wiring (2026-09-09)
+
+Both suites now run on every PR.
+
+- `apps/erp/package.json` gains `"test": "vitest run"`. `turbo run test` picks it up,
+ so the existing `test` job in `.github/workflows/check.yml` gains **990 tests** with
+ no infrastructure change (`pnpm test`: 28/28 tasks, was 27).
+- New `edge-functions` job in `check.yml` — `denoland/setup-deno` then `deno task test`
+ from `packages/database/supabase/functions`, covering **257 tests** (20 DB-backed ones
+ skip). Deliberately NOT added to `turbo run test`, so `pnpm test` keeps working for
+ anyone without Deno installed.
+- `deno.json`'s `test` task is now `deno test --no-lock --no-check --allow-all`. It
+ previously typechecked and failed on 8 pre-existing errors, so it could never have
+ been used as a gate.
+- `hasLocalDatabase` catches `PermissionDenied` as well as an absent variable, because
+ it runs at module scope — without that, `deno test` with no permission flags died
+ before a single pure test could run.
+
+### CI-equivalent verification
+
+| Job | Command | Result |
+|---|---|---|
+| Lint | `pnpm exec biome check` | 35/35 |
+| Typecheck | `pnpm run typegen && pnpm run typecheck` | 31/31 |
+| Lingui | `pnpm run lingui:check` | pass |
+| Catalog | `pnpm run check:workflow-catalog` | ok |
+| Test | `pnpm test` | 28/28, erp 990 passed |
+| Edge Functions | `deno task test` | 257 passed, 0 failed, 20 ignored |
+
+### Known limitation, deliberately accepted
+
+The edge-function job runs `--no-check`. `packages/database/tsconfig.json` covers only
+`src` and `supabase/functions/lib/postgres/**`, so the rest of that tree — including all
+the accounting posting logic — is typechecked by **nothing**. `deno check` reports 8
+pre-existing errors (6 kysely/deno-postgres `Pool` typings, 1 TS2589 in
+`get-next-sequence.ts`). Getting the tests running was worth more than blocking on the
+types; closing the type gap is the next follow-up.
+
+The 20 DB-backed regressions still only run locally, via
+`pnpm exec tsx scripts/run-local-accounting-check.ts`. Provisioning Postgres + migrations
+in CI so they and the 5 SQL suites run is the remaining piece.
diff --git a/.ai/plans/improve/2026-09-07-accounting-readiness-audit.md b/.ai/plans/improve/2026-09-07-accounting-readiness-audit.md
new file mode 100644
index 0000000000..5cd25c43de
--- /dev/null
+++ b/.ai/plans/improve/2026-09-07-accounting-readiness-audit.md
@@ -0,0 +1,112 @@
+# Accounting readiness assessment — 2026-09-07
+
+Assessed [#1060](https://github.com/crbnos/carbon/issues/1060) against HEAD `0a9aef2444b04f0a0f0ade6f99dcd8e60aa3ec30`. HEAD, local origin/main and the remote main SHA were identical at audit time. Issue bodies/specs supplied acceptance criteria; issue states and checkboxes supplied no implementation evidence.
+
+**Execution update (2026-09-08):** The approved [posting corrections plan](../2026-09-07-accounting-posting-corrections.md) now implements tax/shipping separation, exact payment funding and transaction FX, historical AR/AP reports, and consolidation CTA corrections. The matrix below preserves the original audit baseline; it must not be read as the current implementation status of those corrected defects. France and e-invoicing were explicitly excluded from this implementation. Provider sandbox acceptance, fixed-asset void lifecycle, record integrity and broader close/readiness controls remain follow-up work.
+
+**Verdict:** Carbon has a substantial operational accounting foundation, but the program's public-company-readiness exit criteria are not met. Work remains on present-day monetary correctness, independent approvals, record integrity, bank close, GAAP subledgers and statutory interfaces. The current evidence supports neither a readiness date nor a credible percentage-complete estimate.
+
+The July readiness document explicitly **assumes implemented** tax, budgeting, bank reconciliation and FX normalization. Those assumptions do not describe current main. See [the assumed baseline](../../specs/2026-07-03-public-company-readiness.md#L19). Rebaseline the tracker before using its DAG to dispatch work.
+
+**What is present**
+
+Period locking, sequential close/reopen, persisted checklist and transactional balance snapshots; posted-only multi-period balance sheet/income statement scans, TB and ledger drilldowns; inventory quantity-adjustment postings, cost-layer adjustments and overhead absorption; full asset disposal gain/loss; per-trade intercompany eliminations; daily exchange-rate store and company overrides; opening balance entry; several external accounting connectors. These are implemented building blocks, not sign-offs on their enclosing workstreams.
+
+**Code-backed workstream matrix**
+
+“Partial” means material implementation exists but the issue's complete acceptance contract is unmet. “Missing” means the program-specific implementation was not found or the described correction is still absent; older generic foundations can exist. No row represents a production deployment or auditor attestation.
+
+| Issue | Workstream | Assessment | Current code and remaining scope | Evidence |
+|---|---|---|---|---|
+| [#1030](https://github.com/crbnos/carbon/issues/1030) | FX convention | Missing | A new rate store exists, but invoice/payment posting still multiplies foreign-per-base rates; the required coordinated normalization is absent. | [payment conversion](../../../packages/database/supabase/functions/post-payment/build-payment-journal.ts#L192) |
+| [#1031](https://github.com/crbnos/carbon/issues/1031) | Period close and immutability | Partial | Open→Locked→Closed, sequential close/reopen, checklist and snapshots exist. Posted/reversed-header and line-insertion protection remains incomplete. | [close lifecycle](../../../apps/erp/app/modules/accounting/accounting.ee.service.ts#L2472); [latest immutability guard](../../../packages/database/supabase/migrations/20260712142905_reconcile-period-close-definitions.sql#L22) |
+| [#1032](https://github.com/crbnos/carbon/issues/1032) | Accounting approvals / SoD | Missing | Reusable engine supports PO, quality documents and supplier approvals only. No JE/payment/purchase-invoice/memo approval extension or no-self-approval control. | [supported approval types](../../../apps/erp/app/modules/shared/shared.models.ts#L14); [direct JE posting](../../../apps/erp/app/modules/accounting/accounting.ee.service.ts#L5213) |
+| [#1033](https://github.com/crbnos/carbon/issues/1033) | IT general controls (deferred) | Partial | TOTP MFA and Enterprise SAML now exist. The CI dependency audit still ignores failure; the inspected deploy pipeline has no staging-promotion gate. This is not an exhaustive ITGC audit. | [TOTP](../../../packages/auth/src/services/mfa.server.ts#L39); [SAML gate](../../../packages/ee/src/sso/gate.ts#L12); [nonblocking audit](../../../.github/workflows/check.yml#L184) |
+| [#1034](https://github.com/crbnos/carbon/issues/1034) | Bank reconciliation P1 | Missing | No dedicated bank master, bank statements, matching/reconciliation documents or source-currency journal fields found. A payment's bankAccount is a GL account reference. | [existing payment model](../../../packages/database/supabase/migrations/20260630093809_ar-ap-payments.sql#L238) |
+| [#1035](https://github.com/crbnos/carbon/issues/1035) | Financial reporting | Partial | BS/IS/TB, multi-period columns, CSV, ledger drawers and consolidation exist. Cash flow, fiscal-year retained-earnings split, gross TB debit/credit activity and statement PDF package remain missing. | [cumulative earnings](../../../apps/erp/app/modules/accounting/accounting.ee.service.ts#L724); [netted TB columns](../../../apps/erp/app/modules/accounting/ui/Reports/TrialBalanceTree.tsx#L141) |
+| [#1036](https://github.com/crbnos/carbon/issues/1036) | Tax P1 | Missing | Percentage/amount tax fields exist, but ordinary taxed sales post gross to revenue. No tax codes/components/registrations, tax ledger, recovery/reverse-charge machinery or liability report found. | [gross calculation](../../../packages/database/supabase/functions/post-sales-invoice/index.ts#L318); [gross revenue posting](../../../packages/database/supabase/functions/post-sales-invoice/index.ts#L419) |
+| [#1037](https://github.com/crbnos/carbon/issues/1037) | Budgeting P1 | Missing | No budget header/line model, matrix, approval or budget-versus-actual implementation found. | Search A below; existing fiscal periods/cost centers are prerequisites. |
+| [#1038](https://github.com/crbnos/carbon/issues/1038) | Gapless numbering / legal series | Partial | Atomic counter allocation is fixed. Draft/pre-post allocation remains; no posting-time legal-series/cutover/used-counter immutability contract found. | [atomic allocator](../../../packages/database/supabase/functions/shared/get-next-sequence.ts#L28); [numbered draft creation](../../../apps/erp/app/modules/accounting/accounting.ee.service.ts#L4922) |
+| [#1039](https://github.com/crbnos/carbon/issues/1039) | Close automation | Missing | Manual depreciation exists. No scheduled proposal engine, prepaid/recurring/auto-reversing machinery. The depreciation check only warns on existing drafts; no run can pass. | [draft count](../../../apps/erp/app/modules/accounting/accounting.ee.service.ts#L2952); [checklist condition](../../../apps/erp/app/modules/accounting/accounting.ee.service.ts#L3130) |
+| [#1040](https://github.com/crbnos/carbon/issues/1040) | Inventory valuation completeness | Partial | Quantity-adjustment GL, cost-layer adjustments, overhead absorption and valuation/tie-out report exist. Standard costing remains hidden; revaluation/LCNRV/landed-cost documents and full variance treatment are missing. | [Standard hidden](../../../apps/erp/app/modules/items/ui/Item/ItemCostingForm.tsx#L72); [adjustment GL](../../../packages/database/supabase/functions/shared/post-adjustment.ts#L361); [single variance account](../../../packages/database/supabase/functions/close-job/index.ts#L115) |
+| [#1041](https://github.com/crbnos/carbon/issues/1041) | Fixed assets completeness | Partial | Acquisition, manual depreciation and invoice-linked full disposal with gain/loss exist. No impairment, CIP, component assets or partial-disposal implementation found. | [gain/loss calculation](../../../packages/database/supabase/functions/post-sales-invoice/index.ts#L635); [gain/loss posting](../../../packages/database/supabase/functions/post-sales-invoice/index.ts#L688) |
+| [#1042](https://github.com/crbnos/carbon/issues/1042) | Plaid / cash position | Missing | No Plaid feed, sync cursor/token model or cash-position implementation found. | [integration registry](../../../packages/ee/src/index.ts#L31); Search A. |
+| [#1043](https://github.com/crbnos/carbon/issues/1043) | Tax P2 returns | Missing | No tax-return documents, ledger stamping, UK layout, settlement/reopen or remittance implementation found. | Search A; tax-ledger prerequisite also missing. |
+| [#1044](https://github.com/crbnos/carbon/issues/1044) | Tax P3 AvaTax | Missing | No AvaTax determination/commit/void/fallback-and-reconcile engine found. Generic provider taxCode fields are not Carbon's tax model. | [integration registry](../../../packages/ee/src/index.ts#L31); Search A. |
+| [#1045](https://github.com/crbnos/carbon/issues/1045) | Budgeting P2–3 | Missing | No commitment accounting, budget controls/overrides or consolidated budget-versus-actual implementation found. | Search A; budget model prerequisite missing. |
+| [#1046](https://github.com/crbnos/carbon/issues/1046) | Bank reconciliation P3–4 | Missing | No advanced bank parsers, rules, tolerance adjustment or transfer machinery found. | Search A; bank reconciliation prerequisite missing. |
+| [#1047](https://github.com/crbnos/carbon/issues/1047) | Integrity / audit / JE export / book seed | Partial | Append-only audit-log protection exists. Mandatory synchronous accounting capture, comprehensive posted-record guards, deferred balance enforcement, protected long-term archives, canonical JE population export and book seed remain missing. | [optional asynchronous capture](../../../packages/jobs/src/inngest/functions/events/audit.ts#L90); [append-only guard](../../../packages/database/supabase/migrations/20260818014100_audit-log-append-only.sql#L12) |
+| [#1048](https://github.com/crbnos/carbon/issues/1048) | ASC 606 revenue recognition | Missing | Ordinary invoice-time revenue posting exists; no arrangements/obligations/SSP, recognition schedules, POC, contract rollforwards or close integration found. | [current revenue trigger](../../../packages/database/supabase/functions/post-sales-invoice/index.ts#L419); Search A. |
+| [#1049](https://github.com/crbnos/carbon/issues/1049) | Segments / dimension enforcement | Missing | Generic dimensions exist, but reserved Segment derivation/disclosures and required-dimension posting enforcement were not found. | [dimension writer](../../../apps/erp/app/modules/accounting/accounting.ee.service.ts#L4357); [posting validation](../../../apps/erp/app/modules/accounting/accounting.ee.service.ts#L5162) |
+| [#1050](https://github.com/crbnos/carbon/issues/1050) | FX / consolidation completeness | Partial | Daily global rates, overrides and actual pair-rate consolidation exist. No revaluation runs, posted CTA rollforward or transaction-level historical layers. Current CTA calculation also mishandles Expense signs. | [rate resolver](../../../packages/database/supabase/migrations/20260903015941_exchange-rate-global-store.sql#L244); [CTA calculation](../../../apps/erp/app/modules/accounting/accounting.ee.service.ts#L4464) |
+| [#1051](https://github.com/crbnos/carbon/issues/1051) | Master-data controls | Missing | Supplier settings cover invoice party/payment terms; no controlled bank-detail/version/verification/change-alert workflow found. | [supplier payment settings](../../../apps/erp/app/modules/purchasing/purchasing.models.ts#L406) |
+| [#1052](https://github.com/crbnos/carbon/issues/1052) | Multi-book | Missing | No accounting books, journal.bookId, adjustment generators or book-specific reports/close found. Tax depreciation fields are not adjustment books. | [single-ledger TB contract](../../../packages/database/supabase/migrations/20260811123614_widen-ledger-amounts.sql#L196); Search A. |
+| [#1053](https://github.com/crbnos/carbon/issues/1053) | Statutory files / retention (deferred) | Missing | No FEC/SAF-T validation, statutory account mapping, archive legal hold or WORM enforcement found in inspected source. Existing gzip archives use ordinary mutable object storage. | [archive upload](../../../packages/jobs/src/inngest/functions/scheduled/audit-archive.ts#L70); Search A. |
+| [#1054](https://github.com/crbnos/carbon/issues/1054) | E-invoicing | Missing | No EN 16931 renderers, clearance state machine, legal issuance gating or structured inbound AP ingestion found. | Search A; provider registry and tax prerequisite also missing. |
+| [#1055](https://github.com/crbnos/carbon/issues/1055) | WHT / ECSL / Intrastat / MTD | Missing | No withholding/trade declaration models, UK MTD submission or corresponding reporting adapters found. | Search A. |
+| [#1056](https://github.com/crbnos/carbon/issues/1056) | Leases | Missing | No lease subledger, effective-interest schedules, modification/posting runs, disclosures or lessor machinery found. | Search A; multi-book prerequisite missing. |
+| [#1057](https://github.com/crbnos/carbon/issues/1057) | Cutover / flag retirement | Partial | Opening balances and one-posted-opening-entry control exist. accountingEnabled remains reversible; no controlled activation validation/runbook evidence or flag retirement. | [opening-balance gate](../../../apps/erp/app/modules/accounting/accounting.ee.service.ts#L5233); [reversible toggle](../../../apps/erp/app/routes/x+/settings+/accounting.tsx#L94) |
+| [#1058](https://github.com/crbnos/carbon/issues/1058) | Intercompany maturity | Partial | Exact matching and per-trade control/revenue/COGS/capitalization eliminations exist. No tolerance/FX-difference matching, mirrored documents, netting or paired settlement found. | [exact matching](../../../packages/database/supabase/migrations/20260816154722_intercompany-elimination-matching-hardening.sql#L55); [per-trade eliminations](../../../packages/database/supabase/migrations/20260817122328_intercompany-revenue-cogs-elimination.sql#L388) |
+| [#1059](https://github.com/crbnos/carbon/issues/1059) | Integration surface | Partial | Generic REST/MCP operations include TB and JE services. Specified book-aware contracts, canonical full JE export, controlled batch import/idempotency and signed accounting webhooks are missing. | [operation catalog](../../../apps/erp/app/routes/api+/v1+/lib/operations.server.ts#L8); [router](../../../apps/erp/app/routes/api+/v1+/lib/router.server.ts#L26) |
+| [#1061](https://github.com/crbnos/carbon/issues/1061) | Avalara foundation | Missing | No Avalara registry entry, shared client/lifecycle hooks or sandbox smoke-test implementation found. | [integration registry](../../../packages/ee/src/index.ts#L31); [hook registry](../../../packages/ee/src/hooks.server.ts#L46) |
+
+**Highest-priority findings**
+
+Effort: S = hours, M = approximately a day or several focused days, L = multiple days or a multi-PR workstream. These are coarse engineering estimates, not delivery commitments. All findings below have high confidence from source inspection; the CTA finding was also reproduced from the actual function with a mocked rate RPC.
+
+| Priority | Finding | Impact | Effort | Change risk | Evidence |
+|---|---|---|---|---|---|
+| P0 | Tax still flows to ordinary sales revenue | A base-currency 100 sale plus 20 tax credits revenue 120; the required 100 revenue / 20 payable split does not occur. Purchases also fold tax into cost without recoverability machinery. | L for #1036 | High: invoice, memo, void, ledger and GL contracts | [tax-inclusive total](../../../packages/database/supabase/functions/post-sales-invoice/index.ts#L318); [revenue credit](../../../packages/database/supabase/functions/post-sales-invoice/index.ts#L419); [purchase total](../../../packages/database/supabase/functions/post-purchase-invoice/index.ts#L844) |
+| P0 | Foreign-currency posting convention remains wrong | Rates resolve as foreign units per base unit; invoice/payment multipliers do not implement the program's divide-to-base convention. Matching invoice/payment mistakes can still produce a misleading tie-out. | L | High: coordinated monetary change | [rate ratio](../../../packages/database/supabase/migrations/20260903015941_exchange-rate-global-store.sql#L256); [sales conversion](../../../packages/database/supabase/functions/post-sales-invoice/index.ts#L344); [cash conversion](../../../packages/database/supabase/functions/post-payment/build-payment-journal.ts#L192) |
+| P0 | Consolidation creates phantom CTA from Expense balances | Cash 80, Revenue 100, Expense 20, all USD at rate 1, produces CTA −40 instead of 0. Expense is added to equity contributions instead of subtracted. | S–M | Medium: reported consolidated balances change | [actual calculation](../../../apps/erp/app/modules/accounting/accounting.ee.service.ts#L4464); [real caller input](../../../apps/erp/app/modules/accounting/accounting.ee.service.ts#L595); [report application](../../../apps/erp/app/routes/x+/reports+/balance-sheet.tsx#L147) |
+| P0 | Posted-record protection is incomplete | Journal reversal permits business-field changes; old Reversed headers are not guarded by the trigger; line INSERT has no finalized-parent guard. The latter must preserve legitimate posters that insert header/lines atomically. | M header fix; L full boundary | Medium/high: every posting writer | [header guard](../../../packages/database/supabase/migrations/20260712142905_reconcile-period-close-definitions.sql#L30); [line trigger](../../../packages/database/supabase/migrations/20260712142905_reconcile-period-close-definitions.sql#L60) |
+| P0 | Independent accounting approval controls are missing | The accounting document families can post without the specified maker/checker and no-self-approval controls. | L | High: statuses, permissions and posting | [supported types](../../../apps/erp/app/modules/shared/shared.models.ts#L14); [posting transition](../../../apps/erp/app/modules/accounting/accounting.ee.service.ts#L5213) |
+| P0 | Audit storage protection exceeds capture/retention protection | Append-only rows exist, but capture remains optional/asynchronous and lacks core accounting-table coverage. Archives are uploaded with upsert and rows purged; no program-required duration/hold enforcement was found. | L | High: posting and retention | [capture gate](../../../packages/jobs/src/inngest/functions/events/audit.ts#L90); [entity allowlist](../../../packages/database/src/audit.config.ts#L139); [archive path](../../../packages/jobs/src/inngest/functions/scheduled/audit-archive.ts#L70) |
+| P1 | Close evidence is incomplete | No bank reconciliation; no-run depreciation passes its check; core financial statement package remains partial. | L | Medium/high | [depreciation condition](../../../apps/erp/app/modules/accounting/accounting.ee.service.ts#L3130); [earnings presentation](../../../apps/erp/app/modules/accounting/accounting.ee.service.ts#L724); [TB activity columns](../../../apps/erp/app/modules/accounting/ui/Reports/TrialBalanceTree.tsx#L141) |
+
+The journal-header finding was checked against RLS and the later period guard: [journal update policy](../../../packages/database/supabase/migrations/20260402000000_journal-entries.sql#L83) allows existing Posted rows; [period guard](../../../packages/database/supabase/migrations/20260713235930_close-snapshot-posting-lock.sql#L59) skips unchanged dates/periods except Draft→Posted. Existing Reversed rows are excluded by ordinary-user update RLS, so the Reversed reset gap is specifically relevant to privileged/service-role writers. No live database mutation was attempted.
+
+**Recommended execution order**
+
+1. **Restore trustworthy regression coverage and fix the narrow statement/record defects.** Repair the three stale period-test mocks; add same-currency CTA and exact reversal/final-state regression cases. Correct CTA signing and the journal-header boundary promptly.
+2. **Run two coordinated foundation tracks.** Controls: #1032 accounting approvals, then #1047 full record/audit/balance/export/book-seed requirements as dependencies become available, with #1038 posting-time numbering. Monetary correctness: #1030 across invoices/payments/receipts/tie-outs, then #1036 tax Phase 1. The shared posting files require sequencing/rebasing, not concurrent uncoordinated changes.
+3. **Prove a complete accounting close.** #1034 bank reconciliation and core #1035 reporting, followed by #1039 scheduled close proposals/checks and #1050 revaluation/posted CTA. Demonstrate opening TB + complete JE population = closing TB; reconcile AR/AP, bank, inventory and fixed assets to GL; exercise cross-year earnings, FX, approvals, void/reversal and close/reopen.
+4. **Finish manufacturing measurement and required subledgers.** Complete #1040 standard cost/variances/revaluation/LCNRV/landed cost and #1041 assets. Add #1048 revenue recognition for relevant contracts; #1052 books before book-specific lease/NRV/depreciation deltas and #1056. Deliver #1049 server dimension enforcement with these posting paths. Schedule #1051 before vendor payment execution, and finish #1059 once its controlled primitives exist.
+5. **Gate always-on accounting on evidence.** #1057 needs controlled activation, reconciled opening subledgers, at least two demonstrated company cutovers and flag retirement. A convenience opening-balance form does not satisfy this.
+6. **Keep budgeting and advanced banking behind correctness and close evidence.** #1037/#1045 and #1042/#1046 remain valuable, but do not repair the current tax/FX/control gaps. This is delivery ordering; the full program scope remains.
+
+Refresh existing plans against current source before execution. The September rate refactor does not implement #1030. The old #1047 wording about raw `SUM(journalLine.amount)=0` is incompatible with current natural-balance signing: decode account class, as [the existing manual-JE validator](../../../apps/erp/app/modules/accounting/accounting.ee.service.ts#L5162) does. Do not replay superseded migration definitions or implement controls against stale schemas.
+
+**Statutory and company work in parallel**
+
+As of this assessment date, the September 1, 2026 French deadline has passed. In-scope French businesses must receive electronic invoices; large and intermediate businesses must also issue them, while SMEs/microbusinesses have a September 1, 2027 issuance deadline. The issue's blanket “France issue mandate September 2026” wording is too broad. [DGFiP timetable](https://www.impots.gouv.fr/professionnel/questions/partir-de-quand-suis-je-concerne-par-la-reforme-de-la-facturation).
+
+Poland's KSeF timetable already applies, subject to its scope/exemptions: large-taxpayer issuance from February 1, others generally April 1, 2026, with limited transitional exceptions; receipt from February 1. [Polish Ministry of Finance scope and timetable](https://ksef.podatki.gov.pl/informacje-ogolne-ksef-20/zakres-obowiazkowego-ksef/).
+
+Customer legal-entity exposure and any external platform already meeting these duties were not established. Confirm those immediately; if relevant, establish an approved provider-based operational path while executing #1061 → #1044/#1054 with tax and legal-series prerequisites. Do not assume the absent Carbon connector means a particular customer is noncompliant.
+
+#1053's deferred status does not waive FEC/SAF-T/statutory mapping/retention requirements in the program's exit criteria. #1033 also contains real delivered auth work, but remains incomplete as a vendor-control program. Assign the readiness/auditor/SOC evidence work in parallel: software inspection cannot establish control operating effectiveness, which the [PCAOB integrated-audit standard](https://pcaobus.org/oversight/standards/auditing-standards/details/AS2201) requires auditors to test. No live evidence program or auditor engagement was verified here.
+
+**Verification evidence**
+
+- `git rev-parse HEAD origin/main` plus `git ls-remote origin refs/heads/main`: all returned the revision above.
+- `pnpm --filter erp exec vitest run app/modules/accounting/accounting.utils.test.ts app/modules/accounting/accounting.periods.test.ts`: **97 passed, 3 failed**. Utilities 69/69; periods 28/31. Three scripted Supabase mocks lack `maybeSingle()` now called by the company-timezone lookup. This establishes stale tests, not a production close failure.
+- `pnpm --filter erp exec vitest run app/modules/accounting/accounting.utils.test.ts app/modules/accounting/ui/Reports/executivePnl.test.ts app/modules/accounting/ui/Reports/pivotData.test.ts`: **95 passed**; 69 overlap with the preceding command.
+- From `packages/database/supabase/functions`: `deno test --cached-only --no-check post-payment/post-payment.test.ts`: **33 passed**. Existing FX cases pin current multiply semantics; these passes do not clear #1030.
+- `deno test --no-config --no-lock --cached-only packages/database/supabase/functions/shared/post-adjustment.test.ts packages/database/supabase/functions/shared/purchase-cost-adjustment.test.ts`: **14 passed**.
+- Unique tests across those commands: **170 passed, 3 failed**.
+- Document-total and exchange-rate-job Vitest commands could not start because `@carbon/config/dist/vitest.mjs` is absent. No package build/install was performed to alter this audit environment.
+- Actual `translateCompanyBalances` declaration extracted and transpiled in memory; only rate RPC and rounding dependency supplied locally. Balanced USD fixture yielded **expected CTA 0, actual −40**, independently reproduced by the primary reviewer.
+- **Search A:** targeted TS/TSX/SQL symbol searches over `apps/` and `packages/`, including migrations and posting functions, excluding dependency/build/generated catalogs; cross-checked route/file names, operation and integration registries, current models and latest SQL definitions. Searched named models included `taxLedger`, `taxRegistration`, `taxReturn`, `eInvoiceDocument`, `tradeDeclaration`, `bankReconciliation`, `bankStatement`, `budgetLine`, `plaidItem`, `revenueArrangement`, `revenueRecognitionSchedule`, `prepaidSchedule`, `recurringJournalTemplate`, `accountingBook`, `bookId`, `fixedAssetBook`, `leaseScheduleLine`, `legalSeries`, `supplierBankChange` and `apiIdempotencyKey`. Generic external-provider `taxCode` fields were not counted as a tax-code subsystem.
+
+**Considered and rejected / boundaries**
+
+- The old duplicate-sequence allocation race is fixed; gapless posting is the remaining requirement.
+- Full asset sale proceeds/gain/loss posting is fixed; impairment/CIP/components/partial disposal remain.
+- Intercompany source-date/per-trade elimination fixes are present; tolerance/netting/mirroring remain.
+- Draft exclusion in modern statement balance scans and the daily rate writer are implemented; do not repeat the July “all drafts included/no rate writer” claims.
+- Natural-balance journal signing is intentional. Report and constraint math must honor it.
+- Inventory valuation's historic-date mode explicitly uses historical quantities with **current** costs/statuses ([documented implementation](../../../packages/database/supabase/migrations/20260715021050_inventory-valuation-rpc.sql#L13)). Treat this as a readiness boundary, not a newly introduced bug or a historical close valuation proof.
+- Audit `retentionDays: 30` is the live-table archival threshold, **not proof that all history is destroyed after 30 days**. The finding is absent protected long-term retention/capture/hold enforcement.
+- No DB schema/application, browser workflow, production deployment, customer balances, country certification, live Avalara/HMRC contract or control operating-effectiveness evidence was verified. This was an issue-scoped code audit, not a comprehensive security or financial audit.
+- Source code, issue states and remote records were unchanged. This assessment is the only authored artifact.
diff --git a/.ai/playbooks/accounting-posting-corrections-reports.md b/.ai/playbooks/accounting-posting-corrections-reports.md
new file mode 100644
index 0000000000..59ebdefd06
--- /dev/null
+++ b/.ai/playbooks/accounting-posting-corrections-reports.md
@@ -0,0 +1,107 @@
+# Accounting Posting Corrections — Financial Reports
+
+Last tested: 2026-09-09
+Route: `/x/reports/balance-sheet`
+Plan: `.ai/plans/2026-09-07-accounting-posting-corrections.md`, Task 18, Workflow C
+
+## Prerequisites
+
+- A running, migrated local ERP stack; resolve `ERP_URL` from `.env.local`.
+- Authenticate with the auth skill. Keep browser sessions sequential when investigating local login problems, and compare host/runtime UTC clocks after laptop sleep.
+- An owned test parent and subsidiary sharing a chart. The parent has no posted activity; the subsidiary has one balanced journal with Cash debit 80 and Sales credit 80, posted through the actual journal form.
+- The parent's `accountDefault.currencyTranslationAccount` points to custom posting leaf **3998 Report Test Custom CTA**, beneath **Report Test Translation Reserve** beneath Equity. The subsidiary retains the seeded default, proving translated reports resolve the parent's mapping.
+- Identity case: both companies use the same currency. Foreign case: subsidiary-to-parent closing rate 2 and average rate 1.5.
+- `getConsolidationRates` reads the global daily currency pairs; company overrides do not affect this report. This run created unused test codes XXX/XTS only after verifying no existing codes, companies, or rates used them. Existing currency feeds were not changed. Rates: XXX=1 and XTS=1 on 2026-08-01; XXX=2 and XTS=1 on 2026-08-31. The mean pair rate is 1.5. Group historical rate is 1.
+
+## Steps
+
+### 1. Post the source journal
+
+Open `/x/journal-entry/{journalId}/details`. Confirm Cash debit 80, Sales credit 80, posting date 2026-08-15, and balanced totals. Submit the Post button's form with `form.requestSubmit(postButton)`. Verify POSTED status, disabled amount inputs, and the success toast. Independently read the journal and lines to confirm both stored natural amounts are 80 and status is Posted.
+
+### 2. Verify identity reports
+
+Open `/x/reports/balance-sheet?companies={subsidiaryId}&startDate=2026-07-01&endDate=2026-08-31`. Use Monthly columns. July is zero throughout; August Cash and Cash & Bank/Assets are 80, Net Income and Equity are 80, custom CTA and its subgroup are zero, and the Balance Sheet root is zero.
+
+Open the report's company selector, snapshot the menu, and select All Companies. Confirm the same values. Click Download in both scope selections and compare every exported account and both monthly columns with the report loader's displayed measure.
+
+### 3. Verify foreign reports
+
+Set only the owned subsidiary's base currency to the test source currency. Confirm the rate RPC resolves closing 2 and average 1.5. Reopen the subsidiary report and click **Show in XXX** (the reporting parent's currency).
+
+Expected August values: Cash/Cash & Bank/Assets 160; Net Income 120; custom CTA 40; its subgroup 40; Equity 160; Balance Sheet root zero. Seeded account 3200 remains zero. July remains zero.
+
+Collapse Assets to bring Equity into view. Click Equity's disclosure chevron to collapse, then expand it; confirm Net Income, the custom subgroup, and account 3998 remain correct. Switch to All Companies through the report selector and repeat. Download both CSVs and compare every account and column with the loader.
+
+## Selector Notes
+
+- The breadcrumb company selector and report company selector share the subsidiary name. Use the selector beside the Search accounts field, not the breadcrumb.
+- Company options are `menuitemradio` roles: All Companies, the parent name, and the subsidiary name.
+- A tree row's center does not toggle expansion; click its disclosure chevron. The tree virtualizes rows, so collapse Assets or scroll to reveal lower Equity leaves.
+- Actual exports include the full account tree even when groups are collapsed or rows are outside the virtualizer's viewport.
+- For evidence, capture only the relevant report entry in `window.__reactRouterDataRouter.state.loaderData`; never dump the root loader or authentication state.
+- In agent-browser 0.20.7, `screenshot body {path}` reliably writes the specified path. The download command used a directory/UUID file; an already-finished download followed by `wait --download` stalled. Capturing the generated Blob while clicking the real Download button preserved the exact exported CSV without rebuilding it.
+
+## Verified Results and Evidence
+
+All four cases passed: identity subsidiary, identity All Companies, translated subsidiary, translated All Companies. Each CSV had 54 account rows; all rows matched both monthly loader columns. Expanded Equity showed the parent-configured custom CTA exactly once.
+
+Local fixture identifiers and rate ownership: `.context/accounting/report-browser-fixture.json`.
+
+- Parent: `2835329ce4aa40a68e6c`; subsidiary: `e238bd65d92849e89152`; group: `cg_M4AGJ1Q4ToQRGc8McncJep`.
+- Posted source journal: `je_UX5A93t6WudGLmNXYSTzXX` (`REPORT-TEST-80`).
+- Custom CTA: `acct_QpURLHR8Evs5vxokzbZsR6`; subgroup: `acct_Mw3MZJTn4itkgzU2uh5Lk9`.
+- Screenshots: `.context/accounting/report-browser-source-posted.png`, and `report-browser-{identity,foreign}-{subsidiary,all}.png` in the same directory.
+- Exact CSVs: `.context/accounting/report-browser-{identity,foreign}-{subsidiary,all}-export.csv`.
+- Browser loader/export evidence: corresponding `-evidence.json` files. Source status and rates: `report-browser-source-and-rates.json`.
+- Verification command: `python3 .context/accounting/report-browser-verify.py`; result: four PASS cases, `csvChecked: true`, 54 accounts each. Output saved to `report-browser-verification.json`.
+
+The fixture is left foreign-configured (XTS subsidiary, XXX parent); all created company/account/rate IDs are retained for owned-fixture cleanup. No posted journals were deleted. The authenticated accounting-reports session was handed back to the parent agent for sequential workflow testing.
+
+## Environment Failure Observed
+
+During this run, laptop deep idle left Docker about three hours behind the host. Fresh auth tokens appeared expired and Chrome showed `ERR_TOO_MANY_REDIRECTS`. Restarting the runtime without resetting volumes synchronized the clocks; login and the same report flows then passed. Diagnostic captures are `.ai/scratch/e2e/accounting-reports/report-20260908-{foreign-all-error,reauth-error}.{png,txt}`. No authentication or report source changes were needed.
+
+
+## September 9 repeat: subsidiary-only access and large datasets
+
+Use a new test employee with membership and accounting permissions **only in the subsidiary**. Seed the parent and subsidiary through `seed-company`, with a custom parent CTA mapping distinct from the subsidiary's default. Verify that the employee's RLS client cannot read the parent's `accountDefault` row, then use that employee's real authenticated browser session for the report tests.
+
+This run used parent `0ddff794ec6b4b01a1b6`, child `c0803a4c7e8c4aac94b8`, group `cg_Y11kpKnKtErRFt64toa1cy`, and child-only employee `34507169-9e13-458d-81a3-03ee5bb7812d`. Source journal `je_C9wnNom8SpGvxJFKyf91ji` was posted through the real journal form, with Historical Cash debit 80 and Sales credit 80. The custom parent CTA and its group have the prefix `ACCT-E2E-20260909-REPORTS`.
+
+Identity child and All Companies reports passed with Assets 80, Net Income 80, CTA zero, and Balance Sheet zero. Foreign child and All Companies reports passed with Assets 160, Net Income 120, custom CTA 40 exactly once, Equity 160, and Balance Sheet zero. July values were zero. Click the actual Download button and compare **every CSV row and both monthly columns** against the relevant report loader. The child report succeeds while the parent's defaults remain unreadable directly through RLS.
+
+For pagination, add 1,005 zero-balance Asset leaves to the owned chart. There were 1,111 chart accounts and 1,061 balance-sheet rows. Repeat the translated child report and verify all 1,005 additional leaves appear in the loader and CSV without affecting totals. This passed with a real PostgREST hard cap of 1,000 rows, as well as the uncapped local runtime.
+
+To exercise the production-equivalent cap locally, first preserve the existing authenticator `pgrst.db_max_rows` setting. The official PostgREST 13 configuration workflow supports a database-specific role setting and `NOTIFY pgrst, 'reload config'`. Verify the cap using a fixture with more than 1,000 rows; after testing, restore the prior setting and independently verify the uncapped row count. Coordinate with other local agents before temporarily changing the shared local API cap. Never rebuild the database.
+
+Evidence and runnable fixture/verification scripts: `.context/accounting/e2e-20260909/reports-*`. Verified outcomes are in `reports-verification.json`; the complete run findings, limitations, and restoration evidence are in `reports-results.md`.
+
+## Default accounts save and validation
+
+1. In an owned new company, confirm Shipping Revenue is an active Revenue leaf beneath Revenue, distinct from Sales. Current seeds use 4050 Shipping Revenue; 4040 is Customer Payment Discounts.
+2. Open `/x/accounting/defaults`. Select a different Bank — Cash mapping and an owned alternate Shipping Revenue account beneath Revenue. Use the actual combobox option, then verify each hidden input's value. Offscreen coordinate clicks can dismiss the menu without changing the value; clicking the observed option DOM element reliably commits React state.
+3. Submit the form with native `requestSubmit(saveButton)`. Reload the page and independently verify the stored mappings match both sections.
+4. Through the actual authenticated action, submit the whole form with a valid bank change and Shipping Revenue equal to Sales. Verify the specific validation message and compare the entire defaults row before and after: no fields may change.
+5. Repeat with a Shipping Revenue account from an unrelated owned group. Verify the company-group validation message and unchanged full row.
+
+Both invalid mapping cases passed, and the valid UI save/reload passed. No existing company's mappings were changed.
+
+## Payment read paths across 1,000-row boundaries
+
+In an isolated company, create 1,005 open invoices and 1,105 effective settlements against a 2,000 document-currency invoice. A new Draft payment's actual browser loader must return all 1,005 invoices, the first invoice's remaining document amount 895, and total open document amount 10,935. This passed with the real 1,000-row API cap.
+
+Place a temporary malformed settlement with missing exact principal beyond the first page, then request the Draft payment through its authenticated HTTP route. Verify an error redirect instead of partial balances, and remove the malformed test row afterward. This late-page data-validation case passed; it does not simulate a network failure.
+
+
+## September 9 fix verification
+
+After the report fixes, repeat the inactive case with both the posting leaf and its ancestor inactive. Child and All Companies translated reports now retain all historical values: Assets 160, Net Income 120, custom parent CTA 40, Equity 160, Balance Sheet zero. With 1,005 extra chart leaves and the actual PostgREST cap of 1,000, each report returned 1,061 rows and its real two-month CSV matched every loader value. The SQL regression also closes a period and invokes the real snapshot writer after deactivation; inactive balances survive both full scans and snapshot-bounded scans.
+
+Posted payment and invoice detail histories now both display the full 1,105 applied amount under the actual cap, with the posted payment's Unapplied zero. Page-error regressions verify that a later request failure returns no partial history. When seeding invoice fixtures directly, create the `salesInvoiceShipment` companion row: the detail form requires it. The previously observed synthetic invoice render error was resolved by completing that fixture.
+
+Out-of-group selections now return HTTP 404 for balance sheet, income statement, and trial balance. The caller remains the child-only employee, and valid All Companies still resolves the parent's configured CTA.
+
+If the HTTPS local alias fails after an ERP-only restart while direct localhost works, import the same actual callback cookies into the named browser's `http://localhost:<ERP port>` origin and omit `--secure` for that local test origin. Do not change authentication/RLS or reset the database. Restore the original PostgREST cap, verify an unpaged 1,105-row read, reactivate the owned test accounts, close the browser, and delete the temporary session secret.
+
+Verified fix artifacts: `.context/accounting/e2e-20260909/fix-reports-results.md`, `fix-reports-browser-verification.json`, `fix-historical-green.log`, `fix-refund-reports-green.log` (106 SQL report cases), and `fix-reports-vitest-green.log` (83 ERP tests).
diff --git a/.ai/playbooks/accounting-posting-corrections.md b/.ai/playbooks/accounting-posting-corrections.md
new file mode 100644
index 0000000000..71b9c908b3
--- /dev/null
+++ b/.ai/playbooks/accounting-posting-corrections.md
@@ -0,0 +1,171 @@
+# Accounting posting corrections
+
+Last verified: 2026-09-09. The sales, ordinary credit-payment and discount/write-off workflows below passed on the existing local stack. Memo residual, refund, report and Rillet failures found during the expanded run were corrected and reverified; see [the correction run](../runs/2026-09-09-accounting-e2e-fixes.md).
+
+Tracking plan: [Accounting Posting Corrections](../plans/2026-09-07-accounting-posting-corrections.md).
+
+## Setup
+
+Use `/auth` with the ERP URL from `.env.local`. Select an isolated company with
+accounting enabled, group-scoped currencies, seeded accounts and sequences. Do
+not reset the database. Seed only owned fixture records, suppress outbound sync
+during fixture setup, and exercise production posting endpoints and route actions.
+
+The verified company was Accounting Corrections Local Test
+(`d6f4c9407801436387dc`). Fixture ownership and IDs are in
+`.context/accounting/browser-fixture.json` and `payment-browser-fixtures.json`.
+The authenticated `accounting-reports` browser session was reused sequentially
+after the report workflow, then switched to this company.
+
+## A. Shipping, sales posting, cash and reversals
+
+1. Open `/x/accounting/defaults`. Save and reload Shipping Revenue under Revenue (4050 on a fresh
+ company in the September 9 run; older fixtures may use 4040). The actual column is
+ `accountDefault.salesShippingRevenueAccount`.
+2. Prepare a USD-base/EUR invoice at rate 0.8 with merchandise 100, taxable add-on
+ 20, non-taxable add-on 3, line shipping 10, tax 10%, and header shipping 5.
+ The Service line must reference a valid service item. Posting through the
+ actual `post-sales-invoice` endpoint produces AR 151, Sales 123, Shipping 15,
+ and Tax Payable 13, with document gross EUR 120.80.
+3. Open `/x/sales-invoice/{invoiceId}/details` and click Payment. The new payment
+ route is `/x/payments/new`. The loader must seed EUR 120.80 and rate 0.8 from the
+ authoritative invoice, even though the link's legacy amount parameter is 151.
+ Confirm the amount input shows the EUR symbol; select Bank/Cash and Save.
+4. The draft application shows USD 151 and EUR 120.80 with FX 0. Post the payment.
+ Verify the invoice is Paid with zero balance, recorded source units 120.80,
+ base relief 151 and FX 0, and `get_ar_tie_out` variance 0.
+5. Void the payment and verify the invoice returns to Submitted with base 151
+ open. In the invoice's More options menu, select Void and confirm Void Invoice.
+ Verify both documents are Voided and every original journal account nets to
+ zero with its reversal. The AR tie-out still has zero variance.
+6. For purchasing, exercise actual receipt/invoice/void endpoints with purchase
+ UOM factor 5. The verified matching fixture created 15 inventory units, base 174
+ and document 191.40 at rate 1.1, no PPV and no duplicate cost layers. Invoice
+ void preserved receipt-owned costs and restored PO invoiced quantities to 0.
+ Direct inventory, received/direct asset and buyer IC monetary cases also passed.
+
+Evidence: `sales-http-evidence.json`, `payment-browser-cash-{posted,voided}-evidence.json`,
+`payment-browser-cash-payment-voided-evidence.json`, and
+`purchase-http-{verified,direct,ic}-evidence.json` under `.context/accounting/`.
+
+## B. Prior credit and exact document remainders
+
+1. Post an unapplied receipt of EUR 100 at rate 1. Create a EUR 50 invoice at rate 2
+ (base 25), and a separate zero-cash draft receipt at rate 1.5 for the same customer.
+2. On `/x/payments/{consumerId}`, Auto apply and Save applications. Confirm the
+ saved application uses original source rate 1 and target rate 2, document 50,
+ base 25 and gain 25. Post it; the invoice is Paid and credit availability is
+ document 50/base 50.
+3. Try to void the original source receipt. The route refuses and both payments
+ remain Posted. Void the applying payment instead; the invoice reopens and
+ the original credit is restored to document 100/base 100.
+4. For another customer, post a EUR 160.01 unapplied receipt at rate 16000.
+ Create an invoice with quantity 0.16001 × base unit price 0.0625: raw base total
+ 0.010000625, document 160.01, booked AR 0.01. Create two zero-cash draft consumers.
+5. On the first consumer, manually enter base 0.01, then Save applications. This
+ must consume document 160.00. Checkbox/Auto apply intentionally selects the
+ entire exact document balance; manual entry must not infer that intention
+ from equal rounded base values. Zero discount/write-off edits must preserve
+ the partial principal. Post it.
+6. Verify Partially Paid, document balance 0.01 and source credit 0.01, with both
+ remaining booked base amounts 0. The final consumer still lists the invoice,
+ displays USD 0.00/EUR 0.01, and offers EUR 0.01 credit.
+7. Auto apply and Save on the final consumer. Verify source 0.01, base 0 and FX 0;
+ post it. The invoice is Paid, both document remainders are 0 and tie-out variance
+ remains0. Void final and first consumers; the original invoice and source
+ document balances return to 160.01, with original carrying 0.01.
+
+Evidence: `payment-browser-normal-{posted,voided}-evidence.json`,
+`payment-browser-high-{first,final,restored}-evidence.json`, and screenshots under
+`payment-{normal-posted,source-void-refused,final-cent-available,final-cent-posted}/`
+in `.context/accounting/`. `payment-browser-assert.ts` checks actual database
+statuses, settlements, original account reversals, source carrying and AR tie-out.
+
+## C. Consolidation and CSV
+
+Follow the separately verified [report playbook](accounting-posting-corrections-reports.md).
+Identity and foreign translation each passed for subsidiary and All Companies.
+Foreign results were Cash 160, Income 120, custom CTA 40, Equity 160 and root 0.
+All 54 exported account rows matched both monthly report columns.
+
+## Automation notes and verification limits
+
+- Wait for hydration and completion of the previous action before navigating.
+ `requestSubmit()` reliably submits forms; clicking the actual button via DOM
+ works for React fetcher actions. Read server/database state after asynchronous
+ posts, rather than assuming a click completed them.
+- The local CLI sometimes lost numeric fills and returned CDP errors for raw
+ keyboard typing. A native input value setter plus bubbling `input` and blur
+ events exercised the real React amount handler without changing application
+ state directly. Scope selectors by the visible input's aria-label.
+- Laptop sleep caused Docker clock drift and auth refresh loops. Runtime restart
+ preserved volumes and resynchronized clocks. A bounded keep-awake process
+ prevented further drift. Notes/storage also timed out on the invoice page;
+ this was captured separately and did not prevent monetary route verification.
+- The September 9 run exercised live Rillet sandbox documents and its independent
+ journal report. See the current run for confirmed FX, mapping and reversal gaps.
+ Xero and QBO were not configured for live testing.
+- Direct fixed-asset invoice void reverses its GL but leaves acquisition state
+ Active. This separate lifecycle gap is recorded in the spec, outside this fix.
+
+## September 9 repeat and signed-line/discount coverage
+
+Fresh owned fixtures and database assertions are in
+`.context/accounting/e2e-20260909/`. The original-account test changed receivables,
+sales, shipping and tax defaults before voiding, proved each original account
+netted to zero, then restored the defaults.
+
+- Sales: open `/x/payments/new?customerId={customerId}&invoiceId={invoiceId}`.
+ Verify hidden `totalAmount=120.8` and `exchangeRate=0.8`; requestSubmit Save.
+ The created payment stages base 151/document 120.80. Post and verify Paid/FX 0.
+- Mixed signs: post a service line of 100 plus shipping 10 at 10% tax, a quantity −1
+ line at 25 plus shipping −2 at 10% tax, and header shipping 5. Expected base AR 96.30,
+ sales 75, shipping 13 and tax 8.30. At rate 1.2, Auto apply document 115.56; Save
+ applications and Post. Both payment and invoice void exactly by original account.
+- Customer discount/write-off: post base 1000 at EUR rate 1.1; create cash EUR 1072.50.
+ Auto apply base 975. Enter discount 20 and write-off 5, blur and verify the inputs.
+ Save applications and Post. Invoice becomes Paid; discount debits contra-revenue 20,
+ write-off debits Expense 5, and FX is 0. Void reopens base 1000 and reverses each account.
+- Prior credit and high-rate ordinary payments: repeat Workflow B. Check the row
+ before editing the applied amount; explicitly change the visible amount through
+ zero before re-entering 0.01 if it already displays 0.01. The displayed document
+ preview must be 160.00 before Save, then final Auto apply consumes 0.01.
+
+Post, Void, Auto apply, Save applications and Apply credits are React fetcher
+buttons with click handlers, not ValidatedForm submit buttons. Wait for the
+request and route revalidation before reading the database. A success toast alone
+is insufficient. Native input setters plus bubbling input/change and blur events
+were necessary when this CLI's fill command changed the DOM without committing
+React state; the real UI preview and persisted source principal were checked.
+
+Verification commands used (against owned fixtures, not safe to reuse against
+arbitrary IDs): `pnpm exec tsx .context/accounting/e2e-20260909/payments-assert.ts
+{normal-posted,normal-voided,high-first,high-final,high-restored}` and
+`customer-check.ts {sales-posted,discount-posted}`; `sales-void.ts` and
+`customer-finish.ts` checked exact reversal and AR tie-out 0.
+
+## D. Customer refund with FX
+
+1. Post an owned customer credit memo for EUR 55 at rate 1.1 (USD 50 carrying).
+2. Open `/x/payments/new?customerId={customerId}&amount=55`. The Type initially
+ reads Payment from Customer. Select Refund to Customer; the Customer selector
+ remains visible. Select Euro and enter exchange rate 1.25, then blur.
+3. Check native form values: `paymentType=Disbursement`, `supplierId` empty,
+ `customerId` selected, `currencyCode=EUR`, `exchangeRate=1.25`, `totalAmount=55`.
+ Use `requestSubmit` on Save. The created draft retains Refund to Customer.
+4. Refund memos lists the posted memo with USD 50 / EUR 55 open. Auto apply and
+ Save applications. Verify stored `targetMemoId`, source55, applied50, FXgain6.
+ The payment history links the memo and shows Unapplied EUR0.
+5. Post with the actual button. Verify cash credit44, AR debit50 and FX gain
+ credit6; AR tie-out variance0 and the memo absent from open balances.
+6. Void with the actual button. Every account nets0 with its reversal, memo
+ principal EUR55 / base50 is restored, and AR tie-out remains0. Void the owned
+ memo for cleanup. The corresponding supplier refund is covered in the
+ [purchase playbook](accounting-purchase-intercompany.md).
+
+Verified browser payment `dagpujaqu0h3tdpb7h7g`, memo `dagprm2qu0h3ob1b7h60`.
+Evidence: `.context/accounting/e2e-20260909/fix-customer-refund-{fixtures.json,posted.png,voided.png}`.
+Journal storage uses each account's natural balance: convert Revenue/Liability/
+Equity signs before checking a debit-signed total. The initial verification
+script's raw sum incorrectly counted the positive stored FX gain as a debit;
+the corrected class-aware check and the real posting balance assertion passed.
diff --git a/.ai/playbooks/accounting-purchase-intercompany.md b/.ai/playbooks/accounting-purchase-intercompany.md
new file mode 100644
index 0000000000..c9e0674b0f
--- /dev/null
+++ b/.ai/playbooks/accounting-purchase-intercompany.md
@@ -0,0 +1,110 @@
+# Accounting purchases and intercompany posting
+
+Last verified: 2026-09-09 against the existing local stack.
+
+Companion to [Accounting posting corrections](accounting-posting-corrections.md).
+This playbook caches passing purchase and intercompany workflows. Failed refund
+and fixed-asset master reversal behavior is documented separately in the run
+report; a passing GL reversal does not prove the asset master was restored.
+
+## Prerequisites
+
+Use isolated owned companies with seeded accounting defaults, currencies, fiscal
+periods and sequences. Enable accounting on the fixture companies. Create a common
+root/group with seller and buyer subsidiaries for IC; `seed-company` already
+creates an elimination entity. Discover that entity instead of assuming a manually
+created one will be selected. Install no outbound integrations on these fixtures.
+Suppress outbound sync during database fixture setup and use real posting APIs.
+
+Authenticate through `/auth`. If local HTTPS API certificate handling prevents
+Node fetches, the existing Kong HTTP port from `.env.local` can run local edge
+requests. Authenticated HTTP route testing can use a locally generated magic link,
+OTP verification and the production `/callback` action; avoid replacing the
+service-role client's auth session when doing so. These requests carry magic
+links and OTPs in cleartext, and `docker-compose.dev.yml` publishes
+`"${PORT_API}:8000"` on every host interface — so on a shared or untrusted
+network, bind it to loopback (`"127.0.0.1:${PORT_API}:8000"`) before running
+this playbook.
+
+## Direct inventory AP purchase
+
+1. Prepare a EUR invoice at rate 1.1, quantity 2 × purchase conversionFactor 5,
+ supplier unit price 55, line freight 5.5, line tax 2.2, header freight 11 and a
+ separate negative supplier G/L amount−11.
+2. Invoke `post-purchase-invoice` on the Draft. Verify 10 inventory units, signed
+ AP 107 base /117.70 EUR. Header freight is allocated proportionally across signed
+ line totals: inventory 118.03093, negative expense−11.03093, net 107.
+3. Change the fixture's payables default. Create/post a EUR 117.70 supplier
+ Disbursement at rate 1.1 against this invoice. Verify original AP 107 relieved,
+ invoice Paid, source principal 117.70 and FX 0.
+4. Void payment; invoice returns Open with 107 base. Void invoice; group every
+ original/reversal journal by account and verify net 0. Owned item/cost layers
+ net 0. `get_ap_tie_out` variance must remain 0.
+
+## Receipt-owned costs and purchase units
+
+1. Create the PO with actual `insertPurchaseOrder` service/API; never insert the
+ PO header directly. Add two lines with purchase quantities 2 and 1, factor 5,
+ unit price 55, line shipping 5.5, supplier tax 2.2, rate 1.1; header freight 11.
+2. Call actual `finalizePurchaseOrder`, then `create` with
+ `type: receiptFromPurchaseOrder`. The create endpoint returns `{id}` without
+ a `success` field. Post that receipt.
+3. Verify 15 inventory units and 174 base cost /191.40 EUR. Create/post a matching
+ purchase invoice; verify zero PPV and no duplicate invoice-owned cost/item rows.
+4. Void invoice. Receipt-owned inventory/cost records must be unchanged, PO
+ `quantityInvoiced` must be 0 in purchase units, and invoice journals must net 0.
+
+## Supplier applications
+
+1. Prepare invoice 100 and draft supplier Disbursement 90. Post the real
+ `/x/payments/{id}/applications/set` action with applied 90, discount 5, writeoff 5,
+ source/target rate 1 and exact source 90. Verify the saved settlement, post, and
+ verify Paid, cash−90, supplier discount expense−5, writeoff revenue+5.
+2. Prepare a posted supplier Debit memo 30, invoice 50, and draft Disbursement 0.
+ Submit `/x/payments/{id}/credits/set` with memoId, invoiceId, amount 30 and
+ sourceAmount 30. Post; invoice becomes Partially Paid with 20 remaining.
+3. Source memo void must be refused while consumed. Void consumer and verify
+ invoice 50 restored, then void memo and invoice. Final AP tie-out variance 0.
+
+## Actual IC posting, matching and elimination
+
+1. Seller acquires 3 tracked units at 60 each using real purchase posting. Seller
+ invoices the IC customer `3 × 100.005`; buyer purchases the same trade from
+ its IC supplier. Both actual `intercompanyTransaction.amount` values must be
+ exactly 300.015 (matching uses internal precision).
+2. Run `matchIntercompanyTransactions` for the owned group. Verify reciprocal
+ source/target journal anchors and Matched status. Run `generateEliminationEntries`.
+ For BOTH the IC Balance and IC Revenue journals, assert total debits equal
+ total credits explicitly — matching account-class signs shows the entries
+ point the right way, it does not prove the journal balances, which is the
+ invariant `postJournalEntry` enforces before posting. Then verify
+ revenue 300.015, COGS 180 and buyer inventory margin 120.015 are eliminated.
+3. Sell 1.5 of the buyer's3 units externally through real sales posting. Explicitly
+ regenerate eliminations; all previous entries are reversed, remaining deferred
+ profit is 60.0075. A normal rerun creates 0 entries; repeated regeneration changes
+ no net account balance.
+4. Repeat with two merchandise lines 100/50, line shipping 5/2, tax percent 0.1,
+ header shipping 8. Supplier tax amounts are 10.5/5.2. Verify matching key 157,
+ both controls 180.70, seller captured revenue 165, external tax 15.70 excluded,
+ buyer capitalization 180.70 and all lines included in balanced eliminations.
+5. Repeat a100 transfer with seller group cost 60 and a buyer Fixed Asset line.
+ Actual purchase activates 100 acquisition and captures the buyer asset account.
+ Elimination removes 40 margin from that account. The engine creates one shared
+ balance journal per pair and one revenue journal per trade; retries add no net
+ duplicates.
+
+## Evidence
+
+The 2026-09-09 isolated fixture IDs, exact HTTP results, original/reversal GL rows,
+matching/capture IDs and final assertions are in
+`.context/accounting/e2e-20260909/purchase-ic-results.md` and its linked JSON files.
+
+## Payment fixes verified 2026-09-09
+
+The prior supplier refund and final-cent memo failures are fixed. Reuse `.context/accounting/e2e-20260909/fix-supplier-live.ts` as a reference for new uniquely named fixtures; the recorded fixtures are already voided and must not be replayed as fresh documents.
+
+- Published `applyCreditsToInvoices` accepts omitted `createdBy` and injects the API-key actor. A EUR 160.01 memo/invoice at rate 16000 posts source 160/base.01 and then source.01/base 0 successfully.
+- Published `replaceInvoiceSettlements` accepts supplier Receipt refunds with `targetMemoId`. Refund EUR 22 at rate 1.25 against a EUR 55 memo at 1.1 posts AP 20, bank 17.6, FX loss 2.4 and leaves exact memo principal 33/base 30. Final refund 33 clears the memo; every stage has AP tie-out variance 0.
+- Memo void is blocked while posted refunds consume it. Void the refund payments, then the memo. Exact reversal restores the books.
+- An unallocated supplier Receipt EUR 55 at 1.1 appears as AP+50 in both aging and tie-out; void restores 0.
+- Pure/transaction verification: post-payment + post-memo Deno directories 69/69; ERP settlement service 55/55. Evidence and IDs: `.context/accounting/e2e-20260909/fix-payments-results.md` and `fix-supplier-live-evidence.json`.
diff --git a/.ai/playbooks/rillet-provider-accounting.md b/.ai/playbooks/rillet-provider-accounting.md
new file mode 100644
index 0000000000..260b8ebf7f
--- /dev/null
+++ b/.ai/playbooks/rillet-provider-accounting.md
@@ -0,0 +1,49 @@
+# Rillet outbound accounting verification
+
+Last tested: 2026-09-09, including the Rillet accounting corrections.
+Routes: `/x/settings/integrations/rillet`; actual provider/syncer/API surface below.
+
+## Prerequisites
+
+- Resolve configured credentials using Carbon's provider integration path and confirm **sandbox**, subsidiary, base currency, and chart without printing vaulted keys.
+- Use fresh uniquely named owned documents with no customer email addresses; verify automatic invoice sending/reminders are false. Lifecycle fixtures are consumed by void testing.
+- Map source sales/shipping/expense/control accounts to provider accounts. Cash must also link to a **Rillet bank account**, checked with `GET /bank-accounts`. A GL-only account mapping does not establish that bank relationship.
+- The test skill/auth workflow applies to browser setup. Backend fixtures and real APIs are appropriate when authorized. Always preserve all source/remote IDs.
+- Direct sales invoice fixtures must insert `salesInvoiceShipment`, including a zero-shipping row; the actual posting/void endpoint expects it. Seed original posted journals with the original shipping/AP accounts, which may differ from current defaults.
+
+## Verified successful flows
+
+### Native invoice amounts, fixed FX, and revenue
+
+Create/post a USD invoice with twenty lines at 1.99 and 8.25% tax. Use the actual configured provider and `SyncFactory`, preferably through `reconcileEntities` and `drainSyncOperations`. Independently fetch the remote document: net 39.80, tax 3.28, gross 43.08. In `/reports/journal-entries`, require AR +43.08, tax liability −3.28, revenue −39.80, and Deferred Revenue net 0.
+
+Use merchandise 100, line shipping 10, header shipping 5, and 10% tax on merchandise+line shipping. Require gross 126, native tax 11, shipping 15 across two components; GL revenue −100, original shipping revenue −15, tax −11, AR +126. The tested original shipping account mapped 40120 and differed from the current unmapped shipping default. Current defaults must not replace original posted shipping provenance.
+
+Invoices now use `REVENUE_RECOGNITION_ONLY` with explicit same-day revenue periods. Check the entered posting date (including when issue date differs), fixed exchange-rate date, and recognition date. Carbon stores foreign units per base unit; Rillet receives document→subsidiary and the inverse rate. For base USD 100, EUR rates 0.8/1.2/1 must produce document EUR 80/120/100 and AR/revenue base USD 100. JPY 160 at rate 160 must report base USD 1; BHD 0.462 at rate 0.376 must report base USD 1.23. Independently verify returned rates and ledger amounts; successful HTTP alone is insufficient.
+
+### Bills and payment fanout
+
+Push a bill with posted cost 100 and AP 100. Require expense +100/AP −100, and no AP control line among native bill costs. Repeat EUR rates 0.8/1.2/1: source base 100, document 80/120/100, remote base 100. The tested original AP account differed from today's default.
+
+Post a USD customer receipt 169.08 applied to the 43.08 and 126 invoices, plus a USD supplier disbursement 100 against the bill. Use the actual `post-payment` endpoint and a bank-linked cash account. Reconcile/drain and require Completed operations, exactly two AR native payments and one AP native payment, correct amounts, and PAID documents. Repeat reconciliation; require no new operations or native payments.
+
+### Carbon-originated void round trips
+
+Void the two local payments through `post-payment`, then reconcile/drain. All three native payments must delete and invoices/bill return UNPAID. Carbon's own GL is REVERSED, never deleted: the original cash entries and their `VOID ...` reversal must both remain auditable, with the reported cash balance netting to zero. Check all single/fanout mapping keys retain `origin: carbon` and `voided: true`. A pulled-origin mapping is never echoed back as a deletion. Repeat reconciliation and require no new operation; a remote 204 followed by failed local persistence is safe to retry because only DELETE 404 is accepted as already absent.
+
+Void local invoices/bills through their actual posting endpoints and reconcile/drain after payment reversal. Native GET must return 404. The original AR/AP, tax, shipping, revenue-recognition and cash entries must each net to zero in the reporting GL against their reversal — the original rows stay, because `reverseJournalEntry` posts a reversing entry rather than deleting a posted journal. Retained document mappings must carry `voided: true`. Repeat reconciliation and require no new work. A native deletion rejected due to a remaining/cleared payment must surface a failed operation; bounded automatic re-drive handles payment/document drain ordering.
+
+### Journal reversal
+
+Push an owned inventory journal: inventory debit 100 and adjustment expense credit 100. Reverse locally and push the original ID with `:reversal`. Independently sum original/reversal by provider account; every account must net 0. Replays preserve remote IDs. This flow was verified before the provider corrections and its focused regressions remain green.
+
+## Coverage boundaries
+
+- Outbound native documents, reconciliation/drain, and Carbon-originated USD payment voids were live verified. Full inbound webhook delivery was not verified.
+- Xero/QBO were not configured and were not live tested. Their native-void routing remains unchanged.
+- Foreign-currency payment push remains an existing explicit unsupported case; fixed FX proof above applies to invoices and bills.
+- Shared shipping/cash configuration gaps were intentionally preserved. Use mapped owned accounts for these tests.
+
+## Evidence
+
+Workspace-local report: `.context/accounting/e2e-20260909/fix-rillet-results.md`; JSON/API/GL evidence and fresh fixture IDs are in that directory. The scripts must not be blindly rerun after their local and remote documents have been voided. No browser session was opened for this backend verification.
diff --git a/.ai/playbooks/void-confirmation.md b/.ai/playbooks/void-confirmation.md
new file mode 100644
index 0000000000..8da6c2e278
--- /dev/null
+++ b/.ai/playbooks/void-confirmation.md
@@ -0,0 +1,62 @@
+# Void confirmation dialogs
+
+## Scope
+
+Six user-facing Void actions exist: payments, credit/debit memos, sales invoices,
+purchase invoices, receipts, and shipments. Payments and memos use ConfirmDelete
+with a Void title/button; the other four use dedicated Void modals.
+
+## Setup
+
+Use the test and auth skills with ERP_URL from `.env.local`, then select an
+isolated local company with accounting enabled. Prepare a fresh posted payment
+and a separate unapplied posted credit/debit memo owned by the test. Never void
+an existing customer record just to test confirmation. Do not reset the database.
+The September 9 fixtures/scripts and before/after evidence are under
+`.context/void-confirmation/` (gitignored).
+
+## Payment and memo checks
+
+Repeat on `/x/payments/{paymentId}` and `/x/credits/{memoId}`:
+
+1. Record the Posted status and the document's journal lines from the database.
+2. Click the header's Void button. A modal must appear naming the document and
+ explaining that accounting entries and applications will be reversed.
+ Confirm Cancel has focus; the header action must be `type="button"`.
+3. Click Cancel. Verify the modal disappears and status/journal lines are unchanged.
+4. Reopen and press Escape. Verify the same. Reopen and use the Close button;
+ verify the same. No request to the document's `/void` action is allowed.
+5. Reopen and confirm using the modal's destructive Void submit button. Verify
+ loading disables that button. After completion, the modal closes, the page
+ shows Voided, and the header no longer offers Void.
+6. Verify the persisted status is Voided, with exactly one reversal and a zero
+ net balance on every original journal account.
+
+Use real browser clicks. If this CLI's click does not invoke a React handler,
+DOM `.click()` on the actual button or `button.form.requestSubmit(button)` on the
+confirmation exercises the same application handler. Wrap evals in IIFEs to avoid
+persistent top-level binding collisions. Await each browser command before the
+next; do not navigate while a dialog test or submission is still running.
+
+## Existing invoice/inventory checks
+
+On posted sales/purchase invoices and receipts/shipments, the header/menu Void
+item must only open its dedicated modal. The form that posts to `/void` must
+remain inside that modal. Existing permission/status checks still govern whether
+Void is offered.
+
+## Last verification: 2026-09-09
+
+Both payment and memo passed: confirmation title/consequences, Cancel initially
+focused, Cancel and Escape leaving exact persisted state/journals unchanged,
+confirm disabling during loading and ignoring a second click, dialog closing and
+Voided status after completion. Payment Close dismissal also preserved state.
+Both records had exactly one reversal per original account, netting to zero.
+Before the fix, fresh baseline records reproduced the immediate one-click void
+and failed the browser assertion that a dialog must appear.
+
+Checks: 29 existing payment form/composer tests, scoped ERP typecheck, scoped
+Biome, and the missing-translation check passed. The four existing dedicated
+invoice/inventory modal call sites were verified by source audit. The glossary
+checker has existing findings plus eight grammatical-form matches on the new
+translations; see the local localization report for the reviewed delta.
diff --git a/.ai/research/accounting-posting-corrections.md b/.ai/research/accounting-posting-corrections.md
new file mode 100644
index 0000000000..6fe5dd87e4
--- /dev/null
+++ b/.ai/research/accounting-posting-corrections.md
@@ -0,0 +1,93 @@
+# Accounting Posting Corrections Research: Best Practices Survey
+
+## Summary
+
+Research refreshed on 2026-09-07 for the selected fixes: separate tax and customer shipping from product-sales postings, normalize transaction FX, and correct consolidation calculations. This is a focused update to [shipping/tax research](shipping-tax-accounting.md), [FX research](exchange-rate-competitor-practice.md), and [financial reporting research](financial-reporting.md). Their older Carbon inventories are not current implementation evidence. Current code was checked at `0a9aef2444`.
+
+## Competitors Surveyed
+
+- **SAP S/4HANA** — tax account assignment, currency quotation, consolidation and correction of posted documents.
+- **Oracle NetSuite** — shipping income accounts, tax controls, transaction/consolidation rates, earnings presentation and reversals.
+- **Xero and QuickBooks Online** — adapter-specific rate conventions affecting Carbon's existing integrations.
+
+## Key Consensus Patterns
+
+### 1. Separate tax collected from sales consideration
+
+- **SAP:** input and output tax have separate accounting treatment; non-deductible tax may remain in asset/expense costs. [Input/output tax](https://help.sap.com/docs/SAP_S4HANA_ON-PREMISE/8fbeed5f2046489696a50ac7fd76f9c6/2847d953189a424de10000000a174cb4.html).
+- **NetSuite:** tax control accounts distinguish sales-tax liability from purchase-tax assets. [Tax control accounts](https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_3726875412.html).
+- **Rationale:** splitting collected sales tax is necessary even without a new tax-determination subsystem. Recoverability must be known before changing purchase-tax capitalization.
+
+### 2. Customer shipping charges and carrier expenses are different amounts
+
+- **NetSuite:** shipping items allocate customer shipping charges to an income account; handling can have its own account. [Shipping items](https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_N1258840.html), [Shipping account selection](https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_N1259213.html).
+- **SAP:** the researched tax/account-assignment documentation supports separating underlying consideration from tax; it does not settle a single mandatory shipping account presentation for Carbon.
+- **Rationale:** a separate Shipping Income account cleans up product-sales reporting. A customer charge is not evidence of the actual carrier expense. Do not create a freight-expense accrual from a billed-charge field.
+
+### 3. FX arithmetic follows the stored quotation
+
+- **SAP:** direct and indirect quotation represent inverse contracts. [Quotation definitions](https://help.sap.com/docs/SAP_ERP/ae5c71ff3b1f490fb7f3b1f17bb2c7ee/b7c38d5377a0ec23e10000000a174cb4.html).
+- **NetSuite:** its rate-list contract uses source amount multiplied by the rate to obtain base. [Rate-list formula](https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/subsect_1527609411.html).
+- **Carbon inference:** preserve Carbon's foreign-units-per-base-unit contract: document-to-base divides, base-to-document multiplies, and already-base fields receive no second conversion. A provider's different quotation requires inversion at that adapter boundary.
+
+### 4. CTA captures translation differences, not source-accounting errors
+
+- **NetSuite:** assets/liabilities generally use current rates, income/expenses average rates, and equity historical rates; CTA reconciles the resulting translated statements. [CTA overview](https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_N2124272.html).
+- **SAP:** translation methods and difference handling distinguish balances translated under different rules. [Translation differences](https://help.sap.com/docs/SAP_ERP_SPV/f1f80b03e15440c0b3cf5e655a6938d8/8a4cd353c6244308e10000000a174cb4.html).
+- **Carbon inference:** natural-balance Expense must contribute to the debit side. A balanced Cash 80 / Revenue 100 / Expense 20 source at all rates 1 has CTA 0. The current function returns −40.
+
+### 5. Earnings presentation has an explicit fiscal boundary
+
+- **NetSuite:** prior-fiscal-year earnings appear in retained earnings; current-year earnings appear in net income. [Year-end closing](https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_N1457773.html).
+- **SAP:** standard translation can preserve opening group-currency values and apply period-specific translation methods. [Translation methods](https://help.sap.com/docs/PRODUCT_ID/90c07e91c7a64f328be3fd6b48955b13/1eac9a4436204081956213fb2d265094.html).
+- **Rationale:** cumulative balances, period activity and fiscal-year income must not be substituted for one another. This informs regression boundaries; a full retained-earnings/history subsystem is broader than fixing the demonstrated CTA sign error.
+
+### 6. Preserve posted facts and reverse their original values
+
+- **SAP:** posted monetary/account fields are protected; correction flows can reverse original postings and repost under corrected mappings. [Protected posted fields](https://help.sap.com/docs/SAP_S4HANA_ON-PREMISE/3cb1182b4a184bdd93f8d62e3f1f0741/6350d7531a4d424de10000000a174cb4.html), [Reversal/reposting](https://help.sap.com/docs/SAP_S4HANA_ONPREMISE/26c2d5e366bc44c1a98f2a9212a0c49d/5e6dfc7b93124d8fbcb745a7aaeb7701.html).
+- **NetSuite:** reversal entries retain the original exchange rate and a relationship to the original journal. [Journal reversal](https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/bridgehead_N1469193.html).
+- **Rationale:** a new posting formula does not authorize rewriting posted history. Reversals invert actual booked lines. Open legacy documents require an explicit transition design so normalized settlements do not strand old control balances.
+
+## Answers to Research Questions
+
+1. **Where should invoice tax post?** Collected sales tax to the configured liability account. Purchase tax recovery depends on classification; current Carbon has no recoverability model.
+2. **Where should customer shipping charges post?** A separate configured shipping-income account is the grounded default; carrier cost needs its own actual-cost source.
+3. **Which FX direction is correct?** The direction defined by each stored rate. Carbon uses foreign/base, so divide only document-denominated values; leave base fields unchanged.
+4. **What should CTA reconcile?** Differences introduced by translation rules after the source ledger balances under the correct account signs.
+5. **How should earnings periods work?** Distinguish current activity, cumulative balance and fiscal-year earnings; retain the existing scope boundary while testing the correction.
+6. **How should existing erroneous postings be corrected?** Preserve them and use linked corrections/reversals with original values and period controls. Exact rollout/remediation coverage is a product/accounting decision.
+
+## Competitor-Specific Details
+
+### SAP
+
+Direct versus indirect quotation is a configurable convention. Carbon should borrow the explicitness, not copy an arithmetic operator from unrelated SAP configuration.
+
+### NetSuite
+
+Shipping-account assignment is an income-account setting. Its documented transaction-rate formula is opposite Carbon's quotation, so adapter conversions need tests.
+
+### Existing Carbon providers
+
+- Xero's [multicurrency documentation](https://developer.xero.com/documentation/best-practices/data-integrity/multicurrency/) is the source for its transaction-rate contract.
+- QuickBooks' [ExchangeRate property documentation](https://static.developer.intuit.com/sdkdocs/qbv3doc/ippdotnetdevkitv3/html/0b5f8961-f32e-e396-3a39-7b3e241434e8.htm) specifies home currency per foreign unit, requiring the reciprocal of Carbon's rate.
+- Unsupported provider FX paths must remain explicitly unsupported; do not assume another provider's rate convention.
+- Rillet's current [Create a bill schema](https://docs.api.rillet.com/reference/create-a-bill-1) defines `exchange_rate` as an object with `base`, `target`, string `rate`, and `date`. Carbon currently sends a scalar from its bill adapter. The adapter needs a schema-valid, explicitly directed pair and a contract fixture; copying the scalar rate from the Xero adapter is insufficient. The schema establishes the object shape; currency-direction verification must accompany the adapter change.
+- Rillet's [AR_ONLY invoice schema](https://docs.api.rillet.com/reference/create-an-invoice-1.md) uses product-backed lines, native header/item tax, and optional line revenue account metadata; its create request does not expose `exchange_rate`. Keep the current AR_ONLY scope and distinguish document-currency correctness from provider-owned base translation. Its [product schema](https://docs.api.rillet.com/reference/create-a-product-1.md) supports the ONE_TIME shipping helper and revenue account mapping.
+- QuickBooks' existing item-based invoice path needs a Service item whose [IncomeAccountRef](https://static.developer.intuit.com/sdkdocs/qbv3doc/ippdotnetdevkitv3/html/e53f8d57-d526-2cee-9c6b-03359cfaae37.htm) resolves to Shipping Revenue. [Native tax detail](https://static.developer.intuit.com/sdkdocs/qbv3doc/ippdotnetdevkitv3/html/7328bab2-a9ed-621e-41fa-188e45aaac65.htm) and [rate membership/percentage rules](https://static.developer.intuit.com/sdkdocs/qbv3doc/ippdotnetdevkitv3/html/9a4b9306-4684-179c-4b74-3896047aa53b.htm) require genuine remote tax references. Mapping a uniquely compatible existing sales tax code is a Carbon implementation choice; ambiguous or unsupported tax configuration must produce a preflight warning rather than tax-as-revenue or a fabricated ID.
+
+## Recommended Approach for Carbon
+
+1. Use a named base-currency sales breakdown for goods/add-ons, billed freight and tax; route each separately.
+2. Preserve current tax bases and purchase-tax capitalization during this correction; avoid introducing new tax-determination policy.
+3. Normalize invoice, receipt, payment, memo, settlement, tie-out, UI and provider boundaries as one coordinated contract.
+4. Correct CTA signs and account-id resolution through actual report call sites, with same-currency and mixed-rate tests.
+5. Follow the user's explicit adoption assumption: accounting has no users yet. Correct the formulas directly without legacy-version or historical-remediation tooling. Preserve normal reversal correctness for future postings; do not interpret this assumption as requiring deletion of existing operational data.
+
+## Carbon Scope Resolution
+
+On 2026-09-07 the user confirmed a separate shipping-revenue default column, a Shipping Revenue account under Revenue, and backfilled company defaults. They subsequently resolved the history question with: “we can assume that no one is use accounting yet and just fix it.” General competitor practices for mature ledgers above remain useful context, but a legacy accounting transition is unnecessary for this scoped implementation. The finalized design is [Accounting Posting Corrections](../specs/2026-09-07-accounting-posting-corrections.md).
+
+## Sources
+
+Primary source URLs are attached directly to the claims above. Existing repository research is linked in Summary for historical context; current source code takes precedence over its older Carbon observations.
diff --git a/.ai/reviews/2026-09-08-accounting-review.md b/.ai/reviews/2026-09-08-accounting-review.md
new file mode 100644
index 0000000000..2e2ffbe481
--- /dev/null
+++ b/.ai/reviews/2026-09-08-accounting-review.md
@@ -0,0 +1,68 @@
+# Accounting PR review resolution
+
+PR: https://github.com/crbnos/carbon/pull/1599 · CodeRabbit review: 5149438993 · Base: origin/main
+
+The review contains six inline findings and 34 additional body findings. Every suggestion was checked against source and the approved exact-document-principal contract. The original nuclear review's eight implementation blockers are also addressed by the same correction pass.
+
+## Suggestions not applied
+
+| Finding | Evidence and disposition |
+| --- | --- |
+| 3964376569 — absolute original controls | Rejected. Actual AR and AP posting tests show +100/−10 originals must carry 90; absolute sums produce 110 and fictitiousFX 20. Signed amounts are correct. Original-role selection excludes `VOID:` reversals and now includes intercompany controls. |
+| f1e4f000272bb8e20b387272 — reject zero rounded memo base | Rejected. Positive document principal may legitimately have zero rounded carrying base at high rates. The approved contract explicitly preserves it; conversion, composer and transaction regressions cover the final document minor unit. Restoring a fixed base threshold would reintroduce the bug. |
+| 3964376574 — hand-add `nullable: true` to generated Swagger | Not applicable to the proposed patch. The generator emits Swagger2.0; `nullable` is an OpenAPI3 keyword. The property is absent from `required`, its schema-derived description explains NULL, and regenerated database types already express `string | null`. Optional omission does not fully express nullable responses: this is an inherited Swagger2 generator limitation, not proof that the API schema fully models nullability. A general OpenAPI format/nullability migration is outside these accounting corrections; no generated file was hand-edited. See [OpenAPI data types](https://swagger.io/docs/specification/v3_0/data-models/data-types/). |
+
+## Confirmed code corrections
+
+| Findings | Resolution |
+| --- | --- |
+| 3964376617 | Block consumed memo void under the same memo lock used by payment posting; reverse consumer first. Actual database red→green proves state/journal preservation and voided/Draft consumer behavior. |
+| 3964376632 | Remove transaction commands from both runner-managed migrations and the stale planning-only preamble; reapply both inside one explicit local transaction. |
+| 3964376646 | Exclude an entire memo with unknown effective consumed principal from open reports rather than fabricate an amount; preserve historical cutoff behavior. |
+| 3964376653 | Evict rejected QBO tax-catalog promises; successful results stay cached. |
+| fbe0d40c67975a6bcdaad6b5 | Guard missing inbound QBO AccountRef values without discarding valid remaining lines. |
+| 5fba2f61b8386f675bc17a62 | Surface the specific invalid-account mapping reason; defaults update is now one atomic write. |
+| db120fa1c4e0be4c6945e0ac | Round merged source principal in payment history, including0.1+0.2 regression. |
+| da7c4995cf1dcb3130d58092 | Empty state, footer and Auto apply use the actual filtered rows. |
+| ae0f05254d816a6ea1a68c03 | Derive costing tolerance from the shared storage scale. |
+
+## Test and documentation corrections
+
+| Findings | Resolution |
+| --- | --- |
+| 3c626ca8c2fbc566e19f7ae9 | Replace audit workstation links with repository-relative paths and line anchors. |
+| 91c762fb1f2a30a287c18ad3 | Correct stale QBO rate/amount comments. |
+| f405311f2bae935b5fc1903e | Diagnose absent local database environment before URL parsing. |
+| c6ef98b3b2672adcf835f170 | Document all deliberate pure edge-shared utility exports; typechecks and ERP production build verify consumer integration. |
+| c7f5816baa88bb1099cabc03 | Keep settlement constraints in the posting-corrections suite; shipping suite owns only backfill/schema behavior. |
+| a52d17dac257d5da125de7d2 | Use private P9001 rollback sentinels so real data exceptions fail tests. |
+| 85ba658d52ba21d5ae138e14, 547d5ba6f453b5e86ca0559a | Move purchase imports and payment sql import to module scope. |
+| ffd8973dc020f76c8c5c5e62 | Remove tautological void arithmetic. Keep actual posting amount/class balance assertions and actual transaction reversal tests; do not assert raw natural-balance amounts sum to zero. |
+| 1813ebb0eb02c683cc0b782b | Assert captured tax-preflight error outside catch so test assertion failures keep their original diagnostic. |
+| ba9322a2dc4d8d58ad8e56c2 | Add AR/AP multiple-application control-relief tests with distinct target rates and both discount/write-off components. |
+
+## Translation findings
+
+The following findings concern existing ERP catalog entries: payment credits versus ledger credit-side postings, FX gain/loss amounts versus exchange rates, shipping fees billed to customers, and payment allocation wording. Corrections preserve interpolation placeholders and existing glossary context.
+
+- ru: 7c30c2aa8fb5ccaf93a02660
+- tr: e9e359b39cba6f90a01ff75a
+- zh: f8d04513831c380ec73be3cf
+- de: e728fd7345c4e40f75f65f2a
+- es: eff660e22867607cea45da3e, 9a53d72300ad16622164bd0a
+- hi: 3593041ebfacbfa7fbacf53c, 948f60c52ccd8abc79ede39f
+- it: af571f7ae773e5cb490dba2a, 418f6c9f2c4886a2eb8f00ed
+- ja: b5af53bbce73660d465e75c4
+- ko: 9c7696bef38ae0a3882d2e11, 8f2e8ed800b61e54038dd683
+- pl: b89ded439c738afb78486f20, 55909a2216821c62a0f4cccb, fe4450c455c7688a28425a2c
+- pt: f9ea9e09ae2d06aa85980c85
+
+## Nuclear review corrections
+
+Signed controls, original shipping/AP account provenance, supported Xero monetary lines, complete invoice/report reads, exact manual memo principal, authorized root CTA access, shared balance/source rules, and atomic defaults writes have focused regressions. Historical inactive chart leaves and ancestors remain included. Account roles come from an exhaustive original journal vocabulary; transport queries retain company/group/source/status scopes.
+
+The safe test launcher is tracked at `scripts/run-local-accounting-check.ts`. Run it from the repository root with an existing local database; it loads local environment without printing credentials and refuses non-local URLs. It never creates or resets a database. Reproduction commands and final gate outcomes are in [the correction plan](../plans/2026-09-08-accounting-review-corrections.md) and [run log](../runs/2026-09-08-accounting-review-corrections.md).
+
+## Remaining evidence boundary
+
+Provider tests exercise real adapter/query/serialization paths with mocked external transport. No live provider writes were made. Independent Xero returned-ledger acceptance and Rillet rate-direction/base-ledger behavior require connected-provider evidence; no claim of that acceptance is made. Existing direct G/L descriptions may collide with original role labels; AP reconciliation refuses an inconsistent replay rather than guessing. France/e-invoicing and historical cutover machinery remain outside the approved scope.
diff --git a/.ai/reviews/2026-09-09-accounting-nuclear-review.md b/.ai/reviews/2026-09-09-accounting-nuclear-review.md
new file mode 100644
index 0000000000..6d16167e80
--- /dev/null
+++ b/.ai/reviews/2026-09-09-accounting-nuclear-review.md
@@ -0,0 +1,66 @@
+# Accounting PR nuclear self-review
+
+PR: https://github.com/crbnos/carbon/pull/1599 · Branch: `assess-issue-against-code` · Base: `origin/main`
+
+Second review pass, run in thermo-nuclear mode after the CodeRabbit round recorded in
+[2026-09-08-accounting-review.md](2026-09-08-accounting-review.md). Eight cluster reviewers read
+the full branch diff (142 files, ~22.7k insertions); every finding below was re-verified against
+source before being accepted. Fixes are tracked in
+[the correction plan](../plans/2026-09-09-accounting-nuclear-review-fixes.md).
+
+## Confirmed defects, fixed in this pass
+
+| # | Defect | Evidence |
+|---|---|---|
+| 1 | `reconcileDocument` concentrated the whole document rounding residual on one component, so that component's tax no longer matched its own `taxPercent`. QBO's `tax = net × percent` preflight then refused the invoice with a message blaming the customer's QuickBooks configuration. | 20 × $1.99 @ 8.25% → one line got $0.24 tax on $1.99 net (12.06% vs a stated 8.25%). Randomised sweep: 1.6% of invoices blocked; some produced a negative tax on positive revenue, which Xero accepts and posts. Fixed with largest-remainder allocation (`distributeRoundingResidual`). |
+| 2 | The two halves of an intercompany trade rounded at different scales — seller at settlement precision, buyer at internal `SCALE` — while `generate_intercompany_matches` pairs them on exact NUMERIC equality. | 3 × 100.005 stored 300.02 vs 300.015 → permanently `Unmatched`, eliminations never run. Regression introduced by this branch; the merge base had both at `SCALE`. |
+| 3 | Refund applications (Disbursement→customer, Receipt→supplier) were refused outright, though the schema, the composer and `payments.mdx:14` all support them. | `cashIn !== isAR` threw before any application was inspected. The merge base explicitly decoupled the two axes "so refunds work". Restored per the user's decision. |
+| 4 | A float tie between the stored `convertedUnitPrice` mirror and the converted extension made ~0.5% of FX invoices permanently unsyncable on all three providers. | `qty 2, unitPrice 2.81, rate 0.9137`. Now derives the unit price from the reconciled net, and still refuses when no representable price reproduces it. |
+| 5 | Rillet serialised money at a hard-coded 2 decimals on the payment and item paths. | JPY payment → `"1000.00"`; BHD lost its third decimal. `toRilletMoney`'s `decimalPlaces = 2` default removed. |
+| 6 | The on-account credit control description was built independently in two files, with a silent fallback to today's default control account on any drift. | A credit booked to intercompany receivables would be drawn against regular AR — original stays credited, default goes negative, no error. Centralised in `shared/accounting-posting.ts`. |
+| 7 | The AR/AP tie-out and aging disagreed on party-less payments, so the tie-out reported a permanent non-zero variance — the one thing it exists to prove. | Tie-out had no `customerId`/`supplierId` predicate; aging did. |
+| 8 | `fxGainLossAmount` became plain-nullable and is summed without `COALESCE` at six sites. | One explicitly-null row erased that settlement's principal from both tie-out and aging. `SET NOT NULL` added; regenerated types are now non-nullable. |
+
+## Also fixed
+
+Dead `updateDefaultBalanceSheetAccounts` (zero callers, unvalidated partial write) and
+`updateDefaultIncomeAccounts` (test-only) — both still reachable as MCP `WRITE` tools, i.e. the
+half-save path this branch set out to eliminate. Dead `getSettledInvoiceStatus` and its two
+baselined raw-rounding violations. 21 discarded-conversion validation sites replaced with named
+`assertExchangeRate` / `assertCurrencyDecimals`. A tautological defaults test whose fixture
+short-circuited before the write. Stale `payments.mdx` (settlement field table, a factually wrong
+CHECK sentence, the FX-plug sentence), `accounting.mdx` (shipping revenue), a missing glossary
+term, and three unsupported `packages/utils/AGENTS.md` claims. Unrelated regeneration churn in
+`events.generated.ts` reverted.
+
+## Checked and cleared
+
+The removal of `× invoiceExchangeRate` from sales posting is **correct**, though two independent
+reviewers flagged it as a suspected bug. `convertedUnitPrice = unitPrice * exchangeRate`
+(`20250507143421_sales-invoice.sql:152`) and `balance = amount_document / exchangeRate`
+(`…030026.sql:67`) together prove `unitPrice` is base and `exchangeRate` is foreign-per-base; the
+merge base had it backwards. A `COMMENT ON COLUMN` on `salesInvoiceLine.unitPrice`, mirroring the
+ones this branch added for `payment.totalAmount` and `memo.amount`, would settle it permanently.
+
+## Open — not addressed in this pass
+
+**The highest-leverage item: CI runs almost none of this branch's evidence.** `apps/erp` and
+`packages/database` have no `test` script, so `turbo run test` skips both, and there is no Deno
+job in `.github/workflows/`. Roughly 7,400 of the ~10,900 new test lines are unenforced. The
+DB-backed regressions additionally fail hard rather than skip without `SUPABASE_DB_URL`.
+
+Also open: the review's full Risks section (invoice-poster TOCTOU and row locks, purchase-side
+fixed-asset writes outside the Kysely transaction, payment-UI stale `rows` state and raw engine
+errors shown to users, `new.tsx` loader/action asymmetry, `getCompanyHasOpenCredits` regression,
+unbounded `FOR UPDATE`, Xero's explicit `CurrencyRate: 1` reversal and 3-decimal refusal, inbound
+Xero `taxPercent` 100×, two questionable new MCP tools), and the structural items (edge-function
+extraction, the 3,188-line `invoicing.service.ts` and 6,849-line `accounting.ee.service.ts`
+splits, duplicated currency-decimals loaders).
+
+## Premise
+
+`sourceAmount` has no backfill, deliberately. Three further findings depend on that: historical
+partially-paid invoices reverting to full balance, fully-paid invoices reappearing as open, and
+`payment-syncer` silently skipping every pre-existing payment. The user confirmed accounting is
+unused, so the no-backfill design stands. **If that premise ever stops holding for any deployment,
+those three become live data-correctness defects.**
diff --git a/.ai/runs/2026-09-08-accounting-review-corrections.md b/.ai/runs/2026-09-08-accounting-review-corrections.md
new file mode 100644
index 0000000000..c782e752bb
--- /dev/null
+++ b/.ai/runs/2026-09-08-accounting-review-corrections.md
@@ -0,0 +1,69 @@
+# Bugfix run: accounting PR review corrections
+
+- Date: 2026-09-08 (America/New_York)
+- Mode: fully-autonomous
+- Request: after making the PR, wait for the coderabbit review, and then solve the problems
+- Phase plan: root-cause [existing nuclear evidence plus CodeRabbit triage] · instrument [only if an unproven runtime finding needs it] · fix [after CodeRabbit review] · test [red-to-green and targeted browser verification where applicable] · commit [update requested PR; user authorization persists]
+
+## Decisions
+
+- Create PR from current committed state before further fixes; PR #1599 created and branch pushed
+- No automatic GitHub review comments; use PR updates and code changes within requested scope
+- Prepare disjoint fix slices while waiting; no production edits before completed CodeRabbit review
+- Existing stopped PostgreSQL container is scoped to this branch/workspace and retains pgdata; start it without recreating/resetting anything
+- Keep original journal metadata roles; no additional production schema role column or legacy migration machinery
+
+## Phase log
+
+- root-cause: nuclear report contains exact repro evidence for M1/M4/M5 and code-backed M2/M6/M8; provider contract uncertainties retained as such
+- baseline: 84 SQL report cases pass (`.context/accounting/nuclear-review/review-fix-sql-baseline.log`)
+- baseline: 15 live payment/memo/concurrency tests pass (`.context/accounting/nuclear-review/review-fix-transactions-baseline.log`)
+- CodeRabbit: review 5149438993 received on 2026-09-09 at 03:29:45Z; six inline findings and 34 review-body findings classified against the code.
+
+## Outcome
+
+COMMITTED AND PUSHED: `de7ab3bbdb` — PR https://github.com/crbnos/carbon/pull/1599
+
+
+## Verified corrections
+
+- Mixed-sign AR/AP controls: live posting first produced applied 110/fictitiousFX 20 for a net90 invoice; signed reduction now posts90/FX 0 and reports reconcile.
+- Original IC controls: changing defaults first lost the original control; the exhaustive selector now relieves its original account.
+- Memo void: consumed memo originally voided with its consumer still Posted; now fails atomically until the applying payment is voided. Draft reservations do not falsely count as consumption.
+- Missing memo principal: SQL formerly treated NULL consumed principal as zero; affected memos are excluded from current open reports, while earlier historical cutoffs remain valid.
+- Root integration: 20 live transaction/concurrency tests; four SQL suites (88 report reconciliation cases plus explicit unknown-principal assertions); 126 runtime edge tests and 46 typed pure helper tests; 177 utils tests pass.
+- Types regenerated from the existing local database; workflow catalog generated and checked; four demo datasets and real backup compatibility check pass. Backup check requires the tracked local runner so its inherited environment points at this workspace.
+
+No database reset, provider writes, GitHub review comments or merge occurred.
+
+
+## Final gates before commit
+
+| Gate | Outcome |
+| --- | --- |
+| Local migration + generate:types | PASS; existing schema current, both edited branch migrations reapplied inside one transaction; regenerated types unchanged |
+| Workflow catalog generation/check | PASS |
+| Biome + diff whitespace | PASS |
+| Database/utils/ERP/EE typechecks | PASS |
+| ERP focused tests | 186 tests across9 files PASS; full reporting slice also198 tests across7 files PASS (overlapping) |
+| EE provider tests | 928 tests across62 files PASS; final document-type scope change59 source tests PASS |
+| Utilities | 177 tests PASS |
+| Edge helpers | 126 runtime tests PASS;46 typed pure helper tests PASS (overlapping) |
+| Payment builder | 30 tests PASS, including2 new distinct-target-rate AR/AP cases (28 overlap runtime suite) |
+| Real posting transactions | 20 payment/memo/concurrency tests PASS |
+| SQL | Shipping backfill, settlement constraints,88 report reconciliation cases plus unknown-principal assertions, and7 intercompany elimination scenarios PASS |
+| RLS/defaults SQL | Child-only policy and atomic combined UPDATE proof PASS; tracked in accounting-defaults-report-access.test.sql |
+| ERP production build | PASS; existing unrelated assembler callback node:crypto/browser and chunk-size warnings remain |
+| Translations | 27 existing messages corrected across11 locales; extraction reports0 missing; compilation PASS |
+| Dataset/backup compatibility | Four datasets PASS; live schema restorable against main manifest |
+
+All40 CodeRabbit findings have dispositions in [the review resolution](../reviews/2026-09-08-accounting-review.md). Two suggestions conflict with tested accounting invariants; the generated Swagger2 nullable suggestion remains an inherited generator limitation. Independent integration source review found no new blocker. Provider transport remains mocked; browser testing was not repeated in this correction pass.
+
+
+## Delivery
+
+- Corrections committed and pushed in `de7ab3bbdb`; PR description updated with full scope, evidence and provider acceptance limits.
+- Commit hooks passed lint-staged, translation compilation, MCP generation/current digest, all four datasets, and the real backup schema check.
+- The backup hook initially staged its output relative to the package directory under an inherited Git worktree context. This was corrected before pushing by using an explicit absolute GIT_WORK_TREE; no stray root manifest ships. Generated manifest content was identical to the previous version apart from timestamp/column order, so that unrelated regeneration churn was excluded after a structural comparison.
+- Refreshed remote CI/CodeRabbit checks are pending; their earlier review was received and all40 findings were addressed or given an evidence-backed disposition. This does not claim the correction commit has received a second completed bot review.
+- Working tree was clean after the correction commit. No merge or deployment action was taken.
diff --git a/.ai/runs/2026-09-09-accounting-e2e-fixes.md b/.ai/runs/2026-09-09-accounting-e2e-fixes.md
new file mode 100644
index 0000000000..80b7d8301c
--- /dev/null
+++ b/.ai/runs/2026-09-09-accounting-e2e-fixes.md
@@ -0,0 +1,52 @@
+# Bugfix run: accounting E2E priorities 1, 3 and 4
+
+- Date: 2026-09-09
+- Mode: fully autonomous, continuing the user-authorized accounting correction work.
+- Request: “fix 1, 3, and 4”
+- Phase plan: root-cause reused/confirmed from real E2E evidence; instrumentation only if new uncertainty requires it; fix with failing regression first; browser/live API verification; commit/push not requested in this turn.
+- Plan: [implementation checklist](../plans/2026-09-09-accounting-e2e-fixes.md).
+
+## Root-cause brief
+
+**Bug:** live Rillet, payment and reporting flows fail despite the branch's core posting corrections.
+
+**Root causes / confidence:** HIGH for reversed bill FX direction; mapped-document idempotency skipping voids; unimplemented payment void hooks; unrounded memo residual subtraction; refund paths inferring party from cash direction and subledgers omitting refunds; published settlement metadata omitting createdBy; historical period RPC active filters; unpaged application readers. These are reproduced in [the E2E run](2026-09-09-accounting-e2e.md). Rillet AR_ONLY FX/deferred revenue behavior is proven, but the correct supported provider representation still requires investigation.
+
+**Approach:** repair each source of the mismatch and its real callers, preserving tenant scope and exact source-document principal. Add regression tests before production edits, then replay fresh owned E2E/provider fixtures. Use migrations for stored SQL definitions and regenerate types before typechecking.
+
+**Risks / BC:** preserve edge names, event names, public routes and existing service callers. Refund flows span both customer/supplier and cash direction. Rillet retry behavior must not duplicate remote reversals; provider refusal states must remain visible. Existing accounting adoption instruction permits direct correction without legacy backfill machinery.
+
+## Phase log
+
+- Diagnosis: prior E2E artifacts loaded; current branch and workspace changes checked.
+- Implementation: parallel bounded agents assigned Rillet, payments and reports; root handles published API author injection and integration gates.
+- API regression RED: real manifest→dispatch tests failed 4 cases (27 existing cases passed): omitted authenticated creator and forged caller creator for both replaceInvoiceSettlements and applyCreditsToInvoices.
+- API fix: use existing per-operation injection overrides for the two transaction services, matching their required createdBy contract. This preserves name-based behavior of unrelated operations and stamps authenticated identity with the existing dispatcher.
+- API GREEN: 55 manifest/metadata/real-dispatch tests passed. Fresh local scoped HTTP requests for replaceInvoiceSettlements and applyCreditsToInvoices both returned200 with omitted and forged createdBy; all persisted rows carried the authenticated author. Temporary API key removed and owned invoice/memo voided after clearing Draft applications. Evidence: `.context/accounting/e2e-20260909/fix-api-live-results.json`.
+- Refund UI RED→GREEN: 10 new failing cases covered validator acceptance of both refund directions, rejection of ambiguous parties, four visible payment choices, memo-only target loader, exact composer save/reopen. All56 model/form/composer/loader tests passed after implementation.
+- Report SQL: both migrations applied without rebuilding database; actual historical leaf/ancestor/snapshot-writer regression and106 balance/report scenarios passed. Type regeneration remains in progress.
+- Integration correction confirmed: live Rillet REVENUE_RECOGNITION_ONLY probe accepts reciprocal fixed FX and produces same-day revenue; adapter implementation uses that supported invoice scope.
+- Runtime: overlapping validation with a separate user agent caused memory pressure and local ERP/API timeouts. Root stopped its own duplicate ERP typecheck; independent user's Explorer edits/typecheck left intact. Live browser/provider replay will resume after the current checks release resources.
+
+## Final verification
+
+**Result: implemented and verified locally.** All selected accounting failures are corrected. No commit or push was made during this fix turn.
+
+- ERP: 204 targeted tests pass across payment models/form/composer/loader/services, paginated histories, reports, manifest and real API dispatch. Final scoped `pnpm exec turbo run typecheck --filter=erp` exits0.
+- Rillet/EE: 197 tests pass; jobs:142 tests pass. Both scoped typechecks exit0. The provider accepts fixed invoice/bill FX, recognizes revenue on Carbon's posting date, and deletes native invoices/bills/payments on void with retry-safe retained mappings.
+- Payment/memo edge:69 tests pass, including actual database transactions for both parties, final document cents, original-account provenance, over-refund rollback and memo void guards. Deno typecheck still reports eight diagnostics in untouched shared pg/sequence files; no changed payment/memo diagnostics.
+- SQL:106 reporting cases plus inactive-account tree, period-series and actual snapshot-writer regressions pass. Both RPC migrations applied; generated database types/swagger refreshed. All four seed datasets remain applicable; backup compatibility is restorable against main (rerun through the local environment loader after the plain command skipped for its connection environment). Workflow catalog and manifest checks pass.
+- Published APIs: fresh real HTTP requests accept omitted createdBy and replace forged createdBy with the authenticated user, on both settlement replacements and memo applications.
+- Live Rillet:11 fresh documents (USD, three EUR rates, JPY, BHD, small-line tax and shipping) preserve the independent remote GL. Three native payments, including AR fanout, post and void through reconciliation/drain. All11 document voids return remote404; the final remote GL contains no remaining fixture entries; replay enqueues0.
+- Browser customer refund: created `dagpujaqu0h3tdpb7h7g` from the new form as Refund to Customer, EUR55/r1.25. Auto apply saved target memo principal55/base50/FXgain6. Post gave AR debit50, cash credit44 and FX gain credit6, with AR variance0. Void restored memo55/base50 and reversed every original account. Owned memo then voided through the actual endpoint. The initial assertion mistakenly summed natural-balance storage signs; class-aware signed-debit proof passed. The initial type selector's blank registered default was reproduced, fixed, and covered by a red→green regression.
+- Supplier live API:11 assertions pass for final-cent memo application, partial/full FX refunds, consumed-memo void refusal, restoration, and unallocated refund aging/tie-out. Owned fixtures voided and API keys removed.
+- Reports under actual PostgREST max_rows1000: payment and invoice UI show all1105 applications; inactive child and All Companies reports retain balanced160 assets/equity,120 net income and40 CTA; all1061 CSV rows match both monthly columns. Invalid scope returns404 on BS/IS/TB. Cap restored and independently verified; test accounts reactivated.
+- Translations:168 empty entries filled across12 locales using Haiku with the approved glossary; deterministic merge reports0 remaining and `linguito check` exits0. The terminology audit retains15773 existing findings and flags4 newly filled Russian/Hindi strings (including inflection/negation cases) for terminology review; this is not a clean glossary audit. The glossary was not edited.
+
+Detailed evidence: `.context/accounting/e2e-20260909/fix-{rillet,payments,reports}-results.md`, `fix-api-live-results.json`, `fix-customer-refund-fixtures.json`, and associated `fix-*.log` files. Successful workflows are cached in the accounting, purchase, reports and Rillet playbooks.
+
+Preserved unrelated concurrent edits: `AccountMapping.tsx`, `PurchaseInvoiceExplorer.tsx`, `SalesInvoiceExplorer.tsx`. Shared shipping/bank mapping gaps (item2), inbound webhook delivery, unconfigured Xero/QBO acceptance, and the separate fixed-asset master lifecycle gap remain outside this selected scope. Foreign-currency payment push remains the provider's explicit unsupported capability; the corrected FX normalization applies to native invoices/bills.
+
+## Commit preparation
+
+The user subsequently requested committing and pushing all workspace changes. The commit therefore also includes the concurrent account-mapping form refresh and invoice-explorer styling edits, alongside the completed fixes and test documentation. Those three UI files pass Biome; the final translation completeness check exits0. Previously completed scoped typechecks, automated tests, SQL and live verification remain applicable to the unchanged implementation. All76 changed source/documentation/catalog files were screened for credential patterns with no matches; disposable evidence and translation chunks stay gitignored.
diff --git a/.ai/runs/2026-09-09-accounting-e2e.md b/.ai/runs/2026-09-09-accounting-e2e.md
new file mode 100644
index 0000000000..2e25591f92
--- /dev/null
+++ b/.ai/runs/2026-09-09-accounting-e2e.md
@@ -0,0 +1,96 @@
+# Accounting priorities 1 and 2 — executed E2E verification
+
+Date: 2026-09-09. Branch: `assess-issue-against-code`, HEAD `84abeb3e3d`. Concurrent uncommitted workspace edits in `AccountMapping.tsx` and the generated tool-manifest digest were preserved; this test run did not modify production source.
+
+**Verdict: the core posting and consolidation corrections have substantial live coverage, but accounting is not ready for rollout.** Real browser, authenticated ERP routes, edge posting endpoints, PostgreSQL and the live Rillet sandbox exposed additional failures. Issue statuses and unit tests were not used as substitutes for execution.
+
+The user authorized `/test`, direct database/API setup and live Rillet verification. All test documents were uniquely prefixed and owned. The existing database was not reset. Rillet was configured only on Carbon Development; Xero and QuickBooks were not configured and have no live verification result.
+
+## Final test matrix
+
+| Priority area | Result | Evidence and observed behavior |
+|---|---|---|
+| Rillet connection, accounts, subsidiary | PASS | Sandbox key validated; chart and USD subsidiary returned by the real API. |
+| Rillet USD invoice, tax rounding and retry | PASS | 20 × 1.99 at 8.25% produced gross 43.08 and tax 3.28; retry reused the same remote invoice. |
+| Rillet document shipping/account provenance | PASS with fixture mapping | Valid invoice gross 126, tax 11 and total shipping 15 used the original mapped shipping revenue code. Current default Shipping Revenue itself lacks a mapping. |
+| Rillet foreign bills | FAIL | Current adapter's directed currency pair is rejected with HTTP 400. Reversed pair and reciprocal rate accepted and independently booked USD 100 for both EUR 80 and EUR 120. |
+| Rillet foreign AR base normalization | FAIL / provider behavior gap | AR_ONLY uses provider FX despite an explicit rate probe; Carbon base 100 became 93.02, 139.53 or 116.28. |
+| Rillet revenue GL parity | UNRESOLVED | Independent GL books invoice net to Deferred Revenue 2160, although line revenue account codes are correct. Recognition workflow has not been proven to reproduce Carbon's immediate revenue posting. |
+| Rillet ordinary USD AR/AP payments | PASS with fixture bank mapping | Actual Carbon posting/event/operation drain created one remote payment each; invoices/bills became PAID; retries reused/skipped the same IDs. |
+| Rillet invoice/bill/payment void | FAIL in Carbon adapter | Local payment void leaves remote documents PAID and returns Skipped/manual remediation. Local invoice and bill voids are treated as already-pushed/idempotent; remote balances stay open. Native Rillet DELETE endpoints successfully reversed owned uncleared AR/AP payments and deleted owned unpaid invoices/bills. |
+| Rillet inventory journal and reversal | PASS | Actual remote journal/reversal entries netted to zero by account. |
+| Customer payment creation, invoice settlement and void | PASS | Browser created EUR 120.80/rate 0.8, staged base 151 and FX 0, posted Paid, then exact reversal. |
+| Customer and supplier discount/write-off | PASS via UI routes | Customer cash 975 + discount 20 + write-off 5 closes base 1000; supplier 90 + 5 + 5 closes 100. Correct account classes and exact voids. |
+| Prior on-account credit and FX | PASS | EUR 50 settled base 25 using original source rate 1 and invoice rate 2; FX gain 25. Source-void guard and consumer-void restoration passed. |
+| High-rate ordinary credit payment | PASS | EUR 160.01/rate 16000: manual base 0.01 consumes EUR 160; final EUR 0.01 consumes base 0, FX 0. Both voids restore principal and carrying. |
+| High-rate memo credit | FAIL on final cent | Customer and supplier first EUR 160/base 0.01 applications succeed; final EUR 0.01/base 0 stages correctly but posting rejects the remaining principal. |
+| Supplier debit memo lifecycle | PASS | Credit 30 against invoice 50 leaves 20; source void blocked while consumed; consumer void restores balances. |
+| Customer/supplier refunds | FAIL | Bank/control GL signs are correct, but AR/AP reconciliation diverges by the refund amount; refund application route also rejects the party/target. |
+| Published settlement API | FAIL | Valid scoped API call returns 422 because `createdBy` is not injected. Equivalent authenticated UI action passes. |
+| Sales tax, shipping, mixed signs and original accounts | PASS | Base 151 = revenue 123 + shipping 15 + tax 13. Signed fixture base 96.30 = revenue 75 + shipping 13 + tax 8.30. Settlement/void and changed-default reversal reconcile exactly. |
+| Direct and receipt-owned purchase posting | PASS | Conversion factor 5, tax/freight, signed lines, zero PPV, original AP settlement, and invoice void preserving receipt-owned cost layers. |
+| Actual fractional intercompany match/elimination | PASS | Both sides retain 300.015; real matching and balanced elimination pass. Half external realization leaves deferred margin 60.0075; regeneration is stable. |
+| Intercompany tax/shipping and fixed-asset account | PASS | Complete captured controls/revenue/COGS used; external tax excluded from revenue; asset profit eliminated against the actual asset account. |
+| Child-only reports, parent CTA, monthly CSV parity | PASS | User has only subsidiary access. Foreign report assets/equity 160, income 120, parent CTA 40, root 0. Identity and All Companies match CSV. |
+| Inactive historical accounts | FAIL | Deactivating historical Cash and its parent removes assets 80 while retaining income 80; CSV copies the error and consolidation refuses the unbalanced subsidiary. |
+| Defaults and new-company setup | PASS | Shipping Revenue seeded as an active revenue leaf. Save/reload and alternate account passed; invalid same-as-sales and cross-group mappings rejected without partial writes. |
+| Large chart/open-invoice paging | PASS under actual cap 1000 | Reports retained 1,061 balance-sheet CSV rows from 1,111 chart accounts. Draft payment loader retained all 1,005 invoices and 1,105 settlement adjustments: first balance 895, total open 10,935. |
+| Posted payment/invoice application paging | FAIL | With actual PostgREST cap 1000, 1,105 effective applications display as 1,000 and incorrectly show 105 unapplied. Invoice application loader likewise aggregates only 1,000. |
+| Unrelated report company parameter | FAIL on explicit rejection | Returns an empty HTTP 200 report instead of rejecting an out-of-group selection. No cross-group balances were disclosed. |
+| Fixed-asset invoice void master state | KNOWN FAILURE | GL reverses, but asset remains Active with acquisition cost 100; pre-existing lifecycle gap reproduced. |
+
+## Fix next
+
+1. **Rillet fidelity and setup.** Correct bill FX direction to document → subsidiary currency with reciprocal Carbon rate. Decide and implement an AR_ONLY FX/revenue-recognition policy that reconciles provider books with Carbon; accepting a remote document is insufficient. Propagate invoice/bill lifecycle states (`RilletTransactionSyncer.pushToAccounting` in `shared.ts` currently returns idempotently before loading the changed local document) and implement provider cash-payment deletion/reversal for supported payment states and retain explicit errors for unsupported states. Map Shipping Revenue and map Bank–Cash to a Rillet bank-linked GL account.
+2. **Memo residual arithmetic.** In `packages/database/supabase/functions/post-payment/post-payment-transaction.ts`, round the remaining document principal after subtracting prior memo consumption before comparison. `160.01 - 160` becomes approximately `0.00999999999999`, so the exact staged `0.01` is incorrectly rejected. Prove final post and both voids through the UI/API again for customer credit and supplier debit memos.
+3. **Refund lifecycle and subledger.** Carry customer/supplier identity independently of Receipt/Disbursement through application loading/staging, memo targets, aging and tie-out. Current posting uses the corrected signs, but subledgers omit opposite-direction cash. Customer refund 50 caused AR variance −50; supplier refund 30 caused AP variance −30. Voiding each restored variance 0.
+4. **Historical report inclusion.** Remove active-only filtering from historical balance calculations while keeping current account selection rules separate. Reject report company parameters outside the authorized group rather than showing an empty report. `accountTreeBalancePeriodSeries` still filters root/child accounts in migration `20260809151458_balance-rpc-period-series.sql` (lines 73, 85 and 130); the live RPC matches the branch source. Verify inactive leaf and ancestor, balance-sheet root, consolidation and CSV together.
+5. **Complete API paging and audit authors.** Paginate `getInvoiceSettlements` and `getInvoiceSettlementsForInvoice`, and any equivalent unpaged application loaders; rerun under actual cap 1000. Fix published `replaceInvoiceSettlements` auth injection so `createdBy` reaches the transaction. Verify the API key path separately from session-authenticated UI actions.
+6. Track fixed-asset acquisition-state reversal as the already-known separate lifecycle issue.
+
+## Rillet verification boundaries
+
+The live adapter and actual sync factory/event drain were exercised; reads of returned documents and `/reports/journal-entries` independently checked amounts and accounts. Dedicated owned mappings were used to continue tests after discovering configuration gaps. These mappings do not prove the user's unmapped defaults work. Final configuration was re-read: Shipping Revenue 4040 is still unmapped; Bank–Cash 1010 maps to a GL account without a bank link. The sandbox bank-linked codes returned were 11111 and 21110.
+
+This run primarily verifies outbound providers; it does not establish a new Rillet-origin inbound webhook round trip. Foreign/discount/write-off/prior-credit-funded outbound payments are explicitly skipped by current integration code; they were not counted as successful synchronization. AR_ONLY provider FX and deferred revenue behavior need a defined accounting contract, not just a payload change assumed from local tests. JPY was accepted at its currency precision; BHD lacked a provider FX rate and therefore did not complete a live round trip. Cleared payment reversal is not covered by the successful native deletion of UNCLEARED test payments.
+
+Native payment, invoice and bill deletion was exercised as an API capability probe and cleanup after preserving proof that Carbon itself skipped void propagation. A final independent journal report confirmed that all five named deleted payment/invoice/bill entries were absent (`rillet-native-cleanup-gl.json`). This does not change the adapter's FAIL verdict.
+
+## Reproduction evidence
+
+All paths below are relative to this workspace. Detailed evidence is gitignored and retained for local inspection; no credentials are embedded in this report.
+
+- Customer/root fixtures: `.context/accounting/e2e-20260909/payments-fixtures.json` and `customer-fixtures.json`.
+- Ordinary FX/precision: `payments-{normal-posted,normal-voided,high-first,high-final,high-restored}-evidence.json`; `payments-source-guard.json`.
+- Sales/discount assertions: `sales-posted.log`, `discount-posted.log`; `customer-fixtures.json` retains original/reversal account rows and explicit expected/actual checks.
+- Memo failure: `memo-final.log`; `customer-fixtures.json` contains exact edge error and staged `sourceAmount=0.01`, `appliedAmount=0`; screenshot `.ai/scratch/e2e/accounting-20260909/memo-final.png` and adjacent snapshot.
+- Customer refund: `customer-fixtures.json` → `refund.post` retains before/after tie-out and bank/control GL. Owned refund and memo were voided afterward to isolate later tests; original failure evidence remains.
+- Purchasing/IC: `.context/accounting/e2e-20260909/purchase-ic-results.md` and its linked evidence JSON. Real PO creation/finalization, receipt, posting, scoped API dispatch and authenticated application routes are distinguished there.
+- Reports/defaults: `.context/accounting/e2e-20260909/reports-results.md`, `reports-verification.json`, `reports-identity-child-inactive.json`, `reports-defaults-*`, `reports-child-rls-evidence.json`.
+- Paging: `reports-postgrest-cap-evidence.json`, `reports-posted-payment-applications-capped.json`, screenshot `.ai/scratch/e2e/accounting-reports/reports-posted-payment-truncated-20260909.png`.
+- Rillet: [adjudicated live results](../../.context/accounting/e2e-20260909/rillet-results.md), `rillet-fixtures.json`, `rillet-*-push.json`, remote document snapshots and independent ledger summaries under `.context/accounting/e2e-20260909/`; the linked Rillet results document gives the adjudicated probe outcomes and primary API documentation.
+
+The actual PostgREST row cap was temporarily set to 1000, independently verified against 1,105 rows, then restored to its prior unset value (again verified as 1,105 returned). A malformed settlement beyond the first page made the draft loader fail closed and was removed afterward. The bulk invoice detail render hit an error with the synthetic fixture, so its truncation verdict is based on the real loader result; the posted-payment truncation was directly visible in the browser.
+
+Local runtime failures (intermittent TLS/proxy requests, bypass login delay, early snapshots before completed requests), corrected fixture assumptions and test-script import problems were separated from product failures. Evidence histories can include failed setup attempts; the matrix above records final adjudicated outcomes.
+
+## Repeatable verification
+
+Successful UI sequences were cached in `.ai/playbooks/accounting-posting-corrections.md` and the reports/purchasing/provider playbooks written for this run. All dedicated browser sessions are closed, and the reports session credential file was removed. Root verification used:
+
+```text
+pnpm exec tsx .context/accounting/e2e-20260909/payments-prepare.ts
+pnpm exec tsx .context/accounting/e2e-20260909/payments-assert.ts normal-posted
+pnpm exec tsx .context/accounting/e2e-20260909/payments-assert.ts normal-voided
+pnpm exec tsx .context/accounting/e2e-20260909/payments-assert.ts high-first
+pnpm exec tsx .context/accounting/e2e-20260909/payments-assert.ts high-final
+pnpm exec tsx .context/accounting/e2e-20260909/payments-assert.ts high-restored
+pnpm exec tsx .context/accounting/e2e-20260909/customer-check.ts sales-posted
+pnpm exec tsx .context/accounting/e2e-20260909/customer-check.ts discount-posted
+pnpm exec tsx .context/accounting/e2e-20260909/sales-void.ts
+pnpm exec tsx .context/accounting/e2e-20260909/customer-finish.ts mixed-settled
+```
+
+These scripts reference owned stateful fixtures and phases; rerunning an earlier phase after later voids will correctly fail its status expectations. Recreate fresh fixtures for a full new run. They are not a substitute for the documented browser actions between assertions.
+
+Final local cleanup verification: root company receivables subledger/GL both 850 with variance 0; all temporarily changed defaults restored. Completed root cash, discount, refund and signed-line payment fixtures are Voided. The failed final customer memo payment remains Draft for reproduction; its preceding partial application remains Posted. Owned purchase test AP subledger/GL both 0, temporary API keys deleted, and its browser session closed.
diff --git a/.ai/runs/2026-09-09-accounting-report-fixes.md b/.ai/runs/2026-09-09-accounting-report-fixes.md
new file mode 100644
index 0000000000..574ea1b715
--- /dev/null
+++ b/.ai/runs/2026-09-09-accounting-report-fixes.md
@@ -0,0 +1,36 @@
+# Bugfix run: accounting report completeness
+
+- Date: 2026-09-09
+- Mode: fully-autonomous
+- Request: Fix E2E findings 1, 3, 4; this slice owns report/history findings 4.
+- Phase plan: root-cause satisfied by verified browser/API/DB evidence; instrument skipped (HIGH confidence); fix with regression tests; browser verify after root's migration batch; commit skipped (root owns integration).
+
+## Root cause
+
+HIGH: actual capped PostgREST tests proved unpaged payment and invoice history truncation. Actual inactive-account test proved the balance RPC's active-only tree/grid filters drop historical balances. Unknown companies parameter bypasses membership-in-group validation in all three report loaders.
+
+## Planned files
+
+- New SQL regression and forward migration for inactive-account balance RPCs.
+- Existing report loader regression plus balance-sheet/income-statement/trial-balance scope checks.
+- New history regression and only getInvoiceSettlements/getInvoiceSettlementsForInvoice function bodies in invoicing.service.ts.
+- Relevant report guidance/playbook freshness after verification.
+
+## Verification
+
+Run each new regression red before production edits. Root applies all agents' migrations and regenerates types together. Then run SQL green and browser/accounting history tests under real max_rows=1000; restore original config and close session.
+
+## Fix progress
+
+- Reporting/history regressions reproduced first: 8 application-history failures, 6 scope failures, and inactive historical balance missing in the SQL RPC.
+- History now pages settlements with embedded parent statuses and stable ordering. Target memo labels are included for refunds. Scope loaders reject unavailable companies (404) and failed company lookup (error redirect).
+- New history + existing settlement + report suites: 83 tests passed after implementation.
+- Historical migration removes active-only filtering from all three reporting RPCs and the period-close snapshot writer. The new SQL regression invokes the actual snapshot writer with inactive leaves and ancestors.
+- Root expanded this slice to the six refund subledger RPCs. Refund regression failed before SQL changes with aging total 0 instead of 50. New cases cover AR/AP cash direction, party isolation, partial/full FX refunds with exact 55.01 memo principal, Draft/Voided/future payments, and unknown target principal.
+- Unknown memo principal retains the existing branch contract: omit the malformed memo rather than reconstructing principal from rounded base; it does not raise a report error. Root explicitly confirmed preserving this contract. Tie-out variance remains the signal for resulting subledger/GL disagreement.
+- Root applied both migrations and is running shared type generation. SQL green and capped browser proof are pending; runtime currently under memory pressure.
+
+
+## Outcome
+
+READY — both new migrations applied by root, all historical snapshot cases and 106 AR/AP report cases pass; 83 scoped ERP tests pass. Actual authenticated browser with hard cap 1,000 verifies complete payment/invoice histories, inactive child/All Companies balances, full two-period CSV parity (1,061 rows), and invalid scope 404. Local ERP restart/proxy fallback recovered runtime resource failures; the synthetic invoice fixture needed its missing shipment companion row. Cap and owned account activity restored, browser closed, session secret deleted. Full evidence: `.context/accounting/e2e-20260909/fix-reports-results.md`. Shared typecheck/full gates and commits remain root-owned.
diff --git a/.ai/runs/2026-09-09-rillet-e2e-corrections.md b/.ai/runs/2026-09-09-rillet-e2e-corrections.md
new file mode 100644
index 0000000000..972c53b447
--- /dev/null
+++ b/.ai/runs/2026-09-09-rillet-e2e-corrections.md
@@ -0,0 +1,14 @@
+# Rillet E2E corrections
+
+Autonomous /fix + TDD. Prior live reproduction proves inverted bill FX and suppressed/unsupported voids; no further instrumentation needed. Root coordinates the overall authorized items 1, 3, 4. This slice owns only Rillet provider behavior and its necessary reconciler plumbing. No commits/push. Plan and red→green/live results: `.context/accounting/e2e-20260909/fix-rillet-plan.md`, `.context/accounting/e2e-20260909/fix-rillet-results.md`.
+
+
+## Outcome
+
+READY, no commit/push. Proven fixed bill FX direction, native RRO invoice fixed rates/immediate revenue using the Carbon posting date, and complete native invoice/bill/payment void propagation with durable fanout mapping markers and bounded reconciler re-drive. Configuration mappings excluded.
+
+Red regressions recorded before implementation: FX/delete9, document/payment void10, RRO1, reconciler3, posting-date1. Final focused checks: EE197 PASS, jobs142 PASS, EE/jobs scoped typechecks exit0, Biome18 files no errors (existing warnings).
+
+Fresh sandbox evidence: eleven native documents matched independently fetched GL across USD/EUR/JPY/BHD, shipping and tax; customer payment169.08 fanned out to2 native payments and supplier100 to1. Real HTTP payment voids reopened all native documents; real invoice/bill voids plus reconciliation/drain deleted all11. Final GL contains zero entries under the fresh prefix, including the removed API-only contract probe. Replays enqueued0. No emails sent, no browser session. Inbound webhook and unconfigured Xero/QBO not live tested; FX payment push remains an existing unsupported case.
+
+Full report: `.context/accounting/e2e-20260909/fix-rillet-results.md`. Updated successful cache: `.ai/playbooks/rillet-provider-accounting.md`.
diff --git a/.ai/specs/2026-07-02-exchange-rate-convention-normalization.md b/.ai/specs/2026-07-02-exchange-rate-convention-normalization.md
index e2aadec32b..01e9f0799f 100644
--- a/.ai/specs/2026-07-02-exchange-rate-convention-normalization.md
+++ b/.ai/specs/2026-07-02-exchange-rate-convention-normalization.md
@@ -4,6 +4,8 @@
> Author: Claude (audit follow-up), for [email protected]
> Date: 2026-07-02
+> Superseded corrective design: [Accounting Posting Corrections](2026-09-07-accounting-posting-corrections.md) resolves the amount contract and covers the current invoice/payment/provider code. The user explicitly authorized assuming accounting has no users, so this document's historical-transition proposal does not apply to that implementation. Retained below as historical context, not implementation instructions.
+
## TLDR
The platform's documented currency convention is `currency.exchangeRate` =
diff --git a/.ai/specs/2026-09-07-accounting-posting-corrections.md b/.ai/specs/2026-09-07-accounting-posting-corrections.md
new file mode 100644
index 0000000000..aa0394ca71
--- /dev/null
+++ b/.ai/specs/2026-09-07-accounting-posting-corrections.md
@@ -0,0 +1,348 @@
+# Accounting Posting Corrections
+
+> Status: implemented and verified locally
+> Author: Codex, with Brad
+> Date: 2026-09-07
+> Local implementation and browser verification are complete. Connected-provider limits remain explicit below.
+> Implementation plan: [Accounting Posting Corrections](../plans/2026-09-07-accounting-posting-corrections.md).
+
+## TLDR
+
+Correct three verified accounting defects: separate collected sales tax and customer shipping from ordinary sales postings; normalize transaction FX across invoices, payments, credits, reports, and accounting integrations; and correct consolidation's currency translation adjustment (CTA), account selection, and report rollups. Add `accountDefault.salesShippingRevenueAccount`, seed a Shipping Revenue account under Revenue, and backfill company defaults. **The user explicitly authorizes assuming accounting has no users yet.** Implement one corrected monetary contract directly; do not build legacy calculation versions, historical restatement tools, or an accounting cutover workflow.
+
+## Problem Statement
+
+The [code-based readiness audit](../plans/improve/2026-09-07-accounting-readiness-audit.md) checked the implementation behind [#1060](https://github.com/crbnos/carbon/issues/1060), rather than relying on issue statuses. This spec selects the posting/FX/consolidation corrections from that audit. Source baseline: `0a9aef2444b04f0a0f0ade6f99dcd8e60aa3ec30`.
+
+| Verified defect | Source and consequence |
+| --- | --- |
+| Sales posting credits the gross charge to `salesAccount` | [post-sales-invoice](../../packages/database/supabase/functions/post-sales-invoice/index.ts), line calculation near 318 and revenue postings near 419/516: merchandise, add-ons, shipping, and tax are combined. Tax inflates revenue; shipping cannot be reported separately. |
+| Already-base invoice amounts receive another FX multiplication | Sales posting near 344 and [purchase posting](../../packages/database/supabase/functions/post-purchase-invoice/index.ts) near 832. An economic base amount of 100 at foreign/base rate 1.10 becomes GL 110. This is an extra conversion of a base field, not a universal rate-squared error. Receipt matching can consequently manufacture PPV. |
+| Payments, credits, and provider adapters disagree about denomination | [payment builder](../../packages/database/supabase/functions/post-payment/build-payment-journal.ts), [invoicing service](../../apps/erp/app/modules/invoicing/invoicing.service.ts), and [document-costing conversion](../../packages/ee/src/accounting/core/document-costing.ts). Payment cash is multiplied to base; invoice-base applications are compared with payment-currency totals; base costing lines are divided to foreign currency. |
+| Consolidation treats Expense as a credit-side balance | `translateCompanyBalances` in [accounting.ee.service.ts](../../apps/erp/app/modules/accounting/accounting.ee.service.ts), near 4464: balanced Cash 80 / Revenue 100 / Expense 20 at identity rates produces CTA −40 instead of 0. |
+| CTA is assigned by account number after report aggregation | [balance-sheet route](../../apps/erp/app/routes/x+/reports+/balance-sheet.tsx), `applyCtaByBucket`: hardcoded `3200` ignores the configured default; changing the leaf after service rollups leaves parent totals stale. |
+| IC control capture includes only one journal row | Sales posting near 1286 and purchase posting near 2100 capture only the first IC receivable/payable row. A multiline invoice's other control postings cannot be eliminated from those captures. |
+
+Already-correct behavior is the starting point: purchase line generated amounts divide supplier amounts to base; receipt header shipping already divides to base; the September consolidation RPC already returns an explicit target/source pair. Do not reintroduce earlier versions of those implementations.
+
+## Proposed Solution
+
+### Scope and prior specifications
+
+This is a correction to the current accounting implementation, not a declaration of full accounting compliance. France and e-invoicing are explicitly excluded. Also excluded: new tax determination/recoverability rules, tax returns, tax-coded memo lines, actual carrier-cost accruals, cross-currency payment allocation, new refund workflows, unrealized-FX revaluation, posted CTA journals, historical equity layers, fiscal-year retained-earnings redesign, NCI, and other workstreams in #1060.
+
+This spec supersedes the corrective design in [July FX normalization](2026-07-02-exchange-rate-convention-normalization.md), including its unresolved amount contract and proposed historical migration policy. It implements only the sales-posting separation overlapping [multi-jurisdiction tax](2026-07-03-multi-jurisdiction-tax.md), and the demonstrated reporting defects overlapping [FX/consolidation completeness](2026-07-04-fx-consolidation-completeness.md). It preserves the delivered [currency store refactor](2026-09-02-currency-exchange-rate-refactor.md).
+
+Research: [Accounting Posting Corrections](../research/accounting-posting-corrections.md), including primary SAP, NetSuite, Xero, QuickBooks, and Rillet references. The source inventory above takes precedence over older research's descriptions of Carbon.
+
+### Design Decisions
+
+| Decision | Choice | Rationale |
+| --- | --- | --- |
+| Adoption and history | Assume no accounting users; replace incorrect formulas directly | Explicit user decision. No version discriminator, legacy arithmetic branch, correction-journal workbench, or migration of old posted balances. This does not require deleting operational data or resetting a database. |
+| Customer shipping | Separate company default pointing to a Revenue leaf | Explicit user decision; consistent with NetSuite shipping-income assignment. It remains revenue, but is separate from product/service sales. |
+| Sales tax | Credit existing `salesTaxPayableAccount` | Collected tax is a liability. Retain current tax bases and rates. |
+| Purchase tax and freight | Preserve existing capitalization/expense classification while fixing denomination | Recoverability cannot be inferred from an amount; the broader tax spec owns that policy. |
+| Transaction quotation | `r = document currency units / company base currency unit` | Matches current generated columns and currency-store contract. Document → base divides; base → document multiplies. |
+| Payment and memo amounts | `payment.totalAmount`, processor fee, and `memo.amount` are in their document currency | Matches provider payment amounts and the remittance/credit amount shown to users. |
+| Settlement amounts | Principal, discount, and write-off remain target-document carrying amounts in company base currency | Invoice views already deduct these fields from base balances. Make labels and all producers consistent. |
+| FX credits | Attribute on-account consumption to its original payment | A party-level total cannot identify the historical rate of the credit being released. Extend the existing settlement primitive instead of adding a parallel credit ledger. |
+| Currency eligibility | Cash applications require matching payment/invoice currency codes; differing rate snapshots are supported | Existing code accepts different currencies without enough information to calculate them. Refuse that unsupported input. Memo applications additionally retain the current equal-rate requirement. |
+| CTA | Natural-sign translation residual, posted to the configured report account in the calculated statement | CTA reflects translation differences. Source imbalance is an error, not a reserve. No new journal-posting subsystem. |
+| Tenant boundaries and RLS | Accounts are group-scoped; defaults, invoices, payments, and settlements are company-scoped | Follow actual schema, not generic table assumptions. Validate all referenced accounts/payments against those boundaries; retain existing RLS and permission scopes. No new table. |
+| Services and transactions | Existing module services; Supabase reads return their normal data/error results; monetary writes use existing Kysely transactions | Preserve the established interface conventions, batch fetches, row locks, and atomic posting. Instantiate DB clients only in server/route code. |
+| UI and permissions | Extend existing defaults form and payment composer using existing controls, validators, route actions, and permission gates | No new configuration surface or authorization model. |
+| Compatibility | Add columns; preserve route/function/event names and existing field identities | Correct the unused accounting contract without renaming public surfaces. Update all affected callers and generated types together. No production dependency. |
+
+### Sales posting breakdown
+
+Calculate one named breakdown in company base currency before branching into supported direct, order-linked, stock/service, fixture, or fixed-asset sales posting. Sales raw `unitPrice`, `shippingCost`, `addOnCost`, and `nonTaxableAddOnCost` are base amounts; `converted*` values are document amounts. `taxPercent` is a fractional rate, e.g. `0.10` for 10%. G/L Account lines are purchase-only in the current model; this spec does not add them to sales.
+
+For each normal sales line, with `q` quantity and `h` allocated header shipping:
+
+```text
+merchandiseBase = q × unitPrice
+salesRevenueBase = merchandiseBase + addOnCost + nonTaxableAddOnCost
+shippingRevenueBase = shippingCost + h
+salesTaxBase = (merchandiseBase + shippingCost + addOnCost) × taxPercent
+grossReceivableBase = salesRevenueBase + shippingRevenueBase + salesTaxBase
+
+DR Receivables grossReceivableBase
+CR Sales salesRevenueBase
+CR Shipping Revenue shippingRevenueBase
+CR Sales Tax Payable salesTaxBase
+```
+
+Preserve the current tax treatment: line shipping and taxable add-ons participate in the taxable base; non-taxable add-ons and header shipping do not. Do not introduce a new header-shipping tax switch. Preserve current allocation weights for header shipping, the equal-share fallback when all eligible weights are zero, and a deterministic residual assignment so allocations total the header charge exactly. Missing required mappings fail before writes; zero components do not create empty journal lines.
+
+Use existing precision helpers and source invoice rounding policy. Monetary totals, provider boundaries, and editable amounts use the relevant currency's configured decimals; prices, rates, allocations, and internal ledger amounts retain internal precision. Do not globally round to two decimals or change tax calculations merely to make the journal balance. The decomposition must reconcile to the authoritative invoice view total at the same precision.
+
+Fixed-asset disposal uses consideration attributable to the asset for sale proceeds and gain/loss. Exclude tax and separately posted shipping from those proceeds; retain gross receivables and the existing acquisition/depreciation removal and separate gain/loss accounts. Preserve the distinction between a direct invoice disposal and monetary enrichment of a disposal already owned by a shipment.
+
+Every split row retains document references, source-line dimensions, company, and period. Preserve alignment of inserted journal lines and dimension/capture metadata; do not assume two rows per invoice line. Intercompany capture includes both `salesAccount` and `salesShippingRevenueAccount` in the existing Revenue role. Capture **every** actual IC receivable/payable journal row as Control on both seller and buyer, while retaining the first line as the existing trade matching anchor. Tax liability is not captured as Revenue. Preserve per-trade elimination, buyer cost treatment, and the existing shipment/receipt ownership of inventory and COGS postings.
+
+Voids negate the actual recorded lines, including shipping/tax and disposal entries. Reversals never recalculate from today's account defaults or rate. Journal-reversal coverage here does not imply a general asset-lifecycle void repair; the current sales-invoice void does not restore asset state. In particular, do not reactivate a shipment-disposed asset as a consequence of changing invoice tax/shipping arithmetic.
+
+### FX contract and settlement algebra
+
+| Field/boundary | Denomination and rule |
+| --- | --- |
+| Sales raw line amounts and header shipping | Company base; no second conversion when journaling |
+| Sales `converted*` fields | Invoice currency; raw base × rate |
+| Purchase `supplier*` amounts | Supplier/invoice currency; divide once to derive base |
+| Purchase unprefixed generated amounts | Already company base; preserve generated amounts during posting |
+| `salesInvoices` / `purchaseInvoices` totals and balances | Company base; do not multiply in aging, tie-outs, or control reconciliation |
+| Payment total / withheld fee | Payment currency; divide by payment snapshot to post cash/fee |
+| Memo amount | Memo currency; divide by memo snapshot to post its control/reason accounts |
+| Settlement applied / discount / write-off | Target carrying base; post control relief without another rate multiplication |
+| Settlement `sourceAmount` | Principal consumed in the funding source's document currency; preserve it independently of rounded base relief |
+| Settlement `fxGainLossAmount` | Company base; positive gain, negative loss, same signed result as the journal |
+| Consolidation RPC rate | Presentation currency per source-company base currency; **multiply** local balances |
+
+For a normal cash application, let `A` be target-base principal, `D` discount, `W` write-off, `ri` invoice foreign/base snapshot, and `rp` payment foreign/base snapshot. Payment and invoice currency codes must match.
+
+```text
+invoiceControlReliefBase = A + D + W
+appliedDocumentAmount = sourceAmount // economically A × ri, before base rounding
+cashFundingBase = appliedDocumentAmount ÷ rp
+AR realized gain = cashFundingBase − A
+AP realized gain = A − cashFundingBase
+grossBankBase = payment.totalAmount ÷ rp
+feeBase = fee.amount ÷ rp
+newOnAccountDocument = payment.totalAmount − sum(current-cash appliedDocumentAmount)
+newOnAccountBase = newOnAccountDocument ÷ rp
+```
+
+Discount/write-off relief uses its recorded target-base amount and generates no independent FX. Processor fees affect net bank/fee postings, not the customer's gross settlement. Sum the rounded per-application FX results into the journal's gain/loss lines, with deterministic internal-precision residual handling; the stored settlement values must reconcile to that journal.
+
+Read currency codes and rate snapshots from authoritative locked source/target rows at posting. Submitted rates are not trusted. Positive, finite rates are required, and same-base-currency documents use identity. Fix both calculation and validation: invoice caps use target-base amounts; funding caps and auto-apply compare amounts in a common, explicitly labeled currency.
+
+The equations describe economic amounts before rounding. Persist document principal as `sourceAmount` before rounding carrying-base relief; never reconstruct it from rounded `appliedAmount × ri`. Allocate in document currency at its configured decimals, preserve internal precision for base, and use authoritative source document totals for full-payment seeding. Full application consumes the exact remaining document amount, with deterministic carrying-base rounding reconciliation; an internal sub-unit residual must not leave a fully settled invoice visibly open. At a rate of 16000, document 160.01 converts to base 0.010000625: rounding base to internal scale and converting back produces 160.00, so the second stored amount is necessary.
+
+Purchase invoices must agree with receipt-side base valuation, including header freight and supplier-to-inventory UOM conversion. Identical receipt/invoice price, rate, freight, and quantity produce zero PPV. True price differences remain PPV; different posting snapshots must not be mistaken for an extra conversion of base values.
+
+Memo availability is authoritatively `memo.amount - sum(effective memo-source sourceAmount)` in memo currency; divide that remainder by the memo snapshot for base display. Memo-to-invoice applications remain GL-neutral only with matching currency and rate, as supported today. Preserve staged/posted/voided status gates, party checks, and balance-increasing/reducing memo direction. Do not infer tax from a memo's gross amount.
+
+### On-account credit funding
+
+Add `invoiceSettlement.sourcePaymentId` for a prior payment funding a current payment's application. `paymentId` continues to identify the current/applying payment and controls when the settlement becomes effective. NULL `sourcePaymentId` means current cash; a non-NULL value means consumption of the named prior posted payment's unapplied credit.
+
+Split an invoice application into funding rows when necessary. Allocate current payment cash first, then eligible previous payments oldest-first by posting date and ID. All funding sources must have the same company, party, side, and document currency. Keep the existing per-invoice composer UX by aggregating rows for display; assign each discount/write-off once, not to every funding row.
+
+For a credit-funded principal `A`, consume the persisted `sourceAmount` units of the source payment's currency and release `sourceAmount / rs` base from its on-account control balance, where `rs` is that source payment's snapshot. Before rounding, `sourceAmount = A × ri`; after rounding, the independently recorded amounts govern. Realized FX is derived from this released carrying value versus `A`, using the AR/AP sign above. The current payment's rate must not revalue an earlier credit. Cash totals and fees exclude credit-funded rows.
+
+For source payment `s`, available document credit is `s.totalAmount` minus the sum of stored `sourceAmount` on effective settlements where `(paymentId = s.id AND sourcePaymentId IS NULL) OR sourcePaymentId = s.id`. A row is effective only while its applying payment is Posted; apply the relevant cutoff in as-of queries. Exclude rows the applying payment funded from someone else's credit when calculating its own unused cash. Spendable document credit is the sum of the sources' remaining document amounts, never a base total multiplied by the new payment's rate.
+
+Serialize consumption by locking sources in a deterministic order, recheck their remaining amounts, and persist funding rows/FX/journal/status in the same transaction. Move journal construction inside that transaction after locks; the current pre-transaction builder call cannot establish authoritative funding. Voiding the applying payment releases its allocations and reverses its recorded journal. Refuse voiding a source payment while an effective downstream application consumes it. Existing valid base-currency credit behavior remains supported, including a zero-cash payment applying existing credit.
+
+This does not add refund or memo-target payment UI. Keep unsupported combinations explicit at service/posting boundaries; retain correct directional arithmetic in the reusable journal builder rather than interpreting `Receipt` alone as AR.
+
+### Provider boundaries
+
+Update provider consumers in the same delivery as posting normalization. Account-costed AP bill replay must convert base journal lines to document currency by multiplication and preserve signed variance lines, account mappings, dimensions, and total reconciliation. Apply each provider's named precision contract.
+
+| Boundary | Required behavior |
+| --- | --- |
+| Shared `toTransactionCurrencyLines` | Base × Carbon rate; residue targets the document total, not a total calculated with the old inverse formula |
+| Xero | `CurrencyRate = r`; keep correctly converted unit prices. Export tax/shipping/add-ons and header totals in document currency with the corresponding sales/shipping mapping. Fractional `taxPercent` receives no extra `/100`. Do not duplicate native tax postings with an extra explicit tax charge. |
+| QuickBooks Online | Home-per-foreign `ExchangeRate = 1/r`; invert inbound rates before storing Carbon snapshots. Monetary payloads still use document currency. |
+| Rillet bills | Send a schema-valid `exchange_rate` object with explicit base/target/date/string rate; the existing scalar is invalid under current documentation. Independently verify the directed pair with provider evidence; a self-authored serializer fixture does not prove its arithmetic direction. |
+| Rillet AR_ONLY invoices | Keep the existing scope. Its documented create schema has no custom `exchange_rate` field; do not invent one or promise matching provider base translation. Preserve document components, native tax, and the shipping product/account mapping. |
+| Inbound payment applications | Keep remote payment total in payment currency; resolve invoice rate/currency and convert applied document amount to target base. Remove the invented target rate 1. Reject unsupported currency pairs before writes. |
+
+Preserve existing provider capability gates, including unsupported FX payment paths. Do not build additional provider features. Existing AR invoice adapters are item-based while AP bill adapters replay account-costed postings: test the real paths separately. Newly required Shipping Revenue mappings must produce the existing actionable unmapped-account error when absent. Preserve mapping identities and retry/idempotency behavior.
+
+Use the existing item syncers to provision/reuse QBO Service and Rillet ONE_TIME shipping helpers mapped to Shipping Revenue, under a separate `shippingItem` mapping identity; no fake local inventory item. Native tax must remain outside revenue. QBO tax export resolves compatible existing remote sales tax codes/rates and fails with an actionable preflight warning if missing, ambiguous, or unsupported. This mapping does not create tax codes or change Carbon's tax determination.
+
+### AR/AP carrying balances
+
+Aging and tie-out `openInBase` use the original posted invoice control carrying
+amount less effective principal, discount, and write-off relief. They do not
+rederive carrying from rounded document money: a 100.004 control at r0.8 remains
+100.004 base even when the document total rounds to 80. Source-payment carrying
+uses original rounded gross less recorded A+FX (AR) or A−FX (AP) releases.
+Document eligibility is independent; preserve positive document remainders with
+zero remaining base as visible rows with `openInBase=0`. The invoice view's
+`balance` remains exact document remainder divided by the invoice snapshot for
+eligibility/display, rather than becoming a reconstructed ledger carrying value.
+
+### Consolidation calculations and report integration
+
+Only actual leaf balances participate in the following sums; exclude group subtotals and synthetic `NET_INCOME_ACCOUNT_ID`. Use account class, preserve negative balances, and do not use the report's `rootSignMultiplier` as a debit/credit conversion.
+
+```text
+sourceResidual = Assets + Expenses − Liabilities − Equity − Revenue
+translatedBalance = localBalance × selectedTargetPerSourceRate
+CTA = translatedAssets + translatedExpenses
+ − translatedLiabilities − translatedEquity − translatedRevenue
+```
+
+Validate the source balance before translation using existing ledger precision/tolerance conventions. An actual source imbalance, invalid class, or nonfinite amount produces a company/date-specific error. A successful RPC with an empty/null rate result is also an error; applicable rates must be finite and positive. Propagate a failed subsidiary to the whole consolidated report.
+
+Preserve the September pair-rate SQL, including identity rates, missing-pair failures, and its documented earliest-rate and closing-rate fallbacks. Do not invert its target/source rate while correcting transaction FX. Retain current balance-versus-activity semantics, synthetic income calculation, fiscal buckets, and automatic inclusion of relevant elimination entities.
+
+Resolve the root reporting company's `accountDefault.currencyTranslationAccount` by ID, matching the root company's presentation currency. Use this mapping for both consolidated reports and an individual subsidiary translated into that currency. Validate an active Equity leaf in the same company group. A custom number/name or a different active-session company must not change the chosen account; missing/invalid mappings produce an explicit report error.
+
+Apply each bucket's calculated CTA once, preserving any existing booked balance on that account, **before the final translated parent/root rollup**. Alternatively use one shared service helper that applies CTA and reruns existing rollups. Both single-company and consolidated branches must use that helper; screen rows, subtotals, roots, and CSV must share its result. CTA remains a computed reporting adjustment.
+
+## Data Model Changes
+
+### Shipping Revenue default and chart backfill
+
+Add nullable `accountDefault.salesShippingRevenueAccount TEXT`, with an indexed FK to `account(id)`, `ON DELETE RESTRICT ON UPDATE CASCADE`. Persist a valid mapping for every existing normal company with account defaults, and initialize it for all new companies. Nullable storage preserves existing backup/import shapes; nonzero shipping cannot post without a valid mapping. Do not create incomplete defaults for elimination-company shells.
+
+The canonical new account is:
+
+| Attribute | Value |
+| --- | --- |
+| `name` | Shipping Revenue |
+| Stock-chart `number` / seed key | 4040 |
+| `parentId` / `parentKey` | The group's Revenue parent / `revenue` |
+| `class` / `accountType` | Revenue / Income |
+| `incomeBalance` / `consolidatedRate` | Income Statement / Average |
+| `isGroup` / `active` | false / true |
+| Identity and ownership | Database-generated account ID; existing group scope and system audit conventions |
+
+Backfill one resolution per `companyGroupId`, then update company defaults through their company/group relationship. Preserve populated valid mappings on rerun. Reuse a compatible existing Shipping Revenue leaf without changing its number or ID. Otherwise create it under the canonical active Revenue group; for a custom chart without that named group, resolve the unique compatible group parent of the configured sales account. Never choose an arbitrary first row, a leaf named Revenue, or a different tenant's account.
+
+Use 4040 when free. If occupied by an unrelated account, use the first unused stock revenue number in the sequence 4050, 4060, …, 4990; preserve the occupied account. An incompatible existing Shipping Revenue name, exhausted range, or ambiguous/missing Revenue parent is an explicit backfill error identifying the group. Resolve all candidates before committing the backfill, and make every step safe to rerun. Existing custom charts must not be silently reclassified.
+
+Update [seed.data.ts](../../packages/database/supabase/functions/lib/seed.data.ts) and [seed-company](../../packages/database/supabase/functions/seed-company/index.ts). Subsidiaries joining an existing group inherit the validated parent shipping default, then fall back to a uniquely resolved compatible group shipping leaf. Number-only lookup is insufficient after a collision or custom renumbering. The dataset [bootstrap](../../packages/database/src/datasets/bootstrap.ts) consumes the canonical seed data and must be verified too.
+
+### Settlement funding and FX snapshot
+
+Add nullable `invoiceSettlement.sourcePaymentId TEXT` with an indexed same-company FK `(sourcePaymentId, companyId) → payment(id, companyId)` using RESTRICT on delete; add the corresponding unique key to `payment` without changing its existing primary key. It is allowed only for a payment-sourced settlement, cannot equal `paymentId`, and references a same-party/currency posted source payment. Enforce those relationships through authoritative transaction validation and the existing settlement access rules; all queries include company scope. The column does not create a new target or change the meaning of `paymentId`.
+
+Add `invoiceSettlement.sourceAmount NUMERIC`, nonnegative and nullable for pre-existing/draft rows, with a required authoritative value on posting. It stores principal consumed in source document currency for current cash, prior-payment credit, and memo sources; it is zero for discount/writeoff-only rows. Save/preview may derive it, but posting computes/validates it with locked parents and persists it alongside target-base `appliedAmount`. Availability and source caps sum this field; they never reconstruct document money from rounded base. No historical backfill of posted settlements is required under the user's adoption assumption.
+
+Settlement completion uses the invoice currency's configured decimals and independently stored document principal. A positive document remainder remains payable even below one base-currency cent or the internal ledger rounding unit. Invoice views expose that remainder divided by the invoice rate without rounding away the remainder; posted ledger amounts retain internal precision. Broaden `invoiceSettlement_anyComponent_check` to allow positive `sourceAmount` when rounded base principal is zero, and keep that terminal application valid through the composer, save, and post paths. Missing currency precision configuration is an actionable posting error; draft invoice views must not disappear because configuration is absent.
+
+Change `invoiceSettlement.fxGainLossAmount` from its current generated expression to an ordinary NUMERIC posting snapshot, retaining its name and values rather than dropping the column. `ALTER COLUMN ... DROP EXPRESSION` is the intended migration operation. Draft previews use the shared authoritative calculation; posting stores its result atomically with the actual journal. Memo-only same-rate applications store zero. Never accept a client-provided FX gain/loss amount as authoritative. No generated expression may depend on mutable parent values, and no legacy-expression branch is needed under the user's adoption assumption.
+
+Document denominations with SQL comments and application types. Recreate affected aging/tie-out RPCs from their **latest** definitions in forward-dated migrations. Preserve existing invoice status, the base-table `Paid`/`datePaid` legacy guards, cutoff-date, and staged/voided settlement logic unrelated to the arithmetic correction. There is no `legacyPaidAmount` column in the current schema. Do not rewrite base generated purchase fields into document currency.
+
+## API / Service Changes
+
+| Area | Existing integration points and required changes |
+| --- | --- |
+| Account defaults | [accounting.models.ts](../../apps/erp/app/modules/accounting/accounting.models.ts): add shipping field to `defaultIncomeAcountValidator`, which feeds the merged validator. [defaults route](../../apps/erp/app/routes/x+/accounting+/defaults.tsx) and `updateDefaultIncomeAccounts` must retain/persist it and validate group/class/active/leaf eligibility. Missing field on an older settings payload preserves the stored default. |
+| Invoice posting | `post-sales-invoice/index.ts`, `post-purchase-invoice/index.ts`: central component breakdown, corrected base postings, fixed-asset amounts, IC captures, references/dimensions. Verify `post-receipt/index.ts` stays correct. |
+| Payments/memos | `post-payment/index.ts`, `build-payment-journal.ts`, `post-memo/index.ts`, `build-memo-journal.ts`, and `invoicing.service.ts`: funding allocation, locks, rate validation, stored FX, memo availability, balance caps, void/retry behavior. Share pure conversion/funding calculations between preview and posting. |
+| Composer | [new payment route](../../apps/erp/app/routes/x+/payments+/new.tsx), [payment detail route](../../apps/erp/app/routes/x+/payments+/$paymentId.tsx), application/credit actions: seed document cash from invoice-base balance × invoice snapshot; use source attribution and explicit currencies throughout. |
+| Reports | `accounting.ee.service.ts`, `balance-sheet.tsx`, latest AR/AP tie-out and aging RPCs. Correct base amounts, CTA signs, mapping, errors, and rollups through actual callers. |
+| Integrations | `packages/ee/src/accounting/core/document-costing.ts`, `payment-application.ts`, and Xero/QBO/Rillet `entities/{bill,invoice,payment}.ts`, serializers/models, and their existing tests. |
+
+Keep changes inside existing module/service organization. Edge-compatible pure helpers may live under the existing shared functions directory and use the current precision exports; do not introduce a new financial arithmetic dependency. Fix stale comments/tests that encode the inverted convention.
+
+## UI Changes
+
+- Add **Shipping Revenue** to the Sales & Revenue section of [AccountDefaultsForm](../../apps/erp/app/modules/accounting/ui/AccountDefaults/AccountDefaultsForm.tsx). Use the existing selector with eligible Revenue leaves; keep it distinct from `salesAccount`. Explain that it receives shipping charged to customers. Carrier expense configuration remains separate.
+- Label payment totals and source credit in payment currency. Label invoice balance/application/discount/write-off inputs in their actual base currency, with invoice-currency equivalents where useful. The composer must not display a base value under a foreign currency symbol. Auto-apply budgets in document currency and converts each selected invoice using its own snapshot.
+- Show only currency-eligible invoice/credit choices and surface the existing actionable errors for invalid mappings, rates, or caps. Repeat validation on save and post.
+- Update payment application/history displays to aggregate split funding rows and show base-currency realized FX consistently. Consolidated reports and CSV use corrected service results. Translate new/changed user-facing strings through the existing Lingui workflow.
+
+## Acceptance Criteria
+
+All amounts below are exact expected economic amounts before applicable precision rounding. Every posted journal must also pass the existing debit/credit balance invariant using natural-balance sign conversion.
+
+### Defaults and invoice components
+
+- [x] Fresh group: Shipping Revenue 4040 is an active Revenue leaf under Revenue, Average translated, and every normal company's shipping default resolves to its ID.
+- [x] Existing group/subsidiary: backfill and seed both use the compatible existing account; custom numbers and subsequent default customization survive reruns. Occupied 4040 allocates the next free number; no unrelated account changes. Ambiguous parents/incompatible names return explicit errors without a partial backfill.
+- [x] The settings form saves/reloads the new default. Cross-group, inactive, group, wrong-class, or same-as-sales mappings are refused server-side.
+- [x] Base USD/document EUR at `r=0.8`: merchandise 100, line shipping 10, taxable add-on 20, non-taxable add-on 3, tax 10%, header shipping 5 produces DR AR **151**, CR Sales **123**, CR Shipping **15**, CR Tax **13** USD. Document total is **120.80 EUR**. No journal component is multiplied by 0.8 again.
+- [x] Zero tax/shipping, all-zero allocation weights, fractional quantities/rates, and supported direct/order-linked stock/service/fixture lines use the same decomposition and correct dimensions. Tax + component sum ties to the invoice view. Purchase G/L Account lines retain their chosen account and correct base cost.
+- [x] Asset carrying value 70 sold for 100 plus shipping 10 and tax 11: AR 121, shipping revenue 10, tax liability 11, disposal proceeds 100, gain 30. Cover direct disposal and shipment-linked monetary enrichment; void negates exact recorded journal postings and leaves shipment-owned disposal state intact.
+- [x] Multiline taxed IC invoices with shipping capture every seller/buyer control row, so matched IC AR/AP balances eliminate completely. Shipping revenue eliminates on its actual account; external tax liability and non-recoverable buyer tax cost remain. Two trades with different margins retain per-trade allocation.
+
+### FX and settlement
+
+- [x] Invoice 110 document units at `r=1.10` posts control **100 base**. Matching receipt/invoice prices, freight, rates, and non-1 UOM conversion produce **zero PPV**; cost ledger and fixed-asset acquisition agree with base valuation.
+- [x] Paying 110 at `ri=rp=1.10`, `A=100`: bank 100, control relief 100, FX 0.
+- [x] Paying 110 at `ri=1.10`, `rp=1`: bank 110; AR gain 10 / AP loss 10. At `rp=1.25`, bank 88; AR loss 12 / AP gain 12.
+- [x] `A=80`, discount 10, `ri=1.10`, `rp=1`, payment 88: control relief 90, cash 88, discount 10, AR FX gain 8, invoice remaining base 10. Write-offs follow their correct AR/AP accounts and the same denomination rule.
+- [x] Payment 132, invoice application base 100, `ri=rp=1.10`: bank 120, invoice relief 100, unapplied credit **22 document / 20 base**.
+- [x] Two invoices, base 100 each, at `ri=1.10` and `1.20`; payment 230 at `rp=1.15`: cash 200, total control 200, net FX 0 after reconciled rounding. Auto-apply/seeding gives the same result as manual entry.
+- [x] A prior unapplied receipt of 110 at rate 1.10 carries credit base 100. Apply it with a zero-cash payment to an invoice of 110 at rate 1.25 (base 88): release the original credit 100, relieve invoice 88, AR gain 12. Changing the applying payment's rate does not change those values. Partial/multi-source use, concurrent consumption, source-void refusal, and applying-payment void/retry preserve exact availability.
+- [x] At rate 16000 with a two-decimal source currency, an application consuming 160.01 records `sourceAmount=160.01` even though carrying base rounds to 0.01000. Full application leaves document availability zero and the invoice settled; void restores 160.01. Repeated partial allocations preserve the source total exactly. Cover mixed current cash and two prior sources with different rates; a split never duplicates discount/writeoff and persisted FX sums match the GL.
+- [x] On that same 160.01 invoice, applying only 160.00 leaves 0.01 document units payable; a final 0.01 source application can close it even when its base principal rounds to zero. Views, composer, constraints, and posting agree on this completion rule.
+- [x] Memo 55 at `r=1.10` posts and provides **50 base** credit; applying it to an eligible invoice deducts 50 base. Draft/posted/voided status gates remain correct. Different-currency cash applications and different-rate memo applications fail without writes.
+- [x] Fee 3.30 on receipt 110 at `rp=1.10`: gross 100 base, fee 3, net bank 97. Receipt/disbursement directional tests and existing credit/discount/write-off tests remain balanced.
+- [x] Invalid/nonfinite/zero rates, forged rate snapshots, over-application, duplicate posting, concurrent settlement, and changed account defaults cannot create incorrect or duplicate journals.
+- [x] AR/AP aging and tie-outs reconcile invoice balances, memos, unapplied credits, applications, and control GL in base currency at the same cutoff. No extra rate multiplication; existing legacy-paid/status filters remain intact.
+- [x] Provider fixtures represent base 100/document 110 with Xero rate 1.10 and QBO rate `1/1.10`. AP lines and AR shipping/tax totals equal the document, inbound settlements become 100 base, and Rillet's rate object validates against its schema (directed-pair arithmetic remains an inference pending independent provider evidence). Unmapped accounts fail before sending; retries retain mapping identities.
+
+### Consolidation
+
+- [x] Cash 80 / Revenue 100 / Expense 20 at identity rates yields **CTA 0** and unchanged balances. Cash −20 / Expense 20 also yields CTA 0.
+- [x] Cash 80 at closing rate 2, Revenue 100 and Expense 20 at average 1.5: translated cash 160, income 120, **CTA +40**, total Equity including CTA 160.
+- [x] Source Cash 79 / Revenue 100 / Expense 20 returns a source-imbalance error. Group/synthetic-income rows do not affect the source test or CTA.
+- [x] Missing/empty/null rate payloads and invalid applicable rates fail translation; a failed subsidiary fails the whole consolidated result. Existing SQL missing-pair errors still reach the UI.
+- [x] Root default pointing to a renamed/non-3200 CTA leaf is respected even when active-company and child defaults differ. Invalid/missing mapping fails explicitly.
+- [x] Multiple buckets, single-subsidiary translation, and consolidation all add CTA once and roll up its leaf, intermediate Equity groups, root totals, and exported rows consistently. Preserve already-booked CTA balances, synthetic income, and elimination-entity inclusion.
+
+### Implementation verification
+
+Use meaningful failing numerical regressions before production changes, then run them through the actual builders/services and posting transactions. Add migration/backfill and database integration fixtures for schema-dependent behavior; pure algebra tests alone do not prove transaction/status/capture correctness. Update the three stale accounting-period mocks identified by the audit if that suite is used; do not hide those failures.
+
+The implementation plan should use these existing entry points, extended with the new focused tests:
+
+```bash
+pnpm --filter @carbon/config build
+pnpm --dir apps/erp exec vitest run app/modules/accounting/accounting.periods.test.ts app/modules/accounting/ui/Reports/executivePnl.test.ts app/modules/accounting/ui/Reports/pivotData.test.ts
+pnpm --filter @carbon/ee exec vitest run src/accounting/core/document-costing.test.ts src/accounting/providers
+deno test --no-lock --config packages/database/supabase/functions/deno.json packages/database/supabase/functions/post-payment/post-payment.test.ts packages/database/supabase/functions/post-memo/post-memo.test.ts
+pnpm run generate:types
+pnpm exec turbo run typecheck --filter=erp --filter=@carbon/ee --filter=@carbon/database
+pnpm db:check:datasets
+pnpm db:check:backups
+```
+
+Apply newly written migrations to the authorized local stack before generating types and running schema-dependent gates; never rebuild/reset the database to test this work. Run scoped Biome validation and translation checks for changed UI/locale files. Exercise a complete invoice → payment/credit → report → void sequence against the running app when browser verification is authorized. Fixing tests that currently assert the wrong FX convention requires new economic expectations, not simply changing their arithmetic operator.
+
+The plan records the actual implementation commits and verification results. Local numerical, transaction, SQL, provider-payload and typechecking gates have passed; connected-provider acceptance remains a separate verification boundary.
+
+## Verification limits and follow-up work
+
+- Local provider tests prove payload amounts, account mapping, native tax, and
+ retries through the production fetch/map paths. They do not prove a connected
+ provider accepted the payload. Confirm the Rillet bill rate direction and QBO
+ US tax-catalog compatibility in provider sandboxes before enabling those paths.
+ Rillet AR_ONLY does not expose a request FX snapshot; its base translation is
+ provider-owned.
+- Memo applications retain the agreed GL-neutral design. Changing defaults between
+ invoice and memo posting can leave offsetting balances in their original control
+ accounts even though the aggregate historical-control tie-out is correct.
+- Actual direct fixed-asset invoice void reverses the invoice journal but leaves
+ the asset acquisition state Active. This existing lifecycle gap is outside this
+ posting/FX/consolidation correction and needs a separate fixed-asset void design.
+
+## Risks
+
+| Risk | Severity | Mitigation |
+| --- | --- | --- |
+| Shipping split changes row counts and downstream metadata | High | Test every sales branch, fixed-asset proceeds, dimensions, per-trade IC captures, and exact reversals. |
+| Only some FX consumers adopt the new contract | High | Deliver invoice/payment/memo/report/provider normalization together; cover both read and write boundaries with non-identity fixtures. |
+| Previous credit is silently valued at the applying payment's rate | High | Persist original funding attribution, release its original carrying amount, and test concurrent/partial/void cases. |
+| Custom account numbering defeats migration or subsidiary creation | Medium | Group-scoped semantic resolution, collision-safe numbering, idempotency, and existing-group seed tests. |
+| Rounding masks a real imbalance | High | Retain named precision policies, reconcile component totals, and distinguish deterministic rounding residue from economic FX. |
+| Corrected CTA leaf leaves report totals stale | High | Apply through a shared service path with final rollups and identical CSV rows. |
+| Accounting has no users is an assumption, not a production-data audit | Low for this design | User explicitly accepted this premise. Build no legacy migration machinery and perform no data deletion as part of this spec task. |
+
+## Open Questions
+
+All design questions are resolved; unchecked boxes above are implementation acceptance criteria.
+
+- [x] Where should customer shipping post? — **User:** add a shipping-revenue default account column, create an account under Revenue, and backfill defaults. Use `salesShippingRevenueAccount`; 4040 is the next free stock revenue number verified in current seeds.
+- [x] How should old accounting errors be migrated? — **User:** “we can assume that no one is use accounting yet and just fix it.” Correct the contract directly; omit historical restatement, calculation versions, and open-balance cutover tooling.
+- [x] Are France/e-invoicing included? — **User:** explicitly excluded; focus on the three selected defects.
+- [x] Which monetary fields are base versus foreign? — **Code/research:** retain base invoice views/settlements, document-currency payment/memo totals, and foreign-per-base transaction rates. Preserve the independently defined target-per-source consolidation quotation.
+- [x] Do we need a broader tax, cross-currency, refund, or consolidation subsystem? — **Code/research and selected scope:** no. Separate existing sales components, correct currently representable settlement math, refuse unsupported currency combinations, and fix CTA through current reporting paths. Existing memo rate restrictions and provider capability gates remain.
+- [x] How do prior overpayments retain their rate and exact document amount? — **Code-derived decision:** extend the existing settlement with original-payment attribution and document principal, split funding rows, and release recorded carrying value. Separate source/base amounts prevent a proven large-rate rounding loss. Source and target calculations also retain remaining booked base independently; a final application takes the residual carrying value, so repeated rounded releases reconcile to the original posting. No separate credit ledger or historical migration framework.
+
+## Changelog
+
+- 2026-09-07: Created from the verified accounting audit and primary-source research. Recorded the user's shipping-account/backfill decision, explicit exclusion of France/e-invoicing, and no-accounting-users assumption. Resolved denominations, prior-credit funding, tax/shipping separation, provider boundaries, CTA arithmetic/mapping/rollups, and numerical acceptance criteria. Implementation remains unstarted.
+- 2026-09-07: Linked the 18-task implementation plan. Clarified positive document remainders below base rounding precision, source-only terminal settlements, provider-native shipping/tax mappings, and the documented Rillet AR_ONLY FX limitation. These clarify the corrected contract; no implementation or migration has run.
+
+- 2026-09-08: Implemented the 18-task plan locally. Shipping defaults/backfill, sales components, base purchase costs, exact document funding and original controls, provider boundaries, AR/AP cutoffs and consolidation CTA are covered by committed regressions. Verification includes 27 repository test tasks, 78 ERP payment cases, 84 live SQL report cases, independent transaction/concurrency tests, scoped typechecks, four datasets, backup compatibility, and actual browser/HTTP workflows. Browser testing also corrected payment currency formatting and manual partial-document inference. Provider acceptance and the separate fixed-asset void lifecycle remain the explicit follow-ups above. No production deployment or database reset occurred.
diff --git a/.claude/rules/accounting-sync-handlers.md b/.claude/rules/accounting-sync-handlers.md
index f12ebb6709..8b33f92764 100644
--- a/.claude/rules/accounting-sync-handlers.md
+++ b/.claude/rules/accounting-sync-handlers.md
@@ -121,7 +121,12 @@ into Carbon as `payment` + `invoiceSettlement` rows that close the
to Carbon's GL** — no double-count because `documents`-mode `Payment` journals are
DOC_BACKED-excluded from outbound push (the payment journal never re-posts to the
provider). `getSettledInvoiceStatus` is retained for tests only (status is
- view-derived).
+ view-derived). Provider-omitted rates remain `null` until authoritative company
+ and currency reads confirm identity; foreign payments require a valid snapshot.
+ Inbound payment amounts/source principal stay in document currency, while
+ target principal is base. Outbound prior-credit-funded payments are rejected
+ before provider writes because the existing provider cash endpoints cannot
+ represent those allocations.
- Provider syncers: `providers/{rillet,quickbooks-online,xero}/entities/payment.ts`.
Composite entity-id convention: AR = `<documentRemoteId>:<paymentRemoteId>` (no
prefix, back-compat), AP = `bill:<billRemoteId>:<paymentRemoteId>`.
@@ -155,8 +160,13 @@ a later pull no-ops. `supportsPaymentPush` gates the whole thing — **Rillet, X
AND QBO all set it true** (2026-08-14 parity). The capability set
`PAYMENT_PUSH_PROVIDERS` (`core/payment-syncer.ts`, must stay in sync with the
syncer flags) is what the reconcile executor and outbound sweep read instead of the
-old `providerId === "rillet"` literal. v1 is single-settlement, base-currency, no
-discount, no void-echo — everything else parks as Skipped. The paid date goes
+old `providerId === "rillet"` literal. Push validation controls supported
+currency, funding and discount shapes; unsupported payments park as Skipped.
+Rillet supports native voids for Carbon-origin payments: every persisted mapping
+under the payment's single/fan-out identity is deleted remotely, then marked
+`metadata.voided=true` in one local transaction. Mapping identities survive;
+404 means the desired deletion already happened, while provider refusals remain
+visible failures. Pulled/provider-origin payments never echo deletion. The paid date goes
through `toPostingDateString` (Kysely's pg driver returns DATE columns as JS
`Date`s; a bare `.slice` crashed the push). Provider adapters (`pushRemotePayment`):
**Rillet** `createInvoicePayment`/`createBillPayment` (`POST /{invoices,bills}/{id}/payments`,
@@ -176,28 +186,40 @@ removed v2 engine spec; the behavior is documented in this section — see git f
## Document representation model (bills, invoices, items)
-Every AR/AP **document** Carbon pushes reproduces its Carbon posting journal, so
-the provider's GL for that document equals Carbon's. Spec:
+AR/AP **documents** preserve Carbon's component amounts and account effects.
+Base-currency GL parity also requires the provider to accept Carbon's FX snapshot.
+Rillet uses REVENUE_RECOGNITION_ONLY invoices with a fixed rate and same-day
+recognition; AR_ONLY ignores the invoice rate and initially credits deferred
+revenue, so it cannot mirror Carbon's posting. Spec:
`.ai/specs/implemented/2026-08-05-accounting-document-representation.md`.
- **AP bills = account-costed replay of the posted "Purchase Invoice" journal**,
NOT the item's account. `core/document-costing.ts` is the shared core:
- `loadBillCostingLines(db, { companyId, billId, payablesAccountId })` reads the
+ `loadBillCostingLines(db, { companyId, billId })` reads the
posted journal (`journal.sourceType='Purchase Invoice'`, `status='Posted'`),
- drops the AP control line, and returns base-currency debit-signed
- `CostingLine[]` (+ `currencyCode`/`exchangeRate`). Item labels are joined via
+ excludes original AP/IC control rows using `classifyAccountingPostingRole` from
+ `@carbon/utils` (never today's payables default), and returns base-currency debit-signed
+ `CostingLine[]` (+ `currencyCode`/`exchangeRate`, document total, base currency and precision). Item labels are joined via
`journalLine.documentLineReference` (`purchase-invoice:<purchaseOrderLineId>`
→ `purchaseOrderLine.itemId` → `item`); direct no-PO / variance lines have
- `sourceItem: undefined`. `toTransactionCurrencyLines(lines, exchangeRate)`
- converts to the invoice's transaction currency (÷ rate, residue into the
- largest-|amount| line; rate 1 = pass-through). The item is a **description
+ `sourceItem: undefined`. `toTransactionCurrencyLines(lines, {exchangeRate, documentTotal, decimalPlaces})`
+ multiplies base values by the foreign-per-base rate, rounds at document
+ currency precision, and reconciles only a permitted rounding residual to the
+ largest absolute line; its storage envelope derives from shared `SCALE`.
+ Identity conversion also rounds; signed PPV is retained. The item is a **description
label only** (`costingLineItemLabel`). Bill lines are **tax-neutral** (the
purchase posting folds tax into cost): Rillet no `tax_rate`, QBO no
`TxnTaxDetail`, Xero `TaxType: "NONE"`. FX bills pin the provider rate
- (Rillet `exchange_rate`, QBO `CurrencyRef`+`ExchangeRate`, Xero `CurrencyRate`).
+ (Rillet named `exchange_rate` object, QBO `CurrencyRef` + reciprocal
+ `ExchangeRate = 1/r`, Xero `CurrencyRate = r`, including foreign 1:1 snapshots).
+ Rillet's directed pair is document currency → subsidiary base currency at
+ `1/r`, not Carbon's base → document convention. Foreign1:1 must stay explicit.
+ This direction is verified against the sandbox's independent journal report.
Every bill syncer has a posted-status `shouldSync` (Draft excluded — no
- journal to replay). Unmapped/account-less/no-journal lines throw the
- structured `UNMAPPED_ACCOUNTS` Warning.
+ journal to replay). Missing original journal/control/account metadata throws
+ the structured `UNMAPPED_ACCOUNTS` Warning before numeric reconciliation.
+ A genuine costing amount discrepancy remains a failure. Provider builders
+ accept costing-only rows and do not repeat the AP filter.
- QBO bill emits `AccountBasedExpenseLineDetail` from a NEW bill-only builder
(`buildQboBillLines`); it no longer uses the shared `buildQboExpenseLines`
or `ensureDependencySynced("item")`. Xero bill uses `buildXeroBillLineItems`.
@@ -205,11 +227,58 @@ the provider's GL for that document equals Carbon's. Spec:
QBO/Xero substitute it). Account codes resolve through the shared
`loadAccountCodesById` (Xero) / `loadQboAccountRefsById` (QBO) /
`loadRilletAccountCodesById` (Rillet).
-- **AR invoices = item-referenced to the item's REVENUE account**
- (`accountDefault.salesAccount` → the account-mapping code/ref — the same
- resolution for Rillet product `account_code`, QBO `IncomeAccountRef`, Xero
- invoice `AccountCode`), NOT the journal line and NOT the blunt
- `defaultSalesAccountCode`. COGS stays on the pushed `Sales Shipment` journal.
+- **AR invoices preserve separate sales, shipping and native tax components.**
+ `core/sales-invoice-source.ts` is the single typed batch loader for all three
+ invoice adapters: authoritative view totals, add-ons, line/header shipping,
+ group-scoped currency metadata and the original posted Shipping Revenue
+ account. `core/sales-document-components.ts` shares the internal posting
+ breakdown, converts base amounts once and reconciles document rounding
+ through `distributeRoundingResidual` (`@carbon/utils`) — **largest remainder,
+ one minor unit per component**, ordered by component id so an exact tie
+ resolves the same way whatever order the lines arrive in. Do NOT go back to
+ concentrating the residual on a single component: that breaks the component's
+ own percent/amount pair, and QBO's `tax = net × percent` preflight
+ (`invoice-tax.ts`) then refuses the invoice with a message blaming the
+ customer's tax configuration, which they cannot act on. A component's unit
+ price is DERIVED from its reconciled net when the stored `convertedUnitPrice`
+ mirror and the converted extension straddle a rounding tie (the two are
+ rounded on independent float paths); it still refuses when no representable
+ price can reproduce the net, which is a real quantity/total contradiction.
+ Original journal reads scope company, document, source type and Posted
+ status; the shared role selector excludes VOID descriptions. Missing or
+ ambiguous original shipping accounts refuse sync before dependency writes.
+ Changing defaults after posting cannot change the account used on retry.
+ Merchandise and add-ons retain the item's existing sales mapping. QBO and
+ Rillet provision reusable service/product helpers under `shippingItem`, keyed
+ by the original shipping account (Rillet also includes base currency).
+ Tax appears once through native provider fields; COGS stays on the pushed
+ `Sales Shipment` journal.
+ - Xero sends one monetary unit per component, keeping original quantity and
+ unit price in Description. This preserves net and native tax for bulk
+ quantities and fine unit prices. Actual invoice/bill POSTs use `unitdp=4`;
+ amounts that cannot be represented at Xero's two-decimal monetary boundary
+ are refused before document writes rather than rounded away. Tax magnitude
+ cannot exceed the monetary line unit; exotic/negative taxable adjustments
+ still need provider acceptance. [Xero rounding contract](https://developer.xero.com/documentation/guides/how-to-guides/rounding-in-xero/).
+ CurrencyRate is omitted only for identical currencies; foreign 1:1 stays
+ explicit. Preflight and mocked transports do not prove returned-provider
+ totals; connected acceptance must compare those independently.
+ - QBO US line `TAX`/`NON` values are documented protocol markers, so an
+ untaxed US invoice does not require catalog marker rows. Nonzero US
+ transaction tax rates and all non-US line codes still resolve from the
+ real active catalog; missing/ambiguous configuration raises
+ `UNMAPPED_TAX_CODES` before dependencies. Failed catalog reads evict the
+ cached promise so another invoice can retry. [Intuit SDK tax contract](https://intuit.github.io/QuickBooks-V3-PHP-SDK/quickstart.html#constructing-entities-with-tax).
+ - Rillet REVENUE_RECOGNITION_ONLY accepts the same directed fixed rate as bills.
+ Each item has a DAILY revenue period beginning and ending on Carbon's
+ posting date, also used as the remote invoice/FX date. The interim
+ deferred-revenue entries net to zero and recognition
+ credits the mapped revenue account; shipping retains its original-account
+ override. Native invoice/bill DELETE handles Carbon Voided status before
+ the mapped-create idempotency shortcut. Reconciliation and the outbound
+ sweep include mapped voided documents/payments, and mapping tombstones stop
+ repeated deletes. Compare independent remote GL, including recognition
+ and reversal, instead of treating create HTTP200 as accounting parity.
- **Provider items are non-tracked** so the provider never posts inventory
(bills) or COGS (invoices): Xero pushes `IsTrackedAsInventory: false` on
create and OMITS the flag on update (Xero rejects untracking an item with
diff --git a/.claude/rules/numeric-precision.md b/.claude/rules/numeric-precision.md
index 98e200a056..d69cb9a00d 100644
--- a/.claude/rules/numeric-precision.md
+++ b/.claude/rules/numeric-precision.md
@@ -1,6 +1,6 @@
paths:
- "packages/database/supabase/functions/shared/precision.ts"
- - "packages/utils/src/math.ts"
+ - "packages/utils/src/precision.ts"
- "packages/utils/src/format.ts"
- "packages/checks/src/conformance/no-derived-percent-column.ts"
- "packages/checks/src/conformance/no-raw-rounding.ts"
@@ -16,24 +16,43 @@ paths:
The numeric standard for every price, rate, quantity, and amount in Carbon.
Source of truth: `packages/database/supabase/functions/shared/precision.ts`
(Deno-side because the edge runtime only mounts `supabase/functions/`;
-`packages/utils/src/math.ts` re-exports it for Node/browser — that relative
+`packages/utils/src/precision.ts` re-exports it for Node/browser — that relative
import is BY DESIGN, not an import to "fix").
+## Accounting currency boundaries
+
+Document `exchangeRate` is foreign units per company base unit. Use
+`shared/accounting-currency.ts` (`@carbon/utils` re-export):
+`toBaseAmount(document, rate)` divides and rounds to internal precision;
+`toDocumentAmount(base, rate, currency.decimalPlaces)` multiplies and rounds to
+settlement precision. Identity currency still rounds at its configured decimals.
+
+Sales line amounts and generated unprefixed purchase amounts are already base.
+Purchase `supplier*` amounts, payment cash/fees, and memo amounts are document
+currency. Never convert a generated base value a second time.
+
+`invoiceSettlement.appliedAmount`, discounts, write-offs, and stored FX are base;
+`sourceAmount` is exact source-document principal. `sourcePaymentId` identifies
+prior credit; `paymentId` owns the applying payment. Funding tracks document units
+and remaining booked base independently, releasing the exact carrying remainder
+on the final application. A positive document remainder remains payable when its
+base amount rounds to zero. Do not reconstruct source units from rounded base or
+use a fixed base-currency dust threshold for completion. Currency precision comes
+from the company's group-scoped currency configuration.
+
## Two storage scales
| Class | Scale | Examples |
|---|---|---|
| Internal values | `SCALE = 5` | per-unit prices, rates (0–1 fractions), quantities, GL journal lines, exchange rates |
-| Settlement values | `currency.decimalPlaces` (DB column — authoritative over Intl/CLDR) | invoice balance/amountDue, applied payment amounts, document totals, tax amounts |
+| Settlement values | `currency.decimalPlaces` (DB column — authoritative over Intl/CLDR) | source-document principal, cash/memo totals, document totals and document tax |
-Settlement values are rounded to the currency's decimals at the boundary that
-produces them — the applied amounts a user enters, and every amount serialized
-to an external system. The columns themselves are bare NUMERIC and an invoice
-`balance` is read from a view rather than written by `post-payment`, so storage
-does not enforce this; the rounding does. Only internal GL journal lines carry
-scale 5. Invoice paid-status dust forgiveness (`INVOICE_DUST_THRESHOLD = 0.01`,
-`invoicing.models.ts`) and post-payment's `0.0001` unapplied-dust band are
-deliberate business behavior layered on top.
+Document principal is rounded at its currency boundary. Base settlement relief
+and GL amounts use internal precision. Invoice-view `balance` converts the exact
+remaining document amount back to base without rounding away a payable remainder;
+report carrying values separately retain the original booked amount. Storage
+columns are bare NUMERIC, so callers enforce these boundaries. Payment completion
+uses document units, with no fixed base-currency dust forgiveness.
## Three-boundary rule
@@ -53,13 +72,25 @@ full float precision; Postgres computes derived values (generated columns);
- `deriveRate(amount, subtotal)` — the inverse of `applyRate`: recover the rate
an absolute amount implies, rounded to internal scale. The ONE place a rate is
derived from an amount; a bare `amount / subtotal` at a call site is a bug.
+- `distributeRoundingResidual(exactValues, target, scale)` — round N parts so
+ they sum EXACTLY to an authoritative total, moving at most ONE minor unit per
+ part (largest remainder: parts rounded furthest down get the surplus first,
+ ties by index). Use this ANY time a document total is apportioned across
+ components. Rounding parts independently leaves a residual of up to N/2 minor
+ units, and **concentrating that residual on one part is a real defect, not a
+ cosmetic one**: it breaks that part's own relative/absolute pair, so a tax line
+ no longer matches its `taxPercent` and QuickBooks refuses the whole invoice
+ (`providers/quickbooks-online/entities/invoice-tax.ts` re-derives
+ `round(net × percent)` within one minor unit). It also produced a negative tax
+ on positive revenue, which Xero accepts and posts. Refuses a residual larger
+ than one unit per part — that is a genuine disagreement, not rounding.
- `equals(a, b)` / `EPSILON = 1e-6` — the one float-noise tolerance.
- `assertBalanced(debits, credits, tolerance = EPSILON, label = "Journal")` —
ledger invariant. Pass a `label` so the refusal names the journal and its
currency (`"Payment journal (base currency)"`).
- `tolerance` is a BUSINESS refusal threshold: payment/memo posting passes
- `0.01`, manual journals and period close use `0.001`. Do not unify them and
- do not tighten to EPSILON — FX journals carry genuine sub-cent residuals.
+ Payment journals reconcile recorded FX/carrying residuals and use `EPSILON`;
+ memo posting retains `0.01`, and manual journals/period close retain `0.001`.
+ Do not change another posting path's threshold without its own numerical proof.
**No scale literals**: a numeric literal as the `scale` argument outside
`precision.ts` is a violation — internal values use the default, settlement
diff --git a/.github/workflows/check.yml b/.github/workflows/check.yml
index 89e350e01e..fcda2410f5 100644
--- a/.github/workflows/check.yml
+++ b/.github/workflows/check.yml
@@ -171,6 +171,37 @@ jobs:
- run: pnpm test
+ edge-functions:
+ name: Edge Functions
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ with:
+ # This job runs PR-authored code. actions/checkout otherwise leaves
+ # GITHUB_TOKEN in .git/config, where a test could read and exfiltrate
+ # it. Nothing here needs to talk to git after checkout.
+ persist-credentials: false
+ - uses: denoland/setup-deno@v2
+ with:
+ # Pin the major the functions are written against; the Supabase edge
+ # runtime is Deno, so this suite needs Deno rather than Node/vitest.
+ deno-version: v1.x
+
+ # Runs with --no-check: `packages/database/tsconfig.json` only covers
+ # `src` and `supabase/functions/lib/postgres/**`, so most of this tree is
+ # not typechecked by tsgo either, and `deno check` currently reports 8
+ # pre-existing errors (kysely/deno-postgres Pool typings + a TS2589).
+ # Closing that gap is separate work — tracked in
+ # .ai/plans/2026-09-09-accounting-nuclear-review-fixes.md.
+ #
+ # The regressions that need a real Postgres SKIP here (see `databaseTest`
+ # in post-payment/payment-test-fixture.ts), so this run needs NO Deno
+ # permissions at all — no env, net, read or write. `deno task test:db`
+ # is the local variant that grants the four the pg driver needs.
+ - name: Test
+ working-directory: packages/database/supabase/functions
+ run: deno task test
+
audit:
name: Audit
runs-on: ubuntu-latest
diff --git a/apps/erp/app/components/Layout/Navigation/PrimaryNavigation.tsx b/apps/erp/app/components/Layout/Navigation/PrimaryNavigation.tsx
index 9693224df1..f1598cc109 100644
--- a/apps/erp/app/components/Layout/Navigation/PrimaryNavigation.tsx
+++ b/apps/erp/app/components/Layout/Navigation/PrimaryNavigation.tsx
@@ -127,7 +127,7 @@ const PrimaryNavigation = () => {
data-state={isOpen ? "expanded" : "collapsed"}
className={cn(
"bg-background py-2 group z-10 h-full w-full",
- "flex flex-col justify-between data-[state=expanded]:border-r data-[state=expanded]:border-border",
+ "flex flex-col justify-between",
"hide-scrollbar overflow-y-auto scrollbar-thin scrollbar-track-transparent scrollbar-thumb-accent"
)}
onMouseEnter={
diff --git a/apps/erp/app/components/Layout/Topbar/AskDocs.tsx b/apps/erp/app/components/Layout/Topbar/AskDocs.tsx
index 997c873d88..b57d04d625 100644
--- a/apps/erp/app/components/Layout/Topbar/AskDocs.tsx
+++ b/apps/erp/app/components/Layout/Topbar/AskDocs.tsx
@@ -18,7 +18,7 @@ export default function AskDocs() {
return (
<Button
aria-label="Question (⌘L)"
- variant="outline"
+ variant="ghost"
leftIcon={<LuCircleHelp />}
className="hover:scale-100"
onClick={() => toggleAgent()}
diff --git a/apps/erp/app/components/Layout/Topbar/Suggestion.tsx b/apps/erp/app/components/Layout/Topbar/Suggestion.tsx
index c8cf180d23..54d86cb980 100644
--- a/apps/erp/app/components/Layout/Topbar/Suggestion.tsx
+++ b/apps/erp/app/components/Layout/Topbar/Suggestion.tsx
@@ -138,7 +138,7 @@ const Suggestion = () => {
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
<Button
- variant="outline"
+ variant="ghost"
className="hover:scale-100"
leftIcon={<LuMegaphone />}
>
diff --git a/apps/erp/app/modules/accounting/AGENTS.md b/apps/erp/app/modules/accounting/AGENTS.md
index cca34e5874..4390313686 100644
--- a/apps/erp/app/modules/accounting/AGENTS.md
+++ b/apps/erp/app/modules/accounting/AGENTS.md
@@ -1,6 +1,6 @@
# Accounting Module
-Chart of accounts, journal entries, general ledger, fiscal periods, currencies, payment terms, cost centers, dimensions, financial reporting (trial balance, balance sheet, income statement), fixed assets with depreciation, intercompany transactions, and external accounting sync (Xero).
+Chart of accounts, journal entries, general ledger, fiscal periods, currencies, payment terms, cost centers, dimensions, financial reporting (trial balance, balance sheet, income statement), fixed assets with depreciation, intercompany transactions, and external accounting sync (Xero, QuickBooks Online, Rillet).
The reports hub lives inside the accounting module at `/x/accounting/reports` (with the module sidebar; single "Reports" sidebar item), while the report pages themselves are full-screen in their own namespace `apps/erp/app/routes/x+/reports+/` (`/x/reports/{balance-sheet,income-statement,executive-pnl,trial-balance,inventory-valuation}` — bare-outlet layout, no module sidebar; `/x/reports` redirects to the hub). Balance sheet and income statement are multi-period: a Columns filter (Monthly default / Quarterly / Yearly) buckets the selected range fiscal-aware via `computeReportPeriodBuckets` (`@carbon/utils`) and the `accountTreeBalancePeriodSeries` RPC returns per-bucket `balanceAtDate`/`netChange` in one snapshot-bounded journal scan. Trial balance stays single-period (Beginning/Debit/Credit/Ending derived from netChange by account class).
@@ -11,12 +11,15 @@ The **Executive P&L** (`executive-pnl.tsx`) shares the income statement's loader
## Key Domain Concepts
- **Chart of Accounts** — hierarchical account tree. Accounts have `class` (Asset/Liability/Equity/Revenue/Expense), `incomeBalance` (Balance Sheet/Income Statement), and `accountType`. Group accounts contain children; leaf accounts post transactions. Scoped by `companyGroupId`.
-- **Journal Entries** — double-entry bookkeeping in the `journal` table. `amount > 0` = debit, `amount < 0` = credit. Lines carry dimensions and cost center allocations. Statuses: Draft → Posted → Reversed.
+- **Journal Entries** — double-entry bookkeeping in the `journal` table. `amount` uses natural balances: positive Asset/Expense is debit; positive Liability/Equity/Revenue is credit. Convert by account class before summing debit-signed amounts. Lines carry dimensions and cost center allocations. Statuses: Draft → Posted → Reversed.
- **Fiscal Year Settings** — configurable start month for fiscal and tax years. Accounting periods auto-created via `getOrCreateAccountingPeriod`.
- **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 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`.
+- **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. Both halves of a trade record their matching amount in the trade's DOCUMENT currency rounded at internal `SCALE` — `calculateSalesIntercompanyAmount` (seller) and `round(intercompanyAmount)` (buyer). `generate_intercompany_matches` pairs them on exact NUMERIC equality with **no tolerance**, so rounding either half at settlement precision leaves every trade with sub-cent digits permanently `Unmatched` and eliminations never run. Investment/NCI and seller fixed-asset disposal (deferred gain) remain out of scope. See `.ai/specs/2026-08-17-intercompany-elimination-engine.md`.
+- **Currency translation / CTA** — `translateCompanyBalances` validates the source trial balance using natural debit/credit signs and positive finite pair rates. Missing rates fail explicitly. `applyCtaToReportPeriodSeriesForReport` resolves only the root company's CTA mapping through a server-only permission and company-group/root check; operating-company ledger reads remain RLS-scoped. The existing `applyCtaToReportPeriodSeries` service adds the calculated CTA once to the reporting root company's configured `currencyTranslationAccount`, validates its active Equity posting leaf, then rerolls intermediate groups and roots before filtering/export. Never identify CTA by account number. Financial report chart reads include inactive historical accounts and their ancestors; chart and balance RPC rows are fully paginated before calculation. Active-only filters belong to posting/configuration pickers. Balance RPC trees and period-close snapshots retain inactive posting leaves and ancestors. Report loaders reject company selections outside the available company group (404) before balance reads.
+- **Shipping revenue** — `accountDefault.salesShippingRevenueAccount` maps an active Revenue posting leaf distinct from Sales. New groups seed 4050 Shipping Revenue under Revenue; existing groups resolve a compatible leaf and backfill mappings. Nonzero invoice shipping requires a valid mapping; output tax posts separately to tax payable. The full defaults form validates once and saves both sections with one company-scoped `updateDefaultAccounts` UPDATE, so a failed mapping cannot half-save the form.
+- **Payments and refunds** — the customer/supplier determines AR/AP independently of cash direction. Customer Disbursements and supplier Receipts refund posted balance-reducing memos through `invoiceSettlement.targetMemoId`, using current cash only (no invoice targets, discounts, writeoffs, or prior credits). Ordinary payments retain invoice targets, memo-source funding, and prior cash credits. Memo availability subtracts effective source and target principal; an effective posted refund blocks memo voiding. Aging and tie-out RPCs sign unallocated refunds opposite ordinary payments and use the applying payment's cash direction for FX consumption. Target memos consume exact `sourceAmount` principal and `appliedAmount` carrying base. Unknown memo principal retains the existing exclusion contract; it is not reconstructed or raised as a report error. Payment/invoice application histories page all rows, including embedded parent statuses and refund labels, before totaling.
- **Net Income** — computed equity line on the balance sheet, never a posted account. Uses synthetic `NET_INCOME_ACCOUNT_ID` constant.
## Safety
@@ -43,8 +46,8 @@ The **Executive P&L** (`executive-pnl.tsx`) shares the income statement's loader
## Validation Commands
```bash
-pnpm --filter @carbon/erp typecheck
-pnpm --filter @carbon/erp test -- --testPathPattern=accounting
+pnpm exec turbo run typecheck --filter=erp
+pnpm --dir apps/erp exec vitest run app/modules/accounting
```
## Key Data Model
@@ -55,7 +58,7 @@ pnpm --filter @carbon/erp test -- --testPathPattern=accounting
| `journal` / `journalLine` | Double-entry transactions; lines carry dimension assignments |
| `journalLineDimension` | Dimension values assigned to journal lines |
| `accountingPeriod` | Fiscal periods. `closeStatus` (`periodCloseStatus`: Open→Locked→Closed lifecycle), `fiscalYear`/`periodNumber` (identity from the fiscal start month), `lockedAt`/`lockedBy`. Legacy `status` (Active/Inactive) is deprecated. |
-| `accountingPeriodBalance` | Cumulative per-account GL balance snapshots. `closeAccountingPeriod` calls `snapshotAccountingPeriodBalances` inside its close transaction (after the flip to Closed) to write them; `reopenAccountingPeriod` deletes them (`endingBalanceDate` ≥ period `endDate`) before flipping back to Open. Read by `accountTreeBalancesByCompany` (snapshot + delta; full-scan fallback when empty) and `accountTreeBalancePeriodSeries` (multi-period: base snapshot before the range start + one bounded scan bucketed by period ends; single uniform branch). Balance RPCs exclude Draft journals. |
+| `accountingPeriodBalance` | Cumulative per-account GL balance snapshots. `closeAccountingPeriod` calls `snapshotAccountingPeriodBalances` inside its close transaction (after the flip to Closed) to write them; `reopenAccountingPeriod` deletes them (`endingBalanceDate` ≥ period `endDate`) before flipping back to Open. Read by `accountTreeBalancesByCompany` (snapshot + delta; full-scan fallback when empty) and `accountTreeBalancePeriodSeries` (multi-period: base snapshot before the range start + one bounded scan bucketed by period ends; single uniform branch). Balance RPCs exclude Draft journals and retain inactive leaves/ancestors; the snapshot writer also includes inactive posting accounts. |
| `periodCloseTaskDefinition` / `periodCloseTask` | NetSuite-style close checklist: company-level task templates + per-period instances (seeded via `seed-company`) |
| `accountDefault` | Default GL account mappings (AR, AP, inventory, etc.) |
| `currency` / `currencyCode` | Per-group currency config (decimalPlaces, active, historicalExchangeRate); rates live in the global `exchangeRate` store + per-company `exchangeRateOverride` |
@@ -106,11 +109,11 @@ import { getExchangeRate, getPaymentTermsList, getDefaultAccounts } from "~/modu
- **purchasing** — purchase invoices post to AP; receipts create inventory GL entries
- **sales** — sales invoices post to AR; quotes use `getExchangeRate` for exchange rates
-- **inventory** — inventory movements create GL entries via posting groups
-- **items** — `itemPostingGroup` maps item categories to GL accounts
+- **inventory** — inventory movements resolve GL accounts through replenishment system and company raw-material/finished-goods defaults
+- **items** — `itemPostingGroup` supplies dimension metadata; company defaults resolve posting accounts
- **people** — employees used as dimension values; cost center assignments
## Rules References
-- `.claude/rules/accounting-sync-handlers.md` — Xero sync architecture, entity syncers, Inngest functions
+- `.claude/rules/accounting-sync-handlers.md` — provider sync architecture, entity syncers, Inngest functions
- `.claude/rules/fixed-asset-lifecycle.md` — asset statuses, depreciation methods, disposal flow
diff --git a/apps/erp/app/modules/accounting/accounting.defaults.test.ts b/apps/erp/app/modules/accounting/accounting.defaults.test.ts
new file mode 100644
index 0000000000..32c3b03bd4
--- /dev/null
+++ b/apps/erp/app/modules/accounting/accounting.defaults.test.ts
@@ -0,0 +1,316 @@
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import type { Database } from "@carbon/database";
+import type { SupabaseClient } from "@supabase/supabase-js";
+import { describe, expect, it, vi } from "vitest";
+
+vi.mock("~/modules/settings", () => ({ getNextSequence: vi.fn() }));
+vi.mock("@carbon/glossary", () => ({ terms: {}, glossaryEntries: () => [] }));
+vi.mock("@carbon/auth", () => ({
+ assertIsPost: () => undefined,
+ getMESUrl: () => "http://localhost",
+ getAppUrl: () => "http://localhost",
+ CARBON_API_URL: "http://localhost",
+ error: (cause: unknown, message: string) => ({ cause, message }),
+ success: (message: string) => ({ message })
+}));
+vi.mock("@carbon/auth/auth.server", () => ({ requirePermissions: vi.fn() }));
+vi.mock("@carbon/auth/session.server", () => ({
+ flash: vi.fn(async () => ({}))
+}));
+vi.mock("@carbon/react", () => ({
+ ScrollArea: () => null,
+ VStack: () => null
+}));
+vi.mock("@carbon/form", () => ({
+ validator: (schema: {
+ safeParse: (input: unknown) => {
+ success: boolean;
+ data?: unknown;
+ error?: unknown;
+ };
+ }) => ({
+ validate: async (form: FormData) => {
+ const parsed = schema.safeParse(Object.fromEntries(form));
+ return parsed.success ? { data: parsed.data } : { error: parsed.error };
+ }
+ }),
+ validationError: (error: unknown) => ({ error })
+}));
+vi.mock("@lingui/core/macro", () => ({
+ msg: (strings: TemplateStringsArray) => ({ id: strings.join("") })
+}));
+vi.mock("~/hooks", () => ({ useRouteData: vi.fn() }));
+vi.mock("~/modules/accounting/ui/AccountDefaults", () => ({
+ AccountDefaultsForm: () => null
+}));
+vi.mock("~/modules/accounting", async () => ({
+ ...(await import("./accounting.ee.service")),
+ ...(await import("./accounting.models"))
+}));
+
+import {
+ getDefaultAccounts,
+ updateDefaultAccounts
+} from "./accounting.ee.service";
+import {
+ defaultAccountValidator,
+ defaultIncomeAcountValidator
+} from "./accounting.models";
+
+const income = Object.fromEntries(
+ Object.keys(defaultIncomeAcountValidator.shape).map((key) => [
+ key,
+ `${key}-id`
+ ])
+);
+const allAccounts = Object.fromEntries(
+ Object.keys(defaultAccountValidator.shape).map((key) => [key, `${key}-id`])
+);
+const defaults = {
+ ...allAccounts,
+ companyId: "company",
+ salesAccount: "sales",
+ salesShippingRevenueAccount: "shipping"
+};
+const shipping = {
+ id: "shipping",
+ companyGroupId: "group",
+ active: true,
+ isGroup: false,
+ class: "Revenue",
+ incomeBalance: "Income Statement"
+};
+
+function database(account = shipping) {
+ const rows: Record<string, Record<string, unknown>[]> = {
+ company: [{ id: "company", companyGroupId: "group" }],
+ accountDefault: [{ ...defaults }],
+ account: [account]
+ };
+ const writes = vi.fn();
+ const client = {
+ from(table: string) {
+ const filters: [string, unknown][] = [];
+ let values: Record<string, unknown> | undefined;
+ const result = () => {
+ const matched = rows[table].filter((row) =>
+ filters.every(([key, value]) => row[key] === value)
+ );
+ if (values) {
+ writes(table, values);
+ for (const row of matched) Object.assign(row, values);
+ }
+ return { data: values ? null : (matched[0] ?? null), error: null };
+ };
+ const query = {
+ select: () => query,
+ eq: (key: string, value: unknown) => {
+ filters.push([key, value]);
+ return query;
+ },
+ update: (input: Record<string, unknown>) => {
+ values = input;
+ return query;
+ },
+ single: async () => result(),
+ maybeSingle: async () => result(),
+ then: (resolve: (value: ReturnType<typeof result>) => unknown) =>
+ Promise.resolve(result()).then(resolve)
+ };
+ return query;
+ }
+ } as unknown as SupabaseClient<Database>;
+ return { client, writes, rows };
+}
+
+function payload(overrides: Record<string, string> = {}) {
+ return {
+ ...defaultAccountValidator.parse({
+ ...allAccounts,
+ salesAccount: "sales",
+ ...overrides
+ }),
+ companyId: "company",
+ updatedBy: "user"
+ };
+}
+
+describe("shipping revenue defaults", () => {
+ it("the real defaults action rejects an invalid shipping mapping before either section writes", async () => {
+ const { client, writes } = database({ ...shipping, active: false });
+ vi.mocked(requirePermissions).mockResolvedValue({
+ client,
+ companyId: "company",
+ userId: "user"
+ } as never);
+ const body = new FormData();
+ for (const field of Object.keys(defaultAccountValidator.shape))
+ body.set(field, `${field}-id`);
+ body.set("salesAccount", "sales");
+ body.set("salesShippingRevenueAccount", "shipping");
+ body.set("intent", "all");
+ const { action } = await import("~/routes/x+/accounting+/defaults");
+ await action({
+ request: new Request("http://localhost/x/accounting/defaults", {
+ method: "POST",
+ body
+ }),
+ params: {},
+ context: {}
+ } as never);
+ expect(writes).not.toHaveBeenCalled();
+ });
+ it("preserves the incoming shipping field and rejects present empty values", () => {
+ expect(
+ defaultIncomeAcountValidator.parse({
+ ...income,
+ salesShippingRevenueAccount: "shipping"
+ }).salesShippingRevenueAccount
+ ).toBe("shipping");
+ expect(
+ defaultIncomeAcountValidator.safeParse({
+ ...income,
+ salesShippingRevenueAccount: ""
+ }).success
+ ).toBe(false);
+ });
+
+ it("accepts an older payload without shipping and preserves the stored mapping", async () => {
+ const { salesShippingRevenueAccount: _, ...older } = allAccounts;
+ const parsed = defaultAccountValidator.parse({
+ ...older,
+ salesAccount: "sales"
+ });
+ const { client, writes } = database();
+ const result = await updateDefaultAccounts(client, {
+ ...parsed,
+ companyId: "company",
+ updatedBy: "user"
+ });
+ expect(result.error).toBeNull();
+ expect(writes).toHaveBeenCalledOnce();
+ expect(
+ (await getDefaultAccounts(client, "company")).data
+ ?.salesShippingRevenueAccount
+ ).toBe("shipping");
+ });
+
+ it("saves and reloads a valid account selected from the company group", async () => {
+ const { client } = database({ ...shipping, id: "custom-shipping" });
+ const result = await updateDefaultAccounts(
+ client,
+ payload({ salesShippingRevenueAccount: "custom-shipping" })
+ );
+ expect(result.error).toBeNull();
+ expect(
+ (await getDefaultAccounts(client, "company")).data
+ ?.salesShippingRevenueAccount
+ ).toBe("custom-shipping");
+ });
+
+ it.each([
+ ["missing", { id: "other" }],
+ ["foreign group", { companyGroupId: "other" }],
+ ["inactive", { active: false }],
+ ["group account", { isGroup: true }],
+ ["expense", { class: "Expense" }],
+ ["balance sheet", { incomeBalance: "Balance Sheet" }]
+ ])("rejects %s before any write", async (_, invalid) => {
+ const { client, writes } = database({
+ ...shipping,
+ ...(invalid as object)
+ });
+ const result = await updateDefaultAccounts(
+ client,
+ payload({ salesShippingRevenueAccount: "shipping" })
+ );
+ expect(result.error).toBeTruthy();
+ expect(writes).not.toHaveBeenCalled();
+ });
+
+ it("rejects the effective Sales account even when shipping was omitted", async () => {
+ const { client, writes } = database();
+ const { salesShippingRevenueAccount: _, ...older } = allAccounts;
+ const result = await updateDefaultAccounts(client, {
+ ...defaultAccountValidator.parse({
+ ...older,
+ salesAccount: "shipping"
+ }),
+ companyId: "company",
+ updatedBy: "user"
+ });
+ expect(result.error).toBeTruthy();
+ expect(writes).not.toHaveBeenCalled();
+ });
+
+ it("refuses an unknown company without writing another company's defaults", async () => {
+ const { client, writes } = database();
+ const result = await updateDefaultAccounts(client, {
+ ...payload({ salesShippingRevenueAccount: "shipping" }),
+ companyId: "other"
+ });
+ expect(result.error).toBeTruthy();
+ expect(writes).not.toHaveBeenCalled();
+ });
+});
+
+describe("combined defaults action", () => {
+ async function submit(client: SupabaseClient<Database>) {
+ vi.mocked(requirePermissions).mockResolvedValue({
+ client,
+ companyId: "company",
+ userId: "user"
+ } as never);
+ const body = new FormData();
+ for (const field of Object.keys(defaultAccountValidator.shape))
+ body.set(field, `${field}-new`);
+ body.set("salesAccount", "sales");
+ body.set("salesShippingRevenueAccount", "shipping");
+ body.set("intent", "all");
+ const { action } = await import("~/routes/x+/accounting+/defaults");
+ return action({
+ request: new Request("http://localhost/x/accounting/defaults", {
+ method: "POST",
+ body
+ }),
+ params: {},
+ context: {}
+ } as never);
+ }
+
+ it("saves the full form as one statement", async () => {
+ const { client, writes } = database();
+ await expect(submit(client)).rejects.toMatchObject({ status: 302 });
+ expect(writes).toHaveBeenCalledOnce();
+ expect(writes).toHaveBeenCalledWith(
+ "accountDefault",
+ expect.objectContaining({
+ companyId: "company",
+ salesShippingRevenueAccount: "shipping",
+ receivablesAccount: "receivablesAccount-new"
+ })
+ );
+ });
+
+ it("leaves both sections unchanged when the mapping is rejected", async () => {
+ const { client, writes, rows } = database({ ...shipping, active: false });
+ const original = structuredClone(rows.accountDefault);
+ await submit(client);
+ expect(writes).not.toHaveBeenCalled();
+ expect(rows.accountDefault).toEqual(original);
+ });
+
+ it("shows the actual shipping mapping validation error", async () => {
+ vi.mocked(flash).mockClear();
+ const { client } = database({ ...shipping, active: false });
+ await submit(client);
+ expect(flash).toHaveBeenCalledWith(
+ expect.any(Request),
+ expect.objectContaining({
+ message:
+ "Shipping revenue must be an active Revenue leaf account in this company group"
+ })
+ );
+ });
+});
diff --git a/apps/erp/app/modules/accounting/accounting.ee.server.ts b/apps/erp/app/modules/accounting/accounting.ee.server.ts
index 80b0f3bf34..d1870b6e2b 100644
--- a/apps/erp/app/modules/accounting/accounting.ee.server.ts
+++ b/apps/erp/app/modules/accounting/accounting.ee.server.ts
@@ -1,3 +1,4 @@
+import { requirePermissions } from "@carbon/auth/auth.server";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
import type { Database } from "@carbon/database";
import type { Kysely, KyselyDatabase } from "@carbon/database/client";
@@ -6,6 +7,7 @@ import type { ReportPeriodBucket } from "@carbon/utils";
import { toStoredAmount } from "@carbon/utils";
import type { SupabaseClient } from "@supabase/supabase-js";
import {
+ applyCtaToReportPeriodSeries,
getAccountLedger,
getAccountLedgerSummary,
getConsolidatedBalances,
@@ -13,6 +15,45 @@ import {
} from "./accounting.ee.service";
import { acquisitionLines } from "./accounting.utils";
+/** Resolve only the authorized group's root CTA configuration for reporting.
+ * Operating-company balances continue to use the loader's RLS client.
+ */
+export async function applyCtaToReportPeriodSeriesForReport(
+ request: Request,
+ reportingCompanyId: string,
+ args: Parameters<typeof applyCtaToReportPeriodSeries>[3]
+) {
+ const { client, companyGroupId } = await requirePermissions(request, {
+ view: "accounting",
+ role: "employee",
+ bypassRls: true
+ });
+ const root = await client
+ .from("company")
+ .select("id")
+ .eq("id", reportingCompanyId)
+ .eq("companyGroupId", companyGroupId)
+ .is("parentCompanyId", null)
+ .single();
+ if (root.error || !root.data) {
+ return {
+ data: null,
+ error: root.error ?? {
+ message:
+ "Reporting company must be the root of the authorized company group"
+ }
+ };
+ }
+ // Use the authenticated client returned above: API keys never gain service-role
+ // privileges, even if their request also supplies the bypassRls option.
+ return applyCtaToReportPeriodSeries(
+ client,
+ companyGroupId,
+ root.data.id,
+ args
+ );
+}
+
// 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
diff --git a/apps/erp/app/modules/accounting/accounting.ee.service.ts b/apps/erp/app/modules/accounting/accounting.ee.service.ts
index 4a3aeb3d7b..b898bbfb1e 100644
--- a/apps/erp/app/modules/accounting/accounting.ee.service.ts
+++ b/apps/erp/app/modules/accounting/accounting.ee.service.ts
@@ -1,6 +1,7 @@
import type { Database, Json } from "@carbon/database";
import { fetchAllFromTable, getCompanyTimeZone } from "@carbon/database";
import type { Kysely, KyselyDatabase } from "@carbon/database/client";
+import { fetchAll } from "@carbon/database/fetch-all";
import type { PeriodPostingSource, ReportPeriodBucket } from "@carbon/utils";
import {
datetime,
@@ -27,7 +28,7 @@ import type {
accountValidator,
costCenterValidator,
currencyValidator,
- defaultBalanceSheetAccountValidator,
+ defaultAccountValidator,
defaultIncomeAcountValidator,
depreciationMethods,
dimensionValidator,
@@ -258,8 +259,8 @@ export async function getFinancialStatementBalances(
.from("accounts")
.select("*")
.eq("companyGroupId", companyGroupId)
- .eq("active", true)
- .order("number", { ascending: true });
+ .order("number", { ascending: true })
+ .order("id", { ascending: true });
const balancesQuery = client.rpc("accountTreeBalancesByCompany", {
p_company_group_id: companyGroupId,
@@ -270,12 +271,18 @@ export async function getFinancialStatementBalances(
});
const [accountsResponse, balancesResponse] = await Promise.all([
- accountsQuery,
- balancesQuery
+ fetchAll<Database["public"]["Views"]["accounts"]["Row"]>(
+ () => accountsQuery
+ ),
+ fetchAll<
+ Database["public"]["Functions"]["accountTreeBalancesByCompany"]["Returns"][number]
+ >(() => balancesQuery.order("accountId", { ascending: true }))
]);
- if (accountsResponse.error) return accountsResponse;
- if (balancesResponse.error) return balancesResponse;
+ if (accountsResponse.error)
+ return { data: null, error: accountsResponse.error };
+ if (balancesResponse.error)
+ return { data: null, error: balancesResponse.error };
const balancesByAccountId = (
balancesResponse.data as unknown as (Transaction & { accountId: string })[]
@@ -360,6 +367,16 @@ export async function getAccountPeriodSeries(
companyGroupId: string,
companyId: string,
args: { start: string; periodEnds: string[] }
+) {
+ return accountPeriodSeriesQuery(client, companyGroupId, companyId, args);
+}
+
+// Keep the exported RPC response contract while report readers page the same query.
+function accountPeriodSeriesQuery(
+ client: SupabaseClient<Database>,
+ companyGroupId: string,
+ companyId: string,
+ args: { start: string; periodEnds: string[] }
) {
// Defined in migration 20260809151458_balance-rpc-period-series.sql.
// The contract on p_period_ends (sorted ascending, distinct, >= p_start) is
@@ -532,6 +549,132 @@ function rollUpTranslatedGroups<
});
}
+/** Apply report-only CTA to the reporting company's configured Equity account. */
+export async function applyCtaToReportPeriodSeries(
+ client: SupabaseClient<Database>,
+ companyGroupId: string,
+ reportingCompanyId: string,
+ args: {
+ accounts: ChartPeriodSeries[];
+ bucketKeys: string[];
+ ctaByBucket: Record<string, number>;
+ }
+): Promise<{
+ data: ChartPeriodSeries[] | null;
+ error: { message: string } | null;
+}> {
+ const defaults = await client
+ .from("accountDefault")
+ .select("currencyTranslationAccount")
+ .eq("companyId", reportingCompanyId)
+ .single();
+ if (defaults.error) return { data: null, error: defaults.error };
+ const accountId = defaults.data?.currencyTranslationAccount;
+ if (!accountId) {
+ return {
+ data: null,
+ error: {
+ message: `Configure a currency translation account for company ${reportingCompanyId}`
+ }
+ };
+ }
+ const ctaAccount = args.accounts.find((account) => account.id === accountId);
+ if (!ctaAccount) {
+ return {
+ data: null,
+ error: {
+ message:
+ "The configured currency translation account is missing from the report"
+ }
+ };
+ }
+
+ if (
+ ctaAccount.companyGroupId !== companyGroupId ||
+ ctaAccount.active !== true ||
+ ctaAccount.isGroup !== false ||
+ ctaAccount.class !== "Equity" ||
+ ctaAccount.incomeBalance !== "Balance Sheet"
+ ) {
+ return {
+ data: null,
+ error: {
+ message:
+ "The currency translation account must be an active Balance Sheet Equity posting account in this company group"
+ }
+ };
+ }
+
+ const accounts = args.accounts.map((account) => ({
+ ...account,
+ periods: Object.fromEntries(
+ Object.entries(account.periods).map(([key, cell]) => [key, { ...cell }])
+ )
+ }));
+ const translatedCta = accounts.find((account) => account.id === accountId)!;
+ const netIncome = accounts.find(
+ (account) => account.id === NET_INCOME_ACCOUNT_ID
+ );
+
+ for (const key of args.bucketKeys) {
+ const cell = translatedCta.periods[key];
+ const cta = args.ctaByBucket[key];
+ if (
+ !cell ||
+ typeof cell.translatedBalance !== "number" ||
+ !Number.isFinite(cell.translatedBalance) ||
+ typeof cta !== "number" ||
+ !Number.isFinite(cta)
+ ) {
+ return {
+ data: null,
+ error: {
+ message: `Missing or invalid currency translation values for period ${key}`
+ }
+ };
+ }
+ translatedCta.periods[key] = {
+ ...cell,
+ translatedBalance: round(cell.translatedBalance + cta)
+ };
+
+ // Single-company translation deliberately excludes the synthetic income
+ // leaf. Derive its translated values from the full income statement before
+ // rolling Equity up; the raw current-year earnings remain unchanged.
+ const incomeCell = netIncome?.periods[key];
+ if (
+ netIncome &&
+ incomeCell &&
+ typeof incomeCell.translatedBalance !== "number"
+ ) {
+ let translatedBalance = 0;
+ let translatedNetChange = 0;
+ for (const account of accounts) {
+ if (account.incomeBalance !== "Income Statement" || account.isGroup)
+ continue;
+ const sign = rootSignMultiplier(account.class);
+ translatedBalance +=
+ sign * (account.periods[key]?.translatedBalance ?? 0);
+ translatedNetChange +=
+ sign * (account.periods[key]?.translatedNetChange ?? 0);
+ }
+ netIncome.periods[key] = {
+ ...incomeCell,
+ translatedBalance: round(translatedBalance),
+ translatedNetChange: round(translatedNetChange)
+ };
+ }
+ }
+
+ return {
+ data: applyRootSignCorrectionToSeries(
+ rollUpTranslatedGroups(accounts, args.bucketKeys),
+ args.bucketKeys
+ ),
+ error: null
+ };
+}
+
// Overlay per-bucket translated leaf balances onto the series rows.
function overlayTranslationOnSeries<
T extends { id: string; periods: Record<string, PeriodCell> }
@@ -660,12 +803,12 @@ export async function getFinancialStatementPeriodSeries(
.from("accounts")
.select("*")
.eq("companyGroupId", companyGroupId)
- .eq("active", true)
- .order("number", { ascending: true });
+ .order("number", { ascending: true })
+ .order("id", { ascending: true });
// The buckets helper may truncate a very wide range, so the series start is
// the FIRST bucket's start — not whatever the caller had before bucketing.
- const seriesQuery = getAccountPeriodSeries(
+ const seriesQuery = accountPeriodSeriesQuery(
client,
companyGroupId,
companyId,
@@ -676,8 +819,16 @@ export async function getFinancialStatementPeriodSeries(
);
const [accountsResponse, seriesResponse] = await Promise.all([
- accountsQuery,
- seriesQuery
+ fetchAll<Database["public"]["Views"]["accounts"]["Row"]>(
+ () => accountsQuery
+ ),
+ fetchAll<
+ Database["public"]["Functions"]["accountTreeBalancePeriodSeries"]["Returns"][number]
+ >(() =>
+ seriesQuery
+ .order("accountId", { ascending: true })
+ .order("periodEnd", { ascending: true })
+ )
]);
if (accountsResponse.error) {
@@ -3744,30 +3895,79 @@ export async function getPaymentTermsList(
.order("name", { ascending: true });
}
-export async function updateDefaultBalanceSheetAccounts(
+/** Save both defaults sections atomically after validating the effective mapping. */
+export async function updateDefaultAccounts(
client: SupabaseClient<Database>,
- defaultAccounts: z.infer<typeof defaultBalanceSheetAccountValidator> & {
+ defaultAccounts: z.infer<typeof defaultAccountValidator> & {
companyId: string;
updatedBy: string;
}
) {
+ const validation = await validateDefaultIncomeAccounts(
+ client,
+ defaultAccounts
+ );
+ if (validation.error) return { data: null, error: validation.error };
return client
.from("accountDefault")
.update(defaultAccounts)
.eq("companyId", defaultAccounts.companyId);
}
-export async function updateDefaultIncomeAccounts(
+/** Validate the effective shipping mapping before either defaults section saves. */
+export async function validateDefaultIncomeAccounts(
client: SupabaseClient<Database>,
defaultAccounts: z.infer<typeof defaultIncomeAcountValidator> & {
companyId: string;
- updatedBy: string;
}
) {
- return client
- .from("accountDefault")
- .update(defaultAccounts)
- .eq("companyId", defaultAccounts.companyId);
+ const [company, stored] = await Promise.all([
+ client
+ .from("company")
+ .select("companyGroupId")
+ .eq("id", defaultAccounts.companyId)
+ .single(),
+ getDefaultAccounts(client, defaultAccounts.companyId)
+ ]);
+ if (company.error || stored.error) {
+ return { error: company.error ?? stored.error };
+ }
+ if (!company.data?.companyGroupId || !stored.data) {
+ return { error: { message: "Company account defaults not found" } };
+ }
+ const shippingId =
+ defaultAccounts.salesShippingRevenueAccount === undefined
+ ? stored.data.salesShippingRevenueAccount
+ : defaultAccounts.salesShippingRevenueAccount;
+ if (!shippingId || shippingId === defaultAccounts.salesAccount) {
+ return {
+ error: {
+ message: "Select a shipping revenue account distinct from Sales"
+ }
+ };
+ }
+ const account = await client
+ .from("account")
+ .select("id, active, isGroup, class, incomeBalance")
+ .eq("id", shippingId)
+ .eq("companyGroupId", company.data.companyGroupId)
+ .maybeSingle();
+ if (account.error) return { error: account.error };
+ if (
+ !account.data ||
+ account.data.active !== true ||
+ account.data.isGroup !== false ||
+ account.data.class !== "Revenue" ||
+ account.data.incomeBalance !== "Income Statement"
+ ) {
+ return {
+ error: {
+ message:
+ "Shipping revenue must be an active Revenue leaf account in this company group"
+ }
+ };
+ }
+ return { error: null };
}
export async function updateFiscalYearSettings(
@@ -4424,11 +4624,30 @@ export async function translateCompanyBalances(
averageRate: number;
historicalRate: number;
}
+ | null
| undefined;
- const sameCurrency = rates?.sourceCurrency === targetCurrency;
+ if (!rates) {
+ return {
+ data: null,
+ cta: 0,
+ error: `Missing consolidation rates for company ${companyId}`
+ };
+ }
+ if (
+ typeof rates.sourceCurrency !== "string" ||
+ !rates.sourceCurrency.trim()
+ ) {
+ return {
+ data: null,
+ cta: 0,
+ error: `Missing source currency for company ${companyId}`
+ };
+ }
+
+ const sameCurrency = rates.sourceCurrency === targetCurrency;
const rateFor = (consolidatedRate: string | null): number => {
- if (sameCurrency || !rates) return 1;
+ if (sameCurrency) return 1;
switch (consolidatedRate) {
case "Average":
return Number(rates.averageRate);
@@ -4440,9 +4659,12 @@ export async function translateCompanyBalances(
}
};
- const rows: TranslatedBalance[] = [];
- let totalTranslatedAssets = 0;
- let totalTranslatedLiabilitiesAndEquity = 0;
+ const leaves: Array<{
+ account: (typeof balances)[number];
+ localBalance: number;
+ sign: number;
+ }> = [];
+ let sourceDebitMinusCredit = 0;
for (const account of balances) {
// Leaf accounts only, and never the synthetic Net Income line — its
@@ -4450,8 +4672,55 @@ export async function translateCompanyBalances(
// too would double-count net income in the CTA.
if (account.isGroup || account.id === NET_INCOME_ACCOUNT_ID) continue;
+ let sign: number;
+ switch (account.class) {
+ case "Asset":
+ case "Expense":
+ sign = 1;
+ break;
+ case "Liability":
+ case "Equity":
+ case "Revenue":
+ sign = -1;
+ break;
+ default:
+ return {
+ data: null,
+ cta: 0,
+ error: `Invalid account class for account ${account.id}`
+ };
+ }
+ const localBalance = Number(account.balanceAtDate);
+ if (!Number.isFinite(localBalance)) {
+ return {
+ data: null,
+ cta: 0,
+ error: `Invalid source balance for account ${account.id}`
+ };
+ }
+ sourceDebitMinusCredit += sign * localBalance;
+ leaves.push({ account, localBalance, sign });
+ }
+
+ if (!isBalanced(sourceDebitMinusCredit, 0, JOURNAL_BALANCE_TOLERANCE)) {
+ return {
+ data: null,
+ cta: 0,
+ error: `Source balances for company ${companyId} do not balance (off by ${round(sourceDebitMinusCredit)})`
+ };
+ }
+
+ const rows: TranslatedBalance[] = [];
+ let translatedDebitMinusCredit = 0;
+ for (const { account, localBalance, sign } of leaves) {
const exchangeRate = rateFor(account.consolidatedRate);
- const localBalance = Number(account.balanceAtDate ?? 0);
+ if (!Number.isFinite(exchangeRate) || exchangeRate <= 0) {
+ return {
+ data: null,
+ cta: 0,
+ error: `Invalid ${account.consolidatedRate ?? "Current"} consolidation rate for account ${account.id}`
+ };
+ }
const translatedBalance = round(localBalance * exchangeRate);
rows.push({
@@ -4461,18 +4730,13 @@ export async function translateCompanyBalances(
translatedBalance
});
- if (account.class === "Asset") {
- totalTranslatedAssets += translatedBalance;
- } else {
- // Liability, Equity, Revenue, Expense (but income statement
- // accounts net to retained earnings on balance sheet)
- totalTranslatedLiabilitiesAndEquity += translatedBalance;
- }
+ translatedDebitMinusCredit += sign * translatedBalance;
}
- // CTA = translated assets - translated (liabilities + equity)
- // A balanced sheet means assets = liabilities + equity + CTA
- const cta = totalTranslatedAssets - totalTranslatedLiabilitiesAndEquity;
+ // Natural balances become debit-minus-credit with Asset/Expense positive
+ // and Liability/Equity/Revenue negative. The translated residual is the
+ // additional Equity balance; report-tree presentation signs do not apply.
+ const cta = round(translatedDebitMinusCredit);
return { data: rows, cta, error: null };
}
diff --git a/apps/erp/app/modules/accounting/accounting.models.ts b/apps/erp/app/modules/accounting/accounting.models.ts
index 08baae32a9..2fffd8083f 100644
--- a/apps/erp/app/modules/accounting/accounting.models.ts
+++ b/apps/erp/app/modules/accounting/accounting.models.ts
@@ -479,6 +479,12 @@ export const defaultBalanceSheetAccountValidator = z.object({
export const defaultIncomeAcountValidator = z.object({
salesAccount: z.string().min(1, { message: "Sales account is required" }),
+ salesShippingRevenueAccount: z
+ .string()
+ .min(1, {
+ message: "Shipping revenue account is required"
+ })
+ .optional(),
salesDiscountAccount: z.string().min(1, {
message: "Sales discount account is required"
}),
diff --git a/apps/erp/app/modules/accounting/accounting.periods.test.ts b/apps/erp/app/modules/accounting/accounting.periods.test.ts
index 7f4ec51f00..958ad354aa 100644
--- a/apps/erp/app/modules/accounting/accounting.periods.test.ts
+++ b/apps/erp/app/modules/accounting/accounting.periods.test.ts
@@ -73,6 +73,7 @@ function makeClient(responses: Scripted[]) {
order: () => builder,
limit: () => builder,
single: () => Promise.resolve(next()),
+ maybeSingle: () => Promise.resolve(next()),
then: (resolve: (v: Scripted) => unknown) => resolve(next())
};
return { from: () => builder } as any;
@@ -106,6 +107,7 @@ function makeRecordingClient(responses: Scripted[]) {
order: () => builder,
limit: () => builder,
single: () => Promise.resolve(next()),
+ maybeSingle: () => Promise.resolve(next()),
then: (resolve: (v: Scripted) => unknown) => resolve(next())
};
return builder;
@@ -221,6 +223,8 @@ describe("closeAccountingPeriod — sequential close", () => {
},
{ data: [] }, // active definitions (none configured)
{ data: [] }, // existing tasks (none)
+ { data: { timezone: "America/New_York" } }, // company business calendar
+ { data: [] }, // external GL readiness: no active integrations
{ count: 0 }, // readiness: draft journals
{ data: [] }, // readiness: posted journals in period
{ count: 0 }, // readiness: draft depreciation
@@ -296,6 +300,8 @@ describe("closePeriodWithChecklist — Blocker gate + Auto-task persistence", ()
}
]
}, // existing tasks — no instantiation needed
+ { data: { timezone: "America/New_York" } }, // company business calendar
+ { data: [] }, // external GL readiness: no active integrations
{ count: 2 }, // readiness: draft journals present -> Blocker failing
{ data: [] }, // readiness: posted journals in period
{ count: 0 }, // readiness: draft depreciation
@@ -352,6 +358,8 @@ describe("closePeriodWithChecklist — Blocker gate + Auto-task persistence", ()
}
]
},
+ { data: { timezone: "America/New_York" } }, // company business calendar
+ { data: [] }, // external GL readiness: no active integrations
{ count: 0 }, // readiness: no draft journals -> Blocker passing
{ data: [] }, // readiness: posted journals in period
{ count: 0 }, // readiness: draft depreciation
diff --git a/apps/erp/app/modules/accounting/accounting.translation.test.ts b/apps/erp/app/modules/accounting/accounting.translation.test.ts
new file mode 100644
index 0000000000..39c36a3625
--- /dev/null
+++ b/apps/erp/app/modules/accounting/accounting.translation.test.ts
@@ -0,0 +1,675 @@
+import type { Database } from "@carbon/database";
+import { computeReportPeriodBuckets } from "@carbon/utils";
+import type { SupabaseClient } from "@supabase/supabase-js";
+import { describe, expect, it, vi } from "vitest";
+
+// The settings/glossary barrels evaluate Lingui macros that Vitest does not
+// transform. The real translation service needs neither dependency here.
+vi.mock("~/modules/settings", () => ({ getNextSequence: vi.fn() }));
+vi.mock("@carbon/glossary", () => ({
+ getDefinitionText: () => "",
+ getEntry: () => undefined,
+ getTermText: () => "",
+ glossaryEntries: () => [],
+ hasEntry: () => false,
+ listEntries: () => [],
+ lookupEntry: () => undefined,
+ termSlug: (term: string) => term,
+ terms: {}
+}));
+
+import {
+ applyCtaToReportPeriodSeries,
+ getFinancialStatementBalances,
+ getFinancialStatementPeriodSeries,
+ translateCompanyBalances,
+ translateCompanyPeriodSeries
+} from "./accounting.ee.service";
+import type { ChartPeriodSeries } from "./types";
+import { NET_INCOME_ACCOUNT_ID } from "./types";
+
+type Balance = Parameters<typeof translateCompanyBalances>[6][number];
+type RpcResult = { data: unknown; error: { message: string } | null };
+type RateArgs = {
+ p_company_group_id: string;
+ p_company_id: string;
+ p_target_currency: string;
+ p_period_end: string;
+ p_period_start?: string;
+};
+
+const rates = {
+ sourceCurrency: "EUR",
+ closingRate: 1,
+ averageRate: 1,
+ historicalRate: 1
+};
+
+const balanced: Balance[] = [
+ {
+ id: "cash",
+ balanceAtDate: 80,
+ consolidatedRate: "Current",
+ isGroup: false,
+ class: "Asset"
+ },
+ {
+ id: "sales",
+ balanceAtDate: 100,
+ consolidatedRate: "Average",
+ isGroup: false,
+ class: "Revenue"
+ },
+ {
+ id: "expenses",
+ balanceAtDate: 20,
+ consolidatedRate: "Average",
+ isGroup: false,
+ class: "Expense"
+ }
+];
+
+function makeRateClient(resolve: (args: RateArgs) => RpcResult) {
+ const rpc = vi.fn(async (name: string, args: RateArgs) => {
+ if (name !== "getConsolidationRates") {
+ throw new Error(`Unexpected RPC: ${name}`);
+ }
+ return resolve(args);
+ });
+ return { client: { rpc } as unknown as SupabaseClient<Database>, rpc };
+}
+
+async function translate(
+ balances: Balance[] = balanced,
+ data: unknown = [rates]
+) {
+ const { client } = makeRateClient(() => ({ data, error: null }));
+ return translateCompanyBalances(
+ client,
+ "group",
+ "subsidiary",
+ "USD",
+ "2026-08-31",
+ "2026-08-01",
+ balances
+ );
+}
+
+describe("translateCompanyBalances", () => {
+ it("keeps a balanced income statement at zero CTA with identity rates", async () => {
+ const result = await translate();
+ expect(result.error).toBeNull();
+ expect(result.cta).toBe(0);
+ expect(result.data).toEqual([
+ {
+ accountId: "cash",
+ localBalance: 80,
+ translatedBalance: 80,
+ exchangeRate: 1
+ },
+ {
+ accountId: "sales",
+ localBalance: 100,
+ translatedBalance: 100,
+ exchangeRate: 1
+ },
+ {
+ accountId: "expenses",
+ localBalance: 20,
+ translatedBalance: 20,
+ exchangeRate: 1
+ }
+ ]);
+ });
+
+ it("preserves negative asset balances in the debit-minus-credit sum", async () => {
+ const result = await translate(
+ balanced
+ .filter((row) => row.id !== "sales")
+ .map((row) =>
+ row.id === "cash" ? { ...row, balanceAtDate: -20 } : row
+ )
+ );
+ expect(result.error).toBeNull();
+ expect(result.cta).toBe(0);
+ expect(
+ result.data?.find((row) => row.accountId === "cash")?.translatedBalance
+ ).toBe(-20);
+ });
+
+ it("reports CTA 40 from closing cash 160 and translated income 120", async () => {
+ const result = await translate(balanced, [
+ { ...rates, closingRate: 2, averageRate: 1.5 }
+ ]);
+ expect(result.error).toBeNull();
+ expect(result.cta).toBe(40);
+ expect(result.data?.map((row) => row.translatedBalance)).toEqual([
+ 160, 150, 30
+ ]);
+ });
+
+ it("subtracts liability and historical equity balances without changing their signs", async () => {
+ const result = await translate(
+ [
+ {
+ id: "cash",
+ class: "Asset",
+ balanceAtDate: 80,
+ consolidatedRate: "Current",
+ isGroup: false
+ },
+ {
+ id: "payables",
+ class: "Liability",
+ balanceAtDate: 30,
+ consolidatedRate: "Current",
+ isGroup: false
+ },
+ {
+ id: "capital",
+ class: "Equity",
+ balanceAtDate: 50,
+ consolidatedRate: "Historical",
+ isGroup: false
+ }
+ ],
+ [{ ...rates, closingRate: 2, historicalRate: 1.5 }]
+ );
+ expect(result.error).toBeNull();
+ expect(result.cta).toBe(25);
+ expect(result.data?.map((row) => row.translatedBalance)).toEqual([
+ 160, 60, 75
+ ]);
+ });
+
+ it("rejects a source imbalance instead of concealing it as CTA", async () => {
+ const result = await translate(
+ balanced.map((row) =>
+ row.id === "cash" ? { ...row, balanceAtDate: 79 } : row
+ )
+ );
+ expect(result).toEqual({
+ data: null,
+ cta: 0,
+ error: expect.stringMatching(/source.*balanc/i)
+ });
+ });
+
+ it("retains the existing 0.001 journal tolerance for source validation", async () => {
+ const within = await translate(
+ balanced.map((row) =>
+ row.id === "cash" ? { ...row, balanceAtDate: 80.0005 } : row
+ )
+ );
+ const outside = await translate(
+ balanced.map((row) =>
+ row.id === "cash" ? { ...row, balanceAtDate: 80.0015 } : row
+ )
+ );
+ expect(within.error).toBeNull();
+ expect(outside.error).toEqual(expect.stringMatching(/source.*balanc/i));
+ });
+
+ it.each([
+ "Unknown",
+ null
+ ])("rejects invalid leaf account class %s", async (accountClass) => {
+ const result = await translate(
+ balanced.map((row) =>
+ row.id === "cash" ? { ...row, class: accountClass } : row
+ )
+ );
+ expect(result).toEqual({
+ data: null,
+ cta: 0,
+ error: expect.stringMatching(/class.*cash|cash.*class/i)
+ });
+ });
+
+ it.each([
+ Number.NaN,
+ Number.POSITIVE_INFINITY,
+ Number.NEGATIVE_INFINITY
+ ])("rejects nonfinite source balance %s", async (balanceAtDate) => {
+ const result = await translate(
+ balanced.map((row) =>
+ row.id === "cash" ? { ...row, balanceAtDate } : row
+ )
+ );
+ expect(result).toEqual({
+ data: null,
+ cta: 0,
+ error: expect.stringMatching(/balanc.*cash|cash.*balanc/i)
+ });
+ });
+
+ it("excludes groups and synthetic income before both validation and translation", async () => {
+ const result = await translate(
+ [
+ ...balanced,
+ {
+ id: "group-header",
+ class: null,
+ balanceAtDate: Number.NaN,
+ consolidatedRate: "Historical",
+ isGroup: true
+ },
+ {
+ id: NET_INCOME_ACCOUNT_ID,
+ class: "Equity",
+ balanceAtDate: 80,
+ consolidatedRate: "Historical",
+ isGroup: false
+ }
+ ],
+ [{ ...rates, historicalRate: null }]
+ );
+ expect(result.error).toBeNull();
+ expect(result.cta).toBe(0);
+ expect(result.data).toHaveLength(3);
+ });
+
+ it.each([
+ { label: "null", payload: null },
+ { label: "undefined", payload: undefined },
+ { label: "empty array", payload: [] },
+ { label: "empty object", payload: {} },
+ { label: "null row", payload: [null] }
+ ])("rejects empty or malformed rate payload $label", async ({ payload }) => {
+ const { client } = makeRateClient(() => ({ data: payload, error: null }));
+ const result = await translateCompanyBalances(
+ client,
+ "group",
+ "subsidiary",
+ "USD",
+ "2026-08-31",
+ undefined,
+ balanced
+ );
+ expect(result).toEqual({
+ data: null,
+ cta: 0,
+ error: expect.stringMatching(/rate|currency/i)
+ });
+ });
+
+ it.each([
+ null,
+ "",
+ " "
+ ])("rejects missing source currency %j", async (sourceCurrency) => {
+ const result = await translate(balanced, [{ ...rates, sourceCurrency }]);
+ expect(result).toEqual({
+ data: null,
+ cta: 0,
+ error: expect.stringMatching(/source currency/i)
+ });
+ });
+
+ it.each([
+ null,
+ undefined,
+ 0,
+ -1,
+ Number.NaN,
+ Number.POSITIVE_INFINITY
+ ])("rejects invalid applicable rate %s", async (closingRate) => {
+ const result = await translate(balanced, [{ ...rates, closingRate }]);
+ expect(result).toEqual({
+ data: null,
+ cta: 0,
+ error: expect.stringMatching(/rate/i)
+ });
+ });
+
+ it.each([
+ "Average",
+ "Historical"
+ ])("validates applicable %s rates", async (consolidatedRate) => {
+ const result = await translate(
+ balanced.map((row) => ({ ...row, consolidatedRate })),
+ [{ ...rates, averageRate: 0, historicalRate: Number.NaN }]
+ );
+ expect(result).toEqual({
+ data: null,
+ cta: 0,
+ error: expect.stringMatching(/rate/i)
+ });
+ });
+
+ it("uses identity when the source currency equals the requested currency", async () => {
+ const result = await translate(balanced, [
+ { ...rates, sourceCurrency: "USD", closingRate: 2, averageRate: 1.5 }
+ ]);
+ expect(result.error).toBeNull();
+ expect(result.cta).toBe(0);
+ expect(result.data?.map((row) => row.exchangeRate)).toEqual([1, 1, 1]);
+ });
+
+ it("propagates a missing-pair RPC error with its original message", async () => {
+ const { client } = makeRateClient(() => ({
+ data: null,
+ error: { message: "No exchange rate for EUR/USD" }
+ }));
+ const result = await translateCompanyBalances(
+ client,
+ "group",
+ "subsidiary",
+ "USD",
+ "2026-08-31",
+ undefined,
+ balanced
+ );
+ expect(result).toEqual({
+ data: null,
+ cta: 0,
+ error: "No exchange rate for EUR/USD"
+ });
+ });
+});
+
+describe("translateCompanyPeriodSeries", () => {
+ const buckets = computeReportPeriodBuckets(
+ "2026-07-01",
+ "2026-08-31",
+ "month",
+ 1
+ );
+ const series = balanced.map(({ balanceAtDate, ...row }) => ({
+ ...row,
+ periods: Object.fromEntries(
+ buckets.map((bucket) => [
+ bucket.key,
+ { balanceAtDate, netChange: balanceAtDate }
+ ])
+ )
+ }));
+
+ it("selects rates by the company and period arguments for concurrent buckets", async () => {
+ const { client, rpc } = makeRateClient((args) => ({
+ data: [
+ {
+ ...rates,
+ closingRate: args.p_period_end === "2026-08-31" ? 2 : 1,
+ averageRate: args.p_period_end === "2026-08-31" ? 1.5 : 1
+ }
+ ],
+ error: null
+ }));
+ const result = await translateCompanyPeriodSeries(
+ client,
+ "group",
+ "subsidiary",
+ "USD",
+ buckets,
+ series
+ );
+ expect(result.error).toBeNull();
+ expect(result.byBucket["2026-07"]?.cta).toBe(0);
+ expect(result.byBucket["2026-08"]?.cta).toBe(40);
+ for (const bucket of buckets) {
+ expect(rpc).toHaveBeenCalledWith("getConsolidationRates", {
+ p_company_group_id: "group",
+ p_company_id: "subsidiary",
+ p_target_currency: "USD",
+ p_period_end: bucket.end,
+ p_period_start: bucket.start
+ });
+ }
+ });
+
+ it("returns no partial report when one bucket has no rate payload", async () => {
+ const { client } = makeRateClient((args) => ({
+ data: args.p_period_end === "2026-08-31" ? [] : [rates],
+ error: null
+ }));
+ const result = await translateCompanyPeriodSeries(
+ client,
+ "group",
+ "subsidiary",
+ "USD",
+ buckets,
+ series
+ );
+ expect(result).toEqual({
+ byBucket: {},
+ error: expect.stringMatching(/rate|currency/i)
+ });
+ });
+});
+
+describe("single-company period series and configured CTA", () => {
+ it.each([
+ "active",
+ "inactive leaf",
+ "inactive group",
+ "paged history"
+ ])("derives translated synthetic income including %s history, then rolls CTA into Equity", async (state) => {
+ const buckets = computeReportPeriodBuckets(
+ "2026-08-01",
+ "2026-08-31",
+ "month",
+ 1
+ );
+ const row = (
+ id: string,
+ parentId: string | null,
+ accountClass: ChartPeriodSeries["class"],
+ extra: Partial<ChartPeriodSeries> = {}
+ ) => ({
+ id,
+ parentId,
+ class: accountClass,
+ companyGroupId: "group",
+ active: true,
+ isGroup: false,
+ isSystem: false,
+ incomeBalance: "Balance Sheet",
+ consolidatedRate: "Current",
+ ...extra
+ });
+ const emptyHistory =
+ state === "paged history"
+ ? Array.from({ length: 1000 }, (_, index) =>
+ row(`old-${index}`, "assets", "Asset", { active: false })
+ )
+ : [];
+ const chart = [
+ ...emptyHistory,
+ row("balance-sheet", null, "Asset", { isGroup: true, isSystem: true }),
+ row("assets", "balance-sheet", "Asset", { isGroup: true }),
+ row("cash", "assets", "Asset"),
+ row("equity", "balance-sheet", "Equity", { isGroup: true }),
+ row("reserves", "equity", "Equity", { isGroup: true }),
+ row("custom-cta", "reserves", "Equity", {
+ number: "3999",
+ name: "Renamed FX Reserve"
+ }),
+ row("income-statement", null, "Revenue", {
+ isGroup: true,
+ isSystem: true,
+ incomeBalance: "Income Statement"
+ }),
+ row("sales", "income-statement", "Revenue", {
+ consolidatedRate: "Average",
+ incomeBalance: "Income Statement"
+ }),
+ row("expense-group", "income-statement", "Expense", {
+ isGroup: true,
+ active: state !== "inactive group",
+ incomeBalance: "Income Statement"
+ }),
+ row("expenses", "expense-group", "Expense", {
+ active: state !== "inactive leaf",
+ consolidatedRate: "Average",
+ incomeBalance: "Income Statement"
+ })
+ ];
+ const sourceBalances = [
+ ...emptyHistory.map((account) => ({ ...account, balanceAtDate: 0 })),
+ ...balanced
+ ];
+ const paged = (data: unknown[]) => {
+ let start = 0,
+ end = 999;
+ const query = {
+ order: () => query,
+ range: (from: number, to: number) => {
+ start = from;
+ end = to;
+ return query;
+ },
+ then: (resolve: (value: unknown) => unknown) =>
+ resolve({ data: data.slice(start, end + 1), error: null })
+ };
+ return query;
+ };
+ const client = {
+ rpc(name: string, args: RateArgs) {
+ if (name === "getConsolidationRates") {
+ expect(args.p_company_id).toBe("subsidiary");
+ expect(args.p_target_currency).toBe("USD");
+ return Promise.resolve({
+ data: [{ ...rates, closingRate: 2, averageRate: 1.5 }],
+ error: null
+ });
+ }
+ if (name === "accountTreeBalancesByCompany") {
+ return paged(
+ sourceBalances.map((account) => ({
+ accountId: account.id,
+ balance: account.balanceAtDate,
+ balanceAtDate: account.balanceAtDate,
+ netChange: account.balanceAtDate
+ }))
+ );
+ }
+ if (name === "accountTreeBalancePeriodSeries") {
+ return paged(
+ sourceBalances.map((account) => ({
+ accountId: account.id,
+ periodEnd: "2026-08-31",
+ netChange: account.balanceAtDate,
+ balanceAtDate: account.balanceAtDate
+ }))
+ );
+ }
+ throw new Error(`Unexpected RPC ${name}`);
+ },
+ from(table: string) {
+ const filters: Record<string, unknown> = {};
+ let pageStart = 0,
+ pageEnd = 999;
+ const builder = {
+ range: (from: number, to: number) => {
+ pageStart = from;
+ pageEnd = to;
+ return builder;
+ },
+ select: () => builder,
+ eq: (field: string, value: unknown) => {
+ filters[field] = value;
+ return builder;
+ },
+ order: () => builder,
+ single: async () => {
+ expect(table).toBe("accountDefault");
+ expect(filters.companyId).toBe("parent");
+ return {
+ data: { currencyTranslationAccount: "custom-cta" },
+ error: null
+ };
+ },
+ then: (resolve: (value: unknown) => unknown) => {
+ expect(table).toBe("accounts");
+ expect(filters.companyGroupId).toBe("group");
+ return resolve({
+ data: chart
+ .filter((row) =>
+ Object.entries(filters).every(
+ ([key, value]) => row[key as keyof typeof row] === value
+ )
+ )
+ .slice(pageStart, pageEnd + 1),
+ error: null
+ });
+ }
+ };
+ return builder;
+ }
+ } as unknown as SupabaseClient<Database>;
+
+ const source = await getFinancialStatementPeriodSeries(
+ client,
+ "group",
+ "subsidiary",
+ {
+ buckets,
+ includeCurrentYearEarnings: true,
+ translate: { targetCurrency: "USD" }
+ }
+ );
+ expect(source.error).toBeNull();
+ expect(
+ source.data?.find((account) => account.id === "expense-group")?.periods[
+ "2026-08"
+ ]?.translatedBalance
+ ).toBe(30);
+ const singlePeriod = await getFinancialStatementBalances(
+ client,
+ "group",
+ "subsidiary",
+ {
+ startDate: "2026-08-01",
+ endDate: "2026-08-31",
+ includeCurrentYearEarnings: true
+ }
+ );
+ expect(singlePeriod.error).toBeNull();
+ expect(
+ singlePeriod.data?.find((account) => account.id === "expenses")
+ ?.balanceAtDate
+ ).toBe(20);
+ expect(
+ singlePeriod.data?.find((account) => account.id === NET_INCOME_ACCOUNT_ID)
+ ?.balanceAtDate
+ ).toBe(80);
+ expect(source.ctaByBucket).toEqual({ "2026-08": 40 });
+ if (!source.data) throw new Error("Missing source report");
+ const original = structuredClone(source.data);
+ const args = {
+ accounts: source.data,
+ bucketKeys: ["2026-08"],
+ ctaByBucket: source.ctaByBucket
+ };
+ const adjusted = await applyCtaToReportPeriodSeries(
+ client,
+ "group",
+ "parent",
+ args
+ );
+ const repeated = await applyCtaToReportPeriodSeries(
+ client,
+ "group",
+ "parent",
+ args
+ );
+ expect(adjusted.error).toBeNull();
+ const cells = new Map(
+ adjusted.data?.map((account) => [account.id, account.periods["2026-08"]])
+ );
+ expect(cells.get("cash")?.translatedBalance).toBe(160);
+ expect(cells.get(NET_INCOME_ACCOUNT_ID)).toMatchObject({
+ balanceAtDate: 80,
+ netChange: 80,
+ translatedBalance: 120,
+ translatedNetChange: 120
+ });
+ expect(cells.get("custom-cta")?.translatedBalance).toBe(40);
+ expect(cells.get("reserves")?.translatedBalance).toBe(40);
+ expect(cells.get("equity")?.translatedBalance).toBe(160);
+ expect(cells.get("balance-sheet")?.translatedBalance).toBe(0);
+ expect(repeated).toEqual(adjusted);
+ expect(source.data).toEqual(original);
+ });
+});
diff --git a/apps/erp/app/modules/accounting/ui/AccountDefaults/AccountDefaultsForm.tsx b/apps/erp/app/modules/accounting/ui/AccountDefaults/AccountDefaultsForm.tsx
index 2498a8c3dd..d6ede08429 100644
--- a/apps/erp/app/modules/accounting/ui/AccountDefaults/AccountDefaultsForm.tsx
+++ b/apps/erp/app/modules/accounting/ui/AccountDefaults/AccountDefaultsForm.tsx
@@ -2,7 +2,7 @@ import { ValidatedForm } from "@carbon/form";
import type { TermId } from "@carbon/glossary";
import { Badge, Button, HStack, LabelWithHelp } from "@carbon/react";
import { Trans, useLingui } from "@lingui/react/macro";
-import { useMemo } from "react";
+import { useMemo, useState } from "react";
import { useNavigate } from "react-router";
import { Combobox, Hidden, Submit } from "~/components/Form";
import { usePermissions } from "~/hooks";
@@ -10,6 +10,11 @@ import { path } from "~/utils/path";
import { defaultAccountValidator } from "../../accounting.models";
import type { AccountListItem } from "../../types";
+const formValidator = defaultAccountValidator.extend({
+ salesShippingRevenueAccount:
+ defaultAccountValidator.shape.salesShippingRevenueAccount.unwrap()
+});
+
type BadgeType = "Asset" | "Liability" | "Equity" | "Revenue" | "Expense";
type AccountDefaultField = {
@@ -53,6 +58,7 @@ const AccountDefaultsForm = ({
const permissions = usePermissions();
const navigate = useNavigate();
const onClose = () => navigate(-1);
+ const [salesAccount, setSalesAccount] = useState(initialValues.salesAccount);
const isDisabled = !permissions.can("update", "accounting");
@@ -280,6 +286,13 @@ const AccountDefaultsForm = ({
badgeType: "Revenue",
termId: "account-default-sales"
},
+ {
+ name: "salesShippingRevenueAccount",
+ label: t`Shipping Revenue`,
+ description: t`Revenue account for shipping charged to customers`,
+ badgeType: "Revenue",
+ termId: "account-default-sales-shipping-revenue"
+ },
{
name: "salesDiscountAccount",
label: t`Sales Discounts`,
@@ -515,7 +528,7 @@ const AccountDefaultsForm = ({
return (
<ValidatedForm
- validator={defaultAccountValidator}
+ validator={formValidator}
method="post"
action={path.to.accountingDefaults}
defaultValues={initialValues}
@@ -587,7 +600,23 @@ const AccountDefaultsForm = ({
<div className="flex-shrink-0 w-64">
<Combobox
name={field.name}
- options={accountOptions[field.badgeType]}
+ options={
+ field.name === "salesShippingRevenueAccount"
+ ? accountOptions.Revenue.filter(
+ (account) => account.value !== salesAccount
+ )
+ : accountOptions[field.badgeType]
+ }
+ onChange={
+ field.name === "salesAccount"
+ ? (account) =>
+ setSalesAccount(account?.value ?? "")
+ : undefined
+ }
+ isRequired={
+ field.name === "salesShippingRevenueAccount" ||
+ undefined
+ }
size="sm"
/>
</div>
diff --git a/apps/erp/app/modules/inventory/ui/Receipts/ReceiptVoidModal.tsx b/apps/erp/app/modules/inventory/ui/Receipts/ReceiptVoidModal.tsx
index e03db42293..d2da9c30d4 100644
--- a/apps/erp/app/modules/inventory/ui/Receipts/ReceiptVoidModal.tsx
+++ b/apps/erp/app/modules/inventory/ui/Receipts/ReceiptVoidModal.tsx
@@ -7,7 +7,6 @@ import {
Modal,
ModalBody,
ModalContent,
- ModalDescription,
ModalFooter,
ModalHeader,
ModalOverlay,
@@ -47,14 +46,14 @@ const ReceiptVoidModal = ({ onClose }: { onClose: () => void }) => {
<ModalTitle>
<Trans>Void Receipt</Trans>
</ModalTitle>
- <ModalDescription>
+ </ModalHeader>
+ <ModalBody>
+ <p className="text-sm text-muted-foreground mb-4">
<Trans>
Are you sure you want to void this receipt? This action will
reverse all inventory transactions and cannot be undone.
</Trans>
- </ModalDescription>
- </ModalHeader>
- <ModalBody>
+ </p>
<Alert variant="destructive">
<LuTriangleAlert className="h-4 w-4" />
<AlertTitle>
diff --git a/apps/erp/app/modules/inventory/ui/Shipments/ShipmentPostModal.tsx b/apps/erp/app/modules/inventory/ui/Shipments/ShipmentPostModal.tsx
index 05d68e83b8..c1ba272682 100644
--- a/apps/erp/app/modules/inventory/ui/Shipments/ShipmentPostModal.tsx
+++ b/apps/erp/app/modules/inventory/ui/Shipments/ShipmentPostModal.tsx
@@ -9,7 +9,6 @@ import {
Modal,
ModalBody,
ModalContent,
- ModalDescription,
ModalFooter,
ModalHeader,
ModalOverlay,
@@ -247,11 +246,11 @@ const ShipmentPostModal = ({ onClose }: { onClose: () => void }) => {
<ModalTitle>
<Trans>Post Shipment</Trans>
</ModalTitle>
- <ModalDescription>
- <Trans>Are you sure you want to post this shipment?</Trans>
- </ModalDescription>
</ModalHeader>
<ModalBody>
+ <p className="text-sm text-muted-foreground mb-4">
+ <Trans>Are you sure you want to post this shipment?</Trans>
+ </p>
{validationErrors.length > 0 && (
<Alert variant="destructive">
<LuTriangleAlert className="h-4 w-4" />
diff --git a/apps/erp/app/modules/inventory/ui/Shipments/ShipmentVoidModal.tsx b/apps/erp/app/modules/inventory/ui/Shipments/ShipmentVoidModal.tsx
index 1f167c1314..6f560f8236 100644
--- a/apps/erp/app/modules/inventory/ui/Shipments/ShipmentVoidModal.tsx
+++ b/apps/erp/app/modules/inventory/ui/Shipments/ShipmentVoidModal.tsx
@@ -7,7 +7,6 @@ import {
Modal,
ModalBody,
ModalContent,
- ModalDescription,
ModalFooter,
ModalHeader,
ModalOverlay,
@@ -47,14 +46,14 @@ const ShipmentVoidModal = ({ onClose }: { onClose: () => void }) => {
<ModalTitle>
<Trans>Void Shipment</Trans>
</ModalTitle>
- <ModalDescription>
+ </ModalHeader>
+ <ModalBody>
+ <p className="text-sm text-muted-foreground mb-4">
<Trans>
Are you sure you want to void this shipment? This action will
reverse all inventory transactions and cannot be undone.
</Trans>
- </ModalDescription>
- </ModalHeader>
- <ModalBody>
+ </p>
<Alert variant="destructive">
<LuTriangleAlert className="h-4 w-4" />
<AlertTitle>
diff --git a/apps/erp/app/modules/invoicing/invoicing.application-history.test.ts b/apps/erp/app/modules/invoicing/invoicing.application-history.test.ts
new file mode 100644
index 0000000000..9eb33c5bbe
--- /dev/null
+++ b/apps/erp/app/modules/invoicing/invoicing.application-history.test.ts
@@ -0,0 +1,246 @@
+import type { Database } from "@carbon/database";
+import { createClient } from "@supabase/supabase-js";
+import { describe, expect, it, vi } from "vitest";
+
+vi.mock("@carbon/glossary", () => ({
+ terms: {},
+ getEntry: () => null,
+ lookupEntry: () => null,
+ hasEntry: () => false,
+ termSlug: (s: string) => s,
+ glossaryEntries: () => []
+}));
+vi.mock("~/modules/purchasing", () => ({}));
+vi.mock("../people/people.service", () => ({}));
+vi.mock("../sales/sales.service", () => ({}));
+vi.mock("../accounting/accounting.ee.service", () => ({}));
+
+import {
+ getInvoiceSettlements,
+ getInvoiceSettlementsForInvoice
+} from "./invoicing.service";
+
+type Row = Record<string, unknown>;
+function cappedClient(tables: Record<string, Row[]>, failOffset?: number) {
+ const requests: URL[] = [];
+ const client = createClient<Database>("http://history.test", "test-key", {
+ auth: { persistSession: false, autoRefreshToken: false },
+ global: {
+ fetch: async (input) => {
+ const url = new URL(String(input));
+ requests.push(url);
+ const table = url.pathname.split("/").at(-1)!;
+ const offset = Number(url.searchParams.get("offset") ?? 0);
+ if (table === "invoiceSettlement" && offset === failOffset) {
+ return Response.json(
+ { message: "Later history page failed", code: "XX000" },
+ { status: 500 }
+ );
+ }
+ let rows = tables[table] ?? [];
+ for (const [key, value] of url.searchParams) {
+ if (value.startsWith("eq."))
+ rows = rows.filter((row) => String(row[key]) === value.slice(3));
+ if (value.startsWith("in.(")) {
+ const values = value.slice(4, -1).split(",");
+ rows = rows.filter((row) => values.includes(String(row[key])));
+ }
+ }
+ const limit = Math.min(
+ Number(url.searchParams.get("limit") ?? 1000),
+ 1000
+ );
+ return Response.json(rows.slice(offset, offset + limit), {
+ headers: {
+ "content-range": `${offset}-${Math.min(offset + limit, rows.length) - 1}/${rows.length}`
+ }
+ });
+ }
+ }
+ });
+ return { client, requests };
+}
+
+function payment(id = "cash", status = "Posted") {
+ return {
+ id,
+ companyId: "co",
+ paymentId: `PAY-${id}`,
+ status,
+ paymentDate: "2026-09-09",
+ currencyCode: "USD"
+ };
+}
+function settlement(n: number, extra: Row = {}): Row {
+ return {
+ id: `application-${String(n).padStart(4, "0")}`,
+ companyId: "co",
+ paymentId: "cash",
+ memoId: null,
+ appliedViaPaymentId: null,
+ targetSalesInvoiceId: "invoice",
+ targetPurchaseInvoiceId: "invoice",
+ sourceAmount: 1,
+ appliedAmount: 1,
+ discountAmount: 0,
+ writeOffAmount: 0,
+ fxGainLossAmount: 0,
+ targetExchangeRate: 1,
+ sourceExchangeRate: 1,
+ appliedDate: "2026-09-09",
+ payment: payment(),
+ memo: null,
+ appliedViaPayment: null,
+ salesInvoice: { invoiceId: "AR-1" },
+ purchaseInvoice: { invoiceId: "AP-1" },
+ targetMemo: { memoId: "MEMO-1" },
+ ...extra
+ };
+}
+
+const rows = Array.from({ length: 1105 }, (_, index) => settlement(index));
+
+describe("complete payment application history", () => {
+ it("returns all 1,105 applications and refund target labels under the API cap", async () => {
+ const { client } = cappedClient({
+ invoiceSettlement: [...rows, settlement(1200, { companyId: "other" })]
+ });
+ const result = await getInvoiceSettlements(client, "co", "cash");
+ expect(result.error).toBeNull();
+ expect(result.data).toHaveLength(1105);
+ expect(
+ result.data?.reduce((sum, row) => sum + Number(row.sourceAmount), 0)
+ ).toBe(1105);
+ expect(result.data?.at(-1)?.targetMemo).toEqual({ memoId: "MEMO-1" });
+ });
+
+ it("refuses a partial payment total if a later application page fails", async () => {
+ const { client } = cappedClient({ invoiceSettlement: rows }, 1000);
+ const result = await getInvoiceSettlements(client, "co", "cash");
+ expect(result.data).toBeNull();
+ expect(result.error?.message).toBe("Later history page failed");
+ });
+});
+
+describe.each([
+ "sales",
+ "purchase"
+] as const)("%s invoice application history", (side) => {
+ it("aggregates all source allocations before displaying the applied total", async () => {
+ const { client } = cappedClient({
+ invoiceSettlement: rows,
+ payment: [payment()]
+ });
+ const result = await getInvoiceSettlementsForInvoice(
+ client,
+ "co",
+ side,
+ "invoice"
+ );
+ expect(result.error).toBeNull();
+ expect(result.data).toHaveLength(1);
+ expect(result.data?.[0]).toMatchObject({
+ sourceAmount: 1105,
+ appliedAmount: 1105
+ });
+ });
+
+ it("retains more than 1,000 distinct sources without an oversized ID lookup", async () => {
+ const payments = Array.from({ length: 1105 }, (_, index) =>
+ payment(`cash-${index}`)
+ );
+ const distinctRows = payments.map((p, index) =>
+ settlement(index, { paymentId: p.id, payment: p })
+ );
+ const { client, requests } = cappedClient({
+ invoiceSettlement: distinctRows,
+ payment: payments
+ });
+ const result = await getInvoiceSettlementsForInvoice(
+ client,
+ "co",
+ side,
+ "invoice"
+ );
+ expect(result.error).toBeNull();
+ expect(result.data).toHaveLength(1105);
+ expect(
+ Math.max(...requests.map((url) => url.toString().length))
+ ).toBeLessThan(8000);
+ });
+
+ it("rejects a later page failure instead of returning the first applied total", async () => {
+ const { client } = cappedClient(
+ { invoiceSettlement: rows, payment: [payment()] },
+ 1000
+ );
+ const result = await getInvoiceSettlementsForInvoice(
+ client,
+ "co",
+ side,
+ "invoice"
+ );
+ expect(result.data).toBeNull();
+ expect(result.error).toMatchObject({
+ message: "Later history page failed"
+ });
+ });
+
+ it("includes only posted cash, posted direct memos, and memos consumed through posted payments", async () => {
+ const memo = {
+ id: "memo",
+ memoId: "MEMO-1",
+ companyId: "co",
+ status: "Posted",
+ postingDate: "2026-09-09",
+ memoDate: "2026-09-09",
+ currencyCode: "USD",
+ direction: "Credit"
+ };
+ const statuses = ["Posted", "Draft", "Voided"];
+ const applications = [
+ settlement(0),
+ ...statuses.map((status, index) =>
+ settlement(index + 1, {
+ paymentId: `via-${status}`,
+ payment: payment(`via-${status}`, status)
+ })
+ ),
+ settlement(4, { paymentId: null, payment: null, memoId: "memo", memo }),
+ ...statuses.map((status, index) =>
+ settlement(index + 5, {
+ paymentId: null,
+ payment: null,
+ memoId: "memo",
+ memo,
+ appliedViaPaymentId: `via-${status}`,
+ appliedViaPayment: { status }
+ })
+ ),
+ settlement(9, {
+ paymentId: null,
+ payment: null,
+ memoId: "draft-memo",
+ memo: { ...memo, id: "draft-memo", status: "Draft" }
+ })
+ ];
+ const { client } = cappedClient({
+ invoiceSettlement: applications,
+ payment: [payment(), ...statuses.map((s) => payment(`via-${s}`, s))],
+ memo: [memo, { ...memo, id: "draft-memo", status: "Draft" }]
+ });
+ const result = await getInvoiceSettlementsForInvoice(
+ client,
+ "co",
+ side,
+ "invoice"
+ );
+ expect(result.error).toBeNull();
+ expect(result.data?.reduce((sum, row) => sum + row.appliedAmount, 0)).toBe(
+ 4
+ );
+ expect(
+ result.data?.find((row) => row.source.type === "memo")?.appliedAmount
+ ).toBe(2);
+ });
+});
diff --git a/apps/erp/app/modules/invoicing/invoicing.models.test.ts b/apps/erp/app/modules/invoicing/invoicing.models.test.ts
index 2cb905cffe..acf5e32e4b 100644
--- a/apps/erp/app/modules/invoicing/invoicing.models.test.ts
+++ b/apps/erp/app/modules/invoicing/invoicing.models.test.ts
@@ -31,6 +31,38 @@ describe("paymentValidator", () => {
expect(r.success).toBe(true);
});
+ it("accepts a customer refund disbursement", () => {
+ expect(
+ paymentValidator.safeParse({
+ ...validReceipt,
+ paymentType: "Disbursement"
+ }).success
+ ).toBe(true);
+ });
+
+ it("accepts a supplier refund receipt", () => {
+ expect(
+ paymentValidator.safeParse({
+ ...validReceipt,
+ customerId: undefined,
+ supplierId: "supp1"
+ }).success
+ ).toBe(true);
+ });
+
+ it.each([
+ "Receipt",
+ "Disbursement"
+ ])("rejects ambiguous %s counterparty", (paymentType) => {
+ expect(
+ paymentValidator.safeParse({
+ ...validReceipt,
+ paymentType,
+ supplierId: "supp1"
+ }).success
+ ).toBe(false);
+ });
+
it("rejects a Receipt missing customer", () => {
const r = paymentValidator.safeParse({
...validReceipt,
@@ -167,9 +199,9 @@ describe("isInvoicePayable", () => {
expect(isInvoicePayable("Overdue", 100)).toBe(true);
});
- it("forgives a sub-cent dust balance (not payable)", () => {
- expect(isInvoicePayable("Partially Paid", 0.003)).toBe(false);
- expect(isInvoicePayable("Partially Paid", 0.009)).toBe(false);
+ it("keeps positive foreign document remainders payable below a base cent", () => {
+ expect(isInvoicePayable("Partially Paid", 0.003)).toBe(true);
+ expect(isInvoicePayable("Partially Paid", 0.009)).toBe(true);
});
it("is not payable when fully paid or zero balance", () => {
@@ -188,3 +220,19 @@ describe("isInvoicePayable", () => {
expect(isInvoicePayable(undefined, undefined)).toBe(false);
});
});
+
+it("retains exact document principal when its rounded base is zero", () => {
+ const result = invoiceSettlementValidator.safeParse({
+ paymentId: "pay",
+ targetSalesInvoiceId: "inv",
+ appliedAmount: 0,
+ discountAmount: 0,
+ writeOffAmount: 0,
+ sourceAmount: 0.01,
+ sourceExchangeRate: 100000,
+ targetExchangeRate: 100000,
+ appliedDate: "2026-09-07"
+ });
+ expect(result.success).toBe(true);
+ if (result.success) expect(result.data).toHaveProperty("sourceAmount", 0.01);
+});
diff --git a/apps/erp/app/modules/invoicing/invoicing.models.ts b/apps/erp/app/modules/invoicing/invoicing.models.ts
index 338daab5e2..fe5e055190 100644
--- a/apps/erp/app/modules/invoicing/invoicing.models.ts
+++ b/apps/erp/app/modules/invoicing/invoicing.models.ts
@@ -419,16 +419,10 @@ export const paymentValidator = z
reference: zfd.text(z.string().optional()),
memo: zfd.text(z.string().optional())
})
- .refine(
- (d) =>
- d.paymentType === "Receipt"
- ? Boolean(d.customerId)
- : Boolean(d.supplierId),
- {
- message: "Receipt requires a customer; Disbursement requires a supplier",
- path: ["customerId"]
- }
- );
+ .refine((d) => Boolean(d.customerId) !== Boolean(d.supplierId), {
+ message: "A payment requires exactly one customer or supplier",
+ path: ["customerId"]
+ });
// The raw object schema (no refinements). Routes that need to `.omit()` a source
// key before injecting it from the URL use THIS — peeling `.refine()` layers off
@@ -443,7 +437,8 @@ export const invoiceSettlementBase = z.object({
targetSalesInvoiceId: zfd.text(z.string().optional()),
targetPurchaseInvoiceId: zfd.text(z.string().optional()),
targetMemoId: zfd.text(z.string().optional()),
- appliedAmount: zfd.numeric(z.number().nonnegative().default(0)),
+ sourceAmount: zfd.numeric(z.number().finite().nonnegative().optional()),
+ appliedAmount: zfd.numeric(z.number().finite().nonnegative().default(0)),
discountAmount: zfd.numeric(z.number().nonnegative().default(0)),
writeOffAmount: zfd.numeric(z.number().nonnegative().default(0)),
targetExchangeRate: zfd.numeric(
@@ -477,7 +472,8 @@ export const invoiceSettlementValidator = invoiceSettlementBase
(d) =>
Number(d.appliedAmount) +
Number(d.discountAmount) +
- Number(d.writeOffAmount) >
+ Number(d.writeOffAmount) +
+ Number(d.sourceAmount ?? 0) >
0,
{
message: "At least one of applied / discount / write-off must be > 0",
@@ -485,22 +481,15 @@ export const invoiceSettlementValidator = invoiceSettlementBase
}
);
-// Sub-cent balances are forgiven as dust: an outstanding amount below one cent
-// (the smallest representable currency unit) can't be collected and is treated
-// as paid. Kept in sync with the SQL view forgiveness in
-// 20260630151500_invoice-dust-forgiveness.sql.
-export const INVOICE_DUST_THRESHOLD = 0.01;
-
-// An invoice is payable when it's posted with an outstanding balance of at least
-// one cent — i.e. not draft/pending, voided, already fully paid, or down to dust.
-// Shared by the sales (AR) and purchase (AP) invoice headers; the caller AND-s in
-// the permission check.
+// The balance views preserve any remaining document minor unit, even when its
+// base equivalent is smaller than a base currency cent.
export function isInvoicePayable(
status: string | null | undefined,
balance: number | null | undefined
): boolean {
return (
!["Voided", "Draft", "Pending", "Paid"].includes(status ?? "") &&
- Number(balance ?? 0) >= INVOICE_DUST_THRESHOLD
+ Number.isFinite(Number(balance)) &&
+ Number(balance ?? 0) > 0
);
}
diff --git a/apps/erp/app/modules/invoicing/invoicing.service.ts b/apps/erp/app/modules/invoicing/invoicing.service.ts
index 7b31b79190..29412c9c5b 100644
--- a/apps/erp/app/modules/invoicing/invoicing.service.ts
+++ b/apps/erp/app/modules/invoicing/invoicing.service.ts
@@ -1,7 +1,28 @@
import type { Database, Json } from "@carbon/database";
-import { getCompanyTimeZone } from "@carbon/database";
+import { fetchAllFromTable, getCompanyTimeZone } from "@carbon/database";
import type { Kysely, KyselyDatabase } from "@carbon/database/client";
-import { applyRate, datetime, EPSILON, round } from "@carbon/utils";
+import {
+ allocatePaymentFunding,
+ applyRate,
+ assertCurrencyDecimals,
+ assertExchangeRate,
+ chunkArray,
+ datetime,
+ type FundingConsumptionRow,
+ type FundingPaymentRow,
+ type FundingRequest,
+ type FundingSource,
+ invoiceRemainingAmounts,
+ isEffectiveSettlement,
+ PAYABLE_POSTING_DESCRIPTIONS,
+ RECEIVABLE_POSTING_DESCRIPTIONS,
+ reduceInvoiceSettlements,
+ remainingFundingSources,
+ round,
+ type SettlementBalanceRow,
+ toBaseAmount,
+ toDocumentAmount
+} from "@carbon/utils";
import { endOfMonth, parseDate } from "@internationalized/date";
import type { SupabaseClient } from "@supabase/supabase-js";
import type { z } from "zod";
@@ -1348,8 +1369,14 @@ export async function updateSalesInvoiceLineOrder(
// Payments (AR receipts + AP disbursements + applications)
// ======================================================================
-export async function getPayment(client: SupabaseClient<Database>, id: string) {
- return client.from("payment").select("*").eq("id", id).single();
+export async function getPayment(
+ client: SupabaseClient<Database>,
+ id: string,
+ companyId?: string
+) {
+ let query = client.from("payment").select("*").eq("id", id);
+ if (companyId) query = query.eq("companyId", companyId);
+ return query.single();
}
export async function getPayments(
@@ -1407,16 +1434,22 @@ export async function getInvoiceSettlements(
companyId: string,
paymentId: string
) {
- // Embed the invoice's human-readable id (salesInvoice/purchaseInvoice.invoiceId)
- // so the UI can show "AP000001" rather than the raw FK id.
- return client
- .from("invoiceSettlement")
- .select(
- "*, salesInvoice:targetSalesInvoiceId(invoiceId), purchaseInvoice:targetPurchaseInvoiceId(invoiceId)"
- )
- .eq("companyId", companyId)
- .eq("paymentId", paymentId)
- .order("appliedDate", { ascending: true });
+ type Settlement = Database["public"]["Tables"]["invoiceSettlement"]["Row"] & {
+ salesInvoice: { invoiceId: string } | null;
+ purchaseInvoice: { invoiceId: string } | null;
+ targetMemo: { memoId: string } | null;
+ };
+ return fetchAllFromTable<Settlement>(
+ client,
+ "invoiceSettlement",
+ "*, salesInvoice:targetSalesInvoiceId(invoiceId), purchaseInvoice:targetPurchaseInvoiceId(invoiceId), targetMemo:targetMemoId(memoId)",
+ (query) =>
+ query
+ .eq("companyId", companyId)
+ .eq("paymentId", paymentId)
+ .order("appliedDate", { ascending: true })
+ .order("id")
+ );
}
// A settlement against an invoice can be sourced by either a cash payment or a
@@ -1443,21 +1476,21 @@ export type InvoiceSettlementSource =
export type InvoiceSettlementForInvoice = {
id: string;
+ sourceAmount: number | null;
appliedAmount: number;
discountAmount: number;
writeOffAmount: number;
fxGainLossAmount: number | null;
targetExchangeRate: number;
- sourceExchangeRate: number;
+ sourceExchangeRate: number | null;
appliedDate: string;
source: InvoiceSettlementSource;
};
// Posted settlements against a specific invoice — BOTH cash payments and applied
// credit/debit memos. Used by the "Applied" panel on the sales/purchase invoice
-// detail page. Two-step query (settlements, then their parent payments/memos)
-// dodges the supabase JS type depth limit a !inner join hits, and lets us drop
-// settlements whose source is still Draft/Voided.
+// detail page. Page the embedded parents with their applications so large histories
+// retain every source without oversized ID lookups.
export async function getInvoiceSettlementsForInvoice(
client: SupabaseClient<Database>,
companyId: string,
@@ -1469,81 +1502,66 @@ export async function getInvoiceSettlementsForInvoice(
}> {
const column =
side === "sales" ? "targetSalesInvoiceId" : "targetPurchaseInvoiceId";
- const apps = await client
- .from("invoiceSettlement")
- .select(
- "id, paymentId, memoId, appliedViaPaymentId, appliedAmount, discountAmount, writeOffAmount, fxGainLossAmount, targetExchangeRate, sourceExchangeRate, appliedDate"
- )
- .eq("companyId", companyId)
- .eq(column, invoiceId)
- .order("appliedDate", { ascending: false });
-
- if (apps.error) return { data: null, error: apps.error };
- if (!apps.data || apps.data.length === 0) return { data: [], error: null };
-
- const paymentIds = apps.data
- .map((a) => a.paymentId)
- .filter((id): id is string => Boolean(id));
- const memoIds = apps.data
- .map((a) => (a as { memoId: string | null }).memoId)
- .filter((id): id is string => Boolean(id));
-
- const [payments, memos] = await Promise.all([
- paymentIds.length > 0
- ? client
- .from("payment")
- .select("id, paymentId, status, paymentDate, currencyCode")
- .in("id", paymentIds)
- .eq("status", "Posted")
- : Promise.resolve({ data: [], error: null }),
- memoIds.length > 0
- ? client
- .from("memo")
- .select(
- "id, memoId, status, postingDate, memoDate, currencyCode, direction"
- )
- .in("id", memoIds)
- .eq("status", "Posted")
- : Promise.resolve({ data: [], error: null })
- ]);
-
- if (payments.error) return { data: null, error: payments.error };
- if (memos.error) return { data: null, error: memos.error };
-
- // deno-lint-ignore no-explicit-any
- const paymentById = new Map(
- ((payments.data ?? []) as any[]).map((p) => [p.id, p])
- );
- // deno-lint-ignore no-explicit-any
- const memoById = new Map(((memos.data ?? []) as any[]).map((m) => [m.id, m]));
-
- // A credit applied through a payment is staged on that payment and only counts
- // once the payment is Posted (mirrors the invoice-balance view gating).
- const viaPaymentIds = apps.data
- .map(
- (a) => (a as { appliedViaPaymentId: string | null }).appliedViaPaymentId
- )
- .filter((id): id is string => Boolean(id));
- const postedViaPayments =
- viaPaymentIds.length > 0
- ? await client
- .from("payment")
- .select("id")
- .in("id", viaPaymentIds)
- .eq("status", "Posted")
- : { data: [] as { id: string }[], error: null };
- if (postedViaPayments.error)
- return { data: null, error: postedViaPayments.error };
- const postedViaSet = new Set(
- ((postedViaPayments.data ?? []) as { id: string }[]).map((p) => p.id)
+ type Settlement = Pick<
+ Database["public"]["Tables"]["invoiceSettlement"]["Row"],
+ | "id"
+ | "paymentId"
+ | "memoId"
+ | "appliedViaPaymentId"
+ | "sourceAmount"
+ | "appliedAmount"
+ | "discountAmount"
+ | "writeOffAmount"
+ | "fxGainLossAmount"
+ | "targetExchangeRate"
+ | "sourceExchangeRate"
+ | "appliedDate"
+ > & {
+ payment: Pick<
+ Database["public"]["Tables"]["payment"]["Row"],
+ "id" | "paymentId" | "status" | "paymentDate" | "currencyCode"
+ > | null;
+ memo: Pick<
+ Database["public"]["Tables"]["memo"]["Row"],
+ | "id"
+ | "memoId"
+ | "status"
+ | "postingDate"
+ | "memoDate"
+ | "currencyCode"
+ | "direction"
+ > | null;
+ appliedViaPayment: { status: string | null } | null;
+ };
+ const apps = await fetchAllFromTable<Settlement>(
+ client,
+ "invoiceSettlement",
+ "id, paymentId, memoId, appliedViaPaymentId, sourceAmount, appliedAmount, discountAmount, writeOffAmount, fxGainLossAmount, targetExchangeRate, sourceExchangeRate, appliedDate, payment:payment!invoiceSettlement_paymentId_fkey(id,paymentId,status,paymentDate,currencyCode), memo:memo!invoiceSettlement_memoId_fkey(id,memoId,status,postingDate,memoDate,currencyCode,direction), appliedViaPayment:payment!invoiceSettlement_appliedViaPaymentId_fkey(status)",
+ (query) =>
+ query
+ .eq("companyId", companyId)
+ .eq(column, invoiceId)
+ .order("appliedDate", { ascending: false })
+ .order("id")
);
+ if (apps.error) return { data: null, error: apps.error };
const merged: InvoiceSettlementForInvoice[] = [];
- for (const a of apps.data) {
- const memoId = (a as { memoId: string | null }).memoId;
+ for (const a of apps.data ?? []) {
+ if (
+ !isEffectiveSettlement({
+ paymentId: a.paymentId,
+ memoId: a.memoId,
+ appliedViaPaymentId: a.appliedViaPaymentId,
+ paymentStatus: a.payment?.status ?? null,
+ memoStatus: a.memo?.status ?? null,
+ viaStatus: a.appliedViaPayment?.status ?? null
+ })
+ )
+ continue;
let source: InvoiceSettlementSource | null = null;
- if (a.paymentId && paymentById.has(a.paymentId)) {
- const p = paymentById.get(a.paymentId);
+ if (a.paymentId && a.payment) {
+ const p = a.payment;
source = {
type: "payment",
id: p.id,
@@ -1552,12 +1570,8 @@ export async function getInvoiceSettlementsForInvoice(
date: p.paymentDate,
currencyCode: p.currencyCode
};
- } else if (memoId && memoById.has(memoId)) {
- const viaId = (a as { appliedViaPaymentId: string | null })
- .appliedViaPaymentId;
- // Staged on a Draft payment — not applied yet, so omit it from the card.
- if (viaId && !postedViaSet.has(viaId)) continue;
- const m = memoById.get(memoId);
+ } else if (a.memoId && a.memo) {
+ const m = a.memo;
source = {
type: "memo",
id: m.id,
@@ -1568,10 +1582,10 @@ export async function getInvoiceSettlementsForInvoice(
direction: m.direction
};
}
- // Skip settlements whose source isn't Posted (a Draft/Voided payment/memo).
if (!source) continue;
merged.push({
id: a.id,
+ sourceAmount: a.sourceAmount,
appliedAmount: Number(a.appliedAmount),
discountAmount: Number(a.discountAmount),
writeOffAmount: Number(a.writeOffAmount),
@@ -1584,7 +1598,32 @@ export async function getInvoiceSettlementsForInvoice(
});
}
- return { data: merged, error: null };
+ const bySource = new Map<string, InvoiceSettlementForInvoice>();
+ for (const row of merged) {
+ const key = `${row.source.type}:${row.source.id}:${row.appliedDate}`;
+ const previous = bySource.get(key);
+ if (!previous) {
+ bySource.set(key, { ...row });
+ continue;
+ }
+ previous.appliedAmount = round(previous.appliedAmount + row.appliedAmount);
+ previous.discountAmount = round(
+ previous.discountAmount + row.discountAmount
+ );
+ previous.writeOffAmount = round(
+ previous.writeOffAmount + row.writeOffAmount
+ );
+ previous.sourceAmount =
+ previous.sourceAmount == null || row.sourceAmount == null
+ ? null
+ : round(previous.sourceAmount + row.sourceAmount);
+ previous.fxGainLossAmount = round(
+ Number(previous.fxGainLossAmount ?? 0) + Number(row.fxGainLossAmount ?? 0)
+ );
+ if (previous.sourceExchangeRate !== row.sourceExchangeRate)
+ previous.sourceExchangeRate = null;
+ }
+ return { data: [...bySource.values()], error: null };
}
// Where a posted credit/debit memo's balance went — the documents it has been
@@ -1685,91 +1724,389 @@ export async function getMemoApplications(
export async function getOpenSalesInvoicesForCustomer(
client: SupabaseClient<Database>,
companyId: string,
- customerId: string
+ customerId: string,
+ currencyCode?: string
) {
- return client
- .from("salesInvoices")
- .select(
- "id, invoiceId, dateIssued, dateDue, paymentTermId, currencyCode, exchangeRate, totalAmount, balance, status"
- )
- .eq("companyId", companyId)
- .eq("customerId", customerId)
- .in("status", ["Submitted", "Partially Paid", "Overdue"])
- .gt("balance", 0)
- .order("dateDue", { ascending: true });
+ return getOpenInvoicesForParty(
+ client,
+ companyId,
+ true,
+ customerId,
+ currencyCode
+ );
}
-
export async function getOpenPurchaseInvoicesForSupplier(
client: SupabaseClient<Database>,
companyId: string,
- supplierId: string
+ supplierId: string,
+ currencyCode?: string
) {
- return client
- .from("purchaseInvoices")
- .select(
- "id, invoiceId, dateIssued, dateDue, paymentTermId, currencyCode, exchangeRate, totalAmount, balance, status"
- )
- .eq("companyId", companyId)
- .eq("supplierId", supplierId)
- .in("status", ["Open", "Partially Paid", "Overdue"])
- .gt("balance", 0)
- .order("dateDue", { ascending: true });
-}
-
-// The party's available on-account credit in BASE currency: the net unapplied
-// cash across their posted payments (Σ cash − Σ applied). This is the pool a new
-// payment may draw on when it applies more than its own cash. Mirrors the
-// authoritative check in the post-payment edge function; returns 0 on any read
-// error (conservative — posting re-validates under lock). Returns base currency;
-// callers convert to the payment's currency for display via the exchange rate.
-export async function getAvailableOnAccountCredit(
+ return getOpenInvoicesForParty(
+ client,
+ companyId,
+ false,
+ supplierId,
+ currencyCode
+ );
+}
+
+async function getOpenInvoicesForParty(
client: SupabaseClient<Database>,
companyId: string,
- party:
- | { paymentType: "Receipt"; customerId: string }
- | { paymentType: "Disbursement"; supplierId: string }
-): Promise<number> {
- let query = client
- .from("payment")
- .select("id, totalAmount, exchangeRate")
- .eq("companyId", companyId)
- .eq("status", "Posted")
- .eq("paymentType", party.paymentType);
- query =
- party.paymentType === "Receipt"
- ? query.eq("customerId", party.customerId)
- : query.eq("supplierId", party.supplierId);
-
- const payments = await query;
- if (payments.error || !payments.data || payments.data.length === 0) return 0;
-
- const apps = await client
- .from("invoiceSettlement")
- .select("paymentId, appliedAmount, sourceExchangeRate")
- .eq("companyId", companyId)
- .in(
- "paymentId",
- payments.data.map((p) => p.id)
+ isAR: boolean,
+ partyId: string,
+ currencyCode?: string
+) {
+ type OpenInvoiceRow = Pick<
+ Database["public"]["Views"]["salesInvoices" | "purchaseInvoices"]["Row"],
+ | "id"
+ | "invoiceId"
+ // dateIssued + paymentTermId drive the early-payment discount window when a
+ // payment is seeded from these invoices.
+ | "dateIssued"
+ | "dateDue"
+ | "paymentTermId"
+ | "currencyCode"
+ | "exchangeRate"
+ | "totalAmount"
+ | "balance"
+ | "status"
+ >;
+ type SettlementRow = SettlementBalanceRow & {
+ paymentId: string | null;
+ memoId: string | null;
+ appliedViaPaymentId: string | null;
+ payment: { status: string } | null;
+ memo: { status: string } | null;
+ appliedViaPayment: { status: string } | null;
+ };
+ type ControlRow = Pick<
+ Database["public"]["Tables"]["journalLine"]["Row"],
+ "documentId" | "amount"
+ >;
+ const [invoices, company] = await Promise.all([
+ fetchAllFromTable<OpenInvoiceRow>(
+ client,
+ isAR ? "salesInvoices" : "purchaseInvoices",
+ "id, invoiceId, dateIssued, dateDue, paymentTermId, currencyCode, exchangeRate, totalAmount, balance, status",
+ (query) => {
+ query = query
+ .eq("companyId", companyId)
+ .in(
+ "status",
+ isAR
+ ? ["Submitted", "Partially Paid", "Overdue"]
+ : ["Open", "Partially Paid", "Overdue"]
+ )
+ .eq(isAR ? "customerId" : "supplierId", partyId);
+ if (currencyCode) query = query.eq("currencyCode", currencyCode);
+ return query.order("dateDue", { ascending: true }).order("id");
+ }
+ ),
+ client.from("company").select("companyGroupId").eq("id", companyId).single()
+ ]);
+ if (invoices.error) return { data: null, error: invoices.error };
+ if (company.error || !company.data?.companyGroupId)
+ return {
+ data: null,
+ error: { message: "Company currency configuration is missing" }
+ };
+ const currencies = await client
+ .from("currency")
+ .select("code, decimalPlaces")
+ .eq("companyGroupId", company.data.companyGroupId);
+ if (currencies.error) return { data: null, error: currencies.error };
+ const ids = invoices.data.map((i) => i.id!);
+ const settlements: SettlementRow[] = [];
+ const controls: ControlRow[] = [];
+ // Bound filter URLs as well as response pages. A single invoice can itself
+ // have more than one response page of control lines or settlements.
+ for (const batch of chunkArray(ids, 100)) {
+ const [batchSettlements, batchControls] = await Promise.all([
+ fetchAllFromTable<SettlementRow>(
+ client,
+ "invoiceSettlement",
+ "paymentId, memoId, targetSalesInvoiceId, targetPurchaseInvoiceId, sourceAmount, appliedAmount, discountAmount, writeOffAmount, appliedViaPaymentId, payment:payment!invoiceSettlement_paymentId_fkey(status), memo:memo!invoiceSettlement_memoId_fkey(status), appliedViaPayment:payment!invoiceSettlement_appliedViaPaymentId_fkey(status)",
+ (query) =>
+ query
+ .eq("companyId", companyId)
+ .in(
+ isAR ? "targetSalesInvoiceId" : "targetPurchaseInvoiceId",
+ batch
+ )
+ .order("id")
+ ),
+ fetchAllFromTable<ControlRow>(
+ client,
+ "journalLine",
+ "documentId, amount, journal:journalId!inner(status,sourceType,companyId)",
+ (query) =>
+ query
+ .eq("companyId", companyId)
+ .eq("journal.companyId", companyId)
+ .eq("journal.status", "Posted")
+ .eq(
+ "journal.sourceType",
+ isAR ? "Sales Invoice" : "Purchase Invoice"
+ )
+ .eq("documentType", "Invoice")
+ .in(
+ "description",
+ isAR
+ ? RECEIVABLE_POSTING_DESCRIPTIONS
+ : PAYABLE_POSTING_DESCRIPTIONS
+ )
+ .in("documentId", batch)
+ .order("id")
+ )
+ ]);
+ const error = batchSettlements.error ?? batchControls.error;
+ if (error) return { data: null, error };
+ settlements.push(...(batchSettlements.data ?? []));
+ controls.push(...(batchControls.data ?? []));
+ }
+ try {
+ const decimals = new Map(
+ (currencies.data ?? []).map((c) => [c.code, c.decimalPlaces])
+ );
+ if (currencyCode) requireCurrencyDecimals(decimals, currencyCode);
+ const effective = settlements.filter((s) =>
+ isEffectiveSettlement({
+ paymentId: s.paymentId,
+ memoId: s.memoId,
+ appliedViaPaymentId: s.appliedViaPaymentId,
+ paymentStatus: s.payment?.status ?? null,
+ memoStatus: s.memo?.status ?? null,
+ viaStatus: s.appliedViaPayment?.status ?? null
+ })
);
- if (apps.error) return 0;
+ const controlAmounts = new Map<string, number>();
+ for (const line of controls)
+ if (line.documentId)
+ controlAmounts.set(
+ line.documentId,
+ (controlAmounts.get(line.documentId) ?? 0) + Number(line.amount)
+ );
+ return {
+ data: (invoices.data ?? [])
+ .map((i) => {
+ if (!i.id || !i.currencyCode)
+ throw new Error("Invoice currency or identity is missing");
+ const remaining = invoiceRemainingAmounts(
+ i,
+ effective,
+ controlAmounts,
+ requireCurrencyDecimals(decimals, i.currencyCode!),
+ isAR
+ );
+ return {
+ ...i,
+ id: i.id,
+ currencyCode: i.currencyCode,
+ balance: remaining.remainingBase,
+ remainingDocument: remaining.remainingDocument
+ };
+ })
+ .filter((i) => i.remainingDocument > 0),
+ error: null
+ };
+ } catch (error) {
+ return {
+ data: null,
+ error: {
+ message:
+ error instanceof Error
+ ? error.message
+ : "Unable to load invoice balances"
+ }
+ };
+ }
+}
- const appliedBaseByPayment = new Map<string, number>();
- for (const a of apps.data ?? []) {
- if (!a.paymentId) continue;
- appliedBaseByPayment.set(
- a.paymentId,
- (appliedBaseByPayment.get(a.paymentId) ?? 0) +
- Number(a.appliedAmount) * Number(a.sourceExchangeRate)
+type PaymentParty =
+ | { paymentType: "Receipt"; customerId: string }
+ | { paymentType: "Disbursement"; supplierId: string };
+
+function requireCurrencyDecimals(
+ decimals: Map<string, number>,
+ code: string
+): number {
+ const value = decimals.get(code);
+ if (value == null || !Number.isInteger(value) || value < 0) {
+ throw new Error(`Currency ${code} requires configured decimal places`);
+ }
+ assertCurrencyDecimals(value);
+ return value;
+}
+
+export async function getPaymentCurrencyConfiguration(
+ client: SupabaseClient<Database>,
+ companyId: string,
+ currencyCode: string
+): Promise<{ baseCurrencyCode: string; currencyDecimals: number }> {
+ const company = await client
+ .from("company")
+ .select("companyGroupId, baseCurrencyCode")
+ .eq("id", companyId)
+ .single();
+ if (
+ company.error ||
+ !company.data?.companyGroupId ||
+ !company.data.baseCurrencyCode
+ ) {
+ throw new Error("Company currency configuration is missing");
+ }
+ const currencies = await client
+ .from("currency")
+ .select("code, decimalPlaces")
+ .eq("companyGroupId", company.data.companyGroupId)
+ .eq("code", currencyCode);
+ if (currencies.error) throw new Error(currencies.error.message);
+ return {
+ baseCurrencyCode: company.data.baseCurrencyCode,
+ currencyDecimals: requireCurrencyDecimals(
+ new Map((currencies.data ?? []).map((c) => [c.code, c.decimalPlaces])),
+ currencyCode
+ )
+ };
+}
+
+async function loadOnAccountSources(
+ client: SupabaseClient<Database>,
+ companyId: string,
+ party: PaymentParty,
+ currencyCode?: string
+) {
+ const [payments, company] = await Promise.all([
+ fetchAllFromTable<FundingPaymentRow>(
+ client,
+ "payment",
+ "id, totalAmount, exchangeRate, postingDate, paymentDate, currencyCode",
+ (query) => {
+ query = query
+ .eq("companyId", companyId)
+ .eq("status", "Posted")
+ .eq("paymentType", party.paymentType);
+ query =
+ party.paymentType === "Receipt"
+ ? query.eq("customerId", party.customerId)
+ : query.eq("supplierId", party.supplierId);
+ if (currencyCode) query = query.eq("currencyCode", currencyCode);
+ return query.order("id");
+ }
+ ),
+ client.from("company").select("companyGroupId").eq("id", companyId).single()
+ ]);
+ if (payments.error) throw new Error(payments.error.message);
+ if (company.error || !company.data?.companyGroupId)
+ throw new Error("Company currency configuration is missing");
+ const currencies = await client
+ .from("currency")
+ .select("code, decimalPlaces")
+ .eq("companyGroupId", company.data.companyGroupId);
+ if (currencies.error) throw new Error(currencies.error.message);
+ const decimals = new Map(
+ (currencies.data ?? []).map((c) => [c.code, c.decimalPlaces])
+ );
+ if (currencyCode) requireCurrencyDecimals(decimals, currencyCode);
+ if (!payments.data.length)
+ return { sources: [] as FundingSource[], decimals };
+ // Filter through the applying parent instead of sending an unbounded source-ID
+ // list in the URL. Every valid use of prior funding has the same party/currency.
+ const apps = await fetchAllFromTable<
+ FundingConsumptionRow & { payment: { status: string } | null }
+ >(
+ client,
+ "invoiceSettlement",
+ "paymentId, sourcePaymentId, sourceAmount, appliedAmount, fxGainLossAmount, payment:payment!invoiceSettlement_paymentId_fkey!inner(status)",
+ (query) => {
+ query = query
+ .eq("companyId", companyId)
+ .eq("payment.companyId", companyId)
+ .eq("payment.status", "Posted")
+ .eq("payment.paymentType", party.paymentType);
+ query =
+ party.paymentType === "Receipt"
+ ? query.eq("payment.customerId", party.customerId)
+ : query.eq("payment.supplierId", party.supplierId);
+ if (currencyCode) query = query.eq("payment.currencyCode", currencyCode);
+ return query.order("id");
+ }
+ );
+ if (apps.error) throw new Error(apps.error.message);
+ const effective = (apps.data ?? []).filter(
+ (a) => a.payment?.status === "Posted"
+ );
+ return {
+ sources: remainingFundingSources(
+ payments.data ?? [],
+ effective,
+ decimals,
+ party.paymentType === "Receipt"
+ ),
+ decimals
+ };
+}
+
+export async function getAvailableOnAccountCreditSources(
+ client: SupabaseClient<Database>,
+ companyId: string,
+ party: PaymentParty,
+ currencyCode: string
+): Promise<{
+ data: {
+ sources: FundingSource[];
+ availableDocumentAmount: number;
+ availableBaseAmount: number;
+ } | null;
+ error: { message: string } | null;
+}> {
+ try {
+ const { sources, decimals } = await loadOnAccountSources(
+ client,
+ companyId,
+ party,
+ currencyCode
);
+ return {
+ data: {
+ sources,
+ availableDocumentAmount: toDocumentAmount(
+ sources.reduce((sum, p) => sum + p.remainingDocument, 0),
+ 1,
+ requireCurrencyDecimals(decimals, currencyCode)
+ ),
+ availableBaseAmount: round(
+ sources.reduce((sum, p) => sum + p.remainingBase, 0)
+ )
+ },
+ error: null
+ };
+ } catch (error) {
+ return {
+ data: null,
+ error: {
+ message:
+ error instanceof Error
+ ? error.message
+ : "Unable to load payment funding"
+ }
+ };
}
+}
- let baseCredit = 0;
- for (const p of payments.data) {
- baseCredit +=
- Number(p.totalAmount) * Number(p.exchangeRate) -
- (appliedBaseByPayment.get(p.id) ?? 0);
+/** Base-total contract for other readers; the composer uses typed document sources. */
+export async function getAvailableOnAccountCredit(
+ client: SupabaseClient<Database>,
+ companyId: string,
+ party: PaymentParty
+): Promise<number> {
+ try {
+ const { sources } = await loadOnAccountSources(client, companyId, party);
+ return round(sources.reduce((sum, p) => sum + p.remainingBase, 0));
+ } catch {
+ return 0;
}
- return Math.max(0, round(baseCredit));
}
export async function upsertPayment(
@@ -1790,13 +2127,23 @@ export async function upsertPayment(
if ("createdBy" in payment) {
return client
.from("payment")
- .insert([sanitize(payment)])
+ .insert([
+ {
+ ...sanitize(payment),
+ customerId: payment.customerId ?? null,
+ supplierId: payment.supplierId ?? null
+ }
+ ])
.select("id, paymentId")
.single();
}
return client
.from("payment")
- .update(sanitize(payment))
+ .update({
+ ...sanitize(payment),
+ customerId: payment.customerId ?? null,
+ supplierId: payment.supplierId ?? null
+ })
.eq("id", payment.id)
.select("id, paymentId")
.single();
@@ -1849,6 +2196,241 @@ export async function deleteInvoiceSettlement(
// applications wiped and nothing in their place. Kysely bypasses RLS, so we
// re-assert the payment is Draft inside the txn — the FOR UPDATE lock also
// serializes this against a concurrent post/void of the same payment.
+async function loadTransactionCurrency(
+ db: Kysely<KyselyDatabase>,
+ companyId: string,
+ code: string
+) {
+ const company = await db
+ .selectFrom("company")
+ .select(["companyGroupId", "baseCurrencyCode"])
+ .where("id", "=", companyId)
+ .executeTakeFirst();
+ if (!company?.companyGroupId)
+ throw new Error("Company currency configuration is missing");
+ const currencies = await db
+ .selectFrom("currency")
+ .select(["code", "decimalPlaces"])
+ .where("companyGroupId", "=", company.companyGroupId)
+ .execute();
+ const decimals = new Map(currencies.map((c) => [c.code, c.decimalPlaces]));
+ return {
+ decimals,
+ currencyDecimals: requireCurrencyDecimals(decimals, code)
+ };
+}
+
+async function loadTransactionInvoices(
+ db: Kysely<KyselyDatabase>,
+ companyId: string,
+ ids: string[],
+ isAR: boolean,
+ currencyCode: string,
+ partyId: string,
+ decimals: number
+) {
+ const view = isAR ? "salesInvoices" : "purchaseInvoices";
+ const targetColumn = isAR
+ ? "invoiceSettlement.targetSalesInvoiceId"
+ : "invoiceSettlement.targetPurchaseInvoiceId";
+ const invoices = isAR
+ ? await db
+ .selectFrom("salesInvoice")
+ .select([
+ "id",
+ "status",
+ "exchangeRate",
+ "currencyCode",
+ "customerId as partyId"
+ ])
+ .where("companyId", "=", companyId)
+ .where("id", "in", ids)
+ .orderBy("id")
+ .forUpdate()
+ .execute()
+ : await db
+ .selectFrom("purchaseInvoice")
+ .select([
+ "id",
+ "status",
+ "exchangeRate",
+ "currencyCode",
+ "supplierId as partyId"
+ ])
+ .where("companyId", "=", companyId)
+ .where("id", "in", ids)
+ .orderBy("id")
+ .forUpdate()
+ .execute();
+ for (const id of ids) {
+ const invoice = invoices.find((i) => i.id === id);
+ if (!invoice) throw new Error(`Invoice ${id} not found`);
+ if (invoice.partyId !== partyId)
+ throw new Error("A payment can only settle invoices for the same party");
+ if (invoice.currencyCode !== currencyCode)
+ throw new Error("Invoice and payment currency must match");
+ if (
+ !(
+ isAR
+ ? ["Submitted", "Partially Paid", "Overdue"]
+ : ["Open", "Partially Paid", "Overdue"]
+ ).includes(invoice.status)
+ )
+ throw new Error(`Invoice ${id} is not open`);
+ assertExchangeRate(Number(invoice.exchangeRate));
+ }
+ const [totals, settlements, controls] = await Promise.all([
+ db
+ .selectFrom(view)
+ .select(["id", "totalAmount", "exchangeRate"])
+ .where("companyId", "=", companyId)
+ .where("id", "in", ids)
+ .execute(),
+ db
+ .selectFrom("invoiceSettlement")
+ .leftJoin(
+ "payment as applyingPayment",
+ "applyingPayment.id",
+ "invoiceSettlement.paymentId"
+ )
+ .leftJoin(
+ "memo as sourceMemo",
+ "sourceMemo.id",
+ "invoiceSettlement.memoId"
+ )
+ .leftJoin(
+ "payment as viaPayment",
+ "viaPayment.id",
+ "invoiceSettlement.appliedViaPaymentId"
+ )
+ .select([
+ "invoiceSettlement.targetSalesInvoiceId",
+ "invoiceSettlement.targetPurchaseInvoiceId",
+ "invoiceSettlement.sourceAmount",
+ "invoiceSettlement.appliedAmount",
+ "invoiceSettlement.discountAmount",
+ "invoiceSettlement.writeOffAmount"
+ ])
+ .where("invoiceSettlement.companyId", "=", companyId)
+ .where(targetColumn, "in", ids)
+ .where((eb) =>
+ eb.or([
+ eb.and([
+ eb("applyingPayment.companyId", "=", companyId),
+ eb("applyingPayment.status", "=", "Posted")
+ ]),
+ eb.and([
+ eb("sourceMemo.companyId", "=", companyId),
+ eb("sourceMemo.status", "=", "Posted"),
+ eb.or([
+ eb("invoiceSettlement.appliedViaPaymentId", "is", null),
+ eb.and([
+ eb("viaPayment.companyId", "=", companyId),
+ eb("viaPayment.status", "=", "Posted")
+ ])
+ ])
+ ])
+ ])
+ )
+ .execute(),
+ db
+ .selectFrom("journalLine")
+ .innerJoin("journal", "journal.id", "journalLine.journalId")
+ .select(["journalLine.documentId", "journalLine.amount"])
+ .where("journalLine.companyId", "=", companyId)
+ .where("journal.companyId", "=", companyId)
+ .where("journal.status", "=", "Posted")
+ .where(
+ "journal.sourceType",
+ "=",
+ isAR ? "Sales Invoice" : "Purchase Invoice"
+ )
+ .where("journalLine.documentType", "=", "Invoice")
+ .where(
+ "journalLine.description",
+ "in",
+ isAR ? RECEIVABLE_POSTING_DESCRIPTIONS : PAYABLE_POSTING_DESCRIPTIONS
+ )
+ .where("journalLine.documentId", "in", ids)
+ .execute()
+ ]);
+ const controlAmounts = new Map<string, number>();
+ for (const line of controls)
+ if (line.documentId)
+ controlAmounts.set(
+ line.documentId,
+ (controlAmounts.get(line.documentId) ?? 0) + Number(line.amount)
+ );
+ return new Map(
+ totals.map((i) => [
+ i.id!,
+ {
+ ...invoiceRemainingAmounts(
+ i,
+ settlements,
+ controlAmounts,
+ decimals,
+ isAR
+ ),
+ exchangeRate: Number(i.exchangeRate)
+ }
+ ])
+ );
+}
+
+/** Reserve both invoice applications and refunds against the same locked memo. */
+async function loadTransactionMemoConsumption(
+ trx: Kysely<KyselyDatabase>,
+ companyId: string,
+ memoIds: string[],
+ excludePaymentId: string
+) {
+ return trx
+ .selectFrom("invoiceSettlement")
+ .leftJoin("payment as viaPayment", (join) =>
+ join
+ .onRef("viaPayment.id", "=", "invoiceSettlement.appliedViaPaymentId")
+ .onRef("viaPayment.companyId", "=", "invoiceSettlement.companyId")
+ )
+ .leftJoin("payment as refund", (join) =>
+ join
+ .onRef("refund.id", "=", "invoiceSettlement.paymentId")
+ .onRef("refund.companyId", "=", "invoiceSettlement.companyId")
+ )
+ .select([
+ "invoiceSettlement.memoId",
+ "invoiceSettlement.targetMemoId",
+ "invoiceSettlement.sourceAmount",
+ "invoiceSettlement.appliedAmount",
+ "invoiceSettlement.fxGainLossAmount"
+ ])
+ .where("invoiceSettlement.companyId", "=", companyId)
+ .where((eb) =>
+ eb.or([
+ eb.and([
+ eb("invoiceSettlement.memoId", "in", memoIds),
+ eb.or([
+ eb("invoiceSettlement.appliedViaPaymentId", "is", null),
+ eb.and([
+ eb(
+ "invoiceSettlement.appliedViaPaymentId",
+ "!=",
+ excludePaymentId
+ ),
+ eb("viaPayment.status", "in", ["Draft", "Posted"])
+ ])
+ ])
+ ]),
+ eb.and([
+ eb("invoiceSettlement.targetMemoId", "in", memoIds),
+ eb("invoiceSettlement.paymentId", "!=", excludePaymentId),
+ eb("refund.status", "in", ["Draft", "Posted"])
+ ])
+ ])
+ )
+ .execute();
+}
+
export async function replaceInvoiceSettlements(
db: Kysely<KyselyDatabase>,
args: {
@@ -1864,113 +2446,403 @@ export async function replaceInvoiceSettlements(
return db.transaction().execute(async (trx) => {
const payment = await trx
.selectFrom("payment")
- .select(["id", "status", "paymentType", "customerId", "supplierId"])
+ .selectAll()
.where("id", "=", args.paymentId)
.where("companyId", "=", args.companyId)
.forUpdate()
.executeTakeFirst();
-
- if (!payment) {
- throw new Error("Payment not found");
- }
- if (payment.status !== "Draft") {
+ if (!payment) throw new Error("Payment not found");
+ if (payment.status !== "Draft")
throw new Error(
"Applications can only be edited while the payment is Draft"
);
- }
-
- await trx
- .deleteFrom("invoiceSettlement")
- .where("paymentId", "=", args.paymentId)
- .execute();
-
- if (args.applications.length === 0) return;
-
- // Guard the source→target relationship before inserting. Kysely bypasses
- // RLS, so this is the only enforcement point for the cash path: a Receipt
- // may only settle ITS customer's sales invoices, a Disbursement only ITS
- // supplier's purchase invoices. (Memo targets aren't persisted here — the
- // insert below maps only invoice targets — so reject them rather than write
- // an orphan row with every target FK null.)
- if (args.applications.some((a) => a.targetMemoId)) {
- throw new Error("Settling a memo from a payment is not supported here");
- }
- const isReceipt = payment.paymentType === "Receipt";
- const salesInvoiceIds = [
- ...new Set(
- args.applications
- .map((a) => a.targetSalesInvoiceId)
- .filter((id): id is string => Boolean(id))
- )
- ];
- const purchaseInvoiceIds = [
- ...new Set(
- args.applications
- .map((a) => a.targetPurchaseInvoiceId)
- .filter((id): id is string => Boolean(id))
+ const { decimals, currencyDecimals } = await loadTransactionCurrency(
+ trx,
+ args.companyId,
+ payment.currencyCode
+ );
+ assertExchangeRate(Number(payment.exchangeRate));
+ const isAR = Boolean(payment.customerId);
+ const cashIn = payment.paymentType === "Receipt";
+ const isRefund = cashIn !== isAR;
+ const partyId = isAR ? payment.customerId : payment.supplierId;
+ if (!partyId || Boolean(payment.customerId) === Boolean(payment.supplierId))
+ throw new Error("Payment must have exactly one customer or supplier");
+ for (const app of args.applications) {
+ if (
+ app.sourceAmount != null &&
+ toDocumentAmount(app.sourceAmount, 1, currencyDecimals) !==
+ app.sourceAmount
+ ) {
+ throw new Error("Source amount exceeds document currency precision");
+ }
+ if ("sourcePaymentId" in app || "fxGainLossAmount" in app || app.memoId)
+ throw new Error("Funding source and FX are server-authoritative");
+ if (app.sourceExchangeRate !== Number(payment.exchangeRate))
+ throw new Error("Source exchange rate does not match the payment");
+ if (
+ isRefund
+ ? !app.targetMemoId ||
+ app.targetSalesInvoiceId ||
+ app.targetPurchaseInvoiceId ||
+ app.discountAmount !== 0 ||
+ app.writeOffAmount !== 0
+ : app.targetMemoId ||
+ (isAR
+ ? !app.targetSalesInvoiceId || app.targetPurchaseInvoiceId
+ : !app.targetPurchaseInvoiceId || app.targetSalesInvoiceId)
)
- ];
- if (isReceipt && purchaseInvoiceIds.length > 0) {
- throw new Error("A receipt can only be applied to sales invoices");
- }
- if (!isReceipt && salesInvoiceIds.length > 0) {
- throw new Error(
- "A disbursement can only be applied to purchase invoices"
- );
+ throw new Error(
+ "Payments target same-side invoices; refunds target reducing memos without adjustments"
+ );
}
- if (salesInvoiceIds.length > 0) {
- const rows = await trx
- .selectFrom("salesInvoice")
- .select(["id", "customerId"])
- .where("id", "in", salesInvoiceIds)
- .where("companyId", "=", args.companyId)
- .execute();
- const customerById = new Map(rows.map((r) => [r.id, r.customerId]));
- for (const id of salesInvoiceIds) {
- if (!customerById.has(id))
- throw new Error(`Sales invoice ${id} not found`);
- if (customerById.get(id) !== payment.customerId)
+ if (isRefund) {
+ const ids = [
+ ...new Set(args.applications.map((app) => app.targetMemoId!))
+ ].sort();
+ const memos = ids.length
+ ? await trx
+ .selectFrom("memo")
+ .selectAll()
+ .where("companyId", "=", args.companyId)
+ .where("id", "in", ids)
+ .orderBy("id")
+ .forUpdate()
+ .execute()
+ : [];
+ if (memos.length !== ids.length)
+ throw new Error("Refund memo not found in this company");
+ for (const memo of memos) {
+ if (
+ memo.status !== "Posted" ||
+ memo.direction !== (isAR ? "Credit" : "Debit") ||
+ (isAR ? memo.customerId : memo.supplierId) !== partyId ||
+ memo.currencyCode !== payment.currencyCode
+ ) {
throw new Error(
- "A payment can only be applied to its own customer's invoices"
+ "Refund target must be a posted reducing memo with matching party and currency"
);
+ }
}
+ const consumption = ids.length
+ ? await loadTransactionMemoConsumption(
+ trx,
+ args.companyId,
+ ids,
+ payment.id
+ )
+ : [];
+ const remaining = new Map(
+ remainingFundingSources(
+ memos.map((memo) => ({
+ ...memo,
+ totalAmount: memo.amount,
+ paymentDate: memo.memoDate
+ })),
+ consumption.map((row) => ({
+ ...row,
+ paymentId: row.memoId ?? row.targetMemoId,
+ sourcePaymentId: null,
+ fxGainLossAmount: row.targetMemoId ? 0 : row.fxGainLossAmount
+ })),
+ decimals,
+ isAR
+ ).map((source) => [source.paymentId, source])
+ );
+ const requests = new Map<string, FundingRequest>();
+ const dates = new Map<string, string>();
+ for (const app of args.applications) {
+ const memo = remaining.get(app.targetMemoId!);
+ if (!memo) throw new Error("Memo has no remaining refund balance");
+ if (app.targetExchangeRate !== memo.exchangeRate)
+ throw new Error("Target exchange rate does not match the memo");
+ const requested =
+ app.sourceAmount ??
+ (app.appliedAmount === memo.remainingBase
+ ? memo.remainingDocument
+ : toDocumentAmount(
+ app.appliedAmount,
+ memo.exchangeRate,
+ currencyDecimals
+ ));
+ const request = requests.get(app.targetMemoId!) ?? {
+ targetId: app.targetMemoId!,
+ targetExchangeRate: memo.exchangeRate,
+ remainingDocument: memo.remainingDocument,
+ remainingBase: memo.remainingBase,
+ requestedDocumentPrincipal: 0,
+ discountAmount: 0,
+ writeOffAmount: 0
+ };
+ request.requestedDocumentPrincipal = toDocumentAmount(
+ request.requestedDocumentPrincipal + requested,
+ 1,
+ currencyDecimals
+ );
+ requests.set(app.targetMemoId!, request);
+ dates.set(app.targetMemoId!, app.appliedDate);
+ }
+ const allocation = allocatePaymentFunding({
+ currentPayment: {
+ paymentId: payment.id,
+ postingDate: payment.paymentDate,
+ exchangeRate: Number(payment.exchangeRate),
+ remainingDocument: Number(payment.totalAmount),
+ remainingBase: toBaseAmount(
+ Number(payment.totalAmount),
+ Number(payment.exchangeRate)
+ )
+ },
+ priorSources: [],
+ requests: [...requests.values()],
+ currencyDecimals,
+ isAR: cashIn
+ });
+ await trx
+ .deleteFrom("invoiceSettlement")
+ .where("paymentId", "=", payment.id)
+ .where("companyId", "=", args.companyId)
+ .execute();
+ if (allocation.applications.length)
+ await trx
+ .insertInto("invoiceSettlement")
+ .values(
+ allocation.applications.map(({ targetId, ...application }) => ({
+ ...application,
+ paymentId: payment.id,
+ targetMemoId: targetId,
+ targetSalesInvoiceId: null,
+ targetPurchaseInvoiceId: null,
+ appliedDate: dates.get(targetId)!,
+ createdBy: args.createdBy,
+ companyId: args.companyId
+ }))
+ )
+ .execute();
+ return;
}
- if (purchaseInvoiceIds.length > 0) {
- const rows = await trx
- .selectFrom("purchaseInvoice")
- .select(["id", "supplierId"])
- .where("id", "in", purchaseInvoiceIds)
+ const ids = [
+ ...new Set(
+ args.applications.map(
+ (a) => (isAR ? a.targetSalesInvoiceId : a.targetPurchaseInvoiceId)!
+ )
+ )
+ ].sort();
+ if (!ids.length) {
+ await trx
+ .deleteFrom("invoiceSettlement")
+ .where("paymentId", "=", args.paymentId)
.where("companyId", "=", args.companyId)
.execute();
- const supplierById = new Map(rows.map((r) => [r.id, r.supplierId]));
- for (const id of purchaseInvoiceIds) {
- if (!supplierById.has(id))
- throw new Error(`Purchase invoice ${id} not found`);
- if (supplierById.get(id) !== payment.supplierId)
- throw new Error(
- "A payment can only be applied to its own supplier's invoices"
- );
+ return;
+ }
+ const invoices = await loadTransactionInvoices(
+ trx,
+ args.companyId,
+ ids,
+ isAR,
+ payment.currencyCode,
+ partyId,
+ currencyDecimals
+ );
+ // Existing staged memos reserve target capacity while the cash half is edited.
+ const staged = await trx
+ .selectFrom("invoiceSettlement")
+ .selectAll()
+ .where("companyId", "=", args.companyId)
+ .where("appliedViaPaymentId", "=", args.paymentId)
+ .execute();
+ const stagedMemoIds = [
+ ...new Set(
+ staged
+ .map((row) => row.memoId)
+ .filter((id): id is string => Boolean(id))
+ )
+ ].sort();
+ const stagedMemos = stagedMemoIds.length
+ ? await trx
+ .selectFrom("memo")
+ .select([
+ "id",
+ "status",
+ "direction",
+ "customerId",
+ "supplierId",
+ "currencyCode",
+ "exchangeRate"
+ ])
+ .where("companyId", "=", args.companyId)
+ .where("id", "in", stagedMemoIds)
+ .orderBy("id")
+ .forUpdate()
+ .execute()
+ : [];
+ const stagedMemoById = new Map(stagedMemos.map((memo) => [memo.id, memo]));
+ for (const row of staged) {
+ const memo = row.memoId ? stagedMemoById.get(row.memoId) : undefined;
+ if (
+ !memo ||
+ memo.status !== "Posted" ||
+ memo.direction !== (isAR ? "Credit" : "Debit")
+ ) {
+ throw new Error("Staged applications must use a posted credit memo");
}
+ if (
+ (isAR ? memo.customerId : memo.supplierId) !== partyId ||
+ memo.currencyCode !== payment.currencyCode
+ ) {
+ throw new Error(
+ "Staged credit and payment currency and party must match"
+ );
+ }
+ const id = isAR ? row.targetSalesInvoiceId : row.targetPurchaseInvoiceId;
+ const invoice = id ? invoices.get(id) : undefined;
+ if (!invoice) continue;
+ if (Number(memo.exchangeRate) !== invoice.exchangeRate)
+ throw new Error("Staged credit and invoice exchange rates must match");
+ const reserved = reduceInvoiceSettlements(
+ [row],
+ invoice.exchangeRate,
+ currencyDecimals
+ );
+ invoice.remainingDocument = toDocumentAmount(
+ invoice.remainingDocument - reserved.document,
+ 1,
+ currencyDecimals
+ );
+ invoice.remainingBase = round(invoice.remainingBase - reserved.base);
}
-
+ let priorQuery = trx
+ .selectFrom("payment")
+ .selectAll()
+ .where("companyId", "=", args.companyId)
+ .where("status", "=", "Posted")
+ .where("paymentType", "=", payment.paymentType)
+ .where("currencyCode", "=", payment.currencyCode);
+ priorQuery = isAR
+ ? priorQuery.where("customerId", "=", partyId)
+ : priorQuery.where("supplierId", "=", partyId);
+ const priorPayments = await priorQuery.orderBy("id").forUpdate().execute();
+ const sourceIds = priorPayments.map((p) => p.id);
+ const consumption = sourceIds.length
+ ? await trx
+ .selectFrom("invoiceSettlement")
+ .innerJoin(
+ "payment as applyingPayment",
+ "applyingPayment.id",
+ "invoiceSettlement.paymentId"
+ )
+ .select([
+ "invoiceSettlement.paymentId",
+ "invoiceSettlement.sourcePaymentId",
+ "invoiceSettlement.sourceAmount",
+ "invoiceSettlement.appliedAmount",
+ "invoiceSettlement.fxGainLossAmount"
+ ])
+ .where("invoiceSettlement.companyId", "=", args.companyId)
+ .where("applyingPayment.companyId", "=", args.companyId)
+ .where("applyingPayment.status", "=", "Posted")
+ .where((eb) =>
+ eb.or([
+ eb("invoiceSettlement.sourcePaymentId", "in", sourceIds),
+ eb("invoiceSettlement.paymentId", "in", sourceIds)
+ ])
+ )
+ .execute()
+ : [];
+ const requests = new Map<string, FundingRequest>();
+ const dates = new Map<string, string>();
+ for (const app of args.applications) {
+ const id = (
+ isAR ? app.targetSalesInvoiceId : app.targetPurchaseInvoiceId
+ )!;
+ const invoice = invoices.get(id);
+ if (!invoice) throw new Error(`Invoice ${id} balance not found`);
+ if (app.targetExchangeRate !== invoice.exchangeRate)
+ throw new Error("Target exchange rate does not match the invoice");
+ const sourceAmount =
+ app.sourceAmount ??
+ (round(app.appliedAmount + app.discountAmount + app.writeOffAmount) ===
+ invoice.remainingBase
+ ? toDocumentAmount(
+ invoice.remainingDocument -
+ toDocumentAmount(
+ app.discountAmount + app.writeOffAmount,
+ invoice.exchangeRate,
+ currencyDecimals
+ ),
+ 1,
+ currencyDecimals
+ )
+ : toDocumentAmount(
+ app.appliedAmount,
+ invoice.exchangeRate,
+ currencyDecimals
+ ));
+ const request = requests.get(id) ?? {
+ targetId: id,
+ targetExchangeRate: invoice.exchangeRate,
+ remainingDocument: invoice.remainingDocument,
+ remainingBase: invoice.remainingBase,
+ requestedDocumentPrincipal: 0,
+ discountAmount: 0,
+ writeOffAmount: 0
+ };
+ request.requestedDocumentPrincipal = toDocumentAmount(
+ request.requestedDocumentPrincipal + sourceAmount,
+ 1,
+ currencyDecimals
+ );
+ request.discountAmount = round(
+ request.discountAmount + app.discountAmount
+ );
+ request.writeOffAmount = round(
+ request.writeOffAmount + app.writeOffAmount
+ );
+ requests.set(id, request);
+ dates.set(id, app.appliedDate);
+ }
+ const result = allocatePaymentFunding({
+ currentPayment: {
+ paymentId: payment.id,
+ postingDate: payment.paymentDate,
+ exchangeRate: Number(payment.exchangeRate),
+ remainingDocument: Number(payment.totalAmount),
+ remainingBase: toBaseAmount(
+ Number(payment.totalAmount),
+ Number(payment.exchangeRate)
+ )
+ },
+ priorSources: remainingFundingSources(
+ priorPayments,
+ consumption,
+ decimals,
+ isAR
+ ),
+ requests: [...requests.values()],
+ currencyDecimals,
+ isAR
+ });
await trx
- .insertInto("invoiceSettlement")
- .values(
- args.applications.map((a) => ({
- paymentId: args.paymentId,
- companyId: args.companyId,
- createdBy: args.createdBy,
- targetSalesInvoiceId: a.targetSalesInvoiceId ?? null,
- targetPurchaseInvoiceId: a.targetPurchaseInvoiceId ?? null,
- appliedAmount: a.appliedAmount,
- discountAmount: a.discountAmount,
- writeOffAmount: a.writeOffAmount,
- targetExchangeRate: a.targetExchangeRate,
- sourceExchangeRate: a.sourceExchangeRate,
- appliedDate: a.appliedDate
- }))
- )
+ .deleteFrom("invoiceSettlement")
+ .where("paymentId", "=", args.paymentId)
+ .where("companyId", "=", args.companyId)
.execute();
+ if (result.applications.length)
+ await trx
+ .insertInto("invoiceSettlement")
+ .values(
+ result.applications.map(({ targetId, ...a }) => ({
+ ...a,
+ paymentId: args.paymentId,
+ companyId: args.companyId,
+ createdBy: args.createdBy,
+ targetSalesInvoiceId: isAR ? targetId : null,
+ targetPurchaseInvoiceId: isAR ? null : targetId,
+ appliedDate: dates.get(targetId)!
+ }))
+ )
+ .execute();
});
}
@@ -2066,138 +2938,216 @@ export async function deleteMemo(client: SupabaseClient<Database>, id: string) {
// (apply to purchase invoices). `remaining` = amount − Σ already applied (memo as
// settlement source). Drives the credits section of the invoice "Receive Payment"
// composer.
+type AvailableMemoCredit = {
+ id: string;
+ memoId: string;
+ direction: string;
+ currencyCode: string;
+ exchangeRate: number;
+ amount: number;
+ remaining: number;
+ remainingDocument: number;
+};
+
+async function loadAvailableMemoCredits(
+ client: SupabaseClient<Database>,
+ companyId: string,
+ side: "sales" | "purchase",
+ partyId?: string,
+ excludePaymentId?: string,
+ currencyCode?: string
+): Promise<AvailableMemoCredit[]> {
+ const [memos, company] = await Promise.all([
+ fetchAllFromTable<
+ Omit<AvailableMemoCredit, "remaining" | "remainingDocument"> & {
+ memoDate: string;
+ postingDate: string | null;
+ }
+ >(
+ client,
+ "memo",
+ "id, memoId, direction, currencyCode, exchangeRate, amount, memoDate, postingDate",
+ (query) => {
+ query = query
+ .eq("companyId", companyId)
+ .eq("status", "Posted")
+ .eq("direction", side === "sales" ? "Credit" : "Debit");
+ if (partyId)
+ query =
+ side === "sales"
+ ? query.eq("customerId", partyId)
+ : query.eq("supplierId", partyId);
+ if (currencyCode) query = query.eq("currencyCode", currencyCode);
+ return query.order("id");
+ }
+ ),
+ client.from("company").select("companyGroupId").eq("id", companyId).single()
+ ]);
+ if (memos.error) throw new Error(memos.error.message);
+ if (company.error || !company.data?.companyGroupId)
+ throw new Error("Company currency configuration is missing");
+ const currencies = await client
+ .from("currency")
+ .select("code, decimalPlaces")
+ .eq("companyGroupId", company.data.companyGroupId);
+ if (currencies.error) throw new Error(currencies.error.message);
+ const decimals = new Map(
+ (currencies.data ?? []).map((c) => [c.code, c.decimalPlaces])
+ );
+ if (currencyCode) requireCurrencyDecimals(decimals, currencyCode);
+ if (!memos.data?.length) return [];
+ const apps = await fetchAllFromTable<{
+ memoId: string | null;
+ sourceAmount: number | null;
+ appliedAmount: number;
+ fxGainLossAmount: number | null;
+ appliedViaPaymentId: string | null;
+ appliedViaPayment: { status: string } | null;
+ }>(
+ client,
+ "invoiceSettlement",
+ "memoId, sourceAmount, appliedAmount, fxGainLossAmount, appliedViaPaymentId, appliedViaPayment:payment!invoiceSettlement_appliedViaPaymentId_fkey(status), memo:memo!invoiceSettlement_memoId_fkey!inner(status)",
+ (query) => {
+ query = query
+ .eq("companyId", companyId)
+ .eq("memo.companyId", companyId)
+ .eq("memo.status", "Posted")
+ .eq("memo.direction", side === "sales" ? "Credit" : "Debit");
+ if (partyId)
+ query =
+ side === "sales"
+ ? query.eq("memo.customerId", partyId)
+ : query.eq("memo.supplierId", partyId);
+ if (currencyCode) query = query.eq("memo.currencyCode", currencyCode);
+ return query.order("id");
+ }
+ );
+ if (apps.error) throw new Error(apps.error.message);
+ const refunds = await fetchAllFromTable<{
+ targetMemoId: string | null;
+ paymentId: string | null;
+ sourceAmount: number | null;
+ appliedAmount: number;
+ payment: { status: string } | null;
+ }>(
+ client,
+ "invoiceSettlement",
+ "targetMemoId, paymentId, sourceAmount, appliedAmount, payment:payment!invoiceSettlement_paymentId_fkey(status), targetMemo:memo!invoiceSettlement_targetMemoId_fkey!inner(status)",
+ (query) => {
+ query = query
+ .eq("companyId", companyId)
+ .eq("targetMemo.companyId", companyId)
+ .eq("targetMemo.status", "Posted")
+ .eq("targetMemo.direction", side === "sales" ? "Credit" : "Debit");
+ if (partyId)
+ query = query.eq(
+ side === "sales" ? "targetMemo.customerId" : "targetMemo.supplierId",
+ partyId
+ );
+ if (currencyCode)
+ query = query.eq("targetMemo.currencyCode", currencyCode);
+ return query.order("id");
+ }
+ );
+ if (refunds.error) throw new Error(refunds.error.message);
+ const reservedRefunds = refunds.data.filter(
+ (row) =>
+ row.targetMemoId &&
+ !(excludePaymentId && row.paymentId === excludePaymentId) &&
+ ["Draft", "Posted"].includes(row.payment?.status ?? "")
+ );
+ // Memo availability reserves competing Draft applications as well as Posted
+ // ones; sharing the arithmetic must not change this eligibility policy.
+ const reserved = apps.data.filter(
+ (row) =>
+ row.memoId &&
+ !(excludePaymentId && row.appliedViaPaymentId === excludePaymentId) &&
+ (!row.appliedViaPaymentId ||
+ ["Draft", "Posted"].includes(row.appliedViaPayment?.status ?? ""))
+ );
+ const sources = remainingFundingSources(
+ memos.data.map((memo) => ({
+ ...memo,
+ totalAmount: memo.amount,
+ paymentDate: memo.memoDate
+ })),
+ [
+ ...reserved.map((row) => ({
+ ...row,
+ paymentId: row.memoId,
+ sourcePaymentId: null
+ })),
+ ...reservedRefunds.map((row) => ({
+ ...row,
+ paymentId: row.targetMemoId,
+ sourcePaymentId: null,
+ fxGainLossAmount: 0
+ }))
+ ],
+ decimals,
+ side === "sales"
+ );
+ const remaining = new Map(
+ sources.map((source) => [source.paymentId, source])
+ );
+ return memos.data.flatMap((memo) => {
+ const source = remaining.get(memo.id);
+ return source
+ ? [
+ {
+ id: memo.id,
+ memoId: memo.memoId,
+ direction: memo.direction,
+ currencyCode: memo.currencyCode,
+ exchangeRate: memo.exchangeRate,
+ amount: toBaseAmount(
+ Number(memo.amount),
+ Number(memo.exchangeRate)
+ ),
+ remaining: source.remainingBase,
+ remainingDocument: source.remainingDocument
+ }
+ ]
+ : [];
+ });
+}
+
export async function getAvailableCreditsForParty(
client: SupabaseClient<Database>,
companyId: string,
party:
| { side: "sales"; customerId: string }
| { side: "purchase"; supplierId: string },
- // When editing a Draft payment's composer, that payment's own staged credits
- // should NOT count as used — they show as staged, not consumed.
- excludePaymentId?: string
-): Promise<{
- data:
- | {
- id: string;
- memoId: string;
- direction: string;
- currencyCode: string;
- exchangeRate: number;
- amount: number;
- remaining: number;
- }[]
- | null;
- error: unknown;
-}> {
- const direction = party.side === "sales" ? "Credit" : "Debit";
- let query = client
- .from("memo")
- .select("id, memoId, direction, currencyCode, exchangeRate, amount")
- .eq("companyId", companyId)
- .eq("status", "Posted")
- .eq("direction", direction);
- query =
- party.side === "sales"
- ? query.eq("customerId", party.customerId)
- : query.eq("supplierId", party.supplierId);
-
- const memos = await query;
- if (memos.error) return { data: null, error: memos.error };
- if (!memos.data || memos.data.length === 0) return { data: [], error: null };
-
- // deno-lint-ignore no-explicit-any
- const rows = memos.data as any[];
- const ids = rows.map((m) => m.id as string);
- const apps = await client
- .from("invoiceSettlement")
- .select(
- "memoId, appliedAmount, appliedViaPaymentId, appliedViaPayment:payment!invoiceSettlement_appliedViaPaymentId_fkey(status)"
- )
- .in("memoId", ids);
- if (apps.error) return { data: null, error: apps.error };
-
- const appliedByMemo = new Map<string, number>();
- for (const a of apps.data ?? []) {
- if (!a.memoId) continue;
- const viaId = (a as { appliedViaPaymentId: string | null })
- .appliedViaPaymentId;
- if (excludePaymentId && viaId === excludePaymentId) continue;
- // A voided applying payment releases its credit application — the
- // invoice balance reopens (the views stop counting the row), so the
- // memo's remaining must reopen with it. Draft still reserves.
- const viaStatus = (a as { appliedViaPayment: { status: string } | null })
- .appliedViaPayment?.status;
- if (viaId && viaStatus === "Voided") continue;
- appliedByMemo.set(
- a.memoId,
- (appliedByMemo.get(a.memoId) ?? 0) + Number(a.appliedAmount)
- );
+ excludePaymentId?: string,
+ currencyCode?: string
+): Promise<{ data: AvailableMemoCredit[] | null; error: unknown }> {
+ try {
+ return {
+ data: await loadAvailableMemoCredits(
+ client,
+ companyId,
+ party.side,
+ party.side === "sales" ? party.customerId : party.supplierId,
+ excludePaymentId,
+ currencyCode
+ ),
+ error: null
+ };
+ } catch (error) {
+ return { data: null, error };
}
-
- const result = rows
- .map((m) => {
- const remaining = round(
- Number(m.amount) - (appliedByMemo.get(m.id) ?? 0)
- );
- return {
- id: m.id as string,
- memoId: m.memoId as string,
- direction: m.direction as string,
- currencyCode: m.currencyCode as string,
- exchangeRate: Number(m.exchangeRate),
- amount: Number(m.amount),
- remaining
- };
- })
- .filter((m) => m.remaining > 0.0001);
-
- return { data: result, error: null };
}
-// Does the company have ANY open credits to apply on this side? (sales → posted
-// customer Credit memos; purchase → posted supplier Debit memos, each with credit
-// remaining.) Cheap org-level gate for the invoice "Apply Credit" action — we
-// don't surface it at all unless there's something to apply.
export async function getCompanyHasOpenCredits(
client: SupabaseClient<Database>,
companyId: string,
side: "sales" | "purchase"
): Promise<boolean> {
- const direction = side === "sales" ? "Credit" : "Debit";
- const memos = await client
- .from("memo")
- .select("id, amount")
- .eq("companyId", companyId)
- .eq("status", "Posted")
- .eq("direction", direction);
- if (memos.error || !memos.data || memos.data.length === 0) return false;
-
- // deno-lint-ignore no-explicit-any
- const rows = memos.data as any[];
- const ids = rows.map((m) => m.id as string);
- const apps = await client
- .from("invoiceSettlement")
- .select(
- "memoId, appliedAmount, appliedViaPaymentId, appliedViaPayment:payment!invoiceSettlement_appliedViaPaymentId_fkey(status)"
- )
- .in("memoId", ids);
- if (apps.error) return false;
-
- const appliedByMemo = new Map<string, number>();
- for (const a of apps.data ?? []) {
- if (!a.memoId) continue;
- // A voided applying payment releases its credit application.
- const viaStatus = (a as { appliedViaPayment: { status: string } | null })
- .appliedViaPayment?.status;
- if (a.appliedViaPaymentId && viaStatus === "Voided") continue;
- appliedByMemo.set(
- a.memoId,
- (appliedByMemo.get(a.memoId) ?? 0) + Number(a.appliedAmount)
- );
+ try {
+ return (await loadAvailableMemoCredits(client, companyId, side)).length > 0;
+ } catch {
+ return false;
}
- return rows.some(
- (m) => Number(m.amount) - (appliedByMemo.get(m.id) ?? 0) > 0.0001
- );
}
// Apply posted credits to invoices — additive insert of memo-sourced
@@ -2212,23 +3162,34 @@ export async function getCompanyHasOpenCredits(
export async function getStagedCreditsForPayment(
client: SupabaseClient<Database>,
paymentId: string,
- side: "sales" | "purchase"
+ side: "sales" | "purchase",
+ companyId?: string
): Promise<{
- data: { memoId: string; invoiceId: string; amount: number }[] | null;
+ data:
+ | {
+ memoId: string;
+ invoiceId: string;
+ amount: number;
+ sourceAmount: number | null;
+ }[]
+ | null;
error: unknown;
}> {
- const apps = await client
+ let query = client
.from("invoiceSettlement")
.select(
- "memoId, targetSalesInvoiceId, targetPurchaseInvoiceId, appliedAmount"
+ "memoId, targetSalesInvoiceId, targetPurchaseInvoiceId, appliedAmount, sourceAmount"
)
.eq("appliedViaPaymentId", paymentId);
+ if (companyId) query = query.eq("companyId", companyId);
+ const apps = await query;
if (apps.error) return { data: null, error: apps.error };
const rows = (apps.data ?? []) as Array<{
memoId: string | null;
targetSalesInvoiceId: string | null;
targetPurchaseInvoiceId: string | null;
appliedAmount: number;
+ sourceAmount: number | null;
}>;
const data = rows
.map((r) => ({
@@ -2237,7 +3198,8 @@ export async function getStagedCreditsForPayment(
side === "sales"
? (r.targetSalesInvoiceId ?? "")
: (r.targetPurchaseInvoiceId ?? ""),
- amount: Number(r.appliedAmount)
+ amount: Number(r.appliedAmount),
+ sourceAmount: r.sourceAmount
}))
.filter((r) => r.memoId && r.invoiceId);
return { data, error: null };
@@ -2251,235 +3213,199 @@ export async function applyCreditsToInvoices(
createdBy: string;
appliedDate: string;
side: "sales" | "purchase";
- applications: { memoId: string; invoiceId: string; amount: number }[];
+ applications: {
+ memoId: string;
+ invoiceId: string;
+ amount: number;
+ sourceAmount?: number;
+ }[];
}
) {
- const isSales = args.side === "sales";
- const activeStatuses = isSales
- ? ["Submitted", "Partially Paid", "Overdue"]
- : ["Open", "Partially Paid", "Overdue"];
-
return db.transaction().execute(async (trx) => {
- // Credit applications are STAGED on a Draft payment and only go live when it
- // posts (the invoice views gate memo settlements on appliedViaPaymentId's
- // payment status). The composer pre-fills the currently-staged set and submits
- // the FULL set each time, so this is a delete-then-insert REPLACE keyed on the
- // payment — exactly like cash applications (replaceInvoiceSettlements).
const payment = await trx
.selectFrom("payment")
- .select(["id", "status", "customerId", "supplierId"])
+ .selectAll()
.where("id", "=", args.paymentId)
.where("companyId", "=", args.companyId)
.forUpdate()
.executeTakeFirst();
if (!payment) throw new Error("Payment not found");
- if (payment.status !== "Draft") {
+ if (payment.status !== "Draft")
throw new Error(
"Credit applications can only be edited while the payment is Draft"
);
+ const isAR = args.side === "sales";
+ if ((payment.paymentType === "Receipt") !== isAR)
+ throw new Error("Payment and invoice side must match");
+ const partyId = isAR ? payment.customerId : payment.supplierId;
+ if (!partyId) throw new Error("Payment party is required");
+ const { currencyDecimals } = await loadTransactionCurrency(
+ trx,
+ args.companyId,
+ payment.currencyCode
+ );
+ if (!args.applications.length) {
+ await trx
+ .deleteFrom("invoiceSettlement")
+ .where("appliedViaPaymentId", "=", args.paymentId)
+ .where("companyId", "=", args.companyId)
+ .execute();
+ return;
}
- // The party every memo and invoice in this batch must belong to: a payment's
- // credits can only clear ITS own party's invoices using ITS own party's
- // credit memos (a customer's credit can't settle another customer's invoice).
- const paymentParty = isSales ? payment.customerId : payment.supplierId;
-
- // Replace this payment's prior credit applications with the submitted set.
- await trx
- .deleteFrom("invoiceSettlement")
- .where("appliedViaPaymentId", "=", args.paymentId)
- .execute();
-
- if (args.applications.length === 0) return;
-
- const memoIds = [...new Set(args.applications.map((a) => a.memoId))];
- const invoiceIds = [...new Set(args.applications.map((a) => a.invoiceId))];
-
- // Lock the memos + read their remaining credit (amount - Σ applied elsewhere).
+ const ids = [...new Set(args.applications.map((a) => a.invoiceId))].sort();
+ const memoIds = [...new Set(args.applications.map((a) => a.memoId))].sort();
+ const invoices = await loadTransactionInvoices(
+ trx,
+ args.companyId,
+ ids,
+ isAR,
+ payment.currencyCode,
+ partyId,
+ currencyDecimals
+ );
const memos = await trx
.selectFrom("memo")
- .select([
- "id",
- "status",
- "exchangeRate",
- "amount",
- "customerId",
- "supplierId"
- ])
- .where("id", "in", memoIds)
- .where("companyId", "=", args.companyId)
- .forUpdate()
- .execute();
- // A voided applying payment releases its credit application; Draft
- // still reserves (pessimistic, matches the composer's available list).
- const priorByMemo = await trx
- .selectFrom("invoiceSettlement")
- .leftJoin(
- "payment as vp",
- "vp.id",
- "invoiceSettlement.appliedViaPaymentId"
- )
- .select(["invoiceSettlement.memoId", "invoiceSettlement.appliedAmount"])
- .where("invoiceSettlement.memoId", "in", memoIds)
- .where((eb) =>
- eb.or([
- eb("invoiceSettlement.appliedViaPaymentId", "is", null),
- eb("vp.status", "!=", "Voided")
- ])
- )
- .execute();
- const priorApplied = new Map<string, number>();
- for (const p of priorByMemo) {
- if (!p.memoId) continue;
- priorApplied.set(
- p.memoId,
- (priorApplied.get(p.memoId) ?? 0) + Number(p.appliedAmount)
- );
- }
- const memoById = new Map(memos.map((m) => [m.id, m]));
-
- // Lock the invoices + read open balance + status from the view.
- const invoiceTable = isSales ? "salesInvoice" : "purchaseInvoice";
- const invoiceView = isSales ? "salesInvoices" : "purchaseInvoices";
- const lockedInvoices = await trx
- .selectFrom(invoiceTable)
- .select(["id", "invoiceId", "status", "exchangeRate"])
- .where("id", "in", invoiceIds)
+ .selectAll()
.where("companyId", "=", args.companyId)
+ .where("id", "in", memoIds)
+ .orderBy("id")
.forUpdate()
.execute();
- const invoiceBalances = await trx
- .selectFrom(invoiceView)
- .select(["id", "balance"])
- .where("id", "in", invoiceIds)
- .execute();
- const balById = new Map(invoiceBalances.map((b) => [b.id, b]));
- const invById = new Map(lockedInvoices.map((i) => [i.id, i]));
-
- // Party of each targeted invoice (the column differs by side, so fetch
- // per-branch). Used below to reject applying a credit to an invoice that
- // belongs to a different party than the payment.
- const partyByInvoice = new Map<string, string | null>();
- if (isSales) {
- const rows = await trx
- .selectFrom("salesInvoice")
- .select(["id", "customerId"])
- .where("id", "in", invoiceIds)
- .where("companyId", "=", args.companyId)
- .execute();
- for (const r of rows) partyByInvoice.set(r.id, r.customerId);
- } else {
- const rows = await trx
- .selectFrom("purchaseInvoice")
- .select(["id", "supplierId"])
- .where("id", "in", invoiceIds)
+ const [prior, cash] = await Promise.all([
+ loadTransactionMemoConsumption(
+ trx,
+ args.companyId,
+ memoIds,
+ args.paymentId
+ ),
+ trx
+ .selectFrom("invoiceSettlement")
+ .selectAll()
.where("companyId", "=", args.companyId)
- .execute();
- for (const r of rows) partyByInvoice.set(r.id, r.supplierId);
- }
-
- // This payment's own cash applications aren't in the live balance yet (the
- // payment is Draft) and its prior credits were just deleted above, so reserve
- // room for the cash when capping these credits.
- const cashApps = await trx
- .selectFrom("invoiceSettlement")
- .select([
- "targetSalesInvoiceId",
- "targetPurchaseInvoiceId",
- "appliedAmount",
- "discountAmount",
- "writeOffAmount"
- ])
- .where("paymentId", "=", args.paymentId)
- .execute();
- const cashByInvoice = new Map<string, number>();
- for (const c of cashApps) {
- const inv = isSales ? c.targetSalesInvoiceId : c.targetPurchaseInvoiceId;
- if (!inv) continue;
- cashByInvoice.set(
- inv,
- (cashByInvoice.get(inv) ?? 0) +
- Number(c.appliedAmount) +
- Number(c.discountAmount) +
- Number(c.writeOffAmount)
+ .where("paymentId", "=", args.paymentId)
+ .execute()
+ ]);
+ for (const row of cash) {
+ const id = isAR ? row.targetSalesInvoiceId : row.targetPurchaseInvoiceId;
+ const invoice = id ? invoices.get(id) : undefined;
+ if (!invoice) continue;
+ const reserved = reduceInvoiceSettlements(
+ [row],
+ invoice.exchangeRate,
+ currencyDecimals
+ );
+ invoice.remainingDocument = toDocumentAmount(
+ invoice.remainingDocument - reserved.document,
+ 1,
+ currencyDecimals
);
+ invoice.remainingBase = round(invoice.remainingBase - reserved.base);
}
-
- // Validate each application, accumulating per-memo and per-invoice caps.
- const memoUse = new Map<string, number>();
- const invoiceUse = new Map<string, number>();
- for (const app of args.applications) {
- if (app.amount <= 0)
- throw new Error("Applied amount must be greater than 0");
- const memo = memoById.get(app.memoId);
- if (!memo) throw new Error(`Credit memo ${app.memoId} not found`);
- if (memo.status !== "Posted")
+ for (const id of memoIds) {
+ const memo = memos.find((m) => m.id === id);
+ if (!memo || memo.status !== "Posted")
throw new Error("Only posted credits can be applied");
- const memoParty = isSales ? memo.customerId : memo.supplierId;
- if (memoParty !== paymentParty)
- throw new Error(
- "A credit memo can only be applied through a payment for the same party"
- );
- const inv = invById.get(app.invoiceId);
- if (!inv) throw new Error(`Invoice ${app.invoiceId} not found`);
- const invoiceLabel = inv.invoiceId ?? app.invoiceId;
- if (partyByInvoice.get(app.invoiceId) !== paymentParty)
- throw new Error(
- `Invoice ${invoiceLabel} belongs to a different party than the payment`
- );
- if (!activeStatuses.includes(String(inv.status)))
- throw new Error(
- `Invoice ${invoiceLabel} is ${String(inv.status).toLowerCase()}, so no credit can be applied to it`
- );
- if (Number(memo.exchangeRate) !== Number(inv.exchangeRate))
- throw new Error(
- "Applying a credit requires matching exchange rates (cross-rate FX not yet supported)"
- );
-
- memoUse.set(app.memoId, (memoUse.get(app.memoId) ?? 0) + app.amount);
- invoiceUse.set(
- app.invoiceId,
- (invoiceUse.get(app.invoiceId) ?? 0) + app.amount
+ if (memo.direction !== (isAR ? "Credit" : "Debit"))
+ throw new Error("Memo direction does not reduce this invoice balance");
+ if ((isAR ? memo.customerId : memo.supplierId) !== partyId)
+ throw new Error("Memo and payment party must match");
+ if (memo.currencyCode !== payment.currencyCode)
+ throw new Error("Memo and payment currency must match");
+ }
+ const sources = new Map(
+ remainingFundingSources(
+ memos.map((memo) => ({
+ ...memo,
+ totalAmount: memo.amount,
+ paymentDate: memo.memoDate
+ })),
+ prior.map((row) => ({
+ ...row,
+ paymentId: row.memoId ?? row.targetMemoId,
+ sourcePaymentId: null,
+ fxGainLossAmount: row.targetMemoId ? 0 : row.fxGainLossAmount
+ })),
+ new Map([[payment.currencyCode, currencyDecimals]]),
+ isAR
+ ).map((source) => [source.paymentId, source])
+ );
+ const values: Database["public"]["Tables"]["invoiceSettlement"]["Insert"][] =
+ [];
+ for (const app of args.applications) {
+ const source = sources.get(app.memoId);
+ if (!source) throw new Error("Credit has no remaining funding balance");
+ const invoice = invoices.get(app.invoiceId);
+ if (!invoice)
+ throw new Error(`Invoice ${app.invoiceId} balance not found`);
+ if (source.exchangeRate !== invoice.exchangeRate)
+ throw new Error("Applying a credit requires matching exchange rates");
+ if (!Number.isFinite(app.amount) || app.amount < 0)
+ throw new Error("Applied amount must be nonnegative and finite");
+ const sourceAmount =
+ app.sourceAmount ??
+ (app.amount === source.remainingBase
+ ? source.remainingDocument
+ : app.amount === invoice.remainingBase
+ ? invoice.remainingDocument
+ : toDocumentAmount(
+ app.amount,
+ invoice.exchangeRate,
+ currencyDecimals
+ ));
+ if (sourceAmount <= 0)
+ throw new Error("Applied document amount must be greater than zero");
+ const result = allocatePaymentFunding({
+ currentPayment: source,
+ priorSources: [],
+ currencyDecimals,
+ isAR,
+ requests: [
+ {
+ targetId: app.invoiceId,
+ targetExchangeRate: invoice.exchangeRate,
+ remainingDocument: invoice.remainingDocument,
+ remainingBase: invoice.remainingBase,
+ requestedDocumentPrincipal: sourceAmount,
+ discountAmount: 0,
+ writeOffAmount: 0
+ }
+ ]
+ });
+ const allocated = result.applications[0];
+ sources.set(app.memoId, { ...source, ...result.sourceRemainders[0] });
+ invoice.remainingDocument = toDocumentAmount(
+ invoice.remainingDocument - sourceAmount,
+ 1,
+ currencyDecimals
);
-
- const memoRemaining =
- Number(memo.amount) - (priorApplied.get(app.memoId) ?? 0);
- if (memoUse.get(app.memoId)! > memoRemaining + 0.0001)
- throw new Error(
- `Applied (${memoUse.get(app.memoId)}) exceeds the credit's remaining balance (${memoRemaining})`
- );
-
- const invoiceOpen =
- Number(balById.get(app.invoiceId)?.balance ?? 0) -
- (cashByInvoice.get(app.invoiceId) ?? 0);
- if (invoiceUse.get(app.invoiceId)! > invoiceOpen + EPSILON)
- throw new Error(
- invoiceOpen <= EPSILON
- ? `Invoice ${invoiceLabel} has no open balance to apply credit to (it is already fully settled)`
- : `Credit applied to invoice ${invoiceLabel} (${invoiceUse.get(
- app.invoiceId
- )}) exceeds its open balance of ${round(invoiceOpen)}`
- );
+ invoice.remainingBase = round(
+ invoice.remainingBase - allocated.appliedAmount
+ );
+ values.push({
+ memoId: app.memoId,
+ appliedViaPaymentId: args.paymentId,
+ companyId: args.companyId,
+ createdBy: args.createdBy,
+ targetSalesInvoiceId: isAR ? app.invoiceId : null,
+ targetPurchaseInvoiceId: isAR ? null : app.invoiceId,
+ sourceAmount: allocated.sourceAmount,
+ appliedAmount: allocated.appliedAmount,
+ discountAmount: 0,
+ writeOffAmount: 0,
+ sourceExchangeRate: source.exchangeRate,
+ targetExchangeRate: invoice.exchangeRate,
+ // Matching-snapshot memo applications are GL-neutral.
+ fxGainLossAmount: 0,
+ appliedDate: args.appliedDate
+ });
}
-
await trx
- .insertInto("invoiceSettlement")
- .values(
- args.applications.map((app) => ({
- memoId: app.memoId,
- appliedViaPaymentId: args.paymentId,
- companyId: args.companyId,
- createdBy: args.createdBy,
- targetSalesInvoiceId: isSales ? app.invoiceId : null,
- targetPurchaseInvoiceId: isSales ? null : app.invoiceId,
- appliedAmount: app.amount,
- discountAmount: 0,
- writeOffAmount: 0,
- sourceExchangeRate: Number(memoById.get(app.memoId)!.exchangeRate),
- targetExchangeRate: Number(invById.get(app.invoiceId)!.exchangeRate),
- appliedDate: args.appliedDate
- }))
- )
+ .deleteFrom("invoiceSettlement")
+ .where("appliedViaPaymentId", "=", args.paymentId)
+ .where("companyId", "=", args.companyId)
.execute();
+ if (values.length)
+ await trx.insertInto("invoiceSettlement").values(values).execute();
});
}
diff --git a/apps/erp/app/modules/invoicing/invoicing.settlements.test.ts b/apps/erp/app/modules/invoicing/invoicing.settlements.test.ts
new file mode 100644
index 0000000000..f2e940af51
--- /dev/null
+++ b/apps/erp/app/modules/invoicing/invoicing.settlements.test.ts
@@ -0,0 +1,1505 @@
+import type { Database } from "@carbon/database";
+import type { SupabaseClient } from "@supabase/supabase-js";
+import { describe, expect, it, vi } from "vitest";
+
+vi.mock("@carbon/glossary", () => ({
+ terms: {},
+ getEntry: () => null,
+ lookupEntry: () => null,
+ hasEntry: () => false,
+ termSlug: (s: string) => s,
+ glossaryEntries: () => []
+}));
+vi.mock("~/modules/purchasing", () => ({}));
+vi.mock("../people/people.service", () => ({}));
+vi.mock("../sales/sales.service", () => ({}));
+vi.mock("../accounting/accounting.ee.service", () => ({}));
+
+import * as service from "./invoicing.service";
+
+type Row = Record<string, any>;
+function clientFor(
+ tables: Record<string, Row[]>,
+ failedPages: Record<string, number> = {}
+) {
+ const calls: {
+ table: string;
+ filters: [string, unknown][];
+ idFilters: unknown[][];
+ }[] = [];
+ return {
+ calls,
+ client: {
+ from(table: string) {
+ const call = {
+ table,
+ filters: [] as [string, unknown][],
+ idFilters: [] as unknown[][]
+ };
+ calls.push(call);
+ let result = tables[table] ?? [];
+ let offset = 0;
+ let end = 999;
+ const q: any = {
+ select: () => q,
+ range: (start: number, last: number) => {
+ offset = start;
+ end = last;
+ return q;
+ },
+ order: () => q,
+ or: () => q,
+ gt: () => q,
+ eq: (key: string, value: unknown) => {
+ call.filters.push([key, value]);
+ result = result.filter(
+ (r) => r[key] === undefined || r[key] === value
+ );
+ return q;
+ },
+ in: (key: string, values: unknown[]) => {
+ call.idFilters.push(values);
+ result = result.filter(
+ (r) => r[key] === undefined || values.includes(r[key])
+ );
+ return q;
+ },
+ single: () =>
+ Promise.resolve({ data: result[0] ?? null, error: null }),
+ then: (done: any) =>
+ Promise.resolve({
+ data:
+ failedPages[table] === offset
+ ? null
+ : result.slice(offset, end + 1),
+ error:
+ failedPages[table] === offset
+ ? { message: "Later page failed" }
+ : null
+ }).then(done)
+ };
+ return q;
+ }
+ } as unknown as SupabaseClient<Database>
+ };
+}
+const payment = {
+ id: "prior",
+ companyId: "co",
+ customerId: "cust",
+ paymentType: "Receipt",
+ currencyCode: "EUR",
+ status: "Posted",
+ exchangeRate: 1.1,
+ totalAmount: 110,
+ postingDate: "2026-01-01",
+ paymentDate: "2026-01-01"
+};
+const config = {
+ company: [{ id: "co", companyGroupId: "group", baseCurrencyCode: "USD" }],
+ currency: [{ code: "EUR", companyGroupId: "group", decimalPlaces: 2 }]
+};
+
+describe("authoritative on-account sources", () => {
+ it("keeps the existing base-total reader contract, dividing document cash by its snapshot", async () => {
+ const { client } = clientFor({ ...config, payment: [payment] });
+ expect(
+ await service.getAvailableOnAccountCredit(client, "co", {
+ paymentType: "Receipt",
+ customerId: "cust"
+ })
+ ).toBe(100);
+ });
+ it("spends original document credit and its recorded base release only after applying payment posts", async () => {
+ const { client, calls } = clientFor({
+ ...config,
+ payment: [
+ payment,
+ { ...payment, id: "applying", totalAmount: 0, exchangeRate: 1.2 }
+ ],
+ invoiceSettlement: [
+ {
+ paymentId: "applying",
+ sourcePaymentId: "prior",
+ sourceAmount: 55,
+ appliedAmount: 40,
+ fxGainLossAmount: 10,
+ payment: { status: "Posted" }
+ },
+ {
+ paymentId: "draft",
+ sourcePaymentId: "prior",
+ sourceAmount: 50,
+ appliedAmount: 45,
+ fxGainLossAmount: 0,
+ payment: { status: "Draft" }
+ }
+ ]
+ });
+ const result = await service.getAvailableOnAccountCreditSources(
+ client,
+ "co",
+ { paymentType: "Receipt", customerId: "cust" },
+ "EUR"
+ );
+ expect(result.error).toBeNull();
+ expect(result.data).toEqual({
+ sources: [
+ {
+ paymentId: "prior",
+ postingDate: "2026-01-01",
+ exchangeRate: 1.1,
+ remainingDocument: 55,
+ remainingBase: 50
+ }
+ ],
+ availableDocumentAmount: 55,
+ availableBaseAmount: 50
+ });
+ expect(
+ calls
+ .filter((c) => c.table === "payment")
+ .every((c) =>
+ c.filters.some(([k, v]) => k === "companyId" && v === "co")
+ )
+ ).toBe(true);
+ });
+ it("uses AP applied minus FX for carrying release", async () => {
+ const { client } = clientFor({
+ ...config,
+ payment: [
+ {
+ ...payment,
+ paymentType: "Disbursement",
+ supplierId: "sup",
+ customerId: null
+ }
+ ],
+ invoiceSettlement: [
+ {
+ paymentId: "prior",
+ sourcePaymentId: null,
+ sourceAmount: 55,
+ appliedAmount: 40,
+ fxGainLossAmount: -10,
+ payment: { status: "Posted" }
+ }
+ ]
+ });
+ const result = await service.getAvailableOnAccountCreditSources(
+ client,
+ "co",
+ { paymentType: "Disbursement", supplierId: "sup" },
+ "EUR"
+ );
+ expect(result.data?.availableBaseAmount).toBe(50);
+ });
+ it("retains a positive minor unit with zero carrying base and rejects missing precision", async () => {
+ const { client } = clientFor({
+ ...config,
+ payment: [{ ...payment, totalAmount: 0.01, exchangeRate: 100000 }]
+ });
+ expect(
+ (
+ await service.getAvailableOnAccountCreditSources(
+ client,
+ "co",
+ { paymentType: "Receipt", customerId: "cust" },
+ "EUR"
+ )
+ ).data?.sources[0]
+ ).toMatchObject({ remainingDocument: 0.01, remainingBase: 0 });
+ const missing = clientFor({ ...config, currency: [], payment: [payment] });
+ expect(
+ (
+ await service.getAvailableOnAccountCreditSources(
+ missing.client,
+ "co",
+ { paymentType: "Receipt", customerId: "cust" },
+ "EUR"
+ )
+ ).error?.message
+ ).toMatch(/currency/i);
+ });
+});
+
+describe("memo credit readers", () => {
+ it("reports 55 EUR at 1.1 as 50 base; Draft reserves, Voided releases, own staged rows remain visible", async () => {
+ const { client } = clientFor({
+ ...config,
+ memo: [
+ {
+ id: "memo",
+ memoId: "CM1",
+ direction: "Credit",
+ companyId: "co",
+ customerId: "cust",
+ status: "Posted",
+ currencyCode: "EUR",
+ exchangeRate: 1.1,
+ amount: 55
+ }
+ ],
+ invoiceSettlement: [
+ {
+ memoId: "memo",
+ sourceAmount: 11,
+ appliedAmount: 10,
+ appliedViaPaymentId: "draft",
+ appliedViaPayment: { status: "Draft" }
+ },
+ {
+ memoId: "memo",
+ sourceAmount: 22,
+ appliedAmount: 20,
+ appliedViaPaymentId: "void",
+ appliedViaPayment: { status: "Voided" }
+ },
+ {
+ memoId: "memo",
+ sourceAmount: 11,
+ appliedAmount: 10,
+ appliedViaPaymentId: "own",
+ appliedViaPayment: { status: "Draft" }
+ }
+ ]
+ });
+ const result = await service.getAvailableCreditsForParty(
+ client,
+ "co",
+ { side: "sales", customerId: "cust" },
+ "own",
+ "EUR"
+ );
+ expect(result.data?.[0]).toMatchObject({
+ amount: 50,
+ remaining: 40,
+ remainingDocument: 44
+ });
+ });
+});
+
+function databaseFor(tables: Record<string, Row[]>) {
+ const inserts: Row[] = [];
+ const deletes: string[] = [];
+ const db: any = {
+ transaction: () => ({ execute: (fn: any) => fn(db) }),
+ selectFrom: (table: string) => query(table),
+ deleteFrom: (table: string) => query(table, "delete"),
+ insertInto: (table: string) => query(table, "insert")
+ };
+ function query(table: string, mode = "select") {
+ let rows = tables[table] ?? [];
+ const q: any = {
+ select: () => q,
+ selectAll: () => q,
+ forUpdate: () => q,
+ orderBy: () => q,
+ leftJoin: () => q,
+ innerJoin: () => q,
+ where: (column: unknown, op: string, value: unknown) => {
+ if (typeof column === "string") {
+ const key = column.split(".").at(-1)!;
+ rows = rows.filter(
+ (r) =>
+ r[key] === undefined ||
+ (op === "in"
+ ? (value as unknown[]).includes(r[key])
+ : op === "!="
+ ? r[key] !== value
+ : r[key] === value)
+ );
+ }
+ return q;
+ },
+ values: (values: Row[]) => {
+ inserts.push(...values);
+ return q;
+ },
+ execute: async () => {
+ if (mode === "delete") deletes.push(table);
+ return rows;
+ },
+ executeTakeFirst: async () => rows[0]
+ };
+ return q;
+ }
+ return { db, inserts, deletes };
+}
+const current = {
+ ...payment,
+ id: "current",
+ status: "Draft",
+ totalAmount: 110,
+ exchangeRate: 1.2
+};
+const invoice = {
+ partyId: "cust",
+ id: "invoice",
+ companyId: "co",
+ customerId: "cust",
+ status: "Submitted",
+ currencyCode: "EUR",
+ exchangeRate: 1.1,
+ totalAmount: 100,
+ balance: 100,
+ invoiceId: "INV1"
+};
+const draft = {
+ targetSalesInvoiceId: "invoice",
+ appliedAmount: 100,
+ discountAmount: 0,
+ writeOffAmount: 0,
+ targetExchangeRate: 1.1,
+ sourceExchangeRate: 1.2,
+ sourceAmount: 110,
+ appliedDate: "2026-09-07"
+};
+function draftDb(overrides: Record<string, Row[]> = {}) {
+ return databaseFor({
+ ...config,
+ payment: [current],
+ salesInvoice: [invoice],
+ salesInvoices: [invoice],
+ ...overrides
+ });
+}
+describe("replaceInvoiceSettlements transaction", () => {
+ it.each([
+ ["target rate", { ...draft, targetExchangeRate: 2 }],
+ ["source rate", { ...draft, sourceExchangeRate: 2 }],
+ ["funding source", { ...draft, sourcePaymentId: "forged" }]
+ ])("rejects a forged %s before replacing drafts", async (_label, app) => {
+ const { db, deletes, inserts } = draftDb();
+ await expect(
+ service.replaceInvoiceSettlements(db, {
+ paymentId: "current",
+ companyId: "co",
+ createdBy: "user",
+ applications: [app]
+ })
+ ).rejects.toThrow(/rate|source/i);
+ expect(deletes).toEqual([]);
+ expect(inserts).toEqual([]);
+ });
+ it("recomputes base principal and realized FX from authoritative invoice/payment snapshots", async () => {
+ const { db, inserts } = draftDb();
+ await service.replaceInvoiceSettlements(db, {
+ paymentId: "current",
+ companyId: "co",
+ createdBy: "user",
+ applications: [draft]
+ });
+ expect(inserts).toEqual([
+ expect.objectContaining({
+ paymentId: "current",
+ sourcePaymentId: null,
+ sourceAmount: 110,
+ appliedAmount: 100,
+ fxGainLossAmount: -8.33333,
+ sourceExchangeRate: 1.2,
+ targetExchangeRate: 1.1
+ })
+ ]);
+ });
+ it("rejects another currency and missing configured precision", async () => {
+ for (const overrides of [
+ { salesInvoice: [{ ...invoice, currencyCode: "GBP" }] },
+ { currency: [] }
+ ] as Record<string, Row[]>[]) {
+ const { db, inserts } = draftDb(overrides);
+ await expect(
+ service.replaceInvoiceSettlements(db, {
+ paymentId: "current",
+ companyId: "co",
+ createdBy: "user",
+ applications: [draft]
+ })
+ ).rejects.toThrow(/currency|decimal/i);
+ expect(inserts).toEqual([]);
+ }
+ });
+ it("allocates a zero-cash draft from the prior payment without repricing it", async () => {
+ const { db, inserts } = draftDb({
+ payment: [{ ...current, totalAmount: 0 }, payment]
+ });
+ await service.replaceInvoiceSettlements(db, {
+ paymentId: "current",
+ companyId: "co",
+ createdBy: "user",
+ applications: [draft]
+ });
+ expect(inserts[0]).toMatchObject({
+ paymentId: "current",
+ sourcePaymentId: "prior",
+ sourceExchangeRate: 1.1,
+ sourceAmount: 110,
+ appliedAmount: 100,
+ fxGainLossAmount: 0
+ });
+ });
+ it("retains full document principal after base precision rounds to zero", async () => {
+ const tiny = {
+ ...invoice,
+ exchangeRate: 100000,
+ totalAmount: 0.0000001,
+ balance: 0.0000001
+ };
+ const { db, inserts } = draftDb({
+ payment: [{ ...current, totalAmount: 0.01, exchangeRate: 100000 }],
+ salesInvoice: [tiny],
+ salesInvoices: [tiny]
+ });
+ await service.replaceInvoiceSettlements(db, {
+ paymentId: "current",
+ companyId: "co",
+ createdBy: "user",
+ applications: [
+ {
+ ...draft,
+ sourceAmount: 0.01,
+ appliedAmount: 0,
+ sourceExchangeRate: 100000,
+ targetExchangeRate: 100000
+ }
+ ]
+ });
+ expect(inserts[0]).toMatchObject({ sourceAmount: 0.01, appliedAmount: 0 });
+ });
+});
+
+describe("composer invoice balances", () => {
+ it("seeds two invoice snapshots from each original document total, independent of an old dust-forgiven view balance", async () => {
+ const { client } = clientFor({
+ ...config,
+ salesInvoices: [
+ { ...invoice, totalAmount: 100, exchangeRate: 1.1, balance: 0 },
+ {
+ ...invoice,
+ id: "two",
+ totalAmount: 50,
+ exchangeRate: 1.2,
+ balance: 0
+ },
+ {
+ ...invoice,
+ id: "tiny",
+ totalAmount: 0.0000001,
+ exchangeRate: 100000,
+ balance: 0
+ }
+ ]
+ });
+ const result = await service.getOpenSalesInvoicesForCustomer(
+ client,
+ "co",
+ "cust",
+ "EUR"
+ );
+ expect(
+ result.data?.map((i) => [i.id, i.balance, i.remainingDocument])
+ ).toEqual([
+ ["invoice", 100, 110],
+ ["two", 50, 60],
+ ["tiny", 0, 0.01]
+ ]);
+ });
+ it("uses recorded per-line control rounding and effective settlements for remaining base", async () => {
+ const { client } = clientFor({
+ ...config,
+ salesInvoices: [
+ { ...invoice, totalAmount: 0.000025, exchangeRate: 1000 }
+ ],
+ journalLine: [
+ {
+ documentId: "invoice",
+ amount: 0.00004,
+ journal: { status: "Posted" }
+ }
+ ],
+ invoiceSettlement: [
+ {
+ targetSalesInvoiceId: "invoice",
+ paymentId: "posted",
+ memoId: null,
+ sourceAmount: 0.01,
+ appliedAmount: 0.00001,
+ discountAmount: 0,
+ writeOffAmount: 0,
+ payment: { status: "Posted" },
+ memo: null,
+ appliedViaPayment: null
+ }
+ ]
+ });
+ const result = await service.getOpenSalesInvoicesForCustomer(
+ client,
+ "co",
+ "cust",
+ "EUR"
+ );
+ expect(result.data?.[0]).toMatchObject({
+ balance: 0.00003,
+ remainingDocument: 0.02
+ });
+ });
+});
+
+describe("memo application save", () => {
+ const memo = {
+ id: "memo",
+ companyId: "co",
+ status: "Posted",
+ direction: "Credit",
+ customerId: "cust",
+ supplierId: null,
+ currencyCode: "EUR",
+ exchangeRate: 1.1,
+ amount: 55
+ };
+ it("stores exact memo document principal while applying base amount", async () => {
+ const { db, inserts } = draftDb({ memo: [memo] });
+ await service.applyCreditsToInvoices(db, {
+ paymentId: "current",
+ companyId: "co",
+ createdBy: "user",
+ side: "sales",
+ appliedDate: "2026-09-07",
+ applications: [{ memoId: "memo", invoiceId: "invoice", amount: 50 }]
+ });
+ expect(inserts[0]).toMatchObject({
+ memoId: "memo",
+ appliedViaPaymentId: "current",
+ appliedAmount: 50,
+ sourceAmount: 55,
+ sourceExchangeRate: 1.1,
+ targetExchangeRate: 1.1
+ });
+ });
+ it.each([
+ { ...memo, status: "Draft" },
+ { ...memo, direction: "Debit" },
+ { ...memo, currencyCode: "GBP" },
+ { ...memo, customerId: "other" }
+ ])("rejects an ineligible memo before replacing staged credits", async (invalid) => {
+ const { db, deletes } = draftDb({ memo: [invalid] });
+ await expect(
+ service.applyCreditsToInvoices(db, {
+ paymentId: "current",
+ companyId: "co",
+ createdBy: "user",
+ side: "sales",
+ appliedDate: "2026-09-07",
+ applications: [{ memoId: "memo", invoiceId: "invoice", amount: 50 }]
+ })
+ ).rejects.toThrow();
+ expect(deletes).toEqual([]);
+ });
+ it("rejects base overdraw that the former document-number cap accepted", async () => {
+ const { db } = draftDb({ memo: [memo] });
+ await expect(
+ service.applyCreditsToInvoices(db, {
+ paymentId: "current",
+ companyId: "co",
+ createdBy: "user",
+ side: "sales",
+ appliedDate: "2026-09-07",
+ applications: [{ memoId: "memo", invoiceId: "invoice", amount: 54 }]
+ })
+ ).rejects.toThrow(/funding|balance/i);
+ });
+});
+
+describe("invoice history", () => {
+ it("aggregates funding splits under the applying payment, excludes draft/voided activity, and scopes parents", async () => {
+ const app = {
+ id: "a",
+ companyId: "co",
+ paymentId: "posted",
+ payment: { ...payment, id: "posted", paymentId: "PAY1" },
+ memoId: null,
+ targetSalesInvoiceId: "invoice",
+ sourceAmount: 44,
+ appliedAmount: 40,
+ discountAmount: 0,
+ writeOffAmount: 0,
+ fxGainLossAmount: -3.33333,
+ targetExchangeRate: 1.1,
+ sourceExchangeRate: 1.2,
+ appliedDate: "2026-09-07",
+ appliedViaPaymentId: null
+ };
+ const { client, calls } = clientFor({
+ invoiceSettlement: [
+ app,
+ {
+ ...app,
+ id: "b",
+ sourceAmount: 66,
+ appliedAmount: 60,
+ fxGainLossAmount: 0,
+ sourceExchangeRate: 1.1
+ },
+ {
+ ...app,
+ id: "c",
+ paymentId: "draft",
+ payment: { ...payment, status: "Draft" }
+ },
+ {
+ ...app,
+ id: "d",
+ paymentId: null,
+ payment: null,
+ memo: { id: "memo", companyId: "co", status: "Posted" },
+ appliedViaPayment: { status: "Draft" },
+ memoId: "memo",
+ appliedViaPaymentId: "draft"
+ }
+ ],
+ payment: [
+ { ...payment, id: "posted", paymentId: "PAY1" },
+ { ...payment, id: "draft", status: "Draft" }
+ ],
+ memo: [{ id: "memo", companyId: "co", status: "Posted" }]
+ });
+ const result = await service.getInvoiceSettlementsForInvoice(
+ client,
+ "co",
+ "sales",
+ "invoice"
+ );
+ expect(result.data).toHaveLength(1);
+ expect(result.data?.[0]).toMatchObject({
+ appliedAmount: 100,
+ sourceAmount: 110,
+ fxGainLossAmount: -3.33333
+ });
+ expect(
+ calls
+ .filter((c) => c.table === "invoiceSettlement")
+ .every((c) =>
+ c.filters.some(
+ ([key, value]) => key === "companyId" && value === "co"
+ )
+ )
+ ).toBe(true);
+ });
+});
+
+it("refuses a draft principal finer than configured document precision", async () => {
+ const { db, deletes } = draftDb();
+ await expect(
+ service.replaceInvoiceSettlements(db, {
+ paymentId: "current",
+ companyId: "co",
+ createdBy: "user",
+ applications: [{ ...draft, sourceAmount: 0.015, appliedAmount: 0.01364 }]
+ })
+ ).rejects.toThrow(/precision/i);
+ expect(deletes).toEqual([]);
+});
+
+it("does not retain a staged credit whose memo has been voided", async () => {
+ const staged = {
+ companyId: "co",
+ memoId: "memo",
+ paymentId: null,
+ appliedViaPaymentId: "current",
+ targetSalesInvoiceId: "invoice",
+ sourceAmount: 11,
+ appliedAmount: 10,
+ discountAmount: 0,
+ writeOffAmount: 0
+ };
+ const { db, deletes } = draftDb({
+ invoiceSettlement: [staged],
+ memo: [
+ {
+ id: "memo",
+ status: "Voided",
+ currencyCode: "EUR",
+ exchangeRate: 1.1,
+ customerId: "cust",
+ direction: "Credit"
+ }
+ ]
+ });
+ await expect(
+ service.replaceInvoiceSettlements(db, {
+ paymentId: "current",
+ companyId: "co",
+ createdBy: "user",
+ applications: [{ ...draft, sourceAmount: 55, appliedAmount: 50 }]
+ })
+ ).rejects.toThrow(/posted credit/i);
+ expect(deletes).toEqual([]);
+});
+
+it("normalizes AP with the opposite FX sign and recorded control carrying amount", async () => {
+ const payable = {
+ ...invoice,
+ customerId: undefined,
+ supplierId: "sup",
+ partyId: "sup",
+ status: "Open"
+ };
+ const { db, inserts } = draftDb({
+ payment: [
+ {
+ ...current,
+ paymentType: "Disbursement",
+ customerId: null,
+ supplierId: "sup"
+ }
+ ],
+ purchaseInvoice: [payable],
+ purchaseInvoices: [payable],
+ journalLine: [{ documentId: "invoice", amount: 100.00001 }]
+ });
+ await service.replaceInvoiceSettlements(db, {
+ paymentId: "current",
+ companyId: "co",
+ createdBy: "user",
+ applications: [
+ {
+ ...draft,
+ targetSalesInvoiceId: undefined,
+ targetPurchaseInvoiceId: "invoice"
+ }
+ ]
+ });
+ expect(inserts[0]).toMatchObject({
+ targetPurchaseInvoiceId: "invoice",
+ appliedAmount: 100.00001,
+ sourceAmount: 110,
+ fxGainLossAmount: 8.33334
+ });
+});
+
+describe("financial reader pagination", () => {
+ it("includes every posted source beyond the default 1000 row response", async () => {
+ const { client } = clientFor({
+ ...config,
+ payment: Array.from({ length: 1001 }, (_, i) => ({
+ ...payment,
+ id: `prior-${i}`
+ }))
+ });
+ const result = await service.getAvailableOnAccountCreditSources(
+ client,
+ "co",
+ { paymentType: "Receipt", customerId: "cust" },
+ "EUR"
+ );
+ expect(result.data?.sources).toHaveLength(1001);
+ expect(result.data?.availableBaseAmount).toBe(100100);
+ expect(result.data?.availableDocumentAmount).toBe(110110);
+ });
+ it("deducts all effective consumption rows across pages", async () => {
+ const { client } = clientFor({
+ ...config,
+ payment: [{ ...payment, totalAmount: 1002, exchangeRate: 1 }],
+ invoiceSettlement: Array.from({ length: 1001 }, (_, i) => ({
+ id: `s-${i}`,
+ paymentId: "prior",
+ sourcePaymentId: null,
+ sourceAmount: 1,
+ appliedAmount: 1,
+ fxGainLossAmount: 0,
+ payment: { status: "Posted" }
+ }))
+ });
+ const result = await service.getAvailableOnAccountCreditSources(
+ client,
+ "co",
+ { paymentType: "Receipt", customerId: "cust" },
+ "EUR"
+ );
+ expect(result.data?.availableDocumentAmount).toBe(1);
+ expect(result.data?.availableBaseAmount).toBe(1);
+ });
+ it("includes all posted memo credit consumption when determining availability", async () => {
+ const { client } = clientFor({
+ ...config,
+ memo: [
+ {
+ id: "memo",
+ memoId: "CM1",
+ direction: "Credit",
+ companyId: "co",
+ customerId: "cust",
+ status: "Posted",
+ currencyCode: "EUR",
+ exchangeRate: 1,
+ amount: 1002
+ }
+ ],
+ invoiceSettlement: Array.from({ length: 1001 }, (_, i) => ({
+ id: `s-${i}`,
+ memoId: "memo",
+ sourceAmount: 1,
+ appliedAmount: 1,
+ fxGainLossAmount: 0,
+ appliedViaPaymentId: null
+ }))
+ });
+ const result = await service.getAvailableCreditsForParty(
+ client,
+ "co",
+ { side: "sales", customerId: "cust" },
+ undefined,
+ "EUR"
+ );
+ expect(result.data?.[0]).toMatchObject({
+ remaining: 1,
+ remainingDocument: 1
+ });
+ });
+});
+
+it("keeps same-rate memo FX zero when the target releases its posted rounding residual", async () => {
+ const { db, inserts } = draftDb({
+ memo: [
+ {
+ id: "memo",
+ companyId: "co",
+ status: "Posted",
+ direction: "Credit",
+ customerId: "cust",
+ supplierId: null,
+ currencyCode: "EUR",
+ exchangeRate: 1.1,
+ amount: 110
+ }
+ ],
+ journalLine: [{ documentId: "invoice", amount: 100.00001 }]
+ });
+ await service.applyCreditsToInvoices(db, {
+ paymentId: "current",
+ companyId: "co",
+ createdBy: "user",
+ side: "sales",
+ appliedDate: "2026-09-07",
+ applications: [
+ { memoId: "memo", invoiceId: "invoice", amount: 100, sourceAmount: 110 }
+ ]
+ });
+ expect(inserts[0]).toMatchObject({
+ sourceAmount: 110,
+ appliedAmount: 100.00001,
+ fxGainLossAmount: 0
+ });
+});
+
+describe("complete composer source reads", () => {
+ const application = {
+ paymentId: "posted",
+ memoId: null,
+ targetSalesInvoiceId: "invoice",
+ targetPurchaseInvoiceId: "invoice",
+ sourceAmount: 1,
+ appliedAmount: 1,
+ discountAmount: 0,
+ writeOffAmount: 0,
+ payment: { status: "Posted" },
+ memo: null,
+ appliedViaPayment: null
+ };
+ it.each([
+ "sales",
+ "purchase"
+ ] as const)("reads all %s settlements beyond the response cap", async (side) => {
+ const { client } = clientFor({
+ ...config,
+ [side === "sales" ? "salesInvoices" : "purchaseInvoices"]: [
+ {
+ ...invoice,
+ totalAmount: 1002,
+ exchangeRate: 1,
+ balance: 1,
+ status: "Partially Paid"
+ }
+ ],
+ journalLine: [{ documentId: "invoice", amount: 1002 }],
+ invoiceSettlement: Array.from({ length: 1001 }, (_, index) => ({
+ ...application,
+ id: `s${index}`
+ }))
+ });
+ const result =
+ side === "sales"
+ ? await service.getOpenSalesInvoicesForCustomer(
+ client,
+ "co",
+ "cust",
+ "EUR"
+ )
+ : await service.getOpenPurchaseInvoicesForSupplier(
+ client,
+ "co",
+ "supplier",
+ "EUR"
+ );
+ expect(result.error).toBeNull();
+ expect(result.data?.[0]).toMatchObject({
+ balance: 1,
+ remainingDocument: 1
+ });
+ });
+ it("reads every original control line beyond the response cap", async () => {
+ const { client } = clientFor({
+ ...config,
+ salesInvoices: [{ ...invoice, totalAmount: 1001, exchangeRate: 1 }],
+ journalLine: Array.from({ length: 1001 }, (_, index) => ({
+ id: `line${index}`,
+ documentId: "invoice",
+ amount: 1
+ }))
+ });
+ const result = await service.getOpenSalesInvoicesForCustomer(
+ client,
+ "co",
+ "cust",
+ "EUR"
+ );
+ expect(result.data?.[0]).toMatchObject({
+ balance: 1001,
+ remainingDocument: 1001
+ });
+ });
+ it("reads every invoice and bounds contributing ID filters across an ordinary invoice batch", async () => {
+ const invoices = Array.from({ length: 1001 }, (_, index) => ({
+ ...invoice,
+ id: `invoice${index}`,
+ totalAmount: 3,
+ exchangeRate: 1
+ }));
+ const { client, calls } = clientFor({
+ ...config,
+ salesInvoices: invoices,
+ journalLine: invoices.map((i) => ({ documentId: i.id, amount: 3 })),
+ invoiceSettlement: invoices.flatMap((i, index) =>
+ [0, 1].map((n) => ({
+ ...application,
+ id: `s${index}-${n}`,
+ targetSalesInvoiceId: i.id
+ }))
+ )
+ });
+ const result = await service.getOpenSalesInvoicesForCustomer(
+ client,
+ "co",
+ "cust",
+ "EUR"
+ );
+ expect(result.data).toHaveLength(1001);
+ expect(
+ result.data?.every((i) => i.balance === 1 && i.remainingDocument === 1)
+ ).toBe(true);
+ const contributing = calls.filter(
+ (c) => c.table === "invoiceSettlement" || c.table === "journalLine"
+ );
+ expect(
+ contributing.every((c) => c.idFilters.every((ids) => ids.length <= 100))
+ ).toBe(true);
+ expect(
+ contributing.every((c) =>
+ c.filters.some(([key, value]) => key === "companyId" && value === "co")
+ )
+ ).toBe(true);
+ });
+ it("refuses a partial balance if a later contributing page fails", async () => {
+ const { client } = clientFor(
+ {
+ ...config,
+ salesInvoices: [{ ...invoice, totalAmount: 1002, exchangeRate: 1 }],
+ invoiceSettlement: Array.from({ length: 1001 }, (_, index) => ({
+ ...application,
+ id: `s${index}`
+ }))
+ },
+ { invoiceSettlement: 1000 }
+ );
+ const result = await service.getOpenSalesInvoicesForCustomer(
+ client,
+ "co",
+ "cust",
+ "EUR"
+ );
+ expect(result.data).toBeNull();
+ expect(result.error?.message).toBe("Later page failed");
+ });
+});
+
+it("rounds merged fractional document principal in invoice history", async () => {
+ const { client } = clientFor({
+ invoiceSettlement: [0.1, 0.2].map((amount, index) => ({
+ id: `s${index}`,
+ companyId: "co",
+ paymentId: "posted",
+ payment: { ...payment, id: "posted", paymentId: "PAY1" },
+ memoId: null,
+ targetSalesInvoiceId: "invoice",
+ sourceAmount: amount,
+ appliedAmount: amount,
+ discountAmount: 0,
+ writeOffAmount: 0,
+ fxGainLossAmount: 0,
+ targetExchangeRate: 1,
+ sourceExchangeRate: 1,
+ appliedDate: "2026-09-07",
+ appliedViaPaymentId: null
+ })),
+ payment: [{ ...payment, id: "posted", paymentId: "PAY1" }]
+ });
+ const result = await service.getInvoiceSettlementsForInvoice(
+ client,
+ "co",
+ "sales",
+ "invoice"
+ );
+ expect(result.data?.[0]?.sourceAmount).toBe(0.3);
+});
+
+it("saves a manual memo partial and then its final document cent with zero carrying base", async () => {
+ const highRateInvoice = {
+ ...invoice,
+ totalAmount: 160.01 / 16000,
+ exchangeRate: 16000
+ };
+ const memo = {
+ id: "memo",
+ companyId: "co",
+ status: "Posted",
+ direction: "Credit",
+ customerId: "cust",
+ supplierId: null,
+ currencyCode: "EUR",
+ exchangeRate: 16000,
+ amount: 160.01,
+ memoDate: "2026-09-07",
+ postingDate: "2026-09-07"
+ };
+ const tables = {
+ payment: [{ ...current, totalAmount: 0, exchangeRate: 16000 }],
+ salesInvoice: [highRateInvoice],
+ salesInvoices: [highRateInvoice],
+ memo: [memo],
+ journalLine: [{ documentId: "invoice", amount: 0.01 }]
+ };
+ const args = {
+ paymentId: "current",
+ companyId: "co",
+ createdBy: "user",
+ side: "sales" as const,
+ appliedDate: "2026-09-07"
+ };
+ const partial = draftDb(tables);
+ await service.applyCreditsToInvoices(partial.db, {
+ ...args,
+ applications: [
+ { memoId: "memo", invoiceId: "invoice", amount: 0.01, sourceAmount: 160 }
+ ]
+ });
+ expect(partial.inserts[0]).toMatchObject({
+ appliedAmount: 0.01,
+ sourceAmount: 160
+ });
+ const final = draftDb({
+ ...tables,
+ invoiceSettlement: [
+ {
+ ...partial.inserts[0],
+ paymentId: null,
+ appliedViaPaymentId: "posted",
+ targetPurchaseInvoiceId: null,
+ discountAmount: 0,
+ writeOffAmount: 0
+ }
+ ]
+ });
+ await service.applyCreditsToInvoices(final.db, {
+ ...args,
+ applications: [
+ { memoId: "memo", invoiceId: "invoice", amount: 0, sourceAmount: 0.01 }
+ ]
+ });
+ expect(final.inserts[0]).toMatchObject({
+ appliedAmount: 0,
+ sourceAmount: 0.01,
+ fxGainLossAmount: 0
+ });
+});
+
+it.each([
+ "sales",
+ "purchase"
+] as const)("preserves signed original %s controls", async (side) => {
+ const { client } = clientFor({
+ ...config,
+ [side === "sales" ? "salesInvoices" : "purchaseInvoices"]: [
+ {
+ ...invoice,
+ status: side === "sales" ? "Submitted" : "Open",
+ totalAmount: 90,
+ exchangeRate: 1
+ }
+ ],
+ journalLine: [
+ { documentId: "invoice", amount: 100 },
+ { documentId: "invoice", amount: -10 }
+ ]
+ });
+ const result =
+ side === "sales"
+ ? await service.getOpenSalesInvoicesForCustomer(
+ client,
+ "co",
+ "cust",
+ "EUR"
+ )
+ : await service.getOpenPurchaseInvoicesForSupplier(
+ client,
+ "co",
+ "supplier",
+ "EUR"
+ );
+ expect(result.data?.[0]).toMatchObject({
+ balance: 90,
+ remainingDocument: 90
+ });
+});
+
+it.each([
+ null,
+ -1,
+ Number.NaN
+])("refuses invalid effective invoice principal %s", async (sourceAmount) => {
+ const { client } = clientFor({
+ ...config,
+ salesInvoices: [{ ...invoice, totalAmount: 90, exchangeRate: 1 }],
+ invoiceSettlement: [
+ {
+ paymentId: "posted",
+ memoId: null,
+ targetSalesInvoiceId: "invoice",
+ sourceAmount,
+ appliedAmount: 1,
+ discountAmount: 0,
+ writeOffAmount: 0,
+ payment: { status: "Posted" },
+ memo: null,
+ appliedViaPayment: null
+ }
+ ]
+ });
+ const result = await service.getOpenSalesInvoicesForCustomer(
+ client,
+ "co",
+ "cust",
+ "EUR"
+ );
+ expect(result.data).toBeNull();
+ expect(result.error?.message).toMatch(/principal/i);
+});
+it("refuses excess invoice settlements instead of silently clamping the balance", async () => {
+ const { client } = clientFor({
+ ...config,
+ salesInvoices: [{ ...invoice, totalAmount: 90, exchangeRate: 1 }],
+ invoiceSettlement: [
+ {
+ paymentId: "posted",
+ memoId: null,
+ targetSalesInvoiceId: "invoice",
+ sourceAmount: 91,
+ appliedAmount: 91,
+ discountAmount: 0,
+ writeOffAmount: 0,
+ payment: { status: "Posted" },
+ memo: null,
+ appliedViaPayment: null
+ }
+ ]
+ });
+ const result = await service.getOpenSalesInvoicesForCustomer(
+ client,
+ "co",
+ "cust",
+ "EUR"
+ );
+ expect(result.data).toBeNull();
+ expect(result.error?.message).toMatch(/excessive settlements/i);
+});
+
+it.each([
+ "sales",
+ "purchase"
+] as const)("uses original IC %s controls and excludes VOID rows", async (side) => {
+ const description = side === "sales" ? "IC Receivables" : "IC Payables";
+ const { client } = clientFor({
+ ...config,
+ [side === "sales" ? "salesInvoices" : "purchaseInvoices"]: [
+ {
+ ...invoice,
+ status: side === "sales" ? "Submitted" : "Open",
+ totalAmount: 99,
+ exchangeRate: 1
+ }
+ ],
+ journalLine: [
+ { documentId: "invoice", amount: 100, description },
+ {
+ documentId: "invoice",
+ amount: -100,
+ description: `VOID: ${description}`
+ }
+ ]
+ });
+ const result =
+ side === "sales"
+ ? await service.getOpenSalesInvoicesForCustomer(
+ client,
+ "co",
+ "cust",
+ "EUR"
+ )
+ : await service.getOpenPurchaseInvoicesForSupplier(
+ client,
+ "co",
+ "supplier",
+ "EUR"
+ );
+ expect(result.data?.[0]).toMatchObject({
+ balance: 100,
+ remainingDocument: 99
+ });
+});
+
+it.each([
+ true,
+ false
+])("stages %s customer-ledger refund against exact memo principal with cash-direction FX", async (isAR) => {
+ const { db, inserts } = draftDb({
+ payment: [
+ {
+ ...current,
+ paymentType: isAR ? "Disbursement" : "Receipt",
+ customerId: isAR ? "cust" : null,
+ supplierId: isAR ? null : "supplier",
+ totalAmount: 55,
+ exchangeRate: 1.25
+ }
+ ],
+ memo: [
+ {
+ id: "memo",
+ companyId: "co",
+ status: "Posted",
+ customerId: isAR ? "cust" : null,
+ supplierId: isAR ? null : "supplier",
+ direction: isAR ? "Credit" : "Debit",
+ currencyCode: "EUR",
+ exchangeRate: 1.1,
+ amount: 55
+ }
+ ],
+ journalLine: [{ documentId: "memo", amount: -50 }]
+ });
+ await service.replaceInvoiceSettlements(db, {
+ paymentId: "current",
+ companyId: "co",
+ createdBy: "user",
+ applications: [
+ {
+ ...draft,
+ targetSalesInvoiceId: undefined,
+ targetMemoId: "memo",
+ sourceAmount: 55,
+ sourceExchangeRate: 1.25,
+ appliedAmount: 50
+ }
+ ]
+ });
+ expect(inserts).toEqual([
+ expect.objectContaining({
+ targetMemoId: "memo",
+ targetSalesInvoiceId: null,
+ targetPurchaseInvoiceId: null,
+ sourcePaymentId: null,
+ sourceAmount: 55,
+ appliedAmount: 50,
+ fxGainLossAmount: isAR ? 6 : -6,
+ createdBy: "user"
+ })
+ ]);
+});
+
+it("memo availability reserves refund document principal without subtracting refund FX from memo carrying", async () => {
+ const { client } = clientFor({
+ ...config,
+ memo: [
+ {
+ id: "memo",
+ memoId: "CR1",
+ companyId: "co",
+ status: "Posted",
+ direction: "Credit",
+ currencyCode: "EUR",
+ exchangeRate: 1.1,
+ amount: 55,
+ memoDate: "2026-09-07"
+ }
+ ],
+ invoiceSettlement: [
+ {
+ memoId: null,
+ targetMemoId: "memo",
+ paymentId: "refund",
+ sourceAmount: 22,
+ appliedAmount: 20,
+ fxGainLossAmount: 2.4,
+ payment: { status: "Posted" },
+ appliedViaPaymentId: null
+ }
+ ]
+ });
+ const result = await service.getAvailableCreditsForParty(
+ client,
+ "co",
+ { side: "sales", customerId: "cust" },
+ undefined,
+ "EUR"
+ );
+ expect(result.data?.[0]).toMatchObject({
+ remainingDocument: 33,
+ remaining: 30
+ });
+});
+
+it("changing a draft payment to a supplier clears its former customer", async () => {
+ let saved: Row | undefined;
+ const query: any = {
+ update: (row: Row) => {
+ saved = row;
+ return query;
+ },
+ eq: () => query,
+ select: () => query,
+ single: async () => ({ data: { id: "current" }, error: null })
+ };
+ await service.upsertPayment({ from: () => query } as any, {
+ id: "current",
+ updatedBy: "user",
+ paymentType: "Receipt",
+ supplierId: "supplier",
+ paymentDate: "2026-09-07",
+ currencyCode: "EUR",
+ exchangeRate: 1,
+ totalAmount: 10,
+ bankAccount: "bank"
+ });
+ expect(saved).toMatchObject({ customerId: null, supplierId: "supplier" });
+});
+
+it.each([
+ ["party", { supplierId: "other" }, {}],
+ ["currency", { currencyCode: "USD" }, {}],
+ ["direction", { direction: "Credit" }, {}],
+ ["memo status", { status: "Draft" }, {}],
+ ["adjustments", {}, { discountAmount: 1 }],
+ ["over-refund", {}, { sourceAmount: 56 }],
+ [
+ "invoice target",
+ {},
+ { targetMemoId: undefined, targetPurchaseInvoiceId: "invoice" }
+ ]
+])("rejects invalid supplier refund %s without replacing applications", async (_label, memoOverride, appOverride) => {
+ const { db, inserts, deletes } = draftDb({
+ payment: [
+ {
+ ...current,
+ paymentType: "Receipt",
+ customerId: null,
+ supplierId: "supplier",
+ totalAmount: 100,
+ exchangeRate: 1.25
+ }
+ ],
+ memo: [
+ {
+ id: "memo",
+ companyId: "co",
+ status: "Posted",
+ supplierId: "supplier",
+ customerId: null,
+ direction: "Debit",
+ currencyCode: "EUR",
+ exchangeRate: 1.1,
+ amount: 55,
+ ...memoOverride
+ }
+ ]
+ });
+ await expect(
+ service.replaceInvoiceSettlements(db, {
+ paymentId: "current",
+ companyId: "co",
+ createdBy: "user",
+ applications: [
+ {
+ ...draft,
+ targetSalesInvoiceId: undefined,
+ targetMemoId: "memo",
+ sourceAmount: 55,
+ sourceExchangeRate: 1.25,
+ appliedAmount: 50,
+ ...appOverride
+ }
+ ]
+ })
+ ).rejects.toThrow();
+ expect(inserts).toEqual([]);
+ expect(deletes).toEqual([]);
+});
+
+it("a fully refunded memo cannot also fund an invoice", async () => {
+ const { db, inserts } = draftDb({
+ payment: [{ ...current, totalAmount: 0, exchangeRate: 1.1 }],
+ memo: [
+ {
+ id: "memo",
+ companyId: "co",
+ status: "Posted",
+ customerId: "cust",
+ direction: "Credit",
+ currencyCode: "EUR",
+ exchangeRate: 1.1,
+ amount: 55
+ }
+ ],
+ invoiceSettlement: [
+ {
+ memoId: null,
+ targetMemoId: "memo",
+ paymentId: "refund",
+ sourceAmount: 55,
+ appliedAmount: 50,
+ fxGainLossAmount: 6
+ }
+ ]
+ });
+ await expect(
+ service.applyCreditsToInvoices(db, {
+ paymentId: "current",
+ companyId: "co",
+ createdBy: "user",
+ side: "sales",
+ appliedDate: "2026-09-07",
+ applications: [
+ { memoId: "memo", invoiceId: "invoice", amount: 50, sourceAmount: 55 }
+ ]
+ })
+ ).rejects.toThrow(/remaining funding balance/);
+ expect(inserts).toEqual([]);
+});
diff --git a/apps/erp/app/modules/invoicing/ui/Memo/MemoForm.tsx b/apps/erp/app/modules/invoicing/ui/Memo/MemoForm.tsx
index d133e558ef..43426fadf5 100644
--- a/apps/erp/app/modules/invoicing/ui/Memo/MemoForm.tsx
+++ b/apps/erp/app/modules/invoicing/ui/Memo/MemoForm.tsx
@@ -65,7 +65,6 @@ const MemoForm = ({ initialValues }: MemoFormProps) => {
);
const permissions = usePermissions();
const post = useFetcher();
- const voidFetcher = useFetcher();
const isEditing = Boolean(initialValues.id);
const status = initialValues.status as
| "Draft"
@@ -76,6 +75,7 @@ const MemoForm = ({ initialValues }: MemoFormProps) => {
const canMutate = permissions.can("update", "invoicing");
const canDelete = permissions.can("delete", "invoicing");
const deleteModal = useDisclosure();
+ const voidModal = useDisclosure();
// Party type is a UI-only toggle — NOT a validator field. It switches which of
// customerId/supplierId is shown; the hidden one stays empty. A memo can be for
@@ -138,14 +138,9 @@ const MemoForm = ({ initialValues }: MemoFormProps) => {
<Button
leftIcon={<LuTicketX />}
variant="destructive"
- isLoading={voidFetcher.state !== "idle"}
+ type="button"
isDisabled={!canMutate}
- onClick={() =>
- voidFetcher.submit(null, {
- method: "post",
- action: path.to.memoVoid(initialValues.id!)
- })
- }
+ onClick={voidModal.onOpen}
>
<Trans>Void</Trans>
</Button>
@@ -252,6 +247,17 @@ const MemoForm = ({ initialValues }: MemoFormProps) => {
</CardFooter>
</Card>
</ValidatedForm>
+ {voidModal.isOpen && (
+ <ConfirmDelete
+ action={path.to.memoVoid(initialValues.id!)}
+ name={initialValues.memoId ?? ""}
+ title={t`Void ${initialValues.memoId}`}
+ text={t`Are you sure you want to void this memo? This will reverse its accounting entries and applications. This cannot be undone.`}
+ deleteText={t`Void`}
+ onCancel={voidModal.onClose}
+ onSubmit={voidModal.onClose}
+ />
+ )}
{deleteModal.isOpen && (
<ConfirmDelete
action={path.to.memoDelete(initialValues.id!)}
diff --git a/apps/erp/app/modules/invoicing/ui/Payment/AvailableCreditsTable.tsx b/apps/erp/app/modules/invoicing/ui/Payment/AvailableCreditsTable.tsx
index 2c8dbfab1f..cff204f3e0 100644
--- a/apps/erp/app/modules/invoicing/ui/Payment/AvailableCreditsTable.tsx
+++ b/apps/erp/app/modules/invoicing/ui/Payment/AvailableCreditsTable.tsx
@@ -16,7 +16,12 @@ import {
SelectTrigger,
SelectValue
} from "@carbon/react";
-import { INPUT_FORMAT, round } from "@carbon/utils";
+import {
+ INPUT_FORMAT,
+ round,
+ toBaseAmount,
+ toDocumentAmount
+} from "@carbon/utils";
import { Trans, useLingui } from "@lingui/react/macro";
import { useCallback, useMemo, useState } from "react";
import { LuSave } from "react-icons/lu";
@@ -38,6 +43,7 @@ type AvailableCredit = {
currencyCode: string;
exchangeRate: number;
remaining: number;
+ remainingDocument: number;
};
type OpenInvoiceOption = {
@@ -45,6 +51,7 @@ type OpenInvoiceOption = {
invoiceId: string;
exchangeRate: number;
balance: number;
+ remainingDocument: number;
};
type AvailableCreditsTableProps = {
@@ -52,11 +59,18 @@ type AvailableCreditsTableProps = {
// Drives which invoice column the settlement targets.
side: "sales" | "purchase";
currency: string;
+ documentCurrency: string;
+ documentDecimals: number;
credits: AvailableCredit[];
openInvoices: OpenInvoiceOption[];
// Credit applications already staged on this (Draft) payment — pre-fills the
// table so a staged credit shows as selected instead of vanishing.
- staged?: { memoId: string; invoiceId: string; amount: number }[];
+ staged?: {
+ memoId: string;
+ invoiceId: string;
+ amount: number;
+ sourceAmount?: number | null;
+ }[];
};
type CreditRow = {
@@ -64,9 +78,12 @@ type CreditRow = {
memoId: string;
direction: string;
remaining: number;
+ remainingDocument: number;
checked: boolean;
invoiceId: string; // target invoice id
amount: number;
+ sourceAmount: number;
+ exchangeRate: number;
};
const GRID =
@@ -76,6 +93,8 @@ const AvailableCreditsTable = ({
paymentId,
side,
currency,
+ documentCurrency,
+ documentDecimals,
credits,
openInvoices,
staged = []
@@ -84,11 +103,14 @@ const AvailableCreditsTable = ({
const permissions = usePermissions();
const fetcher = useFetcher();
const currencyFormatter = useCurrencyFormatter({ currency });
+ const documentFormatter = useCurrencyFormatter({
+ currency: documentCurrency
+ });
const currencyDecimals = useCurrencyDecimals(currency);
const canEdit = permissions.can("update", "invoicing");
const balanceByInvoice = useMemo(
- () => new Map(openInvoices.map((i) => [i.id, i.balance])),
+ () => new Map(openInvoices.map((i) => [i.id, i])),
[openInvoices]
);
@@ -106,69 +128,88 @@ const AvailableCreditsTable = ({
memoId: c.memoId,
direction: c.direction,
remaining: c.remaining,
+ remainingDocument: c.remainingDocument,
+ exchangeRate: c.exchangeRate,
checked: Boolean(s),
- invoiceId: s?.invoiceId ?? openInvoices[0]?.id ?? "",
- amount: s?.amount ?? 0
+ invoiceId:
+ s?.invoiceId ??
+ openInvoices.find((i) => i.exchangeRate === c.exchangeRate)?.id ??
+ "",
+ amount: s?.amount ?? 0,
+ sourceAmount:
+ s?.sourceAmount ??
+ (s
+ ? toDocumentAmount(s.amount, c.exchangeRate, documentDecimals)
+ : 0)
};
}),
- [credits, openInvoices, stagedByMemo]
+ [credits, openInvoices, stagedByMemo, documentDecimals]
);
const [rows, setRows] = useState<CreditRow[]>(seed);
- // The most a credit can apply to the chosen invoice: its remaining vs the
- // invoice's open balance.
const capFor = useCallback(
- (remaining: number, invoiceId: string) =>
- round(Math.min(remaining, Number(balanceByInvoice.get(invoiceId) ?? 0))),
+ (row: CreditRow, invoiceId: string) => {
+ const invoice = balanceByInvoice.get(invoiceId);
+ if (!invoice || invoice.exchangeRate !== row.exchangeRate)
+ return { amount: 0, sourceAmount: 0 };
+ const sourceAmount = Math.min(
+ row.remainingDocument,
+ invoice.remainingDocument
+ );
+ const amount =
+ sourceAmount === invoice.remainingDocument
+ ? invoice.balance
+ : sourceAmount === row.remainingDocument
+ ? row.remaining
+ : toBaseAmount(sourceAmount, row.exchangeRate);
+ return { amount, sourceAmount };
+ },
[balanceByInvoice]
);
-
const toggleRow = useCallback(
(id: string, checked: boolean) =>
setRows((prev) =>
- prev.map((r) => {
- if (r.id !== id) return r;
- if (checked) {
- return {
- ...r,
- checked: true,
- amount:
- r.amount === 0 ? capFor(r.remaining, r.invoiceId) : r.amount
- };
- }
- return { ...r, checked: false, amount: 0 };
- })
+ prev.map((r) =>
+ r.id !== id
+ ? r
+ : {
+ ...r,
+ checked,
+ ...(checked
+ ? capFor(r, r.invoiceId)
+ : { amount: 0, sourceAmount: 0 })
+ }
+ )
),
[capFor]
);
-
const updateInvoice = useCallback(
(id: string, invoiceId: string) =>
setRows((prev) =>
prev.map((r) =>
- r.id === id
- ? {
- ...r,
- invoiceId,
- amount: r.checked ? capFor(r.remaining, invoiceId) : r.amount
- }
- : r
+ r.id !== id
+ ? r
+ : { ...r, invoiceId, ...(r.checked ? capFor(r, invoiceId) : {}) }
)
),
[capFor]
);
-
const updateAmount = useCallback(
(id: string, value: number) =>
setRows((prev) =>
prev.map((r) => {
if (r.id !== id) return r;
const amount = round(Math.max(0, value));
- return { ...r, amount, checked: amount > 0 };
+ const sourceAmount = toDocumentAmount(
+ amount,
+ r.exchangeRate,
+ documentDecimals
+ );
+ return { ...r, amount, sourceAmount, checked: sourceAmount > 0 };
})
),
- []
+ [documentDecimals]
);
const totalApplied = useMemo(
@@ -178,11 +219,12 @@ const AvailableCreditsTable = ({
const onSave = () => {
const applications = rows
- .filter((r) => r.checked && r.amount > 0 && r.invoiceId)
+ .filter((r) => r.checked && r.sourceAmount > 0 && r.invoiceId)
.map((r) => ({
memoId: r.id,
invoiceId: r.invoiceId,
- amount: r.amount
+ amount: r.amount,
+ sourceAmount: r.sourceAmount
}));
const formData = new FormData();
@@ -205,8 +247,8 @@ const AvailableCreditsTable = ({
</CardTitle>
<CardDescription>
<Trans>
- Clear this invoice with the party's posted credits as well as cash.
- Credits apply directly — no posting needed.
+ Credit amounts are in company base currency ({currency}). Credits
+ take effect when this payment posts.
</Trans>
</CardDescription>
</CardHeader>
@@ -271,6 +313,9 @@ const AvailableCreditsTable = ({
</div>
<div className="text-right tabular-nums text-sm text-muted-foreground self-center">
{currencyFormatter.format(Number(r.remaining))}
+ <div className="text-xs">
+ {documentFormatter.format(r.remainingDocument)}
+ </div>
</div>
<Select
value={r.invoiceId}
@@ -280,11 +325,13 @@ const AvailableCreditsTable = ({
<SelectValue placeholder={t`Select invoice`} />
</SelectTrigger>
<SelectContent>
- {openInvoices.map((inv) => (
- <SelectItem key={inv.id} value={inv.id}>
- {inv.invoiceId}
- </SelectItem>
- ))}
+ {openInvoices
+ .filter((inv) => inv.exchangeRate === r.exchangeRate)
+ .map((inv) => (
+ <SelectItem key={inv.id} value={inv.id}>
+ {inv.invoiceId}
+ </SelectItem>
+ ))}
</SelectContent>
</Select>
<NumberField
@@ -349,7 +396,7 @@ const CardFooterRow = ({
leftIcon={<LuSave />}
onClick={onSave}
isLoading={isSaving}
- isDisabled={!canEdit || totalApplied <= 0}
+ isDisabled={!canEdit}
>
<Trans>Apply credits</Trans>
</Button>
diff --git a/apps/erp/app/modules/invoicing/ui/Payment/InvoicePaymentsPanel.tsx b/apps/erp/app/modules/invoicing/ui/Payment/InvoicePaymentsPanel.tsx
index 9f1b9381c5..0e68ebe224 100644
--- a/apps/erp/app/modules/invoicing/ui/Payment/InvoicePaymentsPanel.tsx
+++ b/apps/erp/app/modules/invoicing/ui/Payment/InvoicePaymentsPanel.tsx
@@ -37,8 +37,9 @@ const InvoicePaymentsPanel = ({ rows }: InvoiceSettlementsPanelProps) => {
</CardTitle>
<CardDescription>
<Trans>
- Payments and credits applied to this invoice. Click a row to open
- the source document.
+ Payments and credits applied to this invoice. Applied amounts and FX
+ are in company base currency. Click a row to open the source
+ document.
</Trans>
</CardDescription>
</CardHeader>
@@ -82,7 +83,7 @@ const InvoicePaymentsPanel = ({ rows }: InvoiceSettlementsPanelProps) => {
<Enumerable
value={
r.source.type === "payment"
- ? "Cash"
+ ? "Payment"
: r.source.direction
}
/>
@@ -101,6 +102,7 @@ const InvoicePaymentsPanel = ({ rows }: InvoiceSettlementsPanelProps) => {
</Td>
<Td className="text-right tabular-nums">
{currencyFormatter.format(Number(r.appliedAmount))}
+ <DocumentPrincipal row={r} />
</Td>
<Td className="text-right tabular-nums">
{currencyFormatter.format(Number(r.discountAmount))}
@@ -121,4 +123,13 @@ const InvoicePaymentsPanel = ({ rows }: InvoiceSettlementsPanelProps) => {
);
};
+function DocumentPrincipal({ row }: { row: InvoiceSettlementForInvoice }) {
+ const format = useCurrencyFormatter({ currency: row.source.currencyCode });
+ return row.sourceAmount == null ? null : (
+ <div className="text-xs text-muted-foreground">
+ {format.format(row.sourceAmount)}
+ </div>
+ );
+}
+
export default InvoicePaymentsPanel;
diff --git a/apps/erp/app/modules/invoicing/ui/Payment/PaymentApplications.tsx b/apps/erp/app/modules/invoicing/ui/Payment/PaymentApplications.tsx
index 69236e3952..1525848e9b 100644
--- a/apps/erp/app/modules/invoicing/ui/Payment/PaymentApplications.tsx
+++ b/apps/erp/app/modules/invoicing/ui/Payment/PaymentApplications.tsx
@@ -11,7 +11,7 @@ import {
Thead,
Tr
} from "@carbon/react";
-import { SCALE_FORMAT } from "@carbon/utils";
+import { round, SCALE_FORMAT } from "@carbon/utils";
import { Trans } from "@lingui/react/macro";
import { useNumberFormatter } from "@react-aria/i18n";
import { DateTime, Hyperlink } from "~/components";
@@ -24,8 +24,11 @@ type PaymentApplication = NonNullable<
>[number];
type PaymentApplicationsProps = {
+ isRefund?: boolean;
applications: PaymentApplication[];
paymentTotal: number;
+ paymentCurrency: string;
+ baseCurrency: string;
};
// The applied invoice's human-readable id comes from the embedded
@@ -43,22 +46,69 @@ function invoiceLabel(a: PaymentApplication) {
| null;
targetSalesInvoiceId?: string | null;
targetPurchaseInvoiceId?: string | null;
+ targetMemoId?: string | null;
+ targetMemo?:
+ | { memoId?: string | null }
+ | { memoId?: string | null }[]
+ | null;
};
const pick = (x: typeof rec.salesInvoice) =>
Array.isArray(x) ? x[0]?.invoiceId : x?.invoiceId;
return (
pick(rec.salesInvoice) ??
pick(rec.purchaseInvoice) ??
+ (Array.isArray(rec.targetMemo)
+ ? rec.targetMemo[0]?.memoId
+ : rec.targetMemo?.memoId) ??
rec.targetSalesInvoiceId ??
- rec.targetPurchaseInvoiceId
+ rec.targetPurchaseInvoiceId ??
+ rec.targetMemoId
);
}
const PaymentApplications = ({
- applications,
+ isRefund = false,
+ applications: splits,
+ paymentCurrency,
+ baseCurrency,
paymentTotal
}: PaymentApplicationsProps) => {
- const currencyFormatter = useCurrencyFormatter();
+ const currencyFormatter = useCurrencyFormatter({ currency: baseCurrency });
+ const documentFormatter = useCurrencyFormatter({ currency: paymentCurrency });
+ const byInvoice = new Map<
+ string,
+ PaymentApplication & { sourceRates: number[] }
+ >();
+ for (const a of splits) {
+ const id =
+ a.targetSalesInvoiceId ??
+ a.targetPurchaseInvoiceId ??
+ a.targetMemoId ??
+ a.id;
+ const existing = byInvoice.get(id);
+ if (!existing) {
+ byInvoice.set(id, { ...a, sourceRates: [Number(a.sourceExchangeRate)] });
+ continue;
+ }
+ existing.appliedAmount = round(
+ existing.appliedAmount + Number(a.appliedAmount)
+ );
+ existing.discountAmount = round(
+ existing.discountAmount + Number(a.discountAmount)
+ );
+ existing.writeOffAmount = round(
+ existing.writeOffAmount + Number(a.writeOffAmount)
+ );
+ existing.sourceAmount =
+ (existing.sourceAmount ?? 0) + Number(a.sourceAmount ?? 0);
+ existing.fxGainLossAmount = round(
+ Number(existing.fxGainLossAmount ?? 0) + Number(a.fxGainLossAmount ?? 0)
+ );
+ existing.sourceRates = [
+ ...new Set([...existing.sourceRates, Number(a.sourceExchangeRate)])
+ ];
+ }
+ const applications = [...byInvoice.values()];
const rateFormatter = useNumberFormatter(SCALE_FORMAT);
const totalApplied = applications.reduce(
@@ -71,7 +121,10 @@ const PaymentApplications = ({
);
const unapplied =
paymentTotal -
- applications.reduce((s, a) => s + Number(a.appliedAmount), 0);
+ splits.reduce(
+ (s, a) => s + (a.sourcePaymentId ? 0 : Number(a.sourceAmount ?? 0)),
+ 0
+ );
return (
<Card className="w-full">
@@ -84,9 +137,7 @@ const PaymentApplications = ({
<Table>
<Thead>
<Tr>
- <Th>
- <Trans>Invoice</Trans>
- </Th>
+ <Th>{isRefund ? <Trans>Memo</Trans> : <Trans>Invoice</Trans>}</Th>
<Th className="text-right">
<Trans>Applied</Trans>
</Th>
@@ -133,12 +184,19 @@ const PaymentApplications = ({
>
{invoiceLabel(a)}
</Hyperlink>
+ ) : a.targetMemoId ? (
+ <Hyperlink to={path.to.memo(a.targetMemoId)}>
+ {invoiceLabel(a)}
+ </Hyperlink>
) : (
invoiceLabel(a)
)}
</Td>
<Td className="text-right tabular-nums">
{currencyFormatter.format(Number(a.appliedAmount))}
+ <div className="text-xs text-muted-foreground">
+ {documentFormatter.format(Number(a.sourceAmount ?? 0))}
+ </div>
</Td>
<Td className="text-right tabular-nums">
{currencyFormatter.format(Number(a.discountAmount))}
@@ -150,7 +208,9 @@ const PaymentApplications = ({
{rateFormatter.format(Number(a.targetExchangeRate))}
</Td>
<Td className="text-right tabular-nums">
- {rateFormatter.format(Number(a.sourceExchangeRate))}
+ {a.sourceRates
+ .map((rate) => rateFormatter.format(rate))
+ .join(" / ")}
</Td>
<Td className="text-right tabular-nums">
{currencyFormatter.format(Number(a.fxGainLossAmount ?? 0))}
@@ -174,7 +234,7 @@ const PaymentApplications = ({
<Td colSpan={5} />
<Td className="text-right tabular-nums">
<Trans>Unapplied:</Trans>{" "}
- {currencyFormatter.format(unapplied)}
+ {documentFormatter.format(unapplied)}
</Td>
</Tr>
</Tfoot>
diff --git a/apps/erp/app/modules/invoicing/ui/Payment/PaymentApplyTable.test.tsx b/apps/erp/app/modules/invoicing/ui/Payment/PaymentApplyTable.test.tsx
new file mode 100644
index 0000000000..69d4cdeb76
--- /dev/null
+++ b/apps/erp/app/modules/invoicing/ui/Payment/PaymentApplyTable.test.tsx
@@ -0,0 +1,610 @@
+import type { ReactNode } from "react";
+import { createElement } from "react";
+import { renderToStaticMarkup } from "react-dom/server";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const harness = vi.hoisted(() => ({
+ submit: vi.fn(),
+ buttons: [] as {
+ children: ReactNode;
+ onClick?: () => void;
+ isDisabled?: boolean;
+ }[],
+ amounts: [] as {
+ "aria-label"?: string;
+ onChange?: (value: number) => void;
+ }[],
+ checkboxes: [] as { onCheckedChange?: (checked: boolean) => void }[],
+ state: undefined as unknown
+}));
+vi.mock("react", async (importOriginal) => {
+ const react = await importOriginal<typeof import("react")>();
+ return {
+ ...react,
+ useState: (seed: unknown) => {
+ if (harness.state === undefined)
+ harness.state = typeof seed === "function" ? seed() : seed;
+ return [
+ harness.state,
+ (value: unknown) => {
+ harness.state =
+ typeof value === "function" ? value(harness.state) : value;
+ }
+ ];
+ }
+ };
+});
+vi.mock("@carbon/react", () => {
+ const Box = ({ children }: { children: ReactNode }) =>
+ createElement("div", null, children);
+ return {
+ Button: (props: {
+ children: ReactNode;
+ onClick?: () => void;
+ isDisabled?: boolean;
+ }) => {
+ harness.buttons.push(props);
+ return createElement("button", null, props.children);
+ },
+ Select: Box,
+ SelectContent: Box,
+ SelectItem: Box,
+ SelectTrigger: Box,
+ SelectValue: Box,
+ Table: Box,
+ Tbody: Box,
+ Td: Box,
+ Tfoot: Box,
+ Th: Box,
+ Thead: Box,
+ Tr: Box,
+ Card: Box,
+ CardContent: Box,
+ CardDescription: Box,
+ CardFooter: Box,
+ CardHeader: Box,
+ CardTitle: Box,
+ HStack: Box,
+ Checkbox: (props: { onCheckedChange?: (checked: boolean) => void }) => {
+ harness.checkboxes.push(props);
+ return null;
+ },
+ NumberField: (props: {
+ value: number;
+ formatOptions: Intl.NumberFormatOptions;
+ "aria-label"?: string;
+ onChange?: (value: number) => void;
+ }) => {
+ harness.amounts.push(props);
+ return createElement(
+ "output",
+ null,
+ new Intl.NumberFormat("en-US", props.formatOptions).format(props.value)
+ );
+ },
+ NumberInput: Box,
+ NumberInputGroup: Box,
+ cn: (...args: unknown[]) =>
+ args.filter((x) => typeof x === "string").join(" ")
+ };
+});
+vi.mock("@lingui/react/macro", () => ({
+ Trans: ({ children }: { children: ReactNode }) => children,
+ useLingui: () => ({
+ t: (parts: TemplateStringsArray, ...values: unknown[]) =>
+ parts.reduce((s, p, i) => s + p + (values[i] ?? ""), "")
+ })
+}));
+vi.mock("react-router", () => ({
+ generatePath: (s: string) => s,
+ useFetcher: () => ({ state: "idle", submit: harness.submit })
+}));
+vi.mock("~/components", () => ({
+ DateTime: () => null,
+ Hyperlink: ({ children }: { children: ReactNode }) => children
+}));
+vi.mock("~/components/Enumerable", () => ({ Enumerable: () => null }));
+vi.mock("@react-aria/i18n", () => ({
+ useNumberFormatter: () => new Intl.NumberFormat("en-US")
+}));
+vi.mock("~/hooks", () => ({
+ usePermissions: () => ({ can: () => true }),
+ useCompanyToday: () => ({ toString: () => "2026-09-07" }),
+ useCurrencyDecimals: () => 2,
+ useCurrencyFormatter: ({ currency = "USD" } = {}) =>
+ new Intl.NumberFormat("en-US", { style: "currency", currency })
+}));
+
+import AvailableCreditsTable from "./AvailableCreditsTable";
+import PaymentApplications from "./PaymentApplications";
+import PaymentApplyTable from "./PaymentApplyTable";
+
+const props = {
+ paymentId: "current",
+ paymentType: "Receipt" as const,
+ paymentCurrency: "EUR",
+ baseCurrency: "USD",
+ currencyDecimals: 2,
+ paymentTotal: 170,
+ paymentExchangeRate: 1.2,
+ availableCredit: 0,
+ priorSources: [],
+ openInvoices: [
+ {
+ id: "one",
+ invoiceId: "INV1",
+ dateDue: null,
+ currencyCode: "EUR",
+ exchangeRate: 1.1,
+ totalAmount: 100,
+ balance: 100,
+ remainingDocument: 110,
+ status: "Submitted"
+ },
+ {
+ id: "two",
+ invoiceId: "INV2",
+ dateDue: null,
+ currencyCode: "EUR",
+ exchangeRate: 1.2,
+ totalAmount: 50,
+ balance: 50,
+ remainingDocument: 60,
+ status: "Submitted"
+ }
+ ],
+ existingApplications: []
+};
+function render(overrides = {}) {
+ harness.buttons = [];
+ harness.amounts = [];
+ harness.checkboxes = [];
+ return renderToStaticMarkup(
+ createElement(PaymentApplyTable, { ...props, ...overrides })
+ );
+}
+function click(label: string) {
+ const button = harness.buttons.find((b) =>
+ renderToStaticMarkup(createElement("span", null, b.children)).includes(
+ label
+ )
+ );
+ expect(button).toBeDefined();
+ button?.onClick?.();
+}
+function editAmount(label: string, value: number) {
+ const field = harness.amounts.find((input) => input["aria-label"] === label);
+ expect(field).toBeDefined();
+ field?.onChange?.(value);
+}
+function savedApplications() {
+ click("Save applications");
+ const formData = harness.submit.mock.calls.at(-1)?.[0] as FormData;
+ expect(formData).toBeInstanceOf(FormData);
+ return JSON.parse(String(formData.get("applications")));
+}
+beforeEach(() => {
+ harness.state = undefined;
+ harness.buttons = [];
+ harness.amounts = [];
+ harness.checkboxes = [];
+ harness.submit.mockClear();
+});
+describe("payment composer document funding", () => {
+ it.each([
+ "Receipt",
+ "Disbursement"
+ ])("applies %s refunds to memos and reopens exact principal", (paymentType) => {
+ const overrides = {
+ paymentType,
+ isRefund: true,
+ paymentTotal: 110,
+ openInvoices: [props.openInvoices[0]]
+ };
+ const html = render(overrides);
+ expect(html).toContain("Refund memos");
+ expect(harness.amounts).toHaveLength(1);
+ click("Auto apply");
+ render(overrides);
+ const apps = savedApplications();
+ expect(apps).toEqual([
+ expect.objectContaining({
+ targetMemoId: "one",
+ appliedAmount: 100,
+ sourceAmount: 110
+ })
+ ]);
+ expect(apps[0]).not.toHaveProperty("targetSalesInvoiceId");
+ expect(apps[0]).not.toHaveProperty("targetPurchaseInvoiceId");
+ harness.state = undefined;
+ render({ ...overrides, existingApplications: apps });
+ expect(savedApplications()).toEqual(apps);
+ });
+ const highRate = {
+ paymentTotal: 0,
+ paymentExchangeRate: 16000,
+ availableCredit: 160.01,
+ priorSources: [
+ {
+ paymentId: "prior",
+ postingDate: "2026-09-01",
+ exchangeRate: 16000,
+ remainingDocument: 160.01,
+ remainingBase: 0.01
+ }
+ ],
+ openInvoices: [
+ {
+ ...props.openInvoices[0],
+ exchangeRate: 16000,
+ totalAmount: 0.01,
+ balance: 0.01,
+ remainingDocument: 160.01
+ }
+ ]
+ };
+ const highRateApplication = {
+ targetSalesInvoiceId: "one",
+ targetPurchaseInvoiceId: null,
+ appliedAmount: 0.01,
+ sourceAmount: 160.01,
+ discountAmount: 0,
+ writeOffAmount: 0,
+ targetExchangeRate: 16000,
+ sourceExchangeRate: 16000,
+ appliedDate: "2026-09-07"
+ };
+
+ it.each([
+ false,
+ true
+ ])("manual base .01 consumes160.00 and preserves a document cent (reopened:%s)", (reopened) => {
+ const overrides = {
+ ...highRate,
+ existingApplications: reopened ? [highRateApplication] : []
+ };
+ render(overrides);
+ editAmount("Applied amount for INV1", 0.01);
+ render(overrides);
+ expect(savedApplications()).toEqual([
+ expect.objectContaining({ appliedAmount: 0.01, sourceAmount: 160 })
+ ]);
+ });
+
+ it.each([
+ "Discount",
+ "Write-off"
+ ])("%s zero edit does not promote a rounded partial amount to full document relief", (label) => {
+ const overrides = {
+ ...highRate,
+ existingApplications: [{ ...highRateApplication, sourceAmount: 160 }]
+ };
+ render(overrides);
+ editAmount(`${label} for INV1`, 0);
+ render(overrides);
+ expect(savedApplications()).toEqual([
+ expect.objectContaining({
+ appliedAmount: 0.01,
+ sourceAmount: 160,
+ discountAmount: 0,
+ writeOffAmount: 0
+ })
+ ]);
+ });
+
+ it.each([
+ "checkbox",
+ "Auto apply"
+ ])("%s retains all160.01 source units for an exact full application", (selection) => {
+ render(highRate);
+ if (selection === "checkbox")
+ harness.checkboxes[0]?.onCheckedChange?.(true);
+ else click(selection);
+ render(highRate);
+ expect(savedApplications()).toEqual([
+ expect.objectContaining({ appliedAmount: 0.01, sourceAmount: 160.01 })
+ ]);
+ });
+
+ it.each([
+ "checkbox",
+ "Auto apply"
+ ])("%s retains the final document cent even when its carrying base is zero", (selection) => {
+ const overrides = {
+ ...highRate,
+ availableCredit: 0.01,
+ priorSources: [
+ {
+ ...highRate.priorSources[0],
+ remainingDocument: 0.01,
+ remainingBase: 0
+ }
+ ],
+ openInvoices: [
+ { ...highRate.openInvoices[0], remainingDocument: 0.01, balance: 0 }
+ ]
+ };
+ render(overrides);
+ if (selection === "checkbox")
+ harness.checkboxes[0]?.onCheckedChange?.(true);
+ else click(selection);
+ render(overrides);
+ expect(savedApplications()).toEqual([
+ expect.objectContaining({ appliedAmount: 0, sourceAmount: 0.01 })
+ ]);
+ });
+
+ it("discount and write-off edits still reduce cash on an exact full selection", () => {
+ render();
+ harness.checkboxes[0]?.onCheckedChange?.(true);
+ render();
+ editAmount("Discount for INV1", 10);
+ render();
+ editAmount("Write-off for INV1", 5);
+ render();
+ expect(savedApplications()).toEqual([
+ expect.objectContaining({
+ appliedAmount: 85,
+ sourceAmount: 93.5,
+ discountAmount: 10,
+ writeOffAmount: 5
+ })
+ ]);
+ });
+
+ it("auto applies 170 EUR to invoices carrying 100 and 50 USD at distinct snapshots", () => {
+ render();
+ click("Auto apply");
+ const html = render();
+ expect(html).toContain("$100.00");
+ expect(html).toContain("$50.00");
+ expect(html).toContain("€110.00");
+ expect(html).toContain("€60.00");
+ click("Save applications");
+ const submitted = harness.submit.mock.calls[0][0] as FormData;
+ expect(JSON.parse(String(submitted.get("applications")))).toEqual([
+ expect.objectContaining({
+ targetSalesInvoiceId: "one",
+ appliedAmount: 100,
+ sourceAmount: 110,
+ targetExchangeRate: 1.1,
+ sourceExchangeRate: 1.2
+ }),
+ expect.objectContaining({
+ targetSalesInvoiceId: "two",
+ appliedAmount: 50,
+ sourceAmount: 60,
+ targetExchangeRate: 1.2,
+ sourceExchangeRate: 1.2
+ })
+ ]);
+ });
+ it("aggregates reopened funding splits into one invoice and resaves exact principal", () => {
+ const existingApplications = [
+ {
+ targetSalesInvoiceId: "one",
+ targetPurchaseInvoiceId: null,
+ appliedAmount: 40,
+ discountAmount: 0,
+ writeOffAmount: 0,
+ sourceAmount: 44,
+ sourcePaymentId: null,
+ targetExchangeRate: 1.1,
+ sourceExchangeRate: 1.2,
+ appliedDate: "2026-09-07"
+ },
+ {
+ targetSalesInvoiceId: "one",
+ targetPurchaseInvoiceId: null,
+ appliedAmount: 60,
+ discountAmount: 0,
+ writeOffAmount: 0,
+ sourceAmount: 66,
+ sourcePaymentId: "prior",
+ targetExchangeRate: 1.1,
+ sourceExchangeRate: 1.1,
+ appliedDate: "2026-09-07"
+ }
+ ];
+ const html = render({ existingApplications });
+ expect(html).toContain("$100.00");
+ click("Save applications");
+ const submitted = harness.submit.mock.calls[0][0] as FormData;
+ expect(JSON.parse(String(submitted.get("applications")))).toEqual([
+ expect.objectContaining({
+ appliedAmount: 100,
+ sourceAmount: 110,
+ sourceExchangeRate: 1.2
+ })
+ ]);
+ });
+ it("auto applies a prior document cent on a zero-cash draft even when base rounds to zero", () => {
+ const overrides = {
+ paymentTotal: 0,
+ paymentExchangeRate: 100000,
+ availableCredit: 0.01,
+ priorSources: [
+ {
+ paymentId: "prior",
+ postingDate: "2026-09-01",
+ exchangeRate: 100000,
+ remainingDocument: 0.01,
+ remainingBase: 0
+ }
+ ],
+ openInvoices: [
+ {
+ ...props.openInvoices[0],
+ exchangeRate: 100000,
+ totalAmount: 0.0000001,
+ balance: 0,
+ remainingDocument: 0.01
+ }
+ ]
+ };
+ render(overrides);
+ click("Auto apply");
+ render(overrides);
+ click("Save applications");
+ const submitted = harness.submit.mock.calls[0][0] as FormData;
+ expect(JSON.parse(String(submitted.get("applications")))).toEqual([
+ expect.objectContaining({ appliedAmount: 0, sourceAmount: 0.01 })
+ ]);
+ });
+});
+
+it("displays staged memo base and document amounts and retains a zero-base document cent", () => {
+ const html = renderToStaticMarkup(
+ createElement(AvailableCreditsTable, {
+ paymentId: "current",
+ side: "sales",
+ currency: "USD",
+ documentCurrency: "EUR",
+ documentDecimals: 2,
+ credits: [
+ {
+ id: "m",
+ memoId: "CM1",
+ direction: "Credit",
+ currencyCode: "EUR",
+ exchangeRate: 100000,
+ remaining: 0,
+ remainingDocument: 0.01
+ }
+ ],
+ openInvoices: [
+ {
+ id: "i",
+ invoiceId: "INV",
+ exchangeRate: 100000,
+ balance: 0,
+ remainingDocument: 0.01
+ }
+ ],
+ staged: [{ memoId: "m", invoiceId: "i", amount: 0, sourceAmount: 0.01 }]
+ })
+ );
+ expect(html).toContain("€0.01");
+ expect(html).toContain("$0.00");
+ click("Apply credits");
+ expect(
+ JSON.parse(
+ String((harness.submit.mock.calls[0][0] as FormData).get("applications"))
+ )
+ ).toEqual([{ memoId: "m", invoiceId: "i", amount: 0, sourceAmount: 0.01 }]);
+});
+it("payment history aggregates invoice splits and subtracts only current document cash from unapplied", () => {
+ const app = {
+ id: "a",
+ targetSalesInvoiceId: "one",
+ salesInvoice: { invoiceId: "INV1" },
+ appliedAmount: 40,
+ discountAmount: 0,
+ writeOffAmount: 0,
+ sourceAmount: 44,
+ sourcePaymentId: null,
+ targetExchangeRate: 1.1,
+ sourceExchangeRate: 1.2,
+ fxGainLossAmount: -3.33333,
+ appliedDate: "2026-09-07"
+ };
+ const html = renderToStaticMarkup(
+ createElement(PaymentApplications, {
+ paymentTotal: 44,
+ paymentCurrency: "EUR",
+ baseCurrency: "USD",
+ applications: [
+ app,
+ {
+ ...app,
+ id: "b",
+ appliedAmount: 60,
+ sourceAmount: 66,
+ sourcePaymentId: "prior",
+ sourceExchangeRate: 1.1,
+ fxGainLossAmount: 0
+ }
+ ] as any
+ })
+ );
+ expect(html.match(/INV1/g)).toHaveLength(1);
+ expect(html).toContain("$100.00");
+ expect(html).toContain("€0.00");
+ expect(html).toContain("€110.00");
+});
+
+const memoHighRateProps = {
+ paymentId: "current",
+ side: "sales" as const,
+ currency: "USD",
+ documentCurrency: "EUR",
+ documentDecimals: 2,
+ credits: [
+ {
+ id: "m",
+ memoId: "CM1",
+ direction: "Credit",
+ currencyCode: "EUR",
+ exchangeRate: 16000,
+ remaining: 0.01,
+ remainingDocument: 160.01
+ }
+ ],
+ openInvoices: [
+ {
+ id: "i",
+ invoiceId: "INV",
+ exchangeRate: 16000,
+ balance: 0.01,
+ remainingDocument: 160.01
+ }
+ ]
+};
+it.each([
+ false,
+ true
+])("manual memo base .01 preserves a document cent (reopened: %s)", (reopened) => {
+ const creditProps = {
+ ...memoHighRateProps,
+ staged: reopened
+ ? [{ memoId: "m", invoiceId: "i", amount: 0.01, sourceAmount: 160.01 }]
+ : []
+ };
+ renderToStaticMarkup(createElement(AvailableCreditsTable, creditProps));
+ expect(harness.amounts).toHaveLength(1);
+ harness.amounts[0]?.onChange?.(0.01);
+ harness.buttons = [];
+ renderToStaticMarkup(createElement(AvailableCreditsTable, creditProps));
+ click("Apply credits");
+ const submitted = harness.submit.mock.calls.at(-1)?.[0] as FormData;
+ expect(JSON.parse(String(submitted.get("applications")))).toEqual([
+ { memoId: "m", invoiceId: "i", amount: 0.01, sourceAmount: 160 }
+ ]);
+});
+it("full memo checkbox selection retains the exact document remainder", () => {
+ renderToStaticMarkup(createElement(AvailableCreditsTable, memoHighRateProps));
+ harness.checkboxes[0]?.onCheckedChange?.(true);
+ harness.buttons = [];
+ renderToStaticMarkup(createElement(AvailableCreditsTable, memoHighRateProps));
+ click("Apply credits");
+ const submitted = harness.submit.mock.calls.at(-1)?.[0] as FormData;
+ expect(JSON.parse(String(submitted.get("applications")))).toEqual([
+ { memoId: "m", invoiceId: "i", amount: 0.01, sourceAmount: 160.01 }
+ ]);
+});
+it("shows an empty state when every supplied invoice is filtered out", () => {
+ const html = render({
+ openInvoices: [
+ { ...props.openInvoices[0], currencyCode: "USD" },
+ { ...props.openInvoices[1], remainingDocument: 0 }
+ ]
+ });
+ expect(html).toContain("No open invoices");
+ expect(harness.amounts).toHaveLength(0);
+ const autoApply = harness.buttons.find((b) =>
+ renderToStaticMarkup(createElement("span", null, b.children)).includes(
+ "Auto apply"
+ )
+ );
+ expect(autoApply?.isDisabled).toBe(true);
+});
diff --git a/apps/erp/app/modules/invoicing/ui/Payment/PaymentApplyTable.tsx b/apps/erp/app/modules/invoicing/ui/Payment/PaymentApplyTable.tsx
index 8aa1db4251..a6ffe8016a 100644
--- a/apps/erp/app/modules/invoicing/ui/Payment/PaymentApplyTable.tsx
+++ b/apps/erp/app/modules/invoicing/ui/Payment/PaymentApplyTable.tsx
@@ -13,7 +13,15 @@ import {
NumberInput,
NumberInputGroup
} from "@carbon/react";
-import { EPSILON, INPUT_FORMAT, round } from "@carbon/utils";
+import {
+ allocatePaymentFunding,
+ EPSILON,
+ type FundingSource,
+ INPUT_FORMAT,
+ round,
+ toBaseAmount,
+ toDocumentAmount
+} from "@carbon/utils";
import { Trans, useLingui } from "@lingui/react/macro";
import type { CSSProperties } from "react";
import { useCallback, useMemo, useState } from "react";
@@ -21,6 +29,7 @@ import { LuListChecks, LuRotateCcw, LuSave } from "react-icons/lu";
import { useFetcher } from "react-router";
import { DateTime } from "~/components";
import {
+ useCompanyToday,
useCurrencyDecimals,
useCurrencyFormatter,
usePermissions
@@ -37,10 +46,14 @@ type OpenInvoice = {
exchangeRate: number;
totalAmount: number;
balance: number;
+ remainingDocument: number;
status: string | null;
};
type ExistingApplication = {
+ targetMemoId?: string | null;
+ sourceAmount: number | null;
+ sourcePaymentId?: string | null;
targetSalesInvoiceId: string | null;
targetPurchaseInvoiceId: string | null;
appliedAmount: number;
@@ -53,12 +66,14 @@ type ExistingApplication = {
// The invoice's read-only fields plus the editable selection state.
type ApplyRow = {
+ sourceAmount: number;
id: string;
invoiceId: string;
dateDue: string | null;
currencyCode: string;
exchangeRate: number;
balance: number;
+ remainingDocument: number;
checked: boolean;
appliedAmount: number;
discountAmount: number;
@@ -68,9 +83,13 @@ type ApplyRow = {
type AmountField = "appliedAmount" | "discountAmount" | "writeOffAmount";
type PaymentApplyTableProps = {
+ isRefund?: boolean;
paymentId: string;
paymentType: "Receipt" | "Disbursement";
paymentCurrency: string;
+ baseCurrency: string;
+ currencyDecimals: number;
+ priorSources: FundingSource[];
paymentTotal: number;
paymentExchangeRate: number;
// On-account credit (in payment currency) the counterparty can draw on when
@@ -83,6 +102,7 @@ type PaymentApplyTableProps = {
// Shared grid template so the header labels stay aligned with the rows. Wide
// enough to scroll horizontally on small screens rather than cramp the inputs.
const GRID = "grid grid-cols-[2rem_minmax(9rem,1fr)_7rem_8rem_8rem_8rem] gap-3";
+const REFUND_GRID = "grid grid-cols-[2rem_minmax(9rem,1fr)_7rem_8rem] gap-3";
// Compact, right-aligned numeric input for the editable amount cells.
const AmountInput = ({
@@ -115,9 +135,13 @@ const AmountInput = ({
);
const PaymentApplyTable = ({
+ isRefund = false,
paymentId,
paymentType,
paymentCurrency,
+ baseCurrency,
+ currencyDecimals,
+ priorSources,
paymentTotal,
paymentExchangeRate,
availableCredit,
@@ -128,49 +152,136 @@ const PaymentApplyTable = ({
const permissions = usePermissions();
const fetcher = useFetcher();
const currencyFormatter = useCurrencyFormatter({ currency: paymentCurrency });
- const currencyDecimals = useCurrencyDecimals(paymentCurrency);
- const today = new Date().toISOString().slice(0, 10);
+ const baseFormatter = useCurrencyFormatter({ currency: baseCurrency });
+ const baseDecimals = useCurrencyDecimals(baseCurrency);
+ const today = useCompanyToday().toString();
const isReceipt = paymentType === "Receipt";
+ const grid = isRefund ? REFUND_GRID : GRID;
const canEdit = permissions.can("update", "invoicing");
-
- // Seed rows from existing applications so users see what's already
- // applied when they reopen a Draft payment.
const seed = useMemo<ApplyRow[]>(() => {
- const byInvoice = new Map<string, ExistingApplication>();
+ const byInvoice = new Map<
+ string,
+ {
+ appliedAmount: number;
+ discountAmount: number;
+ writeOffAmount: number;
+ sourceAmount: number;
+ }
+ >();
for (const a of existingApplications) {
- const id = isReceipt ? a.targetSalesInvoiceId : a.targetPurchaseInvoiceId;
- if (id) byInvoice.set(id, a);
+ const id = isRefund
+ ? a.targetMemoId
+ : isReceipt
+ ? a.targetSalesInvoiceId
+ : a.targetPurchaseInvoiceId;
+ if (!id) continue;
+ const existing = byInvoice.get(id) ?? {
+ appliedAmount: 0,
+ discountAmount: 0,
+ writeOffAmount: 0,
+ sourceAmount: 0
+ };
+ existing.appliedAmount = round(existing.appliedAmount + a.appliedAmount);
+ existing.discountAmount = round(
+ existing.discountAmount + a.discountAmount
+ );
+ existing.writeOffAmount = round(
+ existing.writeOffAmount + a.writeOffAmount
+ );
+ existing.sourceAmount = toDocumentAmount(
+ existing.sourceAmount +
+ (a.sourceAmount ??
+ toDocumentAmount(
+ a.appliedAmount,
+ a.targetExchangeRate,
+ currencyDecimals
+ )),
+ 1,
+ currencyDecimals
+ );
+ byInvoice.set(id, existing);
}
- return openInvoices.map((inv) => {
- const existing = byInvoice.get(inv.id);
+ return openInvoices
+ .filter(
+ (inv) =>
+ inv.currencyCode === paymentCurrency && inv.remainingDocument > 0
+ )
+ .map((inv) => ({
+ ...inv,
+ checked: byInvoice.has(inv.id),
+ appliedAmount: 0,
+ discountAmount: 0,
+ writeOffAmount: 0,
+ sourceAmount: 0,
+ ...byInvoice.get(inv.id)
+ }));
+ }, [
+ openInvoices,
+ existingApplications,
+ isReceipt,
+ isRefund,
+ paymentCurrency,
+ currencyDecimals
+ ]);
+ const [rows, setRows] = useState<ApplyRow[]>(seed);
+ const currentPayment = useMemo(
+ () => ({
+ paymentId,
+ postingDate: today,
+ exchangeRate: paymentExchangeRate,
+ remainingDocument: paymentTotal,
+ remainingBase: toBaseAmount(paymentTotal, paymentExchangeRate)
+ }),
+ [paymentId, today, paymentExchangeRate, paymentTotal]
+ );
+ const preview = useMemo(() => {
+ try {
return {
- id: inv.id,
- invoiceId: inv.invoiceId,
- dateDue: inv.dateDue,
- currencyCode: inv.currencyCode,
- exchangeRate: inv.exchangeRate,
- balance: inv.balance,
- checked: Boolean(existing),
- appliedAmount: existing?.appliedAmount ?? 0,
- discountAmount: existing?.discountAmount ?? 0,
- writeOffAmount: existing?.writeOffAmount ?? 0
+ data: allocatePaymentFunding({
+ currentPayment,
+ priorSources,
+ currencyDecimals,
+ isAR: isReceipt,
+ requests: rows
+ .filter((r) => r.checked)
+ .map((r) => ({
+ targetId: r.id,
+ targetExchangeRate: r.exchangeRate,
+ remainingDocument: r.remainingDocument,
+ remainingBase: r.balance,
+ requestedDocumentPrincipal: r.sourceAmount,
+ discountAmount: r.discountAmount,
+ writeOffAmount: r.writeOffAmount
+ }))
+ }),
+ error: null
};
- });
- }, [openInvoices, existingApplications, isReceipt]);
-
- const [rows, setRows] = useState<ApplyRow[]>(seed);
-
- const totalCash = useMemo(
- () => rows.reduce((sum, r) => (r.checked ? sum + r.appliedAmount : sum), 0),
- [rows]
+ } catch (error) {
+ return {
+ data: null,
+ error: error instanceof Error ? error.message : t`Invalid applications`
+ };
+ }
+ }, [rows, currentPayment, priorSources, currencyDecimals, isReceipt, t]);
+ const totalCash = toDocumentAmount(
+ rows.reduce((sum, r) => sum + (r.checked ? r.sourceAmount : 0), 0),
+ 1,
+ currencyDecimals
+ );
+ const maxApplicable = toDocumentAmount(
+ paymentTotal + availableCredit,
+ 1,
+ currencyDecimals
);
- // The most this payment can apply is its own cash plus the counterparty's
- // available on-account credit; applying beyond cash draws that credit down.
- const maxApplicable = paymentTotal + availableCredit;
- const unapplied = paymentTotal - totalCash;
+ const unapplied =
+ preview.data?.newOnAccountDocument ?? Math.max(0, paymentTotal - totalCash);
const creditDraw = Math.max(
0,
- Math.min(availableCredit, totalCash - paymentTotal)
+ toDocumentAmount(
+ totalCash - (paymentTotal - unapplied),
+ 1,
+ currencyDecimals
+ )
);
// EPSILON, not a hand-picked 1e-4: every amount here is already rounded to
// internal scale, so the only slack needed is float noise. A 1e-4 band is
@@ -192,77 +303,159 @@ const PaymentApplyTable = ({
[rows]
);
const appliedPct =
- paymentTotal > 0
- ? Math.min(100, Math.max(0, (totalCash / paymentTotal) * 100))
+ maxApplicable > 0
+ ? Math.min(100, Math.max(0, (totalCash / maxApplicable) * 100))
: 0;
-
const toggleRow = useCallback(
(id: string, checked: boolean) =>
- setRows((prev) =>
- prev.map((r) => {
+ setRows((prev) => {
+ const available = Math.max(
+ 0,
+ toDocumentAmount(
+ maxApplicable -
+ prev.reduce(
+ (sum, r) =>
+ sum + (r.id !== id && r.checked ? r.sourceAmount : 0),
+ 0
+ ),
+ 1,
+ currencyDecimals
+ )
+ );
+ return prev.map((r) => {
if (r.id !== id) return r;
- // Checking an empty row auto-fills the applied amount with the
- // open balance (capped at the payment total). Unchecking zeroes it.
- if (checked) {
+ if (!checked)
return {
...r,
- checked: true,
- appliedAmount:
- r.appliedAmount === 0
- ? round(Math.min(r.balance, maxApplicable))
- : r.appliedAmount
+ checked: false,
+ sourceAmount: 0,
+ appliedAmount: 0,
+ discountAmount: 0,
+ writeOffAmount: 0
};
- }
+ const sourceAmount = Math.min(available, r.remainingDocument);
return {
...r,
- checked: false,
- appliedAmount: 0,
+ checked: true,
+ sourceAmount,
+ appliedAmount:
+ sourceAmount === r.remainingDocument
+ ? r.balance
+ : Math.min(
+ r.balance,
+ toBaseAmount(sourceAmount, r.exchangeRate)
+ ),
discountAmount: 0,
writeOffAmount: 0
};
- })
- ),
- [maxApplicable]
+ });
+ }),
+ [maxApplicable, currencyDecimals]
);
-
- // Entering any amount auto-checks the row so it's included on save (mirrors
- // the check-to-apply affordance).
const updateAmount = useCallback(
(id: string, field: AmountField, value: number) =>
setRows((prev) =>
prev.map((r) => {
if (r.id !== id) return r;
const next = { ...r, [field]: round(Math.max(0, value)) };
+ if (field === "appliedAmount")
+ next.sourceAmount = toDocumentAmount(
+ next.appliedAmount,
+ r.exchangeRate,
+ currencyDecimals
+ );
+ else if (
+ toDocumentAmount(
+ r.sourceAmount +
+ toDocumentAmount(
+ r.discountAmount + r.writeOffAmount,
+ r.exchangeRate,
+ currencyDecimals
+ ),
+ 1,
+ currencyDecimals
+ ) === r.remainingDocument
+ ) {
+ next.appliedAmount = Math.max(
+ 0,
+ round(r.balance - next.discountAmount - next.writeOffAmount)
+ );
+ next.sourceAmount = Math.max(
+ 0,
+ toDocumentAmount(
+ r.remainingDocument -
+ toDocumentAmount(
+ next.discountAmount + next.writeOffAmount,
+ r.exchangeRate,
+ currencyDecimals
+ ),
+ 1,
+ currencyDecimals
+ )
+ );
+ }
next.checked =
- next.appliedAmount + next.discountAmount + next.writeOffAmount > 0;
+ next.sourceAmount + next.discountAmount + next.writeOffAmount > 0;
return next;
})
),
- []
+ [currencyDecimals]
+ );
+ const onAutoApply = useCallback(
+ () =>
+ setRows((prev) => {
+ let remaining = maxApplicable;
+ const requests = prev.map((r) => {
+ const sourceAmount = Math.min(remaining, r.remainingDocument);
+ remaining = toDocumentAmount(
+ remaining - sourceAmount,
+ 1,
+ currencyDecimals
+ );
+ return {
+ targetId: r.id,
+ targetExchangeRate: r.exchangeRate,
+ remainingDocument: r.remainingDocument,
+ remainingBase: r.balance,
+ requestedDocumentPrincipal: sourceAmount,
+ discountAmount: 0,
+ writeOffAmount: 0
+ };
+ });
+ const result = allocatePaymentFunding({
+ currentPayment,
+ priorSources,
+ requests,
+ currencyDecimals,
+ isAR: isReceipt
+ });
+ return prev.map((r) => {
+ const apps = result.applications.filter((a) => a.targetId === r.id);
+ return {
+ ...r,
+ checked: apps.length > 0,
+ sourceAmount: toDocumentAmount(
+ apps.reduce((sum, a) => sum + a.sourceAmount, 0),
+ 1,
+ currencyDecimals
+ ),
+ appliedAmount: round(
+ apps.reduce((sum, a) => sum + a.appliedAmount, 0)
+ ),
+ discountAmount: 0,
+ writeOffAmount: 0
+ };
+ });
+ }),
+ [maxApplicable, currentPayment, priorSources, currencyDecimals, isReceipt]
);
-
- const onAutoApply = useCallback(() => {
- // Distribute payment cash oldest-first (openInvoices is already sorted by
- // dateDue ascending from the loader).
- let remaining = paymentTotal;
- setRows((prev) =>
- prev.map((r) => {
- if (remaining <= 0) {
- return { ...r, checked: false, appliedAmount: 0 };
- }
- const take = Math.min(remaining, r.balance);
- remaining = round(remaining - take);
- return { ...r, checked: true, appliedAmount: round(take) };
- })
- );
- }, [paymentTotal]);
-
const onClear = useCallback(
() =>
setRows((prev) =>
prev.map((r) => ({
...r,
checked: false,
+ sourceAmount: 0,
appliedAmount: 0,
discountAmount: 0,
writeOffAmount: 0
@@ -270,24 +463,25 @@ const PaymentApplyTable = ({
),
[]
);
-
const onSave = () => {
+ if (preview.error) return;
const applications = rows
.filter(
(r) =>
- r.checked && r.appliedAmount + r.discountAmount + r.writeOffAmount > 0
+ r.checked && r.sourceAmount + r.discountAmount + r.writeOffAmount > 0
)
.map((r) => ({
- targetSalesInvoiceId: isReceipt ? r.id : undefined,
- targetPurchaseInvoiceId: isReceipt ? undefined : r.id,
+ targetSalesInvoiceId: !isRefund && isReceipt ? r.id : undefined,
+ targetPurchaseInvoiceId: !isRefund && !isReceipt ? r.id : undefined,
+ targetMemoId: isRefund ? r.id : undefined,
appliedAmount: r.appliedAmount,
+ sourceAmount: r.sourceAmount,
discountAmount: r.discountAmount,
writeOffAmount: r.writeOffAmount,
- targetExchangeRate: r.exchangeRate || 1,
- sourceExchangeRate: paymentExchangeRate || 1,
+ targetExchangeRate: r.exchangeRate,
+ sourceExchangeRate: paymentExchangeRate,
appliedDate: today
}));
-
const formData = new FormData();
formData.set("applications", JSON.stringify(applications));
fetcher.submit(formData, {
@@ -304,13 +498,23 @@ const PaymentApplyTable = ({
<HStack className="justify-between w-full">
<div>
<CardTitle>
- <Trans>Apply to invoices</Trans>
+ {isRefund ? (
+ <Trans>Refund memos</Trans>
+ ) : (
+ <Trans>Apply to invoices</Trans>
+ )}
</CardTitle>
<CardDescription>
- <Trans>
- Select the invoices this payment settles. Discount and write-off
- are in invoice currency.
- </Trans>
+ {isRefund ? (
+ <Trans>
+ Applied amounts are in company base currency ({baseCurrency}).
+ </Trans>
+ ) : (
+ <Trans>
+ Applied, discount and write-off amounts are in company base
+ currency ({baseCurrency}).
+ </Trans>
+ )}
</CardDescription>
</div>
<HStack>
@@ -319,7 +523,7 @@ const PaymentApplyTable = ({
variant="secondary"
leftIcon={<LuListChecks />}
onClick={onAutoApply}
- isDisabled={!canEdit || openInvoices.length === 0}
+ isDisabled={!canEdit || rows.length === 0}
>
<Trans>Auto apply</Trans>
</Button>
@@ -336,10 +540,14 @@ const PaymentApplyTable = ({
</HStack>
</CardHeader>
<CardContent>
- {openInvoices.length === 0 ? (
+ {rows.length === 0 ? (
<div className="rounded-lg border border-dashed border-border py-10 px-6 text-center">
<p className="text-sm font-medium text-foreground">
- <Trans>No open invoices</Trans>
+ {isRefund ? (
+ <Trans>No open memos</Trans>
+ ) : (
+ <Trans>No open invoices</Trans>
+ )}
</p>
<p className="text-sm text-muted-foreground mt-1 text-pretty">
<Trans>
@@ -352,11 +560,11 @@ const PaymentApplyTable = ({
<div className="overflow-x-auto">
<div className="min-w-[44rem]">
<div
- className={cn(GRID, "px-2 pb-2 text-xs text-muted-foreground")}
+ className={cn(grid, "px-2 pb-2 text-xs text-muted-foreground")}
>
<span aria-hidden />
<span>
- <Trans>Invoice</Trans>
+ {isRefund ? <Trans>Memo</Trans> : <Trans>Invoice</Trans>}
</span>
<span className="text-right">
<Trans>Open</Trans>
@@ -364,19 +572,23 @@ const PaymentApplyTable = ({
<span className="text-right">
<Trans>Applied</Trans>
</span>
- <span className="text-right">
- <Trans>Discount</Trans>
- </span>
- <span className="text-right">
- <Trans>Write-off</Trans>
- </span>
+ {!isRefund && (
+ <>
+ <span className="text-right">
+ <Trans>Discount</Trans>
+ </span>
+ <span className="text-right">
+ <Trans>Write-off</Trans>
+ </span>
+ </>
+ )}
</div>
<div className="border-t border-border/70 divide-y divide-border/70">
{rows.map((r) => (
<div
key={r.id}
className={cn(
- GRID,
+ grid,
"items-center px-2 py-2 transition-colors",
r.checked ? "bg-muted/50" : "hover:bg-muted/30"
)}
@@ -405,32 +617,43 @@ const PaymentApplyTable = ({
</div>
</div>
<div className="text-right tabular-nums text-sm text-muted-foreground self-center">
- {currencyFormatter.format(Number(r.balance))}
+ {baseFormatter.format(Number(r.balance))}
+ <div className="text-xs">
+ {currencyFormatter.format(r.remainingDocument)}
+ </div>
</div>
<AmountInput
label={t`Applied amount for ${r.invoiceId}`}
value={r.appliedAmount}
isDisabled={!canEdit}
- currency={paymentCurrency}
- currencyDecimals={currencyDecimals}
+ currency={baseCurrency}
+ currencyDecimals={baseDecimals}
onChange={(v) => updateAmount(r.id, "appliedAmount", v)}
/>
- <AmountInput
- label={t`Discount for ${r.invoiceId}`}
- value={r.discountAmount}
- isDisabled={!canEdit}
- currency={paymentCurrency}
- currencyDecimals={currencyDecimals}
- onChange={(v) => updateAmount(r.id, "discountAmount", v)}
- />
- <AmountInput
- label={t`Write-off for ${r.invoiceId}`}
- value={r.writeOffAmount}
- isDisabled={!canEdit}
- currency={paymentCurrency}
- currencyDecimals={currencyDecimals}
- onChange={(v) => updateAmount(r.id, "writeOffAmount", v)}
- />
+ {!isRefund && (
+ <>
+ <AmountInput
+ label={t`Discount for ${r.invoiceId}`}
+ value={r.discountAmount}
+ isDisabled={!canEdit}
+ currency={baseCurrency}
+ currencyDecimals={baseDecimals}
+ onChange={(v) =>
+ updateAmount(r.id, "discountAmount", v)
+ }
+ />
+ <AmountInput
+ label={t`Write-off for ${r.invoiceId}`}
+ value={r.writeOffAmount}
+ isDisabled={!canEdit}
+ currency={baseCurrency}
+ currencyDecimals={baseDecimals}
+ onChange={(v) =>
+ updateAmount(r.id, "writeOffAmount", v)
+ }
+ />
+ </>
+ )}
</div>
))}
</div>
@@ -439,7 +662,7 @@ const PaymentApplyTable = ({
)}
</CardContent>
<CardFooter className="flex-col items-stretch gap-4">
- {openInvoices.length > 0 ? (
+ {rows.length > 0 ? (
<div className="w-full">
<div className="flex items-baseline justify-between text-sm">
<span className="text-muted-foreground">
@@ -469,7 +692,7 @@ const PaymentApplyTable = ({
style={{ "--applied": `${appliedPct}%` } as CSSProperties}
/>
</div>
- {availableCredit > 0.0001 ? (
+ {availableCredit > 0 ? (
<div className="mt-2 flex items-baseline justify-between text-xs text-muted-foreground">
<span>
<Trans>On-account credit available</Trans>
@@ -481,6 +704,9 @@ const PaymentApplyTable = ({
) : null}
</div>
) : null}
+ {preview.error ? (
+ <p className="text-sm text-destructive">{preview.error}</p>
+ ) : null}
<HStack className="justify-between w-full">
<span className="text-sm">
{overSettled ? (
@@ -494,7 +720,7 @@ const PaymentApplyTable = ({
<Trans>Over-applied by</Trans>{" "}
{currencyFormatter.format(totalCash - maxApplicable)}
</span>
- ) : creditDraw > 0.0001 ? (
+ ) : creditDraw > 0 ? (
<span className="text-muted-foreground">
<Trans>Drawing</Trans>{" "}
<span className="tabular-nums font-medium text-foreground">
@@ -515,7 +741,9 @@ const PaymentApplyTable = ({
leftIcon={<LuSave />}
onClick={onSave}
isLoading={isSaving}
- isDisabled={!canEdit || overApplied || overSettled}
+ isDisabled={
+ !canEdit || overApplied || overSettled || Boolean(preview.error)
+ }
>
<Trans>Save applications</Trans>
</Button>
diff --git a/apps/erp/app/modules/invoicing/ui/Payment/PaymentForm.test.tsx b/apps/erp/app/modules/invoicing/ui/Payment/PaymentForm.test.tsx
new file mode 100644
index 0000000000..2e834cbdc2
--- /dev/null
+++ b/apps/erp/app/modules/invoicing/ui/Payment/PaymentForm.test.tsx
@@ -0,0 +1,246 @@
+import type { ComponentProps, ReactNode } from "react";
+import { createElement } from "react";
+import { renderToStaticMarkup } from "react-dom/server";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const harness = vi.hoisted(() => ({
+ states: [] as unknown[],
+ stateIndex: 0,
+ values: {} as Record<string, unknown>,
+ typeChange: undefined as
+ | ((option: { value: string; label: string }) => void)
+ | undefined,
+ currencyChange: undefined as
+ | ((option: { value: string; label: string }) => void)
+ | undefined,
+ currencies: [
+ { code: "USD", name: "US Dollar", decimalPlaces: 2 },
+ { code: "EUR", name: "Euro", decimalPlaces: 2 },
+ { code: "JPY", name: "Japanese Yen", decimalPlaces: 0 },
+ { code: "BHD", name: "Bahraini Dinar", decimalPlaces: 3 }
+ ]
+}));
+
+// Match the neighboring server-rendered composer tests while retaining each
+// PaymentForm state slot between renders to exercise selector callbacks.
+vi.mock("react", async (importOriginal) => {
+ const react = await importOriginal<typeof import("react")>();
+ return {
+ ...react,
+ useState: (seed: unknown) => {
+ const index = harness.stateIndex++;
+ if (!(index in harness.states))
+ harness.states[index] = typeof seed === "function" ? seed() : seed;
+ return [
+ harness.states[index],
+ (value: unknown) => {
+ harness.states[index] =
+ typeof value === "function" ? value(harness.states[index]) : value;
+ }
+ ];
+ }
+ };
+});
+vi.mock("@carbon/react", () => {
+ const Box = ({ children }: { children?: ReactNode }) =>
+ createElement("div", null, children);
+ return {
+ Button: Box,
+ Card: Box,
+ CardContent: Box,
+ CardDescription: Box,
+ CardFooter: Box,
+ CardHeader: Box,
+ CardTitle: Box,
+ DropdownMenuIcon: Box,
+ DropdownMenuItem: Box,
+ Status: Box,
+ VStack: Box,
+ useDisclosure: () => ({ isOpen: false }),
+ useMount: () => undefined
+ };
+});
+vi.mock("@carbon/form", () => ({
+ ValidatedForm: ({
+ children,
+ defaultValues
+ }: {
+ children: ReactNode;
+ defaultValues: Record<string, unknown>;
+ }) => {
+ harness.values = defaultValues;
+ return createElement("form", null, children);
+ }
+}));
+vi.mock("~/components/Form", () => {
+ const Field = () => null;
+ return {
+ Account: Field,
+ Customer: () => createElement("input", { name: "customerId" }),
+ CustomFormFields: Field,
+ DatePicker: Field,
+ Hidden: ({ name, value }: { name: string; value?: string }) =>
+ createElement("input", { type: "hidden", name, value, readOnly: true }),
+ Input: Field,
+ Select: Field,
+ SelectControlled: ({
+ options,
+ onChange
+ }: {
+ options: { label: string; value: string }[];
+ onChange: typeof harness.typeChange;
+ }) => {
+ harness.typeChange = onChange;
+ return createElement(
+ "select",
+ null,
+ options.map((o) =>
+ createElement("option", { key: o.value, value: o.value }, o.label)
+ )
+ );
+ },
+ SequenceOrCustomId: Field,
+ Submit: Field,
+ Supplier: () => createElement("input", { name: "supplierId" }),
+ TextArea: Field,
+ Currency: ({ onChange }: { onChange?: typeof harness.currencyChange }) => {
+ harness.currencyChange = onChange;
+ return null;
+ },
+ Number: ({
+ name,
+ label,
+ formatOptions
+ }: {
+ name: string;
+ label: string;
+ formatOptions: Intl.NumberFormatOptions;
+ }) =>
+ createElement("input", {
+ name,
+ "aria-label": label,
+ readOnly: true,
+ value: new Intl.NumberFormat("en-US", formatOptions).format(
+ Number(harness.values[name])
+ )
+ })
+ };
+});
+vi.mock("@lingui/react/macro", () => ({
+ Trans: ({ children }: { children: ReactNode }) => children,
+ useLingui: () => ({
+ t: (parts: TemplateStringsArray, ...values: unknown[]) =>
+ parts.reduce(
+ (result, part, index) => result + part + (values[index] ?? ""),
+ ""
+ )
+ })
+}));
+vi.mock("react-router", () => ({
+ generatePath: (path: string) => path,
+ useFetcher: () => ({ state: "idle", data: { data: harness.currencies } })
+}));
+vi.mock("~/components", () => ({ DocumentHeader: () => null }));
+vi.mock("~/components/Enumerable", () => ({ Enumerable: () => null }));
+vi.mock("~/components/Modals", () => ({ ConfirmDelete: () => null }));
+vi.mock("~/hooks/useCompanySettings", () => ({
+ useCompanySettings: () => ({ showCurrencyTrailingZeros: true })
+}));
+vi.mock("~/hooks", async () => {
+ const { useCurrencyDecimals } = await import("~/hooks/useCurrencies");
+ return {
+ useCurrencyDecimals,
+ usePermissions: () => ({ can: () => true }),
+ useUser: () => ({ company: { baseCurrencyCode: "USD" } })
+ };
+});
+vi.mock("~/modules/invoicing", () => import("../../invoicing.models"));
+
+import PaymentForm from "./PaymentForm";
+
+const initialValues: ComponentProps<typeof PaymentForm>["initialValues"] = {
+ paymentType: "Receipt",
+ customerId: "customer",
+ paymentDate: "2026-09-08",
+ currencyCode: "EUR",
+ exchangeRate: 0.8,
+ totalAmount: 120.8,
+ bankAccount: "bank"
+};
+
+function render(values = initialValues) {
+ harness.stateIndex = 0;
+ return renderToStaticMarkup(
+ createElement(PaymentForm, { initialValues: values })
+ );
+}
+
+beforeEach(() => {
+ harness.states = [];
+ harness.stateIndex = 0;
+ harness.currencyChange = undefined;
+ harness.typeChange = undefined;
+});
+
+describe("PaymentForm refund directions", () => {
+ it("seeds the visible payment kind in the form's registered defaults", () => {
+ render();
+ expect(harness.values.paymentKind).toBe("customer-payment");
+ });
+ it.each([
+ ["customer-refund", "Disbursement", "customerId", "supplierId"],
+ ["supplier-refund", "Receipt", "supplierId", "customerId"]
+ ])("offers %s and submits its cash direction with one party", (kind, direction, party, otherParty) => {
+ const html = render();
+ expect(html).toContain("Refund to Customer");
+ expect(html).toContain("Refund from Supplier");
+ harness.typeChange?.({ value: kind, label: kind });
+ const next = render();
+ expect(next).toContain(
+ `name="paymentType" readonly="" value="${direction}"`
+ );
+ expect(next).toContain(`name="${party}"`);
+ expect(next).toContain(`name="${otherParty}" readonly="" value=""`);
+ });
+});
+
+describe("PaymentForm document currency", () => {
+ it.each([
+ undefined,
+ "payment-id"
+ ])("labels document cash in EUR for payment id %s while the company uses USD", (id) => {
+ const html = render({ ...initialValues, id, status: "Draft" });
+ expect(html).toContain(
+ 'aria-label="Total Amount" readonly="" value="€120.80"'
+ );
+ expect(html).not.toContain("$120.80");
+ });
+
+ it.each([
+ ["JPY", 123, "¥123"],
+ ["BHD", 123.456, "BHD 123.456"]
+ ] as const)("uses %s document settlement precision", (currencyCode, totalAmount, formatted) => {
+ expect(render({ ...initialValues, currencyCode, totalAmount })).toContain(
+ `aria-label="Total Amount" readonly="" value="${formatted}"`
+ );
+ });
+
+ it.each([
+ undefined,
+ "payment-id"
+ ])("updates currency and decimal precision after selection for payment id %s", (id) => {
+ const values = {
+ ...initialValues,
+ id,
+ status: "Draft",
+ totalAmount: 123.456
+ };
+ render(values);
+ harness.currencyChange?.({ value: "BHD", label: "Bahraini Dinar" });
+ expect(render(values)).toContain('value="BHD 123.456"');
+ harness.currencyChange?.({ value: "JPY", label: "Japanese Yen" });
+ expect(render(values)).toContain('value="¥123"');
+ harness.currencyChange?.({ value: "EUR", label: "Euro" });
+ expect(render(values)).toContain('value="€123.46"');
+ });
+});
diff --git a/apps/erp/app/modules/invoicing/ui/Payment/PaymentForm.tsx b/apps/erp/app/modules/invoicing/ui/Payment/PaymentForm.tsx
index bc73ca9d4d..2ffb656569 100644
--- a/apps/erp/app/modules/invoicing/ui/Payment/PaymentForm.tsx
+++ b/apps/erp/app/modules/invoicing/ui/Payment/PaymentForm.tsx
@@ -29,7 +29,7 @@ import {
Hidden,
Input,
Number,
- Select,
+ SelectControlled,
SequenceOrCustomId,
Submit,
Supplier,
@@ -37,11 +37,7 @@ import {
} from "~/components/Form";
import { ConfirmDelete } from "~/components/Modals";
import { useCurrencyDecimals, usePermissions, useUser } from "~/hooks";
-import {
- isPaymentLocked,
- paymentType,
- paymentValidator
-} from "~/modules/invoicing";
+import { isPaymentLocked, paymentValidator } from "~/modules/invoicing";
import { path } from "~/utils/path";
import PaymentStatus from "./PaymentStatus";
@@ -91,12 +87,12 @@ type PaymentFormProps = {
const PaymentForm = ({ initialValues, seedInvoiceIds }: PaymentFormProps) => {
const { t } = useLingui();
const { company } = useUser();
- const currencyDecimals = useCurrencyDecimals(
- company?.baseCurrencyCode ?? "USD"
+ const [currencyCode, setCurrencyCode] = useState(
+ initialValues.currencyCode || company?.baseCurrencyCode || "USD"
);
+ const currencyDecimals = useCurrencyDecimals(currencyCode);
const permissions = usePermissions();
const post = useFetcher();
- const voidFetcher = useFetcher();
const isEditing = Boolean(initialValues.id);
const status = initialValues.status as
| "Draft"
@@ -107,24 +103,36 @@ const PaymentForm = ({ initialValues, seedInvoiceIds }: PaymentFormProps) => {
const canMutate = permissions.can("update", "invoicing");
const canDelete = permissions.can("delete", "invoicing");
const deleteModal = useDisclosure();
+ const voidModal = useDisclosure();
- // The counterparty selector visibility tracks paymentType so users
- // see Customer for Receipts and Supplier for Disbursements.
- const [currentType, setCurrentType] = useState<"Receipt" | "Disbursement">(
- initialValues.paymentType ?? "Receipt"
- );
-
- const typeOptions = paymentType.map((t) => ({
- label: t === "Receipt" ? "Payment from Customer" : "Payment to Supplier",
- value: t
- }));
+ // Cash direction and subledger party are independent for refunds.
+ const initialKind = initialValues.supplierId
+ ? initialValues.paymentType === "Receipt"
+ ? "supplier-refund"
+ : "supplier-payment"
+ : initialValues.paymentType === "Disbursement"
+ ? "customer-refund"
+ : "customer-payment";
+ const [paymentKind, setPaymentKind] = useState(initialKind);
+ const defaultValues = { ...initialValues, paymentKind: initialKind };
+ const isCustomer = paymentKind.startsWith("customer-");
+ const currentType =
+ paymentKind === "customer-payment" || paymentKind === "supplier-refund"
+ ? "Receipt"
+ : "Disbursement";
+ const typeOptions = [
+ { label: t`Payment from Customer`, value: "customer-payment" },
+ { label: t`Payment to Supplier`, value: "supplier-payment" },
+ { label: t`Refund to Customer`, value: "customer-refund" },
+ { label: t`Refund from Supplier`, value: "supplier-refund" }
+ ];
return (
<>
<ValidatedForm
method="post"
validator={paymentValidator}
- defaultValues={initialValues}
+ defaultValues={defaultValues}
isDisabled={isEditing && isLocked}
className="w-full"
>
@@ -166,14 +174,9 @@ const PaymentForm = ({ initialValues, seedInvoiceIds }: PaymentFormProps) => {
<Button
leftIcon={<LuTicketX />}
variant="destructive"
- isLoading={voidFetcher.state !== "idle"}
+ type="button"
isDisabled={!canMutate}
- onClick={() =>
- voidFetcher.submit(null, {
- method: "post",
- action: path.to.paymentVoid(initialValues.id!)
- })
- }
+ onClick={voidModal.onOpen}
>
<Trans>Void</Trans>
</Button>
@@ -187,15 +190,17 @@ const PaymentForm = ({ initialValues, seedInvoiceIds }: PaymentFormProps) => {
</CardTitle>
<CardDescription>
<Trans>
- Record cash received from a customer (Receipt) or paid to a
- supplier (Disbursement). Applications to specific invoices are
- added after the payment is created.
+ Record a customer payment, supplier payment, or refund.
+ Applications to invoices or memos are added after the payment
+ is created.
</Trans>
</CardDescription>
</CardHeader>
)}
<CardContent>
<Hidden name="id" />
+ <Hidden name="paymentType" value={currentType} />
+ <Hidden name={isCustomer ? "supplierId" : "customerId"} value="" />
{isEditing && <Hidden name="paymentId" />}
{seedInvoiceIds && seedInvoiceIds.length > 0 && (
<Hidden name="seedInvoiceIds" value={seedInvoiceIds.join(",")} />
@@ -209,26 +214,28 @@ const PaymentForm = ({ initialValues, seedInvoiceIds }: PaymentFormProps) => {
table="payment"
/>
)}
- <Select
- name="paymentType"
+ <SelectControlled
+ name="paymentKind"
label={t`Type`}
options={typeOptions}
+ value={paymentKind}
onChange={(opt) => {
- if (
- opt?.value === "Receipt" ||
- opt?.value === "Disbursement"
- ) {
- setCurrentType(opt.value);
- }
+ if (opt) setPaymentKind(opt.value);
}}
/>
- {currentType === "Receipt" ? (
+ {isCustomer ? (
<Customer name="customerId" label={t`Customer`} />
) : (
<Supplier name="supplierId" label={t`Supplier`} />
)}
<DatePicker name="paymentDate" label={t`Payment Date`} />
- <Currency name="currencyCode" label={t`Currency`} />
+ <Currency
+ name="currencyCode"
+ label={t`Currency`}
+ onChange={(option) => {
+ if (option) setCurrencyCode(option.value);
+ }}
+ />
<Number
name="exchangeRate"
label={t`Exchange Rate`}
@@ -239,7 +246,7 @@ const PaymentForm = ({ initialValues, seedInvoiceIds }: PaymentFormProps) => {
name="totalAmount"
label={t`Total Amount`}
formatOptions={INPUT_FORMAT.money(
- company?.baseCurrencyCode ?? "USD",
+ currencyCode,
currencyDecimals
)}
/>
@@ -269,6 +276,17 @@ const PaymentForm = ({ initialValues, seedInvoiceIds }: PaymentFormProps) => {
</CardFooter>
</Card>
</ValidatedForm>
+ {voidModal.isOpen && (
+ <ConfirmDelete
+ action={path.to.paymentVoid(initialValues.id!)}
+ name={initialValues.paymentId ?? ""}
+ title={t`Void ${initialValues.paymentId}`}
+ text={t`Are you sure you want to void this payment? This will reverse its accounting entries and applications. This cannot be undone.`}
+ deleteText={t`Void`}
+ onCancel={voidModal.onClose}
+ onSubmit={voidModal.onClose}
+ />
+ )}
{deleteModal.isOpen && (
<ConfirmDelete
action={path.to.paymentDelete(initialValues.id!)}
diff --git a/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceExplorer.tsx b/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceExplorer.tsx
index 342ecdea48..428c03d9f3 100644
--- a/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceExplorer.tsx
+++ b/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceExplorer.tsx
@@ -333,7 +333,6 @@ function PurchaseInvoiceLineItem({
<HStack
className={cn(
"group w-full p-2 items-center hover:bg-accent/30 cursor-pointer relative",
- "border-b border-border",
isSelected && "bg-accent/60 hover:bg-accent/50"
)}
>
diff --git a/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoicePostModal.tsx b/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoicePostModal.tsx
index fd77239316..14085a582a 100644
--- a/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoicePostModal.tsx
+++ b/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoicePostModal.tsx
@@ -92,7 +92,7 @@ const PurchaseInvoicePostModal = ({
<div className="gap-4 w-full flex flex-col">
{hasTrackedItems ? (
<>
- <p>
+ <p className="text-sm text-muted-foreground">
Are you sure you want to post this invoice? A receipt will
be created for:
</p>
@@ -109,7 +109,7 @@ const PurchaseInvoicePostModal = ({
</Alert>
</>
) : (
- <p>
+ <p className="text-sm text-muted-foreground">
Are you sure you want to post this invoice? A receipt will be
automatically created and posted for:
</p>
@@ -145,7 +145,9 @@ const PurchaseInvoicePostModal = ({
</Table>
</div>
) : (
- <p>Are you sure you want to post this invoice?</p>
+ <p className="text-sm text-muted-foreground">
+ Are you sure you want to post this invoice?
+ </p>
)}
</ModalBody>
<ModalFooter>
diff --git a/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceExplorer.tsx b/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceExplorer.tsx
index d1039ac6c5..d6ad8a00e6 100644
--- a/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceExplorer.tsx
+++ b/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceExplorer.tsx
@@ -286,7 +286,6 @@ function SalesInvoiceLineItem({
<HStack
className={cn(
"group w-full p-2 items-center hover:bg-accent/30 cursor-pointer relative",
- "border-b border-border",
isSelected && "bg-accent/60 hover:bg-accent/50"
)}
>
diff --git a/apps/erp/app/modules/invoicing/ui/useInvoicingSubmodules.tsx b/apps/erp/app/modules/invoicing/ui/useInvoicingSubmodules.tsx
index b0ae81fd68..528d2b49f3 100644
--- a/apps/erp/app/modules/invoicing/ui/useInvoicingSubmodules.tsx
+++ b/apps/erp/app/modules/invoicing/ui/useInvoicingSubmodules.tsx
@@ -25,7 +25,7 @@ export default function useInvoicingSubmodules() {
permission: "invoicing"
},
{
- name: t`Purchasing Invoices`,
+ name: t`Purchase Invoices`,
to: path.to.invoicingPurchasing,
icon: <LuReceiptText />,
table: "purchaseInvoice",
diff --git a/apps/erp/app/modules/items/ui/Item/PickMethodForm.tsx b/apps/erp/app/modules/items/ui/Item/PickMethodForm.tsx
index f726be9318..391307b7c4 100644
--- a/apps/erp/app/modules/items/ui/Item/PickMethodForm.tsx
+++ b/apps/erp/app/modules/items/ui/Item/PickMethodForm.tsx
@@ -164,7 +164,7 @@ const PickMethodForm = ({
<IconButton
aria-label={t`Inventory actions`}
icon={<LuEllipsisVertical />}
- size="sm"
+ size="md"
variant="secondary"
/>
</DropdownMenuTrigger>
diff --git a/apps/erp/app/modules/production/ui/DemandProjection/DemandProjectionForm.tsx b/apps/erp/app/modules/production/ui/DemandProjection/DemandProjectionForm.tsx
index 0dde9e2fb6..5617268491 100644
--- a/apps/erp/app/modules/production/ui/DemandProjection/DemandProjectionForm.tsx
+++ b/apps/erp/app/modules/production/ui/DemandProjection/DemandProjectionForm.tsx
@@ -17,7 +17,6 @@ import {
import type { ChartConfig } from "@carbon/react/Chart";
import { ChartContainer, ChartTooltip } from "@carbon/react/Chart";
import { getLocalTimeZone, startOfWeek, today } from "@internationalized/date";
-import { msg } from "@lingui/core/macro";
import { useLingui } from "@lingui/react/macro";
import { useNumberFormatter } from "@react-aria/i18n";
import { memo, useDeferredValue, useEffect, useMemo, useState } from "react";
@@ -96,7 +95,7 @@ const DemandProjectionsForm = ({
month: "numeric",
day: "numeric"
});
- return i18n._(msg`Week ${i + 1} (${formattedDate})`);
+ return t`Week ${i + 1} (${formattedDate})`;
});
// Local mirror of the 52 week inputs, seeded from initialValues, that drives
diff --git a/apps/erp/app/modules/production/ui/Jobs/ProductionEventForm.tsx b/apps/erp/app/modules/production/ui/Jobs/ProductionEventForm.tsx
index 4616b1545a..a34ce80547 100644
--- a/apps/erp/app/modules/production/ui/Jobs/ProductionEventForm.tsx
+++ b/apps/erp/app/modules/production/ui/Jobs/ProductionEventForm.tsx
@@ -16,7 +16,6 @@ import {
parseAbsolute,
toCalendarDateTime
} from "@internationalized/date";
-import { msg } from "@lingui/core/macro";
import { Trans, useLingui } from "@lingui/react/macro";
import { useState } from "react";
import { useNavigate } from "react-router";
@@ -47,13 +46,13 @@ const ProductionEventForm = ({
operationOptions
}: ProductionEventFormProps) => {
const permissions = usePermissions();
- const { t, i18n } = useLingui();
+ const { t } = useLingui();
const navigate = useNavigate();
const eventTypeOptions = [
- { label: i18n._(msg`Labor`), value: "Labor" },
- { label: i18n._(msg`Machine`), value: "Machine" },
- { label: i18n._(msg`Setup`), value: "Setup" }
+ { label: t`Labor`, value: "Labor" },
+ { label: t`Machine`, value: "Machine" },
+ { label: t`Setup`, value: "Setup" }
];
const onClose = () => navigate(-1);
diff --git a/apps/erp/app/modules/production/ui/Jobs/ProductionQuantityForm.tsx b/apps/erp/app/modules/production/ui/Jobs/ProductionQuantityForm.tsx
index bf98115a38..c54e086696 100644
--- a/apps/erp/app/modules/production/ui/Jobs/ProductionQuantityForm.tsx
+++ b/apps/erp/app/modules/production/ui/Jobs/ProductionQuantityForm.tsx
@@ -10,7 +10,6 @@ import {
HStack,
VStack
} from "@carbon/react";
-import { msg } from "@lingui/core/macro";
import { Trans, useLingui } from "@lingui/react/macro";
import { useState } from "react";
import { useNavigate } from "react-router";
@@ -41,7 +40,7 @@ const ProductionQuantityForm = ({
operationOptions
}: ProductionQuantityFormProps) => {
const permissions = usePermissions();
- const { t, i18n } = useLingui();
+ const { t } = useLingui();
const navigate = useNavigate();
const onClose = () => navigate(-1);
@@ -50,9 +49,9 @@ const ProductionQuantityForm = ({
);
const quantityTypeOptions = [
- { label: i18n._(msg`Production`), value: "Production" },
- { label: i18n._(msg`Scrap`), value: "Scrap" },
- { label: i18n._(msg`Rework`), value: "Rework" }
+ { label: t`Production`, value: "Production" },
+ { label: t`Scrap`, value: "Scrap" },
+ { label: t`Rework`, value: "Rework" }
];
const isEditing = initialValues.id !== undefined;
diff --git a/apps/erp/app/modules/production/ui/Schedule/Kanban/drag-lifecycle.test.tsx b/apps/erp/app/modules/production/ui/Schedule/Kanban/drag-lifecycle.test.tsx
index 61951ab9af..83ab9c698f 100644
--- a/apps/erp/app/modules/production/ui/Schedule/Kanban/drag-lifecycle.test.tsx
+++ b/apps/erp/app/modules/production/ui/Schedule/Kanban/drag-lifecycle.test.tsx
@@ -103,12 +103,19 @@ vi.mock("react-router", () => ({
useFetchers: () => fetchers.current,
useSubmit: () => submit
}));
+// The boards moved from x/schedule to x/priority in 7f5f1d2145 (#1151), which
+// renamed these helpers scheduleDatesUpdate -> priorityDatesUpdate and
+// scheduleOperationUpdate -> priorityOperationUpdate. The mock must carry the
+// current keys: an unknown key resolves to `undefined`, which both blanks the
+// submit action AND makes the pending-fetcher filters
+// (`fetcher.formAction === path.to.priorityDatesUpdate`) match nothing, so the
+// optimistic merge silently stops happening.
vi.mock("~/utils/path", () => ({
path: {
to: {
- priorityBatchingUpdate: "/priority/batching/update",
- priorityDatesUpdate: "/priority/dates/update",
- priorityOperationUpdate: "/priority/operations/update"
+ priorityBatchingUpdate: "/x/priority/batching/update",
+ priorityDatesUpdate: "/x/priority/dates/update",
+ priorityOperationUpdate: "/x/priority/operations/update"
}
}
}));
@@ -301,7 +308,7 @@ function pendingDateFetcher({
formData.set("optimisticColumnId", optimisticColumnId);
}
return {
- formAction: "/priority/dates/update",
+ formAction: "/x/priority/dates/update",
formData,
key: `job:${id}`,
state: "loading"
@@ -361,7 +368,7 @@ describe("Dates board drag lifecycle", () => {
optimisticColumnId: "2026-08-08",
priority: 11
},
- expect.objectContaining({ action: "/priority/dates/update" })
+ expect.objectContaining({ action: "/x/priority/dates/update" })
);
});
@@ -398,7 +405,7 @@ describe("Dates board drag lifecycle", () => {
optimisticColumnId: "2026-08-08",
priority: 21
},
- expect.objectContaining({ action: "/priority/dates/update" })
+ expect.objectContaining({ action: "/x/priority/dates/update" })
);
expect(submit).not.toHaveBeenCalledWith(
expect.objectContaining({ columnId: "2026-08-16" }),
@@ -428,7 +435,7 @@ describe("Dates board drag lifecycle", () => {
locationId: "location-1",
columnId: "2026-08-15"
}),
- expect.objectContaining({ action: "/priority/dates/update" })
+ expect.objectContaining({ action: "/x/priority/dates/update" })
);
expect(submit).not.toHaveBeenCalledWith(
expect.objectContaining({ columnId: "2026-08-16" }),
@@ -439,7 +446,7 @@ describe("Dates board drag lifecycle", () => {
it("ignores a Dates fetcher without form data and preserves the next drag origin", () => {
fetchers.current = [
{
- formAction: "/priority/dates/update",
+ formAction: "/x/priority/dates/update",
formData: undefined,
key: "job:job-a",
state: "loading"
@@ -463,7 +470,7 @@ describe("Dates board drag lifecycle", () => {
optimisticColumnId: "2026-08-08",
priority: 11
},
- expect.objectContaining({ action: "/priority/dates/update" })
+ expect.objectContaining({ action: "/x/priority/dates/update" })
);
});
@@ -553,7 +560,7 @@ describe("Dates board drag lifecycle", () => {
optimisticColumnId: "next-week",
priority: 21
},
- expect.objectContaining({ action: "/priority/dates/update" })
+ expect.objectContaining({ action: "/x/priority/dates/update" })
);
expect(submit).not.toHaveBeenCalledWith(
expect.objectContaining({ columnId: "2026-08-09" }),
@@ -654,7 +661,7 @@ describe("Operations board drag lifecycle", () => {
expect(submit).toHaveBeenCalledTimes(1);
expect(submit).toHaveBeenCalledWith(
{ id: "operation-a", columnId: "wc-2", priority: 19 },
- expect.objectContaining({ action: "/priority/operations/update" })
+ expect.objectContaining({ action: "/x/priority/operations/update" })
);
});
@@ -773,7 +780,7 @@ describe("Operations board drag lifecycle", () => {
expect(submit).toHaveBeenCalledTimes(1);
expect(submit).toHaveBeenCalledWith(
{ intent: "update", batchId: "BAT1", workCenterId: "wc-2" },
- expect.objectContaining({ action: "/priority/batching/update" })
+ expect.objectContaining({ action: "/x/priority/batching/update" })
);
});
@@ -786,6 +793,17 @@ describe("Operations board drag lifecycle", () => {
over: itemOver(operationItems[0])
});
- expect(submit).not.toHaveBeenCalled();
+ // A within-column drop is a REORDER, so it legitimately writes the batch's
+ // new priority through the batching endpoint. What it must never do is
+ // reassign the work center — that is the `intent: "update"` payload the
+ // cross-column case sends. Asserting `submit` was never called at all would
+ // contradict the reorder the drop actually performed.
+ expect(submit).not.toHaveBeenCalledWith(
+ expect.objectContaining({ intent: "update" }),
+ expect.anything()
+ );
+ for (const [payload] of submit.mock.calls) {
+ expect(payload).not.toHaveProperty("workCenterId");
+ }
});
});
diff --git a/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderApprovalModal.tsx b/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderApprovalModal.tsx
index 9871ce5a8c..9d82e77cbe 100644
--- a/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderApprovalModal.tsx
+++ b/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderApprovalModal.tsx
@@ -4,7 +4,6 @@ import {
Modal,
ModalBody,
ModalContent,
- ModalDescription,
ModalFooter,
ModalHeader,
ModalTitle,
@@ -83,16 +82,16 @@ const PurchaseOrderApprovalModal = ({
{isApproving ? "Approve" : "Reject"}{" "}
{purchaseOrder?.purchaseOrderId}
</ModalTitle>
- <ModalDescription>
- {isApproving
- ? "Are you sure you want to approve this purchase order? This will allow the order to proceed."
- : "Are you sure you want to reject this purchase order? The requester will be notified."}
- </ModalDescription>
</ModalHeader>
<ModalBody>
<Hidden name="approvalRequestId" />
<Hidden name="decision" />
<VStack spacing={4}>
+ <p className="text-sm text-muted-foreground">
+ {isApproving
+ ? "Are you sure you want to approve this purchase order? This will allow the order to proceed."
+ : "Are you sure you want to reject this purchase order? The requester will be notified."}
+ </p>
{isApproving && canEmail && (
<SelectControlled
label={t`Send Via`}
diff --git a/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderFinalizeModal.tsx b/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderFinalizeModal.tsx
index c81e234dca..d798a87dd7 100644
--- a/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderFinalizeModal.tsx
+++ b/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderFinalizeModal.tsx
@@ -5,7 +5,6 @@ import {
Modal,
ModalBody,
ModalContent,
- ModalDescription,
ModalFooter,
ModalHeader,
ModalTitle,
@@ -80,14 +79,14 @@ const PurchaseOrderFinalizeModal = ({
<ModalTitle>{`Finalize ${getPurchaseOrderDisplayId(
purchaseOrder
)}`}</ModalTitle>
- <ModalDescription>
- Are you sure you want to finalize the purchase order? Finalizing
- the order will affect on order quantities used to calculate supply
- and demand.
- </ModalDescription>
</ModalHeader>
<ModalBody>
<VStack spacing={4}>
+ <p className="text-sm text-muted-foreground">
+ Are you sure you want to finalize the purchase order? Finalizing
+ the order will affect on order quantities used to calculate
+ supply and demand.
+ </p>
{canEmail && (
<SelectControlled
label={t`Send Via`}
diff --git a/apps/erp/app/modules/purchasing/ui/Supplier/SupplierApprovalModal.tsx b/apps/erp/app/modules/purchasing/ui/Supplier/SupplierApprovalModal.tsx
index c86d7e0e94..ce068499f0 100644
--- a/apps/erp/app/modules/purchasing/ui/Supplier/SupplierApprovalModal.tsx
+++ b/apps/erp/app/modules/purchasing/ui/Supplier/SupplierApprovalModal.tsx
@@ -4,7 +4,6 @@ import {
Modal,
ModalBody,
ModalContent,
- ModalDescription,
ModalFooter,
ModalHeader,
ModalTitle
@@ -59,15 +58,15 @@ const SupplierApprovalModal = ({
<ModalTitle>
{isApproving ? "Approve" : "Reject"} {supplierName}
</ModalTitle>
- <ModalDescription>
- {isApproving
- ? "Are you sure you want to approve this supplier? This will make it active."
- : "Are you sure you want to reject this supplier?"}
- </ModalDescription>
</ModalHeader>
<ModalBody>
<Hidden name="approvalRequestId" />
<Hidden name="decision" />
+ <p className="text-sm text-muted-foreground mb-4">
+ {isApproving
+ ? "Are you sure you want to approve this supplier? This will make it active."
+ : "Are you sure you want to reject this supplier?"}
+ </p>
<TextArea
name="notes"
label={t`Notes (optional)`}
diff --git a/apps/erp/app/modules/quality/ui/Documents/QualityDocumentApprovalModal.tsx b/apps/erp/app/modules/quality/ui/Documents/QualityDocumentApprovalModal.tsx
index d8e19f4456..1533bb7e07 100644
--- a/apps/erp/app/modules/quality/ui/Documents/QualityDocumentApprovalModal.tsx
+++ b/apps/erp/app/modules/quality/ui/Documents/QualityDocumentApprovalModal.tsx
@@ -4,7 +4,6 @@ import {
Modal,
ModalBody,
ModalContent,
- ModalDescription,
ModalFooter,
ModalHeader,
ModalTitle
@@ -64,15 +63,15 @@ const QualityDocumentApprovalModal = ({
<ModalTitle>
{isApproving ? "Approve" : "Reject"} {qualityDocument?.name}
</ModalTitle>
- <ModalDescription>
- {isApproving
- ? "Are you sure you want to approve this quality document? This will make it active."
- : "Are you sure you want to reject this quality document? The document will remain in draft status."}
- </ModalDescription>
</ModalHeader>
<ModalBody>
<Hidden name="approvalRequestId" />
<Hidden name="decision" />
+ <p className="text-sm text-muted-foreground mb-4">
+ {isApproving
+ ? "Are you sure you want to approve this quality document? This will make it active."
+ : "Are you sure you want to reject this quality document? The document will remain in draft status."}
+ </p>
<TextArea
name="notes"
label={t`Notes (optional)`}
diff --git a/apps/erp/app/modules/sales/ui/Customer/CustomerHeader.tsx b/apps/erp/app/modules/sales/ui/Customer/CustomerHeader.tsx
index 9777944190..a6fc457734 100644
--- a/apps/erp/app/modules/sales/ui/Customer/CustomerHeader.tsx
+++ b/apps/erp/app/modules/sales/ui/Customer/CustomerHeader.tsx
@@ -160,7 +160,9 @@ const CustomerHeader = () => {
</CardAttributeValue>
</CardAttribute>
<CardAttribute>
- <CardAttributeLabel>Tax Status</CardAttributeLabel>
+ <CardAttributeLabel>
+ <Trans>Tax Status</Trans>
+ </CardAttributeLabel>
<CardAttributeValue>
{routeData?.customerTax?.taxExempt ? (
<Status color="red">Exempt</Status>
diff --git a/apps/erp/app/modules/sales/ui/Quotes/QuoteFinalizeModal.tsx b/apps/erp/app/modules/sales/ui/Quotes/QuoteFinalizeModal.tsx
index d8af55a0eb..4b0b744ef2 100644
--- a/apps/erp/app/modules/sales/ui/Quotes/QuoteFinalizeModal.tsx
+++ b/apps/erp/app/modules/sales/ui/Quotes/QuoteFinalizeModal.tsx
@@ -9,7 +9,6 @@ import {
Modal,
ModalBody,
ModalContent,
- ModalDescription,
ModalFooter,
ModalHeader,
ModalTitle,
@@ -172,12 +171,12 @@ const QuotationFinalizeModal = ({
>
<ModalHeader>
<ModalTitle>{`Finalize ${getQuoteDisplayId(quote)}`}</ModalTitle>
- <ModalDescription>
- <Trans>Are you sure you want to finalize the quote?</Trans>
- </ModalDescription>
</ModalHeader>
<ModalBody>
<VStack spacing={4}>
+ <p className="text-sm text-muted-foreground">
+ <Trans>Are you sure you want to finalize the quote?</Trans>
+ </p>
{warningLineReadableIds.length > 0 && (
<Alert variant="destructive">
<LuTriangleAlert className="h-4 w-4" />
diff --git a/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderHeader.tsx b/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderHeader.tsx
index 33cf49d18d..03090e2071 100644
--- a/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderHeader.tsx
+++ b/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderHeader.tsx
@@ -14,7 +14,6 @@ import {
Modal,
ModalBody,
ModalContent,
- ModalDescription,
ModalFooter,
ModalHeader,
ModalTitle,
@@ -122,16 +121,16 @@ const SalesOrderConfirmModal = ({
>
<ModalHeader>
<ModalTitle>{t`Confirm ${salesOrder?.salesOrderId}`}</ModalTitle>
- <ModalDescription>
- <Trans>
- Are you sure you want to confirm this sales order? Confirming
- the order will affect on order quantities used to calculate
- supply and demand.
- </Trans>
- </ModalDescription>
</ModalHeader>
<ModalBody>
<VStack spacing={4}>
+ <p className="text-sm text-muted-foreground">
+ <Trans>
+ Are you sure you want to confirm this sales order? Confirming
+ the order will affect on order quantities used to calculate
+ supply and demand.
+ </Trans>
+ </p>
{canEmail && (
<SelectControlled
label={t`Send Via`}
diff --git a/apps/erp/app/modules/settings/ui/Integrations/AccountMapping.tsx b/apps/erp/app/modules/settings/ui/Integrations/AccountMapping.tsx
index 77170ba82a..afa33da87e 100644
--- a/apps/erp/app/modules/settings/ui/Integrations/AccountMapping.tsx
+++ b/apps/erp/app/modules/settings/ui/Integrations/AccountMapping.tsx
@@ -353,8 +353,15 @@ export function AccountMapping({
{group.accounts.map((account) => {
const mapping = mappedById.get(account.id);
return (
+ // The row's ValidatedForm seeds its controlled `externalId`
+ // Combobox from `defaultValues` only at hydration, so a row
+ // kept mounted across revalidation never repaints when its
+ // saved mapping changes (its own save, match-by-code, AI
+ // suggest). Keying on the persisted external id remounts the
+ // row exactly when the mapping changes, re-seeding it from
+ // fresh loader data instead of requiring a full page reload.
<AccountMappingRowForm
- key={account.id}
+ key={`${account.id}:${mapping?.externalId ?? ""}`}
accountId={account.id}
accountNumber={account.number}
accountName={account.name}
diff --git a/apps/erp/app/modules/storage-rules/ui/RuleAssignmentsList.tsx b/apps/erp/app/modules/storage-rules/ui/RuleAssignmentsList.tsx
index e513532d21..5b817e9d8e 100644
--- a/apps/erp/app/modules/storage-rules/ui/RuleAssignmentsList.tsx
+++ b/apps/erp/app/modules/storage-rules/ui/RuleAssignmentsList.tsx
@@ -2,6 +2,7 @@ import {
Badge,
Button,
Card,
+ CardAction,
CardContent,
CardDescription,
CardHeader,
@@ -152,6 +153,30 @@ export default function RuleAssignmentsList({
const isEmpty = assignments.length === 0;
+ const actions =
+ !isEmpty && canCreate ? (
+ <div className="flex shrink-0 items-center gap-2">
+ {availableOptions.length > 0 && (
+ <Combobox
+ size="md"
+ value=""
+ options={availableOptions}
+ onChange={handleAssign}
+ placeholder={t`Add from library…`}
+ className="w-[200px]"
+ />
+ )}
+ <Button variant="primary" leftIcon={<LuPlus />} asChild>
+ <Link to={`${path.to.newStorageRule}?targetType=${targetType}`}>
+ <Trans>Add rule</Trans>
+ </Link>
+ </Button>
+ </div>
+ ) : null;
+
+ // Flat variant (rendered inside a ModalDrawer body, no Card chrome) keeps the
+ // standalone heading. The card variant uses the shared Card subcomponents
+ // below so it matches every other card in the app.
const header = (
<div className="flex items-start justify-between gap-4">
<div className="min-w-0 flex-1">
@@ -169,25 +194,7 @@ export default function RuleAssignmentsList({
{description}
</p>
</div>
- {!isEmpty && canCreate && (
- <div className="flex shrink-0 items-center gap-2">
- {availableOptions.length > 0 && (
- <Combobox
- size="md"
- value=""
- options={availableOptions}
- onChange={handleAssign}
- placeholder={t`Add from library…`}
- className="w-[200px]"
- />
- )}
- <Button variant="primary" leftIcon={<LuPlus />} asChild>
- <Link to={`${path.to.newStorageRule}?targetType=${targetType}`}>
- <Trans>Add rule</Trans>
- </Link>
- </Button>
- </div>
- )}
+ {actions}
</div>
);
@@ -361,7 +368,20 @@ export default function RuleAssignmentsList({
return (
<Card className="flex-grow">
- <CardHeader>{header}</CardHeader>
+ <HStack className="w-full justify-between items-start">
+ <CardHeader>
+ <CardTitle className="flex items-center gap-2">
+ <Trans>Rules</Trans>
+ {!isEmpty && (
+ <span className="text-sm font-normal text-muted-foreground tabular-nums">
+ {assignments.length}
+ </span>
+ )}
+ </CardTitle>
+ <CardDescription>{description}</CardDescription>
+ </CardHeader>
+ {actions && <CardAction>{actions}</CardAction>}
+ </HStack>
<CardContent>{body}</CardContent>
</Card>
);
@@ -410,7 +430,7 @@ function EmptyState({
<Button
asChild
variant="secondary"
- size="sm"
+ size="md"
leftIcon={<LuPlus />}
>
<Link to={path.to.newStorageRule}>
@@ -423,14 +443,14 @@ function EmptyState({
<Button
asChild
variant="secondary"
- size="sm"
+ size="md"
leftIcon={<LuLibrary />}
>
<Link to={path.to.storageRules}>
<Trans>Browse library</Trans>
</Link>
</Button>
- <Button asChild size="sm" leftIcon={<LuPlus />}>
+ <Button asChild size="md" leftIcon={<LuPlus />}>
<Link to={path.to.newStorageRule}>
<Trans>Create new rule</Trans>
</Link>
diff --git a/apps/erp/app/modules/users/ui/components/ResendInviteModal.tsx b/apps/erp/app/modules/users/ui/components/ResendInviteModal.tsx
index 19027101ce..5377a3e2b4 100644
--- a/apps/erp/app/modules/users/ui/components/ResendInviteModal.tsx
+++ b/apps/erp/app/modules/users/ui/components/ResendInviteModal.tsx
@@ -48,7 +48,7 @@ const ResendInviteModal = ({
</ModalHeader>
<ModalBody>
- <p className="mb-2">
+ <p className="text-sm text-muted-foreground mb-2">
{isSingleUser ? (
<Trans>
Are you sure you want to send an invite to this user?
diff --git a/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json b/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json
index 11cb841e46..100b9fb3cc 100644
--- a/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json
+++ b/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json
@@ -1,5 +1,5 @@
{
- "totalTools": 1495,
+ "totalTools": 1498,
"modules": 15,
"tools": [
{"name":"account_deleteUserAttributeValue","classification":"DESTRUCTIVE","paramCount":2,"schema":"0d38e12233b4","response":"bcde375ebd4c","injectAuth":"companyId","permission":"none"},
@@ -16,6 +16,7 @@
{"name":"account_upsertNotificationPreference","classification":"WRITE","paramCount":3,"schema":"4bf056fb8af6","response":"bcde375ebd4c","injectAuth":"companyId","permission":"none"},
{"name":"account_upsertUserAttributeValue","classification":"WRITE","paramCount":4,"schema":"ed5ec8d6e08d","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"none"},
{"name":"accounting_addCloseTask","classification":"WRITE","paramCount":5,"schema":"2f7e1f0d1298","response":"none","injectAuth":"companyId+createdBy+updatedBy","permission":"accounting:create"},
+ {"name":"accounting_applyCtaToReportPeriodSeries","classification":"WRITE","paramCount":2,"schema":"08ae866b4ea8","response":"5483e69d7515","injectAuth":"companyId","permission":"accounting:update"},
{"name":"accounting_closeAccountingPeriod","classification":"WRITE","paramCount":1,"schema":"7e5905ac5974","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"accounting:update"},
{"name":"accounting_closePeriodWithChecklist","classification":"WRITE","paramCount":1,"schema":"7e5905ac5974","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"accounting:update"},
{"name":"accounting_completeCloseTask","classification":"WRITE","paramCount":2,"schema":"5d2e9a90637b","response":"none","injectAuth":"companyId","permission":"accounting:update"},
@@ -66,7 +67,7 @@
{"name":"accounting_getCurrency","classification":"READ","paramCount":1,"schema":"0e98c276626d","response":"6d5bae3dafd5","injectAuth":"companyId","permission":"accounting:view"},
{"name":"accounting_getCurrencyByCode","classification":"READ","paramCount":1,"schema":"cc2bce783cc5","response":"300e136d14d0","injectAuth":"companyId","permission":"accounting:view"},
{"name":"accounting_getCurrentAccountingPeriod","classification":"READ","paramCount":1,"schema":"2f19cae7bae1","response":"923d00cf55d7","injectAuth":"companyId","permission":"accounting:view"},
- {"name":"accounting_getDefaultAccounts","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"d15f0531072e","injectAuth":"companyId","permission":"accounting:view"},
+ {"name":"accounting_getDefaultAccounts","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"c6ccda55d8ae","injectAuth":"companyId","permission":"accounting:view"},
{"name":"accounting_getDepreciationRun","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"22ccbb1556ab","injectAuth":"companyId","permission":"accounting:view"},
{"name":"accounting_getDepreciationRunLines","classification":"READ","paramCount":1,"schema":"e83946bf5ea7","response":"b9642696fc4d","injectAuth":"companyId","permission":"accounting:view"},
{"name":"accounting_getDepreciationRuns","classification":"READ","paramCount":3,"schema":"04eded31eebb","response":"829d729e81c9","injectAuth":"companyId","permission":"accounting:view"},
@@ -126,8 +127,7 @@
{"name":"accounting_translateCompanyBalances","classification":"WRITE","paramCount":4,"schema":"ba889d393571","response":"be5b093fb6e6","injectAuth":"companyId","permission":"accounting:update"},
{"name":"accounting_translateCompanyPeriodSeries","classification":"WRITE","paramCount":3,"schema":"1c8e97655391","response":"0c01d5ac39c2","injectAuth":"companyId","permission":"accounting:update"},
{"name":"accounting_unlockAccountingPeriod","classification":"WRITE","paramCount":1,"schema":"7e5905ac5974","response":"none","injectAuth":"companyId","permission":"accounting:update"},
- {"name":"accounting_updateDefaultBalanceSheetAccounts","classification":"WRITE","paramCount":21,"schema":"af820410074b","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"accounting:update"},
- {"name":"accounting_updateDefaultIncomeAccounts","classification":"WRITE","paramCount":28,"schema":"d386cfbc865f","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"accounting:update"},
+ {"name":"accounting_updateDefaultAccounts","classification":"WRITE","paramCount":50,"schema":"ba73ae92b14f","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"accounting:update"},
{"name":"accounting_updateFiscalYearSettings","classification":"WRITE","paramCount":2,"schema":"b13ac9bf329b","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"accounting:update"},
{"name":"accounting_updateFixedAsset","classification":"WRITE","paramCount":16,"schema":"c5872851f04c","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"accounting:update"},
{"name":"accounting_updateJournalEntry","classification":"WRITE","paramCount":2,"schema":"8025126e300c","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"accounting:update"},
@@ -144,6 +144,7 @@
{"name":"accounting_upsertPeriodCloseTaskDefinition","classification":"WRITE","paramCount":9,"schema":"22eb270aa01a","response":"none","injectAuth":"companyId+createdBy+updatedBy","permission":"accounting:create+update"},
{"name":"accounting_upsertReportPin","classification":"WRITE","paramCount":2,"schema":"28ab82d5033e","response":"bcde375ebd4c","injectAuth":"companyId+createdBy+updatedBy","permission":"accounting:create+update"},
{"name":"accounting_upsertReportView","classification":"WRITE","paramCount":1,"schema":"d91fde891b7f","response":"b8ded59f5c56","injectAuth":"companyId+createdBy+updatedBy","permission":"accounting:create+update"},
+ {"name":"accounting_validateDefaultIncomeAccounts","classification":"WRITE","paramCount":29,"schema":"9249b04e60e2","response":"090ed1ebfbc1","injectAuth":"companyId","permission":"accounting:update"},
{"name":"documents_deleteDocument","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"documents:delete"},
{"name":"documents_deleteDocumentFavorite","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"documents:delete"},
{"name":"documents_deleteDocumentLabel","classification":"DESTRUCTIVE","paramCount":2,"schema":"5c453c6c156d","response":"bcde375ebd4c","injectAuth":"companyId","permission":"documents:delete"},
@@ -201,7 +202,7 @@
{"name":"inventory_getKanban","classification":"READ","paramCount":1,"schema":"369f807bc840","response":"c5aa7a081ed4","injectAuth":"companyId","permission":"inventory:view"},
{"name":"inventory_getKanbans","classification":"READ","paramCount":2,"schema":"68cb4a73d5a9","response":"fa96e94d8dda","injectAuth":"companyId","permission":"inventory:view"},
{"name":"inventory_getPickingList","classification":"READ","paramCount":1,"schema":"0a4ec3e7319b","response":"227255936b96","injectAuth":"companyId","permission":"inventory:view"},
- {"name":"inventory_getPickingListAvailability","classification":"READ","paramCount":1,"schema":"0a4ec3e7319b","response":"dc7546a2e5ad","injectAuth":"companyId","permission":"inventory:view"},
+ {"name":"inventory_getPickingListAvailability","classification":"READ","paramCount":1,"schema":"0a4ec3e7319b","response":"53618db49932","injectAuth":"companyId","permission":"inventory:view"},
{"name":"inventory_getPickingListLine","classification":"READ","paramCount":1,"schema":"063a6777d378","response":"b51ad23d436f","injectAuth":"companyId","permission":"inventory:view"},
{"name":"inventory_getPickingListLines","classification":"READ","paramCount":1,"schema":"0a4ec3e7319b","response":"cc66c1b66f31","injectAuth":"companyId","permission":"inventory:view"},
{"name":"inventory_getPickingListLineTrackedEntities","classification":"READ","paramCount":1,"schema":"063a6777d378","response":"51dd622ce168","injectAuth":"companyId","permission":"inventory:view"},
@@ -292,8 +293,8 @@
{"name":"inventory_upsertStorageUnit","classification":"WRITE","paramCount":8,"schema":"4fde38482a62","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"inventory:create+update"},
{"name":"inventory_upsertWarehouseTransfer","classification":"WRITE","paramCount":10,"schema":"8af29a9b1929","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"inventory:create+update"},
{"name":"inventory_upsertWarehouseTransferLine","classification":"WRITE","paramCount":1,"schema":"93538fae689b","response":"237082879d41","injectAuth":"companyId+createdBy+updatedBy","permission":"inventory:create+update"},
- {"name":"invoicing_applyCreditsToInvoices","classification":"DESTRUCTIVE","paramCount":4,"schema":"a9944c8799d0","response":"none","injectAuth":"companyId","permission":"invoicing:update"},
- {"name":"invoicing_computeEarlyPaymentDiscounts","classification":"READ","paramCount":3,"schema":"0069677fb034","response":"dc7546a2e5ad","injectAuth":"companyId","permission":"invoicing:view"},
+ {"name":"invoicing_applyCreditsToInvoices","classification":"DESTRUCTIVE","paramCount":4,"schema":"404db2e47d09","response":"none","injectAuth":"companyId+createdBy","permission":"invoicing:update"},
+ {"name":"invoicing_computeEarlyPaymentDiscounts","classification":"READ","paramCount":3,"schema":"0069677fb034","response":"53618db49932","injectAuth":"companyId","permission":"invoicing:view"},
{"name":"invoicing_computeInvoiceDateDue","classification":"READ","paramCount":2,"schema":"c07433aded5b","response":"174e29b899b9","injectAuth":"companyId","permission":"invoicing:view"},
{"name":"invoicing_createPurchaseInvoiceFromPurchaseOrder","classification":"WRITE","paramCount":1,"schema":"28cffcd9d6e8","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"invoicing:create"},
{"name":"invoicing_createSalesInvoiceFromSalesOrder","classification":"WRITE","paramCount":1,"schema":"d160a49d6787","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"invoicing:create"},
@@ -311,17 +312,19 @@
{"name":"invoicing_getArAging","classification":"READ","paramCount":2,"schema":"8c0a142b94d0","response":"10729e9f1c72","injectAuth":"companyId","permission":"invoicing:view"},
{"name":"invoicing_getArOpenByCustomer","classification":"READ","paramCount":1,"schema":"00e9099a963a","response":"8cd731dddf0d","injectAuth":"companyId","permission":"invoicing:view"},
{"name":"invoicing_getArTieOut","classification":"READ","paramCount":1,"schema":"00e9099a963a","response":"194f80599d96","injectAuth":"companyId","permission":"invoicing:view"},
- {"name":"invoicing_getAvailableCreditsForParty","classification":"READ","paramCount":2,"schema":"0710290ee3c3","response":"c6cf3ad92e74","injectAuth":"companyId","permission":"invoicing:view"},
+ {"name":"invoicing_getAvailableCreditsForParty","classification":"READ","paramCount":3,"schema":"cc95c9088447","response":"f8e7a5443d43","injectAuth":"companyId","permission":"invoicing:view"},
{"name":"invoicing_getAvailableOnAccountCredit","classification":"READ","paramCount":1,"schema":"2bfa7d907171","response":"cddf8275afa1","injectAuth":"companyId","permission":"invoicing:view"},
+ {"name":"invoicing_getAvailableOnAccountCreditSources","classification":"READ","paramCount":2,"schema":"b09149f439eb","response":"bd1dd61e7055","injectAuth":"companyId","permission":"invoicing:view"},
{"name":"invoicing_getCompanyHasOpenCredits","classification":"READ","paramCount":1,"schema":"ffed91643c1d","response":"7cb541e84f22","injectAuth":"companyId","permission":"invoicing:view"},
- {"name":"invoicing_getInvoiceSettlements","classification":"READ","paramCount":1,"schema":"bd163ca304cd","response":"dd022cfb2135","injectAuth":"companyId","permission":"invoicing:view"},
- {"name":"invoicing_getInvoiceSettlementsForInvoice","classification":"READ","paramCount":2,"schema":"9d6509fa2229","response":"3c49e0950f22","injectAuth":"companyId","permission":"invoicing:view"},
+ {"name":"invoicing_getInvoiceSettlements","classification":"READ","paramCount":1,"schema":"bd163ca304cd","response":"5483e69d7515","injectAuth":"companyId","permission":"invoicing:view"},
+ {"name":"invoicing_getInvoiceSettlementsForInvoice","classification":"READ","paramCount":2,"schema":"9d6509fa2229","response":"a334c4e05d56","injectAuth":"companyId","permission":"invoicing:view"},
{"name":"invoicing_getMemo","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"ee27f56e2f82","injectAuth":"companyId","permission":"invoicing:view"},
{"name":"invoicing_getMemoApplications","classification":"READ","paramCount":1,"schema":"188417093a55","response":"667060f6a7e4","injectAuth":"companyId","permission":"invoicing:view"},
{"name":"invoicing_getMemos","classification":"READ","paramCount":6,"schema":"b120ea106813","response":"4b05f5647015","injectAuth":"companyId","permission":"invoicing:view"},
- {"name":"invoicing_getOpenPurchaseInvoicesForSupplier","classification":"READ","paramCount":1,"schema":"67043a31b1b5","response":"1c5bb161d464","injectAuth":"companyId","permission":"invoicing:view"},
- {"name":"invoicing_getOpenSalesInvoicesForCustomer","classification":"READ","paramCount":1,"schema":"09e48c79fb16","response":"1c5bb161d464","injectAuth":"companyId","permission":"invoicing:view"},
+ {"name":"invoicing_getOpenPurchaseInvoicesForSupplier","classification":"READ","paramCount":2,"schema":"da8678ca28c2","response":"15ebe9acd4e2","injectAuth":"companyId","permission":"invoicing:view"},
+ {"name":"invoicing_getOpenSalesInvoicesForCustomer","classification":"READ","paramCount":2,"schema":"2d555b8aaf06","response":"15ebe9acd4e2","injectAuth":"companyId","permission":"invoicing:view"},
{"name":"invoicing_getPayment","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"dcd7a2b028c7","injectAuth":"companyId","permission":"invoicing:view"},
+ {"name":"invoicing_getPaymentCurrencyConfiguration","classification":"READ","paramCount":1,"schema":"cc2bce783cc5","response":"35b15cbf37ce","injectAuth":"companyId","permission":"invoicing:view"},
{"name":"invoicing_getPayments","classification":"READ","paramCount":8,"schema":"8294255666da","response":"cb3415df82d8","injectAuth":"companyId","permission":"invoicing:view"},
{"name":"invoicing_getPurchaseInvoice","classification":"READ","paramCount":1,"schema":"9fcbb4e4e012","response":"8af6fcfff1cc","injectAuth":"companyId","permission":"invoicing:view"},
{"name":"invoicing_getPurchaseInvoiceDelivery","classification":"READ","paramCount":1,"schema":"9fcbb4e4e012","response":"57af27aeef3b","injectAuth":"companyId","permission":"invoicing:view"},
@@ -334,10 +337,10 @@
{"name":"invoicing_getSalesInvoiceLines","classification":"READ","paramCount":1,"schema":"9e382a0affeb","response":"b7f2e34a7b22","injectAuth":"companyId","permission":"invoicing:view"},
{"name":"invoicing_getSalesInvoices","classification":"READ","paramCount":4,"schema":"f682a832527b","response":"d0445b461305","injectAuth":"companyId","permission":"invoicing:view"},
{"name":"invoicing_getSalesInvoiceShipment","classification":"READ","paramCount":1,"schema":"9e382a0affeb","response":"43114f5895a3","injectAuth":"companyId","permission":"invoicing:view"},
- {"name":"invoicing_getStagedCreditsForPayment","classification":"READ","paramCount":2,"schema":"d67008f41829","response":"76136dba6f93","injectAuth":"companyId","permission":"invoicing:view"},
+ {"name":"invoicing_getStagedCreditsForPayment","classification":"READ","paramCount":2,"schema":"d67008f41829","response":"5a23b05562f4","injectAuth":"companyId","permission":"invoicing:view"},
{"name":"invoicing_insertPurchaseInvoice","classification":"DESTRUCTIVE","paramCount":15,"schema":"15dc8b208ca1","response":"24b4b1602470","injectAuth":"companyId+createdBy+updatedBy","permission":"invoicing:create"},
{"name":"invoicing_insertSalesInvoice","classification":"DESTRUCTIVE","paramCount":14,"schema":"56c402cfa5a8","response":"24b4b1602470","injectAuth":"companyId+createdBy+updatedBy","permission":"invoicing:create"},
- {"name":"invoicing_replaceInvoiceSettlements","classification":"DESTRUCTIVE","paramCount":2,"schema":"d99cd6172187","response":"none","injectAuth":"companyId","permission":"invoicing:update"},
+ {"name":"invoicing_replaceInvoiceSettlements","classification":"DESTRUCTIVE","paramCount":2,"schema":"8e0a48ddafaf","response":"none","injectAuth":"companyId+createdBy","permission":"invoicing:update"},
{"name":"invoicing_updatePurchaseInvoice","classification":"WRITE","paramCount":15,"schema":"304bf354aa67","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"invoicing:update"},
{"name":"invoicing_updatePurchaseInvoiceExchangeRate","classification":"WRITE","paramCount":2,"schema":"bca4d06461aa","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"invoicing:update"},
{"name":"invoicing_updatePurchaseInvoiceLineOrder","classification":"WRITE","paramCount":1,"schema":"d19d08f2d129","response":"none","injectAuth":"companyId+updatedBy","permission":"invoicing:update"},
@@ -346,7 +349,7 @@
{"name":"invoicing_updateSalesInvoiceExchangeRate","classification":"WRITE","paramCount":2,"schema":"bca4d06461aa","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"invoicing:update"},
{"name":"invoicing_updateSalesInvoiceLineOrder","classification":"WRITE","paramCount":1,"schema":"d19d08f2d129","response":"none","injectAuth":"companyId+updatedBy","permission":"invoicing:update"},
{"name":"invoicing_updateSalesInvoiceStatus","classification":"WRITE","paramCount":4,"schema":"be5f9d03d216","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"invoicing:update"},
- {"name":"invoicing_upsertInvoiceSettlement","classification":"WRITE","paramCount":12,"schema":"57d0974a2e67","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"invoicing:create+update"},
+ {"name":"invoicing_upsertInvoiceSettlement","classification":"WRITE","paramCount":13,"schema":"aa171dfbfeb9","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"invoicing:create+update"},
{"name":"invoicing_upsertMemo","classification":"WRITE","paramCount":12,"schema":"b19aa6b4c8f5","response":"1e0d0fa1a854","injectAuth":"companyId+createdBy+updatedBy","permission":"invoicing:create+update"},
{"name":"invoicing_upsertPayment","classification":"WRITE","paramCount":13,"schema":"496369b3cdf9","response":"1a922c685a61","injectAuth":"companyId+createdBy+updatedBy","permission":"invoicing:create+update"},
{"name":"invoicing_upsertPurchaseInvoice","classification":"DESTRUCTIVE","paramCount":16,"schema":"3ac5ffa004e5","response":"5cc94f07494c","injectAuth":"companyId+createdBy+updatedBy","permission":"invoicing:create+update"},
@@ -393,7 +396,7 @@
{"name":"items_findChangeNoticesForItem","classification":"READ","paramCount":2,"schema":"10c8230a9f49","response":"e0196d4b0041","injectAuth":"companyId","permission":"parts:view"},
{"name":"items_findOtherOpenChangeNoticesForItem","classification":"READ","paramCount":2,"schema":"8a1da983320d","response":"e0196d4b0041","injectAuth":"companyId","permission":"parts:view"},
{"name":"items_getBomHasShelfLifeManagedInput","classification":"READ","paramCount":1,"schema":"623ca47a6c74","response":"7cb541e84f22","injectAuth":"companyId","permission":"parts:view"},
- {"name":"items_getBomItemAttributes","classification":"READ","paramCount":1,"schema":"c4ca22fd1816","response":"dc7546a2e5ad","injectAuth":"companyId","permission":"parts:view"},
+ {"name":"items_getBomItemAttributes","classification":"READ","paramCount":1,"schema":"c4ca22fd1816","response":"53618db49932","injectAuth":"companyId","permission":"parts:view"},
{"name":"items_getChangeNotice","classification":"READ","paramCount":1,"schema":"29578070edb2","response":"09c0b464284c","injectAuth":"companyId","permission":"parts:view"},
{"name":"items_getChangeNoticeActions","classification":"READ","paramCount":1,"schema":"29578070edb2","response":"949f86b5cda3","injectAuth":"companyId","permission":"parts:view"},
{"name":"items_getChangeNoticeAffectedItems","classification":"READ","paramCount":1,"schema":"29578070edb2","response":"5483e69d7515","injectAuth":"companyId","permission":"parts:view"},
@@ -580,7 +583,7 @@
{"name":"people_getEmployeeSummary","classification":"READ","paramCount":1,"schema":"3d90cb5d0437","response":"afd28b3efe9e","injectAuth":"companyId","permission":"people:view"},
{"name":"people_getHoliday","classification":"READ","paramCount":1,"schema":"9189cc10f756","response":"8d2b62b6a13b","injectAuth":"companyId","permission":"people:view"},
{"name":"people_getHolidays","classification":"READ","paramCount":3,"schema":"04eded31eebb","response":"1fedcd5adb59","injectAuth":"companyId","permission":"people:view"},
- {"name":"people_getHolidayYears","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"7dd467066555","injectAuth":"companyId","permission":"people:view"},
+ {"name":"people_getHolidayYears","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"6752ec5720d7","injectAuth":"companyId","permission":"people:view"},
{"name":"people_getOpenClockEntry","classification":"READ","paramCount":1,"schema":"3d90cb5d0437","response":"48d1ac3381b4","injectAuth":"companyId","permission":"people:view"},
{"name":"people_getPeople","classification":"READ","paramCount":3,"schema":"04eded31eebb","response":"5483e69d7515","injectAuth":"companyId","permission":"people:view"},
{"name":"people_getRecentTimecards","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"579660621675","injectAuth":"companyId","permission":"people:view"},
@@ -768,11 +771,11 @@
{"name":"production_insertJob","classification":"WRITE","paramCount":2,"schema":"fea224e085b1","response":"ad63dfd9d877","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create"},
{"name":"production_invalidateAssemblyModelCache","classification":"DESTRUCTIVE","paramCount":1,"schema":"277f7d872d8c","response":"bcde375ebd4c","injectAuth":"companyId","permission":"production:update"},
{"name":"production_issueMaterial","classification":"WRITE","paramCount":7,"schema":"0408bd8c9bde","response":"none","injectAuth":"companyId","permission":"production:update"},
- {"name":"production_maxToolQuantityByItem","classification":"WRITE","paramCount":1,"schema":"8b9e90037b9a","response":"dc7546a2e5ad","injectAuth":"companyId","permission":"production:update"},
+ {"name":"production_maxToolQuantityByItem","classification":"WRITE","paramCount":1,"schema":"8b9e90037b9a","response":"53618db49932","injectAuth":"companyId","permission":"production:update"},
{"name":"production_movePeopleAssignment","classification":"DESTRUCTIVE","paramCount":2,"schema":"a726aa587ccc","response":"fe5e1dc03da5","injectAuth":"companyId+updatedBy","permission":"production:update"},
{"name":"production_movePeopleWeek","classification":"DESTRUCTIVE","paramCount":5,"schema":"fec8ebf1add4","response":"3badaa1686e8","injectAuth":"companyId+updatedBy","permission":"production:update"},
{"name":"production_notifyScheduleInputsChanged","classification":"WRITE","paramCount":3,"schema":"172bee52ed70","response":"none","injectAuth":"companyId","permission":"production:update"},
- {"name":"production_planAssemblyStepMarkerSync","classification":"WRITE","paramCount":2,"schema":"f32958f213ae","response":"133d83f1706f","injectAuth":"companyId","permission":"production:update"},
+ {"name":"production_planAssemblyStepMarkerSync","classification":"WRITE","paramCount":2,"schema":"f32958f213ae","response":"4796bc0b8e8c","injectAuth":"companyId","permission":"production:update"},
{"name":"production_pullJobMaterialMakeMethod","classification":"WRITE","paramCount":2,"schema":"e27f48bbab4c","response":"bcde375ebd4c","injectAuth":"companyId","permission":"production:update"},
{"name":"production_reassignAssemblyStepComponents","classification":"DESTRUCTIVE","paramCount":4,"schema":"99f3d689165d","response":"none","injectAuth":"companyId","permission":"production:update"},
{"name":"production_recalculateJobMakeMethodRequirements","classification":"WRITE","paramCount":1,"schema":"3797626bd17e","response":"none","injectAuth":"companyId+updatedBy","permission":"production:update"},
diff --git a/apps/erp/app/routes/api+/v1+/lib/dispatch-parity.test.ts b/apps/erp/app/routes/api+/v1+/lib/dispatch-parity.test.ts
index d12574dabf..601d7c6eb4 100644
--- a/apps/erp/app/routes/api+/v1+/lib/dispatch-parity.test.ts
+++ b/apps/erp/app/routes/api+/v1+/lib/dispatch-parity.test.ts
@@ -21,6 +21,8 @@ const spies = vi.hoisted(() => ({
insertIssue: vi.fn(),
insertPurchaseOrder: vi.fn(),
insertSalesOrder: vi.fn(),
+ replaceInvoiceSettlements: vi.fn(),
+ applyCreditsToInvoices: vi.fn(),
FAKE_DB: { __kysely: true },
FAKE_CLIENT: { __supabase: true }
}));
@@ -40,7 +42,10 @@ vi.mock("~/modules/documents/documents.service", () => ({}));
vi.mock("~/modules/inventory/inventory.service", () => ({
generateInventoryCountLines: spies.generateInventoryCountLines
}));
-vi.mock("~/modules/invoicing/invoicing.service", () => ({}));
+vi.mock("~/modules/invoicing/invoicing.service", () => ({
+ replaceInvoiceSettlements: spies.replaceInvoiceSettlements,
+ applyCreditsToInvoices: spies.applyCreditsToInvoices
+}));
vi.mock("~/modules/items/items.service", () => ({}));
vi.mock("~/modules/people/people.service", () => ({}));
vi.mock("~/modules/production/production.mcp.server", () => ({}));
@@ -133,7 +138,9 @@ const allSpies = [
spies.insertJob,
spies.insertIssue,
spies.insertPurchaseOrder,
- spies.insertSalesOrder
+ spies.insertSalesOrder,
+ spies.replaceInvoiceSettlements,
+ spies.applyCreditsToInvoices
];
beforeEach(() => {
@@ -144,6 +151,66 @@ beforeEach(() => {
});
describe("dispatchOperation service-call contract (golden, ex-executeFunction parity)", () => {
+ it.each([
+ undefined,
+ "forged-user"
+ ])("attributes memo applications to the authenticated author (caller author: %s)", async (createdBy) => {
+ const input = {
+ paymentId: "payment-1",
+ appliedDate: "2026-09-09",
+ side: "purchase",
+ applications: [{ memoId: "memo-1", invoiceId: "invoice-1", amount: 30 }]
+ };
+ const result = await runDispatch(
+ "invoicing_applyCreditsToInvoices",
+ spies.applyCreditsToInvoices,
+ { ...input, ...(createdBy ? { createdBy } : {}) }
+ );
+ expect(result.dispatchError).toBeUndefined();
+ expect(result.calls).toEqual([
+ [spies.FAKE_DB, { ...input, companyId: "c1", createdBy: "u1" }]
+ ]);
+ });
+
+ it.each([
+ undefined,
+ "forged-user"
+ ])("attributes replacement settlements to the authenticated author (caller author: %s)", async (createdBy) => {
+ const applications = [
+ {
+ targetPurchaseInvoiceId: "invoice-1",
+ appliedAmount: 90,
+ sourceAmount: 90,
+ discountAmount: 5,
+ writeOffAmount: 5,
+ targetExchangeRate: 1,
+ sourceExchangeRate: 1,
+ appliedDate: "2026-09-09"
+ }
+ ];
+ const result = await runDispatch(
+ "invoicing_replaceInvoiceSettlements",
+ spies.replaceInvoiceSettlements,
+ {
+ paymentId: "payment-1",
+ applications,
+ ...(createdBy ? { createdBy } : {})
+ }
+ );
+ expect(result.dispatchError).toBeUndefined();
+ expect(result.calls).toEqual([
+ [
+ spies.FAKE_DB,
+ {
+ paymentId: "payment-1",
+ applications,
+ companyId: "c1",
+ createdBy: "u1"
+ }
+ ]
+ ]);
+ });
+
// The `companyId` in a. and a2. is the fix for the `args` branch skipping
// enrichWithAuthContext. getAccountLedger's args type REQUIRES companyId; without
// the stamp it took neither its companyId nor its companyIds branch and the query
diff --git a/apps/erp/app/routes/select-company+/_layout.tsx b/apps/erp/app/routes/select-company+/_layout.tsx
index 99c6d09331..d4a0bd3799 100644
--- a/apps/erp/app/routes/select-company+/_layout.tsx
+++ b/apps/erp/app/routes/select-company+/_layout.tsx
@@ -1,7 +1,6 @@
import { getMESUrl } from "@carbon/auth";
import { requireAuthSession } from "@carbon/auth/session.server";
import { TooltipProvider, useMode } from "@carbon/react";
-import { MeshGradient } from "@paper-design/shaders-react";
import type { LoaderFunctionArgs } from "react-router";
import { Outlet, redirect } from "react-router";
@@ -30,18 +29,7 @@ export default function SelectCompanyLayout() {
return (
<TooltipProvider>
<div className="relative h-screen w-screen">
- <div className="absolute inset-0" style={{ background }}>
- <MeshGradient
- speed={1}
- colors={colors}
- distortion={0.8}
- swirl={0.1}
- grainMixer={0}
- grainOverlay={0}
- className="absolute inset-0 w-full h-full"
- style={{ height: "100%", width: "100%" }}
- />
- </div>
+ <div className="absolute inset-0" style={{ background }} />
<div className="relative z-10 flex h-full w-full items-center justify-center p-4">
<Outlet />
</div>
diff --git a/apps/erp/app/routes/x+/accounting+/defaults.tsx b/apps/erp/app/routes/x+/accounting+/defaults.tsx
index 959eaba118..034bcbf77d 100644
--- a/apps/erp/app/routes/x+/accounting+/defaults.tsx
+++ b/apps/erp/app/routes/x+/accounting+/defaults.tsx
@@ -10,11 +10,8 @@ import { useRouteData } from "~/hooks";
import type { AccountListItem } from "~/modules/accounting";
import {
defaultAccountValidator,
- defaultBalanceSheetAccountValidator,
- defaultIncomeAcountValidator,
getDefaultAccounts,
- updateDefaultBalanceSheetAccounts,
- updateDefaultIncomeAccounts
+ updateDefaultAccounts
} from "~/modules/accounting";
import { AccountDefaultsForm } from "~/modules/accounting/ui/AccountDefaults";
import type { Handle } from "~/utils/handle";
@@ -65,38 +62,19 @@ export async function action({ request }: ActionFunctionArgs) {
return validationError(validation.error);
}
- const incomeValidation = defaultIncomeAcountValidator.safeParse(
- validation.data
- );
- const balanceValidation = defaultBalanceSheetAccountValidator.safeParse(
- validation.data
- );
-
- if (!incomeValidation.success || !balanceValidation.success) {
- throw new Error("Failed to parse default accounts");
- }
-
- const [updateIncome, updateBalance] = await Promise.all([
- updateDefaultIncomeAccounts(client, {
- ...incomeValidation.data,
- companyId,
- updatedBy: userId
- }),
- updateDefaultBalanceSheetAccounts(client, {
- ...balanceValidation.data,
- companyId,
- updatedBy: userId
- })
- ]);
-
- if (updateIncome.error || updateBalance.error) {
+ const result = await updateDefaultAccounts(client, {
+ ...validation.data,
+ companyId,
+ updatedBy: userId
+ });
+ if (result.error) {
return data(
{},
await flash(
request,
error(
- updateIncome.error || updateBalance.error,
- "Failed to update default accounts"
+ result.error,
+ result.error.message || "Failed to update default accounts"
)
)
);
diff --git a/apps/erp/app/routes/x+/job+/$jobId.status.test.ts b/apps/erp/app/routes/x+/job+/$jobId.status.test.ts
index 84a6b07f4a..3a3eb25941 100644
--- a/apps/erp/app/routes/x+/job+/$jobId.status.test.ts
+++ b/apps/erp/app/routes/x+/job+/$jobId.status.test.ts
@@ -1,5 +1,7 @@
+import { error, success } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
+import { runLocationSchedule } from "@carbon/ee/planning";
import { beforeEach, describe, expect, it, vi } from "vitest";
vi.mock("@carbon/auth", () => ({
@@ -19,6 +21,15 @@ vi.mock("@carbon/auth/session.server", () => ({
vi.mock("@carbon/logger", () => ({
getLogger: () => ({ error: vi.fn() })
}));
+// Scheduling moved OUT of the `schedule` edge function and into Node in #1151:
+// the release path now regenerates the job's whole location in-process via
+// `runLocationSchedule` instead of `serviceRole.functions.invoke("schedule")`.
+vi.mock("@carbon/ee/planning", () => ({
+ runLocationSchedule: vi.fn()
+}));
+vi.mock("~/services/database.server", () => ({
+ getDatabaseClient: vi.fn(() => ({}))
+}));
vi.mock("~/utils/path", () => ({
path: {
to: {
@@ -101,6 +112,10 @@ function setup() {
events.push("updateJobStatus");
return { data: { id: "job-1" }, error: null } as any;
});
+ vi.mocked(runLocationSchedule).mockImplementation(async () => {
+ events.push("runLocationSchedule");
+ return {} as any;
+ });
return { client, serviceRole };
}
@@ -134,15 +149,21 @@ describe("Job release status action", () => {
// On success the action ends by throwing a redirect Response.
await expect(runRelease()).rejects.toBeInstanceOf(Response);
+ // The redirect must be the SUCCESS one. Without this, a scheduler that
+ // throws still redirects (the catch flashes "Failed to schedule job"), and
+ // the ordering assertion below would pass on the failure path.
+ expect(success).toHaveBeenCalledWith("Updated job status");
+ expect(error).not.toHaveBeenCalled();
+
expect(updateJobStatus).toHaveBeenCalledOnce();
expect(events).toContain("updateJobStatus");
- expect(events).toContain("invoke:schedule");
- // Regression guard: the `schedule` edge function only batches jobs already
- // Ready/In Progress/Paused. If the status is committed AFTER the scheduler
- // runs, the freshly released job is filtered out of its own schedule run and
- // never lands in capacityReservation / the forecast.
+ expect(events).toContain("runLocationSchedule");
+ // Regression guard: the scheduler only batches jobs already Ready/In
+ // Progress/Paused. If the status is committed AFTER the scheduler runs, the
+ // freshly released job is filtered out of its own schedule run and never
+ // lands in capacityReservation / the forecast.
expect(events.indexOf("updateJobStatus")).toBeLessThan(
- events.indexOf("invoke:schedule")
+ events.indexOf("runLocationSchedule")
);
});
});
diff --git a/apps/erp/app/routes/x+/payments+/$paymentId.applications.set.tsx b/apps/erp/app/routes/x+/payments+/$paymentId.applications.set.tsx
index 0c1ee7acc6..eb816b6174 100644
--- a/apps/erp/app/routes/x+/payments+/$paymentId.applications.set.tsx
+++ b/apps/erp/app/routes/x+/payments+/$paymentId.applications.set.tsx
@@ -15,8 +15,7 @@ import { path } from "~/utils/path";
// Apply-table submits the full list of applications as one JSON payload.
// Each row is validated against invoiceSettlementValidator (with the
// paymentId injected from the URL), then replaceInvoiceSettlements
-// runs a delete-then-insert under RLS (Draft-only via the parent
-// payment policy).
+// validates authoritative parents and replaces normalized rows in a transaction.
const setApplicationsValidator = z.object({
applications: z.string() // JSON-encoded array
});
@@ -55,7 +54,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
// injected so the validator's required-field check passes without
// depending on the client to send it on every row.
const rowsValidator = z.array(
- invoiceSettlementBase.omit({ paymentId: true })
+ invoiceSettlementBase.omit({ paymentId: true }).strict()
);
const rowsResult = rowsValidator.safeParse(parsed);
if (!rowsResult.success) {
@@ -96,7 +95,10 @@ export async function action({ request, params }: ActionFunctionArgs) {
} catch (e) {
throw redirect(
path.to.payment(paymentId),
- await flash(request, error(e, "Failed to save applications"))
+ await flash(
+ request,
+ error(e, e instanceof Error ? e.message : "Failed to save applications")
+ )
);
}
diff --git a/apps/erp/app/routes/x+/payments+/$paymentId.credits.set.tsx b/apps/erp/app/routes/x+/payments+/$paymentId.credits.set.tsx
index a5a9b8e8f7..5a5dd1c997 100644
--- a/apps/erp/app/routes/x+/payments+/$paymentId.credits.set.tsx
+++ b/apps/erp/app/routes/x+/payments+/$paymentId.credits.set.tsx
@@ -19,11 +19,18 @@ const setCreditsValidator = z.object({
});
const rowsValidator = z.array(
- z.object({
- memoId: z.string().min(1),
- invoiceId: z.string().min(1),
- amount: z.number().positive()
- })
+ z
+ .object({
+ memoId: z.string().min(1),
+ invoiceId: z.string().min(1),
+ amount: z.number().finite().nonnegative(),
+ sourceAmount: z.number().finite().nonnegative().optional()
+ })
+ .strict()
+ .refine(
+ (a) => a.amount > 0 || (a.sourceAmount ?? 0) > 0,
+ "Applied document amount must be positive"
+ )
);
export async function action({ request, params }: ActionFunctionArgs) {
@@ -66,7 +73,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
// The invoice side follows the payment's party: a customer's credits clear
// sales invoices; a supplier's clear purchase invoices.
- const payment = await getPayment(client, paymentId);
+ const payment = await getPayment(client, paymentId, companyId);
if (payment.error || !payment.data) {
throw redirect(
path.to.payment(paymentId),
diff --git a/apps/erp/app/routes/x+/payments+/$paymentId.tsx b/apps/erp/app/routes/x+/payments+/$paymentId.tsx
index 85c84827b4..7c5c33cfdc 100644
--- a/apps/erp/app/routes/x+/payments+/$paymentId.tsx
+++ b/apps/erp/app/routes/x+/payments+/$paymentId.tsx
@@ -3,16 +3,18 @@ import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { validationError, validator } from "@carbon/form";
import { VStack } from "@carbon/react";
+import type { FundingSource } from "@carbon/utils";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
import { data, redirect, useLoaderData } from "react-router";
import {
AvailableCreditsTable,
getAvailableCreditsForParty,
- getAvailableOnAccountCredit,
+ getAvailableOnAccountCreditSources,
getInvoiceSettlements,
getOpenPurchaseInvoicesForSupplier,
getOpenSalesInvoicesForCustomer,
getPayment,
+ getPaymentCurrencyConfiguration,
getStagedCreditsForPayment,
isPaymentLocked,
PaymentApplications,
@@ -39,114 +41,144 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
});
const { paymentId } = params;
if (!paymentId) throw notFound("Missing paymentId");
-
const [payment, applications] = await Promise.all([
- getPayment(client, paymentId),
+ getPayment(client, paymentId, companyId),
getInvoiceSettlements(client, companyId, paymentId)
]);
-
- if (payment.error || !payment.data) {
+ if (payment.error || !payment.data)
throw redirect(
path.to.payments,
await flash(request, error(payment.error, "Failed to load payment"))
);
- }
-
- // Apply table needs the counterparty's open invoices. Only fetched
- // for Draft payments to keep the Posted/Voided detail render lean.
- // Cast to a common shape — sales and purchase status enums differ
- // ('Submitted' vs 'Open') so TypeScript can't unify the two without
- // help.
- type OpenInvoiceRow = {
- id: string;
- invoiceId: string | null;
- dateDue: string | null;
- currencyCode: string;
- exchangeRate: number;
- totalAmount: number;
- balance: number;
- status: string | null;
- };
- // Available on-account credit (base ccy) the counterparty can draw on when
- // this payment applies more than its cash. Only needed while editing a Draft.
- // Posted credits (balance-reducing memos) the party can apply to open invoices
- // alongside this payment's cash — the credits half of the settlement composer.
- type AvailableCreditRow = {
- id: string;
- memoId: string;
- direction: string;
- currencyCode: string;
- exchangeRate: number;
- remaining: number;
- };
- let availableCreditBase = 0;
- let openInvoices: OpenInvoiceRow[] = [];
- let availableCredits: AvailableCreditRow[] = [];
- let stagedCredits: { memoId: string; invoiceId: string; amount: number }[] =
- [];
- if (payment.data.status === "Draft") {
- if (payment.data.customerId) {
- const [res, credit, credits, staged] = await Promise.all([
- getOpenSalesInvoicesForCustomer(
- client,
- companyId,
- payment.data.customerId
- ),
- getAvailableOnAccountCredit(client, companyId, {
- paymentType: "Receipt",
- customerId: payment.data.customerId
- }),
- getAvailableCreditsForParty(
- client,
- companyId,
- { side: "sales", customerId: payment.data.customerId },
- paymentId
- ),
- getStagedCreditsForPayment(client, paymentId, "sales")
- ]);
- openInvoices = (res.data ?? []) as OpenInvoiceRow[];
- availableCreditBase = credit;
- availableCredits = (credits.data ?? []) as AvailableCreditRow[];
- stagedCredits = staged.data ?? [];
- } else if (payment.data.supplierId) {
- const [res, credit, credits, staged] = await Promise.all([
- getOpenPurchaseInvoicesForSupplier(
- client,
- companyId,
- payment.data.supplierId
- ),
- getAvailableOnAccountCredit(client, companyId, {
- paymentType: "Disbursement",
- supplierId: payment.data.supplierId
- }),
- getAvailableCreditsForParty(
+ try {
+ if (applications.error) throw new Error(applications.error.message);
+ const configuration = await getPaymentCurrencyConfiguration(
+ client,
+ companyId,
+ payment.data.currencyCode
+ );
+ let openInvoices: NonNullable<
+ Awaited<ReturnType<typeof getOpenSalesInvoicesForCustomer>>["data"]
+ > = [];
+ let funding = {
+ sources: [] as FundingSource[],
+ availableDocumentAmount: 0,
+ availableBaseAmount: 0
+ };
+ let availableCredits: NonNullable<
+ Awaited<ReturnType<typeof getAvailableCreditsForParty>>["data"]
+ > = [];
+ let stagedCredits: NonNullable<
+ Awaited<ReturnType<typeof getStagedCreditsForPayment>>["data"]
+ > = [];
+ if (payment.data.status === "Draft") {
+ const isAR = Boolean(payment.data.customerId);
+ const isRefund = isAR !== (payment.data.paymentType === "Receipt");
+ const partyId = isAR ? payment.data.customerId : payment.data.supplierId;
+ if (
+ !partyId ||
+ Boolean(payment.data.customerId) === Boolean(payment.data.supplierId)
+ )
+ throw new Error("Payment requires exactly one customer or supplier");
+ if (isRefund) {
+ const memos = await getAvailableCreditsForParty(
client,
companyId,
- { side: "purchase", supplierId: payment.data.supplierId },
- paymentId
- ),
- getStagedCreditsForPayment(client, paymentId, "purchase")
- ]);
- openInvoices = (res.data ?? []) as OpenInvoiceRow[];
- availableCreditBase = credit;
- availableCredits = (credits.data ?? []) as AvailableCreditRow[];
- stagedCredits = staged.data ?? [];
+ isAR
+ ? { side: "sales", customerId: partyId }
+ : { side: "purchase", supplierId: partyId },
+ paymentId,
+ payment.data.currencyCode
+ );
+ if (memos.error) throw memos.error;
+ openInvoices = (memos.data ?? []).map((memo) => ({
+ id: memo.id,
+ invoiceId: memo.memoId,
+ dateDue: null,
+ dateIssued: null,
+ paymentTermId: null,
+ currencyCode: memo.currencyCode,
+ exchangeRate: memo.exchangeRate,
+ totalAmount: memo.amount,
+ balance: memo.remaining,
+ remainingDocument: memo.remainingDocument,
+ status: "Posted"
+ }));
+ } else {
+ const [invoices, credit, credits, staged] = await Promise.all([
+ isAR
+ ? getOpenSalesInvoicesForCustomer(
+ client,
+ companyId,
+ partyId,
+ payment.data.currencyCode
+ )
+ : getOpenPurchaseInvoicesForSupplier(
+ client,
+ companyId,
+ partyId,
+ payment.data.currencyCode
+ ),
+ getAvailableOnAccountCreditSources(
+ client,
+ companyId,
+ isAR
+ ? { paymentType: "Receipt", customerId: partyId }
+ : { paymentType: "Disbursement", supplierId: partyId },
+ payment.data.currencyCode
+ ),
+ getAvailableCreditsForParty(
+ client,
+ companyId,
+ isAR
+ ? { side: "sales", customerId: partyId }
+ : { side: "purchase", supplierId: partyId },
+ paymentId,
+ payment.data.currencyCode
+ ),
+ getStagedCreditsForPayment(
+ client,
+ paymentId,
+ isAR ? "sales" : "purchase",
+ companyId
+ )
+ ]);
+ const loadError =
+ invoices.error ?? credit.error ?? credits.error ?? staged.error;
+ if (loadError) throw loadError;
+ if (!credit.data) throw new Error("Unable to load payment funding");
+ openInvoices = invoices.data ?? [];
+ funding = credit.data;
+ availableCredits = credits.data ?? [];
+ stagedCredits = staged.data ?? [];
+ }
}
+ return {
+ payment: payment.data,
+ applications: applications.data ?? [],
+ openInvoices,
+ funding,
+ availableCredits,
+ stagedCredits,
+ ...configuration
+ };
+ } catch (e) {
+ throw redirect(
+ path.to.payments,
+ await flash(
+ request,
+ error(
+ e,
+ e instanceof Error ? e.message : "Failed to load payment balances"
+ )
+ )
+ );
}
-
- return {
- payment: payment.data,
- applications: applications.data ?? [],
- openInvoices: openInvoices ?? [],
- availableCreditBase,
- availableCredits,
- stagedCredits
- };
}
export async function action({ request, params }: ActionFunctionArgs) {
assertIsPost(request);
- const { client, userId } = await requirePermissions(request, {
+ const { client, companyId, userId } = await requirePermissions(request, {
update: "invoicing"
});
const { paymentId } = params;
@@ -159,7 +191,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
}
// Only Draft payments are editable; Posted/Voided are immutable.
- const existing = await getPayment(client, paymentId);
+ const existing = await getPayment(client, paymentId, companyId);
if (existing.error || !existing.data) {
throw redirect(
path.to.payments,
@@ -173,6 +205,25 @@ export async function action({ request, params }: ActionFunctionArgs) {
);
}
+ try {
+ await getPaymentCurrencyConfiguration(
+ client,
+ companyId,
+ validation.data.currencyCode
+ );
+ } catch (e) {
+ throw redirect(
+ path.to.payment(paymentId),
+ await flash(
+ request,
+ error(
+ e,
+ e instanceof Error ? e.message : "Invalid currency configuration"
+ )
+ )
+ );
+ }
+
const { id: _omitId, ...paymentData } = validation.data;
const update = await upsertPayment(client, {
...paymentData,
@@ -198,17 +249,15 @@ export default function PaymentDetailRoute() {
payment,
applications,
openInvoices,
- availableCreditBase,
+ funding,
+ baseCurrencyCode,
+ currencyDecimals,
availableCredits,
stagedCredits
} = useLoaderData<typeof loader>();
const locked = isPaymentLocked(payment.status);
const side: "sales" | "purchase" = payment.customerId ? "sales" : "purchase";
-
- // Convert the base-currency credit pool into the payment's currency so the
- // apply table can compare it against amounts entered in payment currency.
- const exchangeRate = Number(payment.exchangeRate ?? 1) || 1;
- const availableCredit = (availableCreditBase ?? 0) / exchangeRate;
+ const isRefund = (side === "sales") !== (payment.paymentType === "Receipt");
const initialValues = {
id: payment.id,
@@ -218,7 +267,7 @@ export default function PaymentDetailRoute() {
supplierId: payment.supplierId ?? "",
paymentDate: payment.paymentDate,
currencyCode: payment.currencyCode ?? "",
- exchangeRate: Number(payment.exchangeRate ?? 1),
+ exchangeRate: Number(payment.exchangeRate),
totalAmount: Number(payment.totalAmount ?? 0),
bankAccount: payment.bankAccount ?? "",
reference: payment.reference ?? "",
@@ -228,33 +277,45 @@ export default function PaymentDetailRoute() {
return (
<VStack spacing={4} className="p-6 max-w-6xl w-full mx-auto">
- <PaymentForm initialValues={initialValues} />
+ <PaymentForm key={payment.id} initialValues={initialValues} />
<PaymentApplications
applications={applications}
paymentTotal={Number(payment.totalAmount)}
+ paymentCurrency={payment.currencyCode}
+ baseCurrency={baseCurrencyCode}
+ isRefund={isRefund}
/>
{!locked && (
<PaymentApplyTable
+ key={`${payment.id}:${side}:${payment.customerId ?? payment.supplierId}:${payment.currencyCode}:${payment.paymentType}`}
+ isRefund={isRefund}
paymentId={payment.id}
paymentType={payment.paymentType}
paymentCurrency={payment.currencyCode}
+ baseCurrency={baseCurrencyCode}
+ currencyDecimals={currencyDecimals}
+ priorSources={funding.sources}
paymentTotal={Number(payment.totalAmount)}
paymentExchangeRate={Number(payment.exchangeRate)}
- availableCredit={availableCredit}
+ availableCredit={funding.availableDocumentAmount}
openInvoices={(openInvoices ?? []).map((inv) => ({
id: inv.id,
invoiceId: inv.invoiceId ?? inv.id,
dateDue: inv.dateDue,
currencyCode: inv.currencyCode,
- exchangeRate: Number(inv.exchangeRate ?? 1),
+ exchangeRate: Number(inv.exchangeRate),
totalAmount: Number(inv.totalAmount ?? 0),
balance: Number(inv.balance ?? 0),
+ remainingDocument: inv.remainingDocument,
status: inv.status
}))}
existingApplications={applications.map((a) => ({
targetSalesInvoiceId: a.targetSalesInvoiceId,
targetPurchaseInvoiceId: a.targetPurchaseInvoiceId,
+ targetMemoId: a.targetMemoId,
+ sourceAmount: a.sourceAmount,
+ sourcePaymentId: a.sourcePaymentId,
appliedAmount: Number(a.appliedAmount),
discountAmount: Number(a.discountAmount),
writeOffAmount: Number(a.writeOffAmount),
@@ -265,24 +326,28 @@ export default function PaymentDetailRoute() {
/>
)}
- {!locked && availableCredits.length > 0 && (
+ {!locked && !isRefund && availableCredits.length > 0 && (
<AvailableCreditsTable
paymentId={payment.id}
side={side}
- currency={payment.currencyCode}
+ currency={baseCurrencyCode}
+ documentCurrency={payment.currencyCode}
+ documentDecimals={currencyDecimals}
credits={availableCredits.map((c) => ({
id: c.id,
memoId: c.memoId,
direction: c.direction,
currencyCode: c.currencyCode,
exchangeRate: Number(c.exchangeRate),
- remaining: Number(c.remaining)
+ remaining: Number(c.remaining),
+ remainingDocument: c.remainingDocument
}))}
openInvoices={(openInvoices ?? []).map((inv) => ({
id: inv.id,
invoiceId: inv.invoiceId ?? inv.id,
- exchangeRate: Number(inv.exchangeRate ?? 1),
- balance: Number(inv.balance ?? 0)
+ exchangeRate: Number(inv.exchangeRate),
+ balance: Number(inv.balance ?? 0),
+ remainingDocument: inv.remainingDocument
}))}
staged={stagedCredits}
/>
diff --git a/apps/erp/app/routes/x+/payments+/new.tsx b/apps/erp/app/routes/x+/payments+/new.tsx
index 1567fef08b..a2217413f4 100644
--- a/apps/erp/app/routes/x+/payments+/new.tsx
+++ b/apps/erp/app/routes/x+/payments+/new.tsx
@@ -3,7 +3,7 @@ import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import type { Database } from "@carbon/database";
import { validationError, validator } from "@carbon/form";
-import { datetime, round } from "@carbon/utils";
+import { datetime, round, toBaseAmount, toDocumentAmount } from "@carbon/utils";
import type { SupabaseClient } from "@supabase/supabase-js";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
import { redirect, useLoaderData } from "react-router";
@@ -12,6 +12,7 @@ import {
computeEarlyPaymentDiscounts,
getOpenPurchaseInvoicesForSupplier,
getOpenSalesInvoicesForCustomer,
+ getPaymentCurrencyConfiguration,
PaymentForm,
paymentValidator,
replaceInvoiceSettlements,
@@ -35,12 +36,21 @@ async function getSeedableOpenInvoices(
paymentType === "Receipt"
? await getOpenSalesInvoicesForCustomer(client, companyId, partyId)
: await getOpenPurchaseInvoicesForSupplier(client, companyId, partyId);
+ if (res.error) throw new Error(res.error.message);
return res.data ?? [];
}
-// Resolve the payment currency's decimals, then the early-payment discount per
-// invoice as of `asOfDate`. Returns an all-zero map (no discount) when the
-// currency can't be resolved, so a missing currency never blocks seeding.
+// Loader pre-fills the form. Query params:
+// customerId -> seeds counterparty + paymentType=Receipt
+// supplierId -> seeds counterparty + paymentType=Disbursement
+// invoiceId -> one or more; their open balances are summed into the total
+// and (on submit) one application is seeded per invoice
+// amount -> fallback total when no invoiceId is supplied
+// Early-payment discount per invoice as of `asOfDate`, in the invoice's DOCUMENT
+// currency. It is computed from `remainingDocument` rather than `balance`
+// (which is company base) so it lines up with the payment's cash total, which
+// is a document-currency amount. Returns an all-zero map when the currency
+// can't be resolved, so a missing currency never blocks seeding.
async function getSeededDiscounts(
client: SupabaseClient<Database>,
companyId: string,
@@ -49,7 +59,7 @@ async function getSeededDiscounts(
asOfDate: string,
invoices: {
id?: string | null;
- balance?: number | null;
+ remainingDocument: number;
dateIssued?: string | null;
paymentTermId?: string | null;
}[]
@@ -69,25 +79,17 @@ async function getSeededDiscounts(
currencyDecimals,
invoices: invoices.map((inv) => ({
id: inv.id ?? "",
- balance: Number(inv.balance ?? 0),
+ balance: inv.remainingDocument,
dateIssued: inv.dateIssued ?? null,
paymentTermId: inv.paymentTermId ?? null
}))
});
}
-// Loader pre-fills the form. Query params:
-// customerId -> seeds counterparty + paymentType=Receipt
-// supplierId -> seeds counterparty + paymentType=Disbursement
-// invoiceId -> one or more; their open balances are summed into the total
-// and (on submit) one application is seeded per invoice
-// amount -> fallback total when no invoiceId is supplied
export async function loader({ request }: LoaderFunctionArgs) {
const { client, companyId, companyGroupId } = await requirePermissions(
request,
- {
- create: "invoicing"
- }
+ { create: "invoicing" }
);
const url = new URL(request.url);
@@ -111,14 +113,13 @@ export async function loader({ request }: LoaderFunctionArgs) {
let exchangeRate = 1;
let totalAmount = amount ? Number(amount) : 0;
+ // Resolved before seeding: the discount window is evaluated as of this date.
const paymentDate = datetime
.today(await getCompanyTimeZone(client, companyId))
.toString();
// When seeded from invoices, the total and currency come from the invoices
- // themselves (authoritative), not the URL amount. The seeded total is NET of
- // any early-payment discount the invoice's terms grant as of the payment date,
- // so a "2/10 net 30" invoice paid today pre-fills the discounted cash amount.
+ // themselves (authoritative), not the URL amount.
if (invoiceIds.length > 0 && partyId) {
const open = await getSeedableOpenInvoices(
client,
@@ -129,7 +130,23 @@ export async function loader({ request }: LoaderFunctionArgs) {
const selected = open.filter((inv) => invoiceIds.includes(inv.id ?? ""));
if (selected.length > 0) {
currencyCode = selected[0].currencyCode ?? currencyCode;
- exchangeRate = Number(selected[0].exchangeRate ?? 1);
+ exchangeRate = Number(selected[0].exchangeRate);
+ if (selected.some((inv) => inv.currencyCode !== currencyCode))
+ throw redirect(
+ path.to.payments,
+ await flash(
+ request,
+ error(null, "Selected invoices must use the same currency")
+ )
+ );
+ const configuration = await getPaymentCurrencyConfiguration(
+ client,
+ companyId,
+ currencyCode
+ );
+ // Net of any early-payment discount the invoice's terms grant as of the
+ // payment date, so a "2/10 net 30" invoice paid today pre-fills the
+ // discounted cash amount.
const discounts = await getSeededDiscounts(
client,
companyId,
@@ -138,11 +155,14 @@ export async function loader({ request }: LoaderFunctionArgs) {
paymentDate,
selected
);
- totalAmount = selected.reduce(
- (sum, inv) =>
- sum +
- round(Number(inv.balance ?? 0) - (discounts.get(inv.id ?? "") ?? 0)),
- 0
+ totalAmount = toDocumentAmount(
+ selected.reduce(
+ (sum, inv) =>
+ sum + inv.remainingDocument - (discounts.get(inv.id ?? "") ?? 0),
+ 0
+ ),
+ 1,
+ configuration.currencyDecimals
);
}
}
@@ -168,9 +188,7 @@ export async function loader({ request }: LoaderFunctionArgs) {
export async function action({ request }: ActionFunctionArgs) {
assertIsPost(request);
const { client, companyId, companyGroupId, userId } =
- await requirePermissions(request, {
- create: "invoicing"
- });
+ await requirePermissions(request, { create: "invoicing" });
const formData = await request.formData();
// Hidden field set by the loader so the action can seed applications without
@@ -185,6 +203,25 @@ export async function action({ request }: ActionFunctionArgs) {
return validationError(validation.error);
}
+ try {
+ await getPaymentCurrencyConfiguration(
+ client,
+ companyId,
+ validation.data.currencyCode
+ );
+ } catch (e) {
+ throw redirect(
+ path.to.paymentNew,
+ await flash(
+ request,
+ error(
+ e,
+ e instanceof Error ? e.message : "Invalid currency configuration"
+ )
+ )
+ );
+ }
+
let paymentId = validation.data.paymentId;
if (!paymentId) {
const next = await getNextSequence(client, "payment", companyId);
@@ -201,58 +238,8 @@ export async function action({ request }: ActionFunctionArgs) {
// branch must omit it so the table's xid() default generates the id.
const { id: _omitId, ...paymentData } = validation.data;
- // Resolve the seeded invoices + their early-payment discounts (as of the chosen
- // payment date) BEFORE inserting, so the payment's cash total is derived from
- // the SAME discounts the applications carry (applied + discount = balance).
- // The loader's total is computed for today; recomputing here keeps the total in
- // step when the user changed the payment date before submitting.
- const isReceipt = validation.data.paymentType === "Receipt";
- const seedPartyId = isReceipt
- ? validation.data.customerId
- : validation.data.supplierId;
- let seededInvoices: Awaited<ReturnType<typeof getSeedableOpenInvoices>> = [];
- let seededDiscounts = new Map<string, number>();
- if (seedInvoiceIds.length > 0 && seedPartyId) {
- const open = await getSeedableOpenInvoices(
- client,
- companyId,
- validation.data.paymentType,
- seedPartyId
- );
- seededInvoices = open.filter((inv) =>
- seedInvoiceIds.includes(inv.id ?? "")
- );
- if (seededInvoices.length > 0) {
- seededDiscounts = await getSeededDiscounts(
- client,
- companyId,
- companyGroupId,
- validation.data.currencyCode,
- validation.data.paymentDate,
- seededInvoices
- );
- }
- }
- const seededTotal =
- seededInvoices.length > 0
- ? round(
- seededInvoices.reduce(
- (sum, inv) =>
- sum +
- round(
- Number(inv.balance ?? 0) -
- (seededDiscounts.get(inv.id ?? "") ?? 0)
- ),
- 0
- )
- )
- : null;
-
const insert = await upsertPayment(client, {
...paymentData,
- // Seeded-from-invoice payments take their cash total from the invoices
- // (net of discount), authoritative over the form's pre-filled amount.
- totalAmount: seededTotal ?? paymentData.totalAmount,
paymentId,
companyId,
createdBy: userId,
@@ -265,32 +252,71 @@ export async function action({ request }: ActionFunctionArgs) {
);
}
- // Seed one application per selected invoice: appliedAmount = balance − discount
- // and discountAmount = discount, so applied + discount = balance (settles the
- // invoice in full without over-settling). The user can still adjust via the
- // apply table.
- if (seededInvoices.length > 0) {
+ // Seed one application per selected invoice for its full open balance. Each
+ // invoice's balance + rate are re-fetched server-side so the seed always
+ // reflects the current books. The user can still adjust via the apply table.
+ if (seedInvoiceIds.length > 0) {
+ const isReceipt = validation.data.paymentType === "Receipt";
+ const partyId = isReceipt
+ ? validation.data.customerId
+ : validation.data.supplierId;
try {
- await replaceInvoiceSettlements(getDatabaseClient(), {
- paymentId: insert.data.id,
- companyId,
- createdBy: userId,
- applications: seededInvoices.map((inv) => {
- const discount = seededDiscounts.get(inv.id ?? "") ?? 0;
- return {
- targetSalesInvoiceId: isReceipt ? (inv.id ?? undefined) : undefined,
- targetPurchaseInvoiceId: isReceipt
- ? undefined
- : (inv.id ?? undefined),
- appliedAmount: round(Number(inv.balance ?? 0) - discount),
- discountAmount: discount,
- writeOffAmount: 0,
- targetExchangeRate: Number(inv.exchangeRate ?? 1),
- sourceExchangeRate: Number(validation.data.exchangeRate) || 1,
- appliedDate: validation.data.paymentDate
- };
- })
- });
+ const open = partyId
+ ? await getSeedableOpenInvoices(
+ client,
+ companyId,
+ validation.data.paymentType,
+ partyId
+ )
+ : [];
+ const selected = open.filter(
+ (inv) =>
+ seedInvoiceIds.includes(inv.id ?? "") &&
+ inv.currencyCode === validation.data.currencyCode
+ );
+ if (selected.length > 0) {
+ // Recomputed here rather than reused from the loader: the user may have
+ // changed the payment date before submitting, which moves the discount
+ // window. `applied + discount` still settles the invoice in full.
+ const discounts = await getSeededDiscounts(
+ client,
+ companyId,
+ companyGroupId,
+ validation.data.currencyCode,
+ validation.data.paymentDate,
+ selected
+ );
+ await replaceInvoiceSettlements(getDatabaseClient(), {
+ paymentId: insert.data.id,
+ companyId,
+ createdBy: userId,
+ applications: selected.map((inv) => {
+ // The discount is a DOCUMENT amount (see getSeededDiscounts).
+ // `sourceAmount` is document principal; `appliedAmount` and
+ // `discountAmount` are company base, so the base half is converted
+ // at the invoice's own rate.
+ const discountDocument = discounts.get(inv.id ?? "") ?? 0;
+ const discountBase = discountDocument
+ ? toBaseAmount(discountDocument, Number(inv.exchangeRate))
+ : 0;
+ return {
+ targetSalesInvoiceId: isReceipt
+ ? (inv.id ?? undefined)
+ : undefined,
+ targetPurchaseInvoiceId: isReceipt
+ ? undefined
+ : (inv.id ?? undefined),
+ appliedAmount: round(Number(inv.balance ?? 0) - discountBase),
+ sourceAmount: round(inv.remainingDocument - discountDocument),
+ discountAmount: discountBase,
+ writeOffAmount: 0,
+ targetExchangeRate: Number(inv.exchangeRate),
+ sourceExchangeRate: Number(validation.data.exchangeRate),
+ appliedDate: validation.data.paymentDate
+ };
+ })
+ });
+ }
} catch (e) {
// The payment was created (a Draft with no applications is valid), but
// seeding failed. Send the user to the detail page to apply manually.
diff --git a/apps/erp/app/routes/x+/payments+/payment-refund.test.ts b/apps/erp/app/routes/x+/payments+/payment-refund.test.ts
new file mode 100644
index 0000000000..10bb666615
--- /dev/null
+++ b/apps/erp/app/routes/x+/payments+/payment-refund.test.ts
@@ -0,0 +1,119 @@
+import { beforeEach, expect, it, vi } from "vitest";
+
+const h = vi.hoisted(() => ({
+ payment: {} as Record<string, unknown>,
+ credits: vi.fn(),
+ sales: vi.fn(),
+ purchase: vi.fn(),
+ funding: vi.fn(),
+ staged: vi.fn()
+}));
+vi.mock("@carbon/auth", () => ({
+ assertIsPost: vi.fn(),
+ error: vi.fn(),
+ notFound: vi.fn(),
+ success: vi.fn()
+}));
+vi.mock("@carbon/auth/auth.server", () => ({
+ requirePermissions: vi.fn(async () => ({
+ client: "client",
+ companyId: "company"
+ }))
+}));
+vi.mock("@carbon/auth/session.server", () => ({
+ flash: vi.fn(async () => ({}))
+}));
+vi.mock("@carbon/form", () => ({
+ validationError: vi.fn(),
+ validator: vi.fn()
+}));
+vi.mock("@carbon/react", () => ({ VStack: vi.fn() }));
+vi.mock("~/utils/handle", () => ({ detailBreadcrumb: vi.fn() }));
+vi.mock("~/utils/form", () => ({ setCustomFields: vi.fn() }));
+vi.mock("~/utils/path", () => ({
+ path: { to: { payments: "/x/invoicing/payments" } }
+}));
+vi.mock("~/modules/invoicing", () => ({
+ getPayment: vi.fn(async () => ({ data: h.payment, error: null })),
+ getInvoiceSettlements: vi.fn(async () => ({ data: [], error: null })),
+ getPaymentCurrencyConfiguration: vi.fn(async () => ({
+ baseCurrencyCode: "USD",
+ currencyDecimals: 2
+ })),
+ getAvailableCreditsForParty: h.credits,
+ getOpenSalesInvoicesForCustomer: h.sales,
+ getOpenPurchaseInvoicesForSupplier: h.purchase,
+ getAvailableOnAccountCreditSources: h.funding,
+ getStagedCreditsForPayment: h.staged,
+ isPaymentLocked: vi.fn(),
+ PaymentApplications: vi.fn(),
+ PaymentApplyTable: vi.fn(),
+ PaymentForm: vi.fn(),
+ AvailableCreditsTable: vi.fn(),
+ paymentValidator: {},
+ upsertPayment: vi.fn()
+}));
+
+import { loader } from "./$paymentId";
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ h.payment = {
+ id: "refund",
+ status: "Draft",
+ currencyCode: "EUR",
+ customerId: null,
+ supplierId: null
+ };
+ h.credits.mockResolvedValue({
+ data: [
+ {
+ id: "memo",
+ memoId: "CM1",
+ currencyCode: "EUR",
+ exchangeRate: 1.1,
+ amount: 50,
+ remaining: 40,
+ remainingDocument: 44
+ }
+ ],
+ error: null
+ });
+ h.sales.mockResolvedValue({ data: [], error: null });
+ h.purchase.mockResolvedValue({ data: [], error: null });
+ h.funding.mockResolvedValue({
+ data: { sources: [], availableDocumentAmount: 0, availableBaseAmount: 0 },
+ error: null
+ });
+ h.staged.mockResolvedValue({ data: [], error: null });
+});
+it.each([
+ ["Disbursement", "customerId", "sales"],
+ ["Receipt", "supplierId", "purchase"]
+])("loads memo refund targets for %s %s", async (paymentType, partyKey, side) => {
+ h.payment = { ...h.payment, paymentType, [partyKey]: "party" };
+ const result = await loader({
+ request: new Request("http://localhost/x/payments/refund"),
+ params: { paymentId: "refund" },
+ context: {}
+ } as never);
+ expect(result.openInvoices).toEqual([
+ expect.objectContaining({
+ id: "memo",
+ invoiceId: "CM1",
+ balance: 40,
+ remainingDocument: 44
+ })
+ ]);
+ expect(h.credits).toHaveBeenCalledWith(
+ "client",
+ "company",
+ { side, [partyKey]: "party" },
+ "refund",
+ "EUR"
+ );
+ expect(h.sales).not.toHaveBeenCalled();
+ expect(h.purchase).not.toHaveBeenCalled();
+ expect(h.funding).not.toHaveBeenCalled();
+ expect(h.staged).not.toHaveBeenCalled();
+});
diff --git a/apps/erp/app/routes/x+/reports+/balance-sheet.test.ts b/apps/erp/app/routes/x+/reports+/balance-sheet.test.ts
new file mode 100644
index 0000000000..df5e35eac9
--- /dev/null
+++ b/apps/erp/app/routes/x+/reports+/balance-sheet.test.ts
@@ -0,0 +1,586 @@
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { getCarbonServiceRole } from "@carbon/auth/client.server";
+import { flash } from "@carbon/auth/session.server";
+import type { Database } from "@carbon/database";
+import type { SupabaseClient } from "@supabase/supabase-js";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import {
+ getCompaniesInGroup,
+ getFinancialStatementBalances,
+ getFinancialStatementPeriodSeries,
+ getFiscalYearSettings
+} from "~/modules/accounting";
+import { getConsolidatedPeriodSeriesForReport } from "~/modules/accounting/accounting.ee.server";
+import type { ChartPeriodSeries } from "~/modules/accounting/types";
+import { NET_INCOME_ACCOUNT_ID } from "~/modules/accounting/types";
+import { exportPeriodReport } from "~/modules/accounting/ui/Reports/exportReport";
+import { loader } from "./balance-sheet";
+import { loader as incomeStatementLoader } from "./income-statement";
+import { loader as trialBalanceLoader } from "./trial-balance";
+
+vi.mock("@carbon/auth", () => ({
+ error: (cause: unknown, message: string) => ({
+ cause,
+ message,
+ success: false
+ }),
+ getAppUrl: () => "http://localhost",
+ getMESUrl: () => "http://localhost",
+ CARBON_API_URL: "http://localhost"
+}));
+vi.mock("@carbon/auth/auth.server", () => ({ requirePermissions: vi.fn() }));
+vi.mock("@carbon/auth/session.server", () => ({
+ flash: vi.fn(async () => ({}))
+}));
+vi.mock("@carbon/react", () => ({ VStack: () => null }));
+vi.mock("@lingui/core/macro", () => ({
+ msg: (strings: TemplateStringsArray) => ({ id: strings.join("") })
+}));
+vi.mock("~/modules/settings", () => ({ getNextSequence: vi.fn() }));
+vi.mock("@carbon/glossary", () => ({
+ getDefinitionText: () => "",
+ getEntry: () => undefined,
+ getTermText: () => "",
+ glossaryEntries: () => [],
+ hasEntry: () => false,
+ listEntries: () => [],
+ lookupEntry: () => undefined,
+ termSlug: (term: string) => term,
+ terms: {}
+}));
+vi.mock("~/modules/shared", () => ({
+ months: [
+ "January",
+ "February",
+ "March",
+ "April",
+ "May",
+ "June",
+ "July",
+ "August",
+ "September",
+ "October",
+ "November",
+ "December"
+ ]
+}));
+vi.mock("~/modules/shared/timezone.server", () => ({
+ getCompanyTimeZone: vi.fn(async () => "America/New_York")
+}));
+vi.mock("~/modules/accounting", async () => ({
+ ...(await import("~/modules/accounting/accounting.ee.service")),
+ ...(await import("~/modules/accounting/accounting.models")),
+ getCompaniesInGroup: vi.fn(),
+ getFinancialStatementPeriodSeries: vi.fn(),
+ getFinancialStatementBalances: vi.fn(),
+ getFiscalYearSettings: vi.fn()
+}));
+vi.mock("~/modules/accounting/accounting.ee.server", async () => ({
+ ...(await vi.importActual("~/modules/accounting/accounting.ee.server")),
+ getConsolidatedPeriodSeriesForReport: vi.fn()
+}));
+vi.mock("@carbon/auth/client.server", () => ({
+ getCarbonServiceRole: vi.fn()
+}));
+vi.mock("~/modules/accounting/ui/Reports", () => ({
+ exportPeriodReport: vi.fn(),
+ getPeriodColumnLabel: vi.fn(),
+ MultiPeriodStatementTree: () => null,
+ ReportFilters: () => null
+}));
+
+const keys = ["2026-07", "2026-08"];
+const companies = [
+ {
+ id: "parent",
+ name: "Parent",
+ baseCurrencyCode: "USD",
+ parentCompanyId: null,
+ timezone: "America/New_York",
+ isEliminationEntity: false
+ },
+ {
+ id: "child",
+ name: "Child",
+ baseCurrencyCode: "EUR",
+ parentCompanyId: "parent",
+ timezone: "Europe/Berlin",
+ isEliminationEntity: false
+ }
+];
+
+function account(
+ id: string,
+ parentId: string | null,
+ accountClass: ChartPeriodSeries["class"],
+ amounts: number[],
+ extra: Partial<ChartPeriodSeries> = {}
+): ChartPeriodSeries {
+ return {
+ id,
+ parentId,
+ class: accountClass,
+ name: id,
+ number: null,
+ active: true,
+ companyGroupId: "group",
+ isGroup: false,
+ isSystem: false,
+ incomeBalance: "Balance Sheet",
+ accountType: "Equity - No Close",
+ consolidatedRate: "Current",
+ createdAt: "2026-01-01T00:00:00Z",
+ createdBy: "user",
+ updatedAt: null,
+ updatedBy: null,
+ customFields: {},
+ tags: null,
+ periods: Object.fromEntries(
+ keys.map((key, index) => [
+ key,
+ {
+ balanceAtDate: 0,
+ netChange: 0,
+ translatedBalance: amounts[index] ?? 0,
+ translatedNetChange: amounts[index] ?? 0
+ }
+ ])
+ ),
+ ...extra
+ };
+}
+
+function chart(bookedCta = 0): ChartPeriodSeries[] {
+ return [
+ account("balance-sheet", null, "Asset", [40, 20], {
+ isGroup: true,
+ isSystem: true
+ }),
+ account(
+ "assets",
+ "balance-sheet",
+ "Asset",
+ [160 + bookedCta, 80 + bookedCta],
+ { isGroup: true }
+ ),
+ account("cash", "assets", "Asset", [160 + bookedCta, 80 + bookedCta]),
+ account(
+ "equity",
+ "balance-sheet",
+ "Equity",
+ [120 + bookedCta, 60 + bookedCta],
+ { isGroup: true }
+ ),
+ account("reserves", "equity", "Equity", [bookedCta, bookedCta], {
+ isGroup: true
+ }),
+ account("custom-cta", "reserves", "Equity", [bookedCta, bookedCta], {
+ name: "FX Reserve Renamed",
+ number: "3999"
+ }),
+ account("child-cta", "reserves", "Equity", [0, 0], { number: "3200" }),
+ account(NET_INCOME_ACCOUNT_ID, "equity", "Equity", [120, 60]),
+ account("income-statement", null, "Revenue", [120, 60], {
+ incomeBalance: "Income Statement",
+ isGroup: true,
+ isSystem: true
+ }),
+ account("sales", "income-statement", "Revenue", [150, 75], {
+ incomeBalance: "Income Statement"
+ }),
+ account("expense", "income-statement", "Expense", [30, 15], {
+ incomeBalance: "Income Statement"
+ })
+ ];
+}
+
+let sourceChart: ChartPeriodSeries[];
+let defaults: Record<string, string | null>;
+let defaultError: { message: string } | null;
+let rootGroup: string;
+let rootParent: string | null;
+let client: SupabaseClient<Database>;
+let reads: Array<{ table: string; filters: Record<string, unknown> }>;
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ sourceChart = chart();
+ defaults = { parent: "custom-cta", child: "child-cta" };
+ defaultError = null;
+ rootGroup = "group";
+ rootParent = null;
+ reads = [];
+ client = {
+ from(table: string) {
+ const filters: Record<string, unknown> = {};
+ const builder = {
+ select: () => builder,
+ eq: (field: string, value: unknown) => {
+ filters[field] = value;
+ return builder;
+ },
+ is: (field: string, value: unknown) => {
+ filters[field] = value;
+ return builder;
+ },
+ single: async () => {
+ reads.push({ table, filters: { ...filters } });
+ if (table === "company") {
+ const row = {
+ id: "parent",
+ companyGroupId: rootGroup,
+ parentCompanyId: rootParent
+ };
+ const visible = Object.entries(filters).every(
+ ([key, value]) => row[key as keyof typeof row] === value
+ );
+ return {
+ data: visible ? { id: row.id } : null,
+ error: visible
+ ? null
+ : { message: "Root company is not in the authorized group" }
+ };
+ }
+ if (table === "accountDefault") {
+ return {
+ data: {
+ currencyTranslationAccount: defaults[String(filters.companyId)]
+ },
+ error: defaultError
+ };
+ }
+ if (table === "account") {
+ const data =
+ sourceChart.find(
+ (row) =>
+ row.id === filters.id &&
+ row.companyGroupId === filters.companyGroupId
+ ) ?? null;
+ return { data, error: null };
+ }
+ throw new Error(`Unexpected table ${table}`);
+ }
+ };
+ return builder;
+ }
+ } as unknown as SupabaseClient<Database>;
+ vi.mocked(requirePermissions).mockResolvedValue({
+ client,
+ companyId: "child",
+ companyGroupId: "group",
+ userId: "user"
+ } as Awaited<ReturnType<typeof requirePermissions>>);
+ vi.mocked(getCompaniesInGroup).mockResolvedValue({
+ data: companies,
+ error: null
+ } as Awaited<ReturnType<typeof getCompaniesInGroup>>);
+ vi.mocked(getFiscalYearSettings).mockResolvedValue({
+ data: { startMonth: "January" },
+ error: null
+ } as Awaited<ReturnType<typeof getFiscalYearSettings>>);
+ vi.mocked(getFinancialStatementBalances).mockResolvedValue({
+ data: [],
+ error: null
+ });
+ vi.mocked(getFinancialStatementPeriodSeries).mockImplementation(async () => ({
+ data: sourceChart,
+ ctaByBucket: { "2026-07": 40, "2026-08": 20 },
+ error: null
+ }));
+ vi.mocked(getConsolidatedPeriodSeriesForReport).mockImplementation(
+ async () => ({
+ data: sourceChart,
+ ctaByBucket: { "2026-07": 40, "2026-08": 20 },
+ error: null
+ })
+ );
+});
+
+afterEach(() => vi.unstubAllGlobals());
+
+function runLoader(
+ companiesParam = "all",
+ showTranslated = true,
+ headers?: HeadersInit
+) {
+ const params = new URLSearchParams({
+ companies: companiesParam,
+ showTranslated: String(showTranslated),
+ startDate: "2026-07-01",
+ endDate: "2026-08-31"
+ });
+ return loader({
+ request: new Request(`http://localhost/x/reports/balance-sheet?${params}`, {
+ headers
+ }),
+ params: {},
+ context: {}
+ } as Parameters<typeof loader>[0]);
+}
+
+function amount(rows: ChartPeriodSeries[], id: string, key = "2026-07") {
+ return rows.find((row) => row.id === id)?.periods[key]?.translatedBalance;
+}
+
+describe("balance sheet configured CTA", () => {
+ it("translates a subsidiary for an accountant who cannot read parent defaults", async () => {
+ const deniedClient = {
+ from: () => ({
+ select() {
+ return this;
+ },
+ eq() {
+ return this;
+ },
+ single: async () => ({
+ data: null,
+ error: { message: "Parent defaults are not visible" }
+ })
+ })
+ } as unknown as SupabaseClient<Database>;
+ vi.mocked(requirePermissions).mockImplementation(
+ async (_request, permissions) =>
+ ({
+ client: permissions.bypassRls ? client : deniedClient,
+ companyId: "child",
+ companyGroupId: "group",
+ userId: "user"
+ }) as Awaited<ReturnType<typeof requirePermissions>>
+ );
+ const result = await runLoader("child");
+ expect(amount(result.balanceSheet, "custom-cta")).toBe(40);
+ expect(amount(result.balanceSheet, "balance-sheet")).toBe(0);
+ expect(reads).toContainEqual({
+ table: "company",
+ filters: { id: "parent", companyGroupId: "group", parentCompanyId: null }
+ });
+ });
+
+ it.each([
+ "cross-group",
+ "non-root"
+ ])("refuses %s configuration before reading defaults", async (caseName) => {
+ if (caseName === "cross-group") rootGroup = "other-group";
+ else rootParent = "another-parent";
+ await expect(runLoader("child")).rejects.toMatchObject({ status: 302 });
+ expect(reads.some((read) => read.table === "accountDefault")).toBe(false);
+ });
+
+ it("does not escalate an API key when auth returns an RLS client", async () => {
+ defaultError = {
+ message: "Parent defaults are not visible to this API key"
+ };
+ await expect(
+ runLoader("child", true, { "carbon-key": "test-report-key" })
+ ).rejects.toMatchObject({ status: 302 });
+ expect(getCarbonServiceRole).not.toHaveBeenCalled();
+ });
+
+ it("does not read root configuration after permission denial", async () => {
+ vi.mocked(requirePermissions).mockRejectedValue(
+ new Response("Forbidden", { status: 403 })
+ );
+ await expect(runLoader("child")).rejects.toMatchObject({ status: 403 });
+ expect(reads).toEqual([]);
+ });
+
+ it.each([
+ "all",
+ "child"
+ ])("uses the reporting parent's renamed account and recomputes every total for %s", async (companySelection) => {
+ const result = await runLoader(companySelection);
+ expect(amount(result.balanceSheet, "custom-cta")).toBe(40);
+ expect(amount(result.balanceSheet, "child-cta")).toBe(0);
+ expect(amount(result.balanceSheet, "reserves")).toBe(40);
+ expect(amount(result.balanceSheet, "equity")).toBe(160);
+ expect(amount(result.balanceSheet, "balance-sheet")).toBe(0);
+ expect(amount(result.balanceSheet, "equity", "2026-08")).toBe(80);
+ expect(amount(result.balanceSheet, "balance-sheet", "2026-08")).toBe(0);
+ expect(reads).toContainEqual({
+ table: "accountDefault",
+ filters: { companyId: "parent" }
+ });
+ });
+
+ it("fills single-company translated synthetic income from the full income statement", async () => {
+ const income = sourceChart.find((row) => row.id === NET_INCOME_ACCOUNT_ID)!;
+ for (const key of keys) {
+ income.periods[key] = { netChange: 80, balanceAtDate: 80 };
+ }
+ const result = await runLoader("child");
+ expect(amount(result.balanceSheet, NET_INCOME_ACCOUNT_ID)).toBe(120);
+ expect(amount(result.balanceSheet, "equity")).toBe(160);
+ expect(amount(result.balanceSheet, "balance-sheet")).toBe(0);
+ });
+
+ it("preserves booked CTA and repeated calculations do not mutate the input chart", async () => {
+ sourceChart = chart(10);
+ const original = structuredClone(sourceChart);
+ const first = await runLoader();
+ const second = await runLoader();
+ expect(amount(first.balanceSheet, "custom-cta")).toBe(50);
+ expect(amount(first.balanceSheet, "equity")).toBe(170);
+ expect(amount(first.balanceSheet, "balance-sheet")).toBe(0);
+ expect(second.balanceSheet).toEqual(first.balanceSheet);
+ expect(sourceChart).toEqual(original);
+ });
+
+ it.each([
+ {
+ label: "missing default",
+ change: () => {
+ defaults.parent = null;
+ }
+ },
+ {
+ label: "missing chart account",
+ change: () => {
+ defaults.parent = "missing";
+ }
+ },
+ {
+ label: "inactive",
+ change: () => {
+ sourceChart.find((row) => row.id === "custom-cta")!.active = false;
+ }
+ },
+ {
+ label: "group",
+ change: () => {
+ sourceChart.find((row) => row.id === "custom-cta")!.isGroup = true;
+ }
+ },
+ {
+ label: "wrong class",
+ change: () => {
+ sourceChart.find((row) => row.id === "custom-cta")!.class = "Revenue";
+ }
+ },
+ {
+ label: "wrong statement",
+ change: () => {
+ sourceChart.find((row) => row.id === "custom-cta")!.incomeBalance =
+ "Income Statement";
+ }
+ },
+ {
+ label: "other company group",
+ change: () => {
+ sourceChart.find((row) => row.id === "custom-cta")!.companyGroupId =
+ "other-group";
+ }
+ },
+ {
+ label: "missing period cell",
+ change: () => {
+ delete sourceChart.find((row) => row.id === "custom-cta")!.periods[
+ "2026-08"
+ ];
+ }
+ },
+ {
+ label: "default lookup failure",
+ change: () => {
+ defaultError = { message: "Default lookup failed" };
+ }
+ }
+ ])("refuses $label without returning a partial report", async ({
+ change
+ }) => {
+ change();
+ await expect(runLoader()).rejects.toMatchObject({ status: 302 });
+ expect(flash).toHaveBeenCalledWith(
+ expect.any(Request),
+ expect.objectContaining({ success: false })
+ );
+ });
+
+ it("propagates a subsidiary error before applying CTA", async () => {
+ vi.mocked(getConsolidatedPeriodSeriesForReport).mockResolvedValue({
+ data: null,
+ ctaByBucket: {},
+ error: "Source balances do not balance"
+ });
+ await expect(runLoader()).rejects.toMatchObject({ status: 302 });
+ expect(reads).toEqual([]);
+ });
+
+ it("preserves the untranslated report without resolving CTA defaults", async () => {
+ const original = structuredClone(sourceChart);
+ const result = await runLoader("child", false);
+ expect(result.showTranslated).toBe(false);
+ expect(sourceChart).toEqual(original);
+ expect(reads).toEqual([]);
+ });
+
+ it("exports the corrected leaf, intermediate equity group, and root values", async () => {
+ const result = await runLoader();
+ let downloaded: Blob | undefined;
+ vi.stubGlobal("window", {
+ URL: {
+ createObjectURL: (blob: Blob) => {
+ downloaded = blob;
+ return "blob:report";
+ },
+ revokeObjectURL: vi.fn()
+ }
+ });
+ vi.stubGlobal("document", {
+ createElement: () => ({ click: vi.fn() }),
+ body: { appendChild: vi.fn(), removeChild: vi.fn() }
+ });
+ exportPeriodReport({
+ accounts: result.balanceSheet,
+ periods: result.periods.map((bucket) => ({
+ ...bucket,
+ label: bucket.key
+ })),
+ measure: "balanceAtDate",
+ showTranslated: true,
+ search: "",
+ filename: "balance-sheet.csv"
+ });
+ const csv = await downloaded?.text();
+ expect(csv).toContain("3999,FX Reserve Renamed,40,20");
+ expect(csv).toContain(",reserves,40,20");
+ expect(csv).toContain(",equity,160,80");
+ expect(csv).toContain(",balance-sheet,0,0");
+ });
+});
+
+describe.each([
+ ["balance sheet", loader],
+ ["income statement", incomeStatementLoader],
+ ["trial balance", trialBalanceLoader]
+] as const)("%s company selection", (_name, reportLoader) => {
+ it("rejects an unrelated company before reading ledger balances", async () => {
+ const request = new Request(
+ "http://localhost/x/reports/balance-sheet?companies=unrelated&startDate=2026-07-01&endDate=2026-08-31"
+ );
+ await expect(
+ reportLoader({ request, params: {}, context: {} } as Parameters<
+ typeof reportLoader
+ >[0])
+ ).rejects.toMatchObject({ status: 404 });
+ expect(getFinancialStatementPeriodSeries).not.toHaveBeenCalled();
+ expect(getConsolidatedPeriodSeriesForReport).not.toHaveBeenCalled();
+ expect(reads).toEqual([]);
+ });
+
+ it("refuses a company-list lookup failure instead of reporting empty balances", async () => {
+ vi.mocked(getCompaniesInGroup).mockResolvedValue({
+ data: null,
+ error: { message: "Company lookup failed" }
+ } as unknown as Awaited<ReturnType<typeof getCompaniesInGroup>>);
+ const request = new Request(
+ "http://localhost/x/reports/balance-sheet?companies=all&startDate=2026-07-01&endDate=2026-08-31"
+ );
+ await expect(
+ reportLoader({ request, params: {}, context: {} } as Parameters<
+ typeof reportLoader
+ >[0])
+ ).rejects.toMatchObject({ status: 302 });
+ expect(getFinancialStatementPeriodSeries).not.toHaveBeenCalled();
+ expect(getConsolidatedPeriodSeriesForReport).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/erp/app/routes/x+/reports+/balance-sheet.tsx b/apps/erp/app/routes/x+/reports+/balance-sheet.tsx
index fbbe101f1b..f8d1e133d7 100644
--- a/apps/erp/app/routes/x+/reports+/balance-sheet.tsx
+++ b/apps/erp/app/routes/x+/reports+/balance-sheet.tsx
@@ -12,14 +12,16 @@ import { useLocale } from "@react-aria/i18n";
import { useState } from "react";
import type { LoaderFunctionArgs } from "react-router";
import { Outlet, redirect, useLoaderData } from "react-router";
-import type { ChartPeriodSeries } from "~/modules/accounting";
import {
financialReportParamsValidator,
getCompaniesInGroup,
getFinancialStatementPeriodSeries,
getFiscalYearSettings
} from "~/modules/accounting";
-import { getConsolidatedPeriodSeriesForReport } from "~/modules/accounting/accounting.ee.server";
+import {
+ applyCtaToReportPeriodSeriesForReport,
+ getConsolidatedPeriodSeriesForReport
+} from "~/modules/accounting/accounting.ee.server";
import {
exportPeriodReport,
getPeriodColumnLabel,
@@ -39,26 +41,6 @@ export const handle: Handle = {
export const shouldRevalidate = revalidateIgnoringOffset;
-const CTA_RESERVES_ACCOUNT_NUMBER = "3200";
-
-function applyCtaByBucket(
- accounts: ChartPeriodSeries[],
- ctaByBucket: Record<string, number>
-) {
- const ctaAccount = accounts.find(
- (a) => a.number === CTA_RESERVES_ACCOUNT_NUMBER
- );
- if (!ctaAccount) return;
- for (const [key, cta] of Object.entries(ctaByBucket)) {
- const cell = ctaAccount.periods[key];
- if (!cell) continue;
- ctaAccount.periods[key] = {
- ...cell,
- translatedBalance: (cell.translatedBalance ?? 0) + cta
- };
- }
-}
-
export async function loader({ request }: LoaderFunctionArgs) {
const { client, companyId, companyGroupId } = await requirePermissions(
request,
@@ -91,6 +73,15 @@ export async function loader({ request }: LoaderFunctionArgs) {
]);
const fiscalStartMonth =
months.indexOf(fiscalYearSettings.data?.startMonth ?? "January") + 1;
+ if (companies.error) {
+ throw redirect(
+ path.to.accounting,
+ await flash(
+ request,
+ error(companies.error, "Failed to load report companies")
+ )
+ );
+ }
const companiesList = companies.data ?? [];
const parentCompany = companiesList.find((c) => !c.parentCompanyId);
const parentCurrency = parentCompany?.baseCurrencyCode ?? null;
@@ -101,6 +92,14 @@ export async function loader({ request }: LoaderFunctionArgs) {
: companiesParam
? [companiesParam]
: [companyId];
+ if (
+ selectedCompanyIds.length === 0 ||
+ selectedCompanyIds.some(
+ (id) => !companiesList.some((company) => company.id === id)
+ )
+ ) {
+ throw new Response("Company not found", { status: 404 });
+ }
const isMultiCompany = selectedCompanyIds.length > 1;
// Default range: last 6 months to date (in the company's business timezone) —
@@ -141,10 +140,30 @@ export async function loader({ request }: LoaderFunctionArgs) {
);
}
- const balanceSheetAccounts = consolidated.data.filter(
+ const adjusted = await applyCtaToReportPeriodSeriesForReport(
+ request,
+ parentCompany!.id,
+ {
+ accounts: consolidated.data,
+ bucketKeys: buckets.map((bucket) => bucket.key),
+ ctaByBucket: consolidated.ctaByBucket
+ }
+ );
+ if (adjusted.error || !adjusted.data) {
+ throw redirect(
+ path.to.accounting,
+ await flash(
+ request,
+ error(
+ adjusted.error,
+ adjusted.error?.message ?? "Failed to apply currency translation"
+ )
+ )
+ );
+ }
+ const balanceSheetAccounts = adjusted.data.filter(
(a) => a.incomeBalance === "Balance Sheet"
);
- applyCtaByBucket(balanceSheetAccounts, consolidated.ctaByBucket);
return {
balanceSheet: balanceSheetAccounts,
@@ -189,12 +208,34 @@ export async function loader({ request }: LoaderFunctionArgs) {
);
}
- const balanceSheetAccounts = (series.data ?? []).filter(
- (a) => a.incomeBalance === "Balance Sheet"
- );
+ let accounts = series.data ?? [];
if (showTranslated) {
- applyCtaByBucket(balanceSheetAccounts, series.ctaByBucket);
+ const adjusted = await applyCtaToReportPeriodSeriesForReport(
+ request,
+ parentCompany!.id,
+ {
+ accounts,
+ bucketKeys: buckets.map((bucket) => bucket.key),
+ ctaByBucket: series.ctaByBucket
+ }
+ );
+ if (adjusted.error || !adjusted.data) {
+ throw redirect(
+ path.to.accounting,
+ await flash(
+ request,
+ error(
+ adjusted.error,
+ adjusted.error?.message ?? "Failed to apply currency translation"
+ )
+ )
+ );
+ }
+ accounts = adjusted.data;
}
+ const balanceSheetAccounts = accounts.filter(
+ (a) => a.incomeBalance === "Balance Sheet"
+ );
return {
balanceSheet: balanceSheetAccounts,
diff --git a/apps/erp/app/routes/x+/reports+/income-statement.tsx b/apps/erp/app/routes/x+/reports+/income-statement.tsx
index 691904303d..7a1b2225cf 100644
--- a/apps/erp/app/routes/x+/reports+/income-statement.tsx
+++ b/apps/erp/app/routes/x+/reports+/income-statement.tsx
@@ -70,6 +70,15 @@ export async function loader({ request }: LoaderFunctionArgs) {
]);
const fiscalStartMonth =
months.indexOf(fiscalYearSettings.data?.startMonth ?? "January") + 1;
+ if (companies.error) {
+ throw redirect(
+ path.to.accounting,
+ await flash(
+ request,
+ error(companies.error, "Failed to load report companies")
+ )
+ );
+ }
const companiesList = companies.data ?? [];
const parentCompany = companiesList.find((c) => !c.parentCompanyId);
const parentCurrency = parentCompany?.baseCurrencyCode ?? null;
@@ -80,6 +89,14 @@ export async function loader({ request }: LoaderFunctionArgs) {
: companiesParam
? [companiesParam]
: [companyId];
+ if (
+ selectedCompanyIds.length === 0 ||
+ selectedCompanyIds.some(
+ (id) => !companiesList.some((company) => company.id === id)
+ )
+ ) {
+ throw new Response("Company not found", { status: 404 });
+ }
const isMultiCompany = selectedCompanyIds.length > 1;
// Default range: last 6 months to date (in the company's business timezone) —
diff --git a/apps/erp/app/routes/x+/reports+/trial-balance.tsx b/apps/erp/app/routes/x+/reports+/trial-balance.tsx
index 44171ebc11..2fb038eebe 100644
--- a/apps/erp/app/routes/x+/reports+/trial-balance.tsx
+++ b/apps/erp/app/routes/x+/reports+/trial-balance.tsx
@@ -65,6 +65,15 @@ export async function loader({ request }: LoaderFunctionArgs) {
]);
const fiscalStartMonth =
months.indexOf(fiscalYearSettings.data?.startMonth ?? "January") + 1;
+ if (companies.error) {
+ throw redirect(
+ path.to.accounting,
+ await flash(
+ request,
+ error(companies.error, "Failed to load report companies")
+ )
+ );
+ }
const companiesList = companies.data ?? [];
const parentCompany = companiesList.find((c) => !c.parentCompanyId);
const parentCurrency = parentCompany?.baseCurrencyCode ?? null;
@@ -75,6 +84,14 @@ export async function loader({ request }: LoaderFunctionArgs) {
: companiesParam
? [companiesParam]
: [companyId];
+ if (
+ selectedCompanyIds.length === 0 ||
+ selectedCompanyIds.some(
+ (id) => !companiesList.some((company) => company.id === id)
+ )
+ ) {
+ throw new Response("Company not found", { status: 404 });
+ }
const isMultiCompany = selectedCompanyIds.length > 1;
// Default to the trailing six months, matching every other range report
diff --git a/apps/erp/package.json b/apps/erp/package.json
index 4288a4f26d..d355c0e865 100644
--- a/apps/erp/package.json
+++ b/apps/erp/package.json
@@ -181,6 +181,7 @@
"dev:app": "react-router dev",
"lint": "biome lint --write ",
"start": "NODE_ENV=production react-router-serve ./build/server/index.js",
+ "test": "vitest run",
"typecheck": "tsgo --noEmit",
"typegen": "react-router typegen"
},
diff --git a/apps/erp/test/batching-migration-guards.test.ts b/apps/erp/test/batching-migration-guards.test.ts
index 15bf41473e..f37de02100 100644
--- a/apps/erp/test/batching-migration-guards.test.ts
+++ b/apps/erp/test/batching-migration-guards.test.ts
@@ -19,7 +19,7 @@ const migrations = join(
);
const read = (rel: string) => readFileSync(join(migrations, rel), "utf8");
-const migration = read("20260821024449_job-operation-batching.sql");
+const migration = read("20260905132037_job-operation-batching.sql");
describe("get_batchable_operations is tenant-scoped via RLS", () => {
test("the candidate RPC runs as SECURITY INVOKER so the caller's RLS applies", () => {
@@ -41,15 +41,22 @@ describe("started operations are excluded from batch candidates", () => {
test("the lane branch renders Active AND Completing batches (read-only Completing)", () => {
// The board shows Active batches (drag targets) and Completing batches
- // (read-only, awaiting a retry in MES). Both must appear as lanes.
- expect(migration).toMatch(/OR b\."status"\s+IN\s*\('Active',\s*'Completing'\)/);
+ // (read-only, awaiting a retry in MES). Both must appear as lanes. The
+ // consolidated migration also renders the pre-floor 'Planned' state, which
+ // this assertion allows without letting Active/Completing drop out.
+ expect(migration).toMatch(
+ /OR b\."status"\s+IN\s*\('Planned',\s*'Active',\s*'Completing'\)/
+ );
});
});
describe("batch status enum", () => {
- test("is Active/Completing/Completed with Completing from day one", () => {
+ test("is Planned/Active/Completing/Completed with Completing from day one", () => {
+ // 'Planned' (pre-floor planning) joined the enum in the consolidated
+ // migration; 'Completing' still ships in the same CREATE TYPE rather than
+ // being bolted on by a later ALTER, which is what this pins.
expect(migration).toMatch(
- /CREATE TYPE "jobOperationBatchStatus" AS ENUM \('Active', 'Completing', 'Completed'\)/
+ /CREATE TYPE "jobOperationBatchStatus" AS ENUM \('Planned', 'Active', 'Completing', 'Completed'\)/
);
});
diff --git a/apps/erp/test/batching-tenant-scope-and-fk-locks.test.ts b/apps/erp/test/batching-tenant-scope-and-fk-locks.test.ts
index 5d41818a4c..02b7c21388 100644
--- a/apps/erp/test/batching-tenant-scope-and-fk-locks.test.ts
+++ b/apps/erp/test/batching-tenant-scope-and-fk-locks.test.ts
@@ -20,10 +20,7 @@ const migrations = join(
"migrations"
);
const read = (rel: string) => readFileSync(join(migrations, rel), "utf8");
-const migration = read("20260821024449_job-operation-batching.sql");
-const memberFkFix = read(
- "20260904151137_batch-member-fk-set-null-companyid.sql"
-);
+const migration = read("20260905132037_job-operation-batching.sql");
describe("batch candidates are tenant-scoped (AC[0])", () => {
test("get_batchable_operations runs SECURITY INVOKER so the caller's RLS scopes rows", () => {
@@ -68,11 +65,12 @@ describe("batch membership is pinned to one company via composite FKs", () => {
// referencing column, including the NOT NULL `companyId` — so deleting a
// batch (or a `DELETE FROM company` cascade) would raise a not-null
// violation. The PG15 column-list form nulls ONLY the batch pointer.
- // 20260904151137 fixes both member FKs to this form.
- expect(memberFkFix).toMatch(
+ // The standalone 20260904151137 fix was folded into the consolidated
+ // batching migration when #1550 was squashed, so assert against that.
+ expect(migration).toMatch(
/ADD CONSTRAINT "jobOperation_jobOperationBatchId_fkey"[\s\S]*?ON DELETE SET NULL \("jobOperationBatchId"\)/
);
- expect(memberFkFix).toMatch(
+ expect(migration).toMatch(
/ADD CONSTRAINT "productionEvent_jobOperationBatchId_fkey"[\s\S]*?ON DELETE SET NULL \("jobOperationBatchId"\)/
);
});
diff --git a/apps/erp/test/i18n-react-macros.test.ts b/apps/erp/test/i18n-react-macros.test.ts
index 76f45ed6d8..19a668c51d 100644
--- a/apps/erp/test/i18n-react-macros.test.ts
+++ b/apps/erp/test/i18n-react-macros.test.ts
@@ -37,32 +37,38 @@ function collectFiles(dir: string): string[] {
return files;
}
-describe("Lingui React macro migration", () => {
- it("avoids msg-based translations in React-facing app files", () => {
- const offenders: string[] = [];
+function relative(filePath: string): string {
+ return path.relative(path.resolve(__dirname, ".."), filePath);
+}
- for (const filePath of collectFiles(appRoot)) {
- const source = readFileSync(filePath, "utf8");
- const relativePath = path.relative(path.resolve(__dirname, ".."), filePath);
+// These assertions mirror `.claude/rules/i18n-lingui-system.md`. Keep them in
+// step with it — this file previously banned the `@lingui/core/macro` MODULE
+// outright, which flagged 284 files for importing `msg`, the very pattern that
+// rule prescribes for route breadcrumbs. A gate that contradicts the documented
+// convention cannot be satisfied, so it was never run and rotted for months.
+// What the rule actually prohibits is narrower, and is what is checked here.
+describe("Lingui React macro migration", () => {
+ it("never imports the non-contextual `t` from @lingui/core/macro", () => {
+ // No `runtimeConfigModule` is configured, so this `t` would resolve against
+ // a global i18n instance rather than the request's.
+ const offenders = collectFiles(appRoot).filter((filePath) =>
+ /import\s*\{[^}]*\bt\b[^}]*\}\s*from\s*['"]@lingui\/core\/macro['"]/.test(
+ readFileSync(filePath, "utf8")
+ )
+ );
- if (
- source.includes('@lingui/core/macro') ||
- source.includes("from '@lingui/core/macro'") ||
- source.includes("_(msg") ||
- source.includes("t(msg(")
- ) {
- offenders.push(relativePath);
- }
+ expect(offenders.map(relative)).toEqual([]);
+ });
- if (
- source.includes("useLingui") &&
- (source.includes('from "@lingui/react"') ||
- source.includes("from '@lingui/react'"))
- ) {
- offenders.push(relativePath);
- }
- }
+ it("does not unwrap a literal `msg` at runtime instead of using `t`", () => {
+ // `i18n._(msg`Scrap`)` is the long way round to `t`Scrap``. Rendering a
+ // descriptor built ELSEWHERE — `i18n._(someDescriptor)` from a lookup map —
+ // is legitimate and deliberately not matched here.
+ const offenders = collectFiles(appRoot).filter((filePath) => {
+ const source = readFileSync(filePath, "utf8");
+ return /[._]\(\s*msg`/.test(source) || source.includes("t(msg(");
+ });
- expect(offenders).toEqual([]);
+ expect(offenders.map(relative)).toEqual([]);
});
});
diff --git a/apps/erp/test/localized-submodule-ui.test.ts b/apps/erp/test/localized-submodule-ui.test.ts
index f846c53160..1d88d721a9 100644
--- a/apps/erp/test/localized-submodule-ui.test.ts
+++ b/apps/erp/test/localized-submodule-ui.test.ts
@@ -54,7 +54,11 @@ const forbiddenPatterns: Array<{ pattern: RegExp; description: string }> = [
description: "raw header aria label"
},
{
- pattern: /<CardAttributeLabel>[^<{]+<\/CardAttributeLabel>/g,
+ // Requires a non-whitespace character: once the `<Trans>` children are
+ // stripped above, a correctly localized label is left as an element
+ // containing only the newline and indentation it was written across, and
+ // `[^<{]+` alone would match that whitespace and report it as raw.
+ pattern: /<CardAttributeLabel>\s*[^<{\s][^<{]*<\/CardAttributeLabel>/g,
description: "raw card attribute label"
},
{
@@ -70,9 +74,21 @@ describe("localized sales and invoicing submodule UI", () => {
for (const relativePath of files) {
const source = readFileSync(join(root, relativePath), "utf8");
- const sanitizedSource = source.replace(/\/\*[\s\S]*?\*\//g, "");
+ const sanitizedSource = source
+ .replace(/\/\*[\s\S]*?\*\//g, "")
+ // Strip already-localized JSX before scanning. The `>Label<` patterns
+ // below cannot see element boundaries, and `<Trans>Edit</Trans>`
+ // literally contains `>Edit<` — so without this every correctly
+ // localized label reported itself as a raw one, and the suite could
+ // only be satisfied by UNDOING the localization it exists to enforce.
+ .replace(/<Trans[^>]*>[\s\S]*?<\/Trans>/g, "");
for (const { pattern, description } of forbiddenPatterns) {
+ // `RegExp.test` on a /g regex advances `lastIndex` and the object is
+ // shared across every file in this loop, so a match in one file made
+ // the next file start mid-string and silently under-report. Reset per
+ // use rather than dropping the /g flag, which the descriptions rely on.
+ pattern.lastIndex = 0;
if (pattern.test(sanitizedSource)) {
offenders.push(`${relativePath}: ${description}`);
}
diff --git a/docs/content/docs/reference/accounting.mdx b/docs/content/docs/reference/accounting.mdx
index f461babe68..19321ab44c 100644
--- a/docs/content/docs/reference/accounting.mdx
+++ b/docs/content/docs/reference/accounting.mdx
@@ -20,7 +20,7 @@ Every <Term id="posting">posting</Term> is a **<Term>journal</Term>** with balan
| Source type | Posted by |
| --- | --- |
| Sales Shipment | Posting a shipment: relieves inventory to COGS. |
-| Sales Invoice | Posting a sales invoice: receivable against revenue. |
+| Sales Invoice | Posting a sales invoice: receivable against sales revenue, shipping revenue, and sales tax payable, on separate lines. |
| Purchase Receipt | Posting a receipt: inventory or WIP against GR/IR. |
| Purchase Invoice | Posting a supplier bill: payables, clearing GR/IR. |
| Inventory Adjustment | Manual adjustments and inventory count variances: stock gains and losses against the inventory adjustment account. |
@@ -38,9 +38,13 @@ Carbon resolves the accounts to post to from a **single company-level set of def
| Work in process | Cost accumulating on open jobs. |
| Cost of goods sold | Cost relieved when goods are sold. |
| Accounts receivable / payable | Customer and supplier balances. |
+| Sales | Revenue from goods and services sold. |
+| Shipping revenue | Shipping charged to the customer — its own revenue leaf, never the sales account. |
| Goods received, not invoiced | The accrual between receiving goods and being billed for them. |
| Variance | Differences swept at job close or from purchase price. |
+A sales invoice line splits its charge three ways rather than folding everything into revenue: the line's own shipping plus its share of any header-level shipping credits the **shipping revenue** account, tax credits **sales tax payable**, and merchandise and add-ons credit the **sales** account. The two revenue defaults must be distinct accounts — posting refuses a line that would credit shipping to the sales account. A new company seeds account **4040 "Shipping Revenue"** under Revenue and points the default at it; a company joining an existing group inherits that group's shipping default instead.
+
## Dimensions
A journal line can be tagged with **dimensions**: location, department, cost center, item posting group, work center, process, fixed-asset class. The same handful of accounts can then be sliced for reporting without multiplying the chart of accounts.
diff --git a/docs/content/docs/reference/payments.mdx b/docs/content/docs/reference/payments.mdx
index 9d45b982c6..74df4f82cf 100644
--- a/docs/content/docs/reference/payments.mdx
+++ b/docs/content/docs/reference/payments.mdx
@@ -45,14 +45,17 @@ Cash and memos both settle open items through one primitive: the **invoice settl
<FieldTable>
<Field name="source" type="payment XOR memo">Exactly one of a `paymentId` (cash) or a `memoId` (memo) funds the settlement.</Field>
+ <Field name="sourcePaymentId" type="payment">A *prior* posted payment supplying on-account credit. `NULL` means the row is funded by the applying payment's own cash. Either way `paymentId` stays the applying and voiding owner, so a credit-funded row can only sit on a cash payment, never on a memo.</Field>
<Field name="target" type="one of three">Exactly one of a sales invoice, a purchase invoice, or a memo. (A balance-increasing memo is itself an open item, settled by targeting it.)</Field>
- <Field name="appliedAmount">Principal that reduces the target's balance.</Field>
- <Field name="discountAmount">An early-payment discount you're granting. **Cash payments only** — a memo-sourced settlement can't carry one.</Field>
- <Field name="writeOffAmount">A remainder you're forgiving to the write-off account. **Cash payments only.**</Field>
+ <Field name="sourceAmount">Principal consumed **in the funding source's document currency**, stored independently of `appliedAmount`.</Field>
+ <Field name="appliedAmount">Target-document principal relieved, **in company base currency**.</Field>
+ <Field name="discountAmount">An early-payment discount you're granting, in **base currency**. **Cash payments only** — a memo-sourced settlement can't carry one.</Field>
+ <Field name="writeOffAmount">A remainder you're forgiving to the write-off account, in **base currency**. **Cash payments only.**</Field>
+ <Field name="fxGainLossAmount">The realized FX this one application books, in **base currency**: positive is a gain, negative a loss. Server-calculated at posting, never entered.</Field>
<Field name="appliedDate">When the application takes effect.</Field>
</FieldTable>
-At least one of applied, discount, or write-off must be positive. An AR source only settles AR targets for the same counterparty, and an AP source only settles AP targets — the posting functions enforce party and side consistency (a Receipt rejects purchase invoices, a Disbursement rejects sales invoices, and a payment can only settle its own party's invoices).
+A settlement row has to move something: either applied, discount, and write-off sum to more than zero, or the row consumes a positive `sourceAmount`. An AR source only settles AR targets for the same counterparty, and an AP source only settles AP targets — the posting functions enforce party and side consistency (a Receipt rejects purchase invoices, a Disbursement rejects sales invoices, and a payment can only settle its own party's invoices).
<Callout type="note">
Settlements are **staged while their source is Draft** and only go live when it posts. This includes a memo-sourced "apply credit" made through a payment: even though the memo itself is posted, its credit application is tied to the payment applying it and doesn't count until *that* payment posts — so the composer stays consistent with cash applications.
@@ -74,8 +77,8 @@ Only a **Draft** can be deleted; a **Posted** payment or memo must be voided ins
Posting only touches the ledger when accounting is enabled for the company; otherwise the document still moves to **Posted** and its settlements still apply, but no journal is written.
-- **A payment** books the **bank account** against the **AR or AP control account** (receivables for a customer, payables for a supplier), split per application. Each settlement's discount goes to the discount account and its write-off to the write-off account. A single realized-FX plug reconciles the base-currency difference when the payment's rate differs from the invoice's, to the realized exchange gain or loss account.
-- **A memo** books a balanced two-line entry: the **control account** against the derived **reason account**. Applying a balance-reducing memo to an invoice afterward is GL-neutral — both sit in AR/AP — except for any realized FX.
+- **A payment** books the **bank account** against the **AR or AP control account** (receivables for a customer, payables for a supplier), split per application. Each settlement's discount goes to the discount account and its write-off to the write-off account. Realized FX is computed **per application** — the carrying value released from the funding source, less the base principal relieved on the target — and stored on that settlement row as `fxGainLossAmount`. The journal then books the **net** of those to the realized exchange gain or loss account as one line.
+- **A memo** books a balanced two-line entry: the **control account** against the derived **reason account**. Applying a balance-reducing memo to an invoice afterward is GL-neutral — both sit in AR/AP — and realizes no FX, because Carbon only lets you apply a credit whose exchange rate matches the invoice's.
Every payment and memo journal line is tagged with the counterparty's type and entity dimensions, so AR and AP can be reported by customer or supplier. Voiding emits a paired reversing journal rather than mutating the original, and carries the same dimensions so dimension-filtered balances net to zero. See [Accounting & the ledger](/docs/reference/accounting) for where these entries land.
diff --git a/packages/checks/src/conformance/baseline.json b/packages/checks/src/conformance/baseline.json
index c867fee5da..9376788900 100644
--- a/packages/checks/src/conformance/baseline.json
+++ b/packages/checks/src/conformance/baseline.json
@@ -498,8 +498,6 @@
"no-raw-rounding::packages/documents/src/pdf/components/labelGeometry.ts::const qrModuleSize = Math.max(2, Math.min(8, Math.round(4 * scale)));",
"no-raw-rounding::packages/ee/src/accounting/core/document-costing.ts::(sum, line) => sum + Math.round(line.amount * 100),",
"no-raw-rounding::packages/ee/src/accounting/core/document-costing.ts::const targetCents = Math.round(baseTotalCents / exchangeRate);",
- "no-raw-rounding::packages/ee/src/accounting/core/payment-application.ts::const settledCents = Math.round(args.settledTotal * 100);",
- "no-raw-rounding::packages/ee/src/accounting/core/payment-application.ts::const totalCents = Math.round(args.invoiceTotal * 100);",
"no-raw-rounding::packages/ee/src/accounting/core/posting.ts::(centsByAccount.get(key) ?? 0) + Math.round(line.amount * 100)",
"no-raw-rounding::packages/ee/src/accounting/core/posting.ts::(sum, line) => sum + Math.round(line.amount * 100),",
"no-raw-rounding::packages/ee/src/accounting/core/posting.ts::const cents = Math.round(line.amount * 100);",
diff --git a/packages/database/src/swagger-docs-schema.ts b/packages/database/src/swagger-docs-schema.ts
index e2e8557b9d..c86fc71310 100644
--- a/packages/database/src/swagger-docs-schema.ts
+++ b/packages/database/src/swagger-docs-schema.ts
@@ -24267,6 +24267,9 @@ export default {
{
$ref: "#/parameters/rowFilter.kanbans.jobId"
},
+ {
+ $ref: "#/parameters/rowFilter.kanbans.fromStorageUnitId"
+ },
{
$ref: "#/parameters/rowFilter.kanbans.name"
},
@@ -24282,6 +24285,9 @@ export default {
{
$ref: "#/parameters/rowFilter.kanbans.storageUnitName"
},
+ {
+ $ref: "#/parameters/rowFilter.kanbans.fromStorageUnitName"
+ },
{
$ref: "#/parameters/rowFilter.kanbans.supplierName"
},
@@ -38427,6 +38433,9 @@ export default {
{
$ref: "#/parameters/rowFilter.accountDefault.intercompanyPayablesAccount"
},
+ {
+ $ref: "#/parameters/rowFilter.accountDefault.salesShippingRevenueAccount"
+ },
{
$ref: "#/parameters/select"
},
@@ -38645,6 +38654,9 @@ export default {
{
$ref: "#/parameters/rowFilter.accountDefault.intercompanyPayablesAccount"
},
+ {
+ $ref: "#/parameters/rowFilter.accountDefault.salesShippingRevenueAccount"
+ },
{
$ref: "#/parameters/preferReturn"
}
@@ -38817,6 +38829,9 @@ export default {
{
$ref: "#/parameters/rowFilter.accountDefault.intercompanyPayablesAccount"
},
+ {
+ $ref: "#/parameters/rowFilter.accountDefault.salesShippingRevenueAccount"
+ },
{
$ref: "#/parameters/body.accountDefault"
},
@@ -75066,6 +75081,12 @@ export default {
{
$ref: "#/parameters/rowFilter.invoiceSettlement.updatedBy"
},
+ {
+ $ref: "#/parameters/rowFilter.invoiceSettlement.sourcePaymentId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.invoiceSettlement.sourceAmount"
+ },
{
$ref: "#/parameters/select"
},
@@ -75179,6 +75200,12 @@ export default {
{
$ref: "#/parameters/rowFilter.invoiceSettlement.updatedBy"
},
+ {
+ $ref: "#/parameters/rowFilter.invoiceSettlement.sourcePaymentId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.invoiceSettlement.sourceAmount"
+ },
{
$ref: "#/parameters/preferReturn"
}
@@ -75246,6 +75273,12 @@ export default {
{
$ref: "#/parameters/rowFilter.invoiceSettlement.updatedBy"
},
+ {
+ $ref: "#/parameters/rowFilter.invoiceSettlement.sourcePaymentId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.invoiceSettlement.sourceAmount"
+ },
{
$ref: "#/parameters/body.invoiceSettlement"
},
@@ -88911,6 +88944,9 @@ export default {
{
$ref: "#/parameters/rowFilter.kanban.jobId"
},
+ {
+ $ref: "#/parameters/rowFilter.kanban.fromStorageUnitId"
+ },
{
$ref: "#/parameters/select"
},
@@ -89024,6 +89060,9 @@ export default {
{
$ref: "#/parameters/rowFilter.kanban.jobId"
},
+ {
+ $ref: "#/parameters/rowFilter.kanban.fromStorageUnitId"
+ },
{
$ref: "#/parameters/preferReturn"
}
@@ -89091,6 +89130,9 @@ export default {
{
$ref: "#/parameters/rowFilter.kanban.jobId"
},
+ {
+ $ref: "#/parameters/rowFilter.kanban.fromStorageUnitId"
+ },
{
$ref: "#/parameters/body.kanban"
},
@@ -94237,6 +94279,69 @@ export default {
tags: ["(rpc) sync_create_make_method_related_records"]
}
},
+ "/rpc/accounting_round_internal": {
+ get: {
+ parameters: [
+ {
+ format: "numeric",
+ in: "query",
+ name: "_value",
+ required: true,
+ type: "number"
+ }
+ ],
+ produces: [
+ "application/json",
+ "application/vnd.pgrst.object+json;nulls=stripped",
+ "application/vnd.pgrst.object+json"
+ ],
+ responses: {
+ "200": {
+ description: "OK"
+ }
+ },
+ summary:
+ 'Rounds a value-bearing number to the internal precision scale (SCALE = 5). The one named SQL boundary for internal-scale rounding; settlement amounts round at currency."decimalPlaces" instead.',
+ tags: ["(rpc) accounting_round_internal"]
+ },
+ post: {
+ parameters: [
+ {
+ in: "body",
+ name: "args",
+ required: true,
+ schema: {
+ description:
+ 'Rounds a value-bearing number to the internal precision scale (SCALE = 5). The one named SQL boundary for internal-scale rounding; settlement amounts round at currency."decimalPlaces" instead.',
+ properties: {
+ _value: {
+ format: "numeric",
+ type: "number"
+ }
+ },
+ required: ["_value"],
+ type: "object"
+ }
+ },
+ {
+ $ref: "#/parameters/preferParams"
+ }
+ ],
+ produces: [
+ "application/json",
+ "application/vnd.pgrst.object+json;nulls=stripped",
+ "application/vnd.pgrst.object+json"
+ ],
+ responses: {
+ "200": {
+ description: "OK"
+ }
+ },
+ summary:
+ 'Rounds a value-bearing number to the internal precision scale (SCALE = 5). The one named SQL boundary for internal-scale rounding; settlement amounts round at currency."decimalPlaces" instead.',
+ tags: ["(rpc) accounting_round_internal"]
+ }
+ },
"/rpc/get_entity_audit_log": {
post: {
parameters: [
@@ -108133,6 +108238,8 @@ export default {
type: "number"
},
amount: {
+ description:
+ "Memo amount in memo currency; divide by foreign-per-base exchangeRate for company base.",
format: "numeric",
type: "number"
},
@@ -109715,6 +109822,8 @@ export default {
type: "number"
},
totalAmount: {
+ description:
+ "Gross cash amount in payment currency; divide by foreign-per-base exchangeRate for company base.",
format: "numeric",
type: "number"
},
@@ -112236,8 +112345,8 @@ export default {
type: "string"
},
replenishmentSystem: {
- enum: ["Buy", "Make", "Buy and Make"],
- format: 'public."itemReplenishmentSystem"',
+ enum: ["Buy", "Make", "Transfer"],
+ format: 'public."kanbanReplenishmentSystem"',
type: "string"
},
quantity: {
@@ -112312,6 +112421,12 @@ export default {
format: "text",
type: "string"
},
+ fromStorageUnitId: {
+ description:
+ "Note:\nThis is a Foreign Key to `storageUnit.id`.<fk table='storageUnit' column='id'/>",
+ format: "text",
+ type: "string"
+ },
name: {
format: "text",
type: "string"
@@ -112332,6 +112447,10 @@ export default {
format: "text",
type: "string"
},
+ fromStorageUnitName: {
+ format: "text",
+ type: "string"
+ },
supplierName: {
format: "text",
type: "string"
@@ -119260,6 +119379,12 @@ export default {
"Note:\nThis is a Foreign Key to `account.id`.<fk table='account' column='id'/>",
format: "text",
type: "string"
+ },
+ salesShippingRevenueAccount: {
+ description:
+ "Revenue account for shipping charged to customers; account belongs to the company group.\n\nNote:\nThis is a Foreign Key to `account.id`.<fk table='account' column='id'/>",
+ format: "text",
+ type: "string"
}
},
type: "object"
@@ -136314,6 +136439,7 @@ export default {
"writeOffAmount",
"sourceExchangeRate",
"targetExchangeRate",
+ "fxGainLossAmount",
"appliedDate",
"companyId",
"createdBy",
@@ -136357,16 +136483,22 @@ export default {
type: "string"
},
appliedAmount: {
+ description:
+ "Target-document principal relieved in company base currency.",
format: "numeric",
type: "number"
},
discountAmount: {
default: 0,
+ description:
+ "Target-document discount relief in company base currency.",
format: "numeric",
type: "number"
},
writeOffAmount: {
default: 0,
+ description:
+ "Target-document write-off relief in company base currency.",
format: "numeric",
type: "number"
},
@@ -136379,6 +136511,9 @@ export default {
type: "number"
},
fxGainLossAmount: {
+ default: 0,
+ description:
+ "Server-calculated posting snapshot in company base currency: positive gain, negative loss.",
format: "numeric",
type: "number"
},
@@ -136414,6 +136549,18 @@ export default {
"Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",
format: "text",
type: "string"
+ },
+ sourcePaymentId: {
+ description:
+ "Prior posted payment supplying on-account credit; paymentId remains the applying/void owner. NULL means current payment cash.",
+ format: "text",
+ type: "string"
+ },
+ sourceAmount: {
+ description:
+ "Principal consumed in the funding source document currency, stored independently of target-base appliedAmount.",
+ format: "numeric",
+ type: "number"
}
},
type: "object"
@@ -143040,8 +143187,8 @@ export default {
},
replenishmentSystem: {
default: "Buy",
- enum: ["Buy", "Make", "Buy and Make"],
- format: 'public."itemReplenishmentSystem"',
+ enum: ["Buy", "Make", "Transfer"],
+ format: 'public."kanbanReplenishmentSystem"',
type: "string"
},
quantity: {
@@ -143119,6 +143266,12 @@ export default {
"Note:\nThis is a Foreign Key to `job.id`.<fk table='job' column='id'/>",
format: "text",
type: "string"
+ },
+ fromStorageUnitId: {
+ description:
+ "Note:\nThis is a Foreign Key to `storageUnit.id`.<fk table='storageUnit' column='id'/>",
+ format: "text",
+ type: "string"
}
},
type: "object"
@@ -151377,6 +151530,8 @@ export default {
},
"rowFilter.memo.amount": {
name: "amount",
+ description:
+ "Memo amount in memo currency; divide by foreign-per-base exchangeRate for company base.",
required: false,
in: "query",
type: "string"
@@ -153168,6 +153323,8 @@ export default {
},
"rowFilter.payment.totalAmount": {
name: "totalAmount",
+ description:
+ "Gross cash amount in payment currency; divide by foreign-per-base exchangeRate for company base.",
required: false,
in: "query",
type: "string"
@@ -156085,6 +156242,12 @@ export default {
in: "query",
type: "string"
},
+ "rowFilter.kanbans.fromStorageUnitId": {
+ name: "fromStorageUnitId",
+ required: false,
+ in: "query",
+ type: "string"
+ },
"rowFilter.kanbans.name": {
name: "name",
required: false,
@@ -156115,6 +156278,12 @@ export default {
in: "query",
type: "string"
},
+ "rowFilter.kanbans.fromStorageUnitName": {
+ name: "fromStorageUnitName",
+ required: false,
+ in: "query",
+ type: "string"
+ },
"rowFilter.kanbans.supplierName": {
name: "supplierName",
required: false,
@@ -163814,6 +163983,14 @@ export default {
in: "query",
type: "string"
},
+ "rowFilter.accountDefault.salesShippingRevenueAccount": {
+ name: "salesShippingRevenueAccount",
+ description:
+ "Revenue account for shipping charged to customers; account belongs to the company group.",
+ required: false,
+ in: "query",
+ type: "string"
+ },
"body.warehouse": {
name: "warehouse",
description: "warehouse",
@@ -182861,18 +183038,22 @@ export default {
},
"rowFilter.invoiceSettlement.appliedAmount": {
name: "appliedAmount",
+ description:
+ "Target-document principal relieved in company base currency.",
required: false,
in: "query",
type: "string"
},
"rowFilter.invoiceSettlement.discountAmount": {
name: "discountAmount",
+ description: "Target-document discount relief in company base currency.",
required: false,
in: "query",
type: "string"
},
"rowFilter.invoiceSettlement.writeOffAmount": {
name: "writeOffAmount",
+ description: "Target-document write-off relief in company base currency.",
required: false,
in: "query",
type: "string"
@@ -182891,6 +183072,8 @@ export default {
},
"rowFilter.invoiceSettlement.fxGainLossAmount": {
name: "fxGainLossAmount",
+ description:
+ "Server-calculated posting snapshot in company base currency: positive gain, negative loss.",
required: false,
in: "query",
type: "string"
@@ -182931,6 +183114,22 @@ export default {
in: "query",
type: "string"
},
+ "rowFilter.invoiceSettlement.sourcePaymentId": {
+ name: "sourcePaymentId",
+ description:
+ "Prior posted payment supplying on-account credit; paymentId remains the applying/void owner. NULL means current payment cash.",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.invoiceSettlement.sourceAmount": {
+ name: "sourceAmount",
+ description:
+ "Principal consumed in the funding source document currency, stored independently of target-base appliedAmount.",
+ required: false,
+ in: "query",
+ type: "string"
+ },
"body.printerRoute": {
name: "printerRoute",
description: "printerRoute",
@@ -190323,6 +190522,12 @@ export default {
in: "query",
type: "string"
},
+ "rowFilter.kanban.fromStorageUnitId": {
+ name: "fromStorageUnitId",
+ required: false,
+ in: "query",
+ type: "string"
+ },
"body.salesOrderTransaction": {
name: "salesOrderTransaction",
description: "salesOrderTransaction",
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index 16cb277bce..60b748981e 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -393,6 +393,7 @@ export type Database = {
roundingAccount: string
salesAccount: string
salesDiscountAccount: string
+ salesShippingRevenueAccount: string | null
salesTaxPayableAccount: string
scrapAccount: string | null
serviceChargeAccount: string
@@ -448,6 +449,7 @@ export type Database = {
roundingAccount: string
salesAccount: string
salesDiscountAccount: string
+ salesShippingRevenueAccount?: string | null
salesTaxPayableAccount: string
scrapAccount?: string | null
serviceChargeAccount: string
@@ -503,6 +505,7 @@ export type Database = {
roundingAccount?: string
salesAccount?: string
salesDiscountAccount?: string
+ salesShippingRevenueAccount?: string | null
salesTaxPayableAccount?: string
scrapAccount?: string | null
serviceChargeAccount?: string
@@ -1144,6 +1147,20 @@ export type Database = {
referencedRelation: "accounts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "accountDefault_salesShippingRevenueAccount_fkey"
+ columns: ["salesShippingRevenueAccount"]
+ isOneToOne: false
+ referencedRelation: "account"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "accountDefault_salesShippingRevenueAccount_fkey"
+ columns: ["salesShippingRevenueAccount"]
+ isOneToOne: false
+ referencedRelation: "accounts"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "accountDefault_salesTaxPayableAccount_fkey"
columns: ["salesTaxPayableAccount"]
@@ -19635,11 +19652,13 @@ export type Database = {
createdAt: string
createdBy: string
discountAmount: number
- fxGainLossAmount: number | null
+ fxGainLossAmount: number
id: string
memoId: string | null
paymentId: string | null
+ sourceAmount: number | null
sourceExchangeRate: number
+ sourcePaymentId: string | null
targetExchangeRate: number
targetMemoId: string | null
targetPurchaseInvoiceId: string | null
@@ -19655,11 +19674,13 @@ export type Database = {
createdAt?: string
createdBy: string
discountAmount?: number
- fxGainLossAmount?: number | null
+ fxGainLossAmount?: number
id?: string
memoId?: string | null
paymentId?: string | null
+ sourceAmount?: number | null
sourceExchangeRate: number
+ sourcePaymentId?: string | null
targetExchangeRate: number
targetMemoId?: string | null
targetPurchaseInvoiceId?: string | null
@@ -19675,11 +19696,13 @@ export type Database = {
createdAt?: string
createdBy?: string
discountAmount?: number
- fxGainLossAmount?: number | null
+ fxGainLossAmount?: number
id?: string
memoId?: string | null
paymentId?: string | null
+ sourceAmount?: number | null
sourceExchangeRate?: number
+ sourcePaymentId?: string | null
targetExchangeRate?: number
targetMemoId?: string | null
targetPurchaseInvoiceId?: string | null
@@ -19772,6 +19795,13 @@ export type Database = {
referencedRelation: "payment"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "invoiceSettlement_sourcePaymentId_companyId_fkey"
+ columns: ["sourcePaymentId", "companyId"]
+ isOneToOne: false
+ referencedRelation: "payment"
+ referencedColumns: ["id", "companyId"]
+ },
{
foreignKeyName: "invoiceSettlement_targetMemoId_fkey"
columns: ["targetMemoId"]
@@ -68681,14 +68711,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"]
@@ -70346,14 +70376,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"]
@@ -77678,6 +77708,7 @@ export type Database = {
}
Functions: {
_xid_machine_id: { Args: never; Returns: number }
+ accounting_round_internal: { Args: { _value: number }; Returns: number }
accountTreeBalancePeriodSeries: {
Args: {
p_company_group_id: string
diff --git a/packages/database/supabase/functions/deno.json b/packages/database/supabase/functions/deno.json
index 8932605604..d696b220bb 100644
--- a/packages/database/supabase/functions/deno.json
+++ b/packages/database/supabase/functions/deno.json
@@ -1,7 +1,8 @@
{
"lock": false,
"tasks": {
- "test": "deno test --no-lock",
+ "test": "deno test --no-lock --no-check",
+ "test:db": "deno test --no-lock --no-check --allow-env --allow-net --allow-read --allow-sys",
"check:response": "deno check --no-lock lib/response.ts lib/response.test.ts"
},
"imports": {
diff --git a/packages/database/supabase/functions/lib/response.test.ts b/packages/database/supabase/functions/lib/response.test.ts
index a59b378c34..3df5834221 100644
--- a/packages/database/supabase/functions/lib/response.test.ts
+++ b/packages/database/supabase/functions/lib/response.test.ts
@@ -120,12 +120,45 @@ Deno.test("sanitizer suppresses node-pg-shaped error", async () => {
assertEquals(await errorResponse(err).json(), {});
});
-Deno.test("sanitizer suppresses ZodError", async () => {
+// A ZodError's raw `.message` is a JSON dump, so `isDataLayerError` still blocks
+// it — but a payload-validation failure is the CALLER's input contract, not a
+// data-layer leak. `zodIssueSummary` replaces it with a compact `path: message`
+// summary so an API caller has something to converge on; suppressing it entirely
+// left them with only the service's generic fallback string.
+Deno.test("ZodError is replaced by a compact issue summary, never its raw dump", async () => {
const err = Object.assign(new Error("[{...}]"), {
name: "ZodError",
issues: [{ path: [], message: "x" }],
});
assert(isDataLayerError(err));
+ const body = await errorResponse(err).json();
+ assertEquals(body, { message: "Invalid payload — x" });
+ assert(!body.message.includes("[{...}]"));
+});
+
+Deno.test("ZodError summary names the offending field and caps at five issues", async () => {
+ const err = Object.assign(new Error("[{...}]"), {
+ name: "ZodError",
+ issues: Array.from({ length: 7 }, (_, i) => ({
+ path: ["body", `field${i}`],
+ message: "Required",
+ })),
+ });
+ const { message } = await errorResponse(err).json();
+ assertEquals(
+ message,
+ "Invalid payload — body.field0: Required; body.field1: Required; " +
+ "body.field2: Required; body.field3: Required; body.field4: Required; +2 more",
+ );
+});
+
+Deno.test("a ZodError with no issues omits the message key entirely", async () => {
+ const err = Object.assign(new Error("[{...}]"), {
+ name: "ZodError",
+ issues: [],
+ });
+ // `getEdgeFunctionErrorMessage` falls back to the caller's own copy when the
+ // key is absent, so an empty summary must not ship an empty string.
assertEquals(await errorResponse(err).json(), {});
});
diff --git a/packages/database/supabase/functions/lib/seed.data.ts b/packages/database/supabase/functions/lib/seed.data.ts
index 3a3460d8b7..537dfa8b94 100644
--- a/packages/database/supabase/functions/lib/seed.data.ts
+++ b/packages/database/supabase/functions/lib/seed.data.ts
@@ -709,6 +709,7 @@ export const accounts = [
{ key: "4020", number: "4020", name: "Sales Discounts", isGroup: false, parentKey: "revenue", accountType: "Income", incomeBalance: "Income Statement", class: "Revenue", consolidatedRate: "Average", createdBy: "system" },
{ key: "4030", number: "4030", name: "Manufacturing Services Revenue", isGroup: false, parentKey: "revenue", accountType: "Income", incomeBalance: "Income Statement", class: "Revenue", consolidatedRate: "Average", createdBy: "system" },
{ key: "4040", number: "4040", name: "Customer Payment Discounts", isGroup: false, parentKey: "revenue", accountType: "Income", incomeBalance: "Income Statement", class: "Revenue", consolidatedRate: "Average", createdBy: "system" },
+ { key: "4050", number: "4050", name: "Shipping Revenue", isGroup: false, parentKey: "revenue", accountType: "Income", incomeBalance: "Income Statement", class: "Revenue", consolidatedRate: "Average", createdBy: "system" },
// Other Income
{ key: "other-income", number: null, name: "Other Income", isGroup: true, parentKey: "income-statement", accountType: "Other Income", incomeBalance: "Income Statement", class: "Revenue", consolidatedRate: "Average", createdBy: "system" },
@@ -771,6 +772,7 @@ export const accounts = [
export const accountDefaults = {
salesAccount: "4010",
+ salesShippingRevenueAccount: "4050",
salesDiscountAccount: "4020",
costOfGoodsSoldAccount: "5010",
purchaseVarianceAccount: "5210",
diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.ts
index 16cb277bce..60b748981e 100644
--- a/packages/database/supabase/functions/lib/types.ts
+++ b/packages/database/supabase/functions/lib/types.ts
@@ -393,6 +393,7 @@ export type Database = {
roundingAccount: string
salesAccount: string
salesDiscountAccount: string
+ salesShippingRevenueAccount: string | null
salesTaxPayableAccount: string
scrapAccount: string | null
serviceChargeAccount: string
@@ -448,6 +449,7 @@ export type Database = {
roundingAccount: string
salesAccount: string
salesDiscountAccount: string
+ salesShippingRevenueAccount?: string | null
salesTaxPayableAccount: string
scrapAccount?: string | null
serviceChargeAccount: string
@@ -503,6 +505,7 @@ export type Database = {
roundingAccount?: string
salesAccount?: string
salesDiscountAccount?: string
+ salesShippingRevenueAccount?: string | null
salesTaxPayableAccount?: string
scrapAccount?: string | null
serviceChargeAccount?: string
@@ -1144,6 +1147,20 @@ export type Database = {
referencedRelation: "accounts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "accountDefault_salesShippingRevenueAccount_fkey"
+ columns: ["salesShippingRevenueAccount"]
+ isOneToOne: false
+ referencedRelation: "account"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "accountDefault_salesShippingRevenueAccount_fkey"
+ columns: ["salesShippingRevenueAccount"]
+ isOneToOne: false
+ referencedRelation: "accounts"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "accountDefault_salesTaxPayableAccount_fkey"
columns: ["salesTaxPayableAccount"]
@@ -19635,11 +19652,13 @@ export type Database = {
createdAt: string
createdBy: string
discountAmount: number
- fxGainLossAmount: number | null
+ fxGainLossAmount: number
id: string
memoId: string | null
paymentId: string | null
+ sourceAmount: number | null
sourceExchangeRate: number
+ sourcePaymentId: string | null
targetExchangeRate: number
targetMemoId: string | null
targetPurchaseInvoiceId: string | null
@@ -19655,11 +19674,13 @@ export type Database = {
createdAt?: string
createdBy: string
discountAmount?: number
- fxGainLossAmount?: number | null
+ fxGainLossAmount?: number
id?: string
memoId?: string | null
paymentId?: string | null
+ sourceAmount?: number | null
sourceExchangeRate: number
+ sourcePaymentId?: string | null
targetExchangeRate: number
targetMemoId?: string | null
targetPurchaseInvoiceId?: string | null
@@ -19675,11 +19696,13 @@ export type Database = {
createdAt?: string
createdBy?: string
discountAmount?: number
- fxGainLossAmount?: number | null
+ fxGainLossAmount?: number
id?: string
memoId?: string | null
paymentId?: string | null
+ sourceAmount?: number | null
sourceExchangeRate?: number
+ sourcePaymentId?: string | null
targetExchangeRate?: number
targetMemoId?: string | null
targetPurchaseInvoiceId?: string | null
@@ -19772,6 +19795,13 @@ export type Database = {
referencedRelation: "payment"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "invoiceSettlement_sourcePaymentId_companyId_fkey"
+ columns: ["sourcePaymentId", "companyId"]
+ isOneToOne: false
+ referencedRelation: "payment"
+ referencedColumns: ["id", "companyId"]
+ },
{
foreignKeyName: "invoiceSettlement_targetMemoId_fkey"
columns: ["targetMemoId"]
@@ -68681,14 +68711,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"]
@@ -70346,14 +70376,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"]
@@ -77678,6 +77708,7 @@ export type Database = {
}
Functions: {
_xid_machine_id: { Args: never; Returns: number }
+ accounting_round_internal: { Args: { _value: number }; Returns: number }
accountTreeBalancePeriodSeries: {
Args: {
p_company_group_id: string
diff --git a/packages/database/supabase/functions/post-memo/build-memo-journal.ts b/packages/database/supabase/functions/post-memo/build-memo-journal.ts
index 8bbb5c2ffb..3124385141 100644
--- a/packages/database/supabase/functions/post-memo/build-memo-journal.ts
+++ b/packages/database/supabase/functions/post-memo/build-memo-journal.ts
@@ -24,7 +24,8 @@
// memo — a separate payment posting). Both legs use the same base amount, so the
// entry balances exactly.
-import { assertBalanced, round } from "../shared/precision.ts";
+import { assertBalanced } from "../shared/precision.ts";
+import { toBaseAmount } from "../shared/accounting-currency.ts";
import { accountTypeFromClass, credit, debit } from "../lib/utils.ts";
type AccountType = "asset" | "liability" | "equity" | "revenue" | "expense";
@@ -51,8 +52,9 @@ export interface BuildMemoJournalInput {
// customer (AR) vs supplier (AP). Drives control account TYPE (asset/liability).
isAR: boolean;
direction: "Credit" | "Debit";
- // memo.amount × memo.exchangeRate (base currency).
- amountBase: number;
+ // Memo principal in document currency and its foreign-per-base snapshot.
+ amount: number;
+ exchangeRate: number;
// Resolved once by the driver (nanoid) so this stays pure.
journalLineReference: string;
// receivables (AR) / payables (AP) control account.
@@ -72,14 +74,15 @@ export interface BuildMemoJournalResult {
const BALANCE_TOLERANCE = 0.01;
export function buildMemoJournal(
- input: BuildMemoJournalInput
+ input: BuildMemoJournalInput,
): BuildMemoJournalResult {
const {
memoId,
companyId,
isAR,
direction,
- amountBase,
+ amount,
+ exchangeRate,
journalLineReference,
controlAccountId,
reasonAccountId,
@@ -88,14 +91,16 @@ export function buildMemoJournal(
if (!controlAccountId) {
throw new Error(
- `Missing ${isAR ? "receivables" : "payables"} account default; cannot post memo to GL`
+ `Missing ${
+ isAR ? "receivables" : "payables"
+ } account default; cannot post memo to GL`,
);
}
- const magnitude = round(Math.abs(amountBase));
- if (magnitude < 0.0001) {
+ if (!Number.isFinite(amount) || amount <= 0) {
throw new Error("Memo amount must be greater than 0 to post");
}
+ const magnitude = toBaseAmount(amount, exchangeRate);
const lines: MemoJournalLine[] = [];
let signedDebitTotal = 0;
@@ -104,16 +109,15 @@ export function buildMemoJournal(
side: "debit" | "credit",
accountType: AccountType,
accountId: string,
- description: string
+ description: string,
) => {
signedDebitTotal += side === "debit" ? magnitude : -magnitude;
lines.push({
accountId,
description,
- amount:
- side === "debit"
- ? debit(accountType, magnitude)
- : credit(accountType, magnitude),
+ amount: side === "debit"
+ ? debit(accountType, magnitude)
+ : credit(accountType, magnitude),
quantity: 1,
documentType: "Memo",
documentId: memoId,
@@ -132,7 +136,7 @@ export function buildMemoJournal(
controlIsDebit ? "debit" : "credit",
controlType,
controlAccountId,
- isAR ? "Accounts Receivable" : "Accounts Payable"
+ isAR ? "Accounts Receivable" : "Accounts Payable",
);
// 2) Reason leg — always the inverse side, so the entry balances.
@@ -140,7 +144,7 @@ export function buildMemoJournal(
controlIsDebit ? "credit" : "debit",
reasonType,
reasonAccountId,
- direction === "Credit" ? "Credit memo" : "Debit memo"
+ direction === "Credit" ? "Credit memo" : "Debit memo",
);
// BALANCE_TOLERANCE is a business threshold (multi-currency memos carry
@@ -149,7 +153,7 @@ export function buildMemoJournal(
signedDebitTotal,
0,
BALANCE_TOLERANCE,
- "Memo journal (base currency)"
+ "Memo journal (base currency)",
);
return { lines, signedDebitTotal };
diff --git a/packages/database/supabase/functions/post-memo/index.ts b/packages/database/supabase/functions/post-memo/index.ts
index bc058c2092..3ffa2e25b7 100644
--- a/packages/database/supabase/functions/post-memo/index.ts
+++ b/packages/database/supabase/functions/post-memo/index.ts
@@ -1,5 +1,4 @@
import { serve } from "https://deno.land/[email protected]/http/server.ts";
-import { nanoid } from "https://deno.land/x/[email protected]/mod.ts";
import z from "npm:zod@^4.5.4";
import { DB, getConnectionPool, getDatabaseClient } from "../lib/database.ts";
import { datetime, getCompanyTimeZone } from "../lib/datetime.ts";
@@ -7,10 +6,7 @@ import { getFunctionLogger } from "../lib/logging.ts";
import { corsPreflight, errorResponse, jsonResponse } from "../lib/response.ts";
import { getSupabaseServiceRole } from "../lib/supabase.ts";
-import { getCurrentAccountingPeriod } from "../shared/get-accounting-period.ts";
-import { getNextSequence } from "../shared/get-next-sequence.ts";
-import { getDefaultPostingGroup } from "../shared/get-posting-group.ts";
-import { buildMemoJournal, type MemoJournalLine } from "./build-memo-journal.ts";
+import { postMemoTransaction } from "./post-memo-transaction.ts";
const pool = getConnectionPool(1);
const db = getDatabaseClient<DB>(pool);
@@ -37,397 +33,20 @@ serve(async (req: Request) => {
const client = await getSupabaseServiceRole(
req.headers.get("Authorization"),
req.headers.get("carbon-key") ?? "",
- companyId
+ companyId,
);
- const today = datetime.today(await getCompanyTimeZone(client, companyId)).toString();
-
- const accountingSettings = await client
- .from("companySettings")
- .select("accountingEnabled")
- .eq("id", companyId)
- .single();
- const accountingEnabled =
- accountingSettings.data?.accountingEnabled ?? false;
-
- const [memo, accountDefaults] = await Promise.all([
- client.from("memo").select("*").eq("id", memoId).single(),
- getDefaultPostingGroup(client, companyId),
- ]);
-
- if (memo.error) throw new Error("Failed to fetch memo");
- if (accountingEnabled && accountDefaults.error)
- throw new Error("Failed to fetch account defaults");
-
- // isAR: a customer memo settles AR; a supplier memo settles AP.
- const isAR = memo.data.customerId != null;
-
- // --------------------------------------------------------------
- // VOID
- // --------------------------------------------------------------
- if (type === "void") {
- if (memo.data.status !== "Posted") {
- throw new Error(
- `Cannot void memo in status ${memo.data.status} (only Posted)`
- );
- }
-
- const accountingPeriodId = accountingEnabled
- ? await getCurrentAccountingPeriod(client, companyId, db, today)
- : null;
-
- await db.transaction().execute(async (trx) => {
- // Lock the memo row and re-assert it's still Posted INSIDE the
- // transaction. The status check above runs before the lock (a TOCTOU
- // window): two concurrent voids could otherwise both pass it and each
- // emit a reversing journal. The FOR UPDATE serializes them.
- const lockedMemo = await trx
- .selectFrom("memo")
- .select(["id", "status"])
- .where("id", "=", memoId)
- .where("companyId", "=", companyId)
- .forUpdate()
- .executeTakeFirst();
- if (!lockedMemo) throw new Error("Memo not found");
- if (lockedMemo.status !== "Posted") {
- throw new Error(
- `Cannot void memo in status ${lockedMemo.status} (only Posted)`
- );
- }
-
- if (accountingEnabled && memo.data.journalId) {
- // Mirror the original journal's lines into a reversing journal (the
- // same paired-journal approach post-payment/post-purchase-invoice use
- // for voids — never mutate the original).
- const originalLines = await trx
- .selectFrom("journalLine")
- .selectAll()
- .where("journalId", "=", memo.data.journalId)
- .execute();
-
- if (originalLines.length > 0) {
- const voidEntryId = await getNextSequence(
- trx,
- "journalEntry",
- companyId
- );
-
- const voidJournal = await trx
- .insertInto("journal")
- .values({
- journalEntryId: voidEntryId,
- accountingPeriodId,
- description: `VOID Memo ${memo.data.memoId}`,
- postingDate: today,
- companyId,
- sourceType:
- memo.data.direction === "Credit"
- ? "Credit Memo"
- : "Debit Memo",
- status: "Posted",
- postedAt: new Date().toISOString(),
- postedBy: userId,
- createdBy: userId,
- })
- .returning(["id"])
- .executeTakeFirstOrThrow();
-
- const voidLineResults = await trx
- .insertInto("journalLine")
- .values(
- originalLines.map((line) => ({
- journalId: voidJournal.id,
- accountId: line.accountId,
- amount: -line.amount,
- quantity: line.quantity,
- description: `VOID: ${line.description ?? ""}`,
- documentType: "Memo" as const,
- documentId: memoId,
- documentLineReference: line.documentLineReference,
- journalLineReference: line.journalLineReference,
- companyId,
- }))
- )
- .returning(["id"])
- .execute();
-
- // Carry the original lines' dimensions onto the reversing lines so
- // dimension-filtered balances net to zero after the void.
- const origDimensions = await trx
- .selectFrom("journalLineDimension")
- .select(["journalLineId", "dimensionId", "valueId"])
- .where(
- "journalLineId",
- "in",
- originalLines.map((l) => l.id)
- )
- .execute();
- if (origDimensions.length > 0) {
- const idxByOriginalId = new Map(
- originalLines.map((l, i) => [l.id, i])
- );
- await trx
- .insertInto("journalLineDimension")
- .values(
- origDimensions.map((d) => ({
- journalLineId:
- voidLineResults[idxByOriginalId.get(d.journalLineId)!].id,
- dimensionId: d.dimensionId,
- valueId: d.valueId,
- companyId,
- }))
- )
- .execute();
- }
- }
- }
-
- await trx
- .updateTable("memo")
- .set({
- status: "Voided",
- voidedAt: new Date().toISOString(),
- voidedBy: userId,
- updatedAt: new Date().toISOString(),
- updatedBy: userId,
- })
- .where("id", "=", memoId)
- .where("companyId", "=", companyId)
- .execute();
- });
-
- return jsonResponse({ success: true });
- }
-
- // --------------------------------------------------------------
- // POST
- // --------------------------------------------------------------
- if (memo.data.status !== "Draft") {
- throw new Error(
- `Cannot post memo in status ${memo.data.status} (only Draft)`
- );
- }
- if (memo.data.exchangeRate <= 0) {
- throw new Error("Memo exchange rate must be > 0");
- }
-
- const accountingPeriodId = accountingEnabled
- ? await getCurrentAccountingPeriod(client, companyId, db, today)
- : null;
-
- // Build the (balanced, two-line) journal in base currency. Account-id
- // resolution + the control/reason sign logic live in the pure
- // `buildMemoJournal` so they are unit-tested (post-memo.test.ts).
- const journalLineInserts: MemoJournalLine[] = [];
- const partyDimensions: { dimensionId: string; valueId: string }[] = [];
- // The offset ("reason") account is derived here (not a user choice) and
- // stored on the memo at posting for the audit trail / list display.
- let derivedReasonAccountId: string | null = null;
-
- if (accountingEnabled) {
- if (!accountDefaults.data) {
- throw new Error(
- "Accounting is enabled but this company has no account defaults configured"
- );
- }
- const ad = accountDefaults.data;
- const controlAccountId = isAR
- ? ad.receivablesAccount
- : ad.payablesAccount;
-
- // The offset account is deterministic by party side (NOT a user choice):
- // customer memos adjust sales (salesDiscountAccount); supplier memos adjust
- // purchases (supplierPaymentDiscountAccount). Direction only flips the
- // debit/credit side, handled inside buildMemoJournal.
- const reasonAccountId = isAR
- ? ad.salesDiscountAccount
- : ad.supplierPaymentDiscountAccount;
- if (!reasonAccountId) {
- throw new Error(
- `Missing ${
- isAR ? "salesDiscountAccount" : "supplierPaymentDiscountAccount"
- } account default; cannot post memo to GL`
- );
- }
- derivedReasonAccountId = reasonAccountId;
-
- // Resolve the reason account's class so its natural-balance amount sign is
- // correct (the account can be any class).
- const reasonAccount = await client
- .from("account")
- .select("class")
- .eq("id", reasonAccountId)
- .single();
- if (reasonAccount.error || !reasonAccount.data) {
- throw new Error("Failed to fetch the derived reason account");
- }
-
- const journalLineReference = nanoid();
- const { lines } = buildMemoJournal({
- memoId,
- companyId,
- isAR,
- direction: memo.data.direction as "Credit" | "Debit",
- amountBase: Number(memo.data.amount) * Number(memo.data.exchangeRate),
- journalLineReference,
- controlAccountId,
- reasonAccountId,
- reasonAccountClass: reasonAccount.data.class as string,
- });
- journalLineInserts.push(...lines);
-
- // Tag the journal lines with the counterparty type + entity dimensions so
- // AR/AP can be reported by counterparty (mirrors post-payment).
- const companyRecord = await client
- .from("company")
- .select("companyGroupId")
- .eq("id", companyId)
- .single();
- const companyGroupId = companyRecord.data?.companyGroupId ?? null;
- const partyId = isAR
- ? (memo.data.customerId as string | null)
- : (memo.data.supplierId as string | null);
- const typeEntityType = isAR ? "CustomerType" : "SupplierType";
- const entityEntityType = isAR ? "Customer" : "Supplier";
- if (companyGroupId && partyId) {
- const [partyRow, dimRows] = await Promise.all([
- isAR
- ? client
- .from("customer")
- .select("customerTypeId")
- .eq("id", partyId)
- .maybeSingle()
- : client
- .from("supplier")
- .select("supplierTypeId")
- .eq("id", partyId)
- .maybeSingle(),
- client
- .from("dimension")
- .select("id, entityType")
- .eq("companyGroupId", companyGroupId)
- .eq("active", true)
- .in("entityType", [typeEntityType, entityEntityType]),
- ]);
- const dimByEntityType = new Map<string, string>();
- for (const d of dimRows.data ?? []) {
- if (d.entityType) dimByEntityType.set(d.entityType, d.id);
- }
- // deno-lint-ignore no-explicit-any
- const party = partyRow.data as any;
- const partyTypeId = isAR
- ? (party?.customerTypeId ?? null)
- : (party?.supplierTypeId ?? null);
- const typeDimensionId = dimByEntityType.get(typeEntityType);
- if (typeDimensionId && partyTypeId) {
- partyDimensions.push({
- dimensionId: typeDimensionId,
- valueId: partyTypeId,
- });
- }
- const entityDimensionId = dimByEntityType.get(entityEntityType);
- if (entityDimensionId) {
- partyDimensions.push({ dimensionId: entityDimensionId, valueId: partyId });
- }
- }
- }
-
- // --------------------------------------------------------------
- // Commit: lock the memo, re-check Draft, post the journal, flip Posted.
- // Applying a memo to invoices is GL-neutral (both sit in AR/AP), so there is
- // no invoice validation here — that lives in replaceMemoSettlements.
- // --------------------------------------------------------------
- let createdJournalId: string | null = null;
- await db.transaction().execute(async (trx) => {
- const locked = await trx
- .selectFrom("memo")
- .select(["id", "status"])
- .where("id", "=", memoId)
- .where("companyId", "=", companyId)
- .forUpdate()
- .executeTakeFirst();
- if (!locked) throw new Error("Memo not found");
- if (locked.status !== "Draft") {
- throw new Error(
- `Cannot post memo in status ${locked.status} (only Draft)`
- );
- }
-
- let journalId: string | null = null;
- if (accountingEnabled) {
- const journalEntryId = await getNextSequence(
- trx,
- "journalEntry",
- companyId
- );
- const journalResult = await trx
- .insertInto("journal")
- .values({
- journalEntryId,
- accountingPeriodId,
- description: `${memo.data.direction} Memo ${memo.data.memoId}`,
- postingDate: today,
- companyId,
- sourceType:
- memo.data.direction === "Credit" ? "Credit Memo" : "Debit Memo",
- status: "Posted",
- postedAt: new Date().toISOString(),
- postedBy: userId,
- createdBy: userId,
- })
- .returning(["id"])
- .executeTakeFirstOrThrow();
- journalId = journalResult.id;
-
- if (journalLineInserts.length > 0) {
- const journalLineResults = await trx
- .insertInto("journalLine")
- .values(
- journalLineInserts.map((line) => ({
- ...line,
- journalId: journalResult.id,
- }))
- )
- .returning(["id"])
- .execute();
-
- if (partyDimensions.length > 0) {
- await trx
- .insertInto("journalLineDimension")
- .values(
- journalLineResults.flatMap((jl) =>
- partyDimensions.map((d) => ({
- journalLineId: jl.id,
- dimensionId: d.dimensionId,
- valueId: d.valueId,
- companyId,
- }))
- )
- )
- .execute();
- }
- }
- }
-
- await trx
- .updateTable("memo")
- .set({
- status: "Posted",
- postingDate: today,
- journalId,
- reasonAccount: derivedReasonAccountId,
- postedAt: new Date().toISOString(),
- postedBy: userId,
- updatedAt: new Date().toISOString(),
- updatedBy: userId,
- })
- .where("id", "=", memoId)
- .where("companyId", "=", companyId)
- .execute();
-
- createdJournalId = journalId;
+ const today = datetime.today(await getCompanyTimeZone(client, companyId))
+ .toString();
+
+ const result = await postMemoTransaction(db, {
+ type,
+ memoId,
+ userId,
+ companyId,
+ today,
+ client,
});
-
- return jsonResponse({ success: true, journalId: createdJournalId });
+ return jsonResponse({ success: true, ...result });
} catch (err) {
return errorResponse(err, 500);
}
diff --git a/packages/database/supabase/functions/post-memo/post-memo-transaction.test.ts b/packages/database/supabase/functions/post-memo/post-memo-transaction.test.ts
new file mode 100644
index 0000000000..e20260a47c
--- /dev/null
+++ b/packages/database/supabase/functions/post-memo/post-memo-transaction.test.ts
@@ -0,0 +1,267 @@
+import {
+ assertEquals,
+ assertRejects,
+} from "https://deno.land/[email protected]/testing/asserts.ts";
+import { databaseTest, paymentFixture } from "../post-payment/payment-test-fixture.ts";
+import { postMemoTransaction } from "./post-memo-transaction.ts";
+import { postPaymentTransaction } from "../post-payment/post-payment-transaction.ts";
+
+type Fixture = Awaited<ReturnType<typeof paymentFixture>>;
+async function memoFixture(f: Fixture) {
+ const id = `${f.companyId}-memo`;
+ await f.db.updateTable("accountDefault").set({
+ salesDiscountAccount: f.account("discount"),
+ }).where("companyId", "=", f.companyId).execute();
+ await f.db.insertInto("memo").values({
+ id,
+ memoId: "CREDIT-55",
+ companyId: f.companyId,
+ customerId: f.customerId,
+ direction: "Credit",
+ memoDate: "2026-09-07",
+ currencyCode: "EUR",
+ exchangeRate: 1.1,
+ amount: 55,
+ createdBy: "system",
+ }).execute();
+ return id;
+}
+databaseTest("memo transaction posts authoritative base50, is idempotent, and reverses actual lines after defaults change", async () => {
+ const f = await paymentFixture();
+ try {
+ const memoId = await memoFixture(f);
+ const result = await postMemoTransaction(f.db, { ...f.args, memoId });
+ assertEquals(
+ (await postMemoTransaction(f.db, { ...f.args, memoId })).journalId,
+ result.journalId,
+ );
+ const memo = await f.db.selectFrom("memo").selectAll().where(
+ "id",
+ "=",
+ memoId,
+ ).executeTakeFirstOrThrow();
+ assertEquals(memo.status, "Posted");
+ assertEquals(memo.reasonAccount, f.account("discount"));
+ const original = await f.db.selectFrom("journalLine").select([
+ "accountId",
+ "amount",
+ ]).where("journalId", "=", result.journalId!).execute();
+ assertEquals(
+ original.find((l) => l.accountId === f.account("control"))?.amount,
+ -50,
+ );
+ assertEquals(
+ original.find((l) => l.accountId === f.account("discount"))?.amount,
+ 50,
+ );
+ await f.db.updateTable("accountDefault").set({
+ receivablesAccount: f.account("bank"),
+ }).where("companyId", "=", f.companyId).execute();
+ const reversed = await postMemoTransaction(f.db, {
+ ...f.args,
+ type: "void",
+ memoId,
+ });
+ await postMemoTransaction(f.db, { ...f.args, type: "void", memoId });
+ const reverseLines = await f.db.selectFrom("journalLine").select([
+ "accountId",
+ "amount",
+ ]).where("journalId", "=", reversed.journalId!).execute();
+ assertEquals(
+ reverseLines.find((l) => l.accountId === f.account("control"))?.amount,
+ 50,
+ );
+ assertEquals(
+ reverseLines.find((l) => l.accountId === f.account("discount"))?.amount,
+ -50,
+ );
+ const journals = await f.db.selectFrom("journal").select("id").where(
+ "companyId",
+ "=",
+ f.companyId,
+ ).where("sourceType", "=", "Credit Memo").execute();
+ assertEquals(journals.length, 2);
+ } finally {
+ await f.cleanup();
+ }
+});
+databaseTest("memo period lock is rechecked against transaction state, overriding a stale open-period read", async () => {
+ const f = await paymentFixture();
+ try {
+ const memoId = await memoFixture(f);
+ await f.db.updateTable("accountingPeriod").set({ closeStatus: "Locked" })
+ .where("companyId", "=", f.companyId).execute();
+ await assertRejects(
+ () => postMemoTransaction(f.db, { ...f.args, memoId }),
+ Error,
+ "locked",
+ );
+ const row = await f.db.selectFrom("memo").select(["status", "journalId"])
+ .where("id", "=", memoId).executeTakeFirstOrThrow();
+ assertEquals(row, { status: "Draft", journalId: null });
+ } finally {
+ await f.cleanup();
+ }
+});
+databaseTest("memo refuses invalid precision and invalid posting accounts without writes", async () => {
+ const f = await paymentFixture();
+ try {
+ const memoId = await memoFixture(f);
+ await f.db.deleteFrom("currency").where("companyGroupId", "=", f.groupId)
+ .where("code", "=", "EUR").execute();
+ await assertRejects(
+ () => postMemoTransaction(f.db, { ...f.args, memoId }),
+ Error,
+ "currency",
+ );
+ await f.db.insertInto("currency").values({
+ code: "EUR",
+ decimalPlaces: 2,
+ companyGroupId: f.groupId,
+ createdBy: "system",
+ }).execute();
+ await f.db.updateTable("account").set({ active: false }).where(
+ "id",
+ "=",
+ f.account("discount"),
+ ).execute();
+ await assertRejects(
+ () => postMemoTransaction(f.db, { ...f.args, memoId }),
+ Error,
+ "posting accounts",
+ );
+ assertEquals(
+ (await f.db.selectFrom("memo").select("status").where("id", "=", memoId)
+ .executeTakeFirstOrThrow()).status,
+ "Draft",
+ );
+ } finally {
+ await f.cleanup();
+ }
+});
+databaseTest("memo journal insertion failure rolls back header, lines and sequence", async () => {
+ const f = await paymentFixture();
+ try {
+ const memoId = await memoFixture(f);
+ const before = await f.db.selectFrom("sequence").select("next").where(
+ "companyId",
+ "=",
+ f.companyId,
+ ).where("table", "=", "journalEntry").executeTakeFirstOrThrow();
+ await assertRejects(
+ () =>
+ postMemoTransaction(f.db, {
+ ...f.args,
+ memoId,
+ userId: `${f.companyId}-missing-user`,
+ }),
+ Error,
+ "foreign key",
+ );
+ assertEquals(
+ (await f.db.selectFrom("memo").select("status").where("id", "=", memoId)
+ .executeTakeFirstOrThrow()).status,
+ "Draft",
+ );
+ assertEquals(
+ await f.db.selectFrom("sequence").select("next").where(
+ "companyId",
+ "=",
+ f.companyId,
+ ).where("table", "=", "journalEntry").executeTakeFirstOrThrow(),
+ before,
+ );
+ assertEquals(
+ (await f.db.selectFrom("journal").select("id").where(
+ "companyId",
+ "=",
+ f.companyId,
+ ).where("sourceType", "=", "Credit Memo").execute()).length,
+ 0,
+ );
+ } finally {
+ await f.cleanup();
+ }
+});
+
+databaseTest("memo currency and tenant checks still apply when accounting is disabled", async () => {
+ const f = await paymentFixture();
+ const other = await paymentFixture();
+ try {
+ const memoId = await memoFixture(f);
+ await f.db.updateTable("companySettings").set({ accountingEnabled: false })
+ .where("id", "=", f.companyId).execute();
+ await f.db.updateTable("memo").set({
+ currencyCode: "USD",
+ exchangeRate: 1.1,
+ }).where("id", "=", memoId).execute();
+ await assertRejects(
+ () => postMemoTransaction(f.db, { ...f.args, memoId }),
+ Error,
+ "exchange rate 1",
+ );
+ const otherMemoId = await memoFixture(other);
+ await assertRejects(
+ () => postMemoTransaction(f.db, { ...f.args, memoId: otherMemoId }),
+ Error,
+ "Memo not found",
+ );
+ await f.db.updateTable("memo").set({ currencyCode: "EUR", amount: 0.015 })
+ .where("id", "=", memoId).execute();
+ await assertRejects(
+ () => postMemoTransaction(f.db, { ...f.args, memoId }),
+ Error,
+ "precision",
+ );
+ await f.db.updateTable("memo").set({ amount: 0.01, exchangeRate: 16001 })
+ .where("id", "=", memoId).execute();
+ assertEquals(await postMemoTransaction(f.db, { ...f.args, memoId }), {
+ journalId: null,
+ });
+ assertEquals(
+ (await f.db.selectFrom("memo").select("status").where("id", "=", memoId)
+ .executeTakeFirstOrThrow()).status,
+ "Posted",
+ );
+ } finally {
+ await f.cleanup();
+ await other.cleanup();
+ }
+});
+
+databaseTest("consumed memo cannot be voided until its applying payment is voided", async () => {
+ const f = await paymentFixture();
+ try {
+ const memoId = await memoFixture(f);
+ const original = await postMemoTransaction(f.db, { ...f.args, memoId });
+ const paymentId = await f.payment({ amount: 0, noApplication: true });
+ await f.db.insertInto("invoiceSettlement").values({
+ memoId, appliedViaPaymentId: paymentId, targetSalesInvoiceId: f.invoiceId,
+ sourceAmount: 55, appliedAmount: 50, sourceExchangeRate: 1.1,
+ targetExchangeRate: 1.1, appliedDate: "2026-09-07", companyId: f.companyId, createdBy: "system"
+ }).execute();
+ await postPaymentTransaction(f.db, { ...f.args, paymentId });
+ await assertRejects(() => postMemoTransaction(f.db, { ...f.args, memoId, type: "void" }), Error, "consumed");
+ assertEquals(await f.db.selectFrom("memo").select(["status", "journalId"]).where("id", "=", memoId).executeTakeFirstOrThrow(), { status: "Posted", journalId: original.journalId });
+ assertEquals((await f.db.selectFrom("journal").select("id").where("companyId", "=", f.companyId).where("sourceType", "=", "Credit Memo").execute()).length, 1);
+ await postPaymentTransaction(f.db, { ...f.args, paymentId, type: "void" });
+ await postMemoTransaction(f.db, { ...f.args, memoId, type: "void" });
+ assertEquals((await f.db.selectFrom("memo").select("status").where("id", "=", memoId).executeTakeFirstOrThrow()).status, "Voided");
+ } finally { await f.cleanup(); }
+});
+
+databaseTest("draft memo reservation does not prevent memo void", async () => {
+ const f = await paymentFixture();
+ try {
+ const memoId = await memoFixture(f);
+ await postMemoTransaction(f.db, { ...f.args, memoId });
+ const paymentId = await f.payment({ amount: 0, noApplication: true });
+ await f.db.insertInto("invoiceSettlement").values({
+ memoId, appliedViaPaymentId: paymentId, targetSalesInvoiceId: f.invoiceId,
+ sourceAmount: 55, appliedAmount: 50, sourceExchangeRate: 1.1,
+ targetExchangeRate: 1.1, appliedDate: "2026-09-07", companyId: f.companyId, createdBy: "system"
+ }).execute();
+ await postMemoTransaction(f.db, { ...f.args, memoId, type: "void" });
+ await assertRejects(() => postPaymentTransaction(f.db, { ...f.args, paymentId }), Error);
+ } finally { await f.cleanup(); }
+});
diff --git a/packages/database/supabase/functions/post-memo/post-memo-transaction.ts b/packages/database/supabase/functions/post-memo/post-memo-transaction.ts
new file mode 100644
index 0000000000..fa857dd3c2
--- /dev/null
+++ b/packages/database/supabase/functions/post-memo/post-memo-transaction.ts
@@ -0,0 +1,347 @@
+import type { Kysely } from "kysely";
+import { nanoid } from "https://deno.land/x/[email protected]/mod.ts";
+import type { SupabaseClient } from "@supabase/supabase-js";
+import type { DB } from "../lib/database.ts";
+import type { Database } from "../lib/types.ts";
+import { datetime } from "../lib/datetime.ts";
+import {
+ toBaseAmount,
+ toDocumentAmount,
+} from "../shared/accounting-currency.ts";
+import { getCurrentAccountingPeriod } from "../shared/get-accounting-period.ts";
+import { getNextSequence } from "../shared/get-next-sequence.ts";
+import { buildMemoJournal } from "./build-memo-journal.ts";
+
+export type PostMemoArgs = {
+ type: "post" | "void";
+ memoId: string;
+ companyId: string;
+ userId: string;
+ today: string;
+ client: SupabaseClient<Database>;
+};
+
+/** The endpoint's commit boundary. Headers, defaults and account classes come from this transaction. */
+export function postMemoTransaction(
+ db: Kysely<DB>,
+ args: PostMemoArgs,
+): Promise<{ journalId: string | null }> {
+ const { type, memoId, companyId, userId, today, client } = args;
+ return db.transaction().execute(async (trx) => {
+ const memo = await trx.selectFrom("memo").selectAll().where(
+ "id",
+ "=",
+ memoId,
+ ).where("companyId", "=", companyId).forUpdate().executeTakeFirst();
+ if (!memo) throw new Error("Memo not found");
+ if (type === "post" && memo.status === "Posted") {
+ return { journalId: memo.journalId };
+ }
+ if (type === "void" && memo.status === "Voided") {
+ return { journalId: memo.journalId };
+ }
+ if (memo.status !== (type === "post" ? "Draft" : "Posted")) {
+ throw new Error(`Cannot ${type} memo in status ${memo.status}`);
+ }
+ const settings = await trx.selectFrom("companySettings").select(
+ "accountingEnabled",
+ ).where("id", "=", companyId).executeTakeFirst();
+ const accountingEnabled = settings?.accountingEnabled === true;
+ const timestamp = datetime.timestamp();
+ let accountingPeriodId: string | null = null;
+ if (accountingEnabled) {
+ accountingPeriodId = await getCurrentAccountingPeriod(
+ client,
+ companyId,
+ trx,
+ today,
+ );
+ const period = await trx.selectFrom("accountingPeriod").select([
+ "id",
+ "closeStatus",
+ "closedAt",
+ ])
+ .where("id", "=", accountingPeriodId).where("companyId", "=", companyId)
+ .forShare().executeTakeFirst();
+ if (
+ !period || period.closeStatus === "Locked" ||
+ period.closeStatus === "Closed" || period.closedAt
+ ) throw new Error("Accounting period is closed or locked");
+ }
+ if (type === "void") {
+ // Posting a consuming payment takes this same memo lock. A void cannot
+ // erase its source while that payment still carries the application.
+ const consumption = await trx.selectFrom("invoiceSettlement as s")
+ .leftJoin("payment as applying", (join) =>
+ join
+ .onRef("applying.id", "=", "s.appliedViaPaymentId")
+ .onRef("applying.companyId", "=", "s.companyId"))
+ .leftJoin("payment as refund", (join) =>
+ join
+ .onRef("refund.id", "=", "s.paymentId")
+ .onRef("refund.companyId", "=", "s.companyId"))
+ .select("s.id")
+ .where("s.companyId", "=", companyId)
+ .where((eb) =>
+ eb.or([
+ eb.and([
+ eb("s.memoId", "=", memoId),
+ eb.or([
+ eb("s.appliedViaPaymentId", "is", null),
+ eb("applying.status", "=", "Posted"),
+ ]),
+ ]),
+ eb.and([
+ eb("s.targetMemoId", "=", memoId),
+ eb("refund.status", "=", "Posted"),
+ ]),
+ ])
+ )
+ .limit(1).executeTakeFirst();
+ if (consumption) {
+ throw new Error(
+ "Cannot void a consumed memo; void its applying payment or remove its direct application first",
+ );
+ }
+ let journalId: string | null = null;
+ if (memo.journalId) {
+ if (!accountingPeriodId) {
+ throw new Error(
+ "Enable accounting before reversing a posted memo journal",
+ );
+ }
+ const originalJournal = await trx.selectFrom("journal").select([
+ "id",
+ "status",
+ "sourceType",
+ ])
+ .where("id", "=", memo.journalId).where("companyId", "=", companyId)
+ .executeTakeFirst();
+ if (
+ !originalJournal || originalJournal.status !== "Posted" ||
+ originalJournal.sourceType !==
+ (memo.direction === "Credit" ? "Credit Memo" : "Debit Memo")
+ ) throw new Error("Original memo journal not found in this company");
+ const original = await trx.selectFrom("journalLine").selectAll().where(
+ "journalId",
+ "=",
+ memo.journalId,
+ ).where("companyId", "=", companyId).orderBy("id").execute();
+ if (!original.length) {
+ throw new Error("Original memo journal has no lines to reverse");
+ }
+ const reversed = await trx.insertInto("journal").values({
+ journalEntryId: await getNextSequence(trx, "journalEntry", companyId),
+ accountingPeriodId,
+ description: `VOID Memo ${memo.memoId}`,
+ postingDate: today,
+ companyId,
+ sourceType: originalJournal.sourceType,
+ status: "Posted",
+ postedAt: timestamp,
+ postedBy: userId,
+ createdBy: userId,
+ }).returning("id").executeTakeFirstOrThrow();
+ journalId = reversed.id;
+ const lines = await trx.insertInto("journalLine").values(
+ original.map((line) => ({
+ journalId: reversed.id,
+ accountId: line.accountId,
+ amount: -Number(line.amount),
+ quantity: line.quantity,
+ description: `VOID: ${line.description ?? ""}`,
+ documentType: "Memo" as const,
+ documentId: memoId,
+ documentLineReference: line.documentLineReference,
+ journalLineReference: line.journalLineReference,
+ companyId,
+ })),
+ ).returning("id").execute();
+ const dimensions = await trx.selectFrom("journalLineDimension").select([
+ "journalLineId",
+ "dimensionId",
+ "valueId",
+ ])
+ .where("companyId", "=", companyId).where(
+ "journalLineId",
+ "in",
+ original.map((line) => line.id),
+ ).execute();
+ const reverseByOriginal = new Map(
+ original.map((line, index) => [line.id, lines[index].id]),
+ );
+ if (dimensions.length) {
+ await trx.insertInto("journalLineDimension").values(
+ dimensions.map((d) => ({
+ ...d,
+ journalLineId: reverseByOriginal.get(d.journalLineId)!,
+ companyId,
+ })),
+ ).execute();
+ }
+ }
+ await trx.updateTable("memo").set({
+ status: "Voided",
+ voidedAt: timestamp,
+ voidedBy: userId,
+ updatedAt: timestamp,
+ updatedBy: userId,
+ }).where("id", "=", memoId).where("companyId", "=", companyId).execute();
+ return { journalId };
+ }
+
+ if (Boolean(memo.customerId) === Boolean(memo.supplierId)) {
+ throw new Error("Memo must have exactly one customer or supplier");
+ }
+ const isAR = Boolean(memo.customerId);
+ const partyId = (isAR ? memo.customerId : memo.supplierId)!;
+ const company = await trx.selectFrom("company").select([
+ "companyGroupId",
+ "baseCurrencyCode",
+ ]).where("id", "=", companyId).executeTakeFirst();
+ if (!company?.companyGroupId || !memo.currencyCode) {
+ throw new Error("Memo currency configuration is missing");
+ }
+ const currency = await trx.selectFrom("currency").select("decimalPlaces")
+ .where("companyGroupId", "=", company.companyGroupId).where(
+ "code",
+ "=",
+ memo.currencyCode,
+ ).executeTakeFirst();
+ if (!currency || currency.decimalPlaces == null) {
+ throw new Error("Memo currency decimal places are not configured");
+ }
+ const amount = Number(memo.amount);
+ const exchangeRate = Number(memo.exchangeRate);
+ if (!Number.isFinite(amount) || amount <= 0) {
+ throw new Error("Memo amount must be positive and finite");
+ }
+ toBaseAmount(amount, exchangeRate);
+ if (toDocumentAmount(amount, 1, currency.decimalPlaces) !== amount) {
+ throw new Error("Memo amount exceeds document currency precision");
+ }
+ if (company.baseCurrencyCode === memo.currencyCode && exchangeRate !== 1) {
+ throw new Error("Base-currency memo must use exchange rate 1");
+ }
+ const party = isAR
+ ? await trx.selectFrom("customer").select([
+ "customerTypeId as typeId",
+ "intercompanyCompanyId",
+ ]).where("id", "=", partyId).where("companyId", "=", companyId)
+ .executeTakeFirst()
+ : await trx.selectFrom("supplier").select([
+ "supplierTypeId as typeId",
+ "intercompanyCompanyId",
+ ]).where("id", "=", partyId).where("companyId", "=", companyId)
+ .executeTakeFirst();
+ if (!party) throw new Error("Memo counterparty not found in this company");
+ let journalId: string | null = null;
+ let reasonAccountId: string | null = null;
+ if (accountingEnabled) {
+ const defaults = await trx.selectFrom("accountDefault").selectAll().where(
+ "companyId",
+ "=",
+ companyId,
+ ).executeTakeFirst();
+ if (!defaults) {
+ throw new Error("Accounting defaults are required before posting");
+ }
+ const controlAccountId = isAR
+ ? defaults.receivablesAccount
+ : defaults.payablesAccount;
+ reasonAccountId = isAR
+ ? defaults.salesDiscountAccount
+ : defaults.supplierPaymentDiscountAccount;
+ if (!controlAccountId || !reasonAccountId) {
+ throw new Error(
+ "Memo control and reason account defaults are required",
+ );
+ }
+ const accountIds = [...new Set([controlAccountId, reasonAccountId])];
+ const accounts = await trx.selectFrom("account").select(["id", "class"])
+ .where("id", "in", accountIds).where(
+ "companyGroupId",
+ "=",
+ company.companyGroupId,
+ ).where("active", "=", true).where("isGroup", "=", false).execute();
+ const control = accounts.find((a) => a.id === controlAccountId);
+ const reason = accounts.find((a) => a.id === reasonAccountId);
+ if (
+ accounts.length !== accountIds.length ||
+ control?.class !== (isAR ? "Asset" : "Liability") || !reason?.class
+ ) {
+ throw new Error(
+ "Memo accounts must be active posting accounts in this company group with the correct control class",
+ );
+ }
+ const { lines } = buildMemoJournal({
+ memoId,
+ companyId,
+ isAR,
+ direction: memo.direction,
+ amount,
+ exchangeRate,
+ journalLineReference: nanoid(),
+ controlAccountId,
+ reasonAccountId,
+ reasonAccountClass: reason.class,
+ });
+ const journal = await trx.insertInto("journal").values({
+ journalEntryId: await getNextSequence(trx, "journalEntry", companyId),
+ accountingPeriodId,
+ description: `${memo.direction} Memo ${memo.memoId}`,
+ postingDate: today,
+ companyId,
+ sourceType: memo.direction === "Credit" ? "Credit Memo" : "Debit Memo",
+ status: "Posted",
+ postedAt: timestamp,
+ postedBy: userId,
+ createdBy: userId,
+ }).returning("id").executeTakeFirstOrThrow();
+ journalId = journal.id;
+ const inserted = await trx.insertInto("journalLine").values(
+ lines.map((line) => ({ ...line, journalId: journal.id })),
+ ).returning("id").execute();
+ const dimensions = await trx.selectFrom("dimension").select([
+ "id",
+ "entityType",
+ ]).where("companyGroupId", "=", company.companyGroupId).where(
+ "active",
+ "=",
+ true,
+ ).where(
+ "entityType",
+ "in",
+ isAR ? ["CustomerType", "Customer"] : ["SupplierType", "Supplier"],
+ ).execute();
+ const dimensionValues = dimensions.flatMap((d) => {
+ const valueId = d.entityType === (isAR ? "Customer" : "Supplier")
+ ? partyId
+ : party.typeId;
+ return valueId
+ ? inserted.map((line) => ({
+ journalLineId: line.id,
+ dimensionId: d.id,
+ valueId,
+ companyId,
+ }))
+ : [];
+ });
+ if (dimensionValues.length) {
+ await trx.insertInto("journalLineDimension").values(dimensionValues)
+ .execute();
+ }
+ }
+ await trx.updateTable("memo").set({
+ status: "Posted",
+ postingDate: today,
+ journalId,
+ reasonAccount: reasonAccountId,
+ postedAt: timestamp,
+ postedBy: userId,
+ updatedAt: timestamp,
+ updatedBy: userId,
+ }).where("id", "=", memoId).where("companyId", "=", companyId).execute();
+ return { journalId };
+ });
+}
diff --git a/packages/database/supabase/functions/post-memo/post-memo.test.ts b/packages/database/supabase/functions/post-memo/post-memo.test.ts
index 7a6d827d62..e61cc36a4c 100644
--- a/packages/database/supabase/functions/post-memo/post-memo.test.ts
+++ b/packages/database/supabase/functions/post-memo/post-memo.test.ts
@@ -3,7 +3,10 @@ import {
assertEquals,
assertThrows,
} from "https://deno.land/[email protected]/testing/asserts.ts";
-import { buildMemoJournal, type BuildMemoJournalInput } from "./build-memo-journal.ts";
+import {
+ buildMemoJournal,
+ type BuildMemoJournalInput,
+} from "./build-memo-journal.ts";
// Golden-master tests for the GL journal a credit/debit memo posts. A memo is a
// two-line entry: the AR/AP control leg and a reason leg. Direction alone decides
@@ -12,13 +15,14 @@ import { buildMemoJournal, type BuildMemoJournalInput } from "./build-memo-journ
// natural class. Every combo must balance (signedDebitTotal ~ 0).
const base = (
- overrides: Partial<BuildMemoJournalInput>
+ overrides: Partial<BuildMemoJournalInput>,
): BuildMemoJournalInput => ({
memoId: "memo_1",
companyId: "co_1",
isAR: true,
direction: "Credit",
- amountBase: 300,
+ amount: 300,
+ exchangeRate: 1,
journalLineReference: "ref_1",
controlAccountId: "acct_ar",
reasonAccountId: "acct_reason",
@@ -52,7 +56,7 @@ Deno.test("customer Debit memo: DR AR (asset), CR reason; balances", () => {
Deno.test("supplier Credit memo: CR AP (liability), DR reason; balances", () => {
const r = buildMemoJournal(
- base({ isAR: false, direction: "Credit", reasonAccountClass: "Expense" })
+ base({ isAR: false, direction: "Credit", reasonAccountClass: "Expense" }),
);
// Control AP is a liability; a credit stores +magnitude.
assertEquals(line(r, "acct_ar").amount, 300);
@@ -63,7 +67,7 @@ Deno.test("supplier Credit memo: CR AP (liability), DR reason; balances", () =>
Deno.test("supplier Debit memo: DR AP (liability), CR reason; balances", () => {
const r = buildMemoJournal(
- base({ isAR: false, direction: "Debit", reasonAccountClass: "Expense" })
+ base({ isAR: false, direction: "Debit", reasonAccountClass: "Expense" }),
);
// Control AP debit (liability) stores −magnitude.
assertEquals(line(r, "acct_ar").amount, -300);
@@ -73,20 +77,41 @@ Deno.test("supplier Debit memo: DR AP (liability), CR reason; balances", () => {
});
Deno.test("rounds to internal scale and stays balanced on fractional amounts", () => {
- const r = buildMemoJournal(base({ amountBase: 123.456789 }));
+ const r = buildMemoJournal(base({ amount: 123.456789 }));
// SCALE = 5: GL lines carry internal precision, not the old 4dp column clamp.
assertEquals(line(r, "acct_ar").amount, -123.45679);
assert(Math.abs(r.signedDebitTotal) < 0.01);
});
Deno.test("rejects a zero amount", () => {
- assertThrows(() => buildMemoJournal(base({ amountBase: 0 })), Error, "greater than 0");
+ assertThrows(
+ () => buildMemoJournal(base({ amount: 0 })),
+ Error,
+ "greater than 0",
+ );
});
Deno.test("rejects an unknown reason account class", () => {
assertThrows(
() => buildMemoJournal(base({ reasonAccountClass: "Bogus" })),
Error,
- "Unknown GL account class"
+ "Unknown GL account class",
);
});
+
+Deno.test("memo55 at rate1.1 posts base50 rather than60.5", () => {
+ const result = buildMemoJournal(base({ amount: 55, exchangeRate: 1.1 }));
+ assertEquals(line(result, "acct_ar").amount, -50);
+});
+Deno.test("positive document principal remains postable below base dust thresholds", () => {
+ const result = buildMemoJournal(base({ amount: 0.01, exchangeRate: 16000 }));
+ assertEquals(line(result, "acct_ar").amount, 0);
+});
+Deno.test("invalid memo snapshots are rejected before journal construction", () => {
+ for (const exchangeRate of [0, -1, Number.NaN, Number.POSITIVE_INFINITY]) {
+ assertThrows(() => buildMemoJournal(base({ exchangeRate })));
+ }
+ for (const amount of [-1, Number.NaN, Number.POSITIVE_INFINITY]) {
+ assertThrows(() => buildMemoJournal(base({ amount })));
+ }
+});
diff --git a/packages/database/supabase/functions/post-payment/build-payment-journal.test.ts b/packages/database/supabase/functions/post-payment/build-payment-journal.test.ts
new file mode 100644
index 0000000000..c51c186c8a
--- /dev/null
+++ b/packages/database/supabase/functions/post-payment/build-payment-journal.test.ts
@@ -0,0 +1,206 @@
+import {
+ assert,
+ assertEquals,
+} from "https://deno.land/[email protected]/testing/asserts.ts";
+import { round } from "../shared/precision.ts";
+import {
+ buildPaymentJournal,
+ type PaymentJournalApplicationInput,
+} from "./build-payment-journal.ts";
+
+for (const isAR of [true, false]) {
+ Deno.test(`${isAR ? "AR" : "AP"} multiple target rates preserve per-invoice relief, signed FX and decoded GL balance`, () => {
+ // Document cash 88 + 55 is worth base 143 at the payment's rate of 1.
+ // Target A: 88 / 1.1 = 80 principal + 15 discount + 5 write-off = 100.
+ // Target B: 55 / 0.8 = 68.75 principal + 3 discount + 2 write-off = 73.75.
+ // AR realizes +8 and -13.75; AP has the opposite gains/losses.
+ const applications: PaymentJournalApplicationInput[] = [
+ {
+ targetSalesInvoiceId: isAR ? "invoice-a" : null,
+ targetPurchaseInvoiceId: isAR ? null : "invoice-a",
+ targetControlAccountId: "original-control-a",
+ targetExchangeRate: 1.1,
+ sourceExchangeRate: 1,
+ sourcePaymentId: null,
+ sourceAmount: 88,
+ appliedAmount: 80,
+ discountAmount: 15,
+ writeOffAmount: 5,
+ fxGainLossAmount: isAR ? 8 : -8,
+ },
+ {
+ targetSalesInvoiceId: isAR ? "invoice-b" : null,
+ targetPurchaseInvoiceId: isAR ? null : "invoice-b",
+ targetControlAccountId: "original-control-b",
+ targetExchangeRate: 0.8,
+ sourceExchangeRate: 1,
+ sourcePaymentId: null,
+ sourceAmount: 55,
+ appliedAmount: 68.75,
+ discountAmount: 3,
+ writeOffAmount: 2,
+ fxGainLossAmount: isAR ? -13.75 : 13.75,
+ },
+ ];
+ const result = buildPaymentJournal({
+ paymentId: "payment",
+ companyId: "company",
+ isAR,
+ cashIn: isAR,
+ totalAmount: 143,
+ exchangeRate: 1,
+ bankAccount: "bank",
+ journalLineReference: "reference",
+ applications,
+ newOnAccountBase: 0,
+ accounts: {
+ controlAccountId: "today-control",
+ discountAccountId: "discount",
+ writeOffAccountId: "writeoff",
+ fxGainAccountId: "fxgain",
+ fxLossAccountId: "fxloss",
+ },
+ });
+
+ for (const [index, application] of applications.entries()) {
+ const target = index === 0 ? "invoice-a" : "invoice-b";
+ const expectedRelief = index === 0 ? 100 : 73.75;
+ const lines = result.lines.filter((line) =>
+ line.documentLineReference === target
+ );
+ const control = lines.find((line) =>
+ line.accountId === application.targetControlAccountId
+ );
+ assert(control, `Missing original control for ${target}`);
+ // Natural-balance storage decreases both AR assets and AP liabilities.
+ assertEquals(control.amount, -expectedRelief);
+ assertEquals(
+ -control.amount,
+ round(
+ application.appliedAmount + application.discountAmount +
+ application.writeOffAmount,
+ ),
+ );
+ assertEquals(
+ lines.find((line) => line.accountId === "discount")?.amount,
+ isAR ? application.discountAmount : -application.discountAmount,
+ );
+ assertEquals(
+ lines.find((line) => line.accountId === "writeoff")?.amount,
+ application.writeOffAmount,
+ );
+ assertEquals(round(expectedRelief + control.amount), 0);
+ }
+ assertEquals(
+ result.lines.find((line) => line.accountId === "bank")?.amount,
+ isAR ? 143 : -143,
+ );
+ assertEquals(result.totalFxImpact, isAR ? -5.75 : 5.75);
+ assertEquals(
+ result.lines.find((line) =>
+ line.accountId === (isAR ? "fxloss" : "fxgain")
+ )?.amount,
+ 5.75,
+ );
+ assert(!result.lines.some((line) => line.accountId === "today-control"));
+
+ // Decode storage independently by account class; a natural-signed sum
+ // or the builder's returned running total alone cannot prove GL balance.
+ const classes: Record<
+ string,
+ "Asset" | "Liability" | "Expense" | "Revenue"
+ > = {
+ bank: "Asset",
+ "original-control-a": isAR ? "Asset" : "Liability",
+ "original-control-b": isAR ? "Asset" : "Liability",
+ discount: "Expense",
+ writeoff: isAR ? "Expense" : "Revenue",
+ fxgain: "Revenue",
+ fxloss: "Expense",
+ };
+ const debitSigned = result.lines.reduce((sum, line) => {
+ const accountClass = classes[line.accountId];
+ assert(accountClass, `Unexpected account ${line.accountId}`);
+ return sum +
+ (accountClass === "Asset" || accountClass === "Expense"
+ ? line.amount
+ : -line.amount);
+ }, 0);
+ assertEquals(round(debitSigned), 0);
+ assertEquals(result.signedDebitTotal, 0);
+ });
+}
+
+// Direction of cash and ledger side are independent. A Disbursement to a
+// CUSTOMER is an AR refund (cash out, receivable restored); a Receipt from a
+// SUPPLIER is an AP refund. `payment_party_check` permits both, the composer
+// stages them, and the docs describe them as supported — post-payment must not
+// refuse them.
+for (const isAR of [true, false]) {
+ Deno.test(`${isAR ? "AR" : "AP"} refund posts cash on the opposite side of its ledger`, () => {
+ const result = buildPaymentJournal({
+ paymentId: "payment",
+ companyId: "company",
+ isAR,
+ // The refund case: cash moves the opposite way to the normal flow.
+ cashIn: !isAR,
+ totalAmount: 40,
+ exchangeRate: 1,
+ bankAccount: "bank",
+ journalLineReference: "reference",
+ applications: [
+ {
+ targetMemoId: "memo-a",
+ targetControlAccountId: "original-control",
+ targetExchangeRate: 1,
+ sourceExchangeRate: 1,
+ sourcePaymentId: null,
+ sourceAmount: 40,
+ appliedAmount: 40,
+ discountAmount: 0,
+ writeOffAmount: 0,
+ fxGainLossAmount: 0,
+ },
+ ],
+ newOnAccountBase: 0,
+ accounts: {
+ controlAccountId: "today-control",
+ discountAccountId: "discount",
+ writeOffAccountId: "writeoff",
+ fxGainAccountId: "fxgain",
+ fxLossAccountId: "fxloss",
+ },
+ });
+
+ // An AR refund pays cash OUT, so the bank asset falls; an AP refund
+ // receives cash back, so it rises. This is the axis `cashIn` owns.
+ assertEquals(
+ result.lines.find((line) => line.accountId === "bank")?.amount,
+ isAR ? -40 : 40,
+ );
+ // The ledger side is the axis `isAR` owns: the refund restores the
+ // original control account rather than relieving it.
+ assertEquals(
+ result.lines.find((line) => line.accountId === "original-control")
+ ?.amount,
+ 40,
+ );
+ const classes: Record<
+ string,
+ "Asset" | "Liability" | "Expense" | "Revenue"
+ > = {
+ bank: "Asset",
+ "original-control": isAR ? "Asset" : "Liability",
+ };
+ const debitSigned = result.lines.reduce((sum, line) => {
+ const accountClass = classes[line.accountId];
+ assert(accountClass, `Unexpected account ${line.accountId}`);
+ return sum +
+ (accountClass === "Asset" || accountClass === "Expense"
+ ? line.amount
+ : -line.amount);
+ }, 0);
+ assertEquals(round(debitSigned), 0);
+ assertEquals(result.signedDebitTotal, 0);
+ });
+}
diff --git a/packages/database/supabase/functions/post-payment/build-payment-journal.ts b/packages/database/supabase/functions/post-payment/build-payment-journal.ts
index 80706c6e08..2edf5da3a4 100644
--- a/packages/database/supabase/functions/post-payment/build-payment-journal.ts
+++ b/packages/database/supabase/functions/post-payment/build-payment-journal.ts
@@ -1,53 +1,14 @@
-// Pure construction of the GL journal for posting an AR/AP payment. No DB, no
-// I/O, no clock — so it is unit-testable with `deno test`. The driver
-// (`index.ts`) resolves the account ids, dimensions, accounting period and
-// `journalLineReference` (all impure), then hands them here to compute the
-// balanced double-entry. Keeping this pure is what lets the golden-master tests
-// pin the exact journal for every AR/AP × partial/full × discount/write-off ×
-// FX-gain/loss × unapplied-credit permutation — the lines that hit the general
-// ledger must be provably correct, not merely inspected.
-//
-// TWO independent axes (decoupled so REFUNDS work — a refund is cash flowing the
-// "wrong" way for its ledger):
-// * isAR — does this payment settle AR (customer) or AP (supplier)? Drives
-// account SELECTION (receivables vs payables, customer vs supplier
-// discount/write-off) and the realized-FX gain/loss DIRECTION.
-// * cashIn — does cash come INTO our bank (Receipt) or leave it (Disbursement)?
-// Drives the debit/credit SIDE of every line.
-// Normal receipt: isAR && cashIn. Normal disbursement: !isAR && !cashIn.
-// AR refund (cash out to a customer against a credit memo): isAR && !cashIn.
-// AP refund (cash in from a supplier against a debit memo): !isAR && cashIn.
-//
-// Posting model (all amounts converted to base currency):
-// 1) Cash — DR Bank (cashIn) / CR Bank (!cashIn). When a processor fee is
-// deducted AT SOURCE (e.g. Stripe never deposits the gross —
-// the fee is withheld before the payout lands), the bank line
-// carries only the NET amount and a same-side fee expense line
-// makes up the difference, so the entry reflects what actually
-// moved through the bank rather than a gross deposit that never
-// happened.
-// 2) Per app — control account (AR/AP) at the TARGET rate so it reverses the
-// original booking exactly; discount and write-off (also
-// invoice-currency reliefs) at the target rate; realized FX on
-// the cash-settled principal accumulated for a single plug.
-// 3) Unapplied — cash beyond what was applied becomes new on-account credit;
-// applying more than the cash draws down existing credit (the
-// inverse posting side).
-// 4) FX plug — one Realized FX Gain / Loss line for the accumulated FX.
-//
-// FX sign convention: `totalFxImpact` is normalized by the (isAR ? 1 : -1)
-// factor so a POSITIVE value ALWAYS means a gain and a NEGATIVE value ALWAYS
-// means a loss, for both AR and AP. This is the same quantity the stored
-// `invoiceSettlement.fxGainLossAmount` captures, so the subledger reconciles.
-
+// Pure journal construction from authoritative, locked funding allocations.
+// Cash/sourceAmount are document currency. Control, relief, carrying remainders,
+// and the persisted per-application realized FX snapshots are company base.
import { assertBalanced, EPSILON, round } from "../shared/precision.ts";
+import {
+ assertExchangeRate,
+ toBaseAmount,
+} from "../shared/accounting-currency.ts";
+import { onAccountCreditDescription } from "../shared/accounting-posting.ts";
import { accountTypeFromClass, credit, debit } from "../lib/utils.ts";
-// A journal line this builder emits. Deliberately self-contained — a pure unit
-// shouldn't depend on the generated DB types, and `journalLine.documentType`'s
-// "Payment" enum value (migration 20260628143012) isn't in the generated
-// lib/types.ts until the DB is rebuilt and `db:types` is regenerated. The driver
-// spreads `journalId` on before the Kysely insert.
export interface PaymentJournalLine {
accountId: string;
description: string;
@@ -61,23 +22,30 @@ export interface PaymentJournalLine {
}
export interface PaymentJournalApplicationInput {
+ targetMemoId?: string | null;
targetSalesInvoiceId?: string | null;
targetPurchaseInvoiceId?: string | null;
+ sourceAmount: number;
+ sourcePaymentId: string | null;
+ fxGainLossAmount: number;
appliedAmount: number;
discountAmount: number;
writeOffAmount: number;
targetExchangeRate: number;
sourceExchangeRate: number;
+ /** Original booked control accounts, resolved by the locked posting driver. */
+ targetControlAccountId?: string;
+ sourceControlAccountId?: string;
}
export interface PaymentJournalAccounts {
controlAccountId: string | null;
discountAccountId: string | null;
- // The discount account's glAccountClass. Drives the discount line's natural-
- // balance sign so a customer discount (Revenue) debits contra-revenue and a
- // supplier discount (Expense/COGS) credits contra-cost. Resolved by index.ts;
- // optional so callers without a discount need not supply it (falls back to
- // "expense" for back-compat).
+ /** The discount account's glAccountClass. Drives the discount line's natural-
+ * balance sign so a customer discount (Revenue) debits contra-revenue and a
+ * supplier discount (Expense/COGS) credits contra-cost. Resolved by index.ts;
+ * optional so callers without a discount need not supply it (falls back to
+ * "expense" for back-compat). */
discountAccountClass?: string | null;
writeOffAccountId: string | null;
fxGainAccountId: string | null;
@@ -99,7 +67,8 @@ export interface BuildPaymentJournalInput {
// Internal payment record id — becomes `documentId` on every line.
paymentId: string;
companyId: string;
- // See the two-axis note at the top of the file.
+ // Party determines the control account class; cash direction determines
+ // debit/credit sides independently (including reusable refund arithmetic).
isAR: boolean;
cashIn: boolean;
totalAmount: number;
@@ -108,6 +77,8 @@ export interface BuildPaymentJournalInput {
// Resolved once by the driver (nanoid) so this stays pure.
journalLineReference: string;
applications: PaymentJournalApplicationInput[];
+ /** Authoritative unused current-cash carrying remainder from funding allocation. */
+ newOnAccountBase: number;
accounts: PaymentJournalAccounts;
fee?: PaymentJournalFeeInput;
}
@@ -121,12 +92,15 @@ export interface BuildPaymentJournalResult {
totalFxImpact: number;
}
-// Maximum residual (base ccy) we tolerate before refusing to post. Above this a
-// logic/rounding bug has produced an unbalanced entry.
-const BALANCE_TOLERANCE = 0.01;
+function nonnegative(value: number, label: string): number {
+ if (!Number.isFinite(value) || value < 0) {
+ throw new Error(`${label} must be finite and nonnegative`);
+ }
+ return value;
+}
export function buildPaymentJournal(
- input: BuildPaymentJournalInput
+ input: BuildPaymentJournalInput,
): BuildPaymentJournalResult {
const {
paymentId,
@@ -141,218 +115,205 @@ export function buildPaymentJournal(
accounts,
fee,
} = input;
-
- const {
- controlAccountId,
- discountAccountId,
- discountAccountClass,
- writeOffAccountId,
- fxGainAccountId,
- fxLossAccountId,
- } = accounts;
-
- if (!controlAccountId) {
+ if (!accounts.controlAccountId) {
+ throw new Error("Missing control account default");
+ }
+ const grossBase = toBaseAmount(
+ nonnegative(totalAmount, "Payment amount"),
+ exchangeRate,
+ );
+ const newOnAccountBase = toBaseAmount(
+ nonnegative(input.newOnAccountBase, "New on-account carrying value"),
+ 1,
+ );
+ if (
+ fee &&
+ (nonnegative(fee.amount, "Processor fee") > totalAmount || !fee.accountId)
+ ) {
throw new Error(
- `Missing ${isAR ? "receivables" : "payables"} account default; cannot post payment to GL`
+ "Processor fee requires an account and cannot exceed gross cash",
);
}
-
+ const feeBase = fee ? toBaseAmount(fee.amount, exchangeRate) : 0;
const lines: PaymentJournalLine[] = [];
- // True debit(+)/credit(−) space. A balanced double entry sums to ~0 here. (The
- // stored `amount` is natural-balance signed — credit("asset") is negative — so
- // it does NOT sum to zero; we track debit/credit balance separately.)
let signedDebitTotal = 0;
-
- const pushLine = (
+ const push = (
side: "debit" | "credit",
- accountType: "asset" | "liability" | "equity" | "revenue" | "expense",
+ type: "asset" | "liability" | "equity" | "revenue" | "expense",
magnitude: number,
- fields: {
- accountId: string;
- description: string;
- documentLineReference?: string;
- }
+ accountId: string | null,
+ description: string,
+ target?: string,
) => {
+ magnitude = toBaseAmount(nonnegative(magnitude, "Journal magnitude"), 1);
+ if (magnitude === 0) return;
+ if (!accountId) {
+ throw new Error(`Missing account default for ${description}`);
+ }
signedDebitTotal += side === "debit" ? magnitude : -magnitude;
lines.push({
- accountId: fields.accountId,
- description: fields.description,
- amount:
- side === "debit"
- ? debit(accountType, magnitude)
- : credit(accountType, magnitude),
+ accountId,
+ description,
+ amount: side === "debit"
+ ? debit(type, magnitude)
+ : credit(type, magnitude),
quantity: 1,
documentType: "Payment",
documentId: paymentId,
- documentLineReference: fields.documentLineReference,
+ documentLineReference: target,
journalLineReference,
companyId,
});
};
-
- // 1) Cash: DR Bank (cash in) / CR Bank (cash out). A processor fee withheld
- // at source never reaches the bank, so it comes OUT of the cash line
- // (not booked against a gross deposit that never happened) and gets its
- // own expense line on the SAME side — the control account below is still
- // relieved at the full (gross) applied amount, since the fee is between
- // us and the processor, not something the customer/supplier owes less of.
- const grossBase = round(totalAmount * exchangeRate);
- const feeBase = fee && fee.amount > 0 ? round(fee.amount * exchangeRate) : 0;
- const netBase = round(grossBase - feeBase);
- pushLine(cashIn ? "debit" : "credit", "asset", netBase, {
- accountId: bankAccount,
- description: "Bank / Cash",
- });
- if (feeBase > 0) {
- pushLine(cashIn ? "debit" : "credit", "expense", feeBase, {
- accountId: fee!.accountId,
- description: fee!.description ?? "Payment Processing Fee",
- });
+ push(
+ cashIn ? "debit" : "credit",
+ "asset",
+ round(grossBase - feeBase),
+ bankAccount,
+ "Bank / Cash",
+ );
+ if (fee) {
+ push(
+ cashIn ? "debit" : "credit",
+ "expense",
+ feeBase,
+ fee.accountId,
+ fee.description ?? "Payment Processing Fee",
+ );
}
-
- // 2) Per application: control at TARGET rate; discount / write-off at target
- // rate. FX is accumulated and plugged once below.
- let totalFxImpact = 0; // base ccy; +ve = gain, −ve = loss (both AR and AP)
+ let totalFxImpact = 0;
+ let currentCashReleased = 0;
+ let currentDocumentReleased = 0;
+ const priorCreditReleased = new Map<string, number>();
for (const app of applications) {
- const invId = (isAR
+ const isRefund = cashIn !== isAR;
+ const target = isRefund
+ ? app.targetMemoId
+ : isAR
? app.targetSalesInvoiceId
- : app.targetPurchaseInvoiceId) as string;
- const applied = Number(app.appliedAmount);
- const discount = Number(app.discountAmount);
- const writeOff = Number(app.writeOffAmount);
- const invRate = Number(app.targetExchangeRate);
- const payRate = Number(app.sourceExchangeRate);
-
- // Control account (AR/AP): at target rate (mirrors the original booking).
- // Side follows the cash direction so it offsets the bank line.
- pushLine(
- cashIn ? "credit" : "debit",
- isAR ? "asset" : "liability",
- round((applied + discount + writeOff) * invRate),
- {
- accountId: controlAccountId,
- description: isAR ? "Accounts Receivable" : "Accounts Payable",
- documentLineReference: invId,
- }
+ : app.targetPurchaseInvoiceId;
+ if (
+ !target ||
+ (isRefund
+ ? app.targetSalesInvoiceId || app.targetPurchaseInvoiceId ||
+ app.sourcePaymentId || app.discountAmount !== 0 ||
+ app.writeOffAmount !== 0
+ : app.targetMemoId ||
+ (isAR ? app.targetPurchaseInvoiceId : app.targetSalesInvoiceId))
+ ) {
+ throw new Error("Invalid payment application target");
+ }
+ assertExchangeRate(app.targetExchangeRate);
+ assertExchangeRate(app.sourceExchangeRate);
+ const applied = nonnegative(app.appliedAmount, "Applied amount");
+ const discount = nonnegative(app.discountAmount, "Discount amount");
+ const writeOff = nonnegative(app.writeOffAmount, "Write-off amount");
+ nonnegative(app.sourceAmount, "Source principal");
+ if (!Number.isFinite(app.fxGainLossAmount)) {
+ throw new Error("Settlement FX must be finite");
+ }
+ const releasedBase = round(
+ applied + (cashIn ? app.fxGainLossAmount : -app.fxGainLossAmount),
);
-
- // Discount: at TARGET rate (an invoice-currency relief, not cash, so it
- // carries no FX). AR debits (forgone revenue); AP credits (vendor allowance
- // reduces our cost).
- if (discount > 0) {
- if (!discountAccountId) {
- throw new Error(
- `Missing ${isAR ? "customer" : "supplier"} payment discount account default`
- );
- }
- pushLine(
- cashIn ? "debit" : "credit",
- discountAccountClass ? accountTypeFromClass(discountAccountClass) : "expense",
- round(discount * invRate),
- {
- accountId: discountAccountId,
- description: isAR
- ? "Customer Payment Discount"
- : "Supplier Payment Discount",
- documentLineReference: invId,
- }
+ nonnegative(releasedBase, "Released source carrying value");
+ if (
+ app.sourceAmount === 0 &&
+ (releasedBase !== 0 || applied !== 0 || app.fxGainLossAmount !== 0)
+ ) {
+ throw new Error(
+ "Zero source principal cannot release carrying value or realize FX",
);
}
-
- // Write-off: at TARGET rate (an invoice-currency relief, not cash, so it
- // carries no FX). AR is bad debt (expense); AP is vendor write-off (income —
- // class=Revenue).
- if (writeOff > 0) {
- if (!writeOffAccountId) {
- throw new Error(
- `Missing ${isAR ? "customer" : "supplier"} write-off account default`
- );
- }
- pushLine(
- cashIn ? "debit" : "credit",
- isAR ? "expense" : "revenue",
- round(writeOff * invRate),
- {
- accountId: writeOffAccountId,
- description: isAR ? "Bad Debt Expense" : "Vendor Write-Off Income",
- documentLineReference: invId,
- }
+ if (app.sourcePaymentId) {
+ const sourceAccount = app.sourceControlAccountId ??
+ accounts.controlAccountId;
+ priorCreditReleased.set(
+ sourceAccount,
+ round((priorCreditReleased.get(sourceAccount) ?? 0) + releasedBase),
);
+ } else {
+ if (app.sourceExchangeRate !== exchangeRate) {
+ throw new Error("Current cash rate does not match payment snapshot");
+ }
+ currentCashReleased += releasedBase;
+ currentDocumentReleased += app.sourceAmount;
}
-
- // Realized FX on the cash-settled principal only: applied × (sourceRate −
- // targetRate). Discount and write-off are invoice-currency reliefs booked at
- // the target rate above, so they carry no FX. The (isAR ? 1 : −1) factor
- // normalizes the sign so +ve is always a gain. Matches the stored
- // invoiceSettlement.fxGainLossAmount so the subledger reconciles.
- totalFxImpact += (isAR ? 1 : -1) * applied * (payRate - invRate);
+ push(
+ cashIn ? "credit" : "debit",
+ isAR ? "asset" : "liability",
+ round(applied + discount + writeOff),
+ app.targetControlAccountId ?? accounts.controlAccountId,
+ isAR ? "Accounts Receivable" : "Accounts Payable",
+ target,
+ );
+ push(
+ cashIn ? "debit" : "credit",
+ accounts.discountAccountClass
+ ? accountTypeFromClass(accounts.discountAccountClass)
+ : "expense",
+ discount,
+ accounts.discountAccountId,
+ isAR ? "Customer Payment Discount" : "Supplier Payment Discount",
+ target,
+ );
+ push(
+ cashIn ? "debit" : "credit",
+ isAR ? "expense" : "revenue",
+ writeOff,
+ accounts.writeOffAccountId,
+ isAR ? "Bad Debt Expense" : "Vendor Write-Off Income",
+ target,
+ );
+ totalFxImpact += app.fxGainLossAmount;
}
-
- // 3) Unapplied cash → control account (no invoice anchor), payment rate.
- // Positive: cash beyond what was applied becomes new on-account credit.
- // Negative: this payment applied more than its cash, drawing down the
- // party's existing on-account credit (the inverse posting side).
- // The band is EPSILON, not a hand-picked 1e-4: whatever we DON'T book here
- // stays in the cash line with nothing to offset it, so anything the ledger
- // can store must get a line or the entry is stored out of balance. When the
- // columns were NUMERIC(19,4) a 1e-4 band was exactly "smaller than one
- // storable unit"; at scale 5 that same literal drops ten storable units.
- const unappliedInPaymentCcy =
- totalAmount - applications.reduce((sum, a) => sum + Number(a.appliedAmount), 0);
- if (Math.abs(unappliedInPaymentCcy) > EPSILON) {
- const buildingCredit = unappliedInPaymentCcy > 0;
- pushLine(
- cashIn === buildingCredit ? "credit" : "debit",
+ if (currentDocumentReleased > totalAmount + EPSILON) {
+ throw new Error("Applications exceed current document cash");
+ }
+ assertBalanced(
+ grossBase,
+ round(currentCashReleased + newOnAccountBase),
+ EPSILON,
+ "Current payment funding",
+ );
+ push(
+ cashIn ? "credit" : "debit",
+ isAR ? "asset" : "liability",
+ newOnAccountBase,
+ accounts.controlAccountId,
+ onAccountCreditDescription(isAR),
+ );
+ for (const [accountId, amount] of priorCreditReleased) {
+ push(
+ cashIn ? "debit" : "credit",
isAR ? "asset" : "liability",
- round(Math.abs(unappliedInPaymentCcy) * exchangeRate),
- {
- accountId: controlAccountId,
- description: isAR
- ? buildingCredit
- ? "Accounts Receivable (on-account credit)"
- : "Accounts Receivable (credit applied)"
- : buildingCredit
- ? "Accounts Payable (on-account credit)"
- : "Accounts Payable (credit applied)",
- }
+ amount,
+ accountId,
+ `${isAR ? "Accounts Receivable" : "Accounts Payable"} (credit applied)`,
);
}
-
- // 4) FX plug (single line). Same reasoning as the unapplied band above — an
- // unbooked FX residual has nothing to offset it.
- if (Math.abs(totalFxImpact) > EPSILON) {
- const fxBase = round(Math.abs(totalFxImpact));
- if (totalFxImpact > 0) {
- if (!fxGainAccountId) {
- throw new Error("Missing realized FX gain account default");
- }
- pushLine("credit", "revenue", fxBase, {
- accountId: fxGainAccountId,
- description: "Realized FX Gain",
- });
- } else {
- if (!fxLossAccountId) {
- throw new Error("Missing realized FX loss account default");
- }
- pushLine("debit", "expense", fxBase, {
- accountId: fxLossAccountId,
- description: "Realized FX Loss",
- });
- }
+ totalFxImpact = round(totalFxImpact);
+ if (totalFxImpact > 0) {
+ push(
+ "credit",
+ "revenue",
+ totalFxImpact,
+ accounts.fxGainAccountId,
+ "Realized FX Gain",
+ );
+ } else if (totalFxImpact < 0) {
+ push(
+ "debit",
+ "expense",
+ -totalFxImpact,
+ accounts.fxLossAccountId,
+ "Realized FX Loss",
+ );
}
-
- // Self-check: the entry must balance in true debit/credit space. The FX plug
- // (same formula as the stored fxGainLossAmount) should make this ~0; a larger
- // residual means a logic/rounding bug, so we refuse to post rather than write
- // an unbalanced journal to the GL. BALANCE_TOLERANCE is a business threshold
- // (multi-currency journals carry sub-cent cross-rate residuals), NOT the
- // float-noise default.
assertBalanced(
signedDebitTotal,
0,
- BALANCE_TOLERANCE,
- "Payment journal (base currency)"
+ EPSILON,
+ "Payment journal (base currency)",
);
-
return { lines, signedDebitTotal, totalFxImpact };
}
diff --git a/packages/database/supabase/functions/post-payment/index.ts b/packages/database/supabase/functions/post-payment/index.ts
index cb8cc8f3ac..3980cfbca0 100644
--- a/packages/database/supabase/functions/post-payment/index.ts
+++ b/packages/database/supabase/functions/post-payment/index.ts
@@ -1,5 +1,4 @@
import { serve } from "https://deno.land/[email protected]/http/server.ts";
-import { nanoid } from "https://deno.land/x/[email protected]/mod.ts";
import z from "npm:zod@^4.5.4";
import { DB, getConnectionPool, getDatabaseClient } from "../lib/database.ts";
import { datetime, getCompanyTimeZone } from "../lib/datetime.ts";
@@ -7,14 +6,7 @@ import { getFunctionLogger } from "../lib/logging.ts";
import { corsPreflight, errorResponse, jsonResponse } from "../lib/response.ts";
import { getSupabaseServiceRole } from "../lib/supabase.ts";
-import { getCurrentAccountingPeriod } from "../shared/get-accounting-period.ts";
-import { getNextSequence } from "../shared/get-next-sequence.ts";
-import { getDefaultPostingGroup } from "../shared/get-posting-group.ts";
-import {
- buildPaymentJournal,
- type PaymentJournalLine,
-} from "./build-payment-journal.ts";
-import { round } from "../shared/precision.ts";
+import { postPaymentTransaction } from "./post-payment-transaction.ts";
const pool = getConnectionPool(1);
const db = getDatabaseClient<DB>(pool);
@@ -45,783 +37,30 @@ serve(async (req: Request) => {
const payload = await req.json();
try {
- const { type, paymentId, userId, companyId, fee } =
- payloadValidator.parse(payload);
+ const { type, paymentId, userId, companyId, fee } = payloadValidator.parse(
+ payload,
+ );
logger.info({ type, paymentId, userId, companyId });
const client = await getSupabaseServiceRole(
req.headers.get("Authorization"),
req.headers.get("carbon-key") ?? "",
- companyId
- );
- const today = datetime.today(await getCompanyTimeZone(client, companyId)).toString();
-
- const accountingSettings = await client
- .from("companySettings")
- .select("accountingEnabled")
- .eq("id", companyId)
- .single();
- const accountingEnabled = accountingSettings.data?.accountingEnabled ?? false;
-
- const [payment, applications, credits, accountDefaults] = await Promise.all([
- client.from("payment").select("*").eq("id", paymentId).single(),
- client.from("invoiceSettlement").select("*").eq("paymentId", paymentId),
- client
- .from("invoiceSettlement")
- .select("*")
- .eq("appliedViaPaymentId", paymentId),
- getDefaultPostingGroup(client, companyId),
- ]);
-
- if (payment.error) throw new Error("Failed to fetch payment");
- if (applications.error) throw new Error("Failed to fetch payment applications");
- if (credits.error) throw new Error("Failed to fetch credit applications");
- if (accountingEnabled && accountDefaults.error)
- throw new Error("Failed to fetch account defaults");
-
- // cashIn: direction of cash (Receipt = into our bank). isAR: which ledger
- // this settles (a customer → AR, a supplier → AP). Decoupled so refunds work
- // (a Disbursement to a customer is an AR refund; a Receipt from a supplier is
- // an AP refund). See build-payment-journal's two-axis note.
- const cashIn = payment.data.paymentType === "Receipt";
- const isAR = payment.data.customerId != null;
-
- // --------------------------------------------------------------
- // VOID
- // --------------------------------------------------------------
- if (type === "void") {
- if (payment.data.status !== "Posted") {
- throw new Error(
- `Cannot void payment in status ${payment.data.status} (only Posted)`
- );
- }
-
- const accountingPeriodId = accountingEnabled
- ? await getCurrentAccountingPeriod(client, companyId, db, today)
- : null;
-
- await db.transaction().execute(async (trx) => {
- // Lock the payment row and re-assert it's still Posted INSIDE the
- // transaction. The status check above runs before the lock (a TOCTOU
- // window): two concurrent voids could otherwise both pass it and each
- // emit a reversing journal. The FOR UPDATE serializes them.
- const lockedPayment = await trx
- .selectFrom("payment")
- .select(["id", "status"])
- .where("id", "=", paymentId)
- .where("companyId", "=", companyId)
- .forUpdate()
- .executeTakeFirst();
- if (!lockedPayment) throw new Error("Payment not found");
- if (lockedPayment.status !== "Posted") {
- throw new Error(
- `Cannot void payment in status ${lockedPayment.status} (only Posted)`
- );
- }
-
- if (accountingEnabled && payment.data.journalId) {
- // Pull the original journal's lines and emit a reversing journal
- // (mirror amounts). This matches post-purchase-invoice's void
- // approach — a paired journal rather than mutating the original.
- const originalLines = await trx
- .selectFrom("journalLine")
- .selectAll()
- .where("journalId", "=", payment.data.journalId)
- .execute();
-
- if (originalLines.length > 0) {
- const voidEntryId = await getNextSequence(
- trx,
- "journalEntry",
- companyId
- );
-
- const voidJournal = await trx
- .insertInto("journal")
- .values({
- journalEntryId: voidEntryId,
- accountingPeriodId,
- description: `VOID Payment ${payment.data.paymentId}`,
- postingDate: today,
- companyId,
- sourceType: "Payment",
- status: "Posted",
- postedAt: new Date().toISOString(),
- postedBy: userId,
- createdBy: userId,
- })
- .returning(["id"])
- .executeTakeFirstOrThrow();
-
- const voidLineResults = await trx
- .insertInto("journalLine")
- .values(
- originalLines.map((line) => ({
- journalId: voidJournal.id,
- accountId: line.accountId,
- amount: -line.amount,
- quantity: line.quantity,
- description: `VOID: ${line.description ?? ""}`,
- documentType: "Payment" as const,
- documentId: paymentId,
- documentLineReference: line.documentLineReference,
- journalLineReference: line.journalLineReference,
- companyId,
- }))
- )
- .returning(["id"])
- .execute();
-
- // Carry the original lines' dimensions onto the reversing lines so
- // dimension-filtered balances net to zero after the void.
- const origDimensions = await trx
- .selectFrom("journalLineDimension")
- .select(["journalLineId", "dimensionId", "valueId"])
- .where(
- "journalLineId",
- "in",
- originalLines.map((l) => l.id)
- )
- .execute();
- if (origDimensions.length > 0) {
- const idxByOriginalId = new Map(
- originalLines.map((l, i) => [l.id, i])
- );
- await trx
- .insertInto("journalLineDimension")
- .values(
- origDimensions.map((d) => ({
- journalLineId:
- voidLineResults[idxByOriginalId.get(d.journalLineId)!].id,
- dimensionId: d.dimensionId,
- valueId: d.valueId,
- companyId,
- }))
- )
- .execute();
- }
- }
- }
-
- await trx
- .updateTable("payment")
- .set({
- status: "Voided",
- voidedAt: new Date().toISOString(),
- voidedBy: userId,
- updatedAt: new Date().toISOString(),
- updatedBy: userId,
- })
- .where("id", "=", paymentId)
- .where("companyId", "=", companyId)
- .execute();
- });
-
- return jsonResponse({ success: true });
- }
-
- // --------------------------------------------------------------
- // POST
- // --------------------------------------------------------------
- if (payment.data.status !== "Draft") {
- throw new Error(
- `Cannot post payment in status ${payment.data.status} (only Draft)`
- );
- }
- if (payment.data.exchangeRate <= 0) {
- throw new Error("Payment exchange rate must be > 0");
- }
-
- // Invoice ids referenced by this payment's applications. The lock +
- // validation against invoice state (existence, counterparty, active
- // status, over-settlement cap) happens inside the commit transaction
- // below, NOT here — see the note on the application-level checks.
- // Credit applications staged on this payment (memo-sourced, GL-neutral). They
- // go live when the payment posts, so they share the per-invoice over-settlement
- // cap with cash — but they are NOT cash, so they don't post GL or count toward
- // the cash-vs-total (overApplied) check below.
- const creditByInvoice = new Map<string, number>();
- for (const c of credits.data ?? []) {
- const invId = (isAR
- ? c.targetSalesInvoiceId
- : c.targetPurchaseInvoiceId) as string | null;
- if (!invId) continue;
- creditByInvoice.set(
- invId,
- (creditByInvoice.get(invId) ?? 0) + Number(c.appliedAmount)
- );
- }
-
- const salesInvoiceIds = [
- ...new Set([
- ...applications.data
- .filter((a) => a.targetSalesInvoiceId)
- .map((a) => a.targetSalesInvoiceId as string),
- ...(isAR ? [...creditByInvoice.keys()] : []),
- ]),
- ];
- const purchaseInvoiceIds = [
- ...new Set([
- ...applications.data
- .filter((a) => a.targetPurchaseInvoiceId)
- .map((a) => a.targetPurchaseInvoiceId as string),
- ...(!isAR ? [...creditByInvoice.keys()] : []),
- ]),
- ];
-
- if (isAR && purchaseInvoiceIds.length > 0) {
- throw new Error("Receipt cannot apply to purchase invoices");
- }
- if (!isAR && salesInvoiceIds.length > 0) {
- throw new Error("Disbursement cannot apply to sales invoices");
- }
-
- // Application-level checks that need no invoice state. The invoice-
- // dependent checks run INSIDE the transaction below, after the invoice
- // rows are locked — otherwise two concurrent posts could both read the
- // same prior-settled total and both slip past the over-settlement cap.
- for (const app of applications.data) {
- if (app.targetExchangeRate <= 0 || app.sourceExchangeRate <= 0) {
- throw new Error("Application exchange rates must be > 0");
- }
- }
-
- // Cash vs applied (base ccy). When applied < cash the remainder is new
- // on-account credit; when applied > cash the excess must be funded by the
- // party's existing on-account credit (validated under lock inside the
- // commit transaction below, where prior posted payments are serialized).
- const totalAppliedBase = applications.data.reduce(
- (sum, a) => sum + Number(a.appliedAmount) * Number(a.sourceExchangeRate),
- 0
+ companyId,
);
- const paymentTotalBase = Number(payment.data.totalAmount) * Number(payment.data.exchangeRate);
- const overAppliedBase = round(totalAppliedBase - paymentTotalBase);
-
- // --------------------------------------------------------------
- // Build journal lines (in base currency)
- // --------------------------------------------------------------
- const accountingPeriodId = accountingEnabled
- ? await getCurrentAccountingPeriod(client, companyId, db, today)
- : null;
-
- const journalLineInserts: PaymentJournalLine[] = [];
- // Dimensions to tag on every payment journal line so AR/AP can be reported
- // by counterparty. We tag both the counterparty *type* (CustomerType /
- // SupplierType) and the specific counterparty *entity* (Customer / Supplier).
- const partyDimensions: { dimensionId: string; valueId: string }[] = [];
-
- if (accountingEnabled) {
- if (!accountDefaults.data) {
- throw new Error(
- "Accounting is enabled but this company has no account defaults configured"
- );
- }
- const ad = accountDefaults.data;
- const journalLineReference = nanoid();
-
- // Intercompany invoices are booked to the IC receivables account
- // (1130) at posting, so the payment must relieve the same control
- // account — otherwise 1130 stays debited and regular AR goes negative.
- let controlAccountId = isAR ? ad.receivablesAccount : ad.payablesAccount;
-
- // Resolve the counterparty type + entity dimensions for this payment.
- const companyRecord = await client
- .from("company")
- .select("companyGroupId")
- .eq("id", companyId)
- .single();
- const companyGroupId = companyRecord.data?.companyGroupId ?? null;
- const partyId = isAR
- ? (payment.data.customerId as string | null)
- : (payment.data.supplierId as string | null);
- const typeEntityType = isAR ? "CustomerType" : "SupplierType";
- const entityEntityType = isAR ? "Customer" : "Supplier";
- if (companyGroupId && partyId) {
- const [partyRow, dimRows] = await Promise.all([
- isAR
- ? client
- .from("customer")
- .select("customerTypeId, intercompanyCompanyId")
- .eq("id", partyId)
- .maybeSingle()
- : client
- .from("supplier")
- .select("supplierTypeId")
- .eq("id", partyId)
- .maybeSingle(),
- client
- .from("dimension")
- .select("id, entityType")
- .eq("companyGroupId", companyGroupId)
- .eq("active", true)
- .in("entityType", [typeEntityType, entityEntityType]),
- ]);
- const dimByEntityType = new Map<string, string>();
- for (const d of dimRows.data ?? []) {
- if (d.entityType) dimByEntityType.set(d.entityType, d.id);
- }
- // deno-lint-ignore no-explicit-any
- const party = partyRow.data as any;
- const partyTypeId = isAR
- ? (party?.customerTypeId ?? null)
- : (party?.supplierTypeId ?? null);
- const typeDimensionId = dimByEntityType.get(typeEntityType);
- if (typeDimensionId && partyTypeId) {
- partyDimensions.push({
- dimensionId: typeDimensionId,
- valueId: partyTypeId,
- });
- }
- const entityDimensionId = dimByEntityType.get(entityEntityType);
- if (entityDimensionId) {
- partyDimensions.push({
- dimensionId: entityDimensionId,
- valueId: partyId,
- });
- }
-
- if (isAR && party?.intercompanyCompanyId) {
- // Relieve the same control account the invoice was booked to. Resolve
- // it from accountDefault (stable id), not by account number — numbers
- // are user-editable. Fall back to regular receivables if unset.
- const icReceivablesAccount = (
- ad as unknown as {
- intercompanyReceivablesAccount?: string | null;
- }
- ).intercompanyReceivablesAccount;
- if (icReceivablesAccount) {
- controlAccountId = icReceivablesAccount;
- }
- }
- }
-
- // Resolve the discount account's class so buildPaymentJournal signs the
- // discount line by the account's real natural balance (customer discount
- // → Revenue/contra-revenue; supplier discount → Expense/contra-COGS),
- // mirroring how post-memo resolves its reason account's class.
- const discountAccountId = isAR
- ? ad.customerPaymentDiscountAccount
- : ad.supplierPaymentDiscountAccount;
- let discountAccountClass: string | null = null;
- if (discountAccountId) {
- const discountAccount = await client
- .from("account")
- .select("class")
- .eq("id", discountAccountId)
- .single();
- if (discountAccount.error || !discountAccount.data) {
- throw new Error("Failed to fetch the payment discount account class");
- }
- discountAccountClass = discountAccount.data.class as string;
- }
-
- // Build the balanced double-entry. Account-id resolution, the per-
- // application control/discount/write-off lines, the on-account-credit
- // line, the single FX plug, and the balance self-check all live in the
- // pure `buildPaymentJournal` so they are unit-tested (post-payment.test.ts).
- const { lines } = buildPaymentJournal({
- paymentId,
- companyId,
- isAR,
- cashIn,
- totalAmount: Number(payment.data.totalAmount),
- exchangeRate: Number(payment.data.exchangeRate),
- bankAccount: payment.data.bankAccount,
- journalLineReference,
- applications: applications.data.map((a) => ({
- targetSalesInvoiceId: a.targetSalesInvoiceId,
- targetPurchaseInvoiceId: a.targetPurchaseInvoiceId,
- appliedAmount: Number(a.appliedAmount),
- discountAmount: Number(a.discountAmount),
- writeOffAmount: Number(a.writeOffAmount),
- targetExchangeRate: Number(a.targetExchangeRate),
- sourceExchangeRate: Number(a.sourceExchangeRate),
- })),
- accounts: {
- controlAccountId,
- discountAccountId,
- discountAccountClass,
- writeOffAccountId: isAR
- ? ad.customerWriteOffAccount
- : ad.supplierWriteOffAccount,
- fxGainAccountId: ad.realizedExchangeGainAccount,
- fxLossAccountId: ad.realizedExchangeLossAccount,
- },
- fee,
- });
- journalLineInserts.push(...lines);
- }
-
- // --------------------------------------------------------------
- // Commit: lock + validate the invoices under the transaction, then post.
- // --------------------------------------------------------------
- const paymentPartyId = isAR
- ? payment.data.customerId
- : payment.data.supplierId;
- const activeStatus = isAR ? "Submitted" : "Open";
-
- let createdJournalId: string | null = null;
- await db.transaction().execute(async (trx) => {
- // Lock the payment row and re-assert it's still Draft INSIDE the
- // transaction. The status check above runs before the lock (a TOCTOU
- // window): two concurrent posts could otherwise both pass it and each
- // write a journal + settlements (the invoice lock below doesn't help a
- // payment with no invoice applications, or a partial application under the
- // over-settlement cap). The FOR UPDATE serializes them so the second aborts.
- const lockedPayment = await trx
- .selectFrom("payment")
- .select(["id", "status"])
- .where("id", "=", paymentId)
- .where("companyId", "=", companyId)
- .forUpdate()
- .executeTakeFirst();
- if (!lockedPayment) throw new Error("Payment not found");
- if (lockedPayment.status !== "Draft") {
- throw new Error(
- `Cannot post payment in status ${lockedPayment.status} (only Draft)`
- );
- }
-
- // Lock + read the target invoices in one shot. Holding the row locks for
- // the rest of the transaction serializes concurrent posts so the
- // over-settlement cap below can't be raced (TOCTOU).
- const invoiceById = new Map<
- string,
- {
- status: string;
- totalAmount: number;
- // View balance = remaining open amount on the invoice.
- balance: number;
- partyId: string | null;
- }
- >();
- // The stored base "totalAmount" is deprecated (always 0 for invoices
- // posted after migration 20260604120000); the live total lives in the
- // salesInvoices/purchaseInvoices views. We can't lock a view (it joins +
- // aggregates), so we lock the base row FOR UPDATE — which serializes
- // concurrent posts and gives the raw posting status/party — and read the
- // live total from the view separately. Status MUST come from the base
- // row, not the view: the view derives 'Partially Paid'/'Paid', which
- // would wrongly fail the activeStatus check on a partially-settled
- // invoice.
- if (isAR && salesInvoiceIds.length > 0) {
- const rows = await trx
- .selectFrom("salesInvoice")
- .select(["id", "status", "customerId"])
- .where("id", "in", salesInvoiceIds)
- .forUpdate()
- .execute();
- const totals = await trx
- .selectFrom("salesInvoices")
- .select(["id", "totalAmount", "balance"])
- .where("id", "in", salesInvoiceIds)
- .execute();
- const viewById = new Map(totals.map((t) => [t.id, t]));
- for (const r of rows) {
- const v = viewById.get(r.id);
- invoiceById.set(r.id, {
- status: r.status as string,
- totalAmount: Number(v?.totalAmount ?? 0),
- balance: Number(v?.balance ?? 0),
- partyId: r.customerId,
- });
- }
- }
- if (!isAR && purchaseInvoiceIds.length > 0) {
- const rows = await trx
- .selectFrom("purchaseInvoice")
- .select(["id", "status", "supplierId"])
- .where("id", "in", purchaseInvoiceIds)
- .forUpdate()
- .execute();
- const totals = await trx
- .selectFrom("purchaseInvoices")
- .select(["id", "totalAmount", "balance"])
- .where("id", "in", purchaseInvoiceIds)
- .execute();
- const viewById = new Map(totals.map((t) => [t.id, t]));
- for (const r of rows) {
- const v = viewById.get(r.id);
- invoiceById.set(r.id, {
- status: r.status as string,
- totalAmount: Number(v?.totalAmount ?? 0),
- balance: Number(v?.balance ?? 0),
- partyId: r.supplierId,
- });
- }
- }
-
- // Validate each application against the locked invoice state.
- const currentSettledByInvoice = new Map<string, number>();
- for (const app of applications.data) {
- const invId = (isAR
- ? app.targetSalesInvoiceId
- : app.targetPurchaseInvoiceId) as string;
- const inv = invoiceById.get(invId);
- if (!inv) throw new Error(`Invoice ${invId} not found`);
- if (inv.partyId !== paymentPartyId) {
- throw new Error(
- `Invoice ${invId} belongs to a different ${isAR ? "customer" : "supplier"} than the payment`
- );
- }
- const settledByThisApp =
- Number(app.appliedAmount) +
- Number(app.discountAmount) +
- Number(app.writeOffAmount);
- currentSettledByInvoice.set(
- invId,
- (currentSettledByInvoice.get(invId) ?? 0) + settledByThisApp
- );
- const wouldSettle = currentSettledByInvoice.get(invId)!;
-
- if (inv.status !== activeStatus) {
- throw new Error(
- `Cannot apply payment to invoice ${invId} in status ${inv.status} (must be ${activeStatus})`
- );
- }
- // The view balance nets ALL posted settlements against this invoice —
- // cash AND credit/debit memos — so it's the true remaining open. (The
- // current Draft payment isn't posted, so its own applications aren't in
- // it yet.) Capping against it prevents over-settling an invoice already
- // (partly) cleared by a memo.
- const remainingOpen = inv.balance;
- if (wouldSettle > remainingOpen + 0.0001) {
- throw new Error(
- `Application total (${wouldSettle}) exceeds remaining open amount (${remainingOpen}) on invoice ${invId}`
- );
- }
- }
-
- // Staged credit applications go live when this payment posts, so fold them
- // into the same per-invoice cap: cash + credit must not over-settle.
- for (const [invId, creditAmt] of creditByInvoice) {
- const inv = invoiceById.get(invId);
- if (!inv) throw new Error(`Invoice ${invId} not found`);
- if (inv.partyId !== paymentPartyId) {
- throw new Error(
- `Invoice ${invId} belongs to a different ${isAR ? "customer" : "supplier"} than the payment`
- );
- }
- if (inv.status !== activeStatus) {
- throw new Error(
- `Cannot apply credit to invoice ${invId} in status ${inv.status} (must be ${activeStatus})`
- );
- }
- const wouldSettle = (currentSettledByInvoice.get(invId) ?? 0) + creditAmt;
- if (wouldSettle > inv.balance + 0.0001) {
- throw new Error(
- `Application total (${wouldSettle}) exceeds remaining open amount (${inv.balance}) on invoice ${invId}`
- );
- }
- }
-
- // The memos behind the staged credits must still be Posted with enough
- // remaining when the payment posts — a memo voided (or drawn down by
- // another payment) after staging must fail the post, not go live
- // silently. FOR UPDATE serializes concurrent posts drawing on the same
- // memo.
- const stagedByMemo = new Map<string, number>();
- for (const c of credits.data ?? []) {
- if (!c.memoId) continue;
- stagedByMemo.set(
- c.memoId,
- (stagedByMemo.get(c.memoId) ?? 0) + Number(c.appliedAmount)
- );
- }
- if (stagedByMemo.size > 0) {
- const memoIds = [...stagedByMemo.keys()];
- const memos = await trx
- .selectFrom("memo")
- .select(["id", "status", "amount"])
- .where("id", "in", memoIds)
- .where("companyId", "=", companyId)
- .forUpdate()
- .execute();
- const memoById = new Map(memos.map((m) => [m.id, m]));
-
- // Live consumption of these memos: memo-sourced settlement rows that
- // are not staged on a non-Posted payment. This payment's own staged
- // rows are excluded (its via-payment is still Draft here).
- const memoApps = await trx
- .selectFrom("invoiceSettlement")
- .leftJoin(
- "payment as vp",
- "vp.id",
- "invoiceSettlement.appliedViaPaymentId"
- )
- .select(["invoiceSettlement.memoId", "invoiceSettlement.appliedAmount"])
- .where("invoiceSettlement.memoId", "in", memoIds)
- .where((eb) =>
- eb.or([
- eb("invoiceSettlement.appliedViaPaymentId", "is", null),
- eb("vp.status", "=", "Posted"),
- ])
- )
- .execute();
- const appliedByMemo = new Map<string, number>();
- for (const a of memoApps) {
- if (!a.memoId) continue;
- appliedByMemo.set(
- a.memoId,
- (appliedByMemo.get(a.memoId) ?? 0) + Number(a.appliedAmount)
- );
- }
-
- for (const [memoId, staged] of stagedByMemo) {
- const memo = memoById.get(memoId);
- if (!memo) throw new Error(`Memo ${memoId} not found`);
- if (memo.status !== "Posted") {
- throw new Error(
- `Cannot post payment: memo ${memoId} is ${memo.status} (must be Posted)`
- );
- }
- const remaining =
- Number(memo.amount) - (appliedByMemo.get(memoId) ?? 0);
- if (staged > remaining + 0.0001) {
- throw new Error(
- `Staged credit (${staged}) exceeds remaining amount (${remaining}) on memo ${memoId}`
- );
- }
- }
- }
-
- // When this payment applies more than its cash, the excess draws down the
- // party's available on-account credit — the net unapplied cash left on
- // their OTHER posted payments. Lock those payments FOR UPDATE so two
- // concurrent credit-consuming posts can't both spend the same credit.
- if (overAppliedBase > 0.0001) {
- // Only same-direction payments contribute credit: a Receipt from a
- // customer leaves on-account credit; a Disbursement to the same
- // customer is a refund that CONSUMES credit, not a source of it.
- // Mirrors getAvailableOnAccountCredit in invoicing.service.ts.
- const creditPaymentType = isAR ? "Receipt" : "Disbursement";
- const postedPayments = await (isAR
- ? trx
- .selectFrom("payment")
- .select(["id", "totalAmount", "exchangeRate"])
- .where("companyId", "=", companyId)
- .where("status", "=", "Posted")
- .where("paymentType", "=", creditPaymentType)
- .where("customerId", "=", paymentPartyId)
- .forUpdate()
- .execute()
- : trx
- .selectFrom("payment")
- .select(["id", "totalAmount", "exchangeRate"])
- .where("companyId", "=", companyId)
- .where("status", "=", "Posted")
- .where("paymentType", "=", creditPaymentType)
- .where("supplierId", "=", paymentPartyId)
- .forUpdate()
- .execute());
-
- let availableCreditBase = 0;
- if (postedPayments.length > 0) {
- const postedIds = postedPayments.map((p) => p.id);
- const priorApps = await trx
- .selectFrom("invoiceSettlement")
- .select(["paymentId", "appliedAmount", "sourceExchangeRate"])
- .where("paymentId", "in", postedIds)
- .execute();
- const appliedBaseByPayment = new Map<string, number>();
- for (const a of priorApps) {
- appliedBaseByPayment.set(
- a.paymentId,
- (appliedBaseByPayment.get(a.paymentId) ?? 0) +
- Number(a.appliedAmount) * Number(a.sourceExchangeRate)
- );
- }
- for (const p of postedPayments) {
- availableCreditBase +=
- Number(p.totalAmount) * Number(p.exchangeRate) -
- (appliedBaseByPayment.get(p.id) ?? 0);
- }
- }
-
- if (overAppliedBase > round(availableCreditBase) + 0.0001) {
- throw new Error(
- `Applied exceeds payment cash by ${overAppliedBase} in base currency, but only ${round(availableCreditBase)} of on-account credit is available for this ${isAR ? "customer" : "supplier"}`
- );
- }
- }
-
- // GL journal (only when accounting is enabled).
- let journalId: string | null = null;
- if (accountingEnabled) {
- const journalEntryId = await getNextSequence(
- trx,
- "journalEntry",
- companyId
- );
- const journalResult = await trx
- .insertInto("journal")
- .values({
- journalEntryId,
- accountingPeriodId,
- description: `Payment ${payment.data.paymentId}`,
- postingDate: today,
- companyId,
- sourceType: "Payment",
- status: "Posted",
- postedAt: new Date().toISOString(),
- postedBy: userId,
- createdBy: userId,
- })
- .returning(["id"])
- .executeTakeFirstOrThrow();
- journalId = journalResult.id;
-
- if (journalLineInserts.length > 0) {
- const journalLineResults = await trx
- .insertInto("journalLine")
- .values(
- journalLineInserts.map((line) => ({
- ...line,
- journalId: journalResult.id,
- }))
- )
- .returning(["id"])
- .execute();
-
- // Tag every line with the counterparty dimensions (type + entity).
- if (partyDimensions.length > 0) {
- await trx
- .insertInto("journalLineDimension")
- .values(
- journalLineResults.flatMap((jl) =>
- partyDimensions.map((d) => ({
- journalLineId: jl.id,
- dimensionId: d.dimensionId,
- valueId: d.valueId,
- companyId,
- }))
- )
- )
- .execute();
- }
- }
- }
-
- await trx
- .updateTable("payment")
- .set({
- status: "Posted",
- postingDate: today,
- journalId,
- postedAt: new Date().toISOString(),
- postedBy: userId,
- updatedAt: new Date().toISOString(),
- updatedBy: userId,
- })
- .where("id", "=", paymentId)
- .where("companyId", "=", companyId)
- .execute();
-
- createdJournalId = journalId;
+ const today = datetime.today(await getCompanyTimeZone(client, companyId))
+ .toString();
+
+ const result = await postPaymentTransaction(db, {
+ type,
+ paymentId,
+ companyId,
+ userId,
+ today,
+ client,
+ fee,
});
-
- return jsonResponse({ success: true, journalId: createdJournalId });
+ return jsonResponse({ success: true, ...result });
} catch (err) {
return errorResponse(err, 500);
}
diff --git a/packages/database/supabase/functions/post-payment/payment-refunds.test.ts b/packages/database/supabase/functions/post-payment/payment-refunds.test.ts
new file mode 100644
index 0000000000..428a4a1b01
--- /dev/null
+++ b/packages/database/supabase/functions/post-payment/payment-refunds.test.ts
@@ -0,0 +1,315 @@
+import {
+ assertEquals,
+ assertRejects,
+} from "https://deno.land/[email protected]/testing/asserts.ts";
+import { databaseTest, paymentFixture } from "./payment-test-fixture.ts";
+import { postPaymentTransaction } from "./post-payment-transaction.ts";
+import { postMemoTransaction } from "../post-memo/post-memo-transaction.ts";
+
+type Fixture = Awaited<ReturnType<typeof paymentFixture>>;
+async function party(f: Fixture, isAR: boolean) {
+ if (isAR) {
+ await f.db.updateTable("accountDefault").set({
+ salesDiscountAccount: f.account("discount"),
+ }).where("companyId", "=", f.companyId).execute();
+ return { id: f.customerId, control: f.account("control") };
+ }
+ const supplier = await f.db.insertInto("supplier").values({
+ name: "Refund supplier",
+ companyId: f.companyId,
+ }).returning("id").executeTakeFirstOrThrow();
+ const control = f.account("payable");
+ await f.db.insertInto("account").values({
+ id: control,
+ name: "AP",
+ class: "Liability",
+ incomeBalance: "Balance Sheet",
+ companyGroupId: f.groupId,
+ createdBy: "system",
+ }).execute();
+ await f.db.updateTable("accountDefault").set({
+ payablesAccount: control,
+ supplierPaymentDiscountAccount: f.account("discount"),
+ supplierWriteOffAccount: f.account("sales"),
+ }).where("companyId", "=", f.companyId).execute();
+ return { id: supplier.id, control };
+}
+async function memo(
+ f: Fixture,
+ isAR: boolean,
+ partyId: string,
+ amount: number,
+ rate: number,
+) {
+ const id = crypto.randomUUID();
+ await f.db.insertInto("memo").values({
+ id,
+ memoId: id,
+ companyId: f.companyId,
+ customerId: isAR ? partyId : null,
+ supplierId: isAR ? null : partyId,
+ direction: isAR ? "Credit" : "Debit",
+ memoDate: "2026-09-07",
+ currencyCode: "EUR",
+ exchangeRate: rate,
+ amount,
+ createdBy: "system",
+ }).execute();
+ await postMemoTransaction(f.db, { ...f.args, memoId: id });
+ return id;
+}
+for (const isAR of [true, false]) {
+ databaseTest(
+ `${
+ isAR ? "AR" : "AP"
+ } memo refund uses original carrying and cash FX, blocks memo void, then reverses`,
+ async () => {
+ const f = await paymentFixture();
+ try {
+ const p = await party(f, isAR);
+ const memoId = await memo(f, isAR, p.id, 55, 1.1);
+ const paymentId = await f.payment({
+ amount: 55,
+ rate: 1.25,
+ noApplication: true,
+ });
+ await f.db.updateTable("payment").set({
+ paymentType: isAR ? "Disbursement" : "Receipt",
+ customerId: isAR ? p.id : null,
+ supplierId: isAR ? null : p.id,
+ }).where("id", "=", paymentId).where("companyId", "=", f.companyId)
+ .execute();
+ await f.db.insertInto("invoiceSettlement").values({
+ paymentId,
+ targetMemoId: memoId,
+ sourceAmount: 55,
+ appliedAmount: 50,
+ sourceExchangeRate: 1.25,
+ targetExchangeRate: 1.1,
+ appliedDate: "2026-09-07",
+ companyId: f.companyId,
+ createdBy: "system",
+ }).execute();
+ const changedControl = isAR
+ ? f.account("bank")
+ : f.account("changed-payable");
+ if (!isAR) {
+ await f.db.insertInto("account").values({
+ id: changedControl,
+ name: "New AP default",
+ class: "Liability",
+ incomeBalance: "Balance Sheet",
+ companyGroupId: f.groupId,
+ createdBy: "system",
+ }).execute();
+ }
+ await f.db.updateTable("accountDefault").set(
+ isAR
+ ? { receivablesAccount: changedControl }
+ : { payablesAccount: changedControl },
+ ).where("companyId", "=", f.companyId).execute();
+ const posted = await postPaymentTransaction(f.db, {
+ ...f.args,
+ paymentId,
+ });
+ const settlement = await f.db.selectFrom("invoiceSettlement").select([
+ "sourceAmount",
+ "appliedAmount",
+ "fxGainLossAmount",
+ "targetMemoId",
+ "sourcePaymentId",
+ ]).where("paymentId", "=", paymentId).executeTakeFirstOrThrow();
+ assertEquals(settlement, {
+ sourceAmount: 55,
+ appliedAmount: 50,
+ fxGainLossAmount: isAR ? 6 : -6,
+ targetMemoId: memoId,
+ sourcePaymentId: null,
+ });
+ const lines = await f.db.selectFrom("journalLine").select([
+ "accountId",
+ "amount",
+ ]).where("journalId", "=", posted.journalId!).execute();
+ assertEquals(
+ lines.find((line) => line.accountId === p.control)?.amount,
+ 50,
+ );
+ assertEquals(
+ lines.find((line) => line.accountId === f.account("bank"))?.amount,
+ isAR ? -44 : 44,
+ );
+ const excessive = await f.payment({
+ amount: 55,
+ rate: 1.25,
+ noApplication: true,
+ });
+ await f.db.updateTable("payment").set({
+ paymentType: isAR ? "Disbursement" : "Receipt",
+ customerId: isAR ? p.id : null,
+ supplierId: isAR ? null : p.id,
+ }).where("id", "=", excessive).where("companyId", "=", f.companyId)
+ .execute();
+ await f.db.insertInto("invoiceSettlement").values({
+ paymentId: excessive,
+ targetMemoId: memoId,
+ sourceAmount: 55,
+ appliedAmount: 50,
+ sourceExchangeRate: 1.25,
+ targetExchangeRate: 1.1,
+ appliedDate: "2026-09-07",
+ companyId: f.companyId,
+ createdBy: "system",
+ }).execute();
+ await assertRejects(
+ () =>
+ postPaymentTransaction(f.db, { ...f.args, paymentId: excessive }),
+ Error,
+ );
+ assertEquals(
+ (await f.db.selectFrom("payment").select("status").where(
+ "id",
+ "=",
+ excessive,
+ ).executeTakeFirstOrThrow()).status,
+ "Draft",
+ );
+ await assertRejects(
+ () => postMemoTransaction(f.db, { ...f.args, type: "void", memoId }),
+ Error,
+ "consumed memo",
+ );
+ const reversed = await postPaymentTransaction(f.db, {
+ ...f.args,
+ type: "void",
+ paymentId,
+ });
+ const reversal = await f.db.selectFrom("journalLine").select([
+ "accountId",
+ "amount",
+ ]).where("journalId", "=", reversed.journalId!).execute();
+ assertEquals(
+ reversal.find((line) => line.accountId === p.control)?.amount,
+ -50,
+ );
+ await postMemoTransaction(f.db, { ...f.args, type: "void", memoId });
+ } finally {
+ await f.cleanup();
+ }
+ },
+ );
+}
+
+for (const isAR of [true, false]) {
+ databaseTest(
+ `${
+ isAR ? "AR" : "AP"
+ } final memo document cent posts when its carrying remainder is zero`,
+ async () => {
+ const f = await paymentFixture();
+ try {
+ const p = await party(f, isAR);
+ const memoId = await memo(f, isAR, p.id, 160.01, 16000);
+ let invoiceId: string;
+ if (isAR) {
+ invoiceId = await f.invoice({ amount: 0.010000625, rate: 16000 });
+ } else {
+ invoiceId = crypto.randomUUID();
+ const interaction = await f.db.insertInto("supplierInteraction")
+ .values({ supplierId: p.id, companyId: f.companyId }).returning(
+ "id",
+ ).executeTakeFirstOrThrow();
+ await f.db.insertInto("purchaseInvoice").values({
+ id: invoiceId,
+ invoiceId,
+ supplierId: p.id,
+ supplierInteractionId: interaction.id,
+ currencyCode: "EUR",
+ exchangeRate: 16000,
+ status: "Open",
+ companyId: f.companyId,
+ createdBy: "system",
+ }).execute();
+ await f.db.insertInto("purchaseInvoiceLine").values({
+ invoiceId,
+ invoiceLineType: "G/L Account",
+ quantity: .16001,
+ supplierUnitPrice: 1000,
+ exchangeRate: 16000,
+ accountId: f.account("loss"),
+ companyId: f.companyId,
+ createdBy: "system",
+ }).execute();
+ const period = await f.db.selectFrom("accountingPeriod").select("id")
+ .where("companyId", "=", f.companyId).executeTakeFirstOrThrow();
+ const journal = await f.db.insertInto("journal").values({
+ journalEntryId: invoiceId,
+ accountingPeriodId: period.id,
+ companyId: f.companyId,
+ sourceType: "Purchase Invoice",
+ status: "Posted",
+ postingDate: "2026-09-07",
+ createdBy: "system",
+ }).returning("id").executeTakeFirstOrThrow();
+ await f.db.insertInto("journalLine").values(
+ [{ accountId: p.control, description: "Accounts Payable" }, {
+ accountId: f.account("loss"),
+ description: "Invoice offset",
+ }].map((line) => ({
+ ...line,
+ amount: .01,
+ quantity: 1,
+ journalId: journal.id,
+ documentId: invoiceId,
+ documentType: "Invoice" as const,
+ journalLineReference: invoiceId,
+ companyId: f.companyId,
+ })),
+ ).execute();
+ }
+ for (const [sourceAmount, appliedAmount] of [[160, .01], [.01, 0]]) {
+ const paymentId = await f.payment({
+ amount: 0,
+ rate: 16000,
+ noApplication: true,
+ });
+ if (!isAR) {
+ await f.db.updateTable("payment").set({
+ paymentType: "Disbursement",
+ customerId: null,
+ supplierId: p.id,
+ }).where("id", "=", paymentId).where("companyId", "=", f.companyId)
+ .execute();
+ }
+ await f.db.insertInto("invoiceSettlement").values({
+ memoId,
+ appliedViaPaymentId: paymentId,
+ targetSalesInvoiceId: isAR ? invoiceId : null,
+ targetPurchaseInvoiceId: isAR ? null : invoiceId,
+ sourceAmount,
+ appliedAmount,
+ sourceExchangeRate: 16000,
+ targetExchangeRate: 16000,
+ appliedDate: "2026-09-07",
+ companyId: f.companyId,
+ createdBy: "system",
+ }).execute();
+ await postPaymentTransaction(f.db, { ...f.args, paymentId });
+ }
+ const rows = await f.db.selectFrom("invoiceSettlement").select([
+ "sourceAmount",
+ "appliedAmount",
+ ]).where("memoId", "=", memoId).execute();
+ assertEquals(
+ rows.reduce((sum, row) => sum + Number(row.sourceAmount), 0),
+ 160.01,
+ );
+ assertEquals(
+ rows.reduce((sum, row) => sum + Number(row.appliedAmount), 0),
+ .01,
+ );
+ } finally {
+ await f.cleanup();
+ }
+ },
+ );
+}
diff --git a/packages/database/supabase/functions/post-payment/payment-test-fixture.ts b/packages/database/supabase/functions/post-payment/payment-test-fixture.ts
new file mode 100644
index 0000000000..3396c3c7d5
--- /dev/null
+++ b/packages/database/supabase/functions/post-payment/payment-test-fixture.ts
@@ -0,0 +1,350 @@
+// Isolated local fixtures shared by transaction and concurrency regressions.
+import { sql } from "kysely";
+import { type DB, getDatabaseClient } from "../lib/database.ts";
+import { Pool } from "pg";
+import type { SupabaseClient } from "@supabase/supabase-js";
+import type { Database } from "../lib/types.ts";
+
+/** Is an existing LOCAL database configured?
+ *
+ * These regressions exercise real transactions, row locks and concurrency, so
+ * they cannot be faked against a mock. Without a database they SKIP rather than
+ * fail: hard-failing made a bare `deno test` red on a clean checkout, which is
+ * a large part of why none of this directory was ever wired into CI. A skip is
+ * visible in the run output; a failure just trains people to ignore the suite. */
+export const hasLocalDatabase: boolean = (() => {
+ try {
+ // Also catches PermissionDenied: this runs at module scope, so without
+ // --allow-env it would throw before a single pure test could run.
+ const databaseUrl = Deno.env.get("SUPABASE_DB_URL");
+ if (!databaseUrl) return false;
+ return ["localhost", "127.0.0.1", "[::1]"].includes(
+ new URL(databaseUrl).hostname,
+ );
+ } catch {
+ return false;
+ }
+})();
+
+/** `Deno.test` for a regression that requires the local database. */
+export function databaseTest(
+ name: string,
+ fn: () => void | Promise<void>,
+): void {
+ Deno.test({ name, ignore: !hasLocalDatabase, fn });
+}
+
+export async function connectPaymentTestDatabase() {
+ const databaseUrl = Deno.env.get("SUPABASE_DB_URL");
+ if (!databaseUrl) throw new Error("Payment regressions require SUPABASE_DB_URL for an existing local database");
+ const url = new URL(databaseUrl);
+ if (!["localhost", "127.0.0.1", "[::1]"].includes(url.hostname)) {
+ throw new Error("Payment regressions require an existing local database");
+ }
+ const db = getDatabaseClient<DB>(
+ new Pool({
+ hostname: url.hostname,
+ port: Number(url.port),
+ user: decodeURIComponent(url.username),
+ password: decodeURIComponent(url.password),
+ database: url.pathname.slice(1),
+ controls: { decoders: { 1700: Number } },
+ tls: { enabled: false },
+ }, 1),
+ );
+ // The fixture uses the pool's single connection; requests in the real seam
+ // therefore inherit trigger suppression even when they open a new transaction.
+ await sql`SELECT set_config('app.sync_in_progress', 'true', false)`.execute(
+ db,
+ );
+ return db;
+}
+
+export async function paymentFixture() {
+ const db = await connectPaymentTestDatabase();
+ const prefix = `accttest-${
+ crypto.randomUUID().replaceAll("-", "").slice(0, 12)
+ }`;
+ const companyId = `${prefix}-company`;
+ const groupId = `${prefix}-group`;
+ const customerId = `${prefix}-customer`;
+ const invoiceId = `${prefix}-invoice`;
+ const periodId = `${prefix}-period`;
+ const account = (name: string) => `${prefix}-${name}`;
+ await db.transaction().execute(async (trx) => {
+ await sql`SET LOCAL "app.sync_in_progress" = 'true'`.execute(trx);
+ await trx.insertInto("companyGroup").values({
+ id: groupId,
+ name: prefix,
+ createdBy: "system",
+ }).execute();
+ await trx.insertInto("company").values({
+ id: companyId,
+ name: prefix,
+ companyGroupId: groupId,
+ baseCurrencyCode: "USD",
+ timezone: "America/New_York",
+ }).execute();
+ await trx.insertInto("currency").values(
+ ["USD", "EUR"].map((code) => ({
+ code,
+ decimalPlaces: 2,
+ companyGroupId: groupId,
+ createdBy: "system",
+ })),
+ ).execute();
+ await trx.insertInto("account").values([
+ { name: "bank", class: "Asset" as const },
+ { name: "control", class: "Asset" as const },
+ { name: "sales", class: "Revenue" as const },
+ { name: "gain", class: "Revenue" as const },
+ { name: "loss", class: "Expense" as const },
+ { name: "discount", class: "Expense" as const },
+ { name: "writeoff", class: "Expense" as const },
+ ].map((row) => ({
+ id: account(row.name),
+ name: row.name,
+ class: row.class,
+ incomeBalance: row.class === "Asset"
+ ? "Balance Sheet" as const
+ : "Income Statement" as const,
+ companyGroupId: groupId,
+ createdBy: "system",
+ }))).execute();
+ await sql`INSERT INTO "accountDefault" SELECT (jsonb_populate_record(NULL::"accountDefault",
+ (SELECT jsonb_object_agg(attname, to_jsonb(${
+ account("control")
+ }::text)) FROM pg_attribute
+ WHERE attrelid='"accountDefault"'::regclass AND attnum>0 AND NOT attisdropped AND attnotnull AND attname<>'companyId')
+ || jsonb_build_object('companyId', ${companyId}::text, 'receivablesAccount', ${
+ account("control")
+ }::text,
+ 'salesAccount', ${account("sales")}::text, 'bankCashAccount', ${
+ account("bank")
+ }::text,
+ 'realizedExchangeGainAccount', ${
+ account("gain")
+ }::text, 'realizedExchangeLossAccount', ${account("loss")}::text,
+ 'customerPaymentDiscountAccount', ${
+ account("discount")
+ }::text, 'customerWriteOffAccount', ${account("writeoff")}::text))).*`
+ .execute(trx);
+ await trx.insertInto("companySettings").values({
+ id: companyId,
+ accountingEnabled: true,
+ }).onConflict((oc) =>
+ oc.column("id").doUpdateSet({ accountingEnabled: true })
+ ).execute();
+ await trx.insertInto("accountingPeriod").values({
+ id: periodId,
+ startDate: "2026-09-01",
+ endDate: "2026-09-30",
+ status: "Active",
+ closeStatus: "Open",
+ companyId,
+ createdBy: "system",
+ }).execute();
+ await trx.insertInto("sequence").values({
+ table: "journalEntry",
+ name: "Test journals",
+ prefix: "TEST-",
+ companyId,
+ }).execute();
+ await trx.insertInto("customer").values({
+ id: customerId,
+ name: prefix,
+ companyId,
+ }).execute();
+ await trx.insertInto("salesInvoice").values({
+ id: invoiceId,
+ invoiceId: "TEST-INVOICE",
+ customerId,
+ currencyCode: "EUR",
+ exchangeRate: 1.1,
+ status: "Submitted",
+ companyId,
+ createdBy: "system",
+ }).execute();
+ await trx.insertInto("salesInvoiceLine").values({
+ invoiceId,
+ invoiceLineType: "Service",
+ quantity: 1,
+ unitPrice: 100,
+ unitOfMeasureCode: "EA",
+ companyId,
+ createdBy: "system",
+ }).execute();
+ const journal = await trx.insertInto("journal").values({
+ journalEntryId: "TEST-ORIGINAL",
+ accountingPeriodId: periodId,
+ companyId,
+ sourceType: "Sales Invoice",
+ status: "Posted",
+ postingDate: "2026-09-01",
+ createdBy: "system",
+ }).returning("id").executeTakeFirstOrThrow();
+ await trx.insertInto("journalLine").values([
+ { accountId: account("control"), description: "Accounts Receivable" },
+ { accountId: account("sales"), description: "Sales" },
+ ].map((row) => ({
+ ...row,
+ amount: 100,
+ quantity: 1,
+ documentType: "Invoice" as const,
+ documentId: invoiceId,
+ journalLineReference: `${prefix}-reference`,
+ journalId: journal.id,
+ companyId,
+ }))).execute();
+ });
+ const client = {
+ from: () => {
+ const query = {
+ select: () => query,
+ eq: () => query,
+ gte: () => query,
+ lte: () => query,
+ single: async () => ({
+ data: { id: periodId, status: "Active", closeStatus: "Open" },
+ error: null,
+ }),
+ };
+ return query;
+ },
+ } as unknown as SupabaseClient<Database>;
+ const args = {
+ type: "post" as const,
+ companyId,
+ userId: "system",
+ today: "2026-09-07",
+ client,
+ };
+ return {
+ db,
+ args,
+ companyId,
+ groupId,
+ invoiceId,
+ customerId,
+ account,
+ connect: connectPaymentTestDatabase,
+ async payment(
+ input: {
+ amount?: number;
+ rate?: number;
+ status?: "Draft" | "Posted";
+ sourceAmount?: number;
+ appliedAmount?: number;
+ targetRate?: number;
+ noApplication?: boolean;
+ sourcePaymentId?: string;
+ invoiceId?: string;
+ } = {},
+ ) {
+ const id = `${prefix}-payment-${crypto.randomUUID()}`;
+ await db.transaction().execute(async (trx) => {
+ await sql`SET LOCAL "app.sync_in_progress" = 'true'`.execute(trx);
+ await trx.insertInto("payment").values({
+ id,
+ paymentId: id,
+ paymentType: "Receipt",
+ customerId,
+ paymentDate: "2026-09-01",
+ postingDate: "2026-09-01",
+ currencyCode: "EUR",
+ totalAmount: input.amount ?? 110,
+ exchangeRate: input.rate ?? 1.1,
+ bankAccount: account("bank"),
+ status: input.status ?? "Draft",
+ companyId,
+ createdBy: "system",
+ }).execute();
+ if (!input.noApplication) {
+ await trx.insertInto("invoiceSettlement").values({
+ paymentId: id,
+ targetSalesInvoiceId: input.invoiceId ?? invoiceId,
+ sourceAmount: input.sourceAmount ?? 110,
+ appliedAmount: input.appliedAmount ?? 100,
+ sourcePaymentId: input.sourcePaymentId,
+ sourceExchangeRate: 99,
+ targetExchangeRate: input.targetRate ?? 99,
+ appliedDate: "2026-09-01",
+ companyId,
+ createdBy: "system",
+ }).execute();
+ }
+ });
+ return id;
+ },
+ async invoice(input: { amount?: number; rate?: number; controlDescription?: string } = {}) {
+ const id = `${prefix}-invoice-${crypto.randomUUID()}`;
+ await db.transaction().execute(async (trx) => {
+ await sql`SET LOCAL "app.sync_in_progress" = 'true'`.execute(trx);
+ await trx.insertInto("salesInvoice").values({
+ id,
+ invoiceId: id,
+ customerId,
+ currencyCode: "EUR",
+ exchangeRate: input.rate ?? 1.1,
+ status: "Submitted",
+ companyId,
+ createdBy: "system",
+ }).execute();
+ await trx.insertInto("salesInvoiceLine").values({
+ invoiceId: id,
+ invoiceLineType: "Service",
+ quantity: 1,
+ unitPrice: input.amount ?? 100,
+ unitOfMeasureCode: "EA",
+ companyId,
+ createdBy: "system",
+ }).execute();
+ const journal = await trx.insertInto("journal").values({
+ journalEntryId: id,
+ accountingPeriodId: periodId,
+ companyId,
+ sourceType: "Sales Invoice",
+ status: "Posted",
+ postingDate: "2026-09-01",
+ createdBy: "system",
+ }).returning("id").executeTakeFirstOrThrow();
+ await trx.insertInto("journalLine").values([
+ { accountId: account("control"), description: input.controlDescription ?? "Accounts Receivable" },
+ { accountId: account("sales"), description: "Sales" },
+ ].map((row) => ({
+ ...row,
+ amount: input.amount ?? 100,
+ quantity: 1,
+ documentType: "Invoice" as const,
+ documentId: id,
+ journalLineReference: id,
+ journalId: journal.id,
+ companyId,
+ }))).execute();
+ });
+ return id;
+ },
+ async cleanup() {
+ await db.transaction().execute(async (trx) => {
+ await sql`SET LOCAL "app.sync_in_progress" = 'true'`.execute(trx);
+ // Test-owned committed journals are immutable. Temporarily bypass only
+ // for their cleanup status update; restore normal FK cascades immediately.
+ await sql`SET LOCAL session_replication_role = replica`.execute(trx);
+ await trx.updateTable("journal").set({ status: "Draft" }).where(
+ "companyId",
+ "=",
+ companyId,
+ ).execute();
+ await sql`SET LOCAL session_replication_role = origin`.execute(trx);
+ await trx.deleteFrom("company").where("id", "=", companyId).execute();
+ await trx.deleteFrom("companyGroup").where("id", "=", groupId)
+ .execute();
+ await sql`DROP TABLE IF EXISTS ${sql.id(`searchIndex_${companyId}`)}`
+ .execute(trx);
+ await sql`DROP TABLE IF EXISTS ${sql.id(`auditLog_${companyId}`)}`
+ .execute(trx);
+ });
+ await db.destroy();
+ },
+ };
+}
diff --git a/packages/database/supabase/functions/post-payment/post-payment-concurrency.test.ts b/packages/database/supabase/functions/post-payment/post-payment-concurrency.test.ts
new file mode 100644
index 0000000000..5f9178ef51
--- /dev/null
+++ b/packages/database/supabase/functions/post-payment/post-payment-concurrency.test.ts
@@ -0,0 +1,115 @@
+import { assertEquals } from "https://deno.land/[email protected]/testing/asserts.ts";
+import { databaseTest, paymentFixture } from "./payment-test-fixture.ts";
+import { postPaymentTransaction } from "./post-payment-transaction.ts";
+
+databaseTest("independent concurrent invoice consumers cannot overspend one posted credit source", async () => {
+ const f = await paymentFixture();
+ const left = await f.connect();
+ const right = await f.connect();
+ try {
+ const secondInvoiceId = await f.invoice();
+ const sourceId = await f.payment({
+ amount: 110,
+ rate: 1,
+ noApplication: true,
+ });
+ await postPaymentTransaction(f.db, { ...f.args, paymentId: sourceId });
+ const firstId = await f.payment({ amount: 0, rate: 1.5 });
+ const secondId = await f.payment({
+ amount: 0,
+ rate: 1.5,
+ invoiceId: secondInvoiceId,
+ });
+ const attempts = await Promise.allSettled([
+ postPaymentTransaction(left, { ...f.args, paymentId: firstId }),
+ postPaymentTransaction(right, { ...f.args, paymentId: secondId }),
+ ]);
+ assertEquals(
+ attempts.filter((attempt) => attempt.status === "fulfilled").length,
+ 1,
+ );
+ const rejected = attempts.find((attempt) => attempt.status === "rejected");
+ if (rejected?.status !== "rejected") {
+ throw new Error("Expected exhausted source rejection");
+ }
+ assertEquals(
+ /fund|exceed|insufficient/i.test(String(rejected.reason)),
+ true,
+ );
+ const posted = await f.db.selectFrom("payment").select("id").where(
+ "companyId",
+ "=",
+ f.companyId,
+ )
+ .where("id", "in", [firstId, secondId]).where("status", "=", "Posted")
+ .execute();
+ assertEquals(posted.length, 1);
+ const consumption = await f.db.selectFrom("invoiceSettlement as s")
+ .innerJoin("payment as p", "p.id", "s.paymentId").select([
+ "s.sourceAmount",
+ "s.appliedAmount",
+ "s.fxGainLossAmount",
+ ])
+ .where("s.companyId", "=", f.companyId).where(
+ "s.sourcePaymentId",
+ "=",
+ sourceId,
+ ).where("p.status", "=", "Posted").execute();
+ assertEquals(
+ consumption.reduce((sum, row) => sum + Number(row.sourceAmount), 0),
+ 110,
+ );
+ assertEquals(
+ consumption.reduce(
+ (sum, row) =>
+ sum + Number(row.appliedAmount) + Number(row.fxGainLossAmount),
+ 0,
+ ),
+ 110,
+ );
+ const paymentJournals = await f.db.selectFrom("journal").select("id").where(
+ "companyId",
+ "=",
+ f.companyId,
+ ).where("sourceType", "=", "Payment").execute();
+ assertEquals(paymentJournals.length, 2);
+ } finally {
+ await left.destroy();
+ await right.destroy();
+ await f.cleanup();
+ }
+});
+
+databaseTest("concurrent retries of one payment create exactly one journal and funding allocation", async () => {
+ const f = await paymentFixture();
+ const left = await f.connect();
+ const right = await f.connect();
+ try {
+ const paymentId = await f.payment();
+ const results = await Promise.all([
+ postPaymentTransaction(left, { ...f.args, paymentId }),
+ postPaymentTransaction(right, { ...f.args, paymentId }),
+ ]);
+ assertEquals(results[0].journalId, results[1].journalId);
+ assertEquals(
+ (await f.db.selectFrom("invoiceSettlement").select("id").where(
+ "companyId",
+ "=",
+ f.companyId,
+ ).where("paymentId", "=", paymentId).execute()).length,
+ 1,
+ );
+ assertEquals(
+ (await f.db.selectFrom("journal").select("id").where(
+ "companyId",
+ "=",
+ f.companyId,
+ ).where("sourceType", "=", "Payment").execute()).length,
+ 1,
+ );
+ } finally {
+ await left.destroy();
+ await right.destroy();
+ await f.cleanup();
+ }
+});
diff --git a/packages/database/supabase/functions/post-payment/post-payment-transaction.test.ts b/packages/database/supabase/functions/post-payment/post-payment-transaction.test.ts
new file mode 100644
index 0000000000..11e8505440
--- /dev/null
+++ b/packages/database/supabase/functions/post-payment/post-payment-transaction.test.ts
@@ -0,0 +1,391 @@
+import {
+ assertEquals,
+ assertRejects,
+} from "https://deno.land/[email protected]/testing/asserts.ts";
+import { databaseTest, paymentFixture } from "./payment-test-fixture.ts";
+import { postPaymentTransaction } from "./post-payment-transaction.ts";
+
+databaseTest("posting locks authoritative snapshots, overwrites forged rates, and is idempotent", async () => {
+ const f = await paymentFixture();
+ try {
+ const paymentId = await f.payment();
+ const result = await postPaymentTransaction(f.db, { ...f.args, paymentId });
+ const row = await f.db.selectFrom("invoiceSettlement").selectAll().where(
+ "paymentId",
+ "=",
+ paymentId,
+ ).executeTakeFirstOrThrow();
+ assertEquals(row.sourceAmount, 110);
+ assertEquals(row.appliedAmount, 100);
+ assertEquals(row.sourceExchangeRate, 1.1);
+ assertEquals(row.targetExchangeRate, 1.1);
+ assertEquals(row.fxGainLossAmount, 0);
+ assertEquals(
+ (await postPaymentTransaction(f.db, { ...f.args, paymentId })).journalId,
+ result.journalId,
+ );
+ const journalLines = await f.db.selectFrom("journalLine").select([
+ "accountId",
+ "amount",
+ ]).where("journalId", "=", result.journalId!).execute();
+ assertEquals(
+ journalLines.find((line) => line.accountId === f.account("bank"))?.amount,
+ 100,
+ );
+ } finally {
+ await f.cleanup();
+ }
+});
+
+databaseTest("target over-consumption rolls back and leaves the payment draft unchanged", async () => {
+ const f = await paymentFixture();
+ try {
+ const paymentId = await f.payment({ amount: 111, sourceAmount: 111 });
+ await assertRejects(
+ () => postPaymentTransaction(f.db, { ...f.args, paymentId }),
+ Error,
+ "exceeds",
+ );
+ const payment = await f.db.selectFrom("payment").select([
+ "status",
+ "journalId",
+ ]).where("id", "=", paymentId).executeTakeFirstOrThrow();
+ assertEquals(payment.status, "Draft");
+ assertEquals(payment.journalId, null);
+ const draft = await f.db.selectFrom("invoiceSettlement").selectAll().where(
+ "paymentId",
+ "=",
+ paymentId,
+ ).executeTakeFirstOrThrow();
+ assertEquals(draft.sourceExchangeRate, 99);
+ } finally {
+ await f.cleanup();
+ }
+});
+
+databaseTest("prior credit is attributed to its original source and source void is blocked until consumer void", async () => {
+ const f = await paymentFixture();
+ try {
+ const sourceId = await f.payment({ noApplication: true, rate: 1 });
+ await postPaymentTransaction(f.db, { ...f.args, paymentId: sourceId });
+ const paymentId = await f.payment({ amount: 0, rate: 1.5 });
+ await postPaymentTransaction(f.db, { ...f.args, paymentId });
+ const row = await f.db.selectFrom("invoiceSettlement").selectAll().where(
+ "paymentId",
+ "=",
+ paymentId,
+ ).executeTakeFirstOrThrow();
+ assertEquals(row.sourcePaymentId, sourceId);
+ assertEquals(row.sourceExchangeRate, 1);
+ assertEquals(row.fxGainLossAmount, 10);
+ await assertRejects(
+ () =>
+ postPaymentTransaction(f.db, {
+ ...f.args,
+ paymentId: sourceId,
+ type: "void",
+ }),
+ Error,
+ "consum",
+ );
+ await postPaymentTransaction(f.db, { ...f.args, paymentId, type: "void" });
+ await postPaymentTransaction(f.db, {
+ ...f.args,
+ paymentId: sourceId,
+ type: "void",
+ });
+ } finally {
+ await f.cleanup();
+ }
+});
+
+databaseTest("a sequence fault after settlement replacement rolls the entire post back", async () => {
+ const f = await paymentFixture();
+ try {
+ const paymentId = await f.payment();
+ const before = await f.db.selectFrom("invoiceSettlement").selectAll().where(
+ "paymentId",
+ "=",
+ paymentId,
+ ).execute();
+ await f.db.deleteFrom("sequence").where("companyId", "=", f.companyId)
+ .where("table", "=", "journalEntry").execute();
+ await assertRejects(
+ () => postPaymentTransaction(f.db, { ...f.args, paymentId }),
+ Error,
+ "no result",
+ );
+ assertEquals(
+ await f.db.selectFrom("invoiceSettlement").selectAll().where(
+ "paymentId",
+ "=",
+ paymentId,
+ ).execute(),
+ before,
+ );
+ const payment = await f.db.selectFrom("payment").select([
+ "status",
+ "journalId",
+ ]).where("id", "=", paymentId).executeTakeFirstOrThrow();
+ assertEquals(payment, { status: "Draft", journalId: null });
+ assertEquals(
+ await f.db.selectFrom("journal").select("id").where(
+ "companyId",
+ "=",
+ f.companyId,
+ ).where("sourceType", "=", "Payment").execute(),
+ [],
+ );
+ } finally {
+ await f.cleanup();
+ }
+});
+
+databaseTest("accounting-disabled posting still rejects an invalid bank account", async () => {
+ const f = await paymentFixture();
+ try {
+ await f.db.updateTable("companySettings").set({ accountingEnabled: false })
+ .where("id", "=", f.companyId).execute();
+ await f.db.updateTable("account").set({ active: false }).where(
+ "id",
+ "=",
+ f.account("bank"),
+ ).execute();
+ const paymentId = await f.payment();
+ await assertRejects(
+ () => postPaymentTransaction(f.db, { ...f.args, paymentId }),
+ Error,
+ "bank account",
+ );
+ assertEquals(
+ (await f.db.selectFrom("payment").select("status").where(
+ "id",
+ "=",
+ paymentId,
+ ).executeTakeFirstOrThrow()).status,
+ "Draft",
+ );
+ } finally {
+ await f.cleanup();
+ }
+});
+
+databaseTest("a wrong new-credit control account class cannot create an unbalanced stored ledger", async () => {
+ const f = await paymentFixture();
+ try {
+ await f.db.updateTable("accountDefault").set({
+ receivablesAccount: f.account("sales"),
+ }).where("companyId", "=", f.companyId).execute();
+ const paymentId = await f.payment({ amount: 165 });
+ await assertRejects(
+ () => postPaymentTransaction(f.db, { ...f.args, paymentId }),
+ Error,
+ "account class",
+ );
+ assertEquals(
+ (await f.db.selectFrom("payment").select("status").where(
+ "id",
+ "=",
+ paymentId,
+ ).executeTakeFirstOrThrow()).status,
+ "Draft",
+ );
+ } finally {
+ await f.cleanup();
+ }
+});
+
+databaseTest("positive document remainder with zero base carrying remains eligible until its final unit", async () => {
+ const f = await paymentFixture();
+ try {
+ const invoiceId = await f.invoice({ amount: 0.01, rate: 16001 });
+ const sourceId = await f.payment({
+ noApplication: true,
+ amount: 160.01,
+ rate: 16001,
+ });
+ await postPaymentTransaction(f.db, { ...f.args, paymentId: sourceId });
+ const firstId = await f.payment({
+ amount: 0,
+ rate: 16001,
+ invoiceId,
+ sourceAmount: 160,
+ appliedAmount: 0.01,
+ });
+ await postPaymentTransaction(f.db, { ...f.args, paymentId: firstId });
+ const partial = await f.db.selectFrom("salesInvoices").select([
+ "status",
+ "balance",
+ ]).where("id", "=", invoiceId).executeTakeFirstOrThrow();
+ assertEquals(partial.status, "Partially Paid");
+ const lastId = await f.payment({
+ amount: 0,
+ rate: 16001,
+ invoiceId,
+ sourceAmount: 0.01,
+ appliedAmount: 0,
+ });
+ await postPaymentTransaction(f.db, { ...f.args, paymentId: lastId });
+ const final = await f.db.selectFrom("invoiceSettlement").select([
+ "sourceAmount",
+ "appliedAmount",
+ "fxGainLossAmount",
+ ]).where("paymentId", "=", lastId).executeTakeFirstOrThrow();
+ assertEquals(final, {
+ sourceAmount: 0.01,
+ appliedAmount: 0,
+ fxGainLossAmount: 0,
+ });
+ assertEquals(
+ (await f.db.selectFrom("salesInvoices").select("status").where(
+ "id",
+ "=",
+ invoiceId,
+ ).executeTakeFirstOrThrow()).status,
+ "Paid",
+ );
+ } finally {
+ await f.cleanup();
+ }
+});
+
+databaseTest("changed defaults preserve original invoice and prior-credit control accounts", async () => {
+ const f = await paymentFixture();
+ try {
+ await f.db.insertInto("account").values(
+ ["credit-control", "new-control"].map((name) => ({
+ id: f.account(name),
+ name,
+ class: "Asset" as const,
+ incomeBalance: "Balance Sheet" as const,
+ companyGroupId: f.groupId,
+ createdBy: "system",
+ })),
+ ).execute();
+ await f.db.updateTable("accountDefault").set({
+ receivablesAccount: f.account("credit-control"),
+ }).where("companyId", "=", f.companyId).execute();
+ const sourceId = await f.payment({ noApplication: true });
+ await postPaymentTransaction(f.db, { ...f.args, paymentId: sourceId });
+ await f.db.updateTable("accountDefault").set({
+ receivablesAccount: f.account("new-control"),
+ }).where("companyId", "=", f.companyId).execute();
+ const paymentId = await f.payment({ amount: 0 });
+ const result = await postPaymentTransaction(f.db, { ...f.args, paymentId });
+ const lines = await f.db.selectFrom("journalLine").select([
+ "accountId",
+ "amount",
+ "description",
+ ]).where("journalId", "=", result.journalId!).execute();
+ assertEquals(
+ lines.find((line) => line.description === "Accounts Receivable")
+ ?.accountId,
+ f.account("control"),
+ );
+ assertEquals(
+ lines.find((line) =>
+ line.description === "Accounts Receivable (credit applied)"
+ )?.accountId,
+ f.account("credit-control"),
+ );
+ assertEquals(
+ lines.some((line) => line.accountId === f.account("new-control")),
+ false,
+ );
+ } finally {
+ await f.cleanup();
+ }
+});
+
+for (const isAR of [true, false]) {
+ databaseTest(`${isAR ? "AR" : "AP"} mixed-sign original controls settle their net carrying without fictitious FX`, async () => {
+ const f = await paymentFixture();
+ try {
+ const invoiceId = isAR ? f.invoiceId : `${f.companyId}-purchase`;
+ const controlId = isAR ? f.account("control") : f.account("payable");
+ const paymentId = await f.payment({
+ amount: 90, rate: 1, sourceAmount: 90, appliedAmount: 90,
+ noApplication: !isAR,
+ });
+ const journal = await f.db.selectFrom("journal").select([
+ "id", "accountingPeriodId",
+ ]).where("companyId", "=", f.companyId)
+ .where("sourceType", "=", "Sales Invoice").executeTakeFirstOrThrow();
+ if (isAR) {
+ await f.db.updateTable("salesInvoice").set({ exchangeRate: 1 })
+ .where("id", "=", invoiceId).where("companyId", "=", f.companyId).execute();
+ await f.db.insertInto("salesInvoiceLine").values({
+ invoiceId, invoiceLineType: "Service", quantity: 1, unitPrice: -10,
+ unitOfMeasureCode: "EA", companyId: f.companyId, createdBy: "system",
+ }).execute();
+ } else {
+ const supplier = await f.db.insertInto("supplier").values({
+ name: "Mixed-sign supplier", companyId: f.companyId,
+ }).returning("id").executeTakeFirstOrThrow();
+ const interaction = await f.db.insertInto("supplierInteraction").values({
+ supplierId: supplier.id, companyId: f.companyId,
+ }).returning("id").executeTakeFirstOrThrow();
+ await f.db.insertInto("account").values({
+ id: controlId, name: "Mixed-sign AP", class: "Liability",
+ incomeBalance: "Balance Sheet", companyGroupId: f.groupId, createdBy: "system",
+ }).execute();
+ await f.db.updateTable("accountDefault").set({
+ payablesAccount: controlId, supplierPaymentDiscountAccount: f.account("discount"),
+ supplierWriteOffAccount: f.account("sales"),
+ }).where("companyId", "=", f.companyId).execute();
+ await f.db.insertInto("purchaseInvoice").values({
+ id: invoiceId, invoiceId, supplierId: supplier.id,
+ supplierInteractionId: interaction.id, currencyCode: "EUR", exchangeRate: 1,
+ status: "Open", companyId: f.companyId, createdBy: "system",
+ }).execute();
+ await f.db.insertInto("purchaseInvoiceLine").values([100, -10].map((amount) => ({
+ invoiceId, invoiceLineType: "G/L Account" as const, quantity: 1,
+ supplierUnitPrice: amount, exchangeRate: 1, accountId: f.account("loss"),
+ companyId: f.companyId, createdBy: "system",
+ }))).execute();
+ await f.db.updateTable("payment").set({
+ paymentType: "Disbursement", customerId: null, supplierId: supplier.id,
+ }).where("id", "=", paymentId).where("companyId", "=", f.companyId).execute();
+ await f.db.insertInto("invoiceSettlement").values({
+ paymentId, targetPurchaseInvoiceId: invoiceId, sourceAmount: 90, appliedAmount: 90,
+ sourceExchangeRate: 1, targetExchangeRate: 1,
+ appliedDate: "2026-09-07", companyId: f.companyId, createdBy: "system",
+ }).execute();
+ }
+ const extraJournal = await f.db.insertInto("journal").values({
+ journalEntryId: `${invoiceId}-adjustment`, accountingPeriodId: journal.accountingPeriodId,
+ companyId: f.companyId, sourceType: isAR ? "Sales Invoice" : "Purchase Invoice",
+ status: "Posted", postingDate: "2026-09-01", createdBy: "system",
+ }).returning("id").executeTakeFirstOrThrow();
+ await f.db.insertInto("journalLine").values((isAR ? [-10] : [100, -10]).flatMap((amount) => [
+ { accountId: controlId, description: isAR ? "Accounts Receivable" : "Accounts Payable" },
+ { accountId: isAR ? f.account("sales") : f.account("loss"), description: "Invoice offset" },
+ ].map((line) => ({
+ ...line, amount, quantity: 1, journalId: extraJournal.id, documentId: invoiceId,
+ documentType: "Invoice" as const, journalLineReference: invoiceId, companyId: f.companyId,
+ })))).execute();
+ const result = await postPaymentTransaction(f.db, { ...f.args, paymentId });
+ const settlement = await f.db.selectFrom("invoiceSettlement").select([
+ "sourceAmount", "appliedAmount", "fxGainLossAmount",
+ ]).where("paymentId", "=", paymentId).where("companyId", "=", f.companyId).executeTakeFirstOrThrow();
+ assertEquals(settlement, { sourceAmount: 90, appliedAmount: 90, fxGainLossAmount: 0 });
+ const paymentLines = await f.db.selectFrom("journalLine").select(["amount", "accountId"])
+ .where("journalId", "=", result.journalId!).where("companyId", "=", f.companyId).execute();
+ assertEquals(paymentLines.filter((line) => line.accountId === controlId).reduce((sum, line) => sum + Number(line.amount), 90), 0);
+ } finally {
+ await f.cleanup();
+ }
+ });
+}
+
+databaseTest("intercompany invoice settlement retains its original control after defaults change", async () => {
+ const f = await paymentFixture();
+ try {
+ const invoiceId = await f.invoice({ controlDescription: "IC Receivables" });
+ await f.db.updateTable("accountDefault").set({ receivablesAccount: f.account("bank") }).where("companyId", "=", f.companyId).execute();
+ const paymentId = await f.payment({ invoiceId });
+ const posted = await postPaymentTransaction(f.db, { ...f.args, paymentId });
+ const lines = await f.db.selectFrom("journalLine").select(["accountId", "amount"]).where("journalId", "=", posted.journalId!).execute();
+ assertEquals(lines.find((line) => line.accountId === f.account("control"))?.amount, -100);
+ } finally { await f.cleanup(); }
+});
diff --git a/packages/database/supabase/functions/post-payment/post-payment-transaction.ts b/packages/database/supabase/functions/post-payment/post-payment-transaction.ts
new file mode 100644
index 0000000000..9f95c54b52
--- /dev/null
+++ b/packages/database/supabase/functions/post-payment/post-payment-transaction.ts
@@ -0,0 +1,930 @@
+import { type Kysely, sql, type Transaction } from "kysely";
+import { nanoid } from "https://deno.land/x/[email protected]/mod.ts";
+import type { SupabaseClient } from "@supabase/supabase-js";
+import type { DB } from "../lib/database.ts";
+import type { Database } from "../lib/types.ts";
+import {
+ buildPaymentJournal,
+ type PaymentJournalFeeInput,
+} from "./build-payment-journal.ts";
+import { datetime } from "../lib/datetime.ts";
+import { getCurrentAccountingPeriod } from "../shared/get-accounting-period.ts";
+import { getNextSequence } from "../shared/get-next-sequence.ts";
+import {
+ allocatePaymentFunding,
+ type FundingRequest,
+ invoiceRemainingAmounts,
+ isEffectiveSettlement,
+ remainingFundingSources,
+} from "../shared/payment-funding.ts";
+import {
+ assertCurrencyDecimals,
+ assertExchangeRate,
+ toBaseAmount,
+ toDocumentAmount,
+} from "../shared/accounting-currency.ts";
+import { round } from "../shared/precision.ts";
+import {
+ onAccountCreditDescription,
+ PAYABLE_POSTING_DESCRIPTIONS,
+ RECEIVABLE_POSTING_DESCRIPTIONS,
+} from "../shared/accounting-posting.ts";
+
+export type PostPaymentArgs = {
+ type: "post" | "void";
+ paymentId: string;
+ companyId: string;
+ userId: string;
+ today: string;
+ client: SupabaseClient<Database>;
+ fee?: PaymentJournalFeeInput;
+};
+
+function settlementQuery(trx: Transaction<DB>, companyId: string) {
+ return trx.selectFrom("invoiceSettlement as s")
+ .leftJoin(
+ "payment as p",
+ (join) =>
+ join.onRef("p.id", "=", "s.paymentId").onRef(
+ "p.companyId",
+ "=",
+ "s.companyId",
+ ),
+ )
+ .leftJoin(
+ "memo as m",
+ (join) =>
+ join.onRef("m.id", "=", "s.memoId").onRef(
+ "m.companyId",
+ "=",
+ "s.companyId",
+ ),
+ )
+ .leftJoin(
+ "payment as vp",
+ (join) =>
+ join.onRef("vp.id", "=", "s.appliedViaPaymentId").onRef(
+ "vp.companyId",
+ "=",
+ "s.companyId",
+ ),
+ )
+ .selectAll("s").select([
+ "p.status as paymentStatus",
+ "m.status as memoStatus",
+ "vp.status as viaStatus",
+ ])
+ .where("s.companyId", "=", companyId);
+}
+
+function principal(value: number | null, label: string): number {
+ if (value === null || !Number.isFinite(Number(value)) || Number(value) < 0) {
+ throw new Error(`Missing or invalid source principal for ${label}`);
+ }
+ return Number(value);
+}
+
+/** The endpoint's single commit boundary; every monetary snapshot is read under locks. */
+export function postPaymentTransaction(
+ db: Kysely<DB>,
+ args: PostPaymentArgs,
+): Promise<{ journalId: string | null }> {
+ const { companyId, paymentId, userId, today, client, fee, type } = args;
+ return db.transaction().execute(async (trx) => {
+ const payment = await trx.selectFrom("payment").selectAll()
+ .where("id", "=", paymentId).where("companyId", "=", companyId)
+ .forUpdate().executeTakeFirst();
+ if (!payment) throw new Error("Payment not found");
+ if (type === "post" && payment.status === "Posted") {
+ return { journalId: payment.journalId };
+ }
+ if (type === "void" && payment.status === "Voided") {
+ return { journalId: payment.journalId };
+ }
+ if (payment.status !== (type === "post" ? "Draft" : "Posted")) {
+ throw new Error(`Cannot ${type} payment in status ${payment.status}`);
+ }
+
+ const settings = await trx.selectFrom("companySettings").select(
+ "accountingEnabled",
+ ).where("id", "=", companyId).executeTakeFirst();
+ const accountingEnabled = settings?.accountingEnabled === true;
+ const timestamp = datetime.timestamp();
+ let accountingPeriodId: string | null = null;
+ if (accountingEnabled) {
+ accountingPeriodId = await getCurrentAccountingPeriod(
+ client,
+ companyId,
+ trx,
+ today,
+ );
+ // The reader also checks period status, but the row lock protects the
+ // posting against a concurrent close/lock after that read.
+ const period = await trx.selectFrom("accountingPeriod").select([
+ "id",
+ "closeStatus",
+ ])
+ .where("id", "=", accountingPeriodId).where("companyId", "=", companyId)
+ .forShare().executeTakeFirst();
+ if (
+ !period || period.closeStatus === "Closed" ||
+ period.closeStatus === "Locked"
+ ) throw new Error("Accounting period is closed or locked");
+ }
+
+ if (type === "void") {
+ const consumers = await settlementQuery(trx, companyId).where(
+ "s.sourcePaymentId",
+ "=",
+ paymentId,
+ ).execute();
+ if (
+ consumers.some((row) =>
+ isEffectiveSettlement(row) && principal(row.sourceAmount, row.id) > 0
+ )
+ ) {
+ throw new Error(
+ "Cannot void a funding source while posted payments consume its credit",
+ );
+ }
+ let reversalId: string | null = null;
+ if (payment.journalId) {
+ if (!accountingPeriodId) {
+ throw new Error(
+ "Enable accounting before reversing a posted payment journal",
+ );
+ }
+ const original = await trx.selectFrom("journalLine").selectAll().where(
+ "journalId",
+ "=",
+ payment.journalId,
+ ).where("companyId", "=", companyId).orderBy("id").execute();
+ if (original.length) {
+ const reversed = await trx.insertInto("journal").values({
+ journalEntryId: await getNextSequence(
+ trx,
+ "journalEntry",
+ companyId,
+ ),
+ accountingPeriodId,
+ description: `VOID Payment ${payment.paymentId}`,
+ postingDate: today,
+ companyId,
+ sourceType: "Payment",
+ status: "Posted",
+ postedAt: timestamp,
+ postedBy: userId,
+ createdBy: userId,
+ }).returning("id").executeTakeFirstOrThrow();
+ reversalId = reversed.id;
+ const lines = await trx.insertInto("journalLine").values(
+ original.map((line) => ({
+ journalId: reversed.id,
+ accountId: line.accountId,
+ amount: -Number(line.amount),
+ quantity: line.quantity,
+ description: `VOID: ${line.description ?? ""}`,
+ documentType: "Payment" as const,
+ documentId: paymentId,
+ documentLineReference: line.documentLineReference,
+ journalLineReference: line.journalLineReference,
+ companyId,
+ })),
+ ).returning("id").execute();
+ const dimensions = await trx.selectFrom("journalLineDimension")
+ .select(["journalLineId", "dimensionId", "valueId"])
+ .where("companyId", "=", companyId).where(
+ "journalLineId",
+ "in",
+ original.map((line) => line.id),
+ ).execute();
+ const reverseIdByOriginal = new Map(
+ original.map((line, index) => [line.id, lines[index].id]),
+ );
+ if (dimensions.length) {
+ await trx.insertInto("journalLineDimension").values(
+ dimensions.map((dimension) => ({
+ ...dimension,
+ journalLineId: reverseIdByOriginal.get(
+ dimension.journalLineId,
+ )!,
+ companyId,
+ })),
+ ).execute();
+ }
+ }
+ }
+ await trx.updateTable("payment").set({
+ status: "Voided",
+ voidedAt: timestamp,
+ voidedBy: userId,
+ updatedAt: timestamp,
+ updatedBy: userId,
+ })
+ .where("id", "=", paymentId).where("companyId", "=", companyId)
+ .execute();
+ return { journalId: reversalId };
+ }
+
+ const isAR = payment.customerId !== null;
+ const partyId = isAR ? payment.customerId : payment.supplierId;
+ if (
+ !partyId || Boolean(payment.customerId) === Boolean(payment.supplierId)
+ ) throw new Error("Payment must have exactly one customer or supplier");
+ const cashIn = payment.paymentType === "Receipt";
+ const isRefund = cashIn !== isAR;
+ assertExchangeRate(Number(payment.exchangeRate));
+ const company = await trx.selectFrom("company").select([
+ "companyGroupId",
+ "baseCurrencyCode",
+ ]).where("id", "=", companyId).executeTakeFirstOrThrow();
+ if (!company.companyGroupId || !payment.currencyCode) {
+ throw new Error("Payment currency configuration is missing");
+ }
+ const currency = await trx.selectFrom("currency").select("decimalPlaces")
+ .where("code", "=", payment.currencyCode).where(
+ "companyGroupId",
+ "=",
+ company.companyGroupId,
+ ).executeTakeFirst();
+ if (!currency || currency.decimalPlaces === null) {
+ throw new Error("Payment currency decimal places are not configured");
+ }
+ const decimals = currency.decimalPlaces;
+ assertCurrencyDecimals(decimals);
+ if (
+ company.baseCurrencyCode === payment.currencyCode &&
+ Number(payment.exchangeRate) !== 1
+ ) throw new Error("Base-currency payment must use exchange rate 1");
+
+ const drafts = await trx.selectFrom("invoiceSettlement").selectAll().where(
+ "companyId",
+ "=",
+ companyId,
+ )
+ .where((eb) =>
+ eb.or([
+ eb("paymentId", "=", paymentId),
+ eb("appliedViaPaymentId", "=", paymentId),
+ ])
+ ).orderBy("id").execute();
+ const targetColumn = isRefund
+ ? "targetMemoId"
+ : isAR
+ ? "targetSalesInvoiceId"
+ : "targetPurchaseInvoiceId";
+ for (const draft of drafts) {
+ if (
+ !draft[targetColumn] ||
+ (isRefund
+ ? draft.targetSalesInvoiceId || draft.targetPurchaseInvoiceId ||
+ draft.memoId ||
+ draft.sourcePaymentId || Number(draft.discountAmount) !== 0 ||
+ Number(draft.writeOffAmount) !== 0
+ : draft.targetMemoId ||
+ (isAR ? draft.targetPurchaseInvoiceId : draft.targetSalesInvoiceId))
+ ) throw new Error("Unsupported payment settlement target");
+ }
+ const targetIds = [...new Set(drafts.map((draft) => draft[targetColumn]!))]
+ .sort();
+ const memoIds = [
+ ...new Set(drafts.flatMap((draft) => draft.memoId ? [draft.memoId] : [])),
+ ].sort();
+ const refundMemos = isRefund && targetIds.length
+ ? await trx.selectFrom("memo").selectAll().where(
+ "companyId",
+ "=",
+ companyId,
+ )
+ .where("id", "in", targetIds).orderBy("id").forUpdate().execute()
+ : [];
+ const invoices = isRefund
+ ? refundMemos.map((memo) => ({
+ ...memo,
+ partyId: isAR ? memo.customerId : memo.supplierId,
+ }))
+ : targetIds.length
+ ? await (isAR
+ ? trx.selectFrom("salesInvoice").select([
+ "id",
+ "customerId as partyId",
+ "status",
+ "currencyCode",
+ "exchangeRate",
+ ]).where("companyId", "=", companyId).where("id", "in", targetIds)
+ .orderBy("id").forUpdate().execute()
+ : trx.selectFrom("purchaseInvoice").select([
+ "id",
+ "supplierId as partyId",
+ "status",
+ "currencyCode",
+ "exchangeRate",
+ ]).where("companyId", "=", companyId).where("id", "in", targetIds)
+ .orderBy("id").forUpdate().execute())
+ : [];
+ const totals = isRefund
+ ? refundMemos.map((memo) => ({
+ id: memo.id,
+ totalAmount: toBaseAmount(
+ Number(memo.amount),
+ Number(memo.exchangeRate),
+ ),
+ }))
+ : targetIds.length
+ ? await (isAR
+ ? trx.selectFrom("salesInvoices").select(["id", "totalAmount"]).where(
+ "companyId",
+ "=",
+ companyId,
+ ).where("id", "in", targetIds).execute()
+ : trx.selectFrom("purchaseInvoices").select(["id", "totalAmount"])
+ .where("companyId", "=", companyId).where("id", "in", targetIds)
+ .execute())
+ : [];
+ if (
+ invoices.length !== targetIds.length || totals.length !== targetIds.length
+ ) throw new Error("Payment target invoice not found in this company");
+ const totalById = new Map(
+ totals.map((row) => [row.id, Number(row.totalAmount)]),
+ );
+ const priorTargetRows = targetIds.length
+ ? (await settlementQuery(trx, companyId).where((eb) =>
+ isRefund
+ ? eb.or([
+ eb("s.targetMemoId", "in", targetIds),
+ eb("s.memoId", "in", targetIds),
+ ])
+ : eb(`s.${targetColumn}`, "in", targetIds)
+ ).execute()).filter(isEffectiveSettlement)
+ : [];
+ const controls = targetIds.length
+ ? await trx.selectFrom("journalLine as line")
+ .innerJoin(
+ "journal as journal",
+ (join) =>
+ join.onRef("journal.id", "=", "line.journalId").onRef(
+ "journal.companyId",
+ "=",
+ "line.companyId",
+ ),
+ )
+ .select(["line.documentId", "line.amount", "line.accountId"]).where(
+ "line.companyId",
+ "=",
+ companyId,
+ ).where("line.documentType", "=", isRefund ? "Memo" : "Invoice")
+ .where("line.documentId", "in", targetIds).where(
+ "line.description",
+ "in",
+ isAR ? RECEIVABLE_POSTING_DESCRIPTIONS : PAYABLE_POSTING_DESCRIPTIONS,
+ )
+ .where(
+ "journal.sourceType",
+ "=",
+ isRefund
+ ? (isAR ? "Credit Memo" : "Debit Memo")
+ : (isAR ? "Sales Invoice" : "Purchase Invoice"),
+ ).where("journal.status", "=", "Posted").execute()
+ : [];
+ const carryingById = new Map<string, number>();
+ const targetControlById = new Map<string, string>();
+ for (const line of controls) {
+ if (line.documentId) {
+ if (!line.accountId) {
+ throw new Error("Invoice is missing its original control account");
+ }
+ const originalAccount = targetControlById.get(line.documentId);
+ if (originalAccount && originalAccount !== line.accountId) {
+ throw new Error("Invoice has conflicting original control accounts");
+ }
+ targetControlById.set(line.documentId, line.accountId);
+ carryingById.set(
+ line.documentId,
+ round(
+ (carryingById.get(line.documentId) ?? 0) +
+ Number(line.amount),
+ ),
+ );
+ }
+ }
+ const targets = new Map<
+ string,
+ { rate: number; remainingDocument: number; remainingBase: number }
+ >();
+ for (const invoice of invoices) {
+ if (
+ invoice.partyId !== partyId ||
+ invoice.currencyCode !== payment.currencyCode
+ ) throw new Error("Invoice party/currency does not match payment");
+ if (
+ invoice.status !== (isRefund ? "Posted" : isAR ? "Submitted" : "Open")
+ ) {
+ throw new Error(
+ `Cannot settle invoice ${invoice.id} in status ${invoice.status}`,
+ );
+ }
+ const rate = Number(invoice.exchangeRate);
+ const total = totalById.get(invoice.id)!;
+ const refundMemo = refundMemos.find((memo) => memo.id === invoice.id);
+ if (refundMemo && refundMemo.direction !== (isAR ? "Credit" : "Debit")) {
+ throw new Error("Refund target must be a balance-reducing memo");
+ }
+ const used = priorTargetRows.filter((row) =>
+ row.memoId === invoice.id || row.targetMemoId === invoice.id
+ );
+ const { remainingDocument, remainingBase } = isRefund
+ ? {
+ remainingDocument: toDocumentAmount(
+ Number(refundMemo!.amount) - used.reduce((sum, row) =>
+ sum + principal(row.sourceAmount, row.id), 0),
+ 1,
+ decimals,
+ ),
+ remainingBase: round(
+ -(carryingById.get(invoice.id) ?? -total) -
+ used.reduce((sum, row) =>
+ sum + Number(row.appliedAmount), 0),
+ ),
+ }
+ : invoiceRemainingAmounts(
+ { ...invoice, totalAmount: total },
+ priorTargetRows,
+ carryingById,
+ decimals,
+ isAR,
+ );
+ if (remainingDocument < 0 || remainingBase < 0) {
+ throw new Error("Target memo is over-applied");
+ }
+ if (accountingEnabled && !targetControlById.has(invoice.id)) {
+ throw new Error("Target is missing its original control account");
+ }
+ targets.set(invoice.id, { rate, remainingDocument, remainingBase });
+ }
+
+ const memos = memoIds.length
+ ? await trx.selectFrom("memo").selectAll().where(
+ "companyId",
+ "=",
+ companyId,
+ )
+ .where("id", "in", memoIds).orderBy("id").forUpdate().execute()
+ : [];
+ if (memos.length !== memoIds.length) {
+ throw new Error("Staged memo not found in this company");
+ }
+ const memoConsumption = memoIds.length
+ ? (await settlementQuery(trx, companyId).where((eb) =>
+ eb.or([
+ eb("s.memoId", "in", memoIds),
+ eb("s.targetMemoId", "in", memoIds),
+ ])
+ ).execute()).filter(isEffectiveSettlement)
+ : [];
+ const memoRemaining = new Map(memos.map((memo) => {
+ if (
+ memo.status !== "Posted" ||
+ memo.currencyCode !== payment.currencyCode ||
+ (isAR ? memo.customerId : memo.supplierId) !== partyId ||
+ memo.direction !== (isAR ? "Credit" : "Debit")
+ ) {
+ throw new Error(
+ "Staged memo must be posted with matching party, currency and direction",
+ );
+ }
+ assertExchangeRate(Number(memo.exchangeRate));
+ return [memo.id, {
+ memo,
+ document: toDocumentAmount(
+ Number(memo.amount) -
+ memoConsumption.filter((row) =>
+ row.memoId === memo.id || row.targetMemoId === memo.id
+ ).reduce(
+ (sum, row) => sum + principal(row.sourceAmount, row.id),
+ 0,
+ ),
+ 1,
+ decimals,
+ ),
+ }] as [string, { memo: typeof memo; document: number }];
+ }));
+ const normalizedMemos: Array<
+ {
+ id: string;
+ appliedAmount: number;
+ sourceAmount: number;
+ sourceExchangeRate: number;
+ targetExchangeRate: number;
+ }
+ > = [];
+ for (const draft of drafts.filter((row) => row.memoId !== null)) {
+ if (
+ draft.paymentId || draft.sourcePaymentId ||
+ Number(draft.discountAmount) !== 0 || Number(draft.writeOffAmount) !== 0
+ ) {
+ throw new Error(
+ "Memo applications cannot carry payment funding, discounts or write-offs",
+ );
+ }
+ const target = targets.get(draft[targetColumn]!)!;
+ const source = memoRemaining.get(draft.memoId!)!;
+ if (Number(source.memo.exchangeRate) !== target.rate) {
+ throw new Error("Memo and invoice exchange-rate snapshots must match");
+ }
+ const sourceAmount = draft.sourceAmount === null
+ ? toDocumentAmount(Number(draft.appliedAmount), target.rate, decimals)
+ : principal(draft.sourceAmount, draft.id);
+ if (
+ toDocumentAmount(sourceAmount, 1, decimals) !== sourceAmount ||
+ sourceAmount > source.document ||
+ sourceAmount > target.remainingDocument
+ ) throw new Error("Staged memo principal exceeds remaining balance");
+ const appliedAmount = sourceAmount === target.remainingDocument
+ ? target.remainingBase
+ : toBaseAmount(sourceAmount, target.rate);
+ if (appliedAmount > target.remainingBase) {
+ throw new Error("Staged memo exceeds target carrying balance");
+ }
+ source.document = toDocumentAmount(
+ source.document - sourceAmount,
+ 1,
+ decimals,
+ );
+ target.remainingDocument = toDocumentAmount(
+ target.remainingDocument - sourceAmount,
+ 1,
+ decimals,
+ );
+ target.remainingBase = round(target.remainingBase - appliedAmount);
+ normalizedMemos.push({
+ id: draft.id,
+ appliedAmount,
+ sourceAmount,
+ sourceExchangeRate: target.rate,
+ targetExchangeRate: target.rate,
+ });
+ }
+
+ const sources = isRefund
+ ? []
+ : await trx.selectFrom("payment").selectAll().where(
+ "companyId",
+ "=",
+ companyId,
+ )
+ .where("status", "=", "Posted").where(
+ "paymentType",
+ "=",
+ isAR ? "Receipt" : "Disbursement",
+ )
+ .where(isAR ? "customerId" : "supplierId", "=", partyId).where(
+ "currencyCode",
+ "=",
+ payment.currencyCode,
+ )
+ .where("id", "!=", paymentId).orderBy("id").forUpdate().execute();
+ const sourceIds = sources.map((source) => source.id);
+ const sourceControls = sourceIds.length
+ ? await trx.selectFrom("journalLine as line")
+ .innerJoin(
+ "journal as journal",
+ (join) =>
+ join.onRef("journal.id", "=", "line.journalId").onRef(
+ "journal.companyId",
+ "=",
+ "line.companyId",
+ ),
+ )
+ .select(["line.documentId", "line.accountId"])
+ .where("line.companyId", "=", companyId).where(
+ "line.documentType",
+ "=",
+ "Payment",
+ )
+ .where("line.documentId", "in", sourceIds)
+ .where(
+ "line.description",
+ "=",
+ onAccountCreditDescription(isAR),
+ )
+ .where("journal.sourceType", "=", "Payment").where(
+ "journal.status",
+ "=",
+ "Posted",
+ ).execute()
+ : [];
+ const sourceControlById = new Map<string, string>();
+ for (const line of sourceControls) {
+ if (!line.documentId) continue;
+ if (!line.accountId) {
+ throw new Error(
+ "Funding source is missing its original control account",
+ );
+ }
+ const originalAccount = sourceControlById.get(line.documentId);
+ if (originalAccount && originalAccount !== line.accountId) {
+ throw new Error(
+ "Funding source has conflicting original control accounts",
+ );
+ }
+ sourceControlById.set(line.documentId, line.accountId);
+ }
+ const consumed = sourceIds.length
+ ? (await settlementQuery(trx, companyId).where((eb) =>
+ eb.or([
+ eb("s.sourcePaymentId", "in", sourceIds),
+ eb.and([
+ eb("s.sourcePaymentId", "is", null),
+ eb("s.paymentId", "in", sourceIds),
+ ]),
+ ])
+ ).execute()).filter(isEffectiveSettlement)
+ : [];
+ const priorSources = remainingFundingSources(
+ sources,
+ consumed,
+ new Map([[payment.currencyCode, decimals]]),
+ isAR,
+ );
+ const requestByTarget = new Map<string, FundingRequest>();
+ for (const draft of drafts.filter((row) => row.paymentId === paymentId)) {
+ const targetId = draft[targetColumn]!;
+ const target = targets.get(targetId)!;
+ const requested = draft.sourceAmount === null
+ ? (Number(draft.appliedAmount) === target.remainingBase &&
+ Number(draft.discountAmount) === 0 &&
+ Number(draft.writeOffAmount) === 0
+ ? target.remainingDocument
+ : toDocumentAmount(
+ Number(draft.appliedAmount),
+ target.rate,
+ decimals,
+ ))
+ : principal(draft.sourceAmount, draft.id);
+ if (toDocumentAmount(requested, 1, decimals) !== requested) {
+ throw new Error(
+ "Requested principal exceeds document currency precision",
+ );
+ }
+ const request = requestByTarget.get(targetId) ?? {
+ targetId,
+ targetExchangeRate: target.rate,
+ remainingDocument: target.remainingDocument,
+ remainingBase: target.remainingBase,
+ requestedDocumentPrincipal: 0,
+ discountAmount: 0,
+ writeOffAmount: 0,
+ };
+ request.requestedDocumentPrincipal = toDocumentAmount(
+ request.requestedDocumentPrincipal + requested,
+ 1,
+ decimals,
+ );
+ request.discountAmount = round(
+ request.discountAmount + Number(draft.discountAmount),
+ );
+ request.writeOffAmount = round(
+ request.writeOffAmount + Number(draft.writeOffAmount),
+ );
+ requestByTarget.set(targetId, request);
+ }
+ const allocation = allocatePaymentFunding({
+ currentPayment: {
+ paymentId,
+ postingDate: today,
+ exchangeRate: Number(payment.exchangeRate),
+ remainingDocument: Number(payment.totalAmount),
+ remainingBase: toBaseAmount(
+ Number(payment.totalAmount),
+ Number(payment.exchangeRate),
+ ),
+ },
+ priorSources,
+ requests: [...requestByTarget.values()].sort((a, b) =>
+ a.targetId.localeCompare(b.targetId)
+ ),
+ currencyDecimals: decimals,
+ isAR: cashIn,
+ });
+
+ const defaults = await trx.selectFrom("accountDefault").selectAll().where(
+ "companyId",
+ "=",
+ companyId,
+ ).executeTakeFirst();
+ const party = isAR
+ ? await trx.selectFrom("customer").select([
+ "customerTypeId as typeId",
+ "intercompanyCompanyId",
+ ]).where("id", "=", partyId).where("companyId", "=", companyId)
+ .executeTakeFirst()
+ : await trx.selectFrom("supplier").select([
+ "supplierTypeId as typeId",
+ "intercompanyCompanyId",
+ ]).where("id", "=", partyId).where("companyId", "=", companyId)
+ .executeTakeFirst();
+ if (!party) throw new Error("Payment counterparty not found");
+ const normalized = allocation.applications.map((application) => ({
+ ...application,
+ targetSalesInvoiceId: !isRefund && isAR ? application.targetId : null,
+ targetPurchaseInvoiceId: !isRefund && !isAR ? application.targetId : null,
+ targetMemoId: isRefund ? application.targetId : null,
+ }));
+ let journalLines: ReturnType<typeof buildPaymentJournal>["lines"] = [];
+ const expectedAccountClasses: Array<[string | null | undefined, string]> = [
+ [payment.bankAccount, "Asset"],
+ ];
+ if (accountingEnabled) {
+ if (!defaults) {
+ throw new Error("Accounting defaults are required before posting");
+ }
+ // Resolve the discount account's class so buildPaymentJournal signs the
+ // discount line by the account's real natural balance (customer discount
+ // -> Revenue/contra-revenue; supplier discount -> Expense/contra-COGS),
+ // mirroring how post-memo resolves its reason account's class.
+ const discountAccountId = isAR
+ ? defaults.customerPaymentDiscountAccount
+ : defaults.supplierPaymentDiscountAccount;
+ let discountAccountClass: string | null = null;
+ if (discountAccountId) {
+ const discountAccount = await trx.selectFrom("account").select("class")
+ .where("id", "=", discountAccountId)
+ .where("companyGroupId", "=", company.companyGroupId)
+ .executeTakeFirst();
+ if (!discountAccount) {
+ throw new Error("Failed to fetch the payment discount account class");
+ }
+ discountAccountClass = discountAccount.class;
+ }
+ const accounts = {
+ controlAccountId: isAR
+ ? (party.intercompanyCompanyId
+ ? defaults.intercompanyReceivablesAccount
+ : defaults.receivablesAccount)
+ : (party.intercompanyCompanyId
+ ? defaults.intercompanyPayablesAccount
+ : defaults.payablesAccount),
+ discountAccountId,
+ discountAccountClass,
+ writeOffAccountId: isAR
+ ? defaults.customerWriteOffAccount
+ : defaults.supplierWriteOffAccount,
+ fxGainAccountId: defaults.realizedExchangeGainAccount,
+ fxLossAccountId: defaults.realizedExchangeLossAccount,
+ };
+ expectedAccountClasses.push(
+ [accounts.controlAccountId, isAR ? "Asset" : "Liability"],
+ [accounts.discountAccountId, isAR ? "Revenue" : "Expense"],
+ [accounts.writeOffAccountId, isAR ? "Expense" : "Revenue"],
+ [accounts.fxGainAccountId, "Revenue"],
+ [accounts.fxLossAccountId, "Expense"],
+ [fee?.accountId, "Expense"],
+ );
+ const journalApplications = normalized.map((application) => ({
+ ...application,
+ targetControlAccountId: targetControlById.get(application.targetId),
+ sourceControlAccountId: application.sourcePaymentId
+ ? sourceControlById.get(application.sourcePaymentId)
+ : undefined,
+ }));
+ for (const application of journalApplications) {
+ expectedAccountClasses.push(
+ [application.targetControlAccountId, isAR ? "Asset" : "Liability"],
+ [application.sourceControlAccountId, isAR ? "Asset" : "Liability"],
+ );
+ }
+ journalLines = buildPaymentJournal({
+ paymentId,
+ companyId,
+ isAR,
+ cashIn,
+ totalAmount: Number(payment.totalAmount),
+ exchangeRate: Number(payment.exchangeRate),
+ bankAccount: payment.bankAccount,
+ journalLineReference: nanoid(),
+ applications: journalApplications,
+ newOnAccountBase: allocation.sourceRemainders[0].remainingBase,
+ fee,
+ accounts,
+ }).lines;
+ }
+ const accountIds = [
+ ...new Set([
+ payment.bankAccount,
+ ...journalLines.map((line) => line.accountId),
+ ]),
+ ];
+ const postingAccounts = await trx.selectFrom("account").select([
+ "id",
+ "class",
+ ])
+ .where("id", "in", accountIds).where(
+ "companyGroupId",
+ "=",
+ company.companyGroupId,
+ )
+ .where("active", "=", true).where("isGroup", "=", false).execute();
+ if (
+ postingAccounts.length !== accountIds.length ||
+ postingAccounts.find((account) => account.id === payment.bankAccount)
+ ?.class !== "Asset"
+ ) {
+ throw new Error(
+ "Payment accounts must be active posting accounts in this company group, with an Asset bank account",
+ );
+ }
+ const classById = new Map(
+ postingAccounts.map((account) => [account.id, account.class]),
+ );
+ if (
+ expectedAccountClasses.some(([id, expected]) =>
+ id && classById.has(id) && classById.get(id) !== expected
+ )
+ ) {
+ throw new Error("Payment account class does not match its posting role");
+ }
+ // Replace current-cash/prior-credit splits only after all authoritative
+ // validation. The entire replacement, journal and status share this transaction.
+ await trx.deleteFrom("invoiceSettlement").where("paymentId", "=", paymentId)
+ .where("companyId", "=", companyId).execute();
+ if (normalized.length) {
+ await trx.insertInto("invoiceSettlement").values(
+ normalized.map(({ targetId: _, ...application }) => ({
+ ...application,
+ paymentId,
+ companyId,
+ appliedDate: today,
+ createdBy: userId,
+ })),
+ ).execute();
+ }
+ // One set-based UPDATE preserves memo row identities and avoids query-per-row writes.
+ if (normalizedMemos.length) {
+ await sql`UPDATE "invoiceSettlement" s SET "appliedAmount"=v."appliedAmount", "sourceAmount"=v."sourceAmount",
+ "sourceExchangeRate"=v."sourceExchangeRate", "targetExchangeRate"=v."targetExchangeRate", "fxGainLossAmount"=0, "appliedDate"=${today}::date, "updatedBy"=${userId}
+ FROM jsonb_to_recordset(${
+ JSON.stringify(normalizedMemos)
+ }::jsonb) AS v(id text,"appliedAmount" numeric,"sourceAmount" numeric,"sourceExchangeRate" numeric,"targetExchangeRate" numeric)
+ WHERE s.id=v.id AND s."companyId"=${companyId} AND s."appliedViaPaymentId"=${paymentId}`
+ .execute(trx);
+ }
+ let journalId: string | null = null;
+ if (accountingEnabled) {
+ const journal = await trx.insertInto("journal").values({
+ journalEntryId: await getNextSequence(trx, "journalEntry", companyId),
+ accountingPeriodId,
+ description: `Payment ${payment.paymentId}`,
+ postingDate: today,
+ companyId,
+ sourceType: "Payment",
+ status: "Posted",
+ postedAt: timestamp,
+ postedBy: userId,
+ createdBy: userId,
+ }).returning("id").executeTakeFirstOrThrow();
+ journalId = journal.id;
+ if (journalLines.length) {
+ const lines = await trx.insertInto("journalLine").values(
+ journalLines.map((line) => ({ ...line, journalId: journal.id })),
+ ).returning("id").execute();
+ const dimensions = await trx.selectFrom("dimension").select([
+ "id",
+ "entityType",
+ ]).where("companyGroupId", "=", company.companyGroupId)
+ .where("active", "=", true).where(
+ "entityType",
+ "in",
+ isAR ? ["CustomerType", "Customer"] : ["SupplierType", "Supplier"],
+ ).execute();
+ const values = dimensions.flatMap((dimension) => {
+ const valueId =
+ dimension.entityType === (isAR ? "Customer" : "Supplier")
+ ? partyId
+ : party.typeId;
+ return valueId
+ ? lines.map((line) => ({
+ journalLineId: line.id,
+ dimensionId: dimension.id,
+ valueId,
+ companyId,
+ }))
+ : [];
+ });
+ if (values.length) {
+ await trx.insertInto("journalLineDimension").values(values).execute();
+ }
+ }
+ }
+ await trx.updateTable("payment").set({
+ status: "Posted",
+ postingDate: today,
+ journalId,
+ postedAt: timestamp,
+ postedBy: userId,
+ updatedAt: timestamp,
+ updatedBy: userId,
+ })
+ .where("id", "=", paymentId).where("companyId", "=", companyId).execute();
+ return { journalId };
+ });
+}
diff --git a/packages/database/supabase/functions/post-payment/post-payment.test.ts b/packages/database/supabase/functions/post-payment/post-payment.test.ts
index 54cb7db6a4..ed15c99c2c 100644
--- a/packages/database/supabase/functions/post-payment/post-payment.test.ts
+++ b/packages/database/supabase/functions/post-payment/post-payment.test.ts
@@ -6,914 +6,506 @@ import {
import {
buildPaymentJournal,
type BuildPaymentJournalInput,
- type PaymentJournalAccounts,
+ type PaymentJournalApplicationInput,
} from "./build-payment-journal.ts";
-import { round } from "../shared/precision.ts";
-// Golden-master tests for the GL journal a payment posts. Each asserts the exact
-// natural-balance-signed `amount` on each line (asset/expense debits are +,
-// credits −; liability/revenue/equity are the mirror — see lib/utils.ts) AND
-// that the entry balances in debit/credit space (signedDebitTotal ≈ 0). The
-// matrix covers AR/AP × full/partial/over × discount/write-off × FX gain/loss,
-// so the ledger that hits the books is provably correct, not merely inspected.
-
-const ACCOUNTS: PaymentJournalAccounts = {
- controlAccountId: "control", // receivables (AR) or payables (AP); driver resolves
+const accounts = {
+ controlAccountId: "control",
discountAccountId: "discount",
- discountAccountClass: "Revenue", // AR default: customer discount is contra-revenue
writeOffAccountId: "writeoff",
fxGainAccountId: "fxgain",
fxLossAccountId: "fxloss",
};
-
-const arBase = (
- over: Partial<BuildPaymentJournalInput> = {}
+const app = (
+ input: Partial<PaymentJournalApplicationInput> = {},
+): PaymentJournalApplicationInput => ({
+ targetSalesInvoiceId: "invoice",
+ appliedAmount: 100,
+ discountAmount: 0,
+ writeOffAmount: 0,
+ sourceAmount: 110,
+ sourcePaymentId: null,
+ sourceExchangeRate: 1.1,
+ targetExchangeRate: 1.1,
+ fxGainLossAmount: 0,
+ ...input,
+});
+const payment = (
+ input: Partial<BuildPaymentJournalInput> = {},
): BuildPaymentJournalInput => ({
- paymentId: "pay_1",
- companyId: "co_1",
+ paymentId: "payment",
+ companyId: "company",
isAR: true,
cashIn: true,
- totalAmount: 100,
- exchangeRate: 1,
+ totalAmount: 110,
+ exchangeRate: 1.1,
bankAccount: "bank",
- journalLineReference: "ref_1",
- applications: [
- {
- targetSalesInvoiceId: "si_1",
- appliedAmount: 100,
- discountAmount: 0,
- writeOffAmount: 0,
- targetExchangeRate: 1,
- sourceExchangeRate: 1,
- },
- ],
- accounts: { ...ACCOUNTS },
- ...over,
-});
-
-const apBase = (
- over: Partial<BuildPaymentJournalInput> = {}
-): BuildPaymentJournalInput => ({
- ...arBase(),
- isAR: false,
- cashIn: false,
- applications: [
- {
- targetPurchaseInvoiceId: "pi_1",
- appliedAmount: 100,
- discountAmount: 0,
- writeOffAmount: 0,
- targetExchangeRate: 1,
- sourceExchangeRate: 1,
- },
- ],
- // AP: supplier discount is contra-COGS (Expense natural balance).
- accounts: { ...ACCOUNTS, discountAccountClass: "Expense" },
- ...over,
-});
-
-const balanced = (signedDebitTotal: number) =>
- Math.abs(signedDebitTotal) < 1e-9;
-
-const line = <T extends { description: string }>(
- lines: T[],
- description: string
-) => lines.find((l) => l.description === description);
-
-
-// Magnitude posted to the control account for a specific invoice (the lines are
-// natural-balance signed, so take the absolute value to compare to the
-// subledger settled amount).
-const controlMagnitudeFor = (
- lines: { description: string; documentLineReference?: string; amount: number }[],
- invoiceId: string
-) => {
- const l = lines.find(
- (x) =>
- (x.description === "Accounts Receivable" ||
- x.description === "Accounts Payable") &&
- x.documentLineReference === invoiceId
+ journalLineReference: "reference",
+ applications: [app()],
+ accounts: { ...accounts },
+ newOnAccountBase: 0,
+ ...input,
+});
+const total = (
+ result: ReturnType<typeof buildPaymentJournal>,
+ account: string,
+) =>
+ result.lines.filter((line) => line.accountId === account).reduce(
+ (sum, line) => sum + line.amount,
+ 0,
);
- return l ? Math.abs(l.amount) : 0;
-};
-
-// ---------------------------------------------------------------------------
-// Simple, no-FX cases — assert the full line set.
-// ---------------------------------------------------------------------------
-
-Deno.test("AR full payment, no FX: DR bank / CR receivables, balanced", () => {
- const { lines, signedDebitTotal } = buildPaymentJournal(arBase());
-
- assertEquals(lines.length, 2);
- assertEquals(lines[0].accountId, "bank");
- assertEquals(lines[0].amount, 100); // debit asset
- assertEquals(lines[0].description, "Bank / Cash");
- assertEquals(lines[0].documentType, "Payment");
- assertEquals(lines[0].documentId, "pay_1");
- assertEquals(lines[0].journalLineReference, "ref_1");
- assertEquals(lines[0].companyId, "co_1");
-
- assertEquals(lines[1].accountId, "control");
- assertEquals(lines[1].amount, -100); // credit asset
- assertEquals(lines[1].description, "Accounts Receivable");
- assertEquals(lines[1].documentLineReference, "si_1");
-
- assert(balanced(signedDebitTotal));
-});
-
-Deno.test("AP full payment, no FX: CR bank / DR payables, balanced", () => {
- const { lines, signedDebitTotal } = buildPaymentJournal(apBase());
-
- assertEquals(lines.length, 2);
- assertEquals(lines[0].accountId, "bank");
- assertEquals(lines[0].amount, -100); // credit asset
- assertEquals(lines[1].accountId, "control");
- assertEquals(lines[1].amount, -100); // debit liability → natural-negative
- assertEquals(lines[1].description, "Accounts Payable");
- assertEquals(lines[1].documentLineReference, "pi_1");
-
- assert(balanced(signedDebitTotal));
-});
-// ---------------------------------------------------------------------------
-// Discount / write-off — invoice-currency reliefs, no FX.
-// ---------------------------------------------------------------------------
-
-Deno.test("AR discount: bank 90 / receivables 100 / discount contra-revenue -10", () => {
- const { lines, signedDebitTotal } = buildPaymentJournal(
- arBase({
- totalAmount: 90,
- applications: [
- {
- targetSalesInvoiceId: "si_1",
- appliedAmount: 90,
- discountAmount: 10,
- writeOffAmount: 0,
- targetExchangeRate: 1,
- sourceExchangeRate: 1,
- },
- ],
- })
+Deno.test("applications clear recorded target and source controls after defaults change", () => {
+ const result = buildPaymentJournal(
+ payment({
+ totalAmount: 0,
+ applications: [app({
+ sourcePaymentId: "prior",
+ targetControlAccountId: "original-invoice-control",
+ sourceControlAccountId: "original-credit-control",
+ })],
+ }),
);
-
- assertEquals(line(lines, "Bank / Cash")!.amount, 90);
- assertEquals(line(lines, "Accounts Receivable")!.amount, -100); // (90+10)*1
- const discount = line(lines, "Customer Payment Discount")!;
- assertEquals(discount.accountId, "discount");
- assertEquals(discount.amount, -10); // debit to a Revenue-class account (contra-revenue)
- assert(balanced(signedDebitTotal));
+ assertEquals(total(result, "original-invoice-control"), -100);
+ assertEquals(total(result, "original-credit-control"), 100);
+ assertEquals(total(result, "control"), 0);
+ assertEquals(result.signedDebitTotal, 0);
});
-Deno.test("AR write-off: bad debt expense debited", () => {
- const { lines, signedDebitTotal } = buildPaymentJournal(
- arBase({
- totalAmount: 90,
- applications: [
- {
- targetSalesInvoiceId: "si_1",
- appliedAmount: 90,
- discountAmount: 0,
- writeOffAmount: 10,
- targetExchangeRate: 1,
- sourceExchangeRate: 1,
- },
- ],
- })
- );
-
- const wo = line(lines, "Bad Debt Expense")!;
- assertEquals(wo.accountId, "writeoff");
- assertEquals(wo.amount, 10); // debit expense
- assert(balanced(signedDebitTotal));
+Deno.test("receipt110 at1.1 releases base100 and posts no realized FX", () => {
+ const result = buildPaymentJournal(payment());
+ assertEquals(total(result, "bank"), 100);
+ assertEquals(total(result, "control"), -100);
+ assertEquals(result.totalFxImpact, 0);
+ assertEquals(result.signedDebitTotal, 0);
});
-Deno.test("AP write-off: vendor write-off income credited (revenue)", () => {
- const { lines, signedDebitTotal } = buildPaymentJournal(
- apBase({
- totalAmount: 90,
+Deno.test("disbursement110 at1.1 releases base100 payable", () => {
+ const result = buildPaymentJournal(
+ payment({
+ isAR: false,
+ cashIn: false,
applications: [
- {
- targetPurchaseInvoiceId: "pi_1",
- appliedAmount: 90,
- discountAmount: 0,
- writeOffAmount: 10,
- targetExchangeRate: 1,
- sourceExchangeRate: 1,
- },
+ app({ targetSalesInvoiceId: null, targetPurchaseInvoiceId: "invoice" }),
],
- })
+ }),
);
-
- const wo = line(lines, "Vendor Write-Off Income")!;
- assertEquals(wo.accountId, "writeoff");
- assertEquals(wo.amount, 10); // credit revenue → natural-positive
- assert(balanced(signedDebitTotal));
+ assertEquals(total(result, "bank"), -100);
+ assertEquals(total(result, "control"), -100);
+ assertEquals(result.signedDebitTotal, 0);
});
-Deno.test("AP discount: supplier discount credited to a contra-COGS (Expense) account", () => {
- const { lines, signedDebitTotal } = buildPaymentJournal(
- apBase({
- totalAmount: 90,
+for (const isAR of [true, false]) {
+ Deno.test(`${isAR ? "customer" : "supplier"} refund builder retains independent party and cash direction`, () => {
+ const result = buildPaymentJournal(payment({
+ isAR,
+ cashIn: !isAR,
+ exchangeRate: 1,
applications: [
- {
- targetPurchaseInvoiceId: "pi_1",
- appliedAmount: 90,
- discountAmount: 10,
- writeOffAmount: 0,
- targetExchangeRate: 1,
+ app({
+ targetSalesInvoiceId: null,
+ targetPurchaseInvoiceId: null,
+ targetMemoId: "memo",
sourceExchangeRate: 1,
- },
+ fxGainLossAmount: isAR ? -10 : 10,
+ }),
],
- })
- );
-
- assertEquals(line(lines, "Bank / Cash")!.amount, -90); // credit asset (cash out)
- assertEquals(line(lines, "Accounts Payable")!.amount, -100); // (90+10)×1, debit liability → natural-negative
- const discount = line(lines, "Supplier Payment Discount")!;
- assertEquals(discount.accountId, "discount");
- assertEquals(discount.amount, -10); // credit to an Expense/COGS account → contra-cost
- assert(balanced(signedDebitTotal));
-});
-
-// ---------------------------------------------------------------------------
-// Processor fee — withheld at source (Stripe Connect), so it never touches the
-// bank line. One journal entry, not a payment entry plus a follow-up fee entry.
-// ---------------------------------------------------------------------------
-
-Deno.test("AR with processor fee: net bank + fee expense / gross receivables, balanced", () => {
- const { lines, signedDebitTotal } = buildPaymentJournal(
- arBase({
- fee: { amount: 3, accountId: "servicecharge" },
- })
- );
-
- assertEquals(lines.length, 3);
- assertEquals(line(lines, "Bank / Cash")!.amount, 97); // (100 − 3) debit asset
- const feeLine = line(lines, "Payment Processing Fee")!;
- assertEquals(feeLine.accountId, "servicecharge");
- assertEquals(feeLine.amount, 3); // debit expense
- assertEquals(line(lines, "Accounts Receivable")!.amount, -100); // gross, unaffected by the fee
- assert(balanced(signedDebitTotal));
-});
-
-Deno.test("AR with processor fee and custom description", () => {
- const { lines } = buildPaymentJournal(
- arBase({
- fee: { amount: 3, accountId: "servicecharge", description: "Stripe processing fee — INV-1" },
- })
- );
-
- assert(line(lines, "Stripe processing fee — INV-1") !== undefined);
- assert(line(lines, "Payment Processing Fee") === undefined);
-});
-
-Deno.test("AR with processor fee and FX: fee stays gross-of-FX, entry still balances", () => {
- const { lines, signedDebitTotal } = buildPaymentJournal(
- arBase({
- exchangeRate: 1.2,
- fee: { amount: 3, accountId: "servicecharge" },
- applications: [
- {
- targetSalesInvoiceId: "si_1",
- appliedAmount: 100,
- discountAmount: 0,
- writeOffAmount: 0,
- targetExchangeRate: 1.0,
- sourceExchangeRate: 1.2,
- },
- ],
- })
- );
-
- assertEquals(line(lines, "Bank / Cash")!.amount, 116.4); // (100 × 1.2) − (3 × 1.2)
- assertEquals(line(lines, "Payment Processing Fee")!.amount, 3.6); // 3 × 1.2
- assertEquals(line(lines, "Accounts Receivable")!.amount, -100); // 100 × 1.0
- assert(line(lines, "Realized FX Gain") !== undefined); // unaffected by the fee
- assert(balanced(signedDebitTotal));
-});
-
-// ---------------------------------------------------------------------------
-// Realized FX — the sign convention. These pin that AR collected high = gain,
-// AP paid high = LOSS (the case a reviewer mis-called as inverted).
-// ---------------------------------------------------------------------------
-
-Deno.test("AR collected above booked rate → FX Gain (credit revenue)", () => {
- const { lines, signedDebitTotal } = buildPaymentJournal(
- arBase({
- exchangeRate: 1.2,
- applications: [
- {
- targetSalesInvoiceId: "si_1",
- appliedAmount: 100,
- discountAmount: 0,
- writeOffAmount: 0,
- targetExchangeRate: 1.0,
- sourceExchangeRate: 1.2,
- },
- ],
- })
- );
-
- assertEquals(line(lines, "Bank / Cash")!.amount, 120); // 100 × 1.2
- assertEquals(line(lines, "Accounts Receivable")!.amount, -100); // 100 × 1.0
- const fx = line(lines, "Realized FX Gain")!;
- assertEquals(fx.accountId, "fxgain");
- assertEquals(fx.amount, 20); // credit revenue
- assert(line(lines, "Realized FX Loss") === undefined);
- assert(balanced(signedDebitTotal));
-});
-
-Deno.test("AR collected below booked rate → FX Loss (debit expense)", () => {
- const { lines, signedDebitTotal } = buildPaymentJournal(
- arBase({
- exchangeRate: 0.8,
- applications: [
- {
- targetSalesInvoiceId: "si_1",
- appliedAmount: 100,
- discountAmount: 0,
- writeOffAmount: 0,
- targetExchangeRate: 1.0,
- sourceExchangeRate: 0.8,
- },
- ],
- })
- );
-
- const fx = line(lines, "Realized FX Loss")!;
- assertEquals(fx.accountId, "fxloss");
- assertEquals(fx.amount, 20); // debit expense
- assert(line(lines, "Realized FX Gain") === undefined);
- assert(balanced(signedDebitTotal));
-});
+ }));
+ assertEquals(total(result, "bank"), isAR ? -110 : 110);
+ assertEquals(total(result, "control"), 100);
+ assertEquals(total(result, isAR ? "fxloss" : "fxgain"), 10);
+ assertEquals(result.signedDebitTotal, 0);
+ });
+}
+
+for (const isAR of [true, false]) {
+ for (
+ const [rate, cashBase, arFx] of [[1, 110, 10], [1.25, 88, -12]] as const
+ ) {
+ Deno.test(`${isAR ? "AR" : "AP"} cash110 at${rate} posts persisted FX and base100 control`, () => {
+ const fx = isAR ? arFx : -arFx;
+ const result = buildPaymentJournal(payment({
+ isAR,
+ cashIn: isAR,
+ exchangeRate: rate,
+ applications: [
+ app({
+ targetSalesInvoiceId: isAR ? "invoice" : null,
+ targetPurchaseInvoiceId: isAR ? null : "invoice",
+ sourceExchangeRate: rate,
+ fxGainLossAmount: fx,
+ }),
+ ],
+ }));
+ assertEquals(total(result, "bank"), isAR ? cashBase : -cashBase);
+ assertEquals(total(result, "control"), -100);
+ assertEquals(result.totalFxImpact, fx);
+ assertEquals(total(result, fx > 0 ? "fxgain" : "fxloss"), Math.abs(fx));
+ assertEquals(result.signedDebitTotal, 0);
+ });
+ }
+}
-Deno.test("AP paid ABOVE booked rate → FX Loss (debit expense)", () => {
- // The case a reviewer wrongly flagged as a sign inversion. Paying a supplier
- // at a higher rate than the liability was booked is a real loss.
- const { lines, signedDebitTotal } = buildPaymentJournal(
- apBase({
- exchangeRate: 1.2,
- applications: [
- {
- targetPurchaseInvoiceId: "pi_1",
- appliedAmount: 100,
- discountAmount: 0,
- writeOffAmount: 0,
- targetExchangeRate: 1.0,
- sourceExchangeRate: 1.2,
- },
- ],
- })
+Deno.test("withheld fee3.30 converts to base3 with bank97 and control100", () => {
+ const result = buildPaymentJournal(
+ payment({
+ fee: { amount: 3.3, accountId: "fee", description: "Processor fee" },
+ }),
);
-
- assertEquals(line(lines, "Bank / Cash")!.amount, -120); // credit asset 100×1.2
- const fx = line(lines, "Realized FX Loss")!;
- assertEquals(fx.accountId, "fxloss");
- assertEquals(fx.amount, 20); // debit expense
- assert(line(lines, "Realized FX Gain") === undefined);
- assert(balanced(signedDebitTotal));
-});
-
-Deno.test("AP paid BELOW booked rate → FX Gain (credit revenue)", () => {
- const { lines, signedDebitTotal } = buildPaymentJournal(
- apBase({
- exchangeRate: 0.8,
- applications: [
- {
- targetPurchaseInvoiceId: "pi_1",
- appliedAmount: 100,
- discountAmount: 0,
- writeOffAmount: 0,
- targetExchangeRate: 1.0,
- sourceExchangeRate: 0.8,
- },
- ],
- })
+ assertEquals(total(result, "bank"), 97);
+ assertEquals(total(result, "fee"), 3);
+ assertEquals(total(result, "control"), -100);
+ assertEquals(result.signedDebitTotal, 0);
+});
+
+Deno.test("base discount/writeoff remain base and carry no separate FX", () => {
+ const result = buildPaymentJournal(payment({
+ totalAmount: 88,
+ exchangeRate: 1,
+ applications: [
+ app({
+ sourceAmount: 88,
+ sourceExchangeRate: 1,
+ appliedAmount: 80,
+ discountAmount: 15,
+ writeOffAmount: 5,
+ fxGainLossAmount: 8,
+ }),
+ ],
+ }));
+ assertEquals(total(result, "bank"), 88);
+ assertEquals(total(result, "control"), -100);
+ assertEquals(total(result, "discount"), 15);
+ assertEquals(total(result, "writeoff"), 5);
+ assertEquals(total(result, "fxgain"), 8);
+ assertEquals(result.signedDebitTotal, 0);
+});
+
+Deno.test("AP allowance and writeoff reverse expense and credit income", () => {
+ const result = buildPaymentJournal(payment({
+ isAR: false,
+ cashIn: false,
+ totalAmount: 88,
+ exchangeRate: 1,
+ applications: [app({
+ targetSalesInvoiceId: null,
+ targetPurchaseInvoiceId: "invoice",
+ sourceAmount: 88,
+ sourceExchangeRate: 1,
+ appliedAmount: 80,
+ discountAmount: 15,
+ writeOffAmount: 5,
+ fxGainLossAmount: -8,
+ })],
+ }));
+ assertEquals(total(result, "bank"), -88);
+ assertEquals(total(result, "control"), -100);
+ assertEquals(total(result, "discount"), -15);
+ assertEquals(total(result, "writeoff"), 5);
+ assertEquals(total(result, "fxloss"), 8);
+ assertEquals(result.signedDebitTotal, 0);
+});
+
+Deno.test("unused current cash alone creates new on-account carrying value", () => {
+ const result = buildPaymentJournal(
+ payment({ totalAmount: 165, newOnAccountBase: 50 }),
);
-
- const fx = line(lines, "Realized FX Gain")!;
- assertEquals(fx.accountId, "fxgain");
- assertEquals(fx.amount, 20); // credit revenue
- assert(line(lines, "Realized FX Loss") === undefined);
- assert(balanced(signedDebitTotal));
-});
-
-// ---------------------------------------------------------------------------
-// Unapplied cash — building vs drawing down on-account credit.
-// ---------------------------------------------------------------------------
-
-Deno.test("AR partial: unapplied cash builds on-account credit", () => {
- const { lines, signedDebitTotal } = buildPaymentJournal(
- arBase({
- totalAmount: 100,
- applications: [
- {
- targetSalesInvoiceId: "si_1",
- appliedAmount: 60,
- discountAmount: 0,
- writeOffAmount: 0,
- targetExchangeRate: 1,
- sourceExchangeRate: 1,
- },
- ],
- })
+ assertEquals(total(result, "bank"), 150);
+ assertEquals(total(result, "control"), -150);
+ assertEquals(
+ result.lines.find((line) => line.description.includes("on-account credit"))
+ ?.amount,
+ -50,
);
-
- assertEquals(line(lines, "Bank / Cash")!.amount, 100);
- assertEquals(line(lines, "Accounts Receivable")!.amount, -60);
- const credit = line(lines, "Accounts Receivable (on-account credit)")!;
- assertEquals(credit.amount, -40); // credit asset (no invoice anchor)
- assertEquals(credit.documentLineReference, undefined);
- assert(balanced(signedDebitTotal));
+ assertEquals(result.signedDebitTotal, 0);
});
-Deno.test("AR over-application draws down existing credit (inverse side)", () => {
- const { lines, signedDebitTotal } = buildPaymentJournal(
- arBase({
- totalAmount: 80,
- applications: [
- {
- targetSalesInvoiceId: "si_1",
- appliedAmount: 100,
- discountAmount: 0,
- writeOffAmount: 0,
- targetExchangeRate: 1,
- sourceExchangeRate: 1,
- },
- ],
- })
+for (const isAR of [true, false]) {
+ Deno.test(`${isAR ? "AR" : "AP"} zero-cash prior credit uses original source carrying at changed target rate`, () => {
+ const result = buildPaymentJournal(payment({
+ isAR,
+ cashIn: isAR,
+ totalAmount: 0,
+ exchangeRate: 1.5,
+ applications: [app({
+ targetSalesInvoiceId: isAR ? "invoice" : null,
+ targetPurchaseInvoiceId: isAR ? null : "invoice",
+ appliedAmount: 88,
+ targetExchangeRate: 1.25,
+ sourcePaymentId: "prior",
+ fxGainLossAmount: isAR ? 12 : -12,
+ })],
+ }));
+ assertEquals(total(result, "bank"), 0);
+ assertEquals(
+ result.lines.find((line) => line.description.includes("credit applied"))
+ ?.amount,
+ 100,
+ );
+ assertEquals(result.totalFxImpact, isAR ? 12 : -12);
+ assertEquals(result.signedDebitTotal, 0);
+ });
+}
+
+Deno.test("mixed current cash and two prior snapshots release recorded sources independently", () => {
+ const result = buildPaymentJournal(payment({
+ totalAmount: 55,
+ applications: [
+ app({ sourceAmount: 55, appliedAmount: 50 }),
+ app({
+ sourcePaymentId: "first",
+ sourceAmount: 27.5,
+ sourceExchangeRate: 1,
+ appliedAmount: 25,
+ fxGainLossAmount: 2.5,
+ }),
+ app({
+ sourcePaymentId: "second",
+ sourceAmount: 27.5,
+ sourceExchangeRate: 1.25,
+ appliedAmount: 25,
+ fxGainLossAmount: -3,
+ }),
+ ],
+ }));
+ assertEquals(total(result, "bank"), 50);
+ assertEquals(
+ result.lines.find((line) => line.description.includes("credit applied"))
+ ?.amount,
+ 49.5,
);
-
- assertEquals(line(lines, "Bank / Cash")!.amount, 80);
- assertEquals(line(lines, "Accounts Receivable")!.amount, -100);
- const draw = line(lines, "Accounts Receivable (credit applied)")!;
- assertEquals(draw.amount, 20); // debit asset — inverse of building credit
- assert(balanced(signedDebitTotal));
+ assertEquals(result.totalFxImpact, -0.5);
+ assertEquals(result.signedDebitTotal, 0);
});
-// ---------------------------------------------------------------------------
-// Multi-invoice + combined relief still balances.
-// ---------------------------------------------------------------------------
-
-Deno.test("AR two invoices with discount and FX all balance", () => {
- const { lines, signedDebitTotal } = buildPaymentJournal(
- arBase({
- exchangeRate: 1.1,
- totalAmount: 190,
+Deno.test("terminal160.01 release uses recorded base .01 without reconstructing source units", () => {
+ const result = buildPaymentJournal(
+ payment({
+ totalAmount: 160.01,
+ exchangeRate: 16000,
applications: [
- {
- targetSalesInvoiceId: "si_1",
- appliedAmount: 100,
- discountAmount: 0,
- writeOffAmount: 0,
- targetExchangeRate: 1.0,
- sourceExchangeRate: 1.1,
- },
- {
- targetSalesInvoiceId: "si_2",
- appliedAmount: 90,
- discountAmount: 10,
- writeOffAmount: 0,
- targetExchangeRate: 1.0,
- sourceExchangeRate: 1.1,
- },
+ app({
+ sourceAmount: 160.01,
+ sourceExchangeRate: 16000,
+ targetExchangeRate: 16000,
+ appliedAmount: 0.01,
+ }),
],
- })
- );
-
- // Two control lines, one discount, one FX gain, cash — and it balances.
- assert(line(lines, "Customer Payment Discount") !== undefined);
- assert(line(lines, "Realized FX Gain") !== undefined);
- assert(balanced(signedDebitTotal));
-});
-
-// ---------------------------------------------------------------------------
-// Refusal paths — missing account defaults and an unbalanced entry.
-// ---------------------------------------------------------------------------
-
-Deno.test("throws when the control account default is missing", () => {
- assertThrows(
- () =>
- buildPaymentJournal(
- arBase({ accounts: { ...ACCOUNTS, controlAccountId: null } })
- ),
- Error,
- "receivables account default"
- );
-});
-
-Deno.test("throws when a discount is taken but no discount account is set", () => {
- assertThrows(
- () =>
- buildPaymentJournal(
- arBase({
- totalAmount: 90,
- accounts: { ...ACCOUNTS, discountAccountId: null },
- applications: [
- {
- targetSalesInvoiceId: "si_1",
- appliedAmount: 90,
- discountAmount: 10,
- writeOffAmount: 0,
- targetExchangeRate: 1,
- sourceExchangeRate: 1,
- },
- ],
- })
- ),
- Error,
- "payment discount account default"
+ }),
);
+ assertEquals(total(result, "bank"), 0.01);
+ assertEquals(total(result, "control"), -0.01);
+ assertEquals(result.signedDebitTotal, 0);
});
-Deno.test("throws when an FX gain arises but no FX gain account is set", () => {
- assertThrows(
- () =>
- buildPaymentJournal(
- arBase({
- exchangeRate: 1.2,
- accounts: { ...ACCOUNTS, fxGainAccountId: null },
- applications: [
- {
- targetSalesInvoiceId: "si_1",
- appliedAmount: 100,
- discountAmount: 0,
- writeOffAmount: 0,
- targetExchangeRate: 1.0,
- sourceExchangeRate: 1.2,
- },
- ],
- })
- ),
- Error,
- "realized FX gain account default"
- );
-});
-
-Deno.test("throws when a write-off arises but no write-off account is set", () => {
- assertThrows(
- () =>
- buildPaymentJournal(
- apBase({
- totalAmount: 90,
- accounts: { ...ACCOUNTS, writeOffAccountId: null },
- applications: [
- {
- targetPurchaseInvoiceId: "pi_1",
- appliedAmount: 90,
- discountAmount: 0,
- writeOffAmount: 10,
- targetExchangeRate: 1,
- sourceExchangeRate: 1,
- },
- ],
- })
- ),
- Error,
- "write-off account default"
- );
-});
-
-// ---------------------------------------------------------------------------
-// No applications — a pure prepayment / on-account receipt or supplier advance.
-// ---------------------------------------------------------------------------
-
-Deno.test("AR prepayment with no applications: cash + full on-account credit", () => {
- const { lines, signedDebitTotal, totalFxImpact } = buildPaymentJournal(
- arBase({ totalAmount: 250, applications: [] })
- );
-
- assertEquals(lines.length, 2);
- assertEquals(line(lines, "Bank / Cash")!.amount, 250); // debit asset
- const credit = line(lines, "Accounts Receivable (on-account credit)")!;
- assertEquals(credit.amount, -250); // credit asset, no invoice anchor
- assertEquals(credit.documentLineReference, undefined);
- assertEquals(totalFxImpact, 0);
- assert(balanced(signedDebitTotal));
-});
-
-Deno.test("AP advance with no applications: CR bank + on-account credit", () => {
- const { lines, signedDebitTotal } = buildPaymentJournal(
- apBase({ totalAmount: 250, applications: [] })
- );
-
- assertEquals(lines.length, 2);
- assertEquals(line(lines, "Bank / Cash")!.amount, -250); // credit asset
- assert(line(lines, "Accounts Payable (on-account credit)") !== undefined);
- assert(balanced(signedDebitTotal));
-});
-
-// ---------------------------------------------------------------------------
-// Unapplied threshold — the 0.0001 dust band must not emit a spurious line.
-// ---------------------------------------------------------------------------
-
-Deno.test("applied exactly equal to cash emits no unapplied line", () => {
- const { lines } = buildPaymentJournal(arBase());
- assert(line(lines, "Accounts Receivable (on-account credit)") === undefined);
- assert(line(lines, "Accounts Receivable (credit applied)") === undefined);
-});
-
-// Anything the ledger can STORE has to be booked: the cash line already carries
-// the full amount, so a dropped residual would be stored out of balance. At scale
-// 5 that means 0.00005 gets its own on-account line; only float noise is dropped.
-Deno.test("storable unapplied dust still emits an on-account line", () => {
- const { lines, signedDebitTotal } = buildPaymentJournal(
- arBase({
- totalAmount: 100,
+Deno.test("positive final document unit with zero base is a valid balanced settlement", () => {
+ const result = buildPaymentJournal(
+ payment({
+ totalAmount: 0.01,
+ exchangeRate: 16000,
applications: [
- {
- targetSalesInvoiceId: "si_1",
- appliedAmount: 99.99995, // unapplied 0.00005 — representable at scale 5
- discountAmount: 0,
- writeOffAmount: 0,
- targetExchangeRate: 1,
- sourceExchangeRate: 1,
- },
+ app({
+ sourceAmount: 0.01,
+ sourceExchangeRate: 16000,
+ targetExchangeRate: 16000,
+ appliedAmount: 0,
+ }),
],
- })
+ }),
);
+ assertEquals(result.signedDebitTotal, 0);
+ assertEquals(result.totalFxImpact, 0);
+});
+
+Deno.test("final prior-source .33334 carrying release is honored instead of rerounding1/3", () => {
+ const result = buildPaymentJournal(payment({
+ totalAmount: 0,
+ exchangeRate: 1,
+ applications: [
+ app({
+ sourcePaymentId: "prior",
+ sourceAmount: 1,
+ sourceExchangeRate: 3,
+ targetExchangeRate: 2,
+ appliedAmount: 0.5,
+ fxGainLossAmount: -0.16666,
+ }),
+ ],
+ }));
assertEquals(
- line(lines, "Accounts Receivable (on-account credit)")?.amount,
- -0.00005
+ result.lines.find((line) => line.description.includes("credit applied"))
+ ?.amount,
+ 0.33334,
);
- assert(balanced(signedDebitTotal));
+ assertEquals(result.totalFxImpact, -0.16666);
+ assert(Math.abs(result.signedDebitTotal) < 1e-9);
});
-Deno.test("float-noise unapplied is dropped and the entry still balances", () => {
- const { lines, signedDebitTotal } = buildPaymentJournal(
- arBase({
- totalAmount: 100,
+Deno.test("discount-only application creates no source release or FX", () => {
+ const result = buildPaymentJournal(
+ payment({
+ totalAmount: 0,
applications: [
- {
- targetSalesInvoiceId: "si_1",
- appliedAmount: 99.9999999, // below EPSILON — not storable
- discountAmount: 0,
- writeOffAmount: 0,
- targetExchangeRate: 1,
- sourceExchangeRate: 1,
- },
+ app({ sourceAmount: 0, appliedAmount: 0, discountAmount: 100 }),
],
- })
+ }),
);
- assert(line(lines, "Accounts Receivable (on-account credit)") === undefined);
- assert(balanced(signedDebitTotal));
+ assertEquals(total(result, "control"), -100);
+ assertEquals(total(result, "discount"), 100);
+ assertEquals(result.signedDebitTotal, 0);
});
-// ---------------------------------------------------------------------------
-// Multiple invoices — full settlement, over-application, under-application.
-// ---------------------------------------------------------------------------
-
-Deno.test("AR three invoices fully settled: one cash + three control lines", () => {
- const { lines, signedDebitTotal } = buildPaymentJournal(
- arBase({
- totalAmount: 60,
- applications: [
- { targetSalesInvoiceId: "si_1", appliedAmount: 10, discountAmount: 0, writeOffAmount: 0, targetExchangeRate: 1, sourceExchangeRate: 1 },
- { targetSalesInvoiceId: "si_2", appliedAmount: 20, discountAmount: 0, writeOffAmount: 0, targetExchangeRate: 1, sourceExchangeRate: 1 },
- { targetSalesInvoiceId: "si_3", appliedAmount: 30, discountAmount: 0, writeOffAmount: 0, targetExchangeRate: 1, sourceExchangeRate: 1 },
- ],
- })
+Deno.test("source and invoice references remain attached to actual emitted lines", () => {
+ const result = buildPaymentJournal(payment());
+ for (const line of result.lines) {
+ assertEquals(line.documentId, "payment");
+ assertEquals(line.companyId, "company");
+ assertEquals(line.journalLineReference, "reference");
+ }
+ assertEquals(
+ result.lines.find((line) => line.accountId === "control")
+ ?.documentLineReference,
+ "invoice",
);
-
- assertEquals(lines.filter((l) => l.description === "Accounts Receivable").length, 3);
- assertEquals(line(lines, "Bank / Cash")!.amount, 60);
- assert(line(lines, "Accounts Receivable (on-account credit)") === undefined);
- assertEquals(controlMagnitudeFor(lines, "si_1"), 10);
- assertEquals(controlMagnitudeFor(lines, "si_2"), 20);
- assertEquals(controlMagnitudeFor(lines, "si_3"), 30);
- assert(balanced(signedDebitTotal));
});
-Deno.test("AR overpayment across multiple invoices: single draw-down line", () => {
- const { lines, signedDebitTotal } = buildPaymentJournal(
- arBase({
- totalAmount: 150,
- applications: [
- { targetSalesInvoiceId: "si_1", appliedAmount: 100, discountAmount: 0, writeOffAmount: 0, targetExchangeRate: 1, sourceExchangeRate: 1 },
- { targetSalesInvoiceId: "si_2", appliedAmount: 80, discountAmount: 0, writeOffAmount: 0, targetExchangeRate: 1, sourceExchangeRate: 1 },
- ],
- })
- );
-
- // applied 180 vs cash 150 → 30 drawn from existing credit (inverse side).
- const draw = line(lines, "Accounts Receivable (credit applied)")!;
- assertEquals(draw.amount, 30); // debit asset
- assertEquals(lines.filter((l) => l.description === "Accounts Receivable (on-account credit)").length, 0);
- assert(balanced(signedDebitTotal));
-});
-
-Deno.test("AP underpayment across multiple invoices builds credit", () => {
- const { lines, signedDebitTotal } = buildPaymentJournal(
- apBase({
- totalAmount: 200,
- applications: [
- { targetPurchaseInvoiceId: "pi_1", appliedAmount: 60, discountAmount: 0, writeOffAmount: 0, targetExchangeRate: 1, sourceExchangeRate: 1 },
- { targetPurchaseInvoiceId: "pi_2", appliedAmount: 60, discountAmount: 0, writeOffAmount: 0, targetExchangeRate: 1, sourceExchangeRate: 1 },
- ],
- })
+for (
+ const [field, input] of [
+ ["controlAccountId", payment()],
+ [
+ "discountAccountId",
+ payment({
+ totalAmount: 99,
+ applications: [
+ app({ sourceAmount: 99, appliedAmount: 90, discountAmount: 10 }),
+ ],
+ }),
+ ],
+ [
+ "writeOffAccountId",
+ payment({
+ totalAmount: 99,
+ applications: [
+ app({ sourceAmount: 99, appliedAmount: 90, writeOffAmount: 10 }),
+ ],
+ }),
+ ],
+ [
+ "fxGainAccountId",
+ payment({
+ exchangeRate: 1,
+ applications: [app({ sourceExchangeRate: 1, fxGainLossAmount: 10 })],
+ }),
+ ],
+ [
+ "fxLossAccountId",
+ payment({
+ exchangeRate: 1.25,
+ applications: [
+ app({ sourceExchangeRate: 1.25, fxGainLossAmount: -12 }),
+ ],
+ }),
+ ],
+ ] as const
+) {
+ Deno.test(`missing relevant ${field} refuses journal construction`, () => {
+ assertThrows(() =>
+ buildPaymentJournal({
+ ...input,
+ accounts: { ...accounts, [field]: null },
+ })
+ );
+ });
+}
+
+Deno.test("invalid rates, nonfinite values, negative relief and excessive fees fail", () => {
+ for (const exchangeRate of [0, -1, Number.NaN, Number.POSITIVE_INFINITY]) {
+ assertThrows(() => buildPaymentJournal(payment({ exchangeRate })));
+ }
+ for (const totalAmount of [-1, Number.NaN, Number.POSITIVE_INFINITY]) {
+ assertThrows(() => buildPaymentJournal(payment({ totalAmount })));
+ }
+ assertThrows(() =>
+ buildPaymentJournal(
+ payment({ applications: [app({ discountAmount: -1 })] }),
+ )
);
-
- // 200 cash − 120 applied → 80 on-account credit.
- const credit = line(lines, "Accounts Payable (on-account credit)")!;
- assertEquals(Math.abs(credit.amount), 80);
- assert(balanced(signedDebitTotal));
-});
-
-// ---------------------------------------------------------------------------
-// Combined relief + FX on the same application.
-// ---------------------------------------------------------------------------
-
-Deno.test("AR discount + write-off + FX on one invoice all coexist, balanced", () => {
- const { lines, signedDebitTotal } = buildPaymentJournal(
- arBase({
- exchangeRate: 1.2,
- totalAmount: 80, // pays 80 cash; 10 discount + 10 write-off settle a 100 invoice
- applications: [
- {
- targetSalesInvoiceId: "si_1",
- appliedAmount: 80,
- discountAmount: 10,
- writeOffAmount: 10,
- targetExchangeRate: 1.0,
- sourceExchangeRate: 1.2,
- },
- ],
- })
+ assertThrows(() =>
+ buildPaymentJournal(payment({ fee: { amount: 111, accountId: "fee" } }))
);
-
- assertEquals(line(lines, "Bank / Cash")!.amount, 96); // 80 × 1.2
- assertEquals(line(lines, "Accounts Receivable")!.amount, -100); // (80+10+10) × 1.0
- assertEquals(line(lines, "Customer Payment Discount")!.amount, -10); // −(10 × 1.0): debit to Revenue = contra-revenue
- assertEquals(line(lines, "Bad Debt Expense")!.amount, 10); // 10 × 1.0
- assertEquals(line(lines, "Realized FX Gain")!.amount, 16); // 80 × (1.2 − 1.0)
- assert(balanced(signedDebitTotal));
-});
-
-Deno.test("FX accrues on applied principal only, never on discount/write-off", () => {
- // Pure discount settlement with a rate gap: applied 0 ⇒ no FX line at all.
- const { lines, totalFxImpact } = buildPaymentJournal(
- arBase({
- totalAmount: 0,
- applications: [
- {
- targetSalesInvoiceId: "si_1",
- appliedAmount: 0,
- discountAmount: 50,
- writeOffAmount: 0,
- targetExchangeRate: 1.0,
- sourceExchangeRate: 1.5,
- },
- ],
- })
+ assertThrows(() =>
+ buildPaymentJournal(
+ payment({ applications: [app({ fxGainLossAmount: Number.NaN })] }),
+ )
);
-
- assertEquals(totalFxImpact, 0);
- assert(line(lines, "Realized FX Gain") === undefined);
- assert(line(lines, "Realized FX Loss") === undefined);
});
-Deno.test("opposing per-invoice FX nets to zero → no FX plug line", () => {
- const { lines, signedDebitTotal, totalFxImpact } = buildPaymentJournal(
- arBase({
- exchangeRate: 1.0,
- totalAmount: 200,
- applications: [
- { targetSalesInvoiceId: "si_1", appliedAmount: 100, discountAmount: 0, writeOffAmount: 0, targetExchangeRate: 1.0, sourceExchangeRate: 1.1 }, // +10
- { targetSalesInvoiceId: "si_2", appliedAmount: 100, discountAmount: 0, writeOffAmount: 0, targetExchangeRate: 1.0, sourceExchangeRate: 0.9 }, // −10
- ],
- })
+Deno.test("inconsistent cash source snapshots cannot be concealed by an unapplied plug", () => {
+ assertThrows(() =>
+ buildPaymentJournal(
+ payment({ applications: [app({ fxGainLossAmount: 10 })] }),
+ )
);
-
- assert(Math.abs(totalFxImpact) < 1e-9);
- assert(line(lines, "Realized FX Gain") === undefined);
- assert(line(lines, "Realized FX Loss") === undefined);
- assert(balanced(signedDebitTotal));
-});
-
-// ---------------------------------------------------------------------------
-// Rounding — NUMERIC(19,4): every magnitude is rounded to 4 dp and the entry
-// still balances within tolerance under messy rates.
-// ---------------------------------------------------------------------------
-
-Deno.test("magnitudes round to 4 dp and the entry still balances", () => {
- // Consistent rates (cash exchangeRate == application paymentExchangeRate).
- // cash = 100 × 1.11111 = 111.111; control = 100 × 1.0 = 100;
- // FX = 100 × (1.11111 − 1.0) = 11.111 → all land on 4 dp and net to zero.
- const { lines, signedDebitTotal } = buildPaymentJournal(
- arBase({
- exchangeRate: 1.11111,
- totalAmount: 100,
- applications: [
- {
- targetSalesInvoiceId: "si_1",
- appliedAmount: 100,
- discountAmount: 0,
- writeOffAmount: 0,
- targetExchangeRate: 1.0,
- sourceExchangeRate: 1.11111,
- },
- ],
- })
+ assertThrows(() => buildPaymentJournal(payment({ newOnAccountBase: 5 })));
+});
+
+// #1600 reclassified the seeded discount accounts: customer discounts are
+// contra-revenue (4040, class Revenue) and supplier discounts contra-COGS
+// (5080, class Expense) — neither is an operating expense. The journal line's
+// natural-balance sign therefore follows the ACCOUNT'S class, not a hardcoded
+// "expense". The tests above omit `discountAccountClass` on purpose and pin the
+// back-compat fallback.
+Deno.test("AR customer discount debits a Revenue-class account as contra-revenue", () => {
+ const result = buildPaymentJournal(payment({
+ totalAmount: 88,
+ exchangeRate: 1,
+ accounts: { ...accounts, discountAccountClass: "Revenue" },
+ applications: [
+ app({
+ sourceAmount: 88,
+ sourceExchangeRate: 1,
+ appliedAmount: 80,
+ discountAmount: 15,
+ writeOffAmount: 5,
+ fxGainLossAmount: 8,
+ }),
+ ],
+ }));
+ // A debit to a credit-natural account stores negative: the discount REDUCES
+ // revenue rather than adding an expense.
+ assertEquals(total(result, "discount"), -15);
+ assertEquals(total(result, "control"), -100);
+ assertEquals(result.signedDebitTotal, 0);
+});
+
+Deno.test("AP supplier discount credits an Expense-class account as contra-cost", () => {
+ const result = buildPaymentJournal(payment({
+ isAR: false,
+ cashIn: false,
+ totalAmount: 88,
+ exchangeRate: 1,
+ accounts: { ...accounts, discountAccountClass: "Expense" },
+ applications: [app({
+ targetSalesInvoiceId: null,
+ targetPurchaseInvoiceId: "invoice",
+ sourceAmount: 88,
+ sourceExchangeRate: 1,
+ appliedAmount: 80,
+ discountAmount: 15,
+ writeOffAmount: 5,
+ fxGainLossAmount: -8,
+ })],
+ }));
+ assertEquals(total(result, "discount"), -15);
+ assertEquals(total(result, "control"), -100);
+ assertEquals(result.signedDebitTotal, 0);
+});
+
+Deno.test("an unknown discount account class is refused rather than guessed", () => {
+ assertThrows(() =>
+ buildPaymentJournal(payment({
+ accounts: { ...accounts, discountAccountClass: "Contra-Revenue" },
+ applications: [app({ discountAmount: 10 })],
+ }))
);
-
- assertEquals(line(lines, "Bank / Cash")!.amount, 111.111);
- assertEquals(line(lines, "Accounts Receivable")!.amount, -100);
- assertEquals(line(lines, "Realized FX Gain")!.amount, 11.111);
- assert(balanced(signedDebitTotal));
-});
-
-// ---------------------------------------------------------------------------
-// Subledger tie-out — the property the SQL tie-out RPCs depend on. For every
-// application, the magnitude posted to the control account equals the settled
-// amount (applied + discount + write-off) at the INVOICE rate, so the GL
-// reconciles to the subledger invoice-by-invoice.
-// ---------------------------------------------------------------------------
-
-Deno.test("control posting ties out to subledger settled per invoice (AR & AP)", () => {
- const apps = [
- { applied: 100, discount: 5, writeOff: 0, invRate: 1.0 },
- { applied: 40, discount: 0, writeOff: 10, invRate: 1.25 },
- { applied: 7.5, discount: 2.5, writeOff: 0, invRate: 0.8 },
- ];
-
- for (const isReceipt of [true, false]) {
- const base = isReceipt ? arBase() : apBase();
- const { lines, signedDebitTotal } = buildPaymentJournal({
- ...base,
- exchangeRate: 1.0,
- totalAmount: apps.reduce((s, a) => s + a.applied, 0),
- applications: apps.map((a, i) => ({
- [isReceipt ? "targetSalesInvoiceId" : "targetPurchaseInvoiceId"]: `inv_${i}`,
- appliedAmount: a.applied,
- discountAmount: a.discount,
- writeOffAmount: a.writeOff,
- targetExchangeRate: a.invRate,
- sourceExchangeRate: 1.0,
- })),
- });
-
- apps.forEach((a, i) => {
- const expected = round((a.applied + a.discount + a.writeOff) * a.invRate);
- assertEquals(controlMagnitudeFor(lines, `inv_${i}`), expected);
- });
- assert(balanced(signedDebitTotal));
- }
-});
-
-// ---------------------------------------------------------------------------
-// Property matrix — every AR/AP × rate × relief combination must balance and
-// must post the correct FX side (gain when collected/under-paid high, loss when
-// collected low / over-paid high).
-// ---------------------------------------------------------------------------
-
-Deno.test("matrix: every scenario balances with the correct FX side", () => {
- const invRates = [0.75, 1.0, 1.37];
- const payRates = [0.75, 1.0, 1.37];
- const reliefs = [
- { discount: 0, writeOff: 0 },
- { discount: 5, writeOff: 0 },
- { discount: 0, writeOff: 5 },
- { discount: 3, writeOff: 4 },
- ];
-
- for (const isReceipt of [true, false]) {
- for (const invRate of invRates) {
- for (const payRate of payRates) {
- for (const relief of reliefs) {
- const applied = 100;
- const base = isReceipt ? arBase() : apBase();
- const { lines, signedDebitTotal, totalFxImpact } = buildPaymentJournal({
- ...base,
- exchangeRate: payRate,
- totalAmount: applied,
- applications: [
- {
- [isReceipt ? "targetSalesInvoiceId" : "targetPurchaseInvoiceId"]: "inv",
- appliedAmount: applied,
- discountAmount: relief.discount,
- writeOffAmount: relief.writeOff,
- targetExchangeRate: invRate,
- sourceExchangeRate: payRate,
- },
- ],
- });
-
- assert(
- Math.abs(signedDebitTotal) < 0.01,
- `unbalanced: receipt=${isReceipt} inv=${invRate} pay=${payRate}`
- );
-
- const expectedFx =
- (isReceipt ? 1 : -1) * applied * (payRate - invRate);
- if (Math.abs(expectedFx) > 0.0001) {
- const side = expectedFx > 0 ? "Realized FX Gain" : "Realized FX Loss";
- const wrong = expectedFx > 0 ? "Realized FX Loss" : "Realized FX Gain";
- assert(line(lines, side) !== undefined, `missing ${side}`);
- assert(line(lines, wrong) === undefined, `unexpected ${wrong}`);
- }
- assert(Math.abs(round(totalFxImpact) - round(expectedFx)) < 1e-9);
- }
- }
- }
- }
});
diff --git a/packages/database/supabase/functions/post-purchase-invoice/index.ts b/packages/database/supabase/functions/post-purchase-invoice/index.ts
index 312e17fab2..10588d6e78 100644
--- a/packages/database/supabase/functions/post-purchase-invoice/index.ts
+++ b/packages/database/supabase/functions/post-purchase-invoice/index.ts
@@ -24,6 +24,11 @@ import {
resolveInventoryAccount,
} from "../shared/get-posting-group.ts";
import { round } from "../shared/precision.ts";
+import { classifyIntercompanyPostingLines } from "../shared/intercompany-capture.ts";
+import {
+ calculatePurchasePostingAmounts,
+ getInvoicedPurchaseQuantityAfterVoid,
+} from "./purchase-posting-amounts.ts";
const pool = getConnectionPool(1);
const db = getDatabaseClient<DB>(pool);
@@ -187,13 +192,9 @@ serve(async (req: Request) => {
purchaseOrderLine.purchaseQuantity &&
purchaseOrderLine.purchaseQuantity > 0
) {
- const invoicedQuantityInPurchaseUnit =
- invoiceLine.quantity / (invoiceLine.conversionFactor ?? 1);
-
- const newQuantityInvoiced = Math.max(
- 0,
- (purchaseOrderLine.quantityInvoiced ?? 0) -
- invoicedQuantityInPurchaseUnit
+ const newQuantityInvoiced = getInvoicedPurchaseQuantityAfterVoid(
+ purchaseOrderLine.quantityInvoiced,
+ invoiceLine.quantity,
);
// Short-close aware: compare against the billable (received)
@@ -552,34 +553,14 @@ serve(async (req: Request) => {
if (dim.entityType) dimensionMap.set(dim.entityType, dim.id);
}
- // supplierShippingCost is a supplier-currency amount; currency.exchangeRate
- // stores foreign-units-per-base, so supplier→base is DIVIDE (matching the
- // purchaseInvoices view and the line-level generated columns). It is then
- // folded into the per-line totals BEFORE the payment-chain exchange-rate
- // multiplier so AP is credited exactly what post-payment will debit.
- const shippingCost =
- (purchaseInvoiceDelivery.data?.supplierShippingCost ?? 0) /
- (purchaseInvoice.data?.exchangeRate || 1);
-
- // Pre-allocation denominator for the header shipping cost. Comment lines
- // post no journal entries, so they must not absorb a share of the
- // shipping (it would never reach the GL).
- const totalLinesCost = purchaseInvoiceLines.data.reduce(
- (acc, invoiceLine) => {
- if (invoiceLine.invoiceLineType === "Comment") return acc;
- const lineCost =
- (invoiceLine.quantity ?? 0) * (invoiceLine.unitPrice ?? 0) +
- (invoiceLine.shippingCost ?? 0) +
- (invoiceLine.taxAmount ?? 0);
- return acc + lineCost;
- },
- 0
+ const amountsByLineId = new Map(
+ calculatePurchasePostingAmounts({
+ lines: purchaseInvoiceLines.data,
+ exchangeRate: purchaseInvoice.data.exchangeRate ?? 1,
+ supplierShippingCost: purchaseInvoiceDelivery.data.supplierShippingCost ?? 0,
+ }).map((amounts) => [amounts.id, amounts])
);
- const postableLineCount = purchaseInvoiceLines.data.filter(
- (invoiceLine) => invoiceLine.invoiceLineType !== "Comment"
- ).length;
-
const itemIds = purchaseInvoiceLines.data.reduce<string[]>(
(acc, invoiceLine) => {
if (invoiceLine.itemId && !acc.includes(invoiceLine.itemId)) {
@@ -637,20 +618,11 @@ serve(async (req: Request) => {
? 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)
- );
- },
+ // Keep the existing pre-tax matching basis in the document currency named
+ // on the trade. Supplier fields retain that denomination; generated unitPrice
+ // and shippingCost are base and must not be labelled as document amounts.
+ const intercompanyAmount = [...amountsByLineId.values()].reduce(
+ (total, amounts) => total + amounts.intercompanyDocumentAmount,
0
);
@@ -829,43 +801,14 @@ serve(async (req: Request) => {
? 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
- // line totals (header shipping included, already divided to base above)
- // to keep AP credit == what payments will debit. See the FX-convention
- // spec for the planned normalization of this multiplier.
- const invoiceExchangeRate = purchaseInvoice.data?.exchangeRate ?? 1;
-
for await (const invoiceLine of purchaseInvoiceLines.data) {
- const invoiceLineQuantityInInventoryUnit =
- invoiceLine.quantity * (invoiceLine.conversionFactor ?? 1);
-
- const totalLineCost =
- invoiceLine.quantity * (invoiceLine.unitPrice ?? 0) +
- (invoiceLine.shippingCost ?? 0) +
- (invoiceLine.taxAmount ?? 0);
-
- // When every line has a zero basis (e.g. a freight-only invoice), fall
- // back to equal weights so the header shipping still reaches AP.
- const lineCostPercentageOfTotalCost =
- invoiceLine.invoiceLineType === "Comment"
- ? 0
- : totalLinesCost === 0
- ? postableLineCount === 0
- ? 0
- : 1 / postableLineCount
- : totalLineCost / totalLinesCost;
- const lineWeightedShippingCost =
- shippingCost * lineCostPercentageOfTotalCost;
- // Line cost and weighted shipping are both base currency here; the
- // exchange-rate multiplier matches the payment chain's AP relief.
- const totalLineCostWithWeightedShipping =
- (totalLineCost + lineWeightedShippingCost) * invoiceExchangeRate;
-
- const invoiceLineUnitCostInInventoryUnit =
- totalLineCostWithWeightedShipping /
- (invoiceLine.quantity * (invoiceLine.conversionFactor ?? 1));
+ if (invoiceLine.invoiceLineType === "Comment") continue;
+ const postingAmounts = amountsByLineId.get(invoiceLine.id)!;
+ const {
+ inventoryQuantity: invoiceLineQuantityInInventoryUnit,
+ totalBaseCost: totalLineCostWithWeightedShipping,
+ inventoryUnitCost: invoiceLineUnitCostInInventoryUnit,
+ } = postingAmounts;
let journalLineReference: string;
@@ -905,7 +848,7 @@ serve(async (req: Request) => {
locationId: invoiceLine.locationId,
storageUnitId: invoiceLine.storageUnitId,
unitOfMeasure: invoiceLine.inventoryUnitOfMeasureCode ?? "EA",
- unitPrice: invoiceLine.unitPrice ?? 0,
+ unitPrice: invoiceLineUnitCostInInventoryUnit,
requiresSerialTracking: itemTrackingType === "Serial",
requiresBatchTracking: itemTrackingType === "Batch",
createdBy: invoiceLine.createdBy,
@@ -947,9 +890,7 @@ serve(async (req: Request) => {
purchaseInvoice.data?.supplierReference ?? undefined,
itemId: invoiceLine.itemId,
quantity: round(invoiceLineQuantityInInventoryUnit),
- nominalCost: round(
- invoiceLine.quantity * (invoiceLine.unitPrice ?? 0)
- ),
+ nominalCost: postingAmounts.nominalBaseCost,
cost: round(totalLineCostWithWeightedShipping),
remainingQuantity: round(invoiceLineQuantityInInventoryUnit),
supplierId: purchaseInvoice.data?.supplierId,
@@ -1716,8 +1657,6 @@ serve(async (req: Request) => {
}
break;
}
- case "Comment":
- break;
case "G/L Account": {
if (accountingEnabled && accountDefaults?.data) {
const account = await client
@@ -2054,18 +1993,19 @@ serve(async (req: Request) => {
// 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;
+ // Keep the first payable as the matching anchor while capturing every
+ // actual payable row for elimination of multiline and split receipts.
+ const icControlLines = isIntercompany
+ ? classifyIntercompanyPostingLines(
+ journalLineInserts.map((line, index) => ({
+ ...line,
+ id: journalLineResults[index]?.id ?? "",
+ })),
+ journalLineDimensionsMeta,
+ { controlAccountId: payablesAccountId }
+ )
+ : [];
+ const icJournalLineId = icControlLines[0]?.journalLineId ?? null;
if (
isIntercompany &&
intercompanyPartnerId &&
@@ -2095,20 +2035,12 @@ serve(async (req: Request) => {
// 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,
- });
+ icControlLines.map((line) => ({
+ ...line,
+ companyId,
+ intercompanyTransactionId: icTxn.id,
+ createdBy: userId,
+ }));
// Capitalization is any Asset-class DEBIT the buyer posted for the
// goods — which excludes GR/IR clearing (a liability) and expensed
@@ -2137,6 +2069,7 @@ serve(async (req: Request) => {
"jl.quantity as quantity",
])
.where("jl.journalId", "=", journalId)
+ .where("jl.companyId", "=", companyId)
.where("a.class", "=", "Asset")
.where("jl.amount", ">", 0)
.execute();
diff --git a/packages/database/supabase/functions/post-purchase-invoice/purchase-posting-amounts.test.ts b/packages/database/supabase/functions/post-purchase-invoice/purchase-posting-amounts.test.ts
new file mode 100644
index 0000000000..e104f02bf8
--- /dev/null
+++ b/packages/database/supabase/functions/post-purchase-invoice/purchase-posting-amounts.test.ts
@@ -0,0 +1,245 @@
+import {
+ assertEquals,
+ assertThrows,
+} from "https://deno.land/[email protected]/testing/asserts.ts";
+import { round } from "../shared/precision.ts";
+import { allocateVarianceAcrossLayers } from "../shared/purchase-cost-adjustment.ts";
+import {
+ calculatePurchasePostingAmounts,
+ getInvoicedPurchaseQuantityAfterVoid,
+ type PurchasePostingLine,
+} from "./purchase-posting-amounts.ts";
+
+Deno.test("invoice void restores purchase-unit quantities when inventory UOM factor is five", () => {
+ for (const quantity of [2, 1]) {
+ const invoice = line({ quantity, conversionFactor: 5 });
+ const [posted] = calculatePurchasePostingAmounts({
+ lines: [invoice],
+ exchangeRate: 1.1,
+ supplierShippingCost: 0,
+ });
+ assertEquals(posted.inventoryQuantity, quantity * 5);
+ assertEquals(
+ getInvoicedPurchaseQuantityAfterVoid(quantity, invoice.quantity),
+ 0,
+ );
+ }
+ assertEquals(getInvoicedPurchaseQuantityAfterVoid(5, 2), 3);
+ assertEquals(getInvoicedPurchaseQuantityAfterVoid(null, 2), 0);
+});
+
+function line(
+ overrides: Partial<PurchasePostingLine> = {},
+): PurchasePostingLine {
+ return {
+ id: "line",
+ invoiceLineType: "Part",
+ quantity: 1,
+ conversionFactor: 1,
+ unitPrice: 100,
+ shippingCost: 0,
+ taxAmount: 0,
+ ...overrides,
+ };
+}
+
+for (
+ const invoiceLineType of [
+ "Part",
+ "Service",
+ "Fixture",
+ "Fixed Asset",
+ "G/L Account",
+ ]
+) {
+ Deno.test(`${invoiceLineType}: document 110 at rate 1.10 posts 100 base`, () => {
+ const [amounts] = calculatePurchasePostingAmounts({
+ lines: [line({ invoiceLineType })],
+ exchangeRate: 1.1,
+ supplierShippingCost: 0,
+ });
+ assertEquals(amounts.totalBaseCost, 100);
+ assertEquals(amounts.nominalBaseCost, 100);
+ assertEquals(amounts.inventoryUnitCost, 100);
+ });
+}
+
+Deno.test("matching receipt and invoice costs produce zero PPV with freight, tax, FX and a non-1 UOM", () => {
+ // Receipt creation divides base purchase price by the UOM factor, spreads
+ // line tax/freight over inventory units, then post-receipt adds header
+ // supplier freight divided by the foreign-per-base rate.
+ const purchaseQuantity = 2;
+ const conversionFactor = 10;
+ const receiptInventoryQuantity = purchaseQuantity * conversionFactor;
+ const receiptUnitCost = 50 / conversionFactor +
+ (10 + 11) / receiptInventoryQuantity;
+ const receiptCost = receiptInventoryQuantity * receiptUnitCost + 11 / 1.1;
+ const [invoice] = calculatePurchasePostingAmounts({
+ lines: [
+ line({
+ quantity: purchaseQuantity,
+ conversionFactor,
+ unitPrice: 50,
+ shippingCost: 10,
+ taxAmount: 11,
+ }),
+ ],
+ exchangeRate: 1.1,
+ supplierShippingCost: 11,
+ });
+ assertEquals(invoice.inventoryQuantity, 20);
+ assertEquals(invoice.nominalBaseCost, 100);
+ assertEquals(invoice.headerShippingBase, 10);
+ assertEquals(invoice.totalBaseCost, 131);
+ assertEquals(invoice.inventoryUnitCost, 6.55);
+ const variance = round(
+ invoice.inventoryQuantity * invoice.inventoryUnitCost - receiptCost,
+ );
+ assertEquals(variance, 0);
+ assertEquals(
+ allocateVarianceAcrossLayers(
+ [{ id: "receipt", quantity: 20, remainingQuantity: 10 }],
+ 20,
+ variance,
+ ),
+ {
+ inventoryShare: 0,
+ ppvShare: 0,
+ perLayer: [],
+ },
+ );
+});
+
+Deno.test("a true purchase price increase still allocates 5 to inventory and 5 to consumed PPV", () => {
+ const [invoice] = calculatePurchasePostingAmounts({
+ lines: [
+ line({
+ quantity: 2,
+ conversionFactor: 10,
+ unitPrice: 55,
+ shippingCost: 10,
+ taxAmount: 11,
+ }),
+ ],
+ exchangeRate: 1.1,
+ supplierShippingCost: 11,
+ });
+ const variance = round(invoice.totalBaseCost - 131);
+ assertEquals(variance, 10);
+ const allocation = allocateVarianceAcrossLayers(
+ [{ id: "receipt", quantity: 20, remainingQuantity: 10 }],
+ 20,
+ variance,
+ );
+ assertEquals(allocation.inventoryShare, 5);
+ assertEquals(allocation.ppvShare, 5);
+});
+
+Deno.test("header supplier freight is allocated by base cost and comment lines absorb none", () => {
+ const amounts = calculatePurchasePostingAmounts({
+ lines: [
+ line({ id: "a", unitPrice: 25 }),
+ line({ id: "b", unitPrice: 75 }),
+ line({ id: "comment", invoiceLineType: "Comment", unitPrice: 999 }),
+ ],
+ exchangeRate: 0.8,
+ supplierShippingCost: 8,
+ });
+ assertEquals(
+ amounts.map((row) => [row.id, row.headerShippingBase, row.totalBaseCost]),
+ [["a", 2.5, 27.5], ["b", 7.5, 82.5]],
+ );
+});
+
+Deno.test("zero-cost freight allocation reconciles the final internal rounding unit", () => {
+ const amounts = calculatePurchasePostingAmounts({
+ lines: ["a", "b", "c"].map((id) =>
+ line({ id, invoiceLineType: "G/L Account", unitPrice: 0 })
+ ),
+ exchangeRate: 1.1,
+ supplierShippingCost: 0.011,
+ });
+ assertEquals(amounts.map((row) => row.headerShippingBase), [
+ 0.00333,
+ 0.00333,
+ 0.00334,
+ ]);
+ assertEquals(
+ round(amounts.reduce((sum, row) => sum + row.totalBaseCost, 0)),
+ 0.01,
+ );
+});
+
+Deno.test("fractional quantities retain inventory-unit precision", () => {
+ const [amounts] = calculatePurchasePostingAmounts({
+ lines: [
+ line({
+ quantity: 2.5,
+ conversionFactor: 2.4,
+ unitPrice: 3.2,
+ shippingCost: 0.04,
+ taxAmount: 0.01,
+ }),
+ ],
+ exchangeRate: 0.8,
+ supplierShippingCost: 0.016,
+ });
+ assertEquals(amounts.inventoryQuantity, 6);
+ assertEquals(amounts.totalBaseCost, 8.07);
+ assertEquals(amounts.inventoryUnitCost, 1.345);
+});
+
+for (const exchangeRate of [0, -1, Number.NaN, Number.POSITIVE_INFINITY]) {
+ Deno.test(`invalid rate ${exchangeRate} refuses a purchase posting`, () => {
+ assertThrows(
+ () =>
+ calculatePurchasePostingAmounts({
+ lines: [line()],
+ exchangeRate,
+ supplierShippingCost: 0,
+ }),
+ Error,
+ "rate",
+ );
+ });
+}
+
+Deno.test("an invalid UOM factor refuses a nonfinite inventory unit cost", () => {
+ assertThrows(
+ () =>
+ calculatePurchasePostingAmounts({
+ lines: [line({ conversionFactor: 0 })],
+ exchangeRate: 1.1,
+ supplierShippingCost: 0,
+ }),
+ Error,
+ "conversion factor",
+ );
+});
+
+Deno.test("nonfinite base costs cannot enter AP or an acquisition", () => {
+ assertThrows(
+ () =>
+ calculatePurchasePostingAmounts({
+ lines: [line({ unitPrice: Number.NaN })],
+ exchangeRate: 1.1,
+ supplierShippingCost: 0,
+ }),
+ Error,
+ "finite",
+ );
+});
+
+Deno.test("buyer matching value keeps supplier currency and excludes tax/header freight", () => {
+ const source = {
+ ...line({ shippingCost: 10, taxAmount: 20 }),
+ supplierUnitPrice: 110,
+ supplierShippingCost: 11,
+ };
+ const [amounts] = calculatePurchasePostingAmounts({
+ lines: [source],
+ exchangeRate: 1.1,
+ supplierShippingCost: 33,
+ });
+ assertEquals(amounts.intercompanyDocumentAmount, 121);
+});
diff --git a/packages/database/supabase/functions/post-purchase-invoice/purchase-posting-amounts.ts b/packages/database/supabase/functions/post-purchase-invoice/purchase-posting-amounts.ts
new file mode 100644
index 0000000000..dd074bceee
--- /dev/null
+++ b/packages/database/supabase/functions/post-purchase-invoice/purchase-posting-amounts.ts
@@ -0,0 +1,102 @@
+import { toBaseAmount } from "../shared/accounting-currency.ts";
+import { round } from "../shared/precision.ts";
+
+export type PurchasePostingLine = {
+ id: string;
+ invoiceLineType: string;
+ quantity: number;
+ conversionFactor: number | null;
+ /** Generated company-base amount per purchase unit. */
+ unitPrice: number | null;
+ /** Generated company-base line freight and nonrecoverable tax. */
+ shippingCost: number | null;
+ taxAmount: number | null;
+ /** Supplier-currency fields used only for the existing pretax IC matching basis. */
+ supplierUnitPrice?: number | null;
+ supplierShippingCost?: number | null;
+};
+
+export type PurchasePostingAmounts = {
+ id: string;
+ inventoryQuantity: number;
+ nominalBaseCost: number;
+ headerShippingBase: number;
+ totalBaseCost: number;
+ inventoryUnitCost: number;
+ intercompanyDocumentAmount: number;
+};
+
+/** Both the PO counter and invoice quantity are in purchase units. */
+export function getInvoicedPurchaseQuantityAfterVoid(
+ quantityInvoiced: number | null,
+ invoicePurchaseQuantity: number,
+): number {
+ return Math.max(0, (quantityInvoiced ?? 0) - invoicePurchaseQuantity);
+}
+
+export function calculatePurchasePostingAmounts(input: {
+ lines: PurchasePostingLine[];
+ exchangeRate: number;
+ supplierShippingCost: number;
+}): PurchasePostingAmounts[] {
+ const lines = input.lines.filter((line) =>
+ line.invoiceLineType !== "Comment"
+ );
+ const headerBase = toBaseAmount(
+ input.supplierShippingCost,
+ input.exchangeRate,
+ );
+ const costs = lines.map((line) => {
+ const factor = line.conversionFactor ?? 1;
+ if (!Number.isFinite(factor) || factor <= 0) {
+ throw new Error(
+ `Purchase line ${line.id} conversion factor must be positive and finite`,
+ );
+ }
+ const nominal = line.quantity * (line.unitPrice ?? 0);
+ const cost = nominal + (line.shippingCost ?? 0) + (line.taxAmount ?? 0);
+ const inventoryQuantity = line.quantity * factor;
+ const intercompanyDocumentAmount =
+ line.quantity * (line.supplierUnitPrice ?? 0) +
+ (line.supplierShippingCost ?? 0);
+ if (
+ ![nominal, cost, inventoryQuantity, intercompanyDocumentAmount].every(
+ Number.isFinite,
+ )
+ ) {
+ throw new Error(`Purchase line ${line.id} amounts must be finite`);
+ }
+ return { nominal, cost, inventoryQuantity, intercompanyDocumentAmount };
+ });
+ const totalLinesCost = costs.reduce((sum, row) => sum + row.cost, 0);
+ let allocatedHeader = 0;
+ return lines.map((line, index) => {
+ const { nominal, cost, inventoryQuantity, intercompanyDocumentAmount } =
+ costs[index];
+ const weight = totalLinesCost === 0
+ ? 1 / lines.length
+ : cost / totalLinesCost;
+ // Reconcile the final share to the converted header, so all posted shares
+ // retain the total even when an equal allocation crosses internal precision.
+ const headerShippingBase = round(
+ index === lines.length - 1
+ ? headerBase - allocatedHeader
+ : headerBase * weight,
+ );
+ allocatedHeader += headerShippingBase;
+ // Generated line fields are already base; only supplier header freight is
+ // converted. These same amounts fund AP, inventory/expense and acquisition.
+ const totalBaseCost = round(cost + headerShippingBase);
+ return {
+ id: line.id,
+ inventoryQuantity,
+ nominalBaseCost: round(nominal),
+ headerShippingBase,
+ totalBaseCost,
+ inventoryUnitCost: inventoryQuantity === 0
+ ? 0
+ : totalBaseCost / inventoryQuantity,
+ intercompanyDocumentAmount,
+ };
+ });
+}
diff --git a/packages/database/supabase/functions/post-sales-invoice/index.ts b/packages/database/supabase/functions/post-sales-invoice/index.ts
index a89f2b1efd..c86269d375 100644
--- a/packages/database/supabase/functions/post-sales-invoice/index.ts
+++ b/packages/database/supabase/functions/post-sales-invoice/index.ts
@@ -1,9 +1,11 @@
import { serve } from "https://deno.land/[email protected]/http/server.ts";
import { nanoid } from "https://deno.land/x/[email protected]/mod.ts";
+import { sql } from "kysely";
import z from "npm:zod@^4.5.4";
import { DB, getConnectionPool, getDatabaseClient } from "../lib/database.ts";
import { datetime, getCompanyTimeZone } from "../lib/datetime.ts";
import { getFunctionLogger } from "../lib/logging.ts";
+import { fetchAll } from "../lib/fetch-all.ts";
import { corsPreflight, errorResponse, jsonResponse } from "../lib/response.ts";
import { requirePermissions } from "../lib/supabase.ts";
import type { Database } from "../lib/types.ts";
@@ -18,6 +20,18 @@ import {
} from "../shared/get-posting-group.ts";
import { round } from "../shared/precision.ts";
import { calculateCOGS } from "../shared/calculate-cogs.ts";
+import {
+ assertCurrencyDecimals,
+ assertExchangeRate,
+} from "../shared/accounting-currency.ts";
+import { classifyIntercompanyPostingLines } from "../shared/intercompany-capture.ts";
+import {
+ allocateSalesHeaderShipping,
+ buildSalesPostingLines,
+ calculateSalesIntercompanyAmount,
+ type SalesPostingAccount,
+ type SalesPostingMetadata,
+} from "../shared/sales-posting-amounts.ts";
const pool = getConnectionPool(1);
const db = getDatabaseClient<DB>(pool);
@@ -48,7 +62,7 @@ serve(async (req: Request) => {
const [companyRecord, accountingSettings] = await Promise.all([
client
.from("company")
- .select("companyGroupId")
+ .select("companyGroupId, baseCurrencyCode")
.eq("id", companyId)
.single(),
client
@@ -105,24 +119,9 @@ serve(async (req: Request) => {
switch (type) {
case "post": {
- // Pre-tax denominator for allocating the header shipping cost.
- // Comment lines post no journal entries, so they must not absorb a
- // share of the shipping (it would never reach the GL).
- const totalLinesCost = salesInvoiceLines.data.reduce(
- (acc, invoiceLine) => {
- if (invoiceLine.invoiceLineType === "Comment") return acc;
- const lineCost =
- (invoiceLine.quantity ?? 0) * (invoiceLine.unitPrice ?? 0) +
- (invoiceLine.shippingCost ?? 0) +
- (invoiceLine.addOnCost ?? 0);
- return acc + lineCost;
- },
- 0
- );
-
- const postableLineCount = salesInvoiceLines.data.filter(
- (invoiceLine) => invoiceLine.invoiceLineType !== "Comment"
- ).length;
+ const headerShippingAllocations = accountingEnabled
+ ? allocateSalesHeaderShipping(salesInvoiceLines.data, shippingCost)
+ : new Map<string, number>();
const itemIds = salesInvoiceLines.data.reduce<string[]>(
(acc, invoiceLine) => {
@@ -204,6 +203,12 @@ serve(async (req: Request) => {
saleProceeds: number;
gainLoss: number;
}[] = [];
+ const directAssetDisposals: {
+ assetId: string;
+ saleProceeds: number;
+ netBookValue: number;
+ gainLoss: number;
+ }[] = [];
const salesInvoiceLinesBySalesOrderLine = salesInvoiceLines.data.reduce<
Record<
@@ -283,14 +288,7 @@ serve(async (req: Request) => {
}
}
- const journalLineDimensionsMeta: {
- customerTypeId: string | null;
- itemPostingGroupId: string | null;
- itemId: string | null;
- locationId: string | null;
- costCenterId: string | null;
- fixedAssetClassId: string | null;
- }[] = [];
+ const journalLineDimensionsMeta: SalesPostingMetadata[] = [];
// For IC transactions, book to Inter-Company Receivables instead of
// regular AR. Resolve it from accountDefault (stable id), not by account
@@ -306,49 +304,92 @@ serve(async (req: Request) => {
? icReceivablesAccount
: accountDefaults?.data?.receivablesAccount;
- // Invoice exchange rate (defaults to 1 for base-currency invoices).
- // journalLine.amount is denominated in base currency, so all monetary
- // amounts derived from the invoice's foreign-currency unitPrice etc.
- // must be multiplied by this rate before they reach a journal line.
- const invoiceExchangeRate = salesInvoice.data?.exchangeRate ?? 1;
+ const invoiceCurrencyCode = salesInvoice.data.currencyCode ?? companyRecord.data.baseCurrencyCode;
+ const invoiceExchangeRate = salesInvoice.data.exchangeRate ??
+ (invoiceCurrencyCode === companyRecord.data.baseCurrencyCode ? 1 : Number.NaN);
+ if (accountingEnabled) {
+ if (!companyGroupId) throw new Error("Accounting requires a company group");
+ assertExchangeRate(invoiceExchangeRate);
+ if (invoiceCurrencyCode === companyRecord.data.baseCurrencyCode && invoiceExchangeRate !== 1) {
+ throw new Error("Base-currency invoices require an identity exchange rate");
+ }
+ }
- for await (const invoiceLine of salesInvoiceLines.data) {
+ // Batch the asset/class and disposal facts once. No asset state changes
+ // occur until the journal transaction commits.
+ type InvoiceLineRecord = Database["public"]["Tables"]["salesInvoiceLine"]["Row"];
+ const assetIds = [...new Set(salesInvoiceLines.data
+ .filter((line: InvoiceLineRecord) => line.invoiceLineType === "Fixed Asset" && line.assetId)
+ .map((line: InvoiceLineRecord) => line.assetId!))];
+ const assetQuery = () => client.from("fixedAsset")
+ .select("id, status, acquisitionCost, accumulatedDepreciation, locationId, fixedAssetClass:fixedAssetClassId(id, assetAccountId, accumulatedDepreciationAccountId, writeOffAccountId, gainOnDisposalAccountId, lossOnDisposalAccountId)")
+ .in("id", assetIds).eq("companyId", companyId).order("id");
+ type AssetRecord = Pick<Database["public"]["Tables"]["fixedAsset"]["Row"],
+ "id" | "status" | "acquisitionCost" | "accumulatedDepreciation" | "locationId"> & {
+ fixedAssetClass: Pick<Database["public"]["Tables"]["fixedAssetClass"]["Row"],
+ "id" | "assetAccountId" | "accumulatedDepreciationAccountId" | "writeOffAccountId" | "gainOnDisposalAccountId" | "lossOnDisposalAccountId"> | null;
+ };
+ type DisposalRecord = Pick<Database["public"]["Tables"]["fixedAssetDisposal"]["Row"], "id" | "fixedAssetId" | "netBookValueAtDisposal">;
+ const [assetRecords, disposalRecords, currencyConfig] = await Promise.all([
+ accountingEnabled && assetIds.length > 0
+ ? fetchAll<AssetRecord>(assetQuery)
+ : Promise.resolve({ data: [] as AssetRecord[], error: null }),
+ accountingEnabled && assetIds.length > 0
+ ? fetchAll<DisposalRecord>(() => client.from("fixedAssetDisposal")
+ .select("id, fixedAssetId, netBookValueAtDisposal")
+ .in("fixedAssetId", assetIds).eq("companyId", companyId)
+ .order("createdAt", { ascending: false }).order("id", { ascending: false }))
+ : Promise.resolve({ data: [] as DisposalRecord[], error: null }),
+ accountingEnabled
+ ? client.from("currency").select("decimalPlaces")
+ .eq("companyGroupId", companyGroupId!).eq("code", invoiceCurrencyCode).single()
+ : Promise.resolve({ data: null, error: null }),
+ ]);
+ if (assetRecords.error) throw new Error("Failed to fetch fixed assets for invoice posting");
+ if (disposalRecords.error) throw new Error("Failed to fetch fixed-asset disposal records");
+ if (accountingEnabled && (currencyConfig.error || !currencyConfig.data)) {
+ throw new Error("Missing invoice currency precision configuration");
+ }
+ const invoiceCurrencyDecimals = currencyConfig.data?.decimalPlaces;
+ if (accountingEnabled) assertCurrencyDecimals(invoiceCurrencyDecimals!);
+ const assetsById = new Map<string, AssetRecord>((assetRecords.data ?? []).map((asset: AssetRecord) => [asset.id, asset]));
+ const latestDisposalByAsset = new Map<string, DisposalRecord>();
+ for (const disposal of disposalRecords.data ?? []) {
+ if (!latestDisposalByAsset.has(disposal.fixedAssetId)) latestDisposalByAsset.set(disposal.fixedAssetId, disposal);
+ }
+ const accountIds = new Set<string>();
+ for (const id of [receivablesAccountId, accountDefaults?.data?.salesAccount,
+ accountDefaults?.data?.salesShippingRevenueAccount, accountDefaults?.data?.salesTaxPayableAccount]) {
+ if (id) accountIds.add(id);
+ }
+ for (const asset of assetRecords.data ?? []) {
+ const assetClass = asset.fixedAssetClass;
+ for (const id of [assetClass?.assetAccountId, assetClass?.accumulatedDepreciationAccountId,
+ assetClass?.writeOffAccountId, assetClass?.gainOnDisposalAccountId, assetClass?.lossOnDisposalAccountId]) {
+ if (id) accountIds.add(id);
+ }
+ }
+ const postingAccounts = accountingEnabled
+ ? await client.from("account").select("id, class, active, isGroup, companyGroupId")
+ .in("id", [...accountIds]).eq("companyGroupId", companyGroupId!)
+ : { data: [], error: null };
+ if (postingAccounts.error) throw new Error("Failed to validate invoice posting accounts");
+ const accountsById = new Map<string, SalesPostingAccount>((postingAccounts.data ?? []).map((account: SalesPostingAccount) => [account.id, account]));
+ const account = (id: string | null | undefined) => id ? accountsById.get(id) : undefined;
+ const chargeAccounts = {
+ receivables: account(receivablesAccountId), sales: account(accountDefaults?.data?.salesAccount),
+ shipping: account(accountDefaults?.data?.salesShippingRevenueAccount), tax: account(accountDefaults?.data?.salesTaxPayableAccount),
+ };
+
+ for (const invoiceLine of salesInvoiceLines.data) {
const invoiceLineQuantityInInventoryUnit = invoiceLine.quantity;
-
- const preTaxLineCost =
- invoiceLine.quantity * (invoiceLine.unitPrice ?? 0) +
- (invoiceLine.shippingCost ?? 0) +
- (invoiceLine.addOnCost ?? 0);
-
- // nonTaxableAddOnCost is part of the invoice total (and of the
- // salesInvoices view balance that caps payments) but is excluded
- // from the tax basis.
- const totalLineCost =
- preTaxLineCost * (1 + (invoiceLine.taxPercent ?? 0)) +
- (invoiceLine.nonTaxableAddOnCost ?? 0);
-
- // Header shipping is untaxed (matching the salesInvoices view), so
- // it is weighted by the pre-tax basis — weights sum to exactly 1.
- // When every line has a zero basis, fall back to equal weights so
- // the shipping still reaches AR.
- const lineCostPercentageOfTotalCost =
- invoiceLine.invoiceLineType === "Comment"
- ? 0
- : totalLinesCost === 0
- ? postableLineCount === 0
- ? 0
- : 1 / postableLineCount
- : preTaxLineCost / totalLinesCost;
- const lineWeightedShippingCost =
- shippingCost * lineCostPercentageOfTotalCost;
- // Convert to base currency for the GL.
- const totalLineCostWithWeightedShipping =
- (totalLineCost + lineWeightedShippingCost) * invoiceExchangeRate;
-
- const invoiceLineUnitCostInInventoryUnit =
- totalLineCostWithWeightedShipping / invoiceLine.quantity;
-
- let journalLineReference: string;
+ const postingLine = { ...invoiceLine, allocatedHeaderShipping: headerShippingAllocations.get(invoiceLine.id) ?? 0 };
+ const postingContext = {
+ companyId, companyGroupId: companyGroupId!, documentId: salesInvoice.data.id,
+ externalDocumentId: salesInvoice.data.customerReference,
+ documentLineReference: invoiceLine.salesOrderLineId ? journalReference.to.salesInvoice(invoiceLine.salesOrderLineId) : null,
+ journalLineReference: nanoid(), intercompanyPartnerId,
+ };
switch (invoiceLine.invoiceLineType) {
case "Part":
@@ -364,6 +405,20 @@ serve(async (req: Request) => {
const itemTrackingType =
invoiceLineItem?.itemTrackingType ?? "Inventory";
+ if (accountingEnabled && accountDefaults?.data) {
+ const charges = buildSalesPostingLines({
+ line: postingLine, context: postingContext, accounts: chargeAccounts,
+ metadata: {
+ customerTypeId: customer.data.customerTypeId ?? null,
+ itemPostingGroupId: itemCosts.data.find((cost: Pick<Database["public"]["Tables"]["itemCost"]["Row"], "itemId" | "itemPostingGroupId">) => cost.itemId === invoiceLine.itemId)?.itemPostingGroupId ?? null,
+ itemId: invoiceLine.itemId ?? null, locationId: invoiceLine.locationId ?? null,
+ costCenterId: null, fixedAssetClassId: null,
+ },
+ });
+ journalLineInserts.push(...charges.lines);
+ journalLineDimensionsMeta.push(...charges.metadata);
+ }
+
// if the sales order line is null, we ship the part, do the normal entries and do not use accrual/reversing
if (
invoiceLine.salesOrderLineId === null &&
@@ -414,56 +469,6 @@ serve(async (req: Request) => {
(cost) => cost.itemId === invoiceLine.itemId
)?.itemPostingGroupId ?? null;
- journalLineReference = nanoid();
-
- // credit the sales account
- journalLineInserts.push({
- accountId: accountDefaults.data.salesAccount,
- description: "Sales Account",
- amount: round(
- credit("revenue", totalLineCostWithWeightedShipping)
- ),
- quantity: round(invoiceLineQuantityInInventoryUnit),
- documentType: "Invoice",
- documentId: salesInvoice.data?.id,
- externalDocumentId: salesInvoice.data?.customerReference,
- documentLineReference: journalReference.to.salesInvoice(
- invoiceLine.salesOrderLineId!
- ),
- journalLineReference,
- companyId,
- });
-
- // debit the accounts receivable account
- journalLineInserts.push({
- accountId: receivablesAccountId,
- description: isIntercompany
- ? "IC Receivables"
- : "Accounts Receivable",
- amount: round(debit("asset", totalLineCostWithWeightedShipping)),
- quantity: round(invoiceLineQuantityInInventoryUnit),
- documentType: "Invoice",
- documentId: salesInvoice.data?.id,
- externalDocumentId: salesInvoice.data?.customerReference,
- documentLineReference: journalReference.to.salesInvoice(
- invoiceLine.salesOrderLineId!
- ),
- journalLineReference,
- intercompanyPartnerId,
- companyId,
- });
-
- for (let i = 0; i < 2; i++) {
- journalLineDimensionsMeta.push({
- customerTypeId: customer.data.customerTypeId ?? null,
- itemPostingGroupId: lineItemPostingGroupId,
- itemId: invoiceLine.itemId ?? null,
- locationId: invoiceLine.locationId ?? null,
- costCenterId: null,
- fixedAssetClassId: null,
- });
- }
-
if (itemTrackingType === "Inventory") {
const cogsJournalLineReference = nanoid();
@@ -507,380 +512,62 @@ serve(async (req: Request) => {
}
}
}
- } // if the line is associated with a sales order line, COGS was posted at shipment — keep only AR + Revenue
- else {
- if (accountingEnabled && accountDefaults?.data) {
- // Create the normal GL entries for the invoice
- journalLineReference = nanoid();
-
- // Credit the sales account
- journalLineInserts.push({
- accountId: accountDefaults.data.salesAccount,
- description: "Sales Account",
- amount: round(
- credit("revenue", totalLineCostWithWeightedShipping)
- ),
- quantity: round(invoiceLineQuantityInInventoryUnit),
- documentType: "Invoice",
- documentId: salesInvoice.data?.id,
- externalDocumentId: salesInvoice.data?.customerReference,
- documentLineReference: invoiceLine.salesOrderLineId
- ? journalReference.to.salesInvoice(
- invoiceLine.salesOrderLineId
- )
- : null,
- journalLineReference,
- companyId,
- });
-
- // Debit the accounts receivable account
- journalLineInserts.push({
- accountId: receivablesAccountId,
- description: isIntercompany
- ? "IC Receivables"
- : "Accounts Receivable",
- amount: round(debit("asset", totalLineCostWithWeightedShipping)),
- quantity: round(invoiceLineQuantityInInventoryUnit),
- documentType: "Invoice",
- documentId: salesInvoice.data?.id,
- externalDocumentId: salesInvoice.data?.customerReference,
- documentLineReference: invoiceLine.salesOrderLineId
- ? journalReference.to.salesInvoice(
- invoiceLine.salesOrderLineId
- )
- : null,
- journalLineReference,
- intercompanyPartnerId,
- companyId,
- });
-
- const itemPostingGroupId =
- itemCosts.data.find(
- (cost) => cost.itemId === invoiceLine.itemId
- )?.itemPostingGroupId ?? null;
-
- for (let i = 0; i < 2; i++) {
- journalLineDimensionsMeta.push({
- customerTypeId: customer.data.customerTypeId ?? null,
- itemPostingGroupId,
- itemId: invoiceLine.itemId ?? null,
- locationId: invoiceLine.locationId ?? null,
- costCenterId: null,
- fixedAssetClassId: null,
- });
- }
- }
}
+ // Sales-order and Make-to-Order lines retain shipment-owned COGS;
+ // their charge rows were constructed through the same path above.
}
break;
case "Fixed Asset": {
- // Silently skipping would post less to AR than the invoice
- // total the payment flow is allowed to apply against.
- if (accountingEnabled && !invoiceLine.assetId) {
- throw new Error(
- `Fixed Asset invoice line ${invoiceLine.id} has no asset selected`
- );
+ if (!accountingEnabled) break;
+ if (!invoiceLine.assetId) throw new Error(`Fixed Asset invoice line ${invoiceLine.id} has no asset selected`);
+ const asset = assetsById.get(invoiceLine.assetId);
+ const assetClass = asset?.fixedAssetClass;
+ if (!asset || !assetClass) throw new Error(`Failed to fetch fixed asset/class ${invoiceLine.assetId}`);
+ const salesOrderLine = salesOrderLines.find((line: Database["public"]["Tables"]["salesOrderLine"]["Row"]) => line.id === invoiceLine.salesOrderLineId);
+ const wasShipped = salesOrderLine?.sentComplete === true && !!invoiceLine.salesOrderLineId;
+ const disposal = wasShipped ? latestDisposalByAsset.get(invoiceLine.assetId) : undefined;
+ if (wasShipped && !disposal) {
+ throw new Error(`No disposal record found for asset ${invoiceLine.assetId} — shipment must create it before invoice posting`);
}
- if (accountingEnabled && accountDefaults?.data && invoiceLine.assetId) {
- const salesOrderLine = salesOrderLines?.find(
- (sol) => sol.id === invoiceLine.salesOrderLineId
- );
- const wasShipped = salesOrderLine?.sentComplete === true;
- const saleProceeds = totalLineCostWithWeightedShipping;
-
- if (wasShipped && invoiceLine.salesOrderLineId) {
- // Shipment already removed the asset and parked its NBV in the
- // disposal clearing account (writeOffAccountId). Here we book
- // AR, clear the holding account back to zero, and recognize the
- // explicit gain/loss on the matching Gain/Loss on Disposal account.
- const assetRecord = await client
- .from("fixedAsset")
- .select(
- "locationId, fixedAssetClassId, fixedAssetClass:fixedAssetClassId(id, writeOffAccountId, gainOnDisposalAccountId, lossOnDisposalAccountId)"
- )
- .eq("id", invoiceLine.assetId)
- .eq("companyId", companyId)
- .single();
-
- if (assetRecord.error)
- throw new Error("Failed to fetch fixed asset");
-
- const assetClass = assetRecord.data.fixedAssetClass as any;
- const writeOffAccountId = assetClass.writeOffAccountId;
- const gainOnDisposalAccountId =
- assetClass.gainOnDisposalAccountId;
- const lossOnDisposalAccountId =
- assetClass.lossOnDisposalAccountId;
-
- // NBV was recorded on the disposal row at shipment. The
- // shipment must have created it; if it is missing the ledger
- // would be left unbalanced, so abort rather than guess.
- const disposal = await client
- .from("fixedAssetDisposal")
- .select("id, netBookValueAtDisposal")
- .eq("fixedAssetId", invoiceLine.assetId)
- .eq("companyId", companyId)
- .order("createdAt", { ascending: false })
- .limit(1)
- .single();
-
- if (disposal.error || !disposal.data) {
- throw new Error(
- `No disposal record found for asset ${invoiceLine.assetId} — shipment must create the disposal record before invoice posting`
- );
- }
-
- const nbv = Number(disposal.data.netBookValueAtDisposal);
- const gainLoss = saleProceeds - nbv;
-
- const arJournalLineReference = nanoid();
-
- journalLineInserts.push({
- accountId: receivablesAccountId,
- description: "Accounts Receivable",
- amount: round(debit("asset", saleProceeds)),
- quantity: round(invoiceLineQuantityInInventoryUnit),
- documentType: "Invoice",
- documentId: salesInvoice.data?.id ?? undefined,
- externalDocumentId:
- salesInvoice.data?.customerReference ?? undefined,
- documentLineReference: journalReference.to.salesInvoice(
- invoiceLine.salesOrderLineId
- ),
- journalLineReference: arJournalLineReference,
- intercompanyPartnerId,
- companyId,
- });
-
- // Clear the disposal clearing account back to zero (credit the
- // NBV that was debited there at shipment).
- journalLineInserts.push({
- accountId: writeOffAccountId,
- description: "Clear disposal clearing",
- amount: round(credit("expense", nbv)),
- quantity: round(invoiceLineQuantityInInventoryUnit),
- documentType: "Invoice",
- documentId: salesInvoice.data?.id ?? undefined,
- externalDocumentId:
- salesInvoice.data?.customerReference ?? undefined,
- documentLineReference: journalReference.to.salesInvoice(
- invoiceLine.salesOrderLineId
- ),
- journalLineReference: arJournalLineReference,
- companyId,
- });
-
- for (let i = 0; i < 2; i++) {
- journalLineDimensionsMeta.push({
- customerTypeId: customer.data.customerTypeId ?? null,
- itemPostingGroupId: null,
- itemId: null,
- locationId: invoiceLine.locationId ?? salesOrderLine?.locationId ?? assetRecord.data.locationId ?? null,
- costCenterId: null,
- fixedAssetClassId: assetClass?.id ?? null,
- });
- }
-
- // Recognize the explicit gain (credit) or loss (debit) on the
- // matching non-operating account: gains to the Gain on Disposal
- // account, losses to the Loss on Disposal account.
- if (gainLoss !== 0) {
- journalLineInserts.push({
- accountId:
- gainLoss > 0
- ? gainOnDisposalAccountId
- : lossOnDisposalAccountId,
- description:
- gainLoss > 0 ? "Gain on disposal" : "Loss on disposal",
- amount:
- gainLoss > 0
- ? round(credit("revenue", gainLoss))
- : round(debit("expense", -gainLoss)),
- quantity: round(invoiceLineQuantityInInventoryUnit),
- documentType: "Invoice",
- documentId: salesInvoice.data?.id ?? undefined,
- externalDocumentId:
- salesInvoice.data?.customerReference ?? undefined,
- documentLineReference: journalReference.to.salesInvoice(
- invoiceLine.salesOrderLineId
- ),
- journalLineReference: arJournalLineReference,
- companyId,
- });
-
- journalLineDimensionsMeta.push({
- customerTypeId: customer.data.customerTypeId ?? null,
- itemPostingGroupId: null,
- itemId: null,
- locationId: invoiceLine.locationId ?? salesOrderLine?.locationId ?? assetRecord.data.locationId ?? null,
- costCenterId: null,
- fixedAssetClassId: assetClass?.id ?? null,
- });
- }
-
- // Defer the fixedAssetDisposal + fixedAsset writes so they run
- // inside the same transaction as the journal posting (below).
- fixedAssetDisposalUpdates.push({
- disposalId: disposal.data.id,
- assetId: invoiceLine.assetId,
- saleProceeds,
- gainLoss,
- });
- } else {
- // Direct invoice (no prior shipment) — combined single-step
- // disposal: remove the asset + its accumulated depreciation,
- // book AR for proceeds, and recognize the explicit gain/loss on
- // the matching Gain/Loss on Disposal account. No NBV write-off
- // is comingled with proceeds.
- const assetRecord = await client
- .from("fixedAsset")
- .select(
- "id, status, acquisitionCost, accumulatedDepreciation, locationId, fixedAssetClass:fixedAssetClassId(id, assetAccountId, accumulatedDepreciationAccountId, gainOnDisposalAccountId, lossOnDisposalAccountId)"
- )
- .eq("id", invoiceLine.assetId)
- .eq("companyId", companyId)
- .single();
-
- if (assetRecord.error)
- throw new Error(
- "Failed to fetch fixed asset for disposal"
- );
-
- const assetClass =
- assetRecord.data.fixedAssetClass as any;
- const acquisitionCost =
- Number(assetRecord.data.acquisitionCost) ?? 0;
- const accumulatedDepreciation =
- Number(assetRecord.data.accumulatedDepreciation) ?? 0;
- const nbv = acquisitionCost - accumulatedDepreciation;
- const gainLoss = saleProceeds - nbv;
-
- const disposalDimensionMeta = () => ({
- customerTypeId: customer.data.customerTypeId ?? null,
- itemPostingGroupId: null,
- itemId: null,
- locationId:
- invoiceLine.locationId ??
- salesOrderLine?.locationId ??
- assetRecord.data.locationId ??
- null,
- costCenterId: null,
- fixedAssetClassId: assetClass?.id ?? null,
- });
- const disposalDocumentLineReference =
- invoiceLine.salesOrderLineId
- ? journalReference.to.salesInvoice(
- invoiceLine.salesOrderLineId
- )
- : null;
-
- if (accumulatedDepreciation > 0) {
- journalLineReference = nanoid();
- journalLineInserts.push({
- accountId:
- assetClass.accumulatedDepreciationAccountId,
- description: "Clear accumulated depreciation",
- amount: round(debit("asset", accumulatedDepreciation)),
- quantity: 1,
- documentType: "Invoice",
- documentId: salesInvoice.data?.id ?? undefined,
- externalDocumentId:
- salesInvoice.data?.customerReference ?? undefined,
- documentLineReference: disposalDocumentLineReference,
- journalLineReference,
- companyId,
- });
-
- journalLineDimensionsMeta.push(disposalDimensionMeta());
- }
-
- const removeJournalLineReference = nanoid();
- journalLineInserts.push({
- accountId: assetClass.assetAccountId,
- description: "Remove asset at cost",
- amount: round(credit("asset", acquisitionCost)),
- quantity: 1,
- documentType: "Invoice",
- documentId: salesInvoice.data?.id ?? undefined,
- externalDocumentId:
- salesInvoice.data?.customerReference ?? undefined,
- documentLineReference: disposalDocumentLineReference,
- journalLineReference: removeJournalLineReference,
- companyId,
- });
-
- journalLineDimensionsMeta.push(disposalDimensionMeta());
-
- const arJournalLineReference = nanoid();
- journalLineInserts.push({
- accountId: receivablesAccountId,
- description: "Accounts Receivable",
- amount: round(debit("asset", saleProceeds)),
- quantity: round(invoiceLineQuantityInInventoryUnit),
- documentType: "Invoice",
- documentId: salesInvoice.data?.id ?? undefined,
- externalDocumentId:
- salesInvoice.data?.customerReference ?? undefined,
- documentLineReference: disposalDocumentLineReference,
- journalLineReference: arJournalLineReference,
- intercompanyPartnerId,
- companyId,
- });
-
- journalLineDimensionsMeta.push(disposalDimensionMeta());
-
- // Explicit gain (credit) / loss (debit) on the matching
- // non-operating account — Gain on Disposal for a gain, Loss on
- // Disposal for a loss.
- if (gainLoss !== 0) {
- journalLineInserts.push({
- accountId:
- gainLoss > 0
- ? assetClass.gainOnDisposalAccountId
- : assetClass.lossOnDisposalAccountId,
- description:
- gainLoss > 0 ? "Gain on disposal" : "Loss on disposal",
- amount:
- gainLoss > 0
- ? round(credit("revenue", gainLoss))
- : round(debit("expense", -gainLoss)),
- quantity: 1,
- documentType: "Invoice",
- documentId: salesInvoice.data?.id ?? undefined,
- externalDocumentId:
- salesInvoice.data?.customerReference ?? undefined,
- documentLineReference: disposalDocumentLineReference,
- journalLineReference: arJournalLineReference,
- companyId,
- });
-
- journalLineDimensionsMeta.push(disposalDimensionMeta());
- }
-
- await client
- .from("fixedAsset")
- .update({
- status: "Disposed",
- disposalDate: today,
- disposalMethod: "Sale",
- saleProceeds,
- updatedBy: userId,
- })
- .eq("id", invoiceLine.assetId)
- .eq("companyId", companyId);
-
- await client.from("fixedAssetDisposal").insert({
- fixedAssetId: invoiceLine.assetId,
- disposalMethod: "Sale",
- disposalDate: today,
- saleProceeds,
- netBookValueAtDisposal: nbv,
- gainLoss,
- companyId,
- createdBy: userId,
- });
- }
+ const disposalAccounts = {
+ gainAccount: account(assetClass.gainOnDisposalAccountId),
+ lossAccount: account(assetClass.lossOnDisposalAccountId),
+ };
+ const charges = buildSalesPostingLines({
+ line: postingLine, context: postingContext, accounts: chargeAccounts,
+ metadata: {
+ customerTypeId: customer.data.customerTypeId ?? null,
+ itemPostingGroupId: null, itemId: null,
+ locationId: invoiceLine.locationId ?? salesOrderLine?.locationId ?? asset.locationId ?? null,
+ costCenterId: null, fixedAssetClassId: assetClass.id,
+ },
+ disposal: wasShipped && disposal ? {
+ mode: "shipment", netBookValue: Number(disposal.netBookValueAtDisposal),
+ clearingAccount: account(assetClass.writeOffAccountId), ...disposalAccounts,
+ } : {
+ mode: "direct", acquisitionCost: Number(asset.acquisitionCost),
+ accumulatedDepreciation: Number(asset.accumulatedDepreciation),
+ assetAccount: account(assetClass.assetAccountId),
+ accumulatedDepreciationAccount: account(assetClass.accumulatedDepreciationAccountId),
+ ...disposalAccounts,
+ },
+ });
+ journalLineInserts.push(...charges.lines);
+ journalLineDimensionsMeta.push(...charges.metadata);
+ if (charges.netBookValue === null || charges.gainLoss === null) {
+ throw new Error("Fixed asset disposal posting is missing carrying values");
+ }
+ if (wasShipped && disposal) {
+ fixedAssetDisposalUpdates.push({
+ disposalId: disposal.id, assetId: invoiceLine.assetId,
+ saleProceeds: charges.saleProceeds, gainLoss: charges.gainLoss,
+ });
+ } else {
+ directAssetDisposals.push({
+ assetId: invoiceLine.assetId, saleProceeds: charges.saleProceeds,
+ netBookValue: charges.netBookValue, gainLoss: charges.gainLoss,
+ });
}
break;
}
@@ -1102,7 +789,7 @@ serve(async (req: Request) => {
companyId,
sourceType: "Sales Invoice",
status: "Posted",
- postedAt: new Date().toISOString(),
+ postedAt: datetime.timestamp(),
postedBy: userId,
createdBy: userId,
})
@@ -1221,34 +908,22 @@ serve(async (req: Request) => {
// Create intercompany transaction record if IC
if (accountingEnabled && isIntercompany && intercompanyPartnerId) {
- // 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 cogsAccount = accountDefaults?.data?.costOfGoodsSoldAccount;
+ const classifiedLines = classifyIntercompanyPostingLines(
+ journalLineInserts.map((line, index) => ({ ...line, id: journalLineResults[index]?.id ?? "" })),
+ journalLineDimensionsMeta,
+ {
+ controlAccountId: receivablesAccountId,
+ revenueAccountIds: [accountDefaults?.data?.salesAccount, accountDefaults?.data?.salesShippingRevenueAccount]
+ .filter((id): id is string => !!id),
+ cogsAccountId: cogsAccount,
+ }
);
- 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
+ // Keep the first control as the existing matching anchor, but capture
+ // every emitted control line so multiline balances eliminate fully.
+ const icJournalLineId = classifiedLines.find((line) => line.role === "Control")?.journalLineId;
+ const intercompanyAmount = calculateSalesIntercompanyAmount(
+ salesInvoiceLines.data, invoiceExchangeRate
);
if (icJournalLineId) {
@@ -1259,8 +934,8 @@ serve(async (req: Request) => {
sourceCompanyId: companyId,
targetCompanyId: intercompanyPartnerId,
sourceJournalLineId: icJournalLineId,
- amount: round(intercompanyAmount),
- currencyCode: salesInvoice.data?.currencyCode ?? "USD",
+ amount: intercompanyAmount,
+ currencyCode: invoiceCurrencyCode,
description: `Sales Invoice ${salesInvoice.data?.invoiceId}`,
documentType: "Invoice",
documentId: salesInvoice.data?.id,
@@ -1269,38 +944,10 @@ serve(async (req: Request) => {
.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,
- });
- });
+ classifiedLines.map((line) => ({
+ ...line, companyId, intercompanyTransactionId: icTxn.id, createdBy: userId,
+ }));
// Sales-order-based sales post COGS at SHIPMENT (a prior posting),
// not on this invoice, so it is not in journalLineInserts. Capture
@@ -1355,28 +1002,34 @@ serve(async (req: Request) => {
}
}
- // Apply deferred fixed-asset disposal writes inside the transaction so
- // any failure rolls back the journals posted above.
- for (const upd of fixedAssetDisposalUpdates) {
- await trx
- .updateTable("fixedAssetDisposal")
- .set({
- saleProceeds: upd.saleProceeds,
- gainLoss: upd.gainLoss,
- })
- .where("id", "=", upd.disposalId)
- .where("companyId", "=", companyId)
- .execute();
-
- await trx
- .updateTable("fixedAsset")
- .set({
- saleProceeds: upd.saleProceeds,
- updatedBy: userId,
- })
- .where("id", "=", upd.assetId)
- .where("companyId", "=", companyId)
- .execute();
+ // All disposal state changes share the journal transaction. Batch
+ // monetary enrichment separately from direct-disposal lifecycle changes.
+ const assetProceeds = new Map([
+ ...directAssetDisposals.map((entry) => [entry.assetId, entry.saleProceeds] as const),
+ ...fixedAssetDisposalUpdates.map((entry) => [entry.assetId, entry.saleProceeds] as const),
+ ]);
+ if (assetProceeds.size > 0) {
+ await trx.updateTable("fixedAsset").set({
+ saleProceeds: sql<number>`CASE "id" ${sql.join([...assetProceeds].map(([id, proceeds]) => sql`WHEN ${id} THEN ${proceeds}::numeric`), sql` `)} ELSE "saleProceeds" END`,
+ updatedBy: userId,
+ }).where("id", "in", [...assetProceeds.keys()]).where("companyId", "=", companyId).execute();
+ }
+ if (fixedAssetDisposalUpdates.length > 0) {
+ const updates = [...new Map(fixedAssetDisposalUpdates.map((entry) => [entry.disposalId, entry])).values()];
+ await trx.updateTable("fixedAssetDisposal").set({
+ saleProceeds: sql<number>`CASE "id" ${sql.join(updates.map((entry) => sql`WHEN ${entry.disposalId} THEN ${entry.saleProceeds}::numeric`), sql` `)} ELSE "saleProceeds" END`,
+ gainLoss: sql<number>`CASE "id" ${sql.join(updates.map((entry) => sql`WHEN ${entry.disposalId} THEN ${entry.gainLoss}::numeric`), sql` `)} ELSE "gainLoss" END`,
+ }).where("id", "in", updates.map((entry) => entry.disposalId)).where("companyId", "=", companyId).execute();
+ }
+ if (directAssetDisposals.length > 0) {
+ await trx.updateTable("fixedAsset").set({
+ status: "Disposed", disposalDate: today, disposalMethod: "Sale", updatedBy: userId,
+ }).where("id", "in", directAssetDisposals.map((entry) => entry.assetId)).where("companyId", "=", companyId).execute();
+ await trx.insertInto("fixedAssetDisposal").values(directAssetDisposals.map((entry) => ({
+ fixedAssetId: entry.assetId, disposalMethod: "Sale" as const, disposalDate: today,
+ saleProceeds: entry.saleProceeds, netBookValueAtDisposal: entry.netBookValue,
+ gainLoss: entry.gainLoss, companyId, createdBy: userId,
+ }))).execute();
}
// Posting stamps dateIssued with today, so recompute dateDue from
@@ -1617,7 +1270,7 @@ serve(async (req: Request) => {
companyId,
sourceType: "Sales Invoice",
status: "Posted",
- postedAt: new Date().toISOString(),
+ postedAt: datetime.timestamp(),
postedBy: userId,
createdBy: userId,
})
diff --git a/packages/database/supabase/functions/seed-company/index.ts b/packages/database/supabase/functions/seed-company/index.ts
index d5e680d6b3..d484fbadd2 100644
--- a/packages/database/supabase/functions/seed-company/index.ts
+++ b/packages/database/supabase/functions/seed-company/index.ts
@@ -26,6 +26,7 @@ import {
} from "../lib/seed.ts";
import { getSupabaseServiceRole } from "../lib/supabase.ts";
import { Database } from "../lib/types.ts";
+import { resolveShippingDefault } from "./shipping-default.ts";
const pool = getConnectionPool(1);
const db = getDatabaseClient<DB>(pool);
@@ -368,15 +369,29 @@ serve(async (req: Request) => {
// For subsidiaries joining an existing group, look up account IDs by number
const existingAccounts = await trx
.selectFrom("account")
- .select(["id", "number"])
+ .select(["id", "number", "name", "companyGroupId", "active", "isGroup", "class", "incomeBalance", "accountType", "consolidatedRate", "parentId"])
.where("companyGroupId", "=", companyGroupId!)
- .where("number", "is not", null)
.execute();
for (const acc of existingAccounts) {
if (acc.number) {
accountIdByKey[acc.number] = acc.id;
}
}
+ const parentDefaults = parentCompanyId
+ ? await trx.selectFrom("accountDefault")
+ .innerJoin("company", "company.id", "accountDefault.companyId")
+ .select(["accountDefault.salesShippingRevenueAccount", "accountDefault.salesAccount"])
+ .where("accountDefault.companyId", "=", parentCompanyId)
+ .where("company.companyGroupId", "=", companyGroupId!)
+ .executeTakeFirst()
+ : undefined;
+ const parentDefaultId = parentDefaults?.salesShippingRevenueAccount;
+ accountIdByKey["4050"] = resolveShippingDefault({
+ parentDefaultId: parentDefaultId && parentDefaultId !== parentDefaults?.salesAccount
+ ? parentDefaultId : null,
+ accounts: existingAccounts.filter((account) => account.id !== accountIdByKey["4010"]),
+ companyGroupId: companyGroupId!
+ });
}
// Resolve account numbers to IDs for account defaults
diff --git a/packages/database/supabase/functions/seed-company/shipping-default.test.ts b/packages/database/supabase/functions/seed-company/shipping-default.test.ts
new file mode 100644
index 0000000000..5916c066fc
--- /dev/null
+++ b/packages/database/supabase/functions/seed-company/shipping-default.test.ts
@@ -0,0 +1,56 @@
+import { assertEquals, assertThrows } from "https://deno.land/[email protected]/testing/asserts.ts";
+import { accountDefaults, accounts as seedAccounts } from "../lib/seed.data.ts";
+import { resolveShippingDefault } from "./shipping-default.ts";
+
+const parent = {
+ id: "revenue", name: "Revenue", companyGroupId: "group", active: true,
+ isGroup: true, class: "Revenue" as const, incomeBalance: "Income Statement" as const,
+ accountType: "Income" as const, consolidatedRate: "Average" as const, parentId: null
+};
+const shipping = { ...parent, id: "custom-shipping", name: "Shipping Revenue", isGroup: false, parentId: parent.id };
+const resolve = (accounts = [parent, shipping], parentDefaultId: string | null = null) =>
+ resolveShippingDefault({ accounts, parentDefaultId, companyGroupId: "group" });
+
+Deno.test("new company seeds a separate Shipping Revenue account under Revenue", () => {
+ // 4050, not 4040: 4040 is "Customer Payment Discounts" (#1600), which the
+ // 20260909014032 migration renumbers 7030 into. Claiming 4040 here would
+ // silently suppress that guarded renumber for every company.
+ const account = seedAccounts.find((a) => String(a.name) === "Shipping Revenue");
+ assertEquals<unknown>(account, {
+ key: "4050", number: "4050", name: "Shipping Revenue", isGroup: false,
+ parentKey: "revenue", accountType: "Income", incomeBalance: "Income Statement",
+ class: "Revenue", consolidatedRate: "Average", createdBy: "system"
+ });
+ assertEquals((accountDefaults as Record<string, string>).salesShippingRevenueAccount, "4050");
+});
+
+Deno.test("existing company group resolves a semantic leaf without assuming number4040", () => {
+ assertEquals(resolve(), "custom-shipping");
+});
+
+Deno.test("valid parent mapping wins even with a custom name and another semantic leaf", () => {
+ const custom = { ...shipping, id: "parent-choice", name: "Delivery Income" };
+ assertEquals(resolve([parent, shipping, custom], custom.id), custom.id);
+});
+
+Deno.test("invalid parent mapping falls back only to the unique compatible semantic leaf", () => {
+ assertEquals(resolve([parent, shipping], "missing"), shipping.id);
+ const foreign = { ...shipping, id: "foreign", companyGroupId: "other" };
+ assertEquals(resolve([parent, shipping, foreign], foreign.id), shipping.id);
+});
+
+Deno.test("ambiguous or missing semantic defaults fail rather than choosing Sales or number4040", () => {
+ assertThrows(() => resolve([parent, { ...shipping, name: "Sales" }]), Error, "Shipping Revenue");
+ assertThrows(() => resolve([parent, shipping, { ...shipping, id: "second" }]), Error, "Shipping Revenue");
+});
+
+Deno.test("inactive, group, cross-group, and incompatible semantic leaves are rejected", () => {
+ for (const invalid of [
+ { active: false }, { isGroup: true }, { companyGroupId: "other" },
+ { class: "Expense" as const }, { incomeBalance: "Balance Sheet" as const },
+ { accountType: "Other Income" as const }, { consolidatedRate: "Current" as const },
+ { parentId: "missing" }
+ ]) {
+ assertThrows(() => resolveShippingDefault({ accounts: [parent, { ...shipping, ...invalid }], parentDefaultId: null, companyGroupId: "group" }), Error, "Shipping Revenue");
+ }
+});
diff --git a/packages/database/supabase/functions/seed-company/shipping-default.ts b/packages/database/supabase/functions/seed-company/shipping-default.ts
new file mode 100644
index 0000000000..966d379bf0
--- /dev/null
+++ b/packages/database/supabase/functions/seed-company/shipping-default.ts
@@ -0,0 +1,30 @@
+import type { Database } from "../lib/types.ts";
+
+type Account = Pick<Database["public"]["Tables"]["account"]["Row"],
+ "id" | "name" | "companyGroupId" | "active" | "isGroup" | "class" | "incomeBalance" | "accountType" | "consolidatedRate" | "parentId">;
+
+export function resolveShippingDefault({ parentDefaultId, accounts, companyGroupId }: {
+ parentDefaultId: string | null;
+ accounts: readonly Account[];
+ companyGroupId: string;
+}): string {
+ const eligible = (account: Account) => account.companyGroupId === companyGroupId &&
+ account.active === true && account.isGroup === false &&
+ account.class === "Revenue" && account.incomeBalance === "Income Statement";
+ const mapped = accounts.find((account) => account.id === parentDefaultId);
+ if (mapped && eligible(mapped)) return mapped.id;
+
+ const byId = new Map(accounts.map((account) => [account.id, account]));
+ const candidates = accounts.filter((account) => {
+ const parent = account.parentId ? byId.get(account.parentId) : undefined;
+ return eligible(account) && account.name === "Shipping Revenue" &&
+ account.accountType === "Income" && account.consolidatedRate === "Average" &&
+ parent?.companyGroupId === companyGroupId && parent.active === true &&
+ parent.isGroup === true && parent.class === "Revenue" &&
+ parent.accountType === "Income" && parent.incomeBalance === "Income Statement";
+ });
+ if (candidates.length !== 1) {
+ throw new Error("A unique compatible Shipping Revenue default is required for this company group");
+ }
+ return candidates[0].id;
+}
diff --git a/packages/database/supabase/functions/shared/accounting-currency.test.ts b/packages/database/supabase/functions/shared/accounting-currency.test.ts
new file mode 100644
index 0000000000..e785d7f01c
--- /dev/null
+++ b/packages/database/supabase/functions/shared/accounting-currency.test.ts
@@ -0,0 +1,99 @@
+import {
+ assertEquals,
+ assertThrows
+} from "https://deno.land/[email protected]/testing/asserts.ts";
+import {
+ calculateSettlementFx,
+ toBaseAmount,
+ toDocumentAmount
+} from "./accounting-currency.ts";
+
+Deno.test("foreign-per-base conversion divides documents and multiplies base at any rate magnitude", () => {
+ assertEquals(toBaseAmount(110, 1.1), 100);
+ assertEquals(toBaseAmount(120.8, 0.8), 151);
+ assertEquals(toDocumentAmount(100, 1.1, 2), 110);
+ assertEquals(toDocumentAmount(151, 0.8, 2), 120.8);
+});
+
+Deno.test("base conversion preserves internal precision and rounds signed ties away from zero", () => {
+ assertEquals(toBaseAmount(1, 3), 0.33333);
+ assertEquals(toBaseAmount(0.000005, 1), 0.00001);
+ assertEquals(toBaseAmount(-0.000005, 1), -0.00001);
+ assertEquals(toBaseAmount(-110, 1.1), -100);
+});
+
+Deno.test("document boundaries respect configured zero, two, three, and four decimals", () => {
+ assertEquals(toDocumentAmount(1.005, 1, 2), 1.01);
+ assertEquals(toDocumentAmount(-1.005, 1, 2), -1.01);
+ assertEquals(toDocumentAmount(12.5, 1, 0), 13);
+ assertEquals(toDocumentAmount(12.3455, 1, 3), 12.346);
+ assertEquals(toDocumentAmount(12.34555, 1, 4), 12.3456);
+});
+
+Deno.test("160.01 at rate16000 cannot be recovered from rounded carrying base", () => {
+ const carryingBase = toBaseAmount(160.01, 16000);
+ assertEquals(carryingBase, 0.01);
+ assertEquals(toDocumentAmount(carryingBase, 16000, 2), 160);
+ assertEquals(toBaseAmount(0.01, 16000), 0);
+});
+
+Deno.test("memo and fee conversion keeps 55 credit and 3.30 fee at base50 and base3", () => {
+ assertEquals(toBaseAmount(55, 1.1), 50);
+ assertEquals(toBaseAmount(3.3, 1.1), 3);
+ assertEquals(toBaseAmount(110, 1.1) - toBaseAmount(3.3, 1.1), 97);
+});
+
+for (const rate of [0, -1, Number.NaN, Number.POSITIVE_INFINITY, Number.NEGATIVE_INFINITY]) {
+ Deno.test(`currency conversion rejects invalid rate ${rate}`, () => {
+ assertThrows(() => toBaseAmount(100, rate), Error, "rate");
+ assertThrows(() => toDocumentAmount(100, rate, 2), Error, "rate");
+ assertThrows(() => calculateSettlementFx({ appliedAmount: 100, sourceAmount: 110, sourceExchangeRate: rate, isAR: true }), Error, "rate");
+ });
+}
+
+Deno.test("currency conversion refuses nonfinite amounts, unsupported precision, and overflow", () => {
+ for (const amount of [Number.NaN, Number.POSITIVE_INFINITY, Number.NEGATIVE_INFINITY]) {
+ assertThrows(() => toBaseAmount(amount, 1));
+ assertThrows(() => toDocumentAmount(amount, 1, 2));
+ }
+ for (const decimals of [-1, 1.5, Number.NaN, Number.POSITIVE_INFINITY]) {
+ assertThrows(() => toDocumentAmount(1, 1, decimals), Error, "decimal");
+ }
+ assertThrows(() => toBaseAmount(Number.MAX_VALUE, Number.MIN_VALUE));
+ assertThrows(() => toDocumentAmount(Number.MAX_VALUE, Number.MAX_VALUE, 2));
+});
+
+Deno.test("realized FX compares target carrying principal with source cash and reverses AR/AP signs", () => {
+ const cases = [
+ { sourceExchangeRate: 1.1, gain: 0 },
+ { sourceExchangeRate: 1, gain: 10 },
+ { sourceExchangeRate: 1.25, gain: -12 }
+ ];
+ for (const { sourceExchangeRate, gain } of cases) {
+ const input = { appliedAmount: 100, sourceAmount: 110, sourceExchangeRate };
+ assertEquals(calculateSettlementFx({ ...input, isAR: true }), gain);
+ assertEquals(calculateSettlementFx({ ...input, isAR: false }), gain === 0 ? 0 : -gain);
+ }
+ assertEquals(calculateSettlementFx({ appliedAmount: 80, sourceAmount: 88, sourceExchangeRate: 1, isAR: true }), 8);
+ assertEquals(calculateSettlementFx({ appliedAmount: 88, sourceAmount: 110, sourceExchangeRate: 1.1, isAR: true }), 12);
+});
+
+Deno.test("realized FX rounds once at internal precision, preserving tiny source-only applications", () => {
+ assertEquals(calculateSettlementFx({ appliedAmount: 100, sourceAmount: 110, sourceExchangeRate: 1.15, isAR: true }), -4.34783);
+ assertEquals(calculateSettlementFx({ appliedAmount: 100, sourceAmount: 120, sourceExchangeRate: 1.15, isAR: true }), 4.34783);
+ assertEquals(calculateSettlementFx({ appliedAmount: 0, sourceAmount: 0.01, sourceExchangeRate: 16000, isAR: true }), 0);
+});
+
+Deno.test("realized FX rejects negative and nonfinite principal inputs", () => {
+ for (const invalid of [-1, Number.NaN, Number.POSITIVE_INFINITY]) {
+ assertThrows(() => calculateSettlementFx({ appliedAmount: invalid, sourceAmount: 1, sourceExchangeRate: 1, isAR: true }));
+ assertThrows(() => calculateSettlementFx({ appliedAmount: 1, sourceAmount: invalid, sourceExchangeRate: 1, isAR: true }));
+ assertThrows(() => calculateSettlementFx({ appliedAmount: 1, sourceAmount: 1, sourceExchangeRate: 1, sourceBaseAmount: invalid, isAR: true }));
+ }
+});
+
+Deno.test("recorded source carrying residual governs FX on its final allocation", () => {
+ const input = { appliedAmount: 0.33333, sourceAmount: 1, sourceExchangeRate: 3, sourceBaseAmount: 0.33334 };
+ assertEquals(calculateSettlementFx({ ...input, isAR: true }), 0.00001);
+ assertEquals(calculateSettlementFx({ ...input, isAR: false }), -0.00001);
+});
diff --git a/packages/database/supabase/functions/shared/accounting-currency.ts b/packages/database/supabase/functions/shared/accounting-currency.ts
new file mode 100644
index 0000000000..d553b8c547
--- /dev/null
+++ b/packages/database/supabase/functions/shared/accounting-currency.ts
@@ -0,0 +1,88 @@
+import { round } from "./precision.ts";
+
+function requireFinite(amount: number, label: string): number {
+ if (!Number.isFinite(amount)) {
+ throw new Error(`${label} must be finite`);
+ }
+ return amount;
+}
+
+/** Refuse an unusable foreign-per-base rate.
+ *
+ * Exported so callers that only need the CHECK can say so. The alternative
+ * spelling — `toBaseAmount(0, rate)` with the result thrown away — reads as
+ * dead code to every reader, linter and dead-code pass, so deleting it looks
+ * free while silently removing rate validation from a posting path. */
+export function assertExchangeRate(rate: number): void {
+ requireRate(rate);
+}
+
+function requireRate(rate: number): void {
+ if (!Number.isFinite(rate) || rate <= 0) {
+ throw new Error("Foreign-per-base exchange rate must be positive and finite");
+ }
+}
+
+/** Refuse a currency precision that cannot describe a settlement amount.
+ * Exported for the same reason as `assertExchangeRate`. */
+export function assertCurrencyDecimals(currencyDecimals: number): void {
+ requireCurrencyDecimals(currencyDecimals);
+}
+
+function requireCurrencyDecimals(currencyDecimals: number): void {
+ if (!Number.isSafeInteger(currencyDecimals) || currencyDecimals < 0) {
+ throw new Error("Currency decimal places must be a nonnegative integer");
+ }
+}
+
+/** Persist a document-currency amount as company-base carrying value. */
+export function toBaseAmount(
+ documentAmount: number,
+ foreignPerBaseRate: number
+): number {
+ requireFinite(documentAmount, "Document amount");
+ requireRate(foreignPerBaseRate);
+ return requireFinite(round(documentAmount / foreignPerBaseRate), "Base amount");
+}
+
+/** Round at the document boundary using that currency's configured decimals. */
+export function toDocumentAmount(
+ baseAmount: number,
+ foreignPerBaseRate: number,
+ currencyDecimals: number
+): number {
+ requireFinite(baseAmount, "Base amount");
+ requireRate(foreignPerBaseRate);
+ requireCurrencyDecimals(currencyDecimals);
+ return requireFinite(
+ round(baseAmount * foreignPerBaseRate, currencyDecimals),
+ "Document amount"
+ );
+}
+
+/** Positive means realized gain for either AR or AP. Relief amounts carry no FX. */
+export function calculateSettlementFx(input: {
+ appliedAmount: number;
+ sourceAmount: number;
+ sourceExchangeRate: number;
+ isAR: boolean;
+ /** Actual released carrying value, including the source's final rounding residual. */
+ sourceBaseAmount?: number;
+}): number {
+ requireRate(input.sourceExchangeRate);
+ requireFinite(input.appliedAmount, "Applied amount");
+ requireFinite(input.sourceAmount, "Source amount");
+ const sourceBase = requireFinite(
+ input.sourceBaseAmount ?? input.sourceAmount / input.sourceExchangeRate,
+ "Source base amount"
+ );
+ if (input.appliedAmount < 0 || input.sourceAmount < 0 || sourceBase < 0) {
+ throw new Error("Settlement principal amounts must be nonnegative");
+ }
+ const fx = round(
+ input.isAR
+ ? sourceBase - input.appliedAmount
+ : input.appliedAmount - sourceBase
+ );
+ return fx === 0 ? 0 : requireFinite(fx, "Settlement FX amount");
+}
diff --git a/packages/database/supabase/functions/shared/accounting-posting.test.ts b/packages/database/supabase/functions/shared/accounting-posting.test.ts
new file mode 100644
index 0000000000..7ad52b6107
--- /dev/null
+++ b/packages/database/supabase/functions/shared/accounting-posting.test.ts
@@ -0,0 +1,16 @@
+import { assertEquals } from "https://deno.land/[email protected]/testing/asserts.ts";
+import { classifyAccountingPostingRole } from "./accounting-posting.ts";
+
+Deno.test("original invoice posting roles include intercompany controls and exclude void reversals", () => {
+ for (const description of ["Accounts Receivable", "IC Receivables"]) {
+ assertEquals(classifyAccountingPostingRole(description), "Receivables");
+ }
+ for (const description of ["Accounts Payable", "IC Payables"]) {
+ assertEquals(classifyAccountingPostingRole(description), "Payables");
+ }
+ assertEquals(classifyAccountingPostingRole("Shipping Revenue"), "ShippingRevenue");
+ assertEquals(classifyAccountingPostingRole("Sales Account"), "SalesRevenue");
+ for (const description of [null, "Revenue", "VOID: Accounts Receivable", "VOID: IC Payables", "Tax", "Shipping expense"]) {
+ assertEquals(classifyAccountingPostingRole(description), null);
+ }
+});
diff --git a/packages/database/supabase/functions/shared/accounting-posting.ts b/packages/database/supabase/functions/shared/accounting-posting.ts
new file mode 100644
index 0000000000..af738d22f1
--- /dev/null
+++ b/packages/database/supabase/functions/shared/accounting-posting.ts
@@ -0,0 +1,36 @@
+export const RECEIVABLE_POSTING_DESCRIPTIONS = ["Accounts Receivable", "IC Receivables"] as const;
+export const PAYABLE_POSTING_DESCRIPTIONS = ["Accounts Payable", "IC Payables"] as const;
+
+/** The description a payment's NEW on-account credit control line is written
+ * with, and the exact string a later payment reads back to find which account
+ * that credit was originally booked to.
+ *
+ * The writer (build-payment-journal) and the reader (post-payment-transaction)
+ * MUST agree character for character: on a mismatch the lookup returns nothing
+ * and the consuming payment silently falls back to today's default control
+ * account, so a credit booked to intercompany receivables is drawn against
+ * regular receivables instead — the original account stays credited forever
+ * and the default one goes negative, with no error anywhere. */
+export function onAccountCreditDescription(isAR: boolean): string {
+ return `${isAR ? "Accounts Receivable" : "Accounts Payable"} (on-account credit)`;
+}
+
+export type AccountingPostingRole = "Receivables" | "Payables" | "ShippingRevenue" | "SalesRevenue";
+
+/** Roles come from the original journal, never a mutable account name or default. */
+export function classifyAccountingPostingRole(description: string | null): AccountingPostingRole | null {
+ switch (description) {
+ case "Accounts Receivable":
+ case "IC Receivables":
+ return "Receivables";
+ case "Accounts Payable":
+ case "IC Payables":
+ return "Payables";
+ case "Shipping Revenue":
+ return "ShippingRevenue";
+ case "Sales Account":
+ return "SalesRevenue";
+ default:
+ return null;
+ }
+}
diff --git a/packages/database/supabase/functions/shared/intercompany-capture.test.ts b/packages/database/supabase/functions/shared/intercompany-capture.test.ts
new file mode 100644
index 0000000000..80a4b62b34
--- /dev/null
+++ b/packages/database/supabase/functions/shared/intercompany-capture.test.ts
@@ -0,0 +1,140 @@
+import {
+ assertEquals,
+ assertThrows,
+} from "https://deno.land/[email protected]/testing/asserts.ts";
+import { classifyIntercompanyPostingLines } from "./intercompany-capture.ts";
+
+Deno.test("seller captures every receivable and both sales/shipping revenue with aligned item metadata", () => {
+ const lines = [
+ { id: "sales-1", accountId: "sales", amount: 100, quantity: 2 },
+ { id: "shipping-1", accountId: "shipping", amount: 10, quantity: 2 },
+ { id: "tax-1", accountId: "tax", amount: 11, quantity: 2 },
+ { id: "ar-1", accountId: "ar", amount: 121, quantity: 2 },
+ { id: "cogs-1", accountId: "cogs", amount: 70, quantity: 2 },
+ { id: "inventory-1", accountId: "inventory", amount: -70, quantity: 2 },
+ { id: "sales-2", accountId: "sales", amount: 50, quantity: 1 },
+ { id: "ar-2", accountId: "ar", amount: 50, quantity: 1 },
+ ];
+ const metadata = lines.map((_line, index) => ({
+ itemId: index < 6 ? "item-1" : "item-2",
+ }));
+ const captures = classifyIntercompanyPostingLines(lines, metadata, {
+ controlAccountId: "ar",
+ revenueAccountIds: ["sales", "shipping"],
+ cogsAccountId: "cogs",
+ });
+ assertEquals(
+ captures.map((row) => [row.journalLineId, row.role, row.itemId]),
+ [
+ ["sales-1", "Revenue", "item-1"],
+ ["shipping-1", "Revenue", "item-1"],
+ ["ar-1", "Control", "item-1"],
+ ["cogs-1", "COGS", "item-1"],
+ ["sales-2", "Revenue", "item-2"],
+ ["ar-2", "Control", "item-2"],
+ ],
+ );
+ assertEquals(
+ captures.filter((row) => row.role === "Control").reduce(
+ (sum, row) => sum + row.amount,
+ 0,
+ ),
+ 171,
+ );
+ assertEquals(
+ captures.find((row) => row.role === "Control")?.journalLineId,
+ "ar-1",
+ );
+});
+
+Deno.test("buyer captures both payable rows without classifying asset or GRIR rows as control", () => {
+ const lines = [
+ { id: "asset-1", accountId: "asset", amount: 100, quantity: 2 },
+ { id: "ap-1", accountId: "ap", amount: 110, quantity: 2 },
+ { id: "grir-2", accountId: "grir", amount: -200, quantity: 4 },
+ { id: "ap-2", accountId: "ap", amount: 220, quantity: 4 },
+ ];
+ const captures = classifyIntercompanyPostingLines(lines, [
+ { itemId: "item-1" },
+ { itemId: "item-1" },
+ { itemId: "item-2" },
+ { itemId: "item-2" },
+ ], { controlAccountId: "ap" });
+ assertEquals(captures, [
+ {
+ journalLineId: "ap-1",
+ accountId: "ap",
+ amount: 110,
+ quantity: 2,
+ itemId: "item-1",
+ role: "Control",
+ },
+ {
+ journalLineId: "ap-2",
+ accountId: "ap",
+ amount: 220,
+ quantity: 4,
+ itemId: "item-2",
+ role: "Control",
+ },
+ ]);
+ assertEquals(captures[0]?.journalLineId, "ap-1");
+});
+
+Deno.test("explicit capitalization accounts preserve existing buyer capture without a class guess", () => {
+ assertEquals(
+ classifyIntercompanyPostingLines(
+ [
+ { id: "asset-row", accountId: "asset", amount: 100 },
+ ],
+ [{}],
+ { controlAccountId: "ap", capitalizationAccountIds: ["asset"] },
+ ),
+ [
+ {
+ journalLineId: "asset-row",
+ accountId: "asset",
+ amount: 100,
+ quantity: null,
+ itemId: null,
+ role: "Capitalization",
+ },
+ ],
+ );
+});
+
+Deno.test("capture rejects ambiguous account roles and misaligned returned IDs/metadata", () => {
+ assertThrows(
+ () =>
+ classifyIntercompanyPostingLines([], [], {
+ controlAccountId: "ar",
+ revenueAccountIds: ["ar"],
+ }),
+ Error,
+ "Ambiguous",
+ );
+ assertThrows(
+ () =>
+ classifyIntercompanyPostingLines(
+ [
+ { id: "row", accountId: "ar", amount: 1 },
+ ],
+ [],
+ { controlAccountId: "ar" },
+ ),
+ Error,
+ "metadata",
+ );
+ assertThrows(
+ () =>
+ classifyIntercompanyPostingLines(
+ [
+ { id: "", accountId: "ar", amount: 1 },
+ ],
+ [{}],
+ { controlAccountId: "ar" },
+ ),
+ Error,
+ "journal line",
+ );
+});
diff --git a/packages/database/supabase/functions/shared/intercompany-capture.ts b/packages/database/supabase/functions/shared/intercompany-capture.ts
new file mode 100644
index 0000000000..beacb5f6af
--- /dev/null
+++ b/packages/database/supabase/functions/shared/intercompany-capture.ts
@@ -0,0 +1,71 @@
+export type IntercompanyPostingLine = {
+ id: string;
+ accountId?: string | null;
+ amount?: number | null;
+ quantity?: number | null;
+};
+
+export type IntercompanyPostingRole =
+ | "Control"
+ | "Revenue"
+ | "COGS"
+ | "Capitalization";
+
+export function classifyIntercompanyPostingLines(
+ lines: IntercompanyPostingLine[],
+ metadata: Array<{ itemId?: string | null }>,
+ accounts: {
+ controlAccountId: string | null | undefined;
+ revenueAccountIds?: readonly string[];
+ cogsAccountId?: string | null;
+ capitalizationAccountIds?: readonly string[];
+ },
+): Array<{
+ journalLineId: string;
+ accountId: string;
+ amount: number;
+ quantity: number | null;
+ itemId: string | null;
+ role: IntercompanyPostingRole;
+}> {
+ if (lines.length !== metadata.length) {
+ throw new Error("Intercompany journal lines and metadata are misaligned");
+ }
+ const roles = new Map<string, IntercompanyPostingRole>();
+ const register = (
+ accountId: string | null | undefined,
+ role: IntercompanyPostingRole,
+ ) => {
+ if (!accountId) return;
+ const existing = roles.get(accountId);
+ if (existing && existing !== role) {
+ throw new Error(`Ambiguous intercompany account roles for ${accountId}`);
+ }
+ roles.set(accountId, role);
+ };
+ register(accounts.controlAccountId, "Control");
+ for (const account of accounts.revenueAccountIds ?? []) {
+ register(account, "Revenue");
+ }
+ register(accounts.cogsAccountId, "COGS");
+ for (const account of accounts.capitalizationAccountIds ?? []) {
+ register(account, "Capitalization");
+ }
+ return lines.flatMap((line, index) => {
+ if (!line.id) {
+ throw new Error(
+ "Missing returned journal line ID for intercompany capture",
+ );
+ }
+ const role = line.accountId ? roles.get(line.accountId) : undefined;
+ if (!role || !line.accountId) return [];
+ return [{
+ journalLineId: line.id,
+ accountId: line.accountId,
+ amount: line.amount ?? 0,
+ quantity: line.quantity ?? null,
+ itemId: metadata[index]?.itemId ?? null,
+ role,
+ }];
+ });
+}
diff --git a/packages/database/supabase/functions/shared/payment-funding.test.ts b/packages/database/supabase/functions/shared/payment-funding.test.ts
new file mode 100644
index 0000000000..6837ff4244
--- /dev/null
+++ b/packages/database/supabase/functions/shared/payment-funding.test.ts
@@ -0,0 +1,400 @@
+import {
+ assertEquals,
+ assertThrows
+} from "https://deno.land/[email protected]/testing/asserts.ts";
+import { toBaseAmount } from "./accounting-currency.ts";
+import {
+ allocatePaymentFunding,
+ invoiceRemainingAmounts,
+ isEffectiveSettlement,
+ remainingFundingSources,
+ reduceInvoiceSettlements,
+ type FundingApplication,
+ type FundingRequest,
+ type FundingSource
+} from "./payment-funding.ts";
+import { round } from "./precision.ts";
+
+const source = (
+ paymentId: string,
+ remainingDocument: number,
+ exchangeRate = 1,
+ overrides: Partial<FundingSource> = {}
+): FundingSource => ({
+ paymentId,
+ postingDate: "2026-09-07",
+ exchangeRate,
+ remainingDocument,
+ remainingBase: toBaseAmount(remainingDocument, exchangeRate),
+ ...overrides
+});
+
+const request = (
+ targetId: string,
+ principal: number,
+ exchangeRate = 1,
+ overrides: Partial<FundingRequest> = {}
+): FundingRequest => ({
+ targetId,
+ targetExchangeRate: exchangeRate,
+ remainingDocument: principal,
+ remainingBase: toBaseAmount(principal, exchangeRate),
+ requestedDocumentPrincipal: principal,
+ discountAmount: 0,
+ writeOffAmount: 0,
+ ...overrides
+});
+
+const allocate = (
+ currentPayment: FundingSource,
+ requests: FundingRequest[],
+ overrides: Partial<Parameters<typeof allocatePaymentFunding>[0]> = {}
+) => allocatePaymentFunding({
+ currentPayment,
+ priorSources: [],
+ requests,
+ currencyDecimals: 2,
+ isAR: true,
+ ...overrides
+});
+
+function firstApplication(applications: FundingApplication[]) {
+ assertEquals(applications.length > 0, true, "Expected an actual funding row");
+ return applications[0]!;
+}
+
+Deno.test("110 paid at matching1.10 snapshots relieves base100 without FX", () => {
+ const result = allocate(source("current", 110, 1.1), [request("invoice", 110, 1.1)]);
+ assertEquals(result, {
+ applications: [{
+ targetId: "invoice", sourcePaymentId: null, sourceAmount: 110,
+ sourceExchangeRate: 1.1, targetExchangeRate: 1.1, appliedAmount: 100,
+ discountAmount: 0, writeOffAmount: 0, fxGainLossAmount: 0
+ }],
+ newOnAccountDocument: 0,
+ sourceRemainders: [{ paymentId: "current", remainingDocument: 0, remainingBase: 0 }]
+ });
+});
+
+for (const [paymentRate, arFx] of [[1, 10], [1.25, -12]] as const) {
+ for (const isAR of [true, false]) {
+ Deno.test(`110 application with source rate${paymentRate}, ${isAR ? "AR" : "AP"} records correct signed FX`, () => {
+ const result = allocate(source("current", 110, paymentRate), [request("invoice", 110, 1.1)], { isAR });
+ const row = firstApplication(result.applications);
+ assertEquals(row.appliedAmount, 100);
+ assertEquals(row.sourceAmount, 110);
+ assertEquals(row.fxGainLossAmount, isAR ? arFx : -arFx);
+ assertEquals(result.newOnAccountDocument, 0);
+ });
+ }
+}
+
+Deno.test("discount and write-off remain target base and do not consume cash", () => {
+ const result = allocate(source("current", 88), [request("invoice", 88, 1.1, {
+ remainingDocument: 110, remainingBase: 100, discountAmount: 10
+ })]);
+ const row = firstApplication(result.applications);
+ assertEquals(row.appliedAmount, 80);
+ assertEquals(row.discountAmount, 10);
+ assertEquals(row.sourceAmount, 88);
+ assertEquals(row.fxGainLossAmount, 8);
+ assertEquals(100 - row.appliedAmount - row.discountAmount, 10);
+ const writtenOff = allocate(source("current", 88), [request("invoice", 88, 1.1, {
+ remainingDocument: 110, remainingBase: 100, writeOffAmount: 10
+ })], { isAR: false });
+ assertEquals(firstApplication(writtenOff.applications).writeOffAmount, 10);
+ assertEquals(firstApplication(writtenOff.applications).fxGainLossAmount, -8);
+});
+
+Deno.test("payment132 applies110 and retains22 document /20 base from current cash", () => {
+ const result = allocate(source("current", 132, 1.1), [request("invoice", 110, 1.1)]);
+ assertEquals(result.newOnAccountDocument, 22);
+ assertEquals(result.sourceRemainders, [{ paymentId: "current", remainingDocument: 22, remainingBase: 20 }]);
+});
+
+Deno.test("two invoices at1.10 and1.20 funded by230 at1.15 reconcile to zero net FX", () => {
+ const result = allocate(source("current", 230, 1.15), [request("a", 110, 1.1), request("b", 120, 1.2)]);
+ assertEquals(result.applications.map((row) => row.appliedAmount), [100, 100]);
+ assertEquals(result.applications.map((row) => row.fxGainLossAmount), [-4.34783, 4.34783]);
+ assertEquals(round(result.applications.reduce((sum, row) => sum + row.fxGainLossAmount, 0)), 0);
+ assertEquals(result.sourceRemainders, [{ paymentId: "current", remainingDocument: 0, remainingBase: 0 }]);
+});
+
+Deno.test("a prior110 credit releases its original base100 against an invoice carrying88", () => {
+ const priorSources = [source("credit", 110, 1.1, { postingDate: "2026-09-06" })];
+ const requests = [request("invoice", 110, 1.25)];
+ const first = allocate(source("current", 0, 99), requests, { priorSources });
+ const second = allocate(source("current", 0, 0.5), requests, { priorSources });
+ assertEquals(first, second, "Changing the applying payment rate cannot revalue prior credit");
+ assertEquals(firstApplication(first.applications), {
+ targetId: "invoice", sourcePaymentId: "credit", sourceAmount: 110,
+ sourceExchangeRate: 1.1, targetExchangeRate: 1.25, appliedAmount: 88,
+ discountAmount: 0, writeOffAmount: 0, fxGainLossAmount: 12
+ });
+});
+
+Deno.test("current cash first, then prior dates and IDs, without mutating input order", () => {
+ const priorSources = [
+ source("later", 100, 2, { postingDate: "2026-09-05" }),
+ source("b", 33, 1.1, { postingDate: "2026-09-04" }),
+ source("a", 44, 1.1, { postingDate: "2026-09-04" })
+ ];
+ const before = structuredClone(priorSources);
+ const input = source("current", 22, 1.1);
+ const requests = [request("invoice", 110, 1.1)];
+ const result = allocate(input, requests, { priorSources });
+ assertEquals(result, allocate(input, requests, { priorSources: [...priorSources].reverse() }));
+ assertEquals(priorSources, before);
+ assertEquals(result.applications.map((row) => [row.sourcePaymentId, row.sourceAmount, row.appliedAmount]), [
+ [null, 22, 20], ["a", 44, 40], ["b", 33, 30], ["later", 11, 10]
+ ]);
+ assertEquals(result.sourceRemainders, [
+ { paymentId: "current", remainingDocument: 0, remainingBase: 0 },
+ { paymentId: "a", remainingDocument: 0, remainingBase: 0 },
+ { paymentId: "b", remainingDocument: 0, remainingBase: 0 },
+ { paymentId: "later", remainingDocument: 89, remainingBase: 44.5 }
+ ]);
+});
+
+Deno.test("mixed cash and two prior rates assign discount/write-off exactly once", () => {
+ const result = allocate(source("current", 22, 1.1), [request("invoice", 88, 1.1, {
+ remainingDocument: 110, remainingBase: 100, discountAmount: 10, writeOffAmount: 10
+ })], {
+ priorSources: [source("older", 33, 1), source("newer", 33, 1.5, { postingDate: "2026-09-08" })]
+ });
+ assertEquals(result.applications.map((row) => [row.sourceAmount, row.appliedAmount, row.discountAmount, row.writeOffAmount, row.fxGainLossAmount]), [
+ [22, 20, 10, 10, 0], [33, 30, 0, 0, 3], [33, 30, 0, 0, -8]
+ ]);
+ assertEquals(result.applications.reduce((sum, row) => sum + row.appliedAmount + row.discountAmount + row.writeOffAmount, 0), 100);
+ assertEquals(result.newOnAccountDocument, 0);
+});
+
+Deno.test("discount-only rows need no funding source and never create FX", () => {
+ const result = allocate(source("current", 0, 1.5), [request("invoice", 0, 1.1, {
+ remainingDocument: 11, remainingBase: 10, discountAmount: 8, writeOffAmount: 2
+ })]);
+ assertEquals(firstApplication(result.applications), {
+ targetId: "invoice", sourcePaymentId: null, sourceAmount: 0,
+ sourceExchangeRate: 1.5, targetExchangeRate: 1.1, appliedAmount: 0,
+ discountAmount: 8, writeOffAmount: 2, fxGainLossAmount: 0
+ });
+});
+
+Deno.test("160.01 source units exhaust exactly even when target base rounds to0.01000", () => {
+ const result = allocate(source("current", 160.01, 16000), [request("invoice", 160.01, 16000)]);
+ const row = firstApplication(result.applications);
+ assertEquals(row.sourceAmount, 160.01);
+ assertEquals(row.appliedAmount, 0.01);
+ assertEquals(result.newOnAccountDocument, 0);
+ assertEquals(result.sourceRemainders, [{ paymentId: "current", remainingDocument: 0, remainingBase: 0 }]);
+ // Releasing/voiding this persisted allocation restores the exact source units.
+ assertEquals(round(result.newOnAccountDocument + row.sourceAmount, 2), 160.01);
+});
+
+Deno.test("160.00 partial application leaves a positive0.01 document allocation with zero base", () => {
+ const initial = allocate(source("current", 160.01, 16000), [request("invoice", 160, 16000, {
+ remainingDocument: 160.01, remainingBase: 0.01
+ })]);
+ assertEquals(firstApplication(initial.applications).sourceAmount, 160);
+ assertEquals(initial.newOnAccountDocument, 0.01);
+ assertEquals(initial.sourceRemainders[0]?.remainingBase, 0);
+ const closing = allocate(source("applying", 0, 1), [request("invoice", 0.01, 16000, { remainingBase: 0 })], {
+ priorSources: [source("current", 0.01, 16000, { remainingBase: 0 })]
+ });
+ assertEquals(firstApplication(closing.applications).sourceAmount, 0.01);
+ assertEquals(firstApplication(closing.applications).appliedAmount, 0);
+ assertEquals(closing.sourceRemainders.every((row) => row.remainingDocument === 0 && row.remainingBase === 0), true);
+});
+
+Deno.test("three separate partial allocations preserve exact source and target carrying residuals", () => {
+ let remainingDocument = 3;
+ let remainingBase = 1;
+ const applied: number[] = [];
+ const released: number[] = [];
+ for (const installment of [1, 2, 3]) {
+ const result = allocate(source(`owner-${installment}`, 0), [request("invoice", 1, 3, { remainingDocument, remainingBase })], {
+ priorSources: [source("credit", remainingDocument, 3, { remainingBase })]
+ });
+ const row = firstApplication(result.applications);
+ applied.push(row.appliedAmount);
+ released.push(round(row.appliedAmount + row.fxGainLossAmount));
+ const credit = result.sourceRemainders.find((remainder) => remainder.paymentId === "credit")!;
+ remainingDocument = credit.remainingDocument;
+ remainingBase = credit.remainingBase;
+ }
+ assertEquals(applied, [0.33333, 0.33333, 0.33334]);
+ assertEquals(released, [0.33333, 0.33333, 0.33334]);
+ assertEquals(remainingDocument, 0);
+ assertEquals(remainingBase, 0);
+});
+
+Deno.test("source and target final carrying residuals can differ and reconcile through recorded FX", () => {
+ for (const isAR of [true, false]) {
+ const result = allocate(source("current", 0), [request("invoice", 1, 3, { remainingBase: 0.33333 })], {
+ priorSources: [source("credit", 1, 3, { remainingBase: 0.33334 })], isAR
+ });
+ const row = firstApplication(result.applications);
+ assertEquals(row.appliedAmount, 0.33333);
+ assertEquals(row.fxGainLossAmount, isAR ? 0.00001 : -0.00001);
+ assertEquals(result.sourceRemainders[1]?.remainingBase, 0);
+ }
+});
+
+Deno.test("splitting a target across tiny sources reconciles target carrying once", () => {
+ const result = allocate(source("current", 1, 3), [request("invoice", 3, 3)], {
+ priorSources: [source("a", 1, 3), source("b", 1, 3)]
+ });
+ assertEquals(result.applications.map((row) => row.appliedAmount), [0.33333, 0.33333, 0.33334]);
+ assertEquals(result.applications.map((row) => row.fxGainLossAmount), [0, 0, -0.00001]);
+});
+
+Deno.test("repeated cent allocations consume160.01 exactly without floating residuals", () => {
+ let credit = source("credit", 160.01, 16000);
+ const principal = [53.33, 53.33, 53.35];
+ const allocated: FundingApplication[] = [];
+ for (const [index, amount] of principal.entries()) {
+ const result = allocate(source(`owner-${index}`, 0), [request("invoice", amount, 16000, {
+ remainingDocument: credit.remainingDocument, remainingBase: credit.remainingBase
+ })], { priorSources: [credit] });
+ allocated.push(...result.applications);
+ const remainder = result.sourceRemainders.find((row) => row.paymentId === credit.paymentId)!;
+ credit = { ...credit, ...remainder };
+ }
+ assertEquals(credit.remainingDocument, 0);
+ assertEquals(credit.remainingBase, 0);
+ assertEquals(round(allocated.reduce((sum, row) => sum + row.sourceAmount, 0), 2), 160.01);
+ assertEquals(round(allocated.reduce((sum, row) => sum + row.appliedAmount, 0)), 0.01);
+});
+
+Deno.test("funding respects configured zero and three document decimals", () => {
+ const whole = allocate(source("current", 13, 2), [request("invoice", 12, 2)], { currencyDecimals: 0 });
+ assertEquals(whole.newOnAccountDocument, 1);
+ const three = allocate(source("current", 1.005), [request("invoice", 1.001)], { currencyDecimals: 3 });
+ assertEquals(three.newOnAccountDocument, 0.004);
+ assertEquals(three.sourceRemainders[0]?.remainingBase, 0.004);
+});
+
+Deno.test("no requests leave current cash and prior credits independently available", () => {
+ const result = allocate(source("current", 22, 1.1), [], { priorSources: [source("old", 110, 1.1)] });
+ assertEquals(result.applications, []);
+ assertEquals(result.newOnAccountDocument, 22);
+ assertEquals(result.sourceRemainders, [
+ { paymentId: "current", remainingDocument: 22, remainingBase: 20 },
+ { paymentId: "old", remainingDocument: 110, remainingBase: 100 }
+ ]);
+});
+
+Deno.test("empty request rows do not produce empty settlements", () => {
+ const result = allocate(source("current", 20), [request("invoice", 0, 1, { remainingDocument: 10, remainingBase: 10 })]);
+ assertEquals(result.applications, []);
+ assertEquals(result.newOnAccountDocument, 20);
+});
+
+Deno.test("funding rejects target document over-application and excess target relief", () => {
+ assertThrows(() => allocate(source("current", 120), [request("invoice", 110.01, 1.1, { remainingDocument: 110, remainingBase: 100 })]), Error, "target");
+ assertThrows(() => allocate(source("current", 110), [request("invoice", 110, 1.1, { discountAmount: 0.01 })]), Error, "target");
+ assertThrows(() => allocate(source("current", 0), [request("invoice", 0, 1.1, { remainingDocument: 11, remainingBase: 10, discountAmount: 11 })]), Error, "target");
+});
+
+Deno.test("funding rejects insufficient sources without mutating any source or request", () => {
+ const current = source("current", 22);
+ const priorSources = [source("old", 77)];
+ const requests = [request("invoice", 100)];
+ const before = structuredClone({ current, priorSources, requests });
+ assertThrows(() => allocate(current, requests, { priorSources }), Error, "funding");
+ assertEquals({ current, priorSources, requests }, before);
+});
+
+Deno.test("duplicate source IDs, source self-reference, and duplicate target IDs are rejected", () => {
+ assertThrows(() => allocate(source("current", 0), [], { priorSources: [source("a", 1), source("a", 1)] }), Error, "Duplicate");
+ assertThrows(() => allocate(source("current", 0), [], { priorSources: [source("current", 1)] }), Error, "Duplicate");
+ assertThrows(() => allocate(source("current", 2), [request("a", 1), request("a", 1)]), Error, "Duplicate");
+});
+
+Deno.test("funding refuses invalid rates, amounts, document precision, and unsafe integer units", () => {
+ for (const invalid of [0, -1, Number.NaN, Number.POSITIVE_INFINITY]) {
+ assertThrows(() => allocate({ ...source("current", 1), exchangeRate: invalid }, []), Error, "rate");
+ assertThrows(() => allocate(source("current", 1), [{ ...request("a", 1), targetExchangeRate: invalid }]), Error, "rate");
+ }
+ for (const invalid of [-1, Number.NaN, Number.POSITIVE_INFINITY]) {
+ assertThrows(() => allocate({ ...source("current", 1), remainingDocument: invalid }, []));
+ assertThrows(() => allocate({ ...source("current", 1), remainingBase: invalid }, []));
+ for (const key of ["requestedDocumentPrincipal", "discountAmount", "writeOffAmount", "remainingBase", "remainingDocument"] as const) {
+ assertThrows(() => allocate(source("current", 1), [{ ...request("a", 1), [key]: invalid }]));
+ }
+ }
+ assertThrows(() => allocate(source("current", 1.001), []), Error, "precision");
+ assertThrows(() => allocate(source("current", 1), [request("a", 0.001)]), Error, "precision");
+ assertThrows(() => allocate(source("current", Number.MAX_SAFE_INTEGER), []), Error, "safe");
+ assertThrows(() => allocate({ ...source("current", 1), remainingBase: Number.MAX_VALUE }, []));
+ assertThrows(() => allocate(source("current", 1), [], { currencyDecimals: -1 }), Error, "decimal");
+});
+
+Deno.test("inconsistent exhausted source snapshot cannot retain unreleased carrying base", () => {
+ assertThrows(() => allocate(source("current", 0, 3, { remainingBase: 0.00001 }), []), Error, "carrying");
+ assertThrows(() => allocate(source("current", 0), [], {
+ priorSources: [source("credit", 0, 3, { remainingBase: 0.00001 })]
+ }), Error, "carrying");
+});
+
+Deno.test("inconsistent discount-only closure cannot leave target carrying base behind", () => {
+ assertThrows(() => allocate(source("current", 0), [request("invoice", 0, 3, {
+ remainingDocument: 1, remainingBase: 0.33334, discountAmount: 0.33333
+ })]), Error, "carrying");
+ const complete = allocate(source("current", 0), [request("invoice", 0, 3, {
+ remainingDocument: 1, remainingBase: 0.33334, discountAmount: 0.33334
+ })]);
+ assertEquals(firstApplication(complete.applications).discountAmount, 0.33334);
+});
+
+
+Deno.test("settlement effectiveness requires the owning posted parent", () => {
+ const row = { paymentId: null, memoId: null, appliedViaPaymentId: null,
+ paymentStatus: null, memoStatus: null, viaStatus: null };
+ assertEquals(isEffectiveSettlement({ ...row, paymentStatus: "Posted" }), false);
+ assertEquals(isEffectiveSettlement({ ...row, memoStatus: "Posted" }), false);
+ for (const status of ["Draft", "Posted", "Voided"]) {
+ assertEquals(isEffectiveSettlement({ ...row, paymentId: "payment", paymentStatus: status }), status === "Posted");
+ assertEquals(isEffectiveSettlement({ ...row, memoId: "memo", memoStatus: "Posted", appliedViaPaymentId: "payment", viaStatus: status }), status === "Posted");
+ }
+ assertEquals(isEffectiveSettlement({ ...row, memoId: "memo", memoStatus: "Posted" }), true);
+ assertEquals(isEffectiveSettlement({ ...row, paymentId: "payment", paymentStatus: "Draft", memoId: "memo", memoStatus: "Posted" }), false);
+});
+Deno.test("invoice reducers preserve signed controls and aggregate before rounding", () => {
+ for (const isAR of [true, false]) {
+ const invoice = { id: "invoice", totalAmount: 90, exchangeRate: 1 };
+ const controls = new Map([["invoice", 100 - 10]]);
+ const row = { targetSalesInvoiceId: "invoice", targetPurchaseInvoiceId: "invoice",
+ sourceAmount: 90, appliedAmount: 90, discountAmount: 0, writeOffAmount: 0 };
+ assertEquals(invoiceRemainingAmounts(invoice, [row], controls, 2, isAR), { remainingDocument: 0, remainingBase: 0 });
+ assertThrows(() => invoiceRemainingAmounts(invoice, [{ ...row, sourceAmount: 91 }], controls, 2, isAR), Error, "excessive settlements");
+ }
+ assertEquals(reduceInvoiceSettlements(Array.from({ length: 1001 }, () => ({
+ sourceAmount: 0, appliedAmount: 0.000004, discountAmount: 0, writeOffAmount: 0
+ })), 1, 2), { document: 0, base: 0.004 });
+ assertEquals(reduceInvoiceSettlements([{ sourceAmount: 0.1, appliedAmount: 0.09091, discountAmount: 0.004, writeOffAmount: 0.004 },
+ { sourceAmount: 0.2, appliedAmount: 0.18182, discountAmount: 0.004, writeOffAmount: 0.004 }], 1.1, 2),
+ { document: 0.32, base: 0.28873 });
+});
+Deno.test("source reduction preserves principal, final carry and AP FX direction", () => {
+ const payment = { id: "source", totalAmount: 160.01, exchangeRate: 16000,
+ postingDate: null, paymentDate: "2026-09-07", currencyCode: "EUR" };
+ const use = { paymentId: "current", sourcePaymentId: "source", sourceAmount: 160,
+ appliedAmount: 0.01, fxGainLossAmount: 0 };
+ const decimals = new Map([["EUR", 2]]);
+ assertEquals(remainingFundingSources([payment], [use], decimals, true)[0], {
+ paymentId: "source", postingDate: "2026-09-07", exchangeRate: 16000, remainingDocument: 0.01, remainingBase: 0
+ });
+ assertEquals(remainingFundingSources([payment], [use, { ...use, sourceAmount: 0.01, appliedAmount: 0 }], decimals, true), []);
+ assertEquals(remainingFundingSources([{ ...payment, totalAmount: 1, exchangeRate: 3 }],
+ [{ ...use, sourceAmount: 0.5, appliedAmount: 0.16667 }], decimals, true)[0]?.remainingBase, 0.16666);
+ assertEquals(remainingFundingSources([{ ...payment, totalAmount: 110, exchangeRate: 1.1 }],
+ [{ ...use, sourceAmount: 55, appliedAmount: 60, fxGainLossAmount: 10 }], decimals, false)[0]?.remainingBase, 50);
+ assertEquals(remainingFundingSources([{ ...payment, totalAmount: 3, exchangeRate: 3 }],
+ [{ ...use, sourceAmount: 1, appliedAmount: 0.33333 }, { ...use, sourceAmount: 1, appliedAmount: 0.33333 }],
+ decimals, true)[0]?.remainingBase, 0.33334);
+ for (const principal of [null, -1, Number.NaN]) {
+ assertThrows(() => remainingFundingSources([payment], [{ ...use, sourceAmount: principal }], decimals, true), Error, "principal");
+ }
+ assertThrows(() => remainingFundingSources([payment], [{ ...use, sourceAmount: 161 }], decimals, true), Error, "Invalid remaining");
+});
diff --git a/packages/database/supabase/functions/shared/payment-funding.ts b/packages/database/supabase/functions/shared/payment-funding.ts
new file mode 100644
index 0000000000..304830bcfe
--- /dev/null
+++ b/packages/database/supabase/functions/shared/payment-funding.ts
@@ -0,0 +1,343 @@
+import {
+ assertCurrencyDecimals,
+ assertExchangeRate,
+ calculateSettlementFx,
+ toBaseAmount,
+ toDocumentAmount,
+} from "./accounting-currency.ts";
+import { round } from "./precision.ts";
+
+export type FundingSource = {
+ paymentId: string;
+ postingDate: string;
+ exchangeRate: number;
+ remainingDocument: number;
+ /** Original carrying base less effective recorded funding releases. */
+ remainingBase: number;
+};
+
+export type FundingRequest = {
+ targetId: string;
+ targetExchangeRate: number;
+ remainingDocument: number;
+ /** Original target carrying base less effective recorded base relief. */
+ remainingBase: number;
+ requestedDocumentPrincipal: number;
+ discountAmount: number;
+ writeOffAmount: number;
+};
+
+export type FundingApplication = {
+ targetId: string;
+ sourcePaymentId: string | null;
+ sourceAmount: number;
+ sourceExchangeRate: number;
+ targetExchangeRate: number;
+ appliedAmount: number;
+ discountAmount: number;
+ writeOffAmount: number;
+ fxGainLossAmount: number;
+};
+
+function nonnegativeAmount(amount: number, label: string): number {
+ if (!Number.isFinite(amount) || amount < 0) {
+ throw new Error(`${label} must be nonnegative and finite`);
+ }
+ return amount;
+}
+
+function addUniqueId(ids: Set<string>, id: string, label: string): void {
+ if (typeof id !== "string" || !id.trim()) {
+ throw new Error(`${label} ID is required`);
+ }
+ if (ids.has(id)) throw new Error(`Duplicate ${label} ID: ${id}`);
+ ids.add(id);
+}
+
+/**
+ * Pure allocation after the caller validates company, party, side, currency and
+ * authoritative snapshots. Source/target document principal is independent of
+ * carrying base; final exhaustion releases each recorded carrying residual.
+ */
+export function allocatePaymentFunding(input: {
+ currentPayment: FundingSource;
+ priorSources: FundingSource[];
+ requests: FundingRequest[];
+ currencyDecimals: number;
+ isAR: boolean;
+}): {
+ applications: FundingApplication[];
+ newOnAccountDocument: number;
+ sourceRemainders: Array<{
+ paymentId: string;
+ remainingDocument: number;
+ remainingBase: number;
+ }>;
+} {
+ const { currencyDecimals, isAR } = input;
+ // This also validates the configured decimal count through the common boundary.
+ assertCurrencyDecimals(currencyDecimals);
+ const documentScale = 10 ** currencyDecimals;
+ const documentUnits = (amount: number, label: string): number => {
+ nonnegativeAmount(amount, label);
+ const normalized = toDocumentAmount(amount, 1, currencyDecimals);
+ // Admit only binary arithmetic noise, never a fraction of a document unit.
+ const noise = Number.EPSILON * Math.max(1, amount) * 4;
+ if (Math.abs(amount - normalized) > noise) {
+ throw new Error(`${label} exceeds document currency precision`);
+ }
+ const units = round(normalized * documentScale, 0);
+ if (!Number.isSafeInteger(units)) {
+ throw new Error(`${label} exceeds safe document currency units`);
+ }
+ return units;
+ };
+ const fromDocumentUnits = (units: number): number =>
+ toDocumentAmount(units / documentScale, 1, currencyDecimals);
+
+ const sourceIds = new Set<string>();
+ const sources = [input.currentPayment, ...[...input.priorSources].sort((a, b) => {
+ if (a.postingDate !== b.postingDate) return a.postingDate < b.postingDate ? -1 : 1;
+ return a.paymentId < b.paymentId ? -1 : a.paymentId > b.paymentId ? 1 : 0;
+ })].map((source) => {
+ addUniqueId(sourceIds, source.paymentId, "funding source");
+ assertExchangeRate(source.exchangeRate);
+ const remainingUnits = documentUnits(source.remainingDocument, "Source amount");
+ const remainingBase = toBaseAmount(nonnegativeAmount(source.remainingBase, "Source carrying base"), 1);
+ if (remainingUnits === 0 && remainingBase !== 0) {
+ throw new Error(`Exhausted source retains carrying base: ${source.paymentId}`);
+ }
+ return {
+ ...source,
+ remainingUnits,
+ remainingBase
+ };
+ });
+
+ const targetIds = new Set<string>();
+ const requests = input.requests.map((request) => {
+ addUniqueId(targetIds, request.targetId, "target");
+ assertExchangeRate(request.targetExchangeRate);
+ const remainingUnits = documentUnits(request.remainingDocument, "Remaining target document amount");
+ const principalUnits = documentUnits(request.requestedDocumentPrincipal, "Requested document principal");
+ const remainingBase = toBaseAmount(nonnegativeAmount(request.remainingBase, "Remaining target base"), 1);
+ const discountAmount = toBaseAmount(nonnegativeAmount(request.discountAmount, "Target discount amount"), 1);
+ const writeOffAmount = toBaseAmount(nonnegativeAmount(request.writeOffAmount, "Target write-off amount"), 1);
+ const reliefBase = round(discountAmount + writeOffAmount);
+ const reliefUnits = documentUnits(
+ toDocumentAmount(reliefBase, request.targetExchangeRate, currencyDecimals),
+ "Target discount/write-off document amount"
+ );
+ if (principalUnits + reliefUnits > remainingUnits || reliefBase > remainingBase) {
+ throw new Error(`Application exceeds target balance: ${request.targetId}`);
+ }
+ const availablePrincipalBase = round(remainingBase - reliefBase);
+ const closesTarget = principalUnits + reliefUnits === remainingUnits;
+ if (closesTarget && principalUnits === 0 && availablePrincipalBase !== 0) {
+ throw new Error(`Full target relief must release its remaining carrying base: ${request.targetId}`);
+ }
+ const principalBase = closesTarget
+ ? availablePrincipalBase
+ : Math.min(
+ toBaseAmount(fromDocumentUnits(principalUnits), request.targetExchangeRate),
+ availablePrincipalBase
+ );
+ return { ...request, discountAmount, writeOffAmount, principalUnits, principalBase };
+ });
+
+ const applications: FundingApplication[] = [];
+ let sourceIndex = 0;
+ for (const request of requests) {
+ let remainingUnits = request.principalUnits;
+ let remainingBase = request.principalBase;
+ let hasApplication = false;
+ if (remainingUnits === 0) {
+ if (request.discountAmount > 0 || request.writeOffAmount > 0) {
+ applications.push({
+ targetId: request.targetId,
+ sourcePaymentId: null,
+ sourceAmount: 0,
+ sourceExchangeRate: input.currentPayment.exchangeRate,
+ targetExchangeRate: request.targetExchangeRate,
+ appliedAmount: 0,
+ discountAmount: request.discountAmount,
+ writeOffAmount: request.writeOffAmount,
+ fxGainLossAmount: 0
+ });
+ }
+ continue;
+ }
+
+ while (remainingUnits > 0) {
+ const source = sources[sourceIndex];
+ if (!source) throw new Error(`Insufficient payment funding for target: ${request.targetId}`);
+ if (source.remainingUnits === 0) {
+ sourceIndex++;
+ continue;
+ }
+ const units = Math.min(remainingUnits, source.remainingUnits);
+ const sourceAmount = fromDocumentUnits(units);
+ const appliedAmount = units === remainingUnits
+ ? remainingBase
+ : Math.min(toBaseAmount(sourceAmount, request.targetExchangeRate), remainingBase);
+ const sourceBaseAmount = units === source.remainingUnits
+ ? source.remainingBase
+ : Math.min(toBaseAmount(sourceAmount, source.exchangeRate), source.remainingBase);
+ applications.push({
+ targetId: request.targetId,
+ sourcePaymentId: source.paymentId === input.currentPayment.paymentId ? null : source.paymentId,
+ sourceAmount,
+ sourceExchangeRate: source.exchangeRate,
+ targetExchangeRate: request.targetExchangeRate,
+ appliedAmount,
+ discountAmount: hasApplication ? 0 : request.discountAmount,
+ writeOffAmount: hasApplication ? 0 : request.writeOffAmount,
+ fxGainLossAmount: calculateSettlementFx({
+ appliedAmount, sourceAmount, sourceExchangeRate: source.exchangeRate, sourceBaseAmount, isAR
+ })
+ });
+ hasApplication = true;
+ remainingUnits -= units;
+ remainingBase = round(remainingBase - appliedAmount);
+ source.remainingUnits -= units;
+ source.remainingBase = round(source.remainingBase - sourceBaseAmount);
+ }
+ }
+ const sourceRemainders = sources.map((source) => ({
+ paymentId: source.paymentId,
+ remainingDocument: fromDocumentUnits(source.remainingUnits),
+ remainingBase: source.remainingBase
+ }));
+ return {
+ applications,
+ newOnAccountDocument: sourceRemainders[0]?.remainingDocument ?? 0,
+ sourceRemainders
+ };
+}
+
+export type SettlementEffectiveness = {
+ paymentId: string | null;
+ memoId: string | null;
+ appliedViaPaymentId: string | null;
+ paymentStatus: string | null;
+ memoStatus: string | null;
+ viaStatus: string | null;
+};
+
+/** Parent status determines whether a persisted settlement has taken effect. */
+export function isEffectiveSettlement(row: SettlementEffectiveness): boolean {
+ return row.paymentId
+ ? row.paymentStatus === "Posted"
+ : Boolean(row.memoId && row.memoStatus === "Posted" &&
+ (!row.appliedViaPaymentId || row.viaStatus === "Posted"));
+}
+
+export type SettlementBalanceRow = {
+ targetSalesInvoiceId: string | null;
+ targetPurchaseInvoiceId: string | null;
+ sourceAmount: number | null;
+ appliedAmount: number;
+ discountAmount: number;
+ writeOffAmount: number;
+};
+
+function sourcePrincipal(value: number | null): number {
+ if (value === null) throw new Error("Settlement is missing its document principal");
+ return nonnegativeAmount(Number(value), "Settlement document principal");
+}
+
+/** Accumulate first; each adjustment is rounded at its document boundary. */
+export function reduceInvoiceSettlements(
+ rows: readonly Pick<SettlementBalanceRow, "sourceAmount" | "appliedAmount" | "discountAmount" | "writeOffAmount">[],
+ exchangeRate: number,
+ decimals: number
+): { document: number; base: number } {
+ let document = 0;
+ let base = 0;
+ for (const row of rows) {
+ const adjustments = nonnegativeAmount(Number(row.discountAmount), "Settlement discount") +
+ nonnegativeAmount(Number(row.writeOffAmount), "Settlement write-off");
+ document += sourcePrincipal(row.sourceAmount) + toDocumentAmount(adjustments, exchangeRate, decimals);
+ base += nonnegativeAmount(Number(row.appliedAmount), "Settlement applied amount") + adjustments;
+ }
+ return { document: toDocumentAmount(document, 1, decimals), base: round(base) };
+}
+
+/** Original controls use signed natural balances for both AR and AP. */
+export function invoiceRemainingAmounts(
+ invoice: { id: string | null; totalAmount: number | null; exchangeRate: number | null },
+ rows: readonly SettlementBalanceRow[],
+ controlAmounts: ReadonlyMap<string, number>,
+ decimals: number,
+ isAR: boolean
+): { remainingDocument: number; remainingBase: number } {
+ if (!invoice.id || invoice.totalAmount == null || invoice.exchangeRate == null) {
+ throw new Error("Invoice identity, total or exchange rate is missing");
+ }
+ const rate = Number(invoice.exchangeRate);
+ const consumed = reduceInvoiceSettlements(rows.filter((row) =>
+ (isAR ? row.targetSalesInvoiceId : row.targetPurchaseInvoiceId) === invoice.id
+ ), rate, decimals);
+ const originalDocument = toDocumentAmount(Number(invoice.totalAmount), rate, decimals);
+ const remainingDocument = toDocumentAmount(originalDocument - consumed.document, 1, decimals);
+ const originalBase = controlAmounts.get(invoice.id) ?? round(Number(invoice.totalAmount));
+ const remainingBase = round(originalBase - consumed.base);
+ if (!Number.isFinite(remainingBase) || remainingDocument < 0 || remainingBase < 0) {
+ throw new Error("Invoice already has excessive settlements or an invalid carrying balance");
+ }
+ return { remainingDocument, remainingBase };
+}
+
+export type FundingPaymentRow = {
+ id: string;
+ totalAmount: number;
+ exchangeRate: number;
+ postingDate: string | null;
+ paymentDate: string;
+ currencyCode: string;
+};
+export type FundingConsumptionRow = {
+ paymentId: string | null;
+ sourcePaymentId: string | null;
+ sourceAmount: number | null;
+ appliedAmount: number;
+ fxGainLossAmount: number | null;
+};
+
+/** Callers select effective payments or reserved memos before reducing money. */
+export function remainingFundingSources(
+ payments: readonly FundingPaymentRow[],
+ consumption: readonly FundingConsumptionRow[],
+ decimals: ReadonlyMap<string, number>,
+ isAR: boolean
+): FundingSource[] {
+ const consumed = new Map<string, { document: number; base: number }>();
+ for (const row of consumption) {
+ const sourceId = row.sourcePaymentId ?? row.paymentId;
+ if (!sourceId) continue;
+ const current = consumed.get(sourceId) ?? { document: 0, base: 0 };
+ current.document += sourcePrincipal(row.sourceAmount);
+ const fx = Number(row.fxGainLossAmount ?? 0);
+ if (!Number.isFinite(fx)) throw new Error("Settlement FX must be finite");
+ current.base += nonnegativeAmount(Number(row.appliedAmount), "Settlement applied amount") + (isAR ? 1 : -1) * fx;
+ consumed.set(sourceId, current);
+ }
+ return payments.map((payment) => {
+ const precision = decimals.get(payment.currencyCode);
+ if (precision == null) throw new Error(`Currency ${payment.currencyCode} requires configured decimal places`);
+ const use = consumed.get(payment.id);
+ const total = nonnegativeAmount(Number(payment.totalAmount), "Funding document total");
+ const remainingDocument = toDocumentAmount(total - (use?.document ?? 0), 1, precision);
+ const remainingBase = round(toBaseAmount(total, Number(payment.exchangeRate)) - (use?.base ?? 0));
+ if (remainingDocument < 0 || remainingBase < 0 || (remainingDocument === 0 && remainingBase !== 0)) {
+ throw new Error(`Invalid remaining funding balance for payment ${payment.id}`);
+ }
+ return {
+ paymentId: payment.id,
+ postingDate: payment.postingDate ?? payment.paymentDate,
+ exchangeRate: Number(payment.exchangeRate),
+ remainingDocument,
+ remainingBase
+ };
+ }).filter((payment) => payment.remainingDocument > 0);
+}
diff --git a/packages/database/supabase/functions/shared/precision.test.ts b/packages/database/supabase/functions/shared/precision.test.ts
new file mode 100644
index 0000000000..76509dbbc8
--- /dev/null
+++ b/packages/database/supabase/functions/shared/precision.test.ts
@@ -0,0 +1,100 @@
+import { assertEquals, assertThrows } from "jsr:@std/assert@1";
+import { distributeRoundingResidual, round, SCALE } from "./precision.ts";
+
+const sum = (values: number[]) => round(values.reduce((t, v) => t + v, 0), SCALE);
+
+Deno.test("distributes a surplus one minor unit at a time, most under-rounded first", () => {
+ // 20 lines of 1.99 at 8.25%: each exact tax is 0.164175, which rounds down to
+ // 0.16 and leaves an 0.08 residual against the authoritative 3.28.
+ const exact = Array.from({ length: 20 }, () => 1.99 * 0.0825);
+ const allocated = distributeRoundingResidual(exact, 3.28, 2);
+ assertEquals(sum(allocated), 3.28);
+ // Every component stays within one minor unit of its own exact value, which
+ // is the bound QuickBooks' `tax = net × percent` check assumes.
+ for (const [index, value] of allocated.entries()) {
+ assertEquals(Math.abs(value - exact[index]!) <= 0.01, true);
+ }
+ assertEquals(allocated.filter((v) => v === 0.17).length, 8);
+ assertEquals(allocated.filter((v) => v === 0.16).length, 12);
+});
+
+Deno.test("takes a deficit from the most over-rounded parts", () => {
+ // 0.128 rounds UP to 0.13, so those two parts owe a unit back; 0.121 rounds
+ // DOWN and is asked last. One unit is owed, so only the first over-rounded
+ // part gives it up.
+ const allocated = distributeRoundingResidual([0.128, 0.128, 0.121], 0.37, 2);
+ assertEquals(sum(allocated), 0.37);
+ assertEquals(allocated, [0.12, 0.13, 0.12]);
+});
+
+Deno.test("breaks an exact deficit tie by index", () => {
+ const allocated = distributeRoundingResidual([0.126, 0.126, 0.126], 0.37, 2);
+ assertEquals(sum(allocated), 0.37);
+ assertEquals(allocated, [0.12, 0.12, 0.13]);
+});
+
+Deno.test("returns the independently rounded values when nothing is left over", () => {
+ assertEquals(distributeRoundingResidual([1.115, 2.22], 3.34, 2), [1.12, 2.22]);
+});
+
+Deno.test("resolves ties by index so the allocation is stable", () => {
+ const first = distributeRoundingResidual([0.125, 0.125], 0.26, 2);
+ const second = distributeRoundingResidual([0.125, 0.125], 0.26, 2);
+ assertEquals(first, second);
+ assertEquals(first, [0.13, 0.13]);
+});
+
+Deno.test("keeps signed parts on their own side of zero", () => {
+ const allocated = distributeRoundingResidual([1.005, -0.335, -0.335], 0.34, 2);
+ assertEquals(sum(allocated), 0.34);
+ assertEquals(allocated[0]! > 0, true);
+ assertEquals(
+ allocated.slice(1).every((v) => v < 0),
+ true
+ );
+});
+
+Deno.test("refuses a residual larger than one unit per part — that is a real disagreement", () => {
+ assertThrows(
+ () => distributeRoundingResidual([1.0, 2.0], 10.0, 2),
+ Error,
+ "exceeds"
+ );
+});
+
+Deno.test("refuses non-finite inputs", () => {
+ assertThrows(
+ () => distributeRoundingResidual([1, Number.NaN], 1, 2),
+ Error,
+ "finite"
+ );
+});
+
+Deno.test("defaults to internal scale", () => {
+ const allocated = distributeRoundingResidual([0.000005, 0.000005], 0.00002);
+ assertEquals(sum(allocated), 0.00002);
+});
+
+Deno.test("never reverses a part's sign to place the residual", () => {
+ // Reported on PR #1599: mixed-sign tax components. The deficit unit used to
+ // land on the only positive part (it had the smallest rounding error),
+ // turning a +0.001 tax into -0.01 against positive revenue — the exact shape
+ // this helper exists to prevent.
+ const exact = [-0.028, -0.028, 0.001];
+ const allocated = distributeRoundingResidual(exact, -0.07, 2);
+ assertEquals(sum(allocated), -0.07);
+ assertEquals(allocated, [-0.04, -0.03, 0]);
+ for (const [index, value] of allocated.entries()) {
+ if (value !== 0 && exact[index] !== 0) {
+ assertEquals(Math.sign(value), Math.sign(exact[index]!));
+ }
+ }
+});
+
+Deno.test("refuses a target that can only be met by reversing a sign", () => {
+ assertThrows(
+ () => distributeRoundingResidual([0.001, 0.001], -0.02, 2),
+ Error,
+ "reversing",
+ );
+});
diff --git a/packages/database/supabase/functions/shared/precision.ts b/packages/database/supabase/functions/shared/precision.ts
index 509dce72e1..6922363a04 100644
--- a/packages/database/supabase/functions/shared/precision.ts
+++ b/packages/database/supabase/functions/shared/precision.ts
@@ -31,6 +31,73 @@ export function round(
return shift(fn(shift(value, scale)), -scale);
}
+/** Round every part to `scale` so the results sum EXACTLY to `target`, moving at
+ * most ONE minor unit per part (largest-remainder / Hamilton apportionment).
+ *
+ * Independently rounding N parts leaves a residual of up to N/2 minor units.
+ * Concentrating that residual on a single part is what breaks a part's own
+ * relative/absolute pair — a tax line stops matching its own `taxPercent`, and
+ * a provider that re-derives `amount = net × percent` rejects the document.
+ * Spreading it one unit at a time keeps every part within a minor unit of its
+ * exact value, which is the bound those provider checks assume.
+ *
+ * Parts rounded furthest DOWN receive the surplus first; parts rounded furthest
+ * UP give a unit back first. Ties resolve by index so the result is stable.
+ * Refuses when the residual exceeds one unit per part — that is a real
+ * disagreement between the parts and the target, not a rounding artifact. */
+export function distributeRoundingResidual(
+ exactValues: number[],
+ target: number,
+ scale: number = SCALE
+): number[] {
+ const rounded = exactValues.map((value) => round(value, scale));
+ if (!Number.isFinite(target) || rounded.some((v) => !Number.isFinite(v))) {
+ throw new Error("Rounding residual inputs must be finite");
+ }
+ const sum = rounded.reduce((total, value) => total + value, 0);
+ // Compare in whole minor units: the residual is an exact integer count of
+ // them, so this never inherits the float noise of the sum itself.
+ const residualUnits = Math.round(shift(target - sum, scale));
+ if (residualUnits === 0) return rounded;
+ if (Math.abs(residualUnits) > exactValues.length) {
+ throw new Error(
+ `Rounding residual of ${residualUnits} unit(s) exceeds ${exactValues.length} part(s)`
+ );
+ }
+ const unit = shift(1, -scale);
+ const direction = Math.sign(residualUnits);
+ const order = exactValues
+ .map((value, index) => ({ index, error: value - rounded[index]! }))
+ // Surplus goes to the most under-rounded part; a deficit is taken from the
+ // most over-rounded one.
+ .sort((a, b) => direction * (b.error - a.error) || a.index - b.index);
+ let placed = 0;
+ for (const { index } of order) {
+ if (placed === Math.abs(residualUnits)) break;
+ const next = round(rounded[index]! + direction * unit, scale);
+ // A part may not cross zero. One minor unit is a rounding correction on a
+ // part that is nearly its rounded value; on a part that rounds to ~0 it
+ // would instead REVERSE the part's economic direction — a +0.001 tax
+ // becoming -0.01 against positive revenue, which is the negative-tax-on-
+ // positive-revenue shape this whole helper exists to prevent. Skip such a
+ // part and give the unit to the next-most-deserving one.
+ if (exactValues[index]! !== 0 && next !== 0 && Math.sign(next) !== Math.sign(exactValues[index]!)) {
+ continue;
+ }
+ rounded[index] = next;
+ placed += 1;
+ }
+ if (placed !== Math.abs(residualUnits)) {
+ // Every remaining candidate would have to flip sign, so the target
+ // genuinely disagrees with the parts rather than merely rounding away
+ // from them.
+ throw new Error(
+ `Rounding residual of ${residualUnits} unit(s) cannot be placed without reversing a part's sign`
+ );
+ }
+ return rounded;
+}
+
/** The extra whole units to make/procure to cover scrap at `rate`. Ceils to
* whole units — you cannot make a third of a part to throw away — while the
* fractional target itself is NEVER rounded (callers add the two).
diff --git a/packages/database/supabase/functions/shared/sales-posting-amounts.test.ts b/packages/database/supabase/functions/shared/sales-posting-amounts.test.ts
new file mode 100644
index 0000000000..1fa570cd5a
--- /dev/null
+++ b/packages/database/supabase/functions/shared/sales-posting-amounts.test.ts
@@ -0,0 +1,436 @@
+import {
+ assertEquals,
+ assertThrows,
+} from "https://deno.land/[email protected]/testing/asserts.ts";
+import {
+ allocateSalesHeaderShipping,
+ buildSalesPostingLines,
+ type BuildSalesPostingLinesInput,
+ calculateSalesIntercompanyAmount,
+ calculateSalesPostingAmounts,
+ type SalesPostingAccount,
+} from "./sales-posting-amounts.ts";
+import { classifyIntercompanyPostingLines } from "./intercompany-capture.ts";
+import { round } from "./precision.ts";
+
+const account = (id: string, accountClass: string): SalesPostingAccount => ({
+ id,
+ class: accountClass,
+ active: true,
+ isGroup: false,
+ companyGroupId: "group",
+});
+const fixture = (): BuildSalesPostingLinesInput => ({
+ line: {
+ invoiceLineType: "Service",
+ quantity: 1,
+ unitPrice: 100,
+ shippingCost: 10,
+ addOnCost: 20,
+ nonTaxableAddOnCost: 3,
+ taxPercent: 0.1,
+ allocatedHeaderShipping: 5,
+ },
+ context: {
+ companyId: "company",
+ companyGroupId: "group",
+ documentId: "invoice",
+ externalDocumentId: "customer-reference",
+ documentLineReference: "sales-invoice:source-line",
+ journalLineReference: "journal-reference",
+ intercompanyPartnerId: "partner",
+ },
+ accounts: {
+ receivables: account("ar", "Asset"),
+ sales: account("sales", "Revenue"),
+ shipping: account("shipping", "Revenue"),
+ tax: account("tax", "Liability"),
+ },
+ metadata: {
+ customerTypeId: "customer-type",
+ itemPostingGroupId: "item-group",
+ itemId: "item",
+ locationId: "location",
+ costCenterId: "cost-center",
+ fixedAssetClassId: null,
+ },
+});
+
+const byAccount = (result: ReturnType<typeof buildSalesPostingLines>) =>
+ Object.fromEntries(result.lines.map((line) => [line.accountId, line.amount]));
+
+Deno.test("151 gross separates sales123, shipping15 and tax13 without invoice FX conversion", () => {
+ assertEquals(calculateSalesPostingAmounts(fixture().line), {
+ salesRevenueBase: 123,
+ shippingRevenueBase: 15,
+ salesTaxBase: 13,
+ grossReceivableBase: 151,
+ });
+ const result = buildSalesPostingLines(fixture());
+ assertEquals(byAccount(result), {
+ sales: 123,
+ shipping: 15,
+ tax: 13,
+ ar: 151,
+ });
+ assertEquals(result.signedDebitTotal, 0);
+ assertEquals(round(result.amounts.grossReceivableBase * 0.8, 2), 120.8);
+});
+
+Deno.test("all supported item line types use the actual charge builder and preserve metadata/references", () => {
+ for (
+ const invoiceLineType of [
+ "Part",
+ "Service",
+ "Consumable",
+ "Fixture",
+ "Material",
+ "Tool",
+ ]
+ ) {
+ const input = fixture();
+ input.line.invoiceLineType = invoiceLineType;
+ const result = buildSalesPostingLines(input);
+ assertEquals(byAccount(result), {
+ sales: 123,
+ shipping: 15,
+ tax: 13,
+ ar: 151,
+ });
+ assertEquals(result.metadata.length, result.lines.length);
+ for (const [index, line] of result.lines.entries()) {
+ assertEquals(result.metadata[index], input.metadata);
+ assertEquals(line.documentId, "invoice");
+ assertEquals(line.documentLineReference, "sales-invoice:source-line");
+ assertEquals(line.journalLineReference, "journal-reference");
+ assertEquals(line.externalDocumentId, "customer-reference");
+ assertEquals(line.companyId, "company");
+ assertEquals(line.documentType, "Invoice");
+ }
+ assertEquals(
+ result.lines.find((line) => line.accountId === "ar")
+ ?.intercompanyPartnerId,
+ "partner",
+ );
+ }
+});
+
+Deno.test("zero tax/shipping need no mappings and no empty rows are emitted", () => {
+ const input = fixture();
+ input.line = { invoiceLineType: "Service", quantity: 1, unitPrice: 100 };
+ input.accounts.shipping = null;
+ input.accounts.tax = null;
+ const result = buildSalesPostingLines(input);
+ assertEquals(byAccount(result), { sales: 100, ar: 100 });
+ input.line.quantity = 0;
+ input.accounts = {};
+ assertEquals(buildSalesPostingLines(input).lines, []);
+});
+
+Deno.test("header-only and comment lines do not invent merchandise revenue", () => {
+ const input = fixture();
+ input.line = {
+ invoiceLineType: "Service",
+ quantity: 0,
+ allocatedHeaderShipping: 5,
+ };
+ input.accounts.sales = null;
+ input.accounts.tax = null;
+ assertEquals(byAccount(buildSalesPostingLines(input)), {
+ shipping: 5,
+ ar: 5,
+ });
+ input.line.invoiceLineType = "Comment";
+ assertEquals(buildSalesPostingLines(input).lines, []);
+ input.line.invoiceLineType = "G/L Account";
+ assertThrows(() => buildSalesPostingLines(input), Error, "Unsupported");
+});
+
+Deno.test("header allocation preserves current pretax weights, excludes comments and assigns residual deterministically", () => {
+ const lines = [
+ {
+ id: "b",
+ invoiceLineType: "Service",
+ quantity: 1,
+ unitPrice: 10,
+ nonTaxableAddOnCost: 1000,
+ },
+ { id: "comment", invoiceLineType: "Comment", quantity: 1, unitPrice: 999 },
+ {
+ id: "a",
+ invoiceLineType: "Part",
+ quantity: 1,
+ unitPrice: 5,
+ shippingCost: 2,
+ addOnCost: 3,
+ },
+ { id: "c", invoiceLineType: "Tool", quantity: 1, unitPrice: 10 },
+ ];
+ const allocations = allocateSalesHeaderShipping(lines, 1);
+ assertEquals([...allocations], [["a", 0.33333], ["b", 0.33333], [
+ "c",
+ 0.33334,
+ ]]);
+ assertEquals([...allocateSalesHeaderShipping([...lines].reverse(), 1)], [
+ ...allocations,
+ ]);
+ assertEquals(
+ round([...allocations.values()].reduce((sum, value) => sum + value, 0)),
+ 1,
+ );
+ const zeros = lines.filter((line) => line.invoiceLineType !== "Comment").map((
+ line,
+ ) => ({ ...line, quantity: 0, shippingCost: 0, addOnCost: 0 }));
+ assertEquals([...allocateSalesHeaderShipping(zeros, 1)], [...allocations]);
+ assertThrows(() => allocateSalesHeaderShipping([], 1), Error, "shipping");
+});
+
+Deno.test("fractional values retain raw tax bases and reconcile only internal rounding residue", () => {
+ const input = fixture();
+ input.line = {
+ invoiceLineType: "Service",
+ quantity: 0.5,
+ unitPrice: 0.00001,
+ shippingCost: 0.000006,
+ taxPercent: 0.1,
+ };
+ const raw = calculateSalesPostingAmounts(input.line);
+ assertEquals(raw.salesRevenueBase, 0.000005);
+ assertEquals(raw.shippingRevenueBase, 0.000006);
+ assertEquals(round(raw.salesTaxBase, 10), 0.0000011);
+ const result = buildSalesPostingLines(input);
+ assertEquals(
+ result.lines.find((line) => line.accountId === "ar")?.amount,
+ round(raw.grossReceivableBase),
+ );
+ assertEquals(result.signedDebitTotal, 0);
+ assertEquals(result.lines.every((line) => line.amount !== 0), true);
+ assertEquals(
+ round(
+ result.lines.filter((line) => line.accountId !== "ar").reduce(
+ (sum, line) => sum + line.amount,
+ 0,
+ ),
+ ),
+ round(raw.grossReceivableBase),
+ );
+});
+
+for (const mode of ["direct", "shipment"] as const) {
+ Deno.test(`${mode} asset sale keeps proceeds100, shipping10, tax11 and gain30 with gross AR121`, () => {
+ const input = fixture();
+ input.line = {
+ invoiceLineType: "Fixed Asset",
+ quantity: 1,
+ unitPrice: 100,
+ shippingCost: 10,
+ taxPercent: 0.1,
+ };
+ input.accounts.sales = null;
+ input.metadata.itemId = null;
+ input.metadata.fixedAssetClassId = "asset-class";
+ const disposalAccounts = {
+ gainAccount: account("gain", "Revenue"),
+ lossAccount: account("loss", "Expense"),
+ };
+ input.disposal = mode === "direct"
+ ? {
+ mode,
+ acquisitionCost: 100,
+ accumulatedDepreciation: 30,
+ assetAccount: account("asset", "Asset"),
+ accumulatedDepreciationAccount: account("depreciation", "Asset"),
+ ...disposalAccounts,
+ }
+ : {
+ mode,
+ netBookValue: 70,
+ clearingAccount: account("clearing", "Expense"),
+ ...disposalAccounts,
+ };
+ const result = buildSalesPostingLines(input);
+ assertEquals(result.saleProceeds, 100);
+ assertEquals(result.netBookValue, 70);
+ assertEquals(result.gainLoss, 30);
+ assertEquals(
+ byAccount(result),
+ mode === "direct"
+ ? {
+ shipping: 10,
+ tax: 11,
+ ar: 121,
+ depreciation: 30,
+ asset: -100,
+ gain: 30,
+ }
+ : { shipping: 10, tax: 11, ar: 121, clearing: -70, gain: 30 },
+ );
+ assertEquals(result.signedDebitTotal, 0);
+ assertEquals(
+ result.metadata.every((meta) =>
+ meta.fixedAssetClassId === "asset-class" && meta.itemId === null
+ ),
+ true,
+ );
+
+ });
+}
+
+Deno.test("direct disposal retains one-asset quantities independently of invoice quantity", () => {
+ const input = fixture();
+ input.line = {
+ invoiceLineType: "Fixed Asset",
+ quantity: 2,
+ unitPrice: 50,
+ shippingCost: 10,
+ taxPercent: 0.1,
+ };
+ input.disposal = {
+ mode: "direct",
+ acquisitionCost: 90,
+ accumulatedDepreciation: 20,
+ assetAccount: account("asset", "Asset"),
+ accumulatedDepreciationAccount: account("depreciation", "Asset"),
+ gainAccount: account("gain", "Revenue"),
+ };
+ const result = buildSalesPostingLines(input);
+ assertEquals(
+ Object.fromEntries(
+ result.lines.map((line) => [line.accountId, line.quantity]),
+ ),
+ {
+ shipping: 2,
+ tax: 2,
+ ar: 2,
+ depreciation: 1,
+ asset: 1,
+ gain: 1,
+ },
+ );
+});
+
+Deno.test("asset disposal loss uses the expense account and zero gain requires neither gain/loss mapping", () => {
+ const input = fixture();
+ input.line = { invoiceLineType: "Fixed Asset", quantity: 1, unitPrice: 50 };
+ input.disposal = {
+ mode: "shipment",
+ netBookValue: 70,
+ clearingAccount: account("clearing", "Expense"),
+ lossAccount: account("loss", "Expense"),
+ };
+ const loss = buildSalesPostingLines(input);
+ assertEquals(byAccount(loss), { ar: 50, clearing: -70, loss: 20 });
+ assertEquals(loss.gainLoss, -20);
+ input.line.unitPrice = 70;
+ input.disposal.lossAccount = null;
+ assertEquals(byAccount(buildSalesPostingLines(input)), {
+ ar: 70,
+ clearing: -70,
+ });
+});
+
+Deno.test("nonzero required accounts must be valid active leaves in the company group with the correct class", () => {
+ for (const key of ["sales", "shipping", "tax", "receivables"] as const) {
+ const input = fixture();
+ input.accounts[key] = null;
+ assertThrows(() => buildSalesPostingLines(input), Error, "account");
+ for (
+ const changes of [{ class: "Equity" }, { active: false }, {
+ isGroup: true,
+ }, { companyGroupId: "other-group" }]
+ ) {
+ const invalid = fixture();
+ invalid.accounts[key] = { ...invalid.accounts[key]!, ...changes };
+ assertThrows(() => buildSalesPostingLines(invalid), Error, "account");
+ }
+ }
+ const sameSalesShipping = fixture();
+ sameSalesShipping.accounts.shipping = sameSalesShipping.accounts.sales;
+ assertThrows(
+ () => buildSalesPostingLines(sameSalesShipping),
+ Error,
+ "distinct",
+ );
+});
+
+Deno.test("seller matching basis converts raw base once and continues excluding add-ons, tax and header shipping", () => {
+ const lines = [fixture().line, {
+ invoiceLineType: "Comment",
+ quantity: 100,
+ unitPrice: 100,
+ }];
+ assertEquals(calculateSalesIntercompanyAmount(lines, 0.8), 88);
+ assertEquals(calculateSalesIntercompanyAmount(lines, 1.1), 121);
+});
+
+Deno.test("seller matching basis rounds at SCALE so it can equal the buyer's half exactly", () => {
+ // generate_intercompany_matches pairs the two halves on `src.amount =
+ // tgt.amount` with no tolerance, and the buyer records its half with
+ // round() at internal SCALE. A document amount carrying sub-cent digits
+ // (100.005 x 3) must therefore survive here undisturbed — rounding it at
+ // settlement precision would store 300.02 against the buyer's 300.015 and
+ // leave the trade permanently Unmatched.
+ const lines = [{
+ invoiceLineType: "Service",
+ quantity: 3,
+ unitPrice: 100.005,
+ }];
+ const seller = calculateSalesIntercompanyAmount(lines, 1);
+ assertEquals(seller, 300.015);
+ // The buyer's half, as post-purchase-invoice computes it.
+ assertEquals(seller, round(3 * 100.005));
+});
+
+Deno.test("actual multiline charge rows feed complete IC control and shipping revenue capture", () => {
+ const first = buildSalesPostingLines(fixture());
+ const secondInput = fixture();
+ secondInput.line = { invoiceLineType: "Part", quantity: 1, unitPrice: 50 };
+ secondInput.metadata.itemId = "second-item";
+ const second = buildSalesPostingLines(secondInput);
+ const captures = classifyIntercompanyPostingLines(
+ [...first.lines, ...second.lines].map((line, index) => ({
+ ...line,
+ id: `posted-${index}`,
+ })),
+ [...first.metadata, ...second.metadata],
+ { controlAccountId: "ar", revenueAccountIds: ["sales", "shipping"] },
+ );
+ assertEquals(
+ captures.filter((row) => row.role === "Control").map((
+ row,
+ ) => [row.amount, row.itemId]),
+ [[151, "item"], [50, "second-item"]],
+ );
+ assertEquals(
+ captures.filter((row) => row.role === "Revenue").reduce(
+ (sum, row) => sum + row.amount,
+ 0,
+ ),
+ 188,
+ );
+ assertEquals(captures.some((row) => row.accountId === "tax"), false);
+});
+
+Deno.test("nonfinite component arithmetic is refused before any charge rows can be posted", () => {
+ for (
+ const key of [
+ "quantity",
+ "unitPrice",
+ "shippingCost",
+ "addOnCost",
+ "nonTaxableAddOnCost",
+ "taxPercent",
+ "allocatedHeaderShipping",
+ ] as const
+ ) {
+ assertThrows(() =>
+ calculateSalesPostingAmounts({ ...fixture().line, [key]: Number.NaN })
+ );
+ }
+ assertThrows(() =>
+ calculateSalesPostingAmounts({
+ quantity: Number.MAX_VALUE,
+ unitPrice: Number.MAX_VALUE,
+ })
+ );
+});
diff --git a/packages/database/supabase/functions/shared/sales-posting-amounts.ts b/packages/database/supabase/functions/shared/sales-posting-amounts.ts
new file mode 100644
index 0000000000..05f6b4dc44
--- /dev/null
+++ b/packages/database/supabase/functions/shared/sales-posting-amounts.ts
@@ -0,0 +1,426 @@
+import { credit, debit } from "../lib/utils.ts";
+import { toBaseAmount, toDocumentAmount } from "./accounting-currency.ts";
+import { assertBalanced, EPSILON, round, SCALE } from "./precision.ts";
+
+export type SalesPostingAmountsInput = {
+ quantity: number;
+ unitPrice?: number | null;
+ shippingCost?: number | null;
+ addOnCost?: number | null;
+ nonTaxableAddOnCost?: number | null;
+ taxPercent?: number | null;
+ allocatedHeaderShipping?: number;
+};
+
+export type SalesPostingAmounts = {
+ salesRevenueBase: number;
+ shippingRevenueBase: number;
+ salesTaxBase: number;
+ grossReceivableBase: number;
+};
+
+export type SalesPostingAccount = {
+ id: string;
+ class: string | null;
+ active: boolean;
+ isGroup: boolean;
+ companyGroupId: string;
+};
+
+export type SalesPostingMetadata = {
+ customerTypeId: string | null;
+ itemPostingGroupId: string | null;
+ itemId: string | null;
+ locationId: string | null;
+ costCenterId: string | null;
+ fixedAssetClassId: string | null;
+};
+
+export type SalesPostingJournalLine = {
+ accountId: string;
+ description: string;
+ amount: number;
+ quantity: number;
+ documentType: "Invoice";
+ documentId: string;
+ externalDocumentId?: string | null;
+ documentLineReference?: string | null;
+ journalLineReference: string;
+ intercompanyPartnerId?: string | null;
+ companyId: string;
+};
+
+type DisposalAccounts = {
+ gainAccount?: SalesPostingAccount | null;
+ lossAccount?: SalesPostingAccount | null;
+};
+
+export type SalesPostingDisposal =
+ & DisposalAccounts
+ & ({
+ mode: "direct";
+ acquisitionCost: number;
+ accumulatedDepreciation: number;
+ assetAccount?: SalesPostingAccount | null;
+ accumulatedDepreciationAccount?: SalesPostingAccount | null;
+ } | {
+ mode: "shipment";
+ netBookValue: number;
+ clearingAccount?: SalesPostingAccount | null;
+ });
+
+export type BuildSalesPostingLinesInput = {
+ line: SalesPostingAmountsInput & { invoiceLineType: string };
+ context: {
+ companyId: string;
+ companyGroupId: string;
+ documentId: string;
+ externalDocumentId?: string | null;
+ documentLineReference?: string | null;
+ journalLineReference: string;
+ intercompanyPartnerId?: string | null;
+ };
+ accounts: {
+ receivables?: SalesPostingAccount | null;
+ sales?: SalesPostingAccount | null;
+ shipping?: SalesPostingAccount | null;
+ tax?: SalesPostingAccount | null;
+ };
+ metadata: SalesPostingMetadata;
+ disposal?: SalesPostingDisposal;
+};
+
+function finite(amount: number, label: string): number {
+ if (!Number.isFinite(amount)) throw new Error(`${label} must be finite`);
+ return amount;
+}
+
+/** Raw arithmetic shared by ledger and provider boundaries; prices are already base. */
+export function calculateSalesPostingAmounts(
+ input: SalesPostingAmountsInput,
+): SalesPostingAmounts {
+ const merchandise = finite(input.quantity, "Quantity") *
+ finite(input.unitPrice ?? 0, "Unit price");
+ const shipping = finite(input.shippingCost ?? 0, "Line shipping");
+ const addOn = finite(input.addOnCost ?? 0, "Taxable add-on");
+ const nonTaxableAddOn = finite(
+ input.nonTaxableAddOnCost ?? 0,
+ "Non-taxable add-on",
+ );
+ const taxPercent = finite(input.taxPercent ?? 0, "Tax rate");
+ const salesRevenueBase = finite(
+ merchandise + addOn + nonTaxableAddOn,
+ "Sales revenue",
+ );
+ const shippingRevenueBase = finite(
+ shipping + finite(input.allocatedHeaderShipping ?? 0, "Header shipping"),
+ "Shipping revenue",
+ );
+ const salesTaxBase = finite(
+ (merchandise + shipping + addOn) * taxPercent,
+ "Sales tax",
+ );
+ return {
+ salesRevenueBase,
+ shippingRevenueBase,
+ salesTaxBase,
+ grossReceivableBase: finite(
+ salesRevenueBase + shippingRevenueBase + salesTaxBase,
+ "Gross receivable",
+ ),
+ };
+}
+
+export function allocateSalesHeaderShipping(
+ lines: Array<
+ SalesPostingAmountsInput & { id: string; invoiceLineType: string }
+ >,
+ headerShipping: number,
+): Map<string, number> {
+ const header = toBaseAmount(headerShipping, 1);
+ const eligible = lines.filter((line) => line.invoiceLineType !== "Comment")
+ .sort((a, b) => a.id < b.id ? -1 : a.id > b.id ? 1 : 0);
+ if (eligible.length === 0 && header !== 0) {
+ throw new Error("Header shipping requires a postable invoice line");
+ }
+ const weights = eligible.map((line) =>
+ finite(
+ finite(line.quantity, "Quantity") *
+ finite(line.unitPrice ?? 0, "Unit price") +
+ finite(line.shippingCost ?? 0, "Line shipping") +
+ finite(line.addOnCost ?? 0, "Taxable add-on"),
+ "Header shipping weight",
+ )
+ );
+ const totalWeight = finite(
+ weights.reduce((sum, weight) => sum + weight, 0),
+ "Total shipping weight",
+ );
+ let allocated = 0;
+ return new Map(eligible.map((line, index) => {
+ const amount = index === eligible.length - 1
+ ? round(header - allocated)
+ : toBaseAmount(
+ header * (totalWeight === 0
+ ? 1 / eligible.length
+ : weights[index]! / totalWeight),
+ 1,
+ );
+ allocated = round(allocated + amount);
+ return [line.id, amount];
+ }));
+}
+
+export function calculateSalesIntercompanyAmount(
+ lines: Array<SalesPostingAmountsInput & { invoiceLineType: string }>,
+ exchangeRate: number,
+): number {
+ // Preserve the buyer-compatible matching basis: exclude add-ons, tax and header shipping.
+ const base = lines.reduce(
+ (sum, line) =>
+ line.invoiceLineType === "Comment" ? sum : sum +
+ finite(line.quantity, "Quantity") *
+ finite(line.unitPrice ?? 0, "Unit price") +
+ finite(line.shippingCost ?? 0, "Line shipping"),
+ 0,
+ );
+ // The buyer records its half with round() at internal SCALE
+ // (post-purchase-invoice), and generate_intercompany_matches pairs the two
+ // sides on exact NUMERIC equality with no tolerance. Rounding this half at
+ // settlement precision instead would leave every trade whose document amount
+ // carries sub-cent digits permanently Unmatched, so eliminations would never
+ // run. This is a matching key, not a settlement amount: both halves round at
+ // SCALE.
+ return toDocumentAmount(base, exchangeRate, SCALE);
+}
+
+export function buildSalesPostingLines(input: BuildSalesPostingLinesInput): {
+ lines: SalesPostingJournalLine[];
+ metadata: SalesPostingMetadata[];
+ amounts: SalesPostingAmounts;
+ saleProceeds: number;
+ netBookValue: number | null;
+ gainLoss: number | null;
+ signedDebitTotal: number;
+} {
+ const { line, context, accounts, disposal } = input;
+ const empty = {
+ salesRevenueBase: 0,
+ shippingRevenueBase: 0,
+ salesTaxBase: 0,
+ grossReceivableBase: 0,
+ };
+ if (line.invoiceLineType === "Comment") {
+ return {
+ lines: [],
+ metadata: [],
+ amounts: empty,
+ saleProceeds: 0,
+ netBookValue: null,
+ gainLoss: null,
+ signedDebitTotal: 0,
+ };
+ }
+ if (
+ ![
+ "Part",
+ "Service",
+ "Consumable",
+ "Fixture",
+ "Material",
+ "Tool",
+ "Fixed Asset",
+ ].includes(line.invoiceLineType)
+ ) {
+ throw new Error(`Unsupported invoice line type: ${line.invoiceLineType}`);
+ }
+ const isAsset = line.invoiceLineType === "Fixed Asset";
+ if (isAsset && !disposal) {
+ throw new Error("Fixed asset posting requires disposal facts");
+ }
+ const raw = calculateSalesPostingAmounts(line);
+ const componentKeys = [
+ "salesRevenueBase",
+ "shippingRevenueBase",
+ "salesTaxBase",
+ ] as const;
+ const amounts: SalesPostingAmounts = {
+ salesRevenueBase: toBaseAmount(raw.salesRevenueBase, 1),
+ shippingRevenueBase: toBaseAmount(raw.shippingRevenueBase, 1),
+ salesTaxBase: toBaseAmount(raw.salesTaxBase, 1),
+ grossReceivableBase: toBaseAmount(raw.grossReceivableBase, 1),
+ };
+ const residual = round(
+ amounts.grossReceivableBase -
+ componentKeys.reduce((sum, key) => sum + amounts[key], 0),
+ );
+ // Only reconcile the rounding of these three components and their total.
+ // No rounding account or arbitrary balancing entry can hide an economic mismatch.
+ const roundingEnvelope = (componentKeys.length + 1) / (2 * 10 ** SCALE) +
+ EPSILON;
+ if (Math.abs(residual) > roundingEnvelope) {
+ throw new Error("Sales component rounding exceeds its precision envelope");
+ }
+ if (residual !== 0) {
+ const recipient = [...componentKeys].sort((a, b) =>
+ Math.abs(raw[b]) - Math.abs(raw[a])
+ )[0]!;
+ amounts[recipient] = round(amounts[recipient] + residual);
+ }
+ if (
+ amounts.shippingRevenueBase !== 0 &&
+ accounts.shipping?.id === accounts.sales?.id && accounts.shipping?.id
+ ) {
+ throw new Error("Shipping revenue and sales accounts must be distinct");
+ }
+
+ const lines: SalesPostingJournalLine[] = [];
+ const metadata: SalesPostingMetadata[] = [];
+ let signedDebitTotal = 0;
+ const push = (
+ account: SalesPostingAccount | null | undefined,
+ accountClass: "Asset" | "Revenue" | "Liability" | "Expense",
+ side: "debit" | "credit",
+ amount: number,
+ description: string,
+ isControl = false,
+ quantity = line.quantity,
+ ) => {
+ const baseAmount = toBaseAmount(amount, 1);
+ if (baseAmount === 0) return;
+ if (
+ !account || account.class !== accountClass || !account.active ||
+ account.isGroup || account.companyGroupId !== context.companyGroupId
+ ) {
+ throw new Error(
+ `Invalid or missing ${description} account; expected an active ${accountClass} leaf in this company group`,
+ );
+ }
+ const naturalClass = accountClass.toLowerCase() as
+ | "asset"
+ | "revenue"
+ | "liability"
+ | "expense";
+ lines.push({
+ accountId: account.id,
+ description,
+ amount: side === "debit"
+ ? debit(naturalClass, baseAmount)
+ : credit(naturalClass, baseAmount),
+ quantity: round(quantity),
+ documentType: "Invoice",
+ documentId: context.documentId,
+ externalDocumentId: context.externalDocumentId,
+ documentLineReference: context.documentLineReference,
+ journalLineReference: context.journalLineReference,
+ ...(isControl
+ ? { intercompanyPartnerId: context.intercompanyPartnerId }
+ : {}),
+ companyId: context.companyId,
+ });
+ metadata.push({ ...input.metadata });
+ signedDebitTotal += side === "debit" ? baseAmount : -baseAmount;
+ };
+ if (!isAsset) {
+ push(
+ accounts.sales,
+ "Revenue",
+ "credit",
+ amounts.salesRevenueBase,
+ "Sales Account",
+ );
+ }
+ push(
+ accounts.shipping,
+ "Revenue",
+ "credit",
+ amounts.shippingRevenueBase,
+ "Shipping Revenue",
+ );
+ push(
+ accounts.tax,
+ "Liability",
+ "credit",
+ amounts.salesTaxBase,
+ "Sales Tax Payable",
+ );
+ push(
+ accounts.receivables,
+ "Asset",
+ "debit",
+ amounts.grossReceivableBase,
+ context.intercompanyPartnerId ? "IC Receivables" : "Accounts Receivable",
+ true,
+ );
+
+ let netBookValue: number | null = null;
+ let gainLoss: number | null = null;
+ if (isAsset && disposal) {
+ if (disposal.mode === "direct") {
+ const cost = toBaseAmount(disposal.acquisitionCost, 1);
+ const depreciation = toBaseAmount(disposal.accumulatedDepreciation, 1);
+ netBookValue = round(cost - depreciation);
+ push(
+ disposal.accumulatedDepreciationAccount,
+ "Asset",
+ "debit",
+ depreciation,
+ "Clear accumulated depreciation",
+ false,
+ 1,
+ );
+ push(
+ disposal.assetAccount,
+ "Asset",
+ "credit",
+ cost,
+ "Remove asset at cost",
+ false,
+ 1,
+ );
+ } else {
+ netBookValue = toBaseAmount(disposal.netBookValue, 1);
+ push(
+ disposal.clearingAccount,
+ "Expense",
+ "credit",
+ netBookValue,
+ "Clear disposal clearing",
+ );
+ }
+ gainLoss = round(amounts.salesRevenueBase - netBookValue);
+ if (gainLoss > 0) {
+ push(
+ disposal.gainAccount,
+ "Revenue",
+ "credit",
+ gainLoss,
+ "Gain on disposal",
+ false,
+ disposal.mode === "direct" ? 1 : line.quantity,
+ );
+ }
+ if (gainLoss < 0) {
+ push(
+ disposal.lossAccount,
+ "Expense",
+ "debit",
+ -gainLoss,
+ "Loss on disposal",
+ false,
+ disposal.mode === "direct" ? 1 : line.quantity,
+ );
+ }
+ }
+ signedDebitTotal = round(signedDebitTotal);
+ assertBalanced(signedDebitTotal, 0, EPSILON, "Sales invoice charge journal");
+ return {
+ lines,
+ metadata,
+ amounts,
+ saleProceeds: amounts.salesRevenueBase,
+ netBookValue,
+ gainLoss,
+ signedDebitTotal,
+ };
+}
diff --git a/packages/database/supabase/migrations/20260908021155_accounting_posting_corrections.sql b/packages/database/supabase/migrations/20260908021155_accounting_posting_corrections.sql
new file mode 100644
index 0000000000..534bb010de
--- /dev/null
+++ b/packages/database/supabase/migrations/20260908021155_accounting_posting_corrections.sql
@@ -0,0 +1,203 @@
+-- Separate shipping revenue and retain exact settlement funding principal.
+
+-- Wrapped in an explicit transaction: the migration runner applies statements in
+-- autocommit, but `LOCK TABLE` and the `CREATE TEMP TABLE ... ON COMMIT DROP`
+-- resolution below (plus its dependent INSERT/UPDATE) require a single
+-- transaction block. Same pattern as 20250204164256_numeric-increase-2.sql.
+BEGIN;
+
+ALTER TABLE "accountDefault"
+ ADD COLUMN IF NOT EXISTS "salesShippingRevenueAccount" TEXT;
+ALTER TABLE "invoiceSettlement"
+ ADD COLUMN IF NOT EXISTS "sourcePaymentId" TEXT,
+ ADD COLUMN IF NOT EXISTS "sourceAmount" NUMERIC;
+ALTER TABLE "invoiceSettlement"
+ ALTER COLUMN "fxGainLossAmount" DROP EXPRESSION IF EXISTS;
+ALTER TABLE "invoiceSettlement"
+ ALTER COLUMN "fxGainLossAmount" SET DEFAULT 0;
+-- The dropped expression could never yield NULL (all three of its inputs are
+-- NOT NULL), so the column stays NOT NULL now that writers supply it. Without
+-- this the generated Insert type admits null, and every reader sums the column
+-- bare -- SUM("appliedAmount" + "fxGainLossAmount") -- so one null row would
+-- erase that settlement's principal from the tie-outs and the aging reports.
+DO $fx_gain_loss_not_null$
+BEGIN
+ IF EXISTS (
+ SELECT 1 FROM pg_attribute
+ WHERE attrelid = '"invoiceSettlement"'::regclass
+ AND attname = 'fxGainLossAmount'
+ AND attnum > 0 AND NOT attisdropped AND NOT attnotnull
+ ) THEN
+ UPDATE "invoiceSettlement" SET "fxGainLossAmount" = 0
+ WHERE "fxGainLossAmount" IS NULL;
+ ALTER TABLE "invoiceSettlement" ALTER COLUMN "fxGainLossAmount" SET NOT NULL;
+ END IF;
+END;
+$fx_gain_loss_not_null$;
+ALTER TABLE "invoiceSettlement"
+ DROP CONSTRAINT IF EXISTS "invoiceSettlement_anyComponent_check";
+ALTER TABLE "invoiceSettlement"
+ ADD CONSTRAINT "invoiceSettlement_anyComponent_check" CHECK (
+ "appliedAmount" + "discountAmount" + "writeOffAmount" > 0
+ OR COALESCE("sourceAmount", 0) > 0
+ );
+
+DO $constraints$
+BEGIN
+ IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conrelid='"accountDefault"'::regclass AND conname='accountDefault_salesShippingRevenueAccount_fkey') THEN
+ ALTER TABLE "accountDefault" ADD CONSTRAINT "accountDefault_salesShippingRevenueAccount_fkey"
+ FOREIGN KEY ("salesShippingRevenueAccount") REFERENCES "account"(id)
+ ON DELETE RESTRICT ON UPDATE CASCADE;
+ END IF;
+ IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conrelid='"payment"'::regclass AND conname='payment_id_companyId_key') THEN
+ ALTER TABLE "payment" ADD CONSTRAINT "payment_id_companyId_key" UNIQUE (id, "companyId");
+ END IF;
+ IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conrelid='"invoiceSettlement"'::regclass AND conname='invoiceSettlement_sourcePaymentId_companyId_fkey') THEN
+ ALTER TABLE "invoiceSettlement" ADD CONSTRAINT "invoiceSettlement_sourcePaymentId_companyId_fkey"
+ FOREIGN KEY ("sourcePaymentId", "companyId") REFERENCES "payment"(id, "companyId")
+ ON DELETE RESTRICT ON UPDATE CASCADE;
+ END IF;
+ -- Dropped and re-added rather than guarded on existence: the predicate below
+ -- was strengthened after the first cut of this migration, and an IF NOT EXISTS
+ -- guard would leave the weaker version in place on any database that already
+ -- ran it.
+ ALTER TABLE "invoiceSettlement"
+ DROP CONSTRAINT IF EXISTS "invoiceSettlement_sourcePaymentId_check";
+ ALTER TABLE "invoiceSettlement" ADD CONSTRAINT "invoiceSettlement_sourcePaymentId_check"
+ CHECK ("sourcePaymentId" IS NULL OR (
+ "paymentId" IS NOT NULL AND "memoId" IS NULL AND "sourcePaymentId" <> "paymentId"
+ -- A source-linked row MUST carry its document principal. Without it
+ -- `remainingFundingSources` throws "Settlement is missing its document
+ -- principal" and the party's remaining credit becomes uncomputable —
+ -- the row is unreadable rather than merely imprecise. Legacy rows
+ -- (sourcePaymentId IS NULL) keep a NULL sourceAmount and stay valid.
+ AND "sourceAmount" IS NOT NULL
+ ));
+ IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conrelid='"invoiceSettlement"'::regclass AND conname='invoiceSettlement_sourceAmount_check') THEN
+ ALTER TABLE "invoiceSettlement" ADD CONSTRAINT "invoiceSettlement_sourceAmount_check"
+ CHECK ("sourceAmount" IS NULL OR (
+ "sourceAmount" >= 0 AND "sourceAmount" NOT IN ('NaN'::numeric, 'Infinity'::numeric, '-Infinity'::numeric)
+ ));
+ END IF;
+END;
+$constraints$;
+
+CREATE INDEX IF NOT EXISTS "accountDefault_salesShippingRevenueAccount_idx"
+ ON "accountDefault"("salesShippingRevenueAccount");
+CREATE INDEX IF NOT EXISTS "invoiceSettlement_sourcePaymentId_companyId_idx"
+ ON "invoiceSettlement"("sourcePaymentId", "companyId") WHERE "sourcePaymentId" IS NOT NULL;
+
+-- Serialize chart/default resolution while choosing unused numbers and IDs.
+LOCK TABLE "account", "accountDefault" IN SHARE ROW EXCLUSIVE MODE;
+
+DO $existing_defaults$
+DECLARE bad text;
+BEGIN
+ SELECT string_agg(ad."companyId", ', ' ORDER BY ad."companyId") INTO bad
+ FROM "accountDefault" ad
+ JOIN "company" c ON c.id=ad."companyId"
+ LEFT JOIN "account" a ON a.id=ad."salesShippingRevenueAccount"
+ WHERE ad."salesShippingRevenueAccount" IS NOT NULL AND (
+ a.id IS NULL OR a."companyGroupId" IS DISTINCT FROM c."companyGroupId"
+ OR a.active IS DISTINCT FROM true OR a."isGroup" IS DISTINCT FROM false
+ OR a.class IS DISTINCT FROM 'Revenue' OR a."incomeBalance" IS DISTINCT FROM 'Income Statement'
+ OR a.id=ad."salesAccount"
+ );
+ IF bad IS NOT NULL THEN RAISE EXCEPTION 'Invalid shipping defaults for companies: %', bad; END IF;
+END;
+$existing_defaults$;
+
+CREATE TEMP TABLE accounting_shipping_resolution ON COMMIT DROP AS
+WITH groups AS (
+ SELECT DISTINCT c."companyGroupId"
+ FROM "company" c JOIN "accountDefault" ad ON ad."companyId"=c.id
+ WHERE ad."salesShippingRevenueAccount" IS NULL
+), sales_parents AS (
+ SELECT c."companyGroupId", min(p.id) AS parent_id, count(DISTINCT p.id) AS parent_count
+ FROM "company" c
+ JOIN "accountDefault" ad ON ad."companyId"=c.id
+ JOIN "account" sales ON sales.id=ad."salesAccount" AND sales."companyGroupId"=c."companyGroupId"
+ JOIN "account" p ON p.id=sales."parentId" AND p."companyGroupId"=c."companyGroupId"
+ WHERE p.active AND p."isGroup" AND p.class='Revenue'
+ AND p."incomeBalance"='Income Statement' AND p."accountType"='Income'
+ GROUP BY c."companyGroupId"
+)
+SELECT g."companyGroupId",
+ CASE WHEN named_parent.id IS NOT NULL THEN named_parent.id
+ WHEN sp.parent_count=1 THEN sp.parent_id END AS parent_id,
+ named_parent.id IS NOT NULL AND (
+ named_parent.active IS DISTINCT FROM true OR named_parent.class IS DISTINCT FROM 'Revenue'
+ OR named_parent."incomeBalance" IS DISTINCT FROM 'Income Statement'
+ OR named_parent."accountType" IS DISTINCT FROM 'Income'
+ ) AS invalid_named_parent,
+ existing.id AS existing_id,
+ COALESCE(existing.id, id('acct')) AS account_id,
+ COALESCE(existing.number, free_number.number) AS account_number
+FROM groups g
+LEFT JOIN "account" named_parent ON named_parent."companyGroupId"=g."companyGroupId"
+ AND named_parent.name='Revenue' AND named_parent."isGroup"=true
+LEFT JOIN sales_parents sp ON sp."companyGroupId"=g."companyGroupId"
+LEFT JOIN "account" existing ON existing."companyGroupId"=g."companyGroupId"
+ AND existing.name='Shipping Revenue' AND existing."isGroup"=false
+LEFT JOIN LATERAL (
+ -- Starts at 4050: 4040 is reserved for "Customer Payment Discounts", which
+ -- the later 20260909014032 migration renumbers 7030 into. That renumber is
+ -- guarded by NOT EXISTS, so claiming 4040 here would silently suppress it.
+ SELECT n::text AS number FROM generate_series(4050,4990,10) n
+ WHERE NOT EXISTS (SELECT 1 FROM "account" a
+ WHERE a."companyGroupId"=g."companyGroupId" AND a.number=n::text)
+ ORDER BY n LIMIT 1
+) free_number ON true;
+
+DO $resolved$
+DECLARE bad text;
+BEGIN
+ SELECT string_agg(r."companyGroupId", ', ' ORDER BY r."companyGroupId") INTO bad
+ FROM accounting_shipping_resolution r
+ LEFT JOIN "account" a ON a.id=r.existing_id
+ WHERE r.parent_id IS NULL OR r.invalid_named_parent IS TRUE
+ OR (r.existing_id IS NULL AND r.account_number IS NULL)
+ OR EXISTS (
+ SELECT 1 FROM "account" conflicting
+ WHERE conflicting."companyGroupId"=r."companyGroupId"
+ AND conflicting.name='Shipping Revenue' AND conflicting."isGroup" IS DISTINCT FROM false
+ )
+ OR EXISTS (
+ SELECT 1 FROM "company" c JOIN "accountDefault" ad ON ad."companyId"=c.id
+ WHERE c."companyGroupId"=r."companyGroupId"
+ AND ad."salesShippingRevenueAccount" IS NULL AND ad."salesAccount"=r.account_id
+ )
+ OR (r.existing_id IS NOT NULL AND (
+ a.active IS DISTINCT FROM true OR a.class IS DISTINCT FROM 'Revenue'
+ OR a."accountType" IS DISTINCT FROM 'Income' OR a."incomeBalance" IS DISTINCT FROM 'Income Statement'
+ OR a."consolidatedRate" IS DISTINCT FROM 'Average' OR a."parentId" IS DISTINCT FROM r.parent_id
+ ));
+ IF bad IS NOT NULL THEN
+ RAISE EXCEPTION 'Cannot resolve Shipping Revenue parent/account/number for groups: %', bad;
+ END IF;
+END;
+$resolved$;
+
+INSERT INTO "account"(id,number,name,class,"accountType","incomeBalance","consolidatedRate",
+ "parentId","isGroup",active,"isSystem","companyGroupId","createdBy")
+SELECT account_id,account_number,'Shipping Revenue','Revenue','Income','Income Statement','Average',
+ parent_id,false,true,false,"companyGroupId",'system'
+FROM accounting_shipping_resolution WHERE existing_id IS NULL;
+
+UPDATE "accountDefault" ad SET "salesShippingRevenueAccount"=r.account_id,
+ "updatedBy"='system'
+FROM "company" c JOIN accounting_shipping_resolution r ON r."companyGroupId"=c."companyGroupId"
+WHERE ad."companyId"=c.id AND ad."salesShippingRevenueAccount" IS NULL;
+
+COMMENT ON COLUMN "accountDefault"."salesShippingRevenueAccount" IS 'Revenue account for shipping charged to customers; account belongs to the company group.';
+COMMENT ON COLUMN "invoiceSettlement"."sourcePaymentId" IS 'Prior posted payment supplying on-account credit; paymentId remains the applying/void owner. NULL means current payment cash.';
+COMMENT ON COLUMN "invoiceSettlement"."sourceAmount" IS 'Principal consumed in the funding source document currency, stored independently of target-base appliedAmount.';
+COMMENT ON COLUMN "invoiceSettlement"."appliedAmount" IS 'Target-document principal relieved in company base currency.';
+COMMENT ON COLUMN "invoiceSettlement"."discountAmount" IS 'Target-document discount relief in company base currency.';
+COMMENT ON COLUMN "invoiceSettlement"."writeOffAmount" IS 'Target-document write-off relief in company base currency.';
+COMMENT ON COLUMN "invoiceSettlement"."fxGainLossAmount" IS 'Server-calculated posting snapshot in company base currency: positive gain, negative loss.';
+COMMENT ON COLUMN "payment"."totalAmount" IS 'Gross cash amount in payment currency; divide by foreign-per-base exchangeRate for company base.';
+COMMENT ON COLUMN "memo"."amount" IS 'Memo amount in memo currency; divide by foreign-per-base exchangeRate for company base.';
+NOTIFY pgrst, 'reload schema';
+
+COMMIT;
diff --git a/packages/database/supabase/migrations/20260908030026_accounting_balances_and_reports.sql b/packages/database/supabase/migrations/20260908030026_accounting_balances_and_reports.sql
new file mode 100644
index 0000000000..86f9ede581
--- /dev/null
+++ b/packages/database/supabase/migrations/20260908030026_accounting_balances_and_reports.sql
@@ -0,0 +1,862 @@
+
+-- Invoice balances and reporting normalized to the document/source currency contract.
+-- Requires new sourceAmount column. No historical fallback/backfill.
+-- Currency precision is group configuration, never a hardcoded two decimals.
+-- Save/post refuse missing config/rates; the LEFT JOIN keeps operational draft rows visible.
+-- Read balances preserve sub-internal-unit foreign remainders; only ledger lines use internal rounding.
+
+-- Internal-scale rounding boundary for SQL. `no-raw-rounding` in @carbon/checks
+-- reads TypeScript only, so a bare `round(x, 5)` here is unguarded: this is the
+-- SQL twin of `round(value)` at the default SCALE in
+-- packages/database/supabase/functions/shared/precision.ts. Settlement values
+-- keep rounding at currency."decimalPlaces" and must NOT use this function.
+CREATE OR REPLACE FUNCTION accounting_round_internal(_value NUMERIC)
+RETURNS NUMERIC
+LANGUAGE SQL
+IMMUTABLE
+PARALLEL SAFE
+AS $accounting_round_internal$
+ SELECT pg_catalog.round(_value, 5)
+$accounting_round_internal$;
+
+COMMENT ON FUNCTION accounting_round_internal(NUMERIC) IS
+ 'Rounds a value-bearing number to the internal precision scale (SCALE = 5). The one named SQL boundary for internal-scale rounding; settlement amounts round at currency."decimalPlaces" instead.';
+
+-- Latest source: packages/database/supabase/migrations/20260702224219_fix-ar-ap-legacy-paid.sql
+CREATE OR REPLACE VIEW "salesInvoices" WITH(SECURITY_INVOKER=true) AS
+ WITH settled AS (
+ SELECT s."targetSalesInvoiceId", s."companyId",
+ SUM(COALESCE(s."sourceAmount", 0) + round(
+ (s."discountAmount" + s."writeOffAmount") * target."exchangeRate",
+ target_currency."decimalPlaces")) AS amount_document,
+ MAX(s."appliedDate") AS "lastSettlementDate"
+ FROM "invoiceSettlement" s
+ JOIN "salesInvoice" target ON target."id" = s."targetSalesInvoiceId"
+ AND target."companyId" = s."companyId"
+ LEFT JOIN "company" target_company ON target_company."id" = target."companyId"
+ LEFT JOIN "currency" target_currency ON target_currency."code" = target."currencyCode"
+ AND target_currency."companyGroupId" = target_company."companyGroupId"
+ LEFT JOIN "payment" p ON p."id" = s."paymentId" AND p."companyId" = s."companyId"
+ LEFT JOIN "memo" m ON m."id" = s."memoId" AND m."companyId" = s."companyId"
+ LEFT JOIN "payment" vp ON vp."id" = s."appliedViaPaymentId" AND vp."companyId" = s."companyId"
+ WHERE s."targetSalesInvoiceId" IS NOT NULL
+ AND ((s."paymentId" IS NOT NULL AND p."status" = 'Posted')
+ OR (s."memoId" IS NOT NULL AND m."status" = 'Posted'
+ AND (s."appliedViaPaymentId" IS NULL OR vp."status" = 'Posted')))
+ GROUP BY s."targetSalesInvoiceId", s."companyId"
+ )
+ SELECT
+ si."id",
+ si."invoiceId",
+ CASE
+ WHEN si."status" IN ('Draft','Pending','Voided','Return','Credit Note Issued') THEN si."status"::TEXT
+ WHEN si."status" = 'Paid' THEN 'Paid'
+ WHEN COALESCE(s.amount_document, 0) > 0
+ AND amounts.total_document > 0 AND remaining.amount_document <= 0 THEN 'Paid'
+ WHEN COALESCE(s.amount_document, 0) > 0 THEN 'Partially Paid'
+ WHEN si."dateDue" < CURRENT_DATE AND si."status" = 'Submitted' THEN 'Overdue'
+ ELSE si."status"::TEXT
+ END AS status,
+ si."customerId",
+ si."customerReference",
+ si."invoiceCustomerId",
+ si."invoiceCustomerLocationId",
+ si."invoiceCustomerContactId",
+ si."paymentTermId",
+ si."postingDate",
+ si."dateIssued",
+ si."dateDue",
+ CASE
+ WHEN si."status" = 'Paid' THEN si."datePaid"
+ WHEN COALESCE(s.amount_document, 0) > 0
+ AND amounts.total_document > 0 AND remaining.amount_document <= 0
+ THEN COALESCE(s."lastSettlementDate", si."datePaid")
+ ELSE si."datePaid"
+ END AS "datePaid",
+ si."locationId",
+ si."currencyCode",
+ COALESCE(sil."subtotal", 0) AS "subtotal",
+ si."totalDiscount",
+ COALESCE(sil."subtotal", 0) + COALESCE(sil."totalTax", 0) + COALESCE(ss."shippingCost", 0) AS "totalAmount",
+ COALESCE(sil."totalTax", 0) AS "totalTax",
+ CASE
+ WHEN si."status" = 'Paid' THEN 0
+ ELSE remaining.amount_document / NULLIF(si."exchangeRate", 0)
+ END AS "balance",
+ si."exchangeRate",
+ si."exchangeRateUpdatedAt",
+ si."opportunityId",
+ si."shipmentId",
+ si."assignee",
+ si."companyId",
+ si."customFields",
+ si."internalNotes",
+ si."externalNotes",
+ si."tags",
+ si."createdAt",
+ si."createdBy",
+ si."updatedAt",
+ si."updatedBy",
+ sil."thumbnailPath",
+ sil."itemType",
+ COALESCE(sil."subtotal", 0) + COALESCE(sil."totalTax", 0) + COALESCE(ss."shippingCost", 0) AS "invoiceTotal",
+ sil."lines",
+ pt."name" AS "paymentTermName",
+ si."status" AS "baseStatus"
+ FROM "salesInvoice" si
+ LEFT JOIN (
+ SELECT
+ sil."invoiceId",
+ MIN(CASE
+ WHEN i."thumbnailPath" IS NULL AND mu."thumbnailPath" IS NOT NULL THEN mu."thumbnailPath"
+ ELSE i."thumbnailPath"
+ END) AS "thumbnailPath",
+ SUM(
+ COALESCE(sil."quantity", 0)*COALESCE(sil."unitPrice", 0)
+ + COALESCE(sil."addOnCost", 0)
+ + COALESCE(sil."nonTaxableAddOnCost", 0)
+ + COALESCE(sil."shippingCost", 0)
+ ) AS "subtotal",
+ SUM(
+ COALESCE(sil."taxPercent", 0) * (
+ COALESCE(sil."quantity", 0)*COALESCE(sil."unitPrice", 0)
+ + COALESCE(sil."addOnCost", 0)
+ + COALESCE(sil."shippingCost", 0)
+ )
+ ) AS "totalTax",
+ MIN(i."type") AS "itemType",
+ ARRAY_AGG(
+ json_build_object(
+ 'id', sil.id,
+ 'invoiceLineType', sil."invoiceLineType",
+ 'quantity', sil."quantity",
+ 'unitPrice', sil."unitPrice",
+ 'itemId', sil."itemId"
+ )
+ ) AS "lines"
+ FROM "salesInvoiceLine" sil
+ LEFT JOIN "item" i
+ ON i."id" = sil."itemId"
+ LEFT JOIN "modelUpload" mu ON mu.id = i."modelUploadId"
+ GROUP BY sil."invoiceId"
+ ) sil ON sil."invoiceId" = si."id"
+ -- LEFT JOIN (was INNER): an invoice missing its shipment row must not
+ -- vanish from the view — post-payment would read its balance as 0 and
+ -- reject every application. shippingCost is already COALESCEd.
+ LEFT JOIN "salesInvoiceShipment" ss ON ss."id" = si."id"
+ LEFT JOIN "paymentTerm" pt ON pt."id" = si."paymentTermId"
+ LEFT JOIN settled s ON s."targetSalesInvoiceId" = si."id" AND s."companyId" = si."companyId"
+ LEFT JOIN "company" invoice_company ON invoice_company."id" = si."companyId"
+ LEFT JOIN "currency" invoice_currency ON invoice_currency."code" = si."currencyCode"
+ AND invoice_currency."companyGroupId" = invoice_company."companyGroupId"
+ CROSS JOIN LATERAL (
+ SELECT round((COALESCE(sil."subtotal", 0) + COALESCE(sil."totalTax", 0) + COALESCE(ss."shippingCost", 0)) * si."exchangeRate", invoice_currency."decimalPlaces") AS total_document
+ ) amounts
+ CROSS JOIN LATERAL (
+ SELECT amounts.total_document - COALESCE(s.amount_document, 0) AS amount_document
+ ) remaining;
+
+-- Latest source: packages/database/supabase/migrations/20260811123616_widen-purchasing-scale.sql
+CREATE OR REPLACE VIEW "purchaseInvoices" WITH(SECURITY_INVOKER=true) AS
+ WITH settled AS (
+ SELECT s."targetPurchaseInvoiceId", s."companyId",
+ SUM(COALESCE(s."sourceAmount", 0) + round(
+ (s."discountAmount" + s."writeOffAmount") * target."exchangeRate",
+ target_currency."decimalPlaces")) AS amount_document,
+ MAX(s."appliedDate") AS "lastSettlementDate"
+ FROM "invoiceSettlement" s
+ JOIN "purchaseInvoice" target ON target."id" = s."targetPurchaseInvoiceId"
+ AND target."companyId" = s."companyId"
+ LEFT JOIN "company" target_company ON target_company."id" = target."companyId"
+ LEFT JOIN "currency" target_currency ON target_currency."code" = target."currencyCode"
+ AND target_currency."companyGroupId" = target_company."companyGroupId"
+ LEFT JOIN "payment" p ON p."id" = s."paymentId" AND p."companyId" = s."companyId"
+ LEFT JOIN "memo" m ON m."id" = s."memoId" AND m."companyId" = s."companyId"
+ LEFT JOIN "payment" vp ON vp."id" = s."appliedViaPaymentId" AND vp."companyId" = s."companyId"
+ WHERE s."targetPurchaseInvoiceId" IS NOT NULL
+ AND ((s."paymentId" IS NOT NULL AND p."status" = 'Posted')
+ OR (s."memoId" IS NOT NULL AND m."status" = 'Posted'
+ AND (s."appliedViaPaymentId" IS NULL OR vp."status" = 'Posted')))
+ GROUP BY s."targetPurchaseInvoiceId", s."companyId"
+ )
+ SELECT
+ pi."id",
+ pi."invoiceId",
+ pi."supplierId",
+ pi."invoiceSupplierId",
+ pi."supplierInteractionId",
+ pi."supplierReference",
+ pi."invoiceSupplierContactId",
+ pi."invoiceSupplierLocationId",
+ pi."locationId",
+ pi."postingDate",
+ pi."dateIssued",
+ pi."dateDue",
+ CASE
+ WHEN pi."status" = 'Paid' THEN pi."datePaid"
+ WHEN COALESCE(s.amount_document, 0) > 0
+ AND amounts.total_document > 0 AND remaining.amount_document <= 0
+ THEN COALESCE(s."lastSettlementDate", pi."datePaid")
+ ELSE pi."datePaid"
+ END AS "datePaid",
+ pi."paymentTermId",
+ pi."currencyCode",
+ pi."exchangeRate",
+ pi."exchangeRateUpdatedAt",
+ COALESCE(pl."subtotal", 0) AS "subtotal",
+ pi."totalDiscount",
+ (COALESCE(pl."orderTotal", 0) + COALESCE(pid."supplierShippingCost", 0) / CASE WHEN pi."exchangeRate" = 0 THEN 1 ELSE pi."exchangeRate" END) AS "totalAmount",
+ COALESCE(pl."totalTax", 0) AS "totalTax",
+ CASE
+ WHEN pi."status" = 'Paid' THEN 0
+ ELSE remaining.amount_document / NULLIF(pi."exchangeRate", 0)
+ END AS "balance",
+ pi."assignee",
+ pi."createdBy",
+ pi."createdAt",
+ pi."updatedBy",
+ pi."updatedAt",
+ pi."internalNotes",
+ pi."customFields",
+ pi."companyId",
+ pl."thumbnailPath",
+ pl."itemType",
+ COALESCE(pl."orderTotal", 0) + COALESCE(pid."supplierShippingCost", 0) / CASE WHEN pi."exchangeRate" = 0 THEN 1 ELSE pi."exchangeRate" END AS "orderTotal",
+ CASE
+ WHEN pi."status" IN ('Draft','Pending','Voided','Return','Debit Note Issued') THEN pi."status"::TEXT
+ WHEN pi."status" = 'Paid' THEN 'Paid'
+ WHEN COALESCE(s.amount_document, 0) > 0
+ AND amounts.total_document > 0 AND remaining.amount_document <= 0 THEN 'Paid'
+ WHEN COALESCE(s.amount_document, 0) > 0 THEN 'Partially Paid'
+ WHEN pi."dateDue" < CURRENT_DATE AND pi."status" = 'Open' THEN 'Overdue'
+ ELSE pi."status"::TEXT
+ END AS status,
+ pt."name" AS "paymentTermName",
+ pi."status" AS "baseStatus"
+ FROM "purchaseInvoice" pi
+ LEFT JOIN (
+ SELECT
+ pol."invoiceId",
+ MIN(CASE
+ WHEN i."thumbnailPath" IS NULL AND mu."thumbnailPath" IS NOT NULL THEN mu."thumbnailPath"
+ ELSE i."thumbnailPath"
+ END) AS "thumbnailPath",
+ SUM(
+ COALESCE(pol."quantity", 0)*COALESCE(pol."unitPrice", 0) + COALESCE(pol."shippingCost", 0)
+ ) AS "subtotal",
+ SUM(COALESCE(pol."taxAmount", 0)) AS "totalTax",
+ SUM(
+ COALESCE(pol."quantity", 0)*COALESCE(pol."unitPrice", 0) + COALESCE(pol."shippingCost", 0) + COALESCE(pol."taxAmount", 0)
+ ) AS "orderTotal",
+ MIN(i."type") AS "itemType"
+ FROM "purchaseInvoiceLine" pol
+ LEFT JOIN "item" i
+ ON i."id" = pol."itemId"
+ LEFT JOIN "modelUpload" mu ON mu.id = i."modelUploadId"
+ GROUP BY pol."invoiceId"
+ ) pl ON pl."invoiceId" = pi."id"
+ LEFT JOIN "paymentTerm" pt ON pt."id" = pi."paymentTermId"
+ LEFT JOIN "purchaseInvoiceDelivery" pid ON pid."id" = pi."id"
+ LEFT JOIN settled s ON s."targetPurchaseInvoiceId" = pi."id" AND s."companyId" = pi."companyId"
+ LEFT JOIN "company" invoice_company ON invoice_company."id" = pi."companyId"
+ LEFT JOIN "currency" invoice_currency ON invoice_currency."code" = pi."currencyCode"
+ AND invoice_currency."companyGroupId" = invoice_company."companyGroupId"
+ CROSS JOIN LATERAL (
+ SELECT round((COALESCE(pl."orderTotal", 0) + COALESCE(pid."supplierShippingCost", 0) / CASE WHEN pi."exchangeRate" = 0 THEN 1 ELSE pi."exchangeRate" END) * pi."exchangeRate", invoice_currency."decimalPlaces") AS total_document
+ ) amounts
+ CROSS JOIN LATERAL (
+ SELECT amounts.total_document - COALESCE(s.amount_document, 0) AS amount_document
+ ) remaining;
+
+-- Report replacements retain all six RPC signatures.
+-- Latest behavior source: 20260702224219_fix-ar-ap-legacy-paid.sql, all six RPCs.
+-- CREATE OR REPLACE preserves argument/return signatures, ownership and ACLs.
+-- Existing views also need the separate document-remainder/sourceAmount update.
+-- No reset, legacy version, historical posted-row backfill, or new public RPC.
+
+CREATE OR REPLACE FUNCTION get_ar_open_by_customer(
+ _company_id TEXT,
+ _as_of_date DATE
+)
+RETURNS TABLE (
+ "customerId" TEXT,
+ "documentId" TEXT,
+ "documentNumber" TEXT,
+ "documentType" TEXT,
+ "dateDue" DATE,
+ "currencyCode" TEXT,
+ "exchangeRate" NUMERIC,
+ "totalAmount" NUMERIC,
+ "settled" NUMERIC,
+ "openInCurrency" NUMERIC,
+ "openInBase" NUMERIC
+)
+LANGUAGE SQL
+SECURITY INVOKER
+AS $$
+ WITH effective_settlements AS (
+ SELECT s.*
+ FROM "invoiceSettlement" s
+ LEFT JOIN "payment" p ON p."id" = s."paymentId"
+ AND p."companyId" = s."companyId"
+ LEFT JOIN "memo" source_memo ON source_memo."id" = s."memoId"
+ AND source_memo."companyId" = s."companyId"
+ LEFT JOIN "payment" applying ON applying."id" = s."appliedViaPaymentId"
+ AND applying."companyId" = s."companyId"
+ WHERE s."companyId" = _company_id
+ AND (
+ (s."paymentId" IS NOT NULL AND p."status" = 'Posted'
+ AND p."postingDate" <= _as_of_date)
+ OR (s."memoId" IS NOT NULL AND source_memo."status" = 'Posted'
+ AND source_memo."postingDate" <= _as_of_date
+ AND ((s."appliedViaPaymentId" IS NULL AND s."appliedDate" <= _as_of_date) OR
+ (applying."status" = 'Posted' AND applying."postingDate" <= _as_of_date)))
+ )
+ ), invoice_settled AS (
+ SELECT s."targetSalesInvoiceId" AS invoice_id,
+ SUM(s."appliedAmount" + s."discountAmount" + s."writeOffAmount") AS settled_base,
+ SUM(COALESCE(s."sourceAmount", 0) + round(
+ (s."discountAmount" + s."writeOffAmount") * target."exchangeRate",
+ target_currency."decimalPlaces")) AS settled_document
+ FROM effective_settlements s
+ JOIN "salesInvoice" target ON target."id" = s."targetSalesInvoiceId"
+ AND target."companyId" = s."companyId"
+ LEFT JOIN "company" target_company ON target_company."id" = target."companyId"
+ LEFT JOIN "currency" target_currency ON target_currency."code" = target."currencyCode"
+ AND target_currency."companyGroupId" = target_company."companyGroupId"
+ WHERE s."targetSalesInvoiceId" IS NOT NULL
+ GROUP BY s."targetSalesInvoiceId"
+ ), memo_source_consumed AS (
+ SELECT s."memoId" AS memo_id, SUM(s."sourceAmount") AS settled_document,
+ bool_and(s."sourceAmount" IS NOT NULL) AS principal_known,
+ SUM(s."appliedAmount" + s."fxGainLossAmount") AS settled_base
+ FROM effective_settlements s
+ WHERE s."memoId" IS NOT NULL
+ GROUP BY s."memoId"
+ ), memo_target_settled AS (
+ -- Preserve existing cash-to-memo rows without adding a new refund workflow.
+ -- These fields relieve the TARGET memo in base, unlike sourceAmount.
+ SELECT s."targetMemoId" AS memo_id, SUM(s."appliedAmount") AS settled_base
+ FROM effective_settlements s
+ WHERE s."targetMemoId" IS NOT NULL AND s."paymentId" IS NOT NULL
+ GROUP BY s."targetMemoId"
+ ), invoice_carrying AS (
+ -- Same original control snapshots used by post-payment; a document rate
+ -- conversion cannot reconstruct carrying value after document rounding.
+ SELECT line."documentId" AS invoice_id, SUM(line."amount") AS original_base
+ FROM "journalLine" line
+ JOIN "journal" j ON j."id"=line."journalId" AND j."companyId"=line."companyId"
+ WHERE line."companyId"=_company_id AND line."documentType"='Invoice'
+ AND line."description" IN ('Accounts Receivable','IC Receivables') AND j."sourceType"='Sales Invoice'
+ AND j."status"='Posted' AND j."postingDate"<=_as_of_date
+ GROUP BY line."documentId"
+ ), invoice_open AS (
+ SELECT i.*, COALESCE(s.settled_base, 0) AS settled_base,
+ amounts.remaining_document,
+ COALESCE(c.original_base, accounting_round_internal(i."totalAmount")) - COALESCE(s.settled_base,0) AS remaining_base
+ FROM "salesInvoices" i
+ JOIN "salesInvoice" ib ON ib."id" = i."id" AND ib."companyId" = i."companyId"
+ LEFT JOIN invoice_settled s ON s.invoice_id = i."id"
+ LEFT JOIN invoice_carrying c ON c.invoice_id = i."id"
+ LEFT JOIN "company" invoice_company ON invoice_company."id" = i."companyId"
+ LEFT JOIN "currency" invoice_currency ON invoice_currency."code" = i."currencyCode"
+ AND invoice_currency."companyGroupId" = invoice_company."companyGroupId"
+ CROSS JOIN LATERAL (
+ SELECT round(i."totalAmount" * i."exchangeRate", invoice_currency."decimalPlaces")
+ - COALESCE(s.settled_document, 0) AS remaining_document
+ ) amounts
+ WHERE i."companyId" = _company_id
+ AND i."postingDate" <= _as_of_date
+ AND i."status" NOT IN ('Draft', 'Pending', 'Voided')
+ AND NOT (ib."status" = 'Paid'
+ AND (ib."datePaid" IS NULL OR ib."datePaid" <= _as_of_date))
+ ), memo_open AS (
+ SELECT m.*,
+ accounting_round_internal(m."amount"/m."exchangeRate") - COALESCE(s.settled_base,0) - COALESCE(t.settled_base,0) AS remaining_base,
+ COALESCE(s.settled_document, 0) + COALESCE(t.settled_base, 0) * m."exchangeRate" AS settled_document,
+ m."amount" - COALESCE(s.settled_document, 0)
+ - COALESCE(t.settled_base, 0) * m."exchangeRate" AS remaining_document
+ FROM "memo" m
+ LEFT JOIN memo_source_consumed s ON s.memo_id = m."id"
+ LEFT JOIN memo_target_settled t ON t.memo_id = m."id"
+ WHERE m."companyId" = _company_id AND m."customerId" IS NOT NULL
+ AND m."status" = 'Posted' AND m."postingDate" <= _as_of_date
+ -- Unknown principal cannot be reconstructed from rounded carrying base.
+ AND COALESCE(s.principal_known, true)
+ )
+ -- Preserve totalAmount/settled's existing per-document denomination:
+ -- invoices carry base; memo amount/settled carry memo currency.
+ SELECT i."customerId", i."id" AS "documentId", i."invoiceId" AS "documentNumber",
+ 'Invoice'::TEXT AS "documentType", i."dateDue", i."currencyCode", i."exchangeRate",
+ i."totalAmount", i.settled_base AS "settled",
+ i.remaining_document AS "openInCurrency",
+ i.remaining_base AS "openInBase"
+ FROM invoice_open i
+ WHERE i.remaining_document <> 0 OR i.remaining_base <> 0
+ UNION ALL
+ SELECT m."customerId", m."id", m."memoId", m."direction" || ' Memo',
+ NULL::DATE, m."currencyCode", m."exchangeRate", m."amount", m.settled_document,
+ (CASE WHEN m."direction" = 'Credit' THEN -1 ELSE 1 END) * m.remaining_document,
+ (CASE WHEN m."direction" = 'Credit' THEN -1 ELSE 1 END)
+ * m.remaining_base
+ FROM memo_open m
+ WHERE m.remaining_document <> 0 OR m.remaining_base <> 0
+ ORDER BY 1, 5 NULLS LAST;
+$$;
+
+CREATE OR REPLACE FUNCTION get_ap_open_by_supplier(
+ _company_id TEXT,
+ _as_of_date DATE
+)
+RETURNS TABLE (
+ "supplierId" TEXT,
+ "documentId" TEXT,
+ "documentNumber" TEXT,
+ "documentType" TEXT,
+ "dateDue" DATE,
+ "currencyCode" TEXT,
+ "exchangeRate" NUMERIC,
+ "totalAmount" NUMERIC,
+ "settled" NUMERIC,
+ "openInCurrency" NUMERIC,
+ "openInBase" NUMERIC
+)
+LANGUAGE SQL
+SECURITY INVOKER
+AS $$
+ WITH effective_settlements AS (
+ SELECT s.*
+ FROM "invoiceSettlement" s
+ LEFT JOIN "payment" p ON p."id" = s."paymentId"
+ AND p."companyId" = s."companyId"
+ LEFT JOIN "memo" source_memo ON source_memo."id" = s."memoId"
+ AND source_memo."companyId" = s."companyId"
+ LEFT JOIN "payment" applying ON applying."id" = s."appliedViaPaymentId"
+ AND applying."companyId" = s."companyId"
+ WHERE s."companyId" = _company_id
+ AND (
+ (s."paymentId" IS NOT NULL AND p."status" = 'Posted'
+ AND p."postingDate" <= _as_of_date)
+ OR (s."memoId" IS NOT NULL AND source_memo."status" = 'Posted'
+ AND source_memo."postingDate" <= _as_of_date
+ AND ((s."appliedViaPaymentId" IS NULL AND s."appliedDate" <= _as_of_date) OR
+ (applying."status" = 'Posted' AND applying."postingDate" <= _as_of_date)))
+ )
+ ), invoice_settled AS (
+ SELECT s."targetPurchaseInvoiceId" AS invoice_id,
+ SUM(s."appliedAmount" + s."discountAmount" + s."writeOffAmount") AS settled_base,
+ SUM(COALESCE(s."sourceAmount", 0) + round(
+ (s."discountAmount" + s."writeOffAmount") * target."exchangeRate",
+ target_currency."decimalPlaces")) AS settled_document
+ FROM effective_settlements s
+ JOIN "purchaseInvoice" target ON target."id" = s."targetPurchaseInvoiceId"
+ AND target."companyId" = s."companyId"
+ LEFT JOIN "company" target_company ON target_company."id" = target."companyId"
+ LEFT JOIN "currency" target_currency ON target_currency."code" = target."currencyCode"
+ AND target_currency."companyGroupId" = target_company."companyGroupId"
+ WHERE s."targetPurchaseInvoiceId" IS NOT NULL
+ GROUP BY s."targetPurchaseInvoiceId"
+ ), memo_source_consumed AS (
+ SELECT s."memoId" AS memo_id, SUM(s."sourceAmount") AS settled_document,
+ bool_and(s."sourceAmount" IS NOT NULL) AS principal_known,
+ SUM(s."appliedAmount" - s."fxGainLossAmount") AS settled_base
+ FROM effective_settlements s
+ WHERE s."memoId" IS NOT NULL
+ GROUP BY s."memoId"
+ ), memo_target_settled AS (
+ -- Preserve existing cash-to-memo rows without adding a new refund workflow.
+ -- These fields relieve the TARGET memo in base, unlike sourceAmount.
+ SELECT s."targetMemoId" AS memo_id, SUM(s."appliedAmount") AS settled_base
+ FROM effective_settlements s
+ WHERE s."targetMemoId" IS NOT NULL AND s."paymentId" IS NOT NULL
+ GROUP BY s."targetMemoId"
+ ), invoice_carrying AS (
+ -- Same original control snapshots used by post-payment; a document rate
+ -- conversion cannot reconstruct carrying value after document rounding.
+ SELECT line."documentId" AS invoice_id, SUM(line."amount") AS original_base
+ FROM "journalLine" line
+ JOIN "journal" j ON j."id"=line."journalId" AND j."companyId"=line."companyId"
+ WHERE line."companyId"=_company_id AND line."documentType"='Invoice'
+ AND line."description" IN ('Accounts Payable','IC Payables') AND j."sourceType"='Purchase Invoice'
+ AND j."status"='Posted' AND j."postingDate"<=_as_of_date
+ GROUP BY line."documentId"
+ ), invoice_open AS (
+ SELECT i.*, COALESCE(s.settled_base, 0) AS settled_base,
+ amounts.remaining_document,
+ COALESCE(c.original_base, accounting_round_internal(i."totalAmount")) - COALESCE(s.settled_base,0) AS remaining_base
+ FROM "purchaseInvoices" i
+ JOIN "purchaseInvoice" ib ON ib."id" = i."id" AND ib."companyId" = i."companyId"
+ LEFT JOIN invoice_settled s ON s.invoice_id = i."id"
+ LEFT JOIN invoice_carrying c ON c.invoice_id = i."id"
+ LEFT JOIN "company" invoice_company ON invoice_company."id" = i."companyId"
+ LEFT JOIN "currency" invoice_currency ON invoice_currency."code" = i."currencyCode"
+ AND invoice_currency."companyGroupId" = invoice_company."companyGroupId"
+ CROSS JOIN LATERAL (
+ SELECT round(i."totalAmount" * i."exchangeRate", invoice_currency."decimalPlaces")
+ - COALESCE(s.settled_document, 0) AS remaining_document
+ ) amounts
+ WHERE i."companyId" = _company_id
+ AND i."postingDate" <= _as_of_date
+ AND i."status" NOT IN ('Draft', 'Pending', 'Voided')
+ AND NOT (ib."status" = 'Paid'
+ AND (ib."datePaid" IS NULL OR ib."datePaid" <= _as_of_date))
+ ), memo_open AS (
+ SELECT m.*,
+ accounting_round_internal(m."amount"/m."exchangeRate") - COALESCE(s.settled_base,0) - COALESCE(t.settled_base,0) AS remaining_base,
+ COALESCE(s.settled_document, 0) + COALESCE(t.settled_base, 0) * m."exchangeRate" AS settled_document,
+ m."amount" - COALESCE(s.settled_document, 0)
+ - COALESCE(t.settled_base, 0) * m."exchangeRate" AS remaining_document
+ FROM "memo" m
+ LEFT JOIN memo_source_consumed s ON s.memo_id = m."id"
+ LEFT JOIN memo_target_settled t ON t.memo_id = m."id"
+ WHERE m."companyId" = _company_id AND m."supplierId" IS NOT NULL
+ AND m."status" = 'Posted' AND m."postingDate" <= _as_of_date
+ -- Unknown principal cannot be reconstructed from rounded carrying base.
+ AND COALESCE(s.principal_known, true)
+ )
+ -- Preserve totalAmount/settled's existing per-document denomination:
+ -- invoices carry base; memo amount/settled carry memo currency.
+ SELECT i."supplierId", i."id" AS "documentId", i."invoiceId" AS "documentNumber",
+ 'Invoice'::TEXT AS "documentType", i."dateDue", i."currencyCode", i."exchangeRate",
+ i."totalAmount", i.settled_base AS "settled",
+ i.remaining_document AS "openInCurrency",
+ i.remaining_base AS "openInBase"
+ FROM invoice_open i
+ WHERE i.remaining_document <> 0 OR i.remaining_base <> 0
+ UNION ALL
+ SELECT m."supplierId", m."id", m."memoId", m."direction" || ' Memo',
+ NULL::DATE, m."currencyCode", m."exchangeRate", m."amount", m.settled_document,
+ (CASE WHEN m."direction" = 'Debit' THEN -1 ELSE 1 END) * m.remaining_document,
+ (CASE WHEN m."direction" = 'Debit' THEN -1 ELSE 1 END)
+ * m.remaining_base
+ FROM memo_open m
+ WHERE m.remaining_document <> 0 OR m.remaining_base <> 0
+ ORDER BY 1, 5 NULLS LAST;
+$$;
+
+CREATE OR REPLACE FUNCTION get_ar_tie_out(
+ _company_id TEXT,
+ _as_of_date DATE
+)
+RETURNS TABLE (
+ "subledgerBalance" NUMERIC,
+ "glBalance" NUMERIC,
+ "variance" NUMERIC
+)
+LANGUAGE SQL
+SECURITY INVOKER
+AS $$
+ WITH funding_consumed AS (
+ SELECT COALESCE(s."sourcePaymentId", s."paymentId") AS source_payment_id,
+ SUM(s."appliedAmount" + s."fxGainLossAmount") AS source_base_amount
+ FROM "invoiceSettlement" s
+ JOIN "payment" applying ON applying."id" = s."paymentId"
+ AND applying."companyId" = s."companyId"
+ WHERE s."companyId" = _company_id
+ AND s."paymentId" IS NOT NULL
+ AND applying."status" = 'Posted'
+ AND applying."postingDate" <= _as_of_date
+ GROUP BY COALESCE(s."sourcePaymentId", s."paymentId")
+ ), payment_unapplied AS (
+ SELECT (accounting_round_internal(p."totalAmount" / p."exchangeRate") - COALESCE(c.source_base_amount,0)) AS open_base
+ FROM "payment" p
+ LEFT JOIN funding_consumed c ON c.source_payment_id = p."id"
+ WHERE p."companyId" = _company_id AND p."paymentType" = 'Receipt'
+ AND p."status" = 'Posted' AND p."postingDate" <= _as_of_date
+ -- Same party predicate as get_ar_aging. payment_party_check allows a
+ -- Receipt whose party is a SUPPLIER (an AP refund); it belongs to the AP
+ -- subledger, and without this it entered the AR tie-out but never AR
+ -- aging, leaving a permanent variance the tie-out exists to disprove.
+ AND p."customerId" IS NOT NULL
+ ), subledger AS (
+ SELECT COALESCE((SELECT SUM(o."openInBase")
+ FROM get_ar_open_by_customer(_company_id, _as_of_date) o), 0)
+ - COALESCE((SELECT SUM(open_base) FROM payment_unapplied), 0) AS amount
+ ), control_account AS (
+ -- A default change affects future postings; historical invoice, payment
+ -- and memo control accounts remain part of this company's subledger.
+ -- UNION deduplicates repeated control rows and overlap with current defaults.
+ SELECT unnest(ARRAY["receivablesAccount", "intercompanyReceivablesAccount"]) AS account_id
+ FROM "accountDefault" WHERE "companyId" = _company_id
+ UNION
+ SELECT line."accountId"
+ FROM "journalLine" line
+ JOIN "journal" j ON j."id" = line."journalId" AND j."companyId" = line."companyId"
+ WHERE line."companyId" = _company_id
+ AND j."status" = 'Posted' AND j."postingDate" <= _as_of_date
+ AND (
+ (j."sourceType" = 'Sales Invoice' AND line."documentType" = 'Invoice'
+ AND line."description" = 'Accounts Receivable')
+ OR (j."sourceType" = 'Payment' AND line."documentType" = 'Payment'
+ AND line."description" IN ('Accounts Receivable',
+ 'Accounts Receivable (on-account credit)', 'Accounts Receivable (credit applied)'))
+ OR (j."sourceType" IN ('Credit Memo', 'Debit Memo') AND line."documentType" = 'Memo'
+ AND line."description" = 'Accounts Receivable')
+ )
+ ), gl AS (
+ SELECT COALESCE(SUM(jl."amount"), 0) AS amount
+ FROM "journalLine" jl
+ JOIN "journal" j ON j."id" = jl."journalId" AND j."companyId" = jl."companyId"
+ JOIN control_account a ON a.account_id = jl."accountId"
+ WHERE jl."companyId" = _company_id
+ AND j."postingDate" <= _as_of_date AND j."status" = 'Posted'
+ )
+ SELECT subledger.amount AS "subledgerBalance", gl.amount AS "glBalance",
+ subledger.amount - gl.amount AS "variance"
+ FROM subledger, gl;
+$$;
+
+CREATE OR REPLACE FUNCTION get_ap_tie_out(
+ _company_id TEXT,
+ _as_of_date DATE
+)
+RETURNS TABLE (
+ "subledgerBalance" NUMERIC,
+ "glBalance" NUMERIC,
+ "variance" NUMERIC
+)
+LANGUAGE SQL
+SECURITY INVOKER
+AS $$
+ WITH funding_consumed AS (
+ SELECT COALESCE(s."sourcePaymentId", s."paymentId") AS source_payment_id,
+ SUM(s."appliedAmount" - s."fxGainLossAmount") AS source_base_amount
+ FROM "invoiceSettlement" s
+ JOIN "payment" applying ON applying."id" = s."paymentId"
+ AND applying."companyId" = s."companyId"
+ WHERE s."companyId" = _company_id
+ AND s."paymentId" IS NOT NULL
+ AND applying."status" = 'Posted'
+ AND applying."postingDate" <= _as_of_date
+ GROUP BY COALESCE(s."sourcePaymentId", s."paymentId")
+ ), payment_unapplied AS (
+ SELECT (accounting_round_internal(p."totalAmount" / p."exchangeRate") - COALESCE(c.source_base_amount,0)) AS open_base
+ FROM "payment" p
+ LEFT JOIN funding_consumed c ON c.source_payment_id = p."id"
+ WHERE p."companyId" = _company_id AND p."paymentType" = 'Disbursement'
+ AND p."status" = 'Posted' AND p."postingDate" <= _as_of_date
+ -- Same party predicate as get_ap_aging. A Disbursement whose party is a
+ -- CUSTOMER is an AR refund and belongs to the AR subledger.
+ AND p."supplierId" IS NOT NULL
+ ), subledger AS (
+ SELECT COALESCE((SELECT SUM(o."openInBase")
+ FROM get_ap_open_by_supplier(_company_id, _as_of_date) o), 0)
+ - COALESCE((SELECT SUM(open_base) FROM payment_unapplied), 0) AS amount
+ ), control_account AS (
+ SELECT unnest(ARRAY["payablesAccount", "intercompanyPayablesAccount"]) AS account_id
+ FROM "accountDefault" WHERE "companyId" = _company_id
+ UNION
+ SELECT line."accountId"
+ FROM "journalLine" line
+ JOIN "journal" j ON j."id" = line."journalId" AND j."companyId" = line."companyId"
+ WHERE line."companyId" = _company_id
+ AND j."status" = 'Posted' AND j."postingDate" <= _as_of_date
+ AND (
+ (j."sourceType" = 'Purchase Invoice' AND line."documentType" = 'Invoice'
+ AND line."description" = 'Accounts Payable')
+ OR (j."sourceType" = 'Payment' AND line."documentType" = 'Payment'
+ AND line."description" IN ('Accounts Payable',
+ 'Accounts Payable (on-account credit)', 'Accounts Payable (credit applied)'))
+ OR (j."sourceType" IN ('Credit Memo', 'Debit Memo') AND line."documentType" = 'Memo'
+ AND line."description" = 'Accounts Payable')
+ )
+ ), gl AS (
+ SELECT COALESCE(SUM(jl."amount"), 0) AS amount
+ FROM "journalLine" jl
+ JOIN "journal" j ON j."id" = jl."journalId" AND j."companyId" = jl."companyId"
+ JOIN control_account a ON a.account_id = jl."accountId"
+ WHERE jl."companyId" = _company_id
+ AND j."postingDate" <= _as_of_date AND j."status" = 'Posted'
+ )
+ SELECT subledger.amount AS "subledgerBalance", gl.amount AS "glBalance",
+ subledger.amount - gl.amount AS "variance"
+ FROM subledger, gl;
+$$;
+
+CREATE OR REPLACE FUNCTION get_ar_aging(
+ _company_id TEXT,
+ _as_of_date DATE,
+ _aging_method TEXT DEFAULT 'dueDate',
+ _bucket1 INTEGER DEFAULT 30,
+ _bucket2 INTEGER DEFAULT 60,
+ _bucket3 INTEGER DEFAULT 90
+)
+RETURNS TABLE (
+ "customerId" TEXT,
+ "paymentTerm" TEXT,
+ "current" NUMERIC,
+ "bucket1" NUMERIC,
+ "bucket2" NUMERIC,
+ "bucket3" NUMERIC,
+ "bucket4" NUMERIC,
+ "unapplied" NUMERIC,
+ "total" NUMERIC
+)
+LANGUAGE SQL
+SECURITY INVOKER
+AS $$
+ WITH funding_consumed AS (
+ SELECT COALESCE(s."sourcePaymentId", s."paymentId") AS source_payment_id,
+ SUM(s."appliedAmount" + s."fxGainLossAmount") AS source_base_amount
+ FROM "invoiceSettlement" s
+ JOIN "payment" applying ON applying."id" = s."paymentId"
+ AND applying."companyId" = s."companyId"
+ WHERE s."companyId" = _company_id
+ AND s."paymentId" IS NOT NULL
+ AND applying."status" = 'Posted'
+ AND applying."postingDate" <= _as_of_date
+ GROUP BY COALESCE(s."sourcePaymentId", s."paymentId")
+ ), open_items AS (
+ SELECT o."customerId",
+ CASE WHEN o."documentType" = 'Invoice' THEN
+ CASE WHEN _aging_method = 'documentDate' THEN COALESCE(i."dateIssued", i."postingDate")
+ ELSE o."dateDue" END
+ ELSE m."memoDate" END AS age_date,
+ o."openInBase" AS open_base
+ FROM get_ar_open_by_customer(_company_id, _as_of_date) o
+ LEFT JOIN "salesInvoice" i ON i."id" = o."documentId"
+ AND i."companyId" = _company_id AND o."documentType" = 'Invoice'
+ LEFT JOIN "memo" m ON m."id" = o."documentId"
+ AND m."companyId" = _company_id AND o."documentType" <> 'Invoice'
+ ),
+ buckets AS (
+ SELECT
+ "customerId",
+ COALESCE(SUM(open_base) FILTER (WHERE age_date IS NULL OR age_date >= _as_of_date), 0) AS "current",
+ COALESCE(SUM(open_base) FILTER (WHERE age_date < _as_of_date AND _as_of_date - age_date BETWEEN 1 AND _bucket1), 0) AS "bucket1",
+ COALESCE(SUM(open_base) FILTER (WHERE _as_of_date - age_date BETWEEN _bucket1 + 1 AND _bucket2), 0) AS "bucket2",
+ COALESCE(SUM(open_base) FILTER (WHERE _as_of_date - age_date BETWEEN _bucket2 + 1 AND _bucket3), 0) AS "bucket3",
+ COALESCE(SUM(open_base) FILTER (WHERE _as_of_date - age_date > _bucket3), 0) AS "bucket4"
+ FROM open_items
+ WHERE open_base <> 0
+ GROUP BY "customerId"
+ ),
+ unapplied AS (
+ SELECT p."customerId",
+ -COALESCE(SUM((accounting_round_internal(p."totalAmount" / p."exchangeRate") - COALESCE(c.source_base_amount,0))), 0) AS "unapplied"
+ FROM "payment" p
+ LEFT JOIN funding_consumed c ON c.source_payment_id = p."id"
+ WHERE p."companyId" = _company_id AND p."paymentType" = 'Receipt'
+ AND p."status" = 'Posted' AND p."postingDate" <= _as_of_date
+ AND p."customerId" IS NOT NULL
+ GROUP BY p."customerId"
+ )
+ SELECT
+ COALESCE(ib."customerId", u."customerId") AS "customerId",
+ pt."name" AS "paymentTerm",
+ COALESCE(ib."current", 0) AS "current",
+ COALESCE(ib."bucket1", 0) AS "bucket1",
+ COALESCE(ib."bucket2", 0) AS "bucket2",
+ COALESCE(ib."bucket3", 0) AS "bucket3",
+ COALESCE(ib."bucket4", 0) AS "bucket4",
+ COALESCE(u."unapplied", 0) AS "unapplied",
+ COALESCE(ib."current", 0) + COALESCE(ib."bucket1", 0)
+ + COALESCE(ib."bucket2", 0) + COALESCE(ib."bucket3", 0)
+ + COALESCE(ib."bucket4", 0) + COALESCE(u."unapplied", 0) AS "total"
+ FROM buckets ib
+ FULL OUTER JOIN unapplied u ON u."customerId" = ib."customerId"
+ LEFT JOIN "customerPayment" cp
+ ON cp."customerId" = COALESCE(ib."customerId", u."customerId")
+ AND cp."companyId" = _company_id
+ LEFT JOIN "paymentTerm" pt ON pt."id" = cp."paymentTermId"
+ WHERE
+ COALESCE(ib."current", 0) + COALESCE(ib."bucket1", 0)
+ + COALESCE(ib."bucket2", 0) + COALESCE(ib."bucket3", 0)
+ + COALESCE(ib."bucket4", 0) + COALESCE(u."unapplied", 0) <> 0
+ ORDER BY "total" DESC;
+$$;
+
+CREATE OR REPLACE FUNCTION get_ap_aging(
+ _company_id TEXT,
+ _as_of_date DATE,
+ _aging_method TEXT DEFAULT 'dueDate',
+ _bucket1 INTEGER DEFAULT 30,
+ _bucket2 INTEGER DEFAULT 60,
+ _bucket3 INTEGER DEFAULT 90
+)
+RETURNS TABLE (
+ "supplierId" TEXT,
+ "paymentTerm" TEXT,
+ "current" NUMERIC,
+ "bucket1" NUMERIC,
+ "bucket2" NUMERIC,
+ "bucket3" NUMERIC,
+ "bucket4" NUMERIC,
+ "unapplied" NUMERIC,
+ "total" NUMERIC
+)
+LANGUAGE SQL
+SECURITY INVOKER
+AS $$
+ WITH funding_consumed AS (
+ SELECT COALESCE(s."sourcePaymentId", s."paymentId") AS source_payment_id,
+ SUM(s."appliedAmount" - s."fxGainLossAmount") AS source_base_amount
+ FROM "invoiceSettlement" s
+ JOIN "payment" applying ON applying."id" = s."paymentId"
+ AND applying."companyId" = s."companyId"
+ WHERE s."companyId" = _company_id
+ AND s."paymentId" IS NOT NULL
+ AND applying."status" = 'Posted'
+ AND applying."postingDate" <= _as_of_date
+ GROUP BY COALESCE(s."sourcePaymentId", s."paymentId")
+ ), open_items AS (
+ SELECT o."supplierId",
+ CASE WHEN o."documentType" = 'Invoice' THEN
+ CASE WHEN _aging_method = 'documentDate' THEN COALESCE(i."dateIssued", i."postingDate")
+ ELSE o."dateDue" END
+ ELSE m."memoDate" END AS age_date,
+ o."openInBase" AS open_base
+ FROM get_ap_open_by_supplier(_company_id, _as_of_date) o
+ LEFT JOIN "purchaseInvoice" i ON i."id" = o."documentId"
+ AND i."companyId" = _company_id AND o."documentType" = 'Invoice'
+ LEFT JOIN "memo" m ON m."id" = o."documentId"
+ AND m."companyId" = _company_id AND o."documentType" <> 'Invoice'
+ ),
+ buckets AS (
+ SELECT
+ "supplierId",
+ COALESCE(SUM(open_base) FILTER (WHERE age_date IS NULL OR age_date >= _as_of_date), 0) AS "current",
+ COALESCE(SUM(open_base) FILTER (WHERE age_date < _as_of_date AND _as_of_date - age_date BETWEEN 1 AND _bucket1), 0) AS "bucket1",
+ COALESCE(SUM(open_base) FILTER (WHERE _as_of_date - age_date BETWEEN _bucket1 + 1 AND _bucket2), 0) AS "bucket2",
+ COALESCE(SUM(open_base) FILTER (WHERE _as_of_date - age_date BETWEEN _bucket2 + 1 AND _bucket3), 0) AS "bucket3",
+ COALESCE(SUM(open_base) FILTER (WHERE _as_of_date - age_date > _bucket3), 0) AS "bucket4"
+ FROM open_items
+ WHERE open_base <> 0
+ GROUP BY "supplierId"
+ ),
+ unapplied AS (
+ SELECT p."supplierId",
+ -COALESCE(SUM((accounting_round_internal(p."totalAmount" / p."exchangeRate") - COALESCE(c.source_base_amount,0))), 0) AS "unapplied"
+ FROM "payment" p
+ LEFT JOIN funding_consumed c ON c.source_payment_id = p."id"
+ WHERE p."companyId" = _company_id AND p."paymentType" = 'Disbursement'
+ AND p."status" = 'Posted' AND p."postingDate" <= _as_of_date
+ AND p."supplierId" IS NOT NULL
+ GROUP BY p."supplierId"
+ )
+ SELECT
+ COALESCE(ib."supplierId", u."supplierId") AS "supplierId",
+ pt."name" AS "paymentTerm",
+ COALESCE(ib."current", 0) AS "current",
+ COALESCE(ib."bucket1", 0) AS "bucket1",
+ COALESCE(ib."bucket2", 0) AS "bucket2",
+ COALESCE(ib."bucket3", 0) AS "bucket3",
+ COALESCE(ib."bucket4", 0) AS "bucket4",
+ COALESCE(u."unapplied", 0) AS "unapplied",
+ COALESCE(ib."current", 0) + COALESCE(ib."bucket1", 0)
+ + COALESCE(ib."bucket2", 0) + COALESCE(ib."bucket3", 0)
+ + COALESCE(ib."bucket4", 0) + COALESCE(u."unapplied", 0) AS "total"
+ FROM buckets ib
+ FULL OUTER JOIN unapplied u ON u."supplierId" = ib."supplierId"
+ LEFT JOIN "supplierPayment" sp
+ ON sp."supplierId" = COALESCE(ib."supplierId", u."supplierId")
+ AND sp."companyId" = _company_id
+ LEFT JOIN "paymentTerm" pt ON pt."id" = sp."paymentTermId"
+ WHERE
+ COALESCE(ib."current", 0) + COALESCE(ib."bucket1", 0)
+ + COALESCE(ib."bucket2", 0) + COALESCE(ib."bucket3", 0)
+ + COALESCE(ib."bucket4", 0) + COALESCE(u."unapplied", 0) <> 0
+ ORDER BY "total" DESC;
+$$;
+
+NOTIFY pgrst, 'reload schema';
diff --git a/packages/database/supabase/migrations/20260909173619_preserve_inactive_account_report_balances.sql b/packages/database/supabase/migrations/20260909173619_preserve_inactive_account_report_balances.sql
new file mode 100644
index 0000000000..bcad18814b
--- /dev/null
+++ b/packages/database/supabase/migrations/20260909173619_preserve_inactive_account_report_balances.sql
@@ -0,0 +1,408 @@
+-- Account deactivation prevents future selection; posted history and period-close
+-- snapshots must retain inactive leaves and ancestors. Preserve RPC permissions.
+
+
+CREATE OR REPLACE FUNCTION "accountTreeBalances" (
+ p_company_group_id TEXT,
+ from_date DATE DEFAULT (now() - INTERVAL '100 year'),
+ to_date DATE DEFAULT now()
+)
+RETURNS TABLE (
+ "accountId" TEXT,
+ "balance" NUMERIC,
+ "balanceAtDate" NUMERIC,
+ "netChange" NUMERIC
+) LANGUAGE "plpgsql" SECURITY INVOKER SET search_path = public
+AS $$
+BEGIN
+ RETURN QUERY
+ WITH RECURSIVE "accountTree" AS (
+ -- Base case: all accounts in the company group
+ SELECT
+ a."id",
+ a."id" AS "rootId",
+ a."isGroup"
+ FROM "account" a
+ WHERE a."companyGroupId" = p_company_group_id
+
+ UNION ALL
+
+ -- Recursive case: for group accounts, include all descendants
+ SELECT
+ child."id",
+ t."rootId",
+ child."isGroup"
+ FROM "accountTree" t
+ INNER JOIN "account" child ON child."parentId" = t."id"
+ WHERE t."isGroup" = true
+ AND child."companyGroupId" = p_company_group_id
+ ),
+ "leafBalances" AS (
+ SELECT
+ a."id" AS "accountId",
+ COALESCE(SUM(CASE WHEN j."status" <> 'Draft' THEN jl."amount" ELSE 0 END), 0) AS "balance",
+ COALESCE(SUM(CASE WHEN j."status" <> 'Draft' AND j."postingDate" <= to_date THEN jl."amount" ELSE 0 END), 0) AS "balanceAtDate",
+ COALESCE(SUM(CASE WHEN j."status" <> 'Draft' AND j."postingDate" >= from_date AND j."postingDate" <= to_date THEN jl."amount" ELSE 0 END), 0) AS "netChange"
+ FROM "account" a
+ LEFT JOIN "journalLine" jl ON jl."accountId" = a."id"
+ LEFT JOIN "journal" j ON j."id" = jl."journalId"
+ WHERE a."companyGroupId" = p_company_group_id
+ AND a."isGroup" = false
+ GROUP BY a."id"
+ )
+ -- For each account, sum up all descendant leaf balances
+ SELECT
+ t."rootId" AS "accountId",
+ COALESCE(SUM(lb."balance"), 0)::NUMERIC AS "balance",
+ COALESCE(SUM(lb."balanceAtDate"), 0)::NUMERIC AS "balanceAtDate",
+ COALESCE(SUM(lb."netChange"), 0)::NUMERIC AS "netChange"
+ FROM "accountTree" t
+ LEFT JOIN "leafBalances" lb ON lb."accountId" = t."id" AND t."isGroup" = false
+ GROUP BY t."rootId";
+END;
+$$;
+
+CREATE OR REPLACE FUNCTION "accountTreeBalancesByCompany" (
+ p_company_group_id TEXT,
+ p_company_id TEXT DEFAULT NULL,
+ from_date DATE DEFAULT (now() - INTERVAL '100 year'),
+ to_date DATE DEFAULT now()
+)
+RETURNS TABLE (
+ "accountId" TEXT,
+ "balance" NUMERIC,
+ "balanceAtDate" NUMERIC,
+ "netChange" NUMERIC
+) LANGUAGE "plpgsql" SECURITY INVOKER SET search_path = public
+AS $$
+DECLARE
+ v_latest_date DATE; -- newest snapshot (for `balance`, which is unbounded)
+ v_at_date DATE; -- newest snapshot <= to_date (for balanceAtDate)
+ v_before_from DATE; -- newest snapshot < from_date (for netChange's lower bound)
+BEGIN
+ IF p_company_id IS NOT NULL THEN
+ SELECT MAX("endingBalanceDate") INTO v_latest_date
+ FROM "accountingPeriodBalance"
+ WHERE "companyId" = p_company_id;
+
+ SELECT MAX("endingBalanceDate") INTO v_at_date
+ FROM "accountingPeriodBalance"
+ WHERE "companyId" = p_company_id AND "endingBalanceDate" <= to_date;
+
+ SELECT MAX("endingBalanceDate") INTO v_before_from
+ FROM "accountingPeriodBalance"
+ WHERE "companyId" = p_company_id AND "endingBalanceDate" < from_date;
+ END IF;
+
+ IF v_latest_date IS NULL THEN
+ -- No snapshots for this company (or group-wide call): full-history scan,
+ -- identical to the 20260713225803 definition.
+ RETURN QUERY
+ WITH RECURSIVE "accountTree" AS (
+ SELECT
+ a."id",
+ a."id" AS "rootId",
+ a."isGroup"
+ FROM "account" a
+ WHERE a."companyGroupId" = p_company_group_id
+
+ UNION ALL
+
+ SELECT
+ child."id",
+ t."rootId",
+ child."isGroup"
+ FROM "accountTree" t
+ INNER JOIN "account" child ON child."parentId" = t."id"
+ WHERE t."isGroup" = true
+ AND child."companyGroupId" = p_company_group_id
+ ),
+ "leafBalances" AS (
+ SELECT
+ a."id" AS "accountId",
+ COALESCE(SUM(CASE WHEN j."status" <> 'Draft' THEN jl."amount" ELSE 0 END), 0) AS "balance",
+ COALESCE(SUM(CASE WHEN j."status" <> 'Draft' AND j."postingDate" <= to_date THEN jl."amount" ELSE 0 END), 0) AS "balanceAtDate",
+ COALESCE(SUM(CASE WHEN j."status" <> 'Draft' AND j."postingDate" >= from_date AND j."postingDate" <= to_date THEN jl."amount" ELSE 0 END), 0) AS "netChange"
+ FROM "account" a
+ LEFT JOIN "journalLine" jl ON jl."accountId" = a."id"
+ AND (p_company_id IS NULL OR jl."companyId" = p_company_id)
+ LEFT JOIN "journal" j ON j."id" = jl."journalId"
+ WHERE a."companyGroupId" = p_company_group_id
+ AND a."isGroup" = false
+ GROUP BY a."id"
+ )
+ SELECT
+ t."rootId" AS "accountId",
+ COALESCE(SUM(lb."balance"), 0)::NUMERIC AS "balance",
+ COALESCE(SUM(lb."balanceAtDate"), 0)::NUMERIC AS "balanceAtDate",
+ COALESCE(SUM(lb."netChange"), 0)::NUMERIC AS "netChange"
+ FROM "accountTree" t
+ LEFT JOIN "leafBalances" lb ON lb."accountId" = t."id" AND t."isGroup" = false
+ GROUP BY t."rootId";
+ RETURN;
+ END IF;
+
+ RETURN QUERY
+ WITH RECURSIVE "accountTree" AS (
+ SELECT
+ a."id",
+ a."id" AS "rootId",
+ a."isGroup"
+ FROM "account" a
+ WHERE a."companyGroupId" = p_company_group_id
+
+ UNION ALL
+
+ SELECT
+ child."id",
+ t."rootId",
+ child."isGroup"
+ FROM "accountTree" t
+ INNER JOIN "account" child ON child."parentId" = t."id"
+ WHERE t."isGroup" = true
+ AND child."companyGroupId" = p_company_group_id
+ ),
+ -- Only the lines the snapshots don't already cover: after the newest
+ -- snapshot each term uses, plus (for netChange's lower bound) the sliver
+ -- between its snapshot and from_date. Both are bounded postingDate ranges
+ -- served by journal_companyId_postingDate_idx.
+ "deltaLines" AS (
+ SELECT jl."accountId", jl."amount", j."postingDate"
+ FROM "journal" j
+ INNER JOIN "journalLine" jl ON jl."journalId" = j."id"
+ WHERE j."companyId" = p_company_id
+ AND jl."companyId" = p_company_id
+ AND j."status" <> 'Draft'
+ AND (
+ j."postingDate" > LEAST(v_latest_date, COALESCE(v_at_date, DATE '0001-01-01'))
+ OR (j."postingDate" < from_date
+ AND j."postingDate" > COALESCE(v_before_from, DATE '0001-01-01'))
+ )
+ ),
+ "leafBalances" AS (
+ SELECT
+ a."id" AS "accountId",
+ COALESCE(sl."endingBalance", 0)
+ + COALESCE(SUM(CASE WHEN dl."postingDate" > v_latest_date
+ THEN dl."amount" ELSE 0 END), 0) AS "balance",
+ COALESCE(sa."endingBalance", 0)
+ + COALESCE(SUM(CASE WHEN dl."postingDate" > COALESCE(v_at_date, DATE '0001-01-01')
+ AND dl."postingDate" <= to_date
+ THEN dl."amount" ELSE 0 END), 0) AS "balanceAtDate",
+ (COALESCE(sa."endingBalance", 0)
+ + COALESCE(SUM(CASE WHEN dl."postingDate" > COALESCE(v_at_date, DATE '0001-01-01')
+ AND dl."postingDate" <= to_date
+ THEN dl."amount" ELSE 0 END), 0))
+ - (COALESCE(sb."endingBalance", 0)
+ + COALESCE(SUM(CASE WHEN dl."postingDate" > COALESCE(v_before_from, DATE '0001-01-01')
+ AND dl."postingDate" < from_date
+ THEN dl."amount" ELSE 0 END), 0)) AS "netChange"
+ FROM "account" a
+ LEFT JOIN "accountingPeriodBalance" sl ON sl."accountId" = a."id"
+ AND sl."companyId" = p_company_id AND sl."endingBalanceDate" = v_latest_date
+ LEFT JOIN "accountingPeriodBalance" sa ON sa."accountId" = a."id"
+ AND sa."companyId" = p_company_id AND sa."endingBalanceDate" = v_at_date
+ LEFT JOIN "accountingPeriodBalance" sb ON sb."accountId" = a."id"
+ AND sb."companyId" = p_company_id AND sb."endingBalanceDate" = v_before_from
+ LEFT JOIN "deltaLines" dl ON dl."accountId" = a."id"
+ WHERE a."companyGroupId" = p_company_group_id
+ AND a."isGroup" = false
+ GROUP BY a."id", sl."endingBalance", sa."endingBalance", sb."endingBalance"
+ )
+ SELECT
+ t."rootId" AS "accountId",
+ COALESCE(SUM(lb."balance"), 0)::NUMERIC AS "balance",
+ COALESCE(SUM(lb."balanceAtDate"), 0)::NUMERIC AS "balanceAtDate",
+ COALESCE(SUM(lb."netChange"), 0)::NUMERIC AS "netChange"
+ FROM "accountTree" t
+ LEFT JOIN "leafBalances" lb ON lb."accountId" = t."id" AND t."isGroup" = false
+ GROUP BY t."rootId";
+END;
+$$;
+
+CREATE OR REPLACE FUNCTION "accountTreeBalancePeriodSeries" (
+ p_company_group_id TEXT,
+ p_company_id TEXT,
+ p_start DATE,
+ p_period_ends DATE[]
+)
+RETURNS TABLE (
+ "accountId" TEXT,
+ "periodEnd" DATE,
+ "balanceAtDate" NUMERIC,
+ "netChange" NUMERIC
+) LANGUAGE "plpgsql" SECURITY INVOKER SET search_path = public
+AS $$
+DECLARE
+ v_base_date DATE; -- newest snapshot strictly before p_start (NULL => no snapshots)
+ v_last_end DATE;
+BEGIN
+ IF p_company_id IS NULL THEN
+ RAISE EXCEPTION 'accountTreeBalancePeriodSeries requires p_company_id';
+ END IF;
+ IF p_period_ends IS NULL OR array_length(p_period_ends, 1) IS NULL THEN
+ RETURN;
+ END IF;
+
+ SELECT MAX(pe) INTO v_last_end FROM unnest(p_period_ends) pe;
+
+ SELECT MAX("endingBalanceDate") INTO v_base_date
+ FROM "accountingPeriodBalance"
+ WHERE "companyId" = p_company_id AND "endingBalanceDate" < p_start;
+
+ RETURN QUERY
+ WITH RECURSIVE "accountTree" AS (
+ SELECT
+ a."id",
+ a."id" AS "rootId",
+ a."isGroup"
+ FROM "account" a
+ WHERE a."companyGroupId" = p_company_group_id
+
+ UNION ALL
+
+ SELECT
+ child."id",
+ t."rootId",
+ child."isGroup"
+ FROM "accountTree" t
+ INNER JOIN "account" child ON child."parentId" = t."id"
+ WHERE t."isGroup" = true
+ AND child."companyGroupId" = p_company_group_id
+ ),
+ "periods" AS (
+ SELECT pe AS "periodEnd", ord
+ FROM unnest(p_period_ends) WITH ORDINALITY AS u(pe, ord)
+ ),
+ -- The one bounded journal scan: (base snapshot, last bucket end]
+ "deltaLines" AS (
+ SELECT jl."accountId", jl."amount", j."postingDate"
+ FROM "journal" j
+ INNER JOIN "journalLine" jl ON jl."journalId" = j."id"
+ WHERE j."companyId" = p_company_id
+ AND jl."companyId" = p_company_id
+ AND j."status" <> 'Draft'
+ AND j."postingDate" > COALESCE(v_base_date, DATE '0001-01-01')
+ AND j."postingDate" <= v_last_end
+ ),
+ -- ord 0 = the pre-range sliver (base snapshot .. day before p_start):
+ -- the opening anchor that the first bucket's netChange subtracts.
+ "bucketSums" AS (
+ SELECT
+ dl."accountId",
+ CASE WHEN dl."postingDate" < p_start THEN 0::BIGINT
+ ELSE (SELECT MIN(p.ord) FROM "periods" p WHERE p."periodEnd" >= dl."postingDate")
+ END AS ord,
+ SUM(dl."amount") AS "delta"
+ FROM "deltaLines" dl
+ GROUP BY dl."accountId", 2
+ ),
+ "base" AS (
+ SELECT s."accountId", s."endingBalance"
+ FROM "accountingPeriodBalance" s
+ WHERE s."companyId" = p_company_id AND s."endingBalanceDate" = v_base_date
+ ),
+ "leafGrid" AS (
+ SELECT a."id" AS "accountId", g.ord, g."periodEnd"
+ FROM "account" a
+ CROSS JOIN (
+ SELECT 0::BIGINT AS ord, NULL::DATE AS "periodEnd"
+ UNION ALL
+ -- qualify: "periodEnd" is also a RETURNS TABLE out-param name
+ SELECT p2.ord, p2."periodEnd" FROM "periods" p2
+ ) g
+ WHERE a."companyGroupId" = p_company_group_id
+ AND a."isGroup" = false
+ ),
+ "leafSeries" AS (
+ SELECT
+ lg."accountId", lg.ord, lg."periodEnd",
+ COALESCE(b."endingBalance", 0)
+ + SUM(COALESCE(bs."delta", 0))
+ OVER (PARTITION BY lg."accountId" ORDER BY lg.ord) AS "balanceAtDate"
+ FROM "leafGrid" lg
+ LEFT JOIN "bucketSums" bs ON bs."accountId" = lg."accountId" AND bs.ord = lg.ord
+ LEFT JOIN "base" b ON b."accountId" = lg."accountId"
+ ),
+ -- Filter ord 0 AFTER the window so LAG sees the opening row.
+ "leafWithChange" AS (
+ SELECT * FROM (
+ SELECT
+ ls."accountId", ls.ord, ls."periodEnd", ls."balanceAtDate",
+ ls."balanceAtDate"
+ - LAG(ls."balanceAtDate") OVER (PARTITION BY ls."accountId" ORDER BY ls.ord)
+ AS "netChange"
+ FROM "leafSeries" ls
+ ) x
+ WHERE x.ord > 0
+ )
+ SELECT
+ t."rootId" AS "accountId",
+ p."periodEnd",
+ COALESCE(SUM(lw."balanceAtDate"), 0)::NUMERIC AS "balanceAtDate",
+ COALESCE(SUM(lw."netChange"), 0)::NUMERIC AS "netChange"
+ FROM "accountTree" t
+ CROSS JOIN "periods" p
+ LEFT JOIN "leafWithChange" lw
+ ON lw."accountId" = t."id"
+ AND lw."periodEnd" = p."periodEnd"
+ AND t."isGroup" = false
+ GROUP BY t."rootId", p."periodEnd";
+END;
+$$;
+
+CREATE OR REPLACE FUNCTION "snapshotAccountingPeriodBalances" (
+ p_company_id TEXT,
+ p_period_id TEXT,
+ p_user_id TEXT
+) RETURNS void LANGUAGE plpgsql SECURITY DEFINER SET search_path = public
+AS $$
+DECLARE
+ v_end_date DATE;
+ v_close_status "periodCloseStatus";
+BEGIN
+ SELECT "endDate", "closeStatus" INTO v_end_date, v_close_status
+ FROM "accountingPeriod"
+ WHERE "id" = p_period_id AND "companyId" = p_company_id;
+
+ IF v_end_date IS NULL THEN
+ RAISE EXCEPTION 'Accounting period % not found for company %', p_period_id, p_company_id;
+ END IF;
+
+ -- Only Closed periods may hold a snapshot. A Closed period cannot receive new
+ -- postings (the journal_check_period_open trigger from the period-close
+ -- lifecycle blocks any journal whose postingDate lands in a closed period), so
+ -- its cumulative balance is frozen and the snapshot can never go stale.
+ -- closeAccountingPeriod flips the period to Closed inside its transaction
+ -- before calling this, so the check passes for the intended caller; refusing
+ -- anything else is defense-in-depth against writing a snapshot a later posting
+ -- could invalidate.
+ IF v_close_status IS DISTINCT FROM 'Closed' THEN
+ RAISE EXCEPTION 'Cannot snapshot accounting period %: period is not Closed (closeStatus=%)',
+ p_period_id, v_close_status;
+ END IF;
+
+ INSERT INTO "accountingPeriodBalance"
+ ("companyId", "accountingPeriodId", "accountId", "endingBalance", "endingBalanceDate", "createdBy")
+ SELECT
+ p_company_id,
+ p_period_id,
+ a."id",
+ COALESCE(SUM(CASE WHEN j."status" <> 'Draft' AND j."postingDate" <= v_end_date
+ THEN jl."amount" ELSE 0 END), 0),
+ v_end_date,
+ p_user_id
+ FROM "account" a
+ LEFT JOIN "journalLine" jl ON jl."accountId" = a."id" AND jl."companyId" = p_company_id
+ LEFT JOIN "journal" j ON j."id" = jl."journalId"
+ WHERE a."isGroup" = false
+ AND a."companyGroupId" = (SELECT "companyGroupId" FROM "company" WHERE "id" = p_company_id)
+ GROUP BY a."id"
+ ON CONFLICT ("accountId", "accountingPeriodId", "companyId")
+ DO UPDATE SET
+ "endingBalance" = EXCLUDED."endingBalance",
+ "endingBalanceDate" = EXCLUDED."endingBalanceDate",
+ "updatedBy" = p_user_id,
+ "updatedAt" = NOW();
+END;
+$$;
diff --git a/packages/database/supabase/migrations/20260909174352_account_for_memo_refunds_in_subledger_reports.sql b/packages/database/supabase/migrations/20260909174352_account_for_memo_refunds_in_subledger_reports.sql
new file mode 100644
index 0000000000..8ad7081d34
--- /dev/null
+++ b/packages/database/supabase/migrations/20260909174352_account_for_memo_refunds_in_subledger_reports.sql
@@ -0,0 +1,594 @@
+-- Refund cash has the opposite subledger sign to ordinary customer receipts /
+-- supplier disbursements. Memo principal remains exact in document currency;
+-- target carrying relief is appliedAmount, independent of realized FX.
+
+CREATE OR REPLACE FUNCTION get_ar_open_by_customer(
+ _company_id TEXT,
+ _as_of_date DATE
+)
+RETURNS TABLE (
+ "customerId" TEXT,
+ "documentId" TEXT,
+ "documentNumber" TEXT,
+ "documentType" TEXT,
+ "dateDue" DATE,
+ "currencyCode" TEXT,
+ "exchangeRate" NUMERIC,
+ "totalAmount" NUMERIC,
+ "settled" NUMERIC,
+ "openInCurrency" NUMERIC,
+ "openInBase" NUMERIC
+)
+LANGUAGE SQL
+SECURITY INVOKER
+AS $$
+ WITH effective_settlements AS (
+ SELECT s.*
+ FROM "invoiceSettlement" s
+ LEFT JOIN "payment" p ON p."id" = s."paymentId"
+ AND p."companyId" = s."companyId"
+ LEFT JOIN "memo" source_memo ON source_memo."id" = s."memoId"
+ AND source_memo."companyId" = s."companyId"
+ LEFT JOIN "payment" applying ON applying."id" = s."appliedViaPaymentId"
+ AND applying."companyId" = s."companyId"
+ WHERE s."companyId" = _company_id
+ AND (
+ (s."paymentId" IS NOT NULL AND p."status" = 'Posted'
+ AND p."postingDate" <= _as_of_date)
+ OR (s."memoId" IS NOT NULL AND source_memo."status" = 'Posted'
+ AND source_memo."postingDate" <= _as_of_date
+ AND ((s."appliedViaPaymentId" IS NULL AND s."appliedDate" <= _as_of_date) OR
+ (applying."status" = 'Posted' AND applying."postingDate" <= _as_of_date)))
+ )
+ ), invoice_settled AS (
+ SELECT s."targetSalesInvoiceId" AS invoice_id,
+ SUM(s."appliedAmount" + s."discountAmount" + s."writeOffAmount") AS settled_base,
+ SUM(COALESCE(s."sourceAmount", 0) + round(
+ (s."discountAmount" + s."writeOffAmount") * target."exchangeRate",
+ target_currency."decimalPlaces")) AS settled_document
+ FROM effective_settlements s
+ JOIN "salesInvoice" target ON target."id" = s."targetSalesInvoiceId"
+ AND target."companyId" = s."companyId"
+ LEFT JOIN "company" target_company ON target_company."id" = target."companyId"
+ LEFT JOIN "currency" target_currency ON target_currency."code" = target."currencyCode"
+ AND target_currency."companyGroupId" = target_company."companyGroupId"
+ WHERE s."targetSalesInvoiceId" IS NOT NULL
+ GROUP BY s."targetSalesInvoiceId"
+ ), memo_source_consumed AS (
+ SELECT s."memoId" AS memo_id, SUM(s."sourceAmount") AS settled_document,
+ bool_and(s."sourceAmount" IS NOT NULL) AS principal_known,
+ SUM(s."appliedAmount" + s."fxGainLossAmount") AS settled_base
+ FROM effective_settlements s
+ WHERE s."memoId" IS NOT NULL
+ GROUP BY s."memoId"
+ ), memo_target_settled AS (
+ SELECT s."targetMemoId" AS memo_id,
+ SUM(s."sourceAmount") AS settled_document,
+ bool_and(s."sourceAmount" IS NOT NULL) AS principal_known,
+ SUM(s."appliedAmount") AS settled_base
+ FROM effective_settlements s
+ WHERE s."targetMemoId" IS NOT NULL AND s."paymentId" IS NOT NULL
+ GROUP BY s."targetMemoId"
+ ), invoice_carrying AS (
+ -- Same original control snapshots used by post-payment; a document rate
+ -- conversion cannot reconstruct carrying value after document rounding.
+ SELECT line."documentId" AS invoice_id, SUM(line."amount") AS original_base
+ FROM "journalLine" line
+ JOIN "journal" j ON j."id"=line."journalId" AND j."companyId"=line."companyId"
+ WHERE line."companyId"=_company_id AND line."documentType"='Invoice'
+ AND line."description" IN ('Accounts Receivable','IC Receivables') AND j."sourceType"='Sales Invoice'
+ AND j."status"='Posted' AND j."postingDate"<=_as_of_date
+ GROUP BY line."documentId"
+ ), invoice_open AS (
+ SELECT i.*, COALESCE(s.settled_base, 0) AS settled_base,
+ amounts.remaining_document,
+ COALESCE(c.original_base, accounting_round_internal(i."totalAmount")) - COALESCE(s.settled_base,0) AS remaining_base
+ FROM "salesInvoices" i
+ JOIN "salesInvoice" ib ON ib."id" = i."id" AND ib."companyId" = i."companyId"
+ LEFT JOIN invoice_settled s ON s.invoice_id = i."id"
+ LEFT JOIN invoice_carrying c ON c.invoice_id = i."id"
+ LEFT JOIN "company" invoice_company ON invoice_company."id" = i."companyId"
+ LEFT JOIN "currency" invoice_currency ON invoice_currency."code" = i."currencyCode"
+ AND invoice_currency."companyGroupId" = invoice_company."companyGroupId"
+ CROSS JOIN LATERAL (
+ SELECT round(i."totalAmount" * i."exchangeRate", invoice_currency."decimalPlaces")
+ - COALESCE(s.settled_document, 0) AS remaining_document
+ ) amounts
+ WHERE i."companyId" = _company_id
+ AND i."postingDate" <= _as_of_date
+ AND i."status" NOT IN ('Draft', 'Pending', 'Voided')
+ AND NOT (ib."status" = 'Paid'
+ AND (ib."datePaid" IS NULL OR ib."datePaid" <= _as_of_date))
+ ), memo_open AS (
+ SELECT m.*,
+ accounting_round_internal(m."amount"/m."exchangeRate") - COALESCE(s.settled_base,0) - COALESCE(t.settled_base,0) AS remaining_base,
+ COALESCE(s.settled_document, 0) + COALESCE(t.settled_document, 0) AS settled_document,
+ m."amount" - COALESCE(s.settled_document, 0)
+ - COALESCE(t.settled_document, 0) AS remaining_document
+ FROM "memo" m
+ LEFT JOIN memo_source_consumed s ON s.memo_id = m."id"
+ LEFT JOIN memo_target_settled t ON t.memo_id = m."id"
+ WHERE m."companyId" = _company_id AND m."customerId" IS NOT NULL
+ AND m."status" = 'Posted' AND m."postingDate" <= _as_of_date
+ -- Unknown principal cannot be reconstructed from rounded carrying base.
+ AND COALESCE(s.principal_known, true) AND COALESCE(t.principal_known, true)
+ )
+ -- Preserve totalAmount/settled's existing per-document denomination:
+ -- invoices carry base; memo amount/settled carry memo currency.
+ SELECT i."customerId", i."id" AS "documentId", i."invoiceId" AS "documentNumber",
+ 'Invoice'::TEXT AS "documentType", i."dateDue", i."currencyCode", i."exchangeRate",
+ i."totalAmount", i.settled_base AS "settled",
+ i.remaining_document AS "openInCurrency",
+ i.remaining_base AS "openInBase"
+ FROM invoice_open i
+ WHERE i.remaining_document <> 0 OR i.remaining_base <> 0
+ UNION ALL
+ SELECT m."customerId", m."id", m."memoId", m."direction" || ' Memo',
+ NULL::DATE, m."currencyCode", m."exchangeRate", m."amount", m.settled_document,
+ (CASE WHEN m."direction" = 'Credit' THEN -1 ELSE 1 END) * m.remaining_document,
+ (CASE WHEN m."direction" = 'Credit' THEN -1 ELSE 1 END)
+ * m.remaining_base
+ FROM memo_open m
+ WHERE m.remaining_document <> 0 OR m.remaining_base <> 0
+ ORDER BY 1, 5 NULLS LAST;
+$$;
+
+CREATE OR REPLACE FUNCTION get_ap_open_by_supplier(
+ _company_id TEXT,
+ _as_of_date DATE
+)
+RETURNS TABLE (
+ "supplierId" TEXT,
+ "documentId" TEXT,
+ "documentNumber" TEXT,
+ "documentType" TEXT,
+ "dateDue" DATE,
+ "currencyCode" TEXT,
+ "exchangeRate" NUMERIC,
+ "totalAmount" NUMERIC,
+ "settled" NUMERIC,
+ "openInCurrency" NUMERIC,
+ "openInBase" NUMERIC
+)
+LANGUAGE SQL
+SECURITY INVOKER
+AS $$
+ WITH effective_settlements AS (
+ SELECT s.*
+ FROM "invoiceSettlement" s
+ LEFT JOIN "payment" p ON p."id" = s."paymentId"
+ AND p."companyId" = s."companyId"
+ LEFT JOIN "memo" source_memo ON source_memo."id" = s."memoId"
+ AND source_memo."companyId" = s."companyId"
+ LEFT JOIN "payment" applying ON applying."id" = s."appliedViaPaymentId"
+ AND applying."companyId" = s."companyId"
+ WHERE s."companyId" = _company_id
+ AND (
+ (s."paymentId" IS NOT NULL AND p."status" = 'Posted'
+ AND p."postingDate" <= _as_of_date)
+ OR (s."memoId" IS NOT NULL AND source_memo."status" = 'Posted'
+ AND source_memo."postingDate" <= _as_of_date
+ AND ((s."appliedViaPaymentId" IS NULL AND s."appliedDate" <= _as_of_date) OR
+ (applying."status" = 'Posted' AND applying."postingDate" <= _as_of_date)))
+ )
+ ), invoice_settled AS (
+ SELECT s."targetPurchaseInvoiceId" AS invoice_id,
+ SUM(s."appliedAmount" + s."discountAmount" + s."writeOffAmount") AS settled_base,
+ SUM(COALESCE(s."sourceAmount", 0) + round(
+ (s."discountAmount" + s."writeOffAmount") * target."exchangeRate",
+ target_currency."decimalPlaces")) AS settled_document
+ FROM effective_settlements s
+ JOIN "purchaseInvoice" target ON target."id" = s."targetPurchaseInvoiceId"
+ AND target."companyId" = s."companyId"
+ LEFT JOIN "company" target_company ON target_company."id" = target."companyId"
+ LEFT JOIN "currency" target_currency ON target_currency."code" = target."currencyCode"
+ AND target_currency."companyGroupId" = target_company."companyGroupId"
+ WHERE s."targetPurchaseInvoiceId" IS NOT NULL
+ GROUP BY s."targetPurchaseInvoiceId"
+ ), memo_source_consumed AS (
+ SELECT s."memoId" AS memo_id, SUM(s."sourceAmount") AS settled_document,
+ bool_and(s."sourceAmount" IS NOT NULL) AS principal_known,
+ SUM(s."appliedAmount" - s."fxGainLossAmount") AS settled_base
+ FROM effective_settlements s
+ WHERE s."memoId" IS NOT NULL
+ GROUP BY s."memoId"
+ ), memo_target_settled AS (
+ SELECT s."targetMemoId" AS memo_id,
+ SUM(s."sourceAmount") AS settled_document,
+ bool_and(s."sourceAmount" IS NOT NULL) AS principal_known,
+ SUM(s."appliedAmount") AS settled_base
+ FROM effective_settlements s
+ WHERE s."targetMemoId" IS NOT NULL AND s."paymentId" IS NOT NULL
+ GROUP BY s."targetMemoId"
+ ), invoice_carrying AS (
+ -- Same original control snapshots used by post-payment; a document rate
+ -- conversion cannot reconstruct carrying value after document rounding.
+ SELECT line."documentId" AS invoice_id, SUM(line."amount") AS original_base
+ FROM "journalLine" line
+ JOIN "journal" j ON j."id"=line."journalId" AND j."companyId"=line."companyId"
+ WHERE line."companyId"=_company_id AND line."documentType"='Invoice'
+ AND line."description" IN ('Accounts Payable','IC Payables') AND j."sourceType"='Purchase Invoice'
+ AND j."status"='Posted' AND j."postingDate"<=_as_of_date
+ GROUP BY line."documentId"
+ ), invoice_open AS (
+ SELECT i.*, COALESCE(s.settled_base, 0) AS settled_base,
+ amounts.remaining_document,
+ COALESCE(c.original_base, accounting_round_internal(i."totalAmount")) - COALESCE(s.settled_base,0) AS remaining_base
+ FROM "purchaseInvoices" i
+ JOIN "purchaseInvoice" ib ON ib."id" = i."id" AND ib."companyId" = i."companyId"
+ LEFT JOIN invoice_settled s ON s.invoice_id = i."id"
+ LEFT JOIN invoice_carrying c ON c.invoice_id = i."id"
+ LEFT JOIN "company" invoice_company ON invoice_company."id" = i."companyId"
+ LEFT JOIN "currency" invoice_currency ON invoice_currency."code" = i."currencyCode"
+ AND invoice_currency."companyGroupId" = invoice_company."companyGroupId"
+ CROSS JOIN LATERAL (
+ SELECT round(i."totalAmount" * i."exchangeRate", invoice_currency."decimalPlaces")
+ - COALESCE(s.settled_document, 0) AS remaining_document
+ ) amounts
+ WHERE i."companyId" = _company_id
+ AND i."postingDate" <= _as_of_date
+ AND i."status" NOT IN ('Draft', 'Pending', 'Voided')
+ AND NOT (ib."status" = 'Paid'
+ AND (ib."datePaid" IS NULL OR ib."datePaid" <= _as_of_date))
+ ), memo_open AS (
+ SELECT m.*,
+ accounting_round_internal(m."amount"/m."exchangeRate") - COALESCE(s.settled_base,0) - COALESCE(t.settled_base,0) AS remaining_base,
+ COALESCE(s.settled_document, 0) + COALESCE(t.settled_document, 0) AS settled_document,
+ m."amount" - COALESCE(s.settled_document, 0)
+ - COALESCE(t.settled_document, 0) AS remaining_document
+ FROM "memo" m
+ LEFT JOIN memo_source_consumed s ON s.memo_id = m."id"
+ LEFT JOIN memo_target_settled t ON t.memo_id = m."id"
+ WHERE m."companyId" = _company_id AND m."supplierId" IS NOT NULL
+ AND m."status" = 'Posted' AND m."postingDate" <= _as_of_date
+ -- Unknown principal cannot be reconstructed from rounded carrying base.
+ AND COALESCE(s.principal_known, true) AND COALESCE(t.principal_known, true)
+ )
+ -- Preserve totalAmount/settled's existing per-document denomination:
+ -- invoices carry base; memo amount/settled carry memo currency.
+ SELECT i."supplierId", i."id" AS "documentId", i."invoiceId" AS "documentNumber",
+ 'Invoice'::TEXT AS "documentType", i."dateDue", i."currencyCode", i."exchangeRate",
+ i."totalAmount", i.settled_base AS "settled",
+ i.remaining_document AS "openInCurrency",
+ i.remaining_base AS "openInBase"
+ FROM invoice_open i
+ WHERE i.remaining_document <> 0 OR i.remaining_base <> 0
+ UNION ALL
+ SELECT m."supplierId", m."id", m."memoId", m."direction" || ' Memo',
+ NULL::DATE, m."currencyCode", m."exchangeRate", m."amount", m.settled_document,
+ (CASE WHEN m."direction" = 'Debit' THEN -1 ELSE 1 END) * m.remaining_document,
+ (CASE WHEN m."direction" = 'Debit' THEN -1 ELSE 1 END)
+ * m.remaining_base
+ FROM memo_open m
+ WHERE m.remaining_document <> 0 OR m.remaining_base <> 0
+ ORDER BY 1, 5 NULLS LAST;
+$$;
+
+CREATE OR REPLACE FUNCTION get_ar_tie_out(
+ _company_id TEXT,
+ _as_of_date DATE
+)
+RETURNS TABLE (
+ "subledgerBalance" NUMERIC,
+ "glBalance" NUMERIC,
+ "variance" NUMERIC
+)
+LANGUAGE SQL
+SECURITY INVOKER
+AS $$
+ WITH funding_consumed AS (
+ SELECT COALESCE(s."sourcePaymentId", s."paymentId") AS source_payment_id,
+ SUM(s."appliedAmount" + CASE WHEN applying."paymentType" = 'Receipt'
+ THEN s."fxGainLossAmount" ELSE -s."fxGainLossAmount" END) AS source_base_amount
+ FROM "invoiceSettlement" s
+ JOIN "payment" applying ON applying."id" = s."paymentId"
+ AND applying."companyId" = s."companyId"
+ WHERE s."companyId" = _company_id
+ AND s."paymentId" IS NOT NULL
+ AND applying."status" = 'Posted'
+ AND applying."postingDate" <= _as_of_date
+ GROUP BY COALESCE(s."sourcePaymentId", s."paymentId")
+ ), payment_unapplied AS (
+ SELECT ((CASE WHEN p."paymentType" = 'Receipt' THEN 1 ELSE -1 END)
+ * (accounting_round_internal(p."totalAmount" / p."exchangeRate") - COALESCE(c.source_base_amount,0))) AS open_base
+ FROM "payment" p
+ LEFT JOIN funding_consumed c ON c.source_payment_id = p."id"
+ WHERE p."companyId" = _company_id
+ AND p."status" = 'Posted' AND p."postingDate" <= _as_of_date
+ -- Party determines the subledger; cash direction determines its sign.
+ AND p."customerId" IS NOT NULL
+ ), subledger AS (
+ SELECT COALESCE((SELECT SUM(o."openInBase")
+ FROM get_ar_open_by_customer(_company_id, _as_of_date) o), 0)
+ - COALESCE((SELECT SUM(open_base) FROM payment_unapplied), 0) AS amount
+ ), control_account AS (
+ -- A default change affects future postings; historical invoice, payment
+ -- and memo control accounts remain part of this company's subledger.
+ -- UNION deduplicates repeated control rows and overlap with current defaults.
+ SELECT unnest(ARRAY["receivablesAccount", "intercompanyReceivablesAccount"]) AS account_id
+ FROM "accountDefault" WHERE "companyId" = _company_id
+ UNION
+ SELECT line."accountId"
+ FROM "journalLine" line
+ JOIN "journal" j ON j."id" = line."journalId" AND j."companyId" = line."companyId"
+ WHERE line."companyId" = _company_id
+ AND j."status" = 'Posted' AND j."postingDate" <= _as_of_date
+ AND (
+ (j."sourceType" = 'Sales Invoice' AND line."documentType" = 'Invoice'
+ AND line."description" = 'Accounts Receivable')
+ OR (j."sourceType" = 'Payment' AND line."documentType" = 'Payment'
+ AND line."description" IN ('Accounts Receivable',
+ 'Accounts Receivable (on-account credit)', 'Accounts Receivable (credit applied)'))
+ OR (j."sourceType" IN ('Credit Memo', 'Debit Memo') AND line."documentType" = 'Memo'
+ AND line."description" = 'Accounts Receivable')
+ )
+ ), gl AS (
+ SELECT COALESCE(SUM(jl."amount"), 0) AS amount
+ FROM "journalLine" jl
+ JOIN "journal" j ON j."id" = jl."journalId" AND j."companyId" = jl."companyId"
+ JOIN control_account a ON a.account_id = jl."accountId"
+ WHERE jl."companyId" = _company_id
+ AND j."postingDate" <= _as_of_date AND j."status" = 'Posted'
+ )
+ SELECT subledger.amount AS "subledgerBalance", gl.amount AS "glBalance",
+ subledger.amount - gl.amount AS "variance"
+ FROM subledger, gl;
+$$;
+
+CREATE OR REPLACE FUNCTION get_ap_tie_out(
+ _company_id TEXT,
+ _as_of_date DATE
+)
+RETURNS TABLE (
+ "subledgerBalance" NUMERIC,
+ "glBalance" NUMERIC,
+ "variance" NUMERIC
+)
+LANGUAGE SQL
+SECURITY INVOKER
+AS $$
+ WITH funding_consumed AS (
+ SELECT COALESCE(s."sourcePaymentId", s."paymentId") AS source_payment_id,
+ SUM(s."appliedAmount" + CASE WHEN applying."paymentType" = 'Receipt'
+ THEN s."fxGainLossAmount" ELSE -s."fxGainLossAmount" END) AS source_base_amount
+ FROM "invoiceSettlement" s
+ JOIN "payment" applying ON applying."id" = s."paymentId"
+ AND applying."companyId" = s."companyId"
+ WHERE s."companyId" = _company_id
+ AND s."paymentId" IS NOT NULL
+ AND applying."status" = 'Posted'
+ AND applying."postingDate" <= _as_of_date
+ GROUP BY COALESCE(s."sourcePaymentId", s."paymentId")
+ ), payment_unapplied AS (
+ SELECT ((CASE WHEN p."paymentType" = 'Disbursement' THEN 1 ELSE -1 END)
+ * (accounting_round_internal(p."totalAmount" / p."exchangeRate") - COALESCE(c.source_base_amount,0))) AS open_base
+ FROM "payment" p
+ LEFT JOIN funding_consumed c ON c.source_payment_id = p."id"
+ WHERE p."companyId" = _company_id
+ AND p."status" = 'Posted' AND p."postingDate" <= _as_of_date
+ -- Party determines the subledger; cash direction determines its sign.
+ AND p."supplierId" IS NOT NULL
+ ), subledger AS (
+ SELECT COALESCE((SELECT SUM(o."openInBase")
+ FROM get_ap_open_by_supplier(_company_id, _as_of_date) o), 0)
+ - COALESCE((SELECT SUM(open_base) FROM payment_unapplied), 0) AS amount
+ ), control_account AS (
+ SELECT unnest(ARRAY["payablesAccount", "intercompanyPayablesAccount"]) AS account_id
+ FROM "accountDefault" WHERE "companyId" = _company_id
+ UNION
+ SELECT line."accountId"
+ FROM "journalLine" line
+ JOIN "journal" j ON j."id" = line."journalId" AND j."companyId" = line."companyId"
+ WHERE line."companyId" = _company_id
+ AND j."status" = 'Posted' AND j."postingDate" <= _as_of_date
+ AND (
+ (j."sourceType" = 'Purchase Invoice' AND line."documentType" = 'Invoice'
+ AND line."description" = 'Accounts Payable')
+ OR (j."sourceType" = 'Payment' AND line."documentType" = 'Payment'
+ AND line."description" IN ('Accounts Payable',
+ 'Accounts Payable (on-account credit)', 'Accounts Payable (credit applied)'))
+ OR (j."sourceType" IN ('Credit Memo', 'Debit Memo') AND line."documentType" = 'Memo'
+ AND line."description" = 'Accounts Payable')
+ )
+ ), gl AS (
+ SELECT COALESCE(SUM(jl."amount"), 0) AS amount
+ FROM "journalLine" jl
+ JOIN "journal" j ON j."id" = jl."journalId" AND j."companyId" = jl."companyId"
+ JOIN control_account a ON a.account_id = jl."accountId"
+ WHERE jl."companyId" = _company_id
+ AND j."postingDate" <= _as_of_date AND j."status" = 'Posted'
+ )
+ SELECT subledger.amount AS "subledgerBalance", gl.amount AS "glBalance",
+ subledger.amount - gl.amount AS "variance"
+ FROM subledger, gl;
+$$;
+
+CREATE OR REPLACE FUNCTION get_ar_aging(
+ _company_id TEXT,
+ _as_of_date DATE,
+ _aging_method TEXT DEFAULT 'dueDate',
+ _bucket1 INTEGER DEFAULT 30,
+ _bucket2 INTEGER DEFAULT 60,
+ _bucket3 INTEGER DEFAULT 90
+)
+RETURNS TABLE (
+ "customerId" TEXT,
+ "paymentTerm" TEXT,
+ "current" NUMERIC,
+ "bucket1" NUMERIC,
+ "bucket2" NUMERIC,
+ "bucket3" NUMERIC,
+ "bucket4" NUMERIC,
+ "unapplied" NUMERIC,
+ "total" NUMERIC
+)
+LANGUAGE SQL
+SECURITY INVOKER
+AS $$
+ WITH funding_consumed AS (
+ SELECT COALESCE(s."sourcePaymentId", s."paymentId") AS source_payment_id,
+ SUM(s."appliedAmount" + CASE WHEN applying."paymentType" = 'Receipt'
+ THEN s."fxGainLossAmount" ELSE -s."fxGainLossAmount" END) AS source_base_amount
+ FROM "invoiceSettlement" s
+ JOIN "payment" applying ON applying."id" = s."paymentId"
+ AND applying."companyId" = s."companyId"
+ WHERE s."companyId" = _company_id
+ AND s."paymentId" IS NOT NULL
+ AND applying."status" = 'Posted'
+ AND applying."postingDate" <= _as_of_date
+ GROUP BY COALESCE(s."sourcePaymentId", s."paymentId")
+ ), open_items AS (
+ SELECT o."customerId",
+ CASE WHEN o."documentType" = 'Invoice' THEN
+ CASE WHEN _aging_method = 'documentDate' THEN COALESCE(i."dateIssued", i."postingDate")
+ ELSE o."dateDue" END
+ ELSE m."memoDate" END AS age_date,
+ o."openInBase" AS open_base
+ FROM get_ar_open_by_customer(_company_id, _as_of_date) o
+ LEFT JOIN "salesInvoice" i ON i."id" = o."documentId"
+ AND i."companyId" = _company_id AND o."documentType" = 'Invoice'
+ LEFT JOIN "memo" m ON m."id" = o."documentId"
+ AND m."companyId" = _company_id AND o."documentType" <> 'Invoice'
+ ),
+ buckets AS (
+ SELECT
+ "customerId",
+ COALESCE(SUM(open_base) FILTER (WHERE age_date IS NULL OR age_date >= _as_of_date), 0) AS "current",
+ COALESCE(SUM(open_base) FILTER (WHERE age_date < _as_of_date AND _as_of_date - age_date BETWEEN 1 AND _bucket1), 0) AS "bucket1",
+ COALESCE(SUM(open_base) FILTER (WHERE _as_of_date - age_date BETWEEN _bucket1 + 1 AND _bucket2), 0) AS "bucket2",
+ COALESCE(SUM(open_base) FILTER (WHERE _as_of_date - age_date BETWEEN _bucket2 + 1 AND _bucket3), 0) AS "bucket3",
+ COALESCE(SUM(open_base) FILTER (WHERE _as_of_date - age_date > _bucket3), 0) AS "bucket4"
+ FROM open_items
+ WHERE open_base <> 0
+ GROUP BY "customerId"
+ ),
+ unapplied AS (
+ SELECT p."customerId",
+ -COALESCE(SUM(((CASE WHEN p."paymentType" = 'Receipt' THEN 1 ELSE -1 END)
+ * (accounting_round_internal(p."totalAmount" / p."exchangeRate") - COALESCE(c.source_base_amount,0)))), 0) AS "unapplied"
+ FROM "payment" p
+ LEFT JOIN funding_consumed c ON c.source_payment_id = p."id"
+ WHERE p."companyId" = _company_id
+ AND p."status" = 'Posted' AND p."postingDate" <= _as_of_date
+ AND p."customerId" IS NOT NULL
+ GROUP BY p."customerId"
+ )
+ SELECT
+ COALESCE(ib."customerId", u."customerId") AS "customerId",
+ pt."name" AS "paymentTerm",
+ COALESCE(ib."current", 0) AS "current",
+ COALESCE(ib."bucket1", 0) AS "bucket1",
+ COALESCE(ib."bucket2", 0) AS "bucket2",
+ COALESCE(ib."bucket3", 0) AS "bucket3",
+ COALESCE(ib."bucket4", 0) AS "bucket4",
+ COALESCE(u."unapplied", 0) AS "unapplied",
+ COALESCE(ib."current", 0) + COALESCE(ib."bucket1", 0)
+ + COALESCE(ib."bucket2", 0) + COALESCE(ib."bucket3", 0)
+ + COALESCE(ib."bucket4", 0) + COALESCE(u."unapplied", 0) AS "total"
+ FROM buckets ib
+ FULL OUTER JOIN unapplied u ON u."customerId" = ib."customerId"
+ LEFT JOIN "customerPayment" cp
+ ON cp."customerId" = COALESCE(ib."customerId", u."customerId")
+ AND cp."companyId" = _company_id
+ LEFT JOIN "paymentTerm" pt ON pt."id" = cp."paymentTermId"
+ WHERE
+ COALESCE(ib."current", 0) + COALESCE(ib."bucket1", 0)
+ + COALESCE(ib."bucket2", 0) + COALESCE(ib."bucket3", 0)
+ + COALESCE(ib."bucket4", 0) + COALESCE(u."unapplied", 0) <> 0
+ ORDER BY "total" DESC;
+$$;
+
+CREATE OR REPLACE FUNCTION get_ap_aging(
+ _company_id TEXT,
+ _as_of_date DATE,
+ _aging_method TEXT DEFAULT 'dueDate',
+ _bucket1 INTEGER DEFAULT 30,
+ _bucket2 INTEGER DEFAULT 60,
+ _bucket3 INTEGER DEFAULT 90
+)
+RETURNS TABLE (
+ "supplierId" TEXT,
+ "paymentTerm" TEXT,
+ "current" NUMERIC,
+ "bucket1" NUMERIC,
+ "bucket2" NUMERIC,
+ "bucket3" NUMERIC,
+ "bucket4" NUMERIC,
+ "unapplied" NUMERIC,
+ "total" NUMERIC
+)
+LANGUAGE SQL
+SECURITY INVOKER
+AS $$
+ WITH funding_consumed AS (
+ SELECT COALESCE(s."sourcePaymentId", s."paymentId") AS source_payment_id,
+ SUM(s."appliedAmount" + CASE WHEN applying."paymentType" = 'Receipt'
+ THEN s."fxGainLossAmount" ELSE -s."fxGainLossAmount" END) AS source_base_amount
+ FROM "invoiceSettlement" s
+ JOIN "payment" applying ON applying."id" = s."paymentId"
+ AND applying."companyId" = s."companyId"
+ WHERE s."companyId" = _company_id
+ AND s."paymentId" IS NOT NULL
+ AND applying."status" = 'Posted'
+ AND applying."postingDate" <= _as_of_date
+ GROUP BY COALESCE(s."sourcePaymentId", s."paymentId")
+ ), open_items AS (
+ SELECT o."supplierId",
+ CASE WHEN o."documentType" = 'Invoice' THEN
+ CASE WHEN _aging_method = 'documentDate' THEN COALESCE(i."dateIssued", i."postingDate")
+ ELSE o."dateDue" END
+ ELSE m."memoDate" END AS age_date,
+ o."openInBase" AS open_base
+ FROM get_ap_open_by_supplier(_company_id, _as_of_date) o
+ LEFT JOIN "purchaseInvoice" i ON i."id" = o."documentId"
+ AND i."companyId" = _company_id AND o."documentType" = 'Invoice'
+ LEFT JOIN "memo" m ON m."id" = o."documentId"
+ AND m."companyId" = _company_id AND o."documentType" <> 'Invoice'
+ ),
+ buckets AS (
+ SELECT
+ "supplierId",
+ COALESCE(SUM(open_base) FILTER (WHERE age_date IS NULL OR age_date >= _as_of_date), 0) AS "current",
+ COALESCE(SUM(open_base) FILTER (WHERE age_date < _as_of_date AND _as_of_date - age_date BETWEEN 1 AND _bucket1), 0) AS "bucket1",
+ COALESCE(SUM(open_base) FILTER (WHERE _as_of_date - age_date BETWEEN _bucket1 + 1 AND _bucket2), 0) AS "bucket2",
+ COALESCE(SUM(open_base) FILTER (WHERE _as_of_date - age_date BETWEEN _bucket2 + 1 AND _bucket3), 0) AS "bucket3",
+ COALESCE(SUM(open_base) FILTER (WHERE _as_of_date - age_date > _bucket3), 0) AS "bucket4"
+ FROM open_items
+ WHERE open_base <> 0
+ GROUP BY "supplierId"
+ ),
+ unapplied AS (
+ SELECT p."supplierId",
+ -COALESCE(SUM(((CASE WHEN p."paymentType" = 'Disbursement' THEN 1 ELSE -1 END)
+ * (accounting_round_internal(p."totalAmount" / p."exchangeRate") - COALESCE(c.source_base_amount,0)))), 0) AS "unapplied"
+ FROM "payment" p
+ LEFT JOIN funding_consumed c ON c.source_payment_id = p."id"
+ WHERE p."companyId" = _company_id
+ AND p."status" = 'Posted' AND p."postingDate" <= _as_of_date
+ AND p."supplierId" IS NOT NULL
+ GROUP BY p."supplierId"
+ )
+ SELECT
+ COALESCE(ib."supplierId", u."supplierId") AS "supplierId",
+ pt."name" AS "paymentTerm",
+ COALESCE(ib."current", 0) AS "current",
+ COALESCE(ib."bucket1", 0) AS "bucket1",
+ COALESCE(ib."bucket2", 0) AS "bucket2",
+ COALESCE(ib."bucket3", 0) AS "bucket3",
+ COALESCE(ib."bucket4", 0) AS "bucket4",
+ COALESCE(u."unapplied", 0) AS "unapplied",
+ COALESCE(ib."current", 0) + COALESCE(ib."bucket1", 0)
+ + COALESCE(ib."bucket2", 0) + COALESCE(ib."bucket3", 0)
+ + COALESCE(ib."bucket4", 0) + COALESCE(u."unapplied", 0) AS "total"
+ FROM buckets ib
+ FULL OUTER JOIN unapplied u ON u."supplierId" = ib."supplierId"
+ LEFT JOIN "supplierPayment" sp
+ ON sp."supplierId" = COALESCE(ib."supplierId", u."supplierId")
+ AND sp."companyId" = _company_id
+ LEFT JOIN "paymentTerm" pt ON pt."id" = sp."paymentTermId"
+ WHERE
+ COALESCE(ib."current", 0) + COALESCE(ib."bucket1", 0)
+ + COALESCE(ib."bucket2", 0) + COALESCE(ib."bucket3", 0)
+ + COALESCE(ib."bucket4", 0) + COALESCE(u."unapplied", 0) <> 0
+ ORDER BY "total" DESC;
+$$;
diff --git a/packages/database/supabase/tests/accounting-balances-and-reports.test.sql b/packages/database/supabase/tests/accounting-balances-and-reports.test.sql
new file mode 100644
index 0000000000..d299b25136
--- /dev/null
+++ b/packages/database/supabase/tests/accounting-balances-and-reports.test.sql
@@ -0,0 +1,646 @@
+-- AR/AP balances, source funding and reporting contracts against the real views/RPCs.
+-- Run from the repository root via scripts/run-local-accounting-check.ts psql.
+-- Every fixture owns its company/group/parties/accounts. No fixture touches real
+-- documents; transaction rollback and event suppression cover all scenarios.
+\set ON_ERROR_STOP on
+BEGIN;
+SET LOCAL "app.sync_in_progress" = 'true';
+SET LOCAL statement_timeout = '60s';
+CREATE TEMP SEQUENCE report_case_count;
+
+CREATE TYPE pg_temp.report_fixture AS (
+ group_id text, company_id text, customer_id text, supplier_id text,
+ supplier_interaction_id text, ar_account text, ap_account text, bank_account text,
+ reason_account text, period_id text
+);
+
+CREATE FUNCTION pg_temp.seed_report_company() RETURNS pg_temp.report_fixture
+LANGUAGE plpgsql AS $fn$
+DECLARE f pg_temp.report_fixture; defaults_json jsonb;
+BEGIN
+ INSERT INTO "companyGroup" (name,"createdBy") VALUES ('Reporting harness '||id(),'system') RETURNING id INTO f.group_id;
+ INSERT INTO "company" (name,"companyGroupId","baseCurrencyCode",timezone)
+ VALUES ('Reporting harness '||id(),f.group_id,'USD','America/New_York') RETURNING id INTO f.company_id;
+ INSERT INTO "currency" (code,"companyGroupId","decimalPlaces","createdBy")
+ VALUES ('USD',f.group_id,2,'system'),('EUR',f.group_id,2,'system');
+ INSERT INTO "customer" (name,"readableId","companyId") VALUES ('Harness customer','HC-'||id(),f.company_id) RETURNING id INTO f.customer_id;
+ INSERT INTO "supplier" (name,"readableId","companyId") VALUES ('Harness supplier','HS-'||id(),f.company_id) RETURNING id INTO f.supplier_id;
+ INSERT INTO "supplierInteraction" ("companyId","supplierId") VALUES (f.company_id,f.supplier_id) RETURNING id INTO f.supplier_interaction_id;
+ INSERT INTO "account" (name,class,"accountType","incomeBalance","companyGroupId","createdBy")
+ VALUES ('Harness AR','Asset','Accounts Receivable','Balance Sheet',f.group_id,'system') RETURNING id INTO f.ar_account;
+ INSERT INTO "account" (name,class,"accountType","incomeBalance","companyGroupId","createdBy")
+ VALUES ('Harness AP','Liability','Accounts Payable','Balance Sheet',f.group_id,'system') RETURNING id INTO f.ap_account;
+ INSERT INTO "account" (name,class,"accountType","incomeBalance","companyGroupId","createdBy")
+ VALUES ('Harness bank','Asset','Bank','Balance Sheet',f.group_id,'system') RETURNING id INTO f.bank_account;
+ INSERT INTO "account" (name,class,"accountType","incomeBalance","companyGroupId","createdBy")
+ VALUES ('Harness reason','Expense','Expense','Income Statement',f.group_id,'system') RETURNING id INTO f.reason_account;
+ SELECT jsonb_object_agg(attname,to_jsonb(f.reason_account)) INTO defaults_json
+ FROM pg_attribute WHERE attrelid='"accountDefault"'::regclass AND attnum>0 AND NOT attisdropped AND attnotnull AND attname<>'companyId';
+ INSERT INTO "accountDefault" SELECT (jsonb_populate_record(NULL::"accountDefault",defaults_json||jsonb_build_object(
+ 'companyId',f.company_id,'receivablesAccount',f.ar_account,'payablesAccount',f.ap_account,'bankCashAccount',f.bank_account))).*;
+ INSERT INTO "accountingPeriod" ("startDate","endDate",status,"companyId","createdBy","fiscalYear","periodNumber")
+ VALUES ('2026-01-01','2026-12-31','Active',f.company_id,'system',2026,1) RETURNING id INTO f.period_id;
+ RETURN f;
+END;
+$fn$;
+
+CREATE FUNCTION pg_temp.book_control(f pg_temp.report_fixture,is_ar boolean,amount_base numeric,at_date date,invoice_id text DEFAULT NULL,
+ source_type text DEFAULT NULL,source_id text DEFAULT NULL,control_suffix text DEFAULT '')
+RETURNS text LANGUAGE plpgsql AS $fn$
+DECLARE j text;
+BEGIN
+ INSERT INTO journal ("companyId","journalEntryId","postingDate","accountingPeriodId",status,"sourceType","createdBy")
+ VALUES (f.company_id,'HJ-'||id(),at_date,f.period_id,'Draft',COALESCE(source_type,CASE WHEN invoice_id IS NULL THEN 'Payment' WHEN is_ar THEN 'Sales Invoice' ELSE 'Purchase Invoice' END)::"journalEntrySourceType",'system') RETURNING id INTO j;
+ INSERT INTO "journalLine" ("journalId","accountId",amount,"journalLineReference","companyId","documentType","documentId",description) VALUES
+ (j,CASE WHEN is_ar THEN f.ar_account ELSE f.ap_account END,round(amount_base,5),'control-'||id(),f.company_id,
+ CASE WHEN invoice_id IS NOT NULL THEN 'Invoice' WHEN source_type='Payment' THEN 'Payment' WHEN source_type IN ('Credit Memo','Debit Memo') THEN 'Memo' END::"journalLineDocumentType",
+ COALESCE(invoice_id,source_id),(CASE WHEN is_ar THEN 'Accounts Receivable' ELSE 'Accounts Payable' END)||control_suffix),
+ (j,f.bank_account,round(CASE WHEN is_ar THEN -amount_base ELSE amount_base END,5),'offset-'||id(),f.company_id,NULL,NULL,NULL);
+ UPDATE journal SET status='Posted' WHERE id=j AND "companyId"=f.company_id;
+ RETURN j;
+END;
+$fn$;
+
+CREATE FUNCTION pg_temp.replace_control_default(f pg_temp.report_fixture,is_ar boolean)
+RETURNS text LANGUAGE plpgsql AS $fn$
+DECLARE new_account text;
+BEGIN
+ INSERT INTO "account" (name,class,"accountType","incomeBalance","companyGroupId","createdBy")
+ VALUES ('Replacement control',CASE WHEN is_ar THEN 'Asset' ELSE 'Liability' END::"glAccountClass",
+ CASE WHEN is_ar THEN 'Accounts Receivable' ELSE 'Accounts Payable' END::"accountType",'Balance Sheet',f.group_id,'system') RETURNING id INTO new_account;
+ IF is_ar THEN UPDATE "accountDefault" SET "receivablesAccount"=new_account WHERE "companyId"=f.company_id;
+ ELSE UPDATE "accountDefault" SET "payablesAccount"=new_account WHERE "companyId"=f.company_id; END IF;
+ RETURN new_account;
+END;
+$fn$;
+
+CREATE FUNCTION pg_temp.seed_invoice(f pg_temp.report_fixture,is_ar boolean,amount_base numeric,rate numeric,
+ at_date date DEFAULT '2026-01-01',due_date date DEFAULT '2026-01-31',document_status text DEFAULT NULL)
+RETURNS text LANGUAGE plpgsql AS $fn$
+DECLARE doc text;
+BEGIN
+ IF is_ar THEN
+ INSERT INTO "salesInvoice" ("invoiceId","customerId","currencyCode","exchangeRate","companyId","createdBy","postingDate","dateIssued","dateDue",status)
+ VALUES ('HI-'||id(),f.customer_id,'EUR',rate,f.company_id,'system',at_date,at_date,due_date,COALESCE(document_status,'Submitted')::"salesInvoiceStatus") RETURNING id INTO doc;
+ INSERT INTO "salesInvoiceLine" ("invoiceId","invoiceLineType","unitOfMeasureCode","companyId","createdBy",quantity,"unitPrice","exchangeRate")
+ VALUES (doc,'Service','EA',f.company_id,'system',1,amount_base,rate);
+ ELSE
+ INSERT INTO "purchaseInvoice" ("invoiceId","supplierId","supplierInteractionId","currencyCode","exchangeRate","companyId","createdBy","postingDate","dateIssued","dateDue",status)
+ VALUES ('HI-'||id(),f.supplier_id,f.supplier_interaction_id,'EUR',rate,f.company_id,'system',at_date,at_date,due_date,COALESCE(document_status,'Open')::"purchaseInvoiceStatus") RETURNING id INTO doc;
+ INSERT INTO "purchaseInvoiceLine" ("invoiceId","invoiceLineType","companyId","createdBy",quantity,"supplierUnitPrice","exchangeRate","accountId")
+ VALUES (doc,'G/L Account',f.company_id,'system',1,amount_base*rate,rate,f.reason_account);
+ END IF;
+ RETURN doc;
+END;
+$fn$;
+
+CREATE FUNCTION pg_temp.seed_payment(f pg_temp.report_fixture,is_ar boolean,amount_document numeric,rate numeric,at_date date,status_text text DEFAULT 'Posted')
+RETURNS text LANGUAGE plpgsql AS $fn$
+DECLARE p text;
+BEGIN
+ INSERT INTO payment ("paymentId","paymentType","customerId","supplierId","paymentDate","postingDate","currencyCode","exchangeRate","totalAmount","bankAccount","companyId","createdBy",status)
+ VALUES ('HP-'||id(),CASE WHEN is_ar THEN 'Receipt' ELSE 'Disbursement' END::"paymentType",CASE WHEN is_ar THEN f.customer_id END,CASE WHEN NOT is_ar THEN f.supplier_id END,at_date,at_date,'EUR',rate,amount_document,f.bank_account,f.company_id,'system',status_text::"paymentStatus") RETURNING id INTO p;
+ RETURN p;
+END;
+$fn$;
+
+-- payment_party_check permits exactly one party and deliberately decouples the
+-- direction from it: a Receipt whose party is a SUPPLIER is an AP refund, and a
+-- Disbursement whose party is a CUSTOMER is an AR refund. Same paymentType as
+-- seed_payment, opposite party -- so this cash belongs to the OTHER subledger.
+CREATE FUNCTION pg_temp.seed_crossparty_payment(f pg_temp.report_fixture,is_ar boolean,amount_document numeric,rate numeric,at_date date,status_text text DEFAULT 'Posted')
+RETURNS text LANGUAGE plpgsql AS $fn$
+DECLARE p text;
+BEGIN
+ INSERT INTO payment ("paymentId","paymentType","customerId","supplierId","paymentDate","postingDate","currencyCode","exchangeRate","totalAmount","bankAccount","companyId","createdBy",status)
+ VALUES ('HX-'||id(),CASE WHEN is_ar THEN 'Receipt' ELSE 'Disbursement' END::"paymentType",CASE WHEN NOT is_ar THEN f.customer_id END,CASE WHEN is_ar THEN f.supplier_id END,at_date,at_date,'EUR',rate,amount_document,f.bank_account,f.company_id,'system',status_text::"paymentStatus") RETURNING id INTO p;
+ RETURN p;
+END;
+$fn$;
+
+CREATE FUNCTION pg_temp.seed_memo(f pg_temp.report_fixture,is_ar boolean,amount_document numeric,rate numeric,at_date date,credit_to_invoice boolean DEFAULT true)
+RETURNS text LANGUAGE plpgsql AS $fn$
+DECLARE m text;
+BEGIN
+ INSERT INTO memo ("memoId",direction,"customerId","supplierId","memoDate","postingDate","currencyCode","exchangeRate",amount,"reasonAccount","companyId","createdBy",status)
+ VALUES ('HM-'||id(),CASE WHEN is_ar=credit_to_invoice THEN 'Credit' ELSE 'Debit' END::"memoDirection",CASE WHEN is_ar THEN f.customer_id END,CASE WHEN NOT is_ar THEN f.supplier_id END,at_date,at_date,'EUR',rate,amount_document,f.reason_account,f.company_id,'system','Posted') RETURNING id INTO m;
+ RETURN m;
+END;
+$fn$;
+
+CREATE FUNCTION pg_temp.apply_cash(f pg_temp.report_fixture,is_ar boolean,payment_id text,invoice_id text,amount_document numeric,applied_base numeric,source_rate numeric,target_rate numeric,at_date date,source_id text DEFAULT NULL,discount_base numeric DEFAULT 0,writeoff_base numeric DEFAULT 0)
+RETURNS text LANGUAGE plpgsql AS $fn$
+DECLARE s text;
+BEGIN
+ INSERT INTO "invoiceSettlement" ("paymentId","sourcePaymentId","targetSalesInvoiceId","targetPurchaseInvoiceId","sourceAmount","appliedAmount","sourceExchangeRate","targetExchangeRate","fxGainLossAmount","discountAmount","writeOffAmount","appliedDate","companyId","createdBy")
+ VALUES (payment_id,source_id,CASE WHEN is_ar THEN invoice_id END,CASE WHEN NOT is_ar THEN invoice_id END,amount_document,applied_base,source_rate,target_rate,
+ round(CASE WHEN is_ar THEN amount_document/source_rate-applied_base ELSE applied_base-amount_document/source_rate END,5),discount_base,writeoff_base,at_date,f.company_id,'system') RETURNING id INTO s;
+ RETURN s;
+END;
+$fn$;
+
+CREATE FUNCTION pg_temp.assert_reports(f pg_temp.report_fixture,is_ar boolean,at_date date,expected_items numeric,expected_unapplied numeric,expected_gl numeric,label text)
+RETURNS void LANGUAGE plpgsql AS $fn$
+DECLARE open_sum numeric; aging_sum numeric; gl_row record; detail_rows jsonb; tolerance constant numeric := .00001;
+BEGIN
+ IF is_ar THEN
+ SELECT COALESCE(sum("openInBase"),0) INTO open_sum FROM get_ar_open_by_customer(f.company_id,at_date);
+ SELECT COALESCE(sum(total),0) INTO aging_sum FROM get_ar_aging(f.company_id,at_date);
+ SELECT * INTO STRICT gl_row FROM get_ar_tie_out(f.company_id,at_date);
+ ELSE
+ SELECT COALESCE(sum("openInBase"),0) INTO open_sum FROM get_ap_open_by_supplier(f.company_id,at_date);
+ SELECT COALESCE(sum(total),0) INTO aging_sum FROM get_ap_aging(f.company_id,at_date);
+ SELECT * INTO STRICT gl_row FROM get_ap_tie_out(f.company_id,at_date);
+ END IF;
+ ASSERT abs(open_sum-expected_items)<tolerance, label||': open items '||open_sum||' expected '||expected_items;
+ ASSERT abs(aging_sum-(expected_items+expected_unapplied))<tolerance,label||': aging total '||aging_sum;
+ ASSERT abs(gl_row."subledgerBalance"-(expected_items+expected_unapplied))<tolerance,label||': subledger '||gl_row."subledgerBalance";
+ ASSERT abs(gl_row."glBalance"-expected_gl)<tolerance,label||': control GL '||gl_row."glBalance";
+ ASSERT abs(gl_row.variance)<tolerance,label||': tie-out variance '||gl_row.variance;
+ PERFORM nextval('pg_temp.report_case_count');
+ RAISE NOTICE 'PASS % %',CASE WHEN is_ar THEN 'AR' ELSE 'AP' END,label;
+END;
+$fn$;
+
+CREATE FUNCTION pg_temp.assert_invoice(f pg_temp.report_fixture,is_ar boolean,doc text,expected_document numeric,expected_status text,label text)
+RETURNS void LANGUAGE plpgsql AS $fn$
+DECLARE row_value record;
+BEGIN
+ IF is_ar THEN SELECT status,balance,"exchangeRate" INTO STRICT row_value FROM "salesInvoices" WHERE id=doc AND "companyId"=f.company_id;
+ ELSE SELECT status,balance,"exchangeRate" INTO STRICT row_value FROM "purchaseInvoices" WHERE id=doc AND "companyId"=f.company_id; END IF;
+ ASSERT row_value.balance*row_value."exchangeRate"=expected_document,label||': document remainder '||(row_value.balance*row_value."exchangeRate");
+ ASSERT row_value.status=expected_status,label||': status '||row_value.status;
+END;
+$fn$;
+
+-- Refund cash belongs to its party's subledger, with the opposite cash sign.
+-- Its target memo uses exact document principal independently of carrying base.
+DO $refund_cases$
+DECLARE f pg_temp.report_fixture; is_ar boolean; m text; p text; application text; j text; actual numeric; phase text;
+BEGIN
+ FOREACH is_ar IN ARRAY ARRAY[true,false] LOOP
+ BEGIN
+ f:=pg_temp.seed_report_company();
+ p:=pg_temp.seed_crossparty_payment(f,NOT is_ar,55,1.1,'2026-02-01');
+ PERFORM pg_temp.book_control(f,is_ar,50,'2026-02-01',NULL,'Payment',p);
+ PERFORM pg_temp.assert_reports(f,is_ar,'2026-02-01',0,50,50,'unallocated refund');
+ PERFORM pg_temp.assert_reports(f,NOT is_ar,'2026-02-01',0,0,0,'refund excluded from other party subledger');
+ PERFORM pg_temp.assert_reports(f,is_ar,'2026-01-31',0,0,0,'future refund excluded');
+ UPDATE payment SET status='Voided' WHERE id=p AND "companyId"=f.company_id;
+ PERFORM pg_temp.book_control(f,is_ar,-50,'2026-02-02',NULL,'Payment',p);
+ PERFORM pg_temp.assert_reports(f,is_ar,'2026-02-02',0,0,0,'voided unallocated refund');
+ RAISE EXCEPTION USING ERRCODE='P9001',MESSAGE='fixture cleanup';
+ EXCEPTION WHEN SQLSTATE 'P9001' THEN NULL; END;
+
+ BEGIN
+ f:=pg_temp.seed_report_company();
+ m:=pg_temp.seed_memo(f,is_ar,55.01,1.1,'2026-02-01');
+ PERFORM pg_temp.book_control(f,is_ar,-50.00909,'2026-02-01',NULL,CASE WHEN is_ar THEN 'Credit Memo' ELSE 'Debit Memo' END,m);
+ p:=pg_temp.seed_crossparty_payment(f,NOT is_ar,55.01,1.25,'2026-02-02','Draft');
+ INSERT INTO "invoiceSettlement" ("paymentId","targetMemoId","sourceAmount","appliedAmount","sourceExchangeRate","targetExchangeRate","fxGainLossAmount","appliedDate","companyId","createdBy")
+ VALUES (p,m,27.50,25,1.25,1.1,CASE WHEN is_ar THEN 3 ELSE -3 END,'2026-02-02',f.company_id,'system') RETURNING id INTO application;
+ PERFORM pg_temp.assert_reports(f,is_ar,'2026-02-02',-50.00909,0,-50.00909,'draft memo refund excluded');
+ UPDATE payment SET status='Posted' WHERE id=p AND "companyId"=f.company_id;
+ PERFORM pg_temp.book_control(f,is_ar,25,'2026-02-02',NULL,'Payment',p);
+ -- Only 27.50/1.25=22 of cash is applied; the remaining 22.008 is an unallocated refund.
+ PERFORM pg_temp.book_control(f,is_ar,22.008,'2026-02-02',NULL,'Payment',p,' (on-account credit)');
+ PERFORM pg_temp.assert_reports(f,is_ar,'2026-02-02',-25.00909,22.008,-3.00109,'partial FX memo refund');
+ IF is_ar THEN SELECT "openInCurrency" INTO actual FROM get_ar_open_by_customer(f.company_id,'2026-02-02') WHERE "documentId"=m;
+ ELSE SELECT "openInCurrency" INTO actual FROM get_ap_open_by_supplier(f.company_id,'2026-02-02') WHERE "documentId"=m; END IF;
+ ASSERT actual=-27.51,'Partial refund must preserve exact memo principal';
+ UPDATE "invoiceSettlement" SET "sourceAmount"=55.01,"appliedAmount"=50.00909,
+ "fxGainLossAmount"=CASE WHEN is_ar THEN 6.00109 ELSE -6.00109 END WHERE id=application AND "companyId"=f.company_id;
+ PERFORM pg_temp.book_control(f,is_ar,3.00109,'2026-02-03',NULL,'Payment',p);
+ PERFORM pg_temp.assert_reports(f,is_ar,'2026-02-03',0,0,0,'full FX memo refund');
+ IF is_ar THEN SELECT count(*) INTO actual FROM get_ar_open_by_customer(f.company_id,'2026-02-03') WHERE "documentId"=m;
+ ELSE SELECT count(*) INTO actual FROM get_ap_open_by_supplier(f.company_id,'2026-02-03') WHERE "documentId"=m; END IF;
+ ASSERT actual=0,'Fully refunded memo must have no reconstructed fractional principal';
+ UPDATE "invoiceSettlement" SET "sourceAmount"=NULL,"appliedAmount"=25 WHERE id=application AND "companyId"=f.company_id;
+ IF is_ar THEN SELECT count(*) INTO actual FROM get_ar_open_by_customer(f.company_id,'2026-02-03') WHERE "documentId"=m;
+ ELSE SELECT count(*) INTO actual FROM get_ap_open_by_supplier(f.company_id,'2026-02-03') WHERE "documentId"=m; END IF;
+ ASSERT actual=0,'Unknown target memo principal must fail closed';
+ RAISE EXCEPTION USING ERRCODE='P9001',MESSAGE='fixture cleanup';
+ EXCEPTION WHEN SQLSTATE 'P9001' THEN NULL; END;
+ END LOOP;
+END;
+$refund_cases$;
+
+DO $cases$
+DECLARE f pg_temp.report_fixture; other_fixture pg_temp.report_fixture; is_ar boolean; doc text; p1 text; p2 text; m text; s text; row_value record; open_sum numeric; n integer; excluded_status text; new_account text;
+BEGIN
+ FOREACH is_ar IN ARRAY ARRAY[true,false] LOOP
+ BEGIN
+ f:=pg_temp.seed_report_company();
+ doc:=pg_temp.seed_invoice(f,is_ar,100,1.25);
+ m:=pg_temp.seed_memo(f,is_ar,55,1.25,'2026-01-02');
+ INSERT INTO "invoiceSettlement" ("memoId","targetSalesInvoiceId","targetPurchaseInvoiceId","sourceAmount","appliedAmount","sourceExchangeRate","targetExchangeRate","appliedDate","companyId","createdBy")
+ VALUES(m,CASE WHEN is_ar THEN doc END,CASE WHEN NOT is_ar THEN doc END,NULL,20,1.25,1.25,'2026-01-03',f.company_id,'system');
+ IF is_ar THEN SELECT count(*) INTO n FROM get_ar_open_by_customer(f.company_id,'2026-01-03') WHERE "documentId"=m;
+ ELSE SELECT count(*) INTO n FROM get_ap_open_by_supplier(f.company_id,'2026-01-03') WHERE "documentId"=m; END IF;
+ ASSERT n=0,'Memo with unknown consumed principal must not present a fabricated open balance';
+ -- Before that application takes effect the original memo remains valid.
+ IF is_ar THEN SELECT count(*) INTO n FROM get_ar_open_by_customer(f.company_id,'2026-01-02') WHERE "documentId"=m;
+ ELSE SELECT count(*) INTO n FROM get_ap_open_by_supplier(f.company_id,'2026-01-02') WHERE "documentId"=m; END IF;
+ ASSERT n=1,'Future invalid application must not hide the historical memo';
+ RAISE EXCEPTION USING ERRCODE='P9001',MESSAGE='fixture cleanup';
+ EXCEPTION WHEN SQLSTATE 'P9001' THEN NULL; END;
+
+ BEGIN
+ f:=pg_temp.seed_report_company();
+ doc:=pg_temp.seed_invoice(f,is_ar,90,1);
+ PERFORM pg_temp.book_control(f,is_ar,100,'2026-01-01',doc);
+ PERFORM pg_temp.book_control(f,is_ar,-10,'2026-01-01',doc);
+ PERFORM pg_temp.assert_reports(f,is_ar,'2026-01-01',90,0,90,'signed original controls retain net carrying');
+ p1:=pg_temp.seed_payment(f,is_ar,90,1,'2026-01-02');
+ PERFORM pg_temp.apply_cash(f,is_ar,p1,doc,90,90,1,1,'2026-01-02');
+ PERFORM pg_temp.book_control(f,is_ar,-90,'2026-01-02',NULL,'Payment',p1);
+ PERFORM pg_temp.assert_reports(f,is_ar,'2026-01-02',0,0,0,'mixed-sign invoice fully clears without FX');
+ RAISE EXCEPTION USING ERRCODE='P9001',MESSAGE='fixture cleanup';
+ EXCEPTION WHEN SQLSTATE 'P9001' THEN NULL; END;
+
+ -- Each subtransaction unwinds fixture state. SQLSTATE P9001 is our explicit
+ -- successful cleanup; ASSERT uses P0004 and is never caught as success.
+ BEGIN
+ f:=pg_temp.seed_report_company();
+ doc:=pg_temp.seed_invoice(f,is_ar,100,.8);
+ -- Multiple original rows must discover the old account only once.
+ PERFORM pg_temp.book_control(f,is_ar,60,'2026-01-01',doc);
+ PERFORM pg_temp.book_control(f,is_ar,40,'2026-01-01',doc);
+ PERFORM pg_temp.assert_reports(f,is_ar,'2026-01-01',100,0,100,'current and historical account overlap counts once');
+ new_account:=pg_temp.replace_control_default(f,is_ar);
+ PERFORM pg_temp.assert_reports(f,is_ar,'2026-01-01',100,0,100,'changed default retains original invoice control');
+ p1:=pg_temp.seed_payment(f,is_ar,80,.8,'2026-01-02');
+ PERFORM pg_temp.apply_cash(f,is_ar,p1,doc,80,100,.8,.8,'2026-01-02');
+ PERFORM pg_temp.book_control(f,is_ar,-100,'2026-01-02',NULL,'Payment',p1);
+ PERFORM pg_temp.assert_reports(f,is_ar,'2026-01-02',0,0,0,'historical control relief clears after default change');
+ -- Misleading descriptions in an unrelated journal cannot discover an
+ -- account; neither may a supported posting belonging to another company.
+ other_fixture:=f;
+ IF is_ar THEN other_fixture.ar_account:=f.reason_account;
+ ELSE other_fixture.ap_account:=f.reason_account; END IF;
+ PERFORM pg_temp.book_control(other_fixture,is_ar,7,'2026-01-01',NULL,'Manual');
+ other_fixture:=pg_temp.seed_report_company();
+ p2:=pg_temp.seed_payment(other_fixture,is_ar,80,.8,'2026-01-01');
+ IF is_ar THEN other_fixture.ar_account:=f.reason_account;
+ ELSE other_fixture.ap_account:=f.reason_account; END IF;
+ PERFORM pg_temp.book_control(other_fixture,is_ar,-100,'2026-01-01',NULL,'Payment',p2,' (on-account credit)');
+ PERFORM pg_temp.assert_reports(f,is_ar,'2026-01-02',0,0,0,'historical control discovery excludes unrelated journals and companies');
+ RAISE EXCEPTION USING ERRCODE='P9001',MESSAGE='fixture cleanup';
+ EXCEPTION WHEN SQLSTATE 'P9001' THEN NULL; END;
+
+ BEGIN
+ f:=pg_temp.seed_report_company();
+ p1:=pg_temp.seed_payment(f,is_ar,80,.8,'2026-01-01');
+ PERFORM pg_temp.book_control(f,is_ar,-100,'2026-01-01',NULL,'Payment',p1,' (on-account credit)');
+ new_account:=pg_temp.replace_control_default(f,is_ar);
+ PERFORM pg_temp.assert_reports(f,is_ar,'2026-01-01',0,-100,-100,'changed default retains original unapplied payment control');
+ RAISE EXCEPTION USING ERRCODE='P9001',MESSAGE='fixture cleanup';
+ EXCEPTION WHEN SQLSTATE 'P9001' THEN NULL; END;
+
+ BEGIN
+ f:=pg_temp.seed_report_company();
+ m:=pg_temp.seed_memo(f,is_ar,80,.8,'2026-01-01');
+ PERFORM pg_temp.book_control(f,is_ar,-100,'2026-01-01',NULL,CASE WHEN is_ar THEN 'Credit Memo' ELSE 'Debit Memo' END,m);
+ new_account:=pg_temp.replace_control_default(f,is_ar);
+ PERFORM pg_temp.assert_reports(f,is_ar,'2026-01-01',-100,0,-100,'changed default retains original memo control');
+ RAISE EXCEPTION USING ERRCODE='P9001',MESSAGE='fixture cleanup';
+ EXCEPTION WHEN SQLSTATE 'P9001' THEN NULL; END;
+
+ BEGIN
+ f:=pg_temp.seed_report_company();
+ doc:=pg_temp.seed_invoice(f,is_ar,100,1.25,'2026-01-01','2026-01-01');
+ PERFORM pg_temp.book_control(f,is_ar,100,'2026-01-01',doc);
+ m:=pg_temp.seed_memo(f,is_ar,55,1.25,'2026-01-02');
+ PERFORM pg_temp.book_control(f,is_ar,-44,'2026-01-02',NULL,CASE WHEN is_ar THEN 'Credit Memo' ELSE 'Debit Memo' END,m);
+ INSERT INTO "invoiceSettlement" ("memoId","targetSalesInvoiceId","targetPurchaseInvoiceId","sourceAmount","appliedAmount","sourceExchangeRate","targetExchangeRate","fxGainLossAmount","appliedDate","companyId","createdBy")
+ VALUES(m,CASE WHEN is_ar THEN doc END,CASE WHEN NOT is_ar THEN doc END,55,44,1.25,1.25,0,'2026-02-05',f.company_id,'system');
+ -- Aggregate open balances remain56 on both dates, so inspect both
+ -- documents and different aging buckets to prove the application cutoff.
+ IF is_ar THEN SELECT "openInBase" INTO STRICT row_value FROM get_ar_open_by_customer(f.company_id,'2026-02-01') WHERE "documentId"=doc;
+ ELSE SELECT "openInBase" INTO STRICT row_value FROM get_ap_open_by_supplier(f.company_id,'2026-02-01') WHERE "documentId"=doc; END IF;
+ ASSERT row_value."openInBase"=100,'Future direct memo application reduced the historical invoice';
+ IF is_ar THEN SELECT "openInBase" INTO STRICT row_value FROM get_ar_open_by_customer(f.company_id,'2026-02-01') WHERE "documentId"=m;
+ ELSE SELECT "openInBase" INTO STRICT row_value FROM get_ap_open_by_supplier(f.company_id,'2026-02-01') WHERE "documentId"=m; END IF;
+ ASSERT row_value."openInBase"=-44,'Future direct memo application consumed the historical memo';
+ IF is_ar THEN SELECT * INTO STRICT row_value FROM get_ar_aging(f.company_id,'2026-02-01');
+ ELSE SELECT * INTO STRICT row_value FROM get_ap_aging(f.company_id,'2026-02-01'); END IF;
+ ASSERT row_value.bucket1=-44 AND row_value.bucket2=100,'Future direct memo application changed historical aging buckets';
+ PERFORM pg_temp.assert_reports(f,is_ar,'2026-02-01',56,0,56,'direct memo application excluded before appliedDate');
+ IF is_ar THEN SELECT "openInBase" INTO STRICT row_value FROM get_ar_open_by_customer(f.company_id,'2026-02-05') WHERE "documentId"=doc;
+ SELECT count(*) INTO n FROM get_ar_open_by_customer(f.company_id,'2026-02-05') WHERE "documentId"=m;
+ ELSE SELECT "openInBase" INTO STRICT row_value FROM get_ap_open_by_supplier(f.company_id,'2026-02-05') WHERE "documentId"=doc;
+ SELECT count(*) INTO n FROM get_ap_open_by_supplier(f.company_id,'2026-02-05') WHERE "documentId"=m; END IF;
+ ASSERT row_value."openInBase"=56 AND n=0,'Direct memo application must become effective on appliedDate';
+ PERFORM pg_temp.assert_reports(f,is_ar,'2026-02-05',56,0,56,'direct memo application included on appliedDate');
+ RAISE EXCEPTION USING ERRCODE='P9001',MESSAGE='fixture cleanup';
+ EXCEPTION WHEN SQLSTATE 'P9001' THEN NULL; END;
+
+ BEGIN
+ f:=pg_temp.seed_report_company();
+ doc:=pg_temp.seed_invoice(f,is_ar,100,.8);
+ PERFORM pg_temp.book_control(f,is_ar,100,'2026-01-01');
+ PERFORM pg_temp.assert_reports(f,is_ar,'2026-01-01',100,0,100,'unpaid base100/document80');
+ p1:=pg_temp.seed_payment(f,is_ar,40,.8,'2026-01-02');
+ PERFORM pg_temp.apply_cash(f,is_ar,p1,doc,40,50,.8,.8,'2026-01-02');
+ PERFORM pg_temp.book_control(f,is_ar,-50,'2026-01-02');
+ PERFORM pg_temp.assert_invoice(f,is_ar,doc,40,'Partially Paid','partial cash');
+ PERFORM pg_temp.assert_reports(f,is_ar,'2026-01-02',50,0,50,'partial cash');
+ p2:=pg_temp.seed_payment(f,is_ar,40,.8,'2026-01-03');
+ PERFORM pg_temp.apply_cash(f,is_ar,p2,doc,40,50,.8,.8,'2026-01-03');
+ PERFORM pg_temp.book_control(f,is_ar,-50,'2026-01-03');
+ PERFORM pg_temp.assert_invoice(f,is_ar,doc,0,'Paid','full cash');
+ PERFORM pg_temp.assert_reports(f,is_ar,'2026-01-03',0,0,0,'full cash');
+ PERFORM pg_temp.assert_reports(f,is_ar,'2026-01-02',50,0,50,'full today remains partial at cutoff');
+ RAISE EXCEPTION USING ERRCODE='P9001',MESSAGE='fixture cleanup';
+ EXCEPTION WHEN SQLSTATE 'P9001' THEN NULL; END;
+ BEGIN
+ f:=pg_temp.seed_report_company();
+ doc:=pg_temp.seed_invoice(f,is_ar,200,1.25);
+ PERFORM pg_temp.book_control(f,is_ar,200,'2026-01-01');
+ p1:=pg_temp.seed_payment(f,is_ar,110,1.1,'2026-01-02');
+ PERFORM pg_temp.book_control(f,is_ar,-100,'2026-01-02');
+ PERFORM pg_temp.assert_reports(f,is_ar,'2026-01-02',200,-100,100,'prior source fully unapplied');
+ p2:=pg_temp.seed_payment(f,is_ar,55,1.25,'2026-01-03','Draft');
+ PERFORM pg_temp.apply_cash(f,is_ar,p2,doc,55,44,1.25,1.25,'2026-01-03');
+ PERFORM pg_temp.apply_cash(f,is_ar,p2,doc,55,44,1.1,1.25,'2026-01-03',p1);
+ PERFORM pg_temp.assert_reports(f,is_ar,'2026-01-03',200,-100,100,'draft consumer does not reserve prior source');
+ UPDATE payment SET status='Posted' WHERE id=p2 AND "companyId"=f.company_id;
+ -- Current cash releases44 base; prior cash releases50 against target44,
+ -- transferring6 between control balances and realized FX.
+ PERFORM pg_temp.book_control(f,is_ar,-38,'2026-01-03');
+ PERFORM pg_temp.assert_invoice(f,is_ar,doc,140,'Partially Paid','two source snapshots');
+ PERFORM pg_temp.assert_reports(f,is_ar,'2026-01-03',112,-50,62,'current and prior funding each counted once');
+ PERFORM pg_temp.assert_reports(f,is_ar,'2026-01-02',200,-100,100,'cutoff before source consumption');
+ UPDATE payment SET status='Voided' WHERE id=p2 AND "companyId"=f.company_id;
+ PERFORM pg_temp.book_control(f,is_ar,38,'2026-01-03');
+ PERFORM pg_temp.assert_reports(f,is_ar,'2026-01-03',200,-100,100,'voided consumer restores source and target');
+ UPDATE payment SET status='Voided' WHERE id=p1 AND "companyId"=f.company_id;
+ PERFORM pg_temp.book_control(f,is_ar,100,'2026-01-02');
+ PERFORM pg_temp.assert_reports(f,is_ar,'2026-01-03',200,0,200,'voided source contributes no credit');
+ RAISE EXCEPTION USING ERRCODE='P9001',MESSAGE='fixture cleanup';
+ EXCEPTION WHEN SQLSTATE 'P9001' THEN NULL; END;
+
+ BEGIN
+ f:=pg_temp.seed_report_company();
+ doc:=pg_temp.seed_invoice(f,is_ar,100,1.25);
+ PERFORM pg_temp.book_control(f,is_ar,100,'2026-01-01');
+ m:=pg_temp.seed_memo(f,is_ar,55,1.25,'2026-01-02');
+ PERFORM pg_temp.book_control(f,is_ar,-44,'2026-01-02');
+ p1:=pg_temp.seed_payment(f,is_ar,0,1.25,'2026-01-03','Draft');
+ INSERT INTO "invoiceSettlement" ("memoId","appliedViaPaymentId","targetSalesInvoiceId","targetPurchaseInvoiceId","sourceAmount","appliedAmount","sourceExchangeRate","targetExchangeRate","fxGainLossAmount","appliedDate","companyId","createdBy")
+ VALUES(m,p1,CASE WHEN is_ar THEN doc END,CASE WHEN NOT is_ar THEN doc END,55,44,1.25,1.25,0,'2026-01-03',f.company_id,'system');
+ PERFORM pg_temp.assert_reports(f,is_ar,'2026-01-03',56,0,56,'staged memo stays open and invoice stays unpaid');
+ UPDATE payment SET status='Posted' WHERE id=p1 AND "companyId"=f.company_id;
+ PERFORM pg_temp.assert_reports(f,is_ar,'2026-01-03',56,0,56,'effective memo application consumes source once');
+ PERFORM pg_temp.assert_reports(f,is_ar,'2026-01-02',56,0,56,'memo application cutoff');
+ UPDATE payment SET status='Voided' WHERE id=p1 AND "companyId"=f.company_id;
+ PERFORM pg_temp.assert_reports(f,is_ar,'2026-01-03',56,0,56,'voided memo consumer restores source');
+ UPDATE memo SET status='Voided' WHERE id=m AND "companyId"=f.company_id;
+ PERFORM pg_temp.book_control(f,is_ar,44,'2026-01-02');
+ PERFORM pg_temp.assert_reports(f,is_ar,'2026-01-03',100,0,100,'voided memo source disappears');
+ RAISE EXCEPTION USING ERRCODE='P9001',MESSAGE='fixture cleanup';
+ EXCEPTION WHEN SQLSTATE 'P9001' THEN NULL; END;
+
+ BEGIN
+ f:=pg_temp.seed_report_company();
+ doc:=pg_temp.seed_invoice(f,is_ar,100,.8);
+ PERFORM pg_temp.book_control(f,is_ar,100,'2026-01-01');
+ p1:=pg_temp.seed_payment(f,is_ar,60,.8,'2026-01-02');
+ PERFORM pg_temp.apply_cash(f,is_ar,p1,doc,60,75,.8,.8,'2026-01-02',NULL,10,15);
+ PERFORM pg_temp.book_control(f,is_ar,-100,'2026-01-02');
+ PERFORM pg_temp.assert_invoice(f,is_ar,doc,0,'Paid','cash plus noncash relief');
+ PERFORM pg_temp.assert_reports(f,is_ar,'2026-01-02',0,0,0,'discount and writeoff convert to document only once');
+ RAISE EXCEPTION USING ERRCODE='P9001',MESSAGE='fixture cleanup';
+ EXCEPTION WHEN SQLSTATE 'P9001' THEN NULL; END;
+
+ BEGIN
+ f:=pg_temp.seed_report_company();
+ m:=pg_temp.seed_memo(f,is_ar,55,1.1,'2026-01-01',false);
+ PERFORM pg_temp.book_control(f,is_ar,50,'2026-01-01');
+ PERFORM pg_temp.assert_reports(f,is_ar,'2026-01-01',50,0,50,'increasing memo has positive base balance');
+ p1:=pg_temp.seed_payment(f,is_ar,55,1.1,'2026-01-02');
+ INSERT INTO "invoiceSettlement" ("paymentId","targetMemoId","sourceAmount","appliedAmount","sourceExchangeRate","targetExchangeRate","appliedDate","companyId","createdBy")
+ VALUES(p1,m,55,50,1.1,1.1,'2026-01-02',f.company_id,'system');
+ PERFORM pg_temp.book_control(f,is_ar,-50,'2026-01-02');
+ PERFORM pg_temp.assert_reports(f,is_ar,'2026-01-02',0,0,0,'cash-to-memo target relief retains denomination');
+ RAISE EXCEPTION USING ERRCODE='P9001',MESSAGE='fixture cleanup';
+ EXCEPTION WHEN SQLSTATE 'P9001' THEN NULL; END;
+
+ BEGIN
+ f:=pg_temp.seed_report_company();
+ doc:=pg_temp.seed_invoice(f,is_ar,.010000625,16000);
+ PERFORM pg_temp.book_control(f,is_ar,.01,'2026-01-01');
+ p1:=pg_temp.seed_payment(f,is_ar,160,16000,'2026-01-02');
+ PERFORM pg_temp.apply_cash(f,is_ar,p1,doc,160,.01,16000,16000,'2026-01-02');
+ PERFORM pg_temp.book_control(f,is_ar,-.01,'2026-01-02');
+ PERFORM pg_temp.assert_invoice(f,is_ar,doc,.01,'Partially Paid','positive foreign minor unit below ledger scale');
+ IF is_ar THEN SELECT "openInCurrency","openInBase" INTO STRICT row_value FROM get_ar_open_by_customer(f.company_id,'2026-01-02') WHERE "documentId"=doc;
+ ELSE SELECT "openInCurrency","openInBase" INTO STRICT row_value FROM get_ap_open_by_supplier(f.company_id,'2026-01-02') WHERE "documentId"=doc; END IF;
+ ASSERT row_value."openInCurrency"=.01 AND row_value."openInBase"=0,'Large rate must preserve document eligibility without inventing carrying base';
+ PERFORM pg_temp.assert_reports(f,is_ar,'2026-01-02',0,0,0,'large-rate report retains payable minor unit');
+ p2:=pg_temp.seed_payment(f,is_ar,.01,16000,'2026-01-03');
+ PERFORM pg_temp.apply_cash(f,is_ar,p2,doc,.01,0,16000,16000,'2026-01-03');
+ PERFORM pg_temp.assert_invoice(f,is_ar,doc,0,'Paid','source-only terminal settlement');
+ PERFORM pg_temp.assert_reports(f,is_ar,'2026-01-03',0,0,0,'large-rate final source principal closes document');
+ RAISE EXCEPTION USING ERRCODE='P9001',MESSAGE='fixture cleanup';
+ EXCEPTION WHEN SQLSTATE 'P9001' THEN NULL; END;
+
+ BEGIN
+ f:=pg_temp.seed_report_company();
+ doc:=pg_temp.seed_invoice(f,is_ar,100,.8,'2026-01-01','2026-01-31','Paid');
+ IF is_ar THEN UPDATE "salesInvoice" SET "datePaid"='2026-01-05' WHERE id=doc AND "companyId"=f.company_id;
+ ELSE UPDATE "purchaseInvoice" SET "datePaid"='2026-01-05' WHERE id=doc AND "companyId"=f.company_id; END IF;
+ PERFORM pg_temp.book_control(f,is_ar,100,'2026-01-01');
+ PERFORM pg_temp.book_control(f,is_ar,-100,'2026-01-05');
+ PERFORM pg_temp.assert_invoice(f,is_ar,doc,0,'Paid','legacy Paid guard');
+ PERFORM pg_temp.assert_reports(f,is_ar,'2026-01-04',100,0,100,'legacy Paid still open before datePaid');
+ PERFORM pg_temp.assert_reports(f,is_ar,'2026-01-05',0,0,0,'legacy Paid excluded at datePaid');
+ RAISE EXCEPTION USING ERRCODE='P9001',MESSAGE='fixture cleanup';
+ EXCEPTION WHEN SQLSTATE 'P9001' THEN NULL; END;
+
+ BEGIN
+ f:=pg_temp.seed_report_company();
+ doc:=pg_temp.seed_invoice(f,is_ar,100.004,.8);
+ PERFORM pg_temp.book_control(f,is_ar,100.004,'2026-01-01');
+ PERFORM pg_temp.assert_reports(f,is_ar,'2026-01-01',100.004,0,100.004,'fractional original base survives document rounding');
+ p1:=pg_temp.seed_payment(f,is_ar,79.99,.8,'2026-01-02');
+ PERFORM pg_temp.apply_cash(f,is_ar,p1,doc,79.99,99.9875,.8,.8,'2026-01-02');
+ PERFORM pg_temp.book_control(f,is_ar,-99.9875,'2026-01-02');
+ PERFORM pg_temp.assert_reports(f,is_ar,'2026-01-02',.0165,0,.0165,'partial balance retains carrying residual');
+ p2:=pg_temp.seed_payment(f,is_ar,.01,.8,'2026-01-03');
+ PERFORM pg_temp.apply_cash(f,is_ar,p2,doc,.01,.0165,.8,.8,'2026-01-03');
+ PERFORM pg_temp.book_control(f,is_ar,-.0165,'2026-01-03');
+ PERFORM pg_temp.assert_invoice(f,is_ar,doc,0,'Paid','final carrying release');
+ PERFORM pg_temp.assert_reports(f,is_ar,'2026-01-03',0,0,0,'final source FX releases exact carrying');
+ RAISE EXCEPTION USING ERRCODE='P9001',MESSAGE='fixture cleanup';
+ EXCEPTION WHEN SQLSTATE 'P9001' THEN NULL; END;
+
+ BEGIN
+ f:=pg_temp.seed_report_company();
+ doc:=pg_temp.seed_invoice(f,is_ar,100.002,.8);
+ -- Recorded controls, including multiple postings, outrank view-derived
+ -- carrying because their individual component rounding is already booked.
+ PERFORM pg_temp.book_control(f,is_ar,60.002,'2026-01-01',doc);
+ PERFORM pg_temp.book_control(f,is_ar,40.002,'2026-01-01',doc);
+ PERFORM pg_temp.assert_reports(f,is_ar,'2026-01-01',100.004,0,100.004,'recorded original control rows are authoritative');
+ RAISE EXCEPTION USING ERRCODE='P9001',MESSAGE='fixture cleanup';
+ EXCEPTION WHEN SQLSTATE 'P9001' THEN NULL; END;
+
+ BEGIN
+ f:=pg_temp.seed_report_company();
+ doc:=pg_temp.seed_invoice(f,is_ar,2,3);
+ PERFORM pg_temp.book_control(f,is_ar,2,'2026-01-01');
+ p1:=pg_temp.seed_payment(f,is_ar,3,3,'2026-01-02');
+ PERFORM pg_temp.book_control(f,is_ar,-1,'2026-01-02');
+ p2:=pg_temp.seed_payment(f,is_ar,0,3,'2026-01-03');
+ PERFORM pg_temp.apply_cash(f,is_ar,p2,doc,1,.33333,3,3,'2026-01-03',p1);
+ PERFORM pg_temp.assert_reports(f,is_ar,'2026-01-03',1.66667,-.66667,1,'prior source preserves rounded carrying residual');
+ IF is_ar THEN SELECT unapplied INTO open_sum FROM get_ar_aging(f.company_id,'2026-01-03');
+ ELSE SELECT unapplied INTO open_sum FROM get_ap_aging(f.company_id,'2026-01-03'); END IF;
+ ASSERT open_sum=-.66667,'Prior source carrying must subtract recorded release, not reconvert remaining document principal';
+ p2:=pg_temp.seed_payment(f,is_ar,0,3,'2026-01-04');
+ PERFORM pg_temp.apply_cash(f,is_ar,p2,doc,2,.66667,3,3,'2026-01-04',p1);
+ PERFORM pg_temp.assert_reports(f,is_ar,'2026-01-04',1,0,1,'terminal prior source releases exact remaining carrying');
+ RAISE EXCEPTION USING ERRCODE='P9001',MESSAGE='fixture cleanup';
+ EXCEPTION WHEN SQLSTATE 'P9001' THEN NULL; END;
+
+ BEGIN
+ f:=pg_temp.seed_report_company();
+ doc:=pg_temp.seed_invoice(f,is_ar,2,3);
+ PERFORM pg_temp.book_control(f,is_ar,2,'2026-01-01');
+ m:=pg_temp.seed_memo(f,is_ar,3,3,'2026-01-02');
+ PERFORM pg_temp.book_control(f,is_ar,-1,'2026-01-02');
+ p1:=pg_temp.seed_payment(f,is_ar,0,3,'2026-01-03');
+ INSERT INTO "invoiceSettlement" ("memoId","appliedViaPaymentId","targetSalesInvoiceId","targetPurchaseInvoiceId","sourceAmount","appliedAmount","sourceExchangeRate","targetExchangeRate","fxGainLossAmount","appliedDate","companyId","createdBy")
+ VALUES(m,p1,CASE WHEN is_ar THEN doc END,CASE WHEN NOT is_ar THEN doc END,1,.33333,3,3,0,'2026-01-03',f.company_id,'system');
+ PERFORM pg_temp.assert_reports(f,is_ar,'2026-01-03',1,0,1,'memo source preserves rounded carrying residual');
+ IF is_ar THEN SELECT "openInBase" INTO open_sum FROM get_ar_open_by_customer(f.company_id,'2026-01-03') WHERE "documentId"=m;
+ ELSE SELECT "openInBase" INTO open_sum FROM get_ap_open_by_supplier(f.company_id,'2026-01-03') WHERE "documentId"=m; END IF;
+ ASSERT open_sum=-.66667,'Memo source carrying must subtract recorded release, not reconvert remaining document principal';
+ RAISE EXCEPTION USING ERRCODE='P9001',MESSAGE='fixture cleanup';
+ EXCEPTION WHEN SQLSTATE 'P9001' THEN NULL; END;
+
+ BEGIN
+ f:=pg_temp.seed_report_company();
+ -- Configured zero-decimal documents still retain fractional carrying.
+ UPDATE currency SET "decimalPlaces"=0 WHERE code='EUR' AND "companyGroupId"=f.group_id;
+ doc:=pg_temp.seed_invoice(f,is_ar,100.5,.8);
+ PERFORM pg_temp.book_control(f,is_ar,100.5,'2026-01-01');
+ PERFORM pg_temp.assert_reports(f,is_ar,'2026-01-01',100.5,0,100.5,'zero-decimal document preserves original base');
+ IF is_ar THEN SELECT "openInCurrency" INTO open_sum FROM get_ar_open_by_customer(f.company_id,'2026-01-01');
+ ELSE SELECT "openInCurrency" INTO open_sum FROM get_ap_open_by_supplier(f.company_id,'2026-01-01'); END IF;
+ ASSERT open_sum=80,'Zero-decimal document boundary must use group currency precision';
+ RAISE EXCEPTION USING ERRCODE='P9001',MESSAGE='fixture cleanup';
+ EXCEPTION WHEN SQLSTATE 'P9001' THEN NULL; END;
+
+ BEGIN
+ f:=pg_temp.seed_report_company();
+ UPDATE currency SET "decimalPlaces"=3 WHERE code='EUR' AND "companyGroupId"=f.group_id;
+ doc:=pg_temp.seed_invoice(f,is_ar,100.00375,.8);
+ PERFORM pg_temp.book_control(f,is_ar,100.00375,'2026-01-01');
+ p1:=pg_temp.seed_payment(f,is_ar,80.002,.8,'2026-01-02');
+ PERFORM pg_temp.apply_cash(f,is_ar,p1,doc,80.002,100.0025,.8,.8,'2026-01-02');
+ PERFORM pg_temp.book_control(f,is_ar,-100.0025,'2026-01-02');
+ PERFORM pg_temp.assert_invoice(f,is_ar,doc,.001,'Partially Paid','three-decimal minor unit');
+ PERFORM pg_temp.assert_reports(f,is_ar,'2026-01-02',.00125,0,.00125,'three-decimal currency remains payable');
+ RAISE EXCEPTION USING ERRCODE='P9001',MESSAGE='fixture cleanup';
+ EXCEPTION WHEN SQLSTATE 'P9001' THEN NULL; END;
+
+ BEGIN
+ f:=pg_temp.seed_report_company();
+ FOR n IN 1..5 LOOP
+ doc:=pg_temp.seed_invoice(f,is_ar,n*100,.8,'2026-01-02',(ARRAY['2026-05-01','2026-04-30','2026-03-20','2026-02-25','2026-01-01']::date[])[n]);
+ PERFORM pg_temp.book_control(f,is_ar,n*100,'2026-01-02');
+ END LOOP;
+ p1:=pg_temp.seed_payment(f,is_ar,40,.8,'2026-01-03');
+ PERFORM pg_temp.book_control(f,is_ar,-50,'2026-01-03');
+ PERFORM pg_temp.assert_reports(f,is_ar,'2026-05-01',1500,-50,1450,'all aging buckets include unapplied source once');
+ IF is_ar THEN SELECT * INTO STRICT row_value FROM get_ar_aging(f.company_id,'2026-05-01');
+ ELSE SELECT * INTO STRICT row_value FROM get_ap_aging(f.company_id,'2026-05-01'); END IF;
+ ASSERT row_value.current=100 AND row_value.bucket1=200 AND row_value.bucket2=300 AND row_value.bucket3=400 AND row_value.bucket4=500 AND row_value.unapplied=-50,'Due-date aging bucket boundaries changed';
+ IF is_ar THEN SELECT * INTO STRICT row_value FROM get_ar_aging(f.company_id,'2026-05-01','documentDate',10,20,30);
+ ELSE SELECT * INTO STRICT row_value FROM get_ap_aging(f.company_id,'2026-05-01','documentDate',10,20,30); END IF;
+ ASSERT row_value.bucket4=1500 AND row_value.total=1450,'Document-date/custom bucket arguments changed';
+ RAISE EXCEPTION USING ERRCODE='P9001',MESSAGE='fixture cleanup';
+ EXCEPTION WHEN SQLSTATE 'P9001' THEN NULL; END;
+
+ BEGIN
+ f:=pg_temp.seed_report_company();
+ FOREACH excluded_status IN ARRAY ARRAY['Draft','Pending','Voided'] LOOP
+ doc:=pg_temp.seed_invoice(f,is_ar,100,.8,'2026-01-01','2026-01-31',excluded_status);
+ PERFORM pg_temp.assert_invoice(f,is_ar,doc,80,excluded_status,'operational status guard');
+ END LOOP;
+ doc:=pg_temp.seed_invoice(f,is_ar,100,.8,'2026-01-01','2026-01-31','Paid');
+ PERFORM pg_temp.assert_reports(f,is_ar,'2026-01-01',0,0,0,'draft pending voided and legacy Paid without date excluded');
+ doc:=pg_temp.seed_invoice(f,is_ar,100,.8,'2026-01-10');
+ PERFORM pg_temp.book_control(f,is_ar,100,'2026-01-10');
+ PERFORM pg_temp.assert_reports(f,is_ar,'2026-01-09',0,0,0,'future invoice and journal excluded');
+ RAISE EXCEPTION USING ERRCODE='P9001',MESSAGE='fixture cleanup';
+ EXCEPTION WHEN SQLSTATE 'P9001' THEN NULL; END;
+
+ -- The tie-out exists to prove the subledger and the aging agree, so its
+ -- unapplied-cash predicate must be the aging's. A party-less payment for
+ -- this side (a Receipt from a supplier / a Disbursement to a customer) is
+ -- the other subledger's cash: counting it in the tie-out but not the aging
+ -- left get_ar_tie_out/get_ap_tie_out with a permanent non-zero variance.
+ BEGIN
+ f:=pg_temp.seed_report_company();
+ doc:=pg_temp.seed_invoice(f,is_ar,100,.8);
+ PERFORM pg_temp.book_control(f,is_ar,100,'2026-01-01',doc);
+ -- No control journal: this cash posts to the OTHER side's control account.
+ p1:=pg_temp.seed_crossparty_payment(f,is_ar,80,.8,'2026-01-02');
+ ASSERT (SELECT CASE WHEN is_ar THEN "customerId" ELSE "supplierId" END IS NULL
+ FROM payment WHERE id=p1),'Cross-party fixture must leave this side party-less';
+ PERFORM pg_temp.assert_reports(f,is_ar,'2026-01-02',100,0,100,'party-less payment stays out of both the tie-out and the aging');
+ -- The same cash under this side own party still reaches both.
+ p2:=pg_temp.seed_payment(f,is_ar,80,.8,'2026-01-02');
+ PERFORM pg_temp.book_control(f,is_ar,-100,'2026-01-02',NULL,'Payment',p2,' (on-account credit)');
+ PERFORM pg_temp.assert_reports(f,is_ar,'2026-01-02',100,-100,0,'same-party unapplied payment still reaches the tie-out and the aging');
+ RAISE EXCEPTION USING ERRCODE='P9001',MESSAGE='fixture cleanup';
+ EXCEPTION WHEN SQLSTATE 'P9001' THEN NULL; END;
+
+ -- fxGainLossAmount is no longer GENERATED ALWAYS, so writers supply it and
+ -- readers sum it bare -- SUM("appliedAmount" +/- "fxGainLossAmount"). NULL
+ -- plus anything is NULL, so a single nullable row would erase that whole
+ -- settlement principal from the tie-out and the aging. The column must
+ -- refuse a NULL outright rather than have six read sites COALESCE it.
+ BEGIN
+ f:=pg_temp.seed_report_company();
+ doc:=pg_temp.seed_invoice(f,is_ar,100,1);
+ p1:=pg_temp.seed_payment(f,is_ar,100,1,'2026-01-02');
+ BEGIN
+ INSERT INTO "invoiceSettlement" ("paymentId","targetSalesInvoiceId","targetPurchaseInvoiceId","sourceAmount","appliedAmount","sourceExchangeRate","targetExchangeRate","fxGainLossAmount","appliedDate","companyId","createdBy")
+ VALUES (p1,CASE WHEN is_ar THEN doc END,CASE WHEN NOT is_ar THEN doc END,100,100,1,1,NULL,'2026-01-02',f.company_id,'system');
+ ASSERT false,'invoiceSettlement.fxGainLossAmount accepted an explicit NULL';
+ EXCEPTION WHEN not_null_violation THEN NULL; END;
+ -- Omitting it lands on the 0 default, never on NULL.
+ INSERT INTO "invoiceSettlement" ("paymentId","targetSalesInvoiceId","targetPurchaseInvoiceId","sourceAmount","appliedAmount","sourceExchangeRate","targetExchangeRate","appliedDate","companyId","createdBy")
+ VALUES (p1,CASE WHEN is_ar THEN doc END,CASE WHEN NOT is_ar THEN doc END,100,100,1,1,'2026-01-02',f.company_id,'system')
+ RETURNING "fxGainLossAmount" INTO open_sum;
+ ASSERT open_sum=0,'invoiceSettlement.fxGainLossAmount default is no longer 0';
+ RAISE EXCEPTION USING ERRCODE='P9001',MESSAGE='fixture cleanup';
+ EXCEPTION WHEN SQLSTATE 'P9001' THEN NULL; END;
+
+ END LOOP;
+END;
+$cases$;
+
+DO $contract$
+DECLARE fn record;
+BEGIN
+ ASSERT (SELECT array_agg(reloptions ORDER BY relname) IS NOT NULL FROM pg_class WHERE oid IN ('"salesInvoices"'::regclass,'"purchaseInvoices"'::regclass)), 'Invoker view options missing';
+ ASSERT NOT EXISTS (SELECT 1 FROM pg_class WHERE oid IN ('"salesInvoices"'::regclass,'"purchaseInvoices"'::regclass) AND NOT ('security_invoker=true'=ANY(COALESCE(reloptions,ARRAY[]::text[])))), 'Invoice views must use security invoker';
+ ASSERT (SELECT count(*)=40 FROM information_schema.columns WHERE table_schema='public' AND table_name='salesInvoices'), 'salesInvoices column contract changed';
+ ASSERT (SELECT count(*)=36 FROM information_schema.columns WHERE table_schema='public' AND table_name='purchaseInvoices'), 'purchaseInvoices column contract changed';
+ ASSERT (SELECT attnotnull FROM pg_attribute WHERE attrelid='"invoiceSettlement"'::regclass AND attname='fxGainLossAmount'), 'invoiceSettlement.fxGainLossAmount must stay NOT NULL now that it is written rather than generated';
+ ASSERT (SELECT provolatile='i' AND prorettype='numeric'::regtype AND pronargs=1 AND proargtypes[0]='numeric'::regtype FROM pg_proc WHERE pronamespace='public'::regnamespace AND proname='accounting_round_internal'), 'accounting_round_internal must remain an immutable numeric(numeric) helper';
+ ASSERT accounting_round_internal(1.0000050)=1.00001 AND accounting_round_internal(-1.0000050)=-1.00001 AND accounting_round_internal(NULL) IS NULL, 'accounting_round_internal must behave exactly as round(value,5)';
+ ASSERT NOT EXISTS (SELECT 1 FROM pg_proc WHERE pronamespace='public'::regnamespace AND proname IN ('get_ar_tie_out','get_ap_tie_out','get_ar_open_by_customer','get_ap_open_by_supplier','get_ar_aging','get_ap_aging') AND prosrc ~ 'round\([^()]*,[[:space:]]*5[[:space:]]*\)'), 'Reporting RPCs must round internal scale through accounting_round_internal, never a bare scale literal';
+ FOR fn IN SELECT proname,prosecdef,proargnames FROM pg_proc WHERE pronamespace='public'::regnamespace AND proname IN ('get_ar_tie_out','get_ap_tie_out','get_ar_open_by_customer','get_ap_open_by_supplier','get_ar_aging','get_ap_aging') LOOP
+ ASSERT NOT fn.prosecdef,'RPC must remain security invoker: '||fn.proname;
+ ASSERT fn.proargnames[1:2]=ARRAY['_company_id','_as_of_date'],'RPC arguments changed: '||fn.proname;
+ END LOOP;
+ RAISE NOTICE 'ALL % REPORT CASES PASSED',currval('pg_temp.report_case_count');
+END;
+$contract$;
+ROLLBACK;
diff --git a/packages/database/supabase/tests/accounting-defaults-report-access.test.sql b/packages/database/supabase/tests/accounting-defaults-report-access.test.sql
new file mode 100644
index 0000000000..76f37f774e
--- /dev/null
+++ b/packages/database/supabase/tests/accounting-defaults-report-access.test.sql
@@ -0,0 +1,78 @@
+-- Run from the repository root against an existing local database:
+-- pnpm exec tsx scripts/run-local-accounting-check.ts psql -X -v ON_ERROR_STOP=1 -f packages/database/supabase/tests/accounting-defaults-report-access.test.sql
+-- All fixtures and role changes are confined to the rolled-back transaction.
+\set ON_ERROR_STOP on
+BEGIN;
+SET LOCAL "app.sync_in_progress" = 'true';
+SET LOCAL statement_timeout = '30s';
+
+DO $proof$
+DECLARE
+ group_id text; parent_id text; child_id text; foreign_group text;
+ user_id text := gen_random_uuid()::text;
+ cta_id text; sales_id text; old_shipping text; new_shipping text;
+ defaults_json jsonb; found_mapping text; old_defaults jsonb;
+BEGIN
+ INSERT INTO "companyGroup" (name,"createdBy") VALUES ('Reporting review '||id(),'system') RETURNING id INTO group_id;
+ INSERT INTO "companyGroup" (name,"createdBy") VALUES ('Other reporting review '||id(),'system') RETURNING id INTO foreign_group;
+ INSERT INTO "company" (name,"companyGroupId","baseCurrencyCode",timezone)
+ VALUES ('Reporting parent '||id(),group_id,'USD','America/New_York') RETURNING id INTO parent_id;
+ INSERT INTO "company" (name,"companyGroupId","parentCompanyId","baseCurrencyCode",timezone)
+ VALUES ('Reporting child '||id(),group_id,parent_id,'EUR','Europe/Berlin') RETURNING id INTO child_id;
+ INSERT INTO "user" (id,email) VALUES (user_id, user_id||'@reporting-review.invalid');
+ INSERT INTO "userToCompany" ("userId","companyId",role) VALUES (user_id,child_id,'employee');
+ INSERT INTO "userPermission" (id,permissions) VALUES
+ (user_id,jsonb_build_object('accounting_view',jsonb_build_array(child_id),'accounting_update',jsonb_build_array(child_id)));
+ INSERT INTO "account" (name,class,"accountType","incomeBalance","companyGroupId","createdBy")
+ VALUES ('Reporting CTA','Equity','Equity - No Close','Balance Sheet',group_id,'system') RETURNING id INTO cta_id;
+ INSERT INTO "account" (name,class,"accountType","incomeBalance","companyGroupId","createdBy")
+ VALUES ('Reporting Sales','Revenue','Income','Income Statement',group_id,'system') RETURNING id INTO sales_id;
+ INSERT INTO "account" (name,class,"accountType","incomeBalance","companyGroupId","createdBy")
+ VALUES ('Old Shipping','Revenue','Income','Income Statement',group_id,'system') RETURNING id INTO old_shipping;
+ INSERT INTO "account" (name,class,"accountType","incomeBalance","companyGroupId","createdBy")
+ VALUES ('New Shipping','Revenue','Income','Income Statement',group_id,'system') RETURNING id INTO new_shipping;
+ SELECT jsonb_object_agg(attname,to_jsonb(cta_id)) INTO defaults_json
+ FROM pg_attribute WHERE attrelid='"accountDefault"'::regclass AND attnum>0 AND NOT attisdropped AND attnotnull AND attname<>'companyId';
+ defaults_json := defaults_json || jsonb_build_object('currencyTranslationAccount',cta_id,'salesAccount',sales_id,'salesShippingRevenueAccount',old_shipping);
+ INSERT INTO "accountDefault" SELECT (jsonb_populate_record(NULL::"accountDefault",defaults_json||jsonb_build_object('companyId',parent_id))).*;
+ INSERT INTO "accountDefault" SELECT (jsonb_populate_record(NULL::"accountDefault",defaults_json||jsonb_build_object('companyId',child_id))).*;
+
+ PERFORM set_config('request.jwt.claims',jsonb_build_object('sub',user_id,'role','authenticated')::text,true);
+ SET LOCAL ROLE authenticated;
+ ASSERT EXISTS (SELECT 1 FROM "company" WHERE id=parent_id), 'Child employee can see parent company metadata';
+ ASSERT EXISTS (SELECT 1 FROM "account" WHERE id=cta_id), 'Child employee can see group chart';
+ ASSERT EXISTS (SELECT 1 FROM "accountDefault" WHERE "companyId"=child_id), 'Child defaults are visible';
+ ASSERT NOT EXISTS (SELECT 1 FROM "accountDefault" WHERE "companyId"=parent_id), 'Parent defaults remain RLS-invisible';
+ RAISE NOTICE 'PASS real child-only RLS sees parent metadata/chart but cannot read parent defaults';
+ RESET ROLE;
+
+ -- The server resolver runs these two scoped reads only after requirePermissions
+ -- authorizes accounting_view for the employee and supplies the authenticated group.
+ SET LOCAL ROLE service_role;
+ ASSERT EXISTS (SELECT 1 FROM "company" WHERE id=parent_id AND "companyGroupId"=group_id AND "parentCompanyId" IS NULL), 'Authorized root resolves';
+ SELECT "currencyTranslationAccount" INTO STRICT found_mapping FROM "accountDefault" WHERE "companyId"=parent_id;
+ ASSERT found_mapping=cta_id, 'Only configured root CTA is required';
+ ASSERT NOT EXISTS (SELECT 1 FROM "company" WHERE id=parent_id AND "companyGroupId"=foreign_group AND "parentCompanyId" IS NULL), 'Foreign group scope cannot resolve root';
+ ASSERT NOT EXISTS (SELECT 1 FROM "company" WHERE id=child_id AND "companyGroupId"=group_id AND "parentCompanyId" IS NULL), 'Subsidiary cannot act as root';
+ RAISE NOTICE 'PASS scoped privileged root lookup resolves CTA and rejects foreign-group/non-root IDs';
+ RESET ROLE;
+
+ SELECT to_jsonb(d) INTO old_defaults FROM "accountDefault" d WHERE "companyId"=child_id;
+ SET LOCAL ROLE authenticated;
+ BEGIN
+ UPDATE "accountDefault" SET "salesShippingRevenueAccount"=new_shipping,"receivablesAccount"='missing-account-'||id() WHERE "companyId"=child_id;
+ RAISE EXCEPTION 'Expected foreign-key rejection';
+ EXCEPTION WHEN foreign_key_violation THEN NULL;
+ END;
+ ASSERT (SELECT to_jsonb(d)=old_defaults FROM "accountDefault" d WHERE "companyId"=child_id), 'Rejected combined UPDATE preserves the entire defaults row';
+ UPDATE "accountDefault" SET "salesShippingRevenueAccount"=new_shipping,"receivablesAccount"=cta_id WHERE "companyId"=child_id;
+ ASSERT (SELECT "salesShippingRevenueAccount"=new_shipping AND "receivablesAccount"=cta_id FROM "accountDefault" WHERE "companyId"=child_id), 'Valid combined UPDATE saves both values';
+ RAISE NOTICE 'PASS real RLS-scoped combined defaults UPDATE is atomic on rejection and saves valid changes';
+ RESET ROLE;
+
+ UPDATE "account" SET active=false WHERE id=old_shipping;
+ ASSERT EXISTS (SELECT 1 FROM "accounts" WHERE id=old_shipping AND active=false), 'Inactive historical chart state is valid';
+ RAISE NOTICE 'PASS report chart view retains valid inactive account rows';
+END;
+$proof$;
+ROLLBACK;
diff --git a/packages/database/supabase/tests/accounting-historical-balances.test.sql b/packages/database/supabase/tests/accounting-historical-balances.test.sql
new file mode 100644
index 0000000000..31a3bf51bb
--- /dev/null
+++ b/packages/database/supabase/tests/accounting-historical-balances.test.sql
@@ -0,0 +1,96 @@
+-- Historical posting balances survive account/ancestor deactivation in every
+-- financial-report balance RPC, with and without period-close snapshots.
+-- Run: pnpm exec tsx scripts/run-local-accounting-check.ts psql -X -f packages/database/supabase/tests/accounting-historical-balances.test.sql
+\set ON_ERROR_STOP on
+BEGIN;
+SET LOCAL "app.sync_in_progress" = 'true';
+SET LOCAL statement_timeout = '60s';
+
+CREATE FUNCTION pg_temp.assert_historical_balance(group_id text, company_id text, account_id text, label text)
+RETURNS void LANGUAGE plpgsql AS $fn$
+DECLARE actual numeric; delta numeric;
+BEGIN
+ SELECT "balanceAtDate", "netChange" INTO actual, delta
+ FROM "accountTreeBalancePeriodSeries"(group_id, company_id, '2026-07-01', ARRAY['2026-07-31','2026-08-31']::date[])
+ WHERE "accountId"=account_id AND "periodEnd"='2026-08-31';
+ ASSERT actual=100 AND delta=20, label||': monthly history was dropped: '||COALESCE(actual::text,'missing');
+
+ SELECT "balanceAtDate", "netChange" INTO actual, delta
+ FROM "accountTreeBalancePeriodSeries"(group_id, company_id, '2026-08-01', ARRAY['2026-08-31']::date[])
+ WHERE "accountId"=account_id;
+ ASSERT actual=100 AND delta=20, label||': snapshot-bounded monthly history was dropped: '||COALESCE(actual::text,'missing');
+
+ SELECT "balanceAtDate", "netChange" INTO actual, delta
+ FROM "accountTreeBalancesByCompany"(group_id, company_id, '2026-08-01', '2026-08-31')
+ WHERE "accountId"=account_id;
+ ASSERT actual=100 AND delta=20, label||': company history was dropped: '||COALESCE(actual::text,'missing');
+
+ SELECT "balanceAtDate", "netChange" INTO actual, delta
+ FROM "accountTreeBalances"(group_id, '2026-08-01', '2026-08-31')
+ WHERE "accountId"=account_id;
+ ASSERT actual=100 AND delta=20, label||': group history was dropped: '||COALESCE(actual::text,'missing');
+END;
+$fn$;
+
+DO $cases$
+DECLARE
+ group_id text; company_id text; root_id text; parent_id text; leaf_id text; revenue_id text;
+ journal_id text; period_id text; at_date date; amount numeric; account_id text; has_snapshot boolean;
+BEGIN
+ INSERT INTO "companyGroup" (name,"createdBy") VALUES ('Inactive report regression','system') RETURNING id INTO group_id;
+ INSERT INTO company (name,"companyGroupId","baseCurrencyCode",timezone)
+ VALUES ('Inactive report regression',group_id,'USD','America/New_York') RETURNING id INTO company_id;
+ INSERT INTO account (name,class,"incomeBalance","isGroup","companyGroupId","createdBy")
+ VALUES ('Assets','Asset','Balance Sheet',true,group_id,'system') RETURNING id INTO root_id;
+ INSERT INTO account (name,class,"incomeBalance","isGroup","parentId","companyGroupId","createdBy")
+ VALUES ('Historical cash group','Asset','Balance Sheet',true,root_id,group_id,'system') RETURNING id INTO parent_id;
+ INSERT INTO account (name,class,"incomeBalance","isGroup","parentId","companyGroupId","createdBy")
+ VALUES ('Historical cash','Asset','Balance Sheet',false,parent_id,group_id,'system') RETURNING id INTO leaf_id;
+ INSERT INTO account (name,class,"incomeBalance","isGroup","companyGroupId","createdBy")
+ VALUES ('Sales','Revenue','Income Statement',false,group_id,'system') RETURNING id INTO revenue_id;
+ INSERT INTO "accountingPeriod" ("startDate","endDate",status,"companyId","createdBy","fiscalYear","periodNumber")
+ VALUES ('2026-07-01','2026-07-31','Active',company_id,'system',2026,7) RETURNING id INTO period_id;
+
+ FOREACH at_date IN ARRAY ARRAY['2026-07-15','2026-08-15']::date[] LOOP
+ amount:=CASE WHEN at_date='2026-07-15' THEN 80 ELSE 20 END;
+ INSERT INTO journal ("journalEntryId","companyId","postingDate",status,"sourceType","createdBy")
+ VALUES ('INACTIVE-'||id(),company_id,at_date,'Draft','Manual','system') RETURNING id INTO journal_id;
+ INSERT INTO "journalLine" ("journalId","accountId",amount,"journalLineReference","companyId")
+ VALUES (journal_id,leaf_id,amount,id(),company_id),(journal_id,revenue_id,amount,id(),company_id);
+ ASSERT (SELECT sum(CASE a.class WHEN 'Asset' THEN jl.amount ELSE -jl.amount END)=0
+ FROM "journalLine" jl JOIN account a ON a.id=jl."accountId" WHERE jl."journalId"=journal_id), 'Fixture journal must balance';
+ UPDATE journal SET status='Posted' WHERE id=journal_id AND "companyId"=company_id;
+ END LOOP;
+
+ -- Draft activity must stay excluded while historical accounts remain visible.
+ INSERT INTO journal ("journalEntryId","companyId","postingDate",status,"sourceType","createdBy")
+ VALUES ('INACTIVE-DRAFT-'||id(),company_id,'2026-08-20','Draft','Manual','system') RETURNING id INTO journal_id;
+ INSERT INTO "journalLine" ("journalId","accountId",amount,"journalLineReference","companyId")
+ VALUES (journal_id,leaf_id,900,id(),company_id),(journal_id,revenue_id,900,id(),company_id);
+
+ FOREACH account_id IN ARRAY ARRAY[leaf_id,parent_id,root_id,revenue_id] LOOP
+ PERFORM pg_temp.assert_historical_balance(group_id,company_id,account_id,'active baseline');
+ END LOOP;
+
+ FOREACH has_snapshot IN ARRAY ARRAY[false,true] LOOP
+ IF has_snapshot THEN
+ UPDATE "accountingPeriod" SET "closeStatus"='Closed' WHERE id=period_id AND "companyId"=company_id;
+ PERFORM "snapshotAccountingPeriodBalances"(company_id,period_id,'system');
+ ASSERT (SELECT "endingBalance"=80 FROM "accountingPeriodBalance"
+ WHERE "accountingPeriodId"=period_id AND "accountId"=leaf_id AND "companyId"=company_id), 'Snapshot must retain inactive posting accounts';
+ END IF;
+ UPDATE account SET active=false WHERE id IN (leaf_id,revenue_id) AND "companyGroupId"=group_id;
+ FOREACH account_id IN ARRAY ARRAY[leaf_id,parent_id,root_id,revenue_id] LOOP
+ PERFORM pg_temp.assert_historical_balance(group_id,company_id,account_id,'inactive leaf; snapshot='||has_snapshot);
+ END LOOP;
+ UPDATE account SET active=false WHERE id=parent_id AND "companyGroupId"=group_id;
+ FOREACH account_id IN ARRAY ARRAY[leaf_id,parent_id,root_id,revenue_id] LOOP
+ PERFORM pg_temp.assert_historical_balance(group_id,company_id,account_id,'inactive ancestor; snapshot='||has_snapshot);
+ END LOOP;
+ END LOOP;
+ ASSERT NOT EXISTS(SELECT 1 FROM pg_proc WHERE pronamespace='public'::regnamespace
+ AND proname IN ('accountTreeBalances','accountTreeBalancesByCompany','accountTreeBalancePeriodSeries') AND prosecdef), 'Balance RPCs must remain security invoker';
+ RAISE NOTICE 'ALL HISTORICAL BALANCE CASES PASSED (active/inactive leaf/ancestor, full scan/snapshot, draft exclusion)';
+END;
+$cases$;
+ROLLBACK;
diff --git a/packages/database/supabase/tests/accounting-posting-corrections.test.sql b/packages/database/supabase/tests/accounting-posting-corrections.test.sql
new file mode 100644
index 0000000000..de5cfbcab6
--- /dev/null
+++ b/packages/database/supabase/tests/accounting-posting-corrections.test.sql
@@ -0,0 +1,244 @@
+-- Database denomination, source-principal constraints, and real consolidation rates.
+-- Complements production posting/transaction tests; seeded SQL does not execute HTTP posting.
+-- Run: pnpm exec tsx scripts/run-local-accounting-check.ts psql -X -v ON_ERROR_STOP=1
+-- -f packages/database/supabase/tests/accounting-posting-corrections.test.sql
+\set ON_ERROR_STOP on
+BEGIN;
+SET LOCAL "app.sync_in_progress" = 'true';
+SET LOCAL statement_timeout = '60s';
+
+CREATE TYPE pg_temp.posting_fixture AS (
+ group_id text, company_id text, customer_id text, supplier_id text,
+ supplier_interaction_id text, ar_account text, ap_account text, bank_account text,
+ reason_account text, period_id text
+);
+
+CREATE FUNCTION pg_temp.seed_posting_company() RETURNS pg_temp.posting_fixture
+LANGUAGE plpgsql AS $fn$
+DECLARE f pg_temp.posting_fixture; defaults_json jsonb;
+BEGIN
+ INSERT INTO "companyGroup" (name,"createdBy") VALUES ('Posting harness '||id(),'system') RETURNING id INTO f.group_id;
+ INSERT INTO "company" (name,"companyGroupId","baseCurrencyCode",timezone)
+ VALUES ('Posting harness '||id(),f.group_id,'USD','America/New_York') RETURNING id INTO f.company_id;
+ INSERT INTO "currency" (code,"companyGroupId","decimalPlaces","createdBy")
+ VALUES ('USD',f.group_id,2,'system'),('EUR',f.group_id,2,'system');
+ INSERT INTO "customer" (name,"readableId","companyId") VALUES ('Harness customer','HC-'||id(),f.company_id) RETURNING id INTO f.customer_id;
+ INSERT INTO "supplier" (name,"readableId","companyId") VALUES ('Harness supplier','HS-'||id(),f.company_id) RETURNING id INTO f.supplier_id;
+ INSERT INTO "supplierInteraction" ("companyId","supplierId") VALUES (f.company_id,f.supplier_id) RETURNING id INTO f.supplier_interaction_id;
+ INSERT INTO "account" (name,class,"accountType","incomeBalance","companyGroupId","createdBy")
+ VALUES ('Harness AR','Asset','Accounts Receivable','Balance Sheet',f.group_id,'system') RETURNING id INTO f.ar_account;
+ INSERT INTO "account" (name,class,"accountType","incomeBalance","companyGroupId","createdBy")
+ VALUES ('Harness AP','Liability','Accounts Payable','Balance Sheet',f.group_id,'system') RETURNING id INTO f.ap_account;
+ INSERT INTO "account" (name,class,"accountType","incomeBalance","companyGroupId","createdBy")
+ VALUES ('Harness bank','Asset','Bank','Balance Sheet',f.group_id,'system') RETURNING id INTO f.bank_account;
+ INSERT INTO "account" (name,class,"accountType","incomeBalance","companyGroupId","createdBy")
+ VALUES ('Harness reason','Expense','Expense','Income Statement',f.group_id,'system') RETURNING id INTO f.reason_account;
+ SELECT jsonb_object_agg(attname,to_jsonb(f.reason_account)) INTO defaults_json
+ FROM pg_attribute WHERE attrelid='"accountDefault"'::regclass AND attnum>0 AND NOT attisdropped AND attnotnull AND attname<>'companyId';
+ INSERT INTO "accountDefault" SELECT (jsonb_populate_record(NULL::"accountDefault",defaults_json||jsonb_build_object(
+ 'companyId',f.company_id,'receivablesAccount',f.ar_account,'payablesAccount',f.ap_account,'bankCashAccount',f.bank_account))).*;
+ INSERT INTO "accountingPeriod" ("startDate","endDate",status,"companyId","createdBy","fiscalYear","periodNumber")
+ VALUES ('2026-01-01','2026-12-31','Active',f.company_id,'system',2026,1) RETURNING id INTO f.period_id;
+ RETURN f;
+END;
+$fn$;
+
+CREATE FUNCTION pg_temp.seed_invoice(f pg_temp.posting_fixture,is_ar boolean,amount_base numeric,rate numeric,
+ at_date date DEFAULT '2026-01-01',due_date date DEFAULT '2026-01-31',document_status text DEFAULT NULL)
+RETURNS text LANGUAGE plpgsql AS $fn$
+DECLARE doc text;
+BEGIN
+ IF is_ar THEN
+ INSERT INTO "salesInvoice" ("invoiceId","customerId","currencyCode","exchangeRate","companyId","createdBy","postingDate","dateIssued","dateDue",status)
+ VALUES ('HI-'||id(),f.customer_id,'EUR',rate,f.company_id,'system',at_date,at_date,due_date,COALESCE(document_status,'Submitted')::"salesInvoiceStatus") RETURNING id INTO doc;
+ INSERT INTO "salesInvoiceLine" ("invoiceId","invoiceLineType","unitOfMeasureCode","companyId","createdBy",quantity,"unitPrice","exchangeRate")
+ VALUES (doc,'Service','EA',f.company_id,'system',1,amount_base,rate);
+ ELSE
+ INSERT INTO "purchaseInvoice" ("invoiceId","supplierId","supplierInteractionId","currencyCode","exchangeRate","companyId","createdBy","postingDate","dateIssued","dateDue",status)
+ VALUES ('HI-'||id(),f.supplier_id,f.supplier_interaction_id,'EUR',rate,f.company_id,'system',at_date,at_date,due_date,COALESCE(document_status,'Open')::"purchaseInvoiceStatus") RETURNING id INTO doc;
+ INSERT INTO "purchaseInvoiceLine" ("invoiceId","invoiceLineType","companyId","createdBy",quantity,"supplierUnitPrice","exchangeRate","accountId")
+ VALUES (doc,'G/L Account',f.company_id,'system',1,amount_base*rate,rate,f.reason_account);
+ END IF;
+ RETURN doc;
+END;
+$fn$;
+
+DO $denominations$
+DECLARE f pg_temp.posting_fixture; invoice_id text; row_value record;
+BEGIN
+ f:=pg_temp.seed_posting_company();
+ invoice_id:=pg_temp.seed_invoice(f,true,50,.8);
+ UPDATE "salesInvoiceLine" SET quantity=2,"addOnCost"=20,"nonTaxableAddOnCost"=10,"shippingCost"=5,"setupPrice"=7,"taxPercent"=.1
+ WHERE "invoiceId"=invoice_id AND "companyId"=f.company_id;
+ SELECT * INTO STRICT row_value FROM "salesInvoiceLine" WHERE "invoiceId"=invoice_id AND "companyId"=f.company_id;
+ ASSERT row_value."unitPrice"=50 AND row_value."convertedUnitPrice"=40,'Sales unitPrice is base; convertedUnitPrice is document';
+ ASSERT row_value."convertedAddOnCost"=16 AND row_value."convertedNonTaxableAddOnCost"=8 AND row_value."convertedShippingCost"=4 AND row_value."convertedSetupPrice"=5.6,'Sales generated components multiply base by foreign-per-base rate';
+ SELECT * INTO STRICT row_value FROM "salesInvoices" WHERE id=invoice_id AND "companyId"=f.company_id;
+ ASSERT row_value.subtotal=135 AND row_value."totalTax"=12.5 AND row_value."totalAmount"=147.5,'Sales aggregate remains base and applies taxable/non-taxable split';
+ ASSERT row_value.balance*.8=118,'Sales balance converts base carrying to document display once';
+ RAISE NOTICE 'PASS generated sales base/document components and aggregate denomination';
+
+ invoice_id:=pg_temp.seed_invoice(f,false,50,.8);
+ UPDATE "purchaseInvoiceLine" SET quantity=2,"supplierShippingCost"=4,"supplierTaxAmount"=8,"conversionFactor"=5
+ WHERE "invoiceId"=invoice_id AND "companyId"=f.company_id;
+ SELECT * INTO STRICT row_value FROM "purchaseInvoiceLine" WHERE "invoiceId"=invoice_id AND "companyId"=f.company_id;
+ ASSERT row_value."supplierUnitPrice"=40 AND row_value."unitPrice"=50 AND row_value."extendedPrice"=100,'Purchase supplier fields are document; generated unit/extended are base';
+ ASSERT row_value."shippingCost"=5 AND row_value."taxAmount"=10 AND row_value."totalAmount"=115,'Purchase generated components divide document by foreign-per-base rate exactly once';
+ ASSERT row_value."conversionFactor"=5 AND row_value."unitPrice"/row_value."conversionFactor"=10,'Non-1 purchase UOM keeps inventory base unit cost distinct from purchase-unit cost';
+ SELECT * INTO STRICT row_value FROM "purchaseInvoices" WHERE id=invoice_id AND "companyId"=f.company_id;
+ ASSERT row_value."totalAmount"=115 AND row_value.balance*.8=92,'Purchase aggregate and document balance retain denominations';
+ RAISE NOTICE 'PASS generated purchase denominations with non-1 UOM';
+
+ UPDATE "purchaseInvoiceLine" SET quantity=1,"supplierUnitPrice"=160.01,"supplierShippingCost"=0,"supplierTaxAmount"=0,"exchangeRate"=16000
+ WHERE "invoiceId"=invoice_id AND "companyId"=f.company_id;
+ SELECT * INTO STRICT row_value FROM "purchaseInvoiceLine" WHERE "invoiceId"=invoice_id AND "companyId"=f.company_id;
+ ASSERT row_value."unitPrice"=.010000625 AND row_value."totalAmount"=.010000625,'Purchase generated amounts must retain raw precision beyond the ledger scale';
+ ASSERT row_value."unitPrice"*row_value."exchangeRate"=160.01,'Generated purchase precision must round-trip the last foreign minor unit';
+ RAISE NOTICE 'PASS generated purchase amount preserves 160.01 at rate16000';
+END;
+$denominations$;
+
+DO $pair_rates$
+DECLARE f pg_temp.posting_fixture; other pg_temp.posting_fixture; rates record;
+BEGIN
+ f:=pg_temp.seed_posting_company(); other:=pg_temp.seed_posting_company();
+ UPDATE company SET "baseCurrencyCode"='GBP' WHERE id=f.company_id;
+ UPDATE company SET "baseCurrencyCode"='EUR' WHERE id=other.company_id;
+ INSERT INTO currency(code,"companyGroupId","decimalPlaces","historicalExchangeRate","createdBy")
+ VALUES('GBP',f.group_id,2,1.25,'system'),('GBP',other.group_id,2,9,'system');
+ -- New dates only, inside this rollback. Never overwrite a global market row.
+ INSERT INTO "exchangeRate" ("currencyCode","effectiveDate",rate) VALUES
+ ('GBP','2199-12-30',4),('GBP','2199-12-31',2),('EUR','2199-12-30',4),('EUR','2199-12-31',4);
+ SELECT * INTO STRICT rates FROM "getConsolidationRates"(f.group_id,f.company_id,'EUR','2199-12-31','2199-12-30');
+ ASSERT rates."sourceCurrency"='GBP' AND rates."closingRate"=2 AND rates."averageRate"=1.5 AND rates."historicalRate"=1.25,'Consolidation must use target/source pair ratios and group-owned historical rate';
+ RAISE NOTICE 'PASS real consolidation RPC closing2/average1.5/historical1.25 pair rates';
+ SELECT * INTO STRICT rates FROM "getConsolidationRates"(other.group_id,other.company_id,'GBP','2199-12-31','2199-12-30');
+ ASSERT rates."closingRate"=.5 AND rates."averageRate"=.75,'Reverse consolidation direction must invert each daily pair before averaging';
+ RAISE NOTICE 'PASS real consolidation reciprocal pair direction';
+ SELECT * INTO STRICT rates FROM "getConsolidationRates"(f.group_id,f.company_id,'GBP','2199-12-31','2199-12-30');
+ ASSERT rates."closingRate"=1 AND rates."averageRate"=1 AND rates."historicalRate"=1,'Identity consolidation returns one for all rate kinds';
+ RAISE NOTICE 'PASS real consolidation identity rates';
+END;
+$pair_rates$;
+
+DO $settlement_cases$
+DECLARE
+ f pg_temp.posting_fixture;
+ other pg_temp.posting_fixture;
+ customer_id text;
+ other_customer_id text;
+ owner_id text;
+ source_id text;
+ other_source_id text;
+ target_id text;
+ memo_source_id text;
+ settlement_id text;
+ invalid_amount numeric;
+ constraint_name text;
+BEGIN
+ f := pg_temp.seed_posting_company();
+ other := pg_temp.seed_posting_company();
+ INSERT INTO "customer" (name, "companyId", "createdBy")
+ VALUES ('Settlement customer', f.company_id, 'system') RETURNING id INTO customer_id;
+ INSERT INTO "customer" (name, "companyId", "createdBy")
+ VALUES ('Other company customer', other.company_id, 'system') RETURNING id INTO other_customer_id;
+ INSERT INTO "payment" ("paymentId", "paymentType", "paymentDate", "currencyCode", "totalAmount", "bankAccount", "customerId", "companyId", "createdBy", "exchangeRate", status, "postingDate")
+ VALUES ('APPLY', 'Receipt', DATE '2026-09-07', 'EUR', 0.01, f.bank_account, customer_id, f.company_id, 'system',16000,'Posted','2026-09-07') RETURNING id INTO owner_id;
+ INSERT INTO "payment" ("paymentId", "paymentType", "paymentDate", "currencyCode", "totalAmount", "bankAccount", "customerId", "companyId", "createdBy", "exchangeRate", status, "postingDate")
+ VALUES ('SOURCE', 'Receipt', DATE '2026-09-06', 'EUR', 0.01, f.bank_account, customer_id, f.company_id, 'system',16000,'Posted','2026-09-07') RETURNING id INTO source_id;
+ INSERT INTO "payment" ("paymentId", "paymentType", "paymentDate", "currencyCode", "totalAmount", "bankAccount", "customerId", "companyId", "createdBy", "exchangeRate", status, "postingDate")
+ VALUES ('OTHER-SOURCE', 'Receipt', DATE '2026-09-06', 'EUR', 0.01, other.bank_account, other_customer_id, other.company_id, 'system',16000,'Posted','2026-09-06') RETURNING id INTO other_source_id;
+ INSERT INTO "memo" ("memoId", direction, "memoDate", "currencyCode", amount, "customerId", "companyId", "createdBy", "exchangeRate", status, "postingDate", "reasonAccount")
+ VALUES ('TARGET', 'Debit', DATE '2026-09-07', 'EUR', 0.01, customer_id, f.company_id, 'system',16000,'Posted','2026-09-07',f.reason_account) RETURNING id INTO target_id;
+ INSERT INTO "memo" ("memoId", direction, "memoDate", "currencyCode", amount, "customerId", "companyId", "createdBy", "exchangeRate", status, "postingDate", "reasonAccount")
+ VALUES ('MEMO-SOURCE', 'Credit', DATE '2026-09-07', 'EUR', 0.01, customer_id, f.company_id, 'system',16000,'Posted','2026-09-07',f.reason_account) RETURNING id INTO memo_source_id;
+
+ -- This is the terminal 0.01 document-currency application at rate 16000:
+ -- internal base principal rounds to zero, but source principal must survive.
+ INSERT INTO "invoiceSettlement" ("paymentId", "sourcePaymentId", "targetMemoId", "appliedAmount", "sourceAmount",
+ "sourceExchangeRate", "targetExchangeRate", "appliedDate", "companyId", "createdBy", "fxGainLossAmount")
+ VALUES (owner_id, source_id, target_id, 0, 0.01, 16000, 16000, DATE '2026-09-07', f.company_id, 'system', 0)
+ RETURNING id INTO settlement_id;
+ ASSERT (SELECT "appliedAmount" = 0 AND "sourceAmount" = 0.01 FROM "invoiceSettlement" WHERE id = settlement_id),
+ 'Source-only minor-unit allocation must survive base rounding';
+ UPDATE "invoiceSettlement" SET "fxGainLossAmount" = -0.00001 WHERE id = settlement_id;
+ ASSERT (SELECT "fxGainLossAmount" = -0.00001 FROM "invoiceSettlement" WHERE id = settlement_id),
+ 'Signed FX snapshot must be writable';
+ RAISE NOTICE 'PASS source-only minor-unit allocation and writable FX snapshot';
+
+ BEGIN
+ UPDATE "invoiceSettlement" SET "sourcePaymentId" = other_source_id WHERE id = settlement_id;
+ ASSERT false, 'Cross-company source payment must be refused';
+ EXCEPTION WHEN foreign_key_violation THEN
+ GET STACKED DIAGNOSTICS constraint_name = CONSTRAINT_NAME;
+ ASSERT constraint_name = 'invoiceSettlement_sourcePaymentId_companyId_fkey', 'Expected same-company funding FK';
+ END;
+ BEGIN
+ UPDATE "invoiceSettlement" SET "sourcePaymentId" = owner_id WHERE id = settlement_id;
+ ASSERT false, 'A payment must not fund itself as prior credit';
+ EXCEPTION WHEN check_violation THEN
+ GET STACKED DIAGNOSTICS constraint_name = CONSTRAINT_NAME;
+ ASSERT constraint_name = 'invoiceSettlement_sourcePaymentId_check', 'Expected self-funding constraint';
+ END;
+ BEGIN
+ UPDATE "invoiceSettlement" SET "paymentId" = NULL, "memoId" = memo_source_id WHERE id = settlement_id;
+ ASSERT false, 'Memo-owned allocation must not name a source payment';
+ EXCEPTION WHEN check_violation THEN
+ GET STACKED DIAGNOSTICS constraint_name = CONSTRAINT_NAME;
+ ASSERT constraint_name = 'invoiceSettlement_sourcePaymentId_check', 'Expected payment-only funding constraint';
+ END;
+ BEGIN
+ DELETE FROM "payment" WHERE id = source_id AND "companyId" = f.company_id;
+ ASSERT false, 'Referenced funding payment must be retained';
+ EXCEPTION WHEN foreign_key_violation THEN
+ GET STACKED DIAGNOSTICS constraint_name = CONSTRAINT_NAME;
+ ASSERT constraint_name = 'invoiceSettlement_sourcePaymentId_companyId_fkey', 'Expected funding-source delete protection';
+ END;
+ RAISE NOTICE 'PASS same-company FK, self-funding, payment owner, and source deletion guards';
+
+ FOREACH invalid_amount IN ARRAY ARRAY[-0.01::numeric, 'NaN'::numeric, 'Infinity'::numeric, '-Infinity'::numeric] LOOP
+ BEGIN
+ -- Positive appliedAmount isolates sourceAmount validation from the
+ -- zero-components check, proving exactly the constraint under test.
+ UPDATE "invoiceSettlement" SET "appliedAmount" = 1, "sourceAmount" = invalid_amount WHERE id = settlement_id;
+ ASSERT false, 'Invalid source amount accepted: ' || invalid_amount;
+ EXCEPTION WHEN check_violation THEN
+ GET STACKED DIAGNOSTICS constraint_name = CONSTRAINT_NAME;
+ ASSERT constraint_name = 'invoiceSettlement_sourceAmount_check', 'Expected source-amount constraint for ' || invalid_amount;
+ END;
+ END LOOP;
+ BEGIN
+ UPDATE "invoiceSettlement" SET "sourceAmount" = 0 WHERE id = settlement_id;
+ ASSERT false, 'An entirely empty allocation must still be refused';
+ EXCEPTION WHEN check_violation THEN
+ GET STACKED DIAGNOSTICS constraint_name = CONSTRAINT_NAME;
+ ASSERT constraint_name = 'invoiceSettlement_anyComponent_check', 'Expected empty-allocation constraint';
+ END;
+ -- A source-linked row without its document principal is UNREADABLE, not just
+ -- imprecise: remainingFundingSources throws "Settlement is missing its
+ -- document principal" and the party's remaining credit cannot be computed.
+ BEGIN
+ UPDATE "invoiceSettlement"
+ SET "sourcePaymentId" = source_id, "appliedAmount" = 1, "sourceAmount" = NULL
+ WHERE id = settlement_id;
+ ASSERT false, 'A source-linked settlement was accepted without its document principal';
+ EXCEPTION WHEN check_violation THEN
+ GET STACKED DIAGNOSTICS constraint_name = CONSTRAINT_NAME;
+ ASSERT constraint_name = 'invoiceSettlement_sourcePaymentId_check',
+ 'Expected the source-principal constraint';
+ END;
+ UPDATE "invoiceSettlement" SET "sourcePaymentId" = NULL WHERE id = settlement_id;
+ -- Legacy rows stay valid: no source link, so a NULL principal is permitted.
+ UPDATE "invoiceSettlement" SET "sourceAmount" = NULL, "appliedAmount" = 1 WHERE id = settlement_id;
+ ASSERT (SELECT "sourceAmount" IS NULL FROM "invoiceSettlement" WHERE id = settlement_id),
+ 'A legacy settlement with no funding source may keep a NULL principal';
+ UPDATE "invoiceSettlement" SET "sourceAmount" = 0.01 WHERE id = settlement_id;
+ ASSERT (SELECT "sourcePaymentId" IS NULL AND "sourceAmount" = 0.01 FROM "invoiceSettlement" WHERE id = settlement_id),
+ 'Current cash may supply a source-only minor-unit allocation';
+ RAISE NOTICE 'PASS finite/nonnegative source amounts, empty allocation refusal, and current-cash source';
+ RAISE NOTICE 'PASS source-linked rows require a document principal; legacy rows may not';
+ RAISE NOTICE 'ALL SCENARIOS PASSED';
+END;
+$settlement_cases$;
+
+ROLLBACK;
diff --git a/packages/database/supabase/tests/accounting-shipping-backfill.test.sql b/packages/database/supabase/tests/accounting-shipping-backfill.test.sql
new file mode 100644
index 0000000000..ba45efc13d
--- /dev/null
+++ b/packages/database/supabase/tests/accounting-shipping-backfill.test.sql
@@ -0,0 +1,315 @@
+-- Shipping-account migration and backfill behavior.
+-- Run from the repository root against the existing local development database:
+-- pnpm exec tsx scripts/run-local-accounting-check.ts psql -X \
+-- -v ON_ERROR_STOP=1 \
+-- -f packages/database/supabase/tests/accounting-shipping-backfill.test.sql
+--
+-- Before migration this fails at the first missing-schema assertion. After
+-- migration it exercises the ACTUAL migration backfill, loaded from its unique
+-- CLI-generated file; no copied implementation or embedded COMMIT is executed.
+-- All fixtures use new IDs and the outer transaction always rolls back. A failed
+-- assertion terminates psql, which also rolls back the open transaction.
+
+\set ON_ERROR_STOP on
+BEGIN;
+SET LOCAL "app.sync_in_progress" = 'true';
+SET LOCAL statement_timeout = '30s';
+
+DO $contract$
+BEGIN
+ ASSERT EXISTS (
+ SELECT 1 FROM information_schema.columns WHERE table_schema = 'public'
+ AND table_name = 'accountDefault' AND column_name = 'salesShippingRevenueAccount'
+ ), 'Schema contract: accountDefault.salesShippingRevenueAccount is missing';
+ ASSERT (
+ SELECT count(*) = 2 FROM information_schema.columns WHERE table_schema = 'public'
+ AND table_name = 'invoiceSettlement' AND column_name IN ('sourcePaymentId', 'sourceAmount')
+ ), 'Schema contract: invoiceSettlement funding columns are missing';
+ ASSERT (
+ SELECT is_generated = 'NEVER' FROM information_schema.columns
+ WHERE table_schema = 'public' AND table_name = 'invoiceSettlement'
+ AND column_name = 'fxGainLossAmount'
+ ), 'Schema contract: fxGainLossAmount must be a server-written snapshot';
+END;
+$contract$;
+
+CREATE TEMP TABLE accounting_backfill_sql (body text NOT NULL) ON COMMIT DROP;
+-- Python runs locally through psql, reads only a repository file, and emits one
+-- CSV field so newlines/quotes survive unchanged. The boundaries deliberately
+-- exclude all schema DDL and the migration's outer BEGIN/COMMIT.
+\copy accounting_backfill_sql FROM PROGRAM 'python3 -c "from pathlib import Path; import csv,sys; paths=list(Path(\"packages/database/supabase/migrations\").glob(\"*_accounting_posting_corrections.sql\")); assert len(paths)==1, \"Expected exactly one accounting posting migration\"; sql=paths[0].read_text(); start=sql.index(\"-- Serialize chart/default resolution\"); end=sql.index(\"COMMENT ON COLUMN\",start); csv.writer(sys.stdout).writerow([sql[start:end]])"' WITH (FORMAT csv)
+
+CREATE FUNCTION pg_temp.run_shipping_backfill() RETURNS void LANGUAGE plpgsql AS $fn$
+DECLARE body text;
+BEGIN
+ SELECT s.body INTO STRICT body FROM accounting_backfill_sql s;
+ -- A real migration commit drops this temporary resolution table. Removing
+ -- only that scratch table models a fresh retry inside our rollback harness.
+ DROP TABLE IF EXISTS pg_temp.accounting_shipping_resolution;
+ EXECUTE body;
+END;
+$fn$;
+
+CREATE TYPE pg_temp.shipping_fixture AS (
+ group_id text, company_ids text[], parent_id text, sales_id text
+);
+
+CREATE FUNCTION pg_temp.seed_shipping_chart(p_companies integer DEFAULT 1)
+RETURNS pg_temp.shipping_fixture LANGUAGE plpgsql AS $fn$
+DECLARE
+ f pg_temp.shipping_fixture;
+ defaults_json jsonb;
+BEGIN
+ ASSERT p_companies > 0, 'Fixture needs a company';
+ INSERT INTO "companyGroup" (name, "createdBy")
+ VALUES ('Shipping harness ' || id(), 'system') RETURNING id INTO f.group_id;
+ WITH inserted AS (
+ INSERT INTO "company" (id, name, "companyGroupId", "baseCurrencyCode")
+ SELECT id(), 'Shipping harness company ' || id(), f.group_id, 'USD'
+ FROM generate_series(1, p_companies)
+ RETURNING id
+ ) SELECT array_agg(id ORDER BY id) INTO f.company_ids FROM inserted;
+
+ INSERT INTO "account" (name, class, "accountType", "incomeBalance", "consolidatedRate",
+ "isGroup", "companyGroupId", "createdBy")
+ VALUES ('Revenue', 'Revenue', 'Income', 'Income Statement', 'Average', true,
+ f.group_id, 'system') RETURNING id INTO f.parent_id;
+ INSERT INTO "account" (number, name, class, "accountType", "incomeBalance", "consolidatedRate",
+ "parentId", "companyGroupId", "createdBy")
+ VALUES ('4010', 'Sales', 'Revenue', 'Income', 'Income Statement', 'Average',
+ f.parent_id, f.group_id, 'system') RETURNING id INTO f.sales_id;
+
+ -- Unrelated mandatory defaults only need a valid fixture-owned FK; none is
+ -- posted by these schema/backfill tests. Derive the mandatory columns from the
+ -- current schema so adding an unrelated default does not require fake seed data.
+ SELECT jsonb_object_agg(attname, to_jsonb(f.sales_id)) INTO defaults_json
+ FROM pg_attribute WHERE attrelid = '"accountDefault"'::regclass
+ AND attnum > 0 AND NOT attisdropped AND attnotnull AND attname <> 'companyId';
+ INSERT INTO "accountDefault"
+ SELECT (jsonb_populate_record(NULL::"accountDefault",
+ defaults_json || jsonb_build_object('companyId', company_id))).*
+ FROM unnest(f.company_ids) AS company_id;
+ RETURN f;
+END;
+$fn$;
+
+CREATE FUNCTION pg_temp.add_revenue_leaf(f pg_temp.shipping_fixture, p_name text, p_number text)
+RETURNS text LANGUAGE plpgsql AS $fn$
+DECLARE account_id text;
+BEGIN
+ INSERT INTO "account" (number, name, class, "accountType", "incomeBalance", "consolidatedRate",
+ "parentId", "companyGroupId", "createdBy")
+ VALUES (p_number, p_name, 'Revenue', 'Income', 'Income Statement', 'Average',
+ f.parent_id, f.group_id, 'system') RETURNING id INTO account_id;
+ RETURN account_id;
+END;
+$fn$;
+
+CREATE FUNCTION pg_temp.expect_backfill_failure(p_message text) RETURNS void LANGUAGE plpgsql AS $fn$
+DECLARE actual_message text;
+BEGIN
+ BEGIN
+ PERFORM pg_temp.run_shipping_backfill();
+ ASSERT false, 'Expected migration refusal: ' || p_message;
+ EXCEPTION WHEN raise_exception THEN
+ GET STACKED DIAGNOSTICS actual_message = MESSAGE_TEXT;
+ ASSERT position(p_message IN actual_message) > 0,
+ 'Wrong migration refusal: ' || actual_message;
+ END;
+END;
+$fn$;
+
+-- Preserve complete existing records, not just counts. Even while all writes
+-- roll back, the harness refuses to use or modify real company/account defaults.
+CREATE TEMP TABLE accounting_original_accounts ON COMMIT DROP AS
+SELECT id, to_jsonb(a) AS body FROM "account" a;
+CREATE TEMP TABLE accounting_original_defaults ON COMMIT DROP AS
+SELECT "companyId", to_jsonb(ad) AS body FROM "accountDefault" ad;
+
+DO $backfill_cases$
+DECLARE
+ f pg_temp.shipping_fixture;
+ good pg_temp.shipping_fixture;
+ shipping_id text;
+ custom_id text;
+ second_parent text;
+ before_accounts jsonb;
+ before_defaults jsonb;
+BEGIN
+ -- A custom SQLSTATE unwinds each successful scenario's fixtures. Assertion
+ -- errors use P0004 and are never caught as successful test execution.
+ BEGIN
+ f := pg_temp.seed_shipping_chart(2);
+ PERFORM pg_temp.run_shipping_backfill();
+ SELECT "salesShippingRevenueAccount" INTO shipping_id FROM "accountDefault"
+ WHERE "companyId" = f.company_ids[1];
+ ASSERT shipping_id IS NOT NULL AND shipping_id <> f.sales_id, 'Fresh chart: separate shipping account';
+ ASSERT (SELECT number = '4050' AND name = 'Shipping Revenue' AND class = 'Revenue'
+ AND "accountType" = 'Income' AND "incomeBalance" = 'Income Statement'
+ AND "consolidatedRate" = 'Average' AND NOT "isGroup" AND active
+ AND "parentId" = f.parent_id AND "companyGroupId" = f.group_id
+ FROM "account" WHERE id = shipping_id), 'Fresh chart: complete revenue leaf under Revenue';
+ ASSERT (SELECT count(*) = 1 FROM "account" WHERE "companyGroupId" = f.group_id
+ AND name = 'Shipping Revenue'), 'Shared chart: exactly one shipping leaf';
+ ASSERT (SELECT bool_and("salesShippingRevenueAccount" = shipping_id)
+ FROM "accountDefault" WHERE "companyId" = ANY(f.company_ids)), 'Shared chart: same default for both companies';
+ SELECT jsonb_agg(to_jsonb(a) ORDER BY a.id) INTO before_accounts FROM "account" a WHERE "companyGroupId" = f.group_id;
+ SELECT jsonb_agg(to_jsonb(ad) ORDER BY "companyId") INTO before_defaults FROM "accountDefault" ad WHERE "companyId" = ANY(f.company_ids);
+ PERFORM pg_temp.run_shipping_backfill();
+ ASSERT (SELECT jsonb_agg(to_jsonb(a) ORDER BY a.id) FROM "account" a WHERE "companyGroupId" = f.group_id) = before_accounts,
+ 'Rerun must preserve all account records';
+ ASSERT (SELECT jsonb_agg(to_jsonb(ad) ORDER BY "companyId") FROM "accountDefault" ad WHERE "companyId" = ANY(f.company_ids)) = before_defaults,
+ 'Rerun must preserve defaults including timestamps';
+ RAISE NOTICE 'PASS fresh/shared chart and exact rerun preservation';
+ RAISE SQLSTATE 'P9001';
+ EXCEPTION WHEN SQLSTATE 'P9001' THEN NULL; END;
+
+ BEGIN
+ f := pg_temp.seed_shipping_chart(2);
+ shipping_id := pg_temp.add_revenue_leaf(f, 'Shipping Revenue', '4897');
+ custom_id := pg_temp.add_revenue_leaf(f, 'Customer Freight Recovery', '4801');
+ UPDATE "accountDefault" SET "salesShippingRevenueAccount" = custom_id WHERE "companyId" = f.company_ids[1];
+ PERFORM pg_temp.run_shipping_backfill();
+ ASSERT (SELECT "salesShippingRevenueAccount" = custom_id FROM "accountDefault" WHERE "companyId" = f.company_ids[1]),
+ 'Populated custom shipping default must be preserved';
+ ASSERT (SELECT "salesShippingRevenueAccount" = shipping_id FROM "accountDefault" WHERE "companyId" = f.company_ids[2]),
+ 'Reuse existing custom-number Shipping Revenue leaf';
+ ASSERT (SELECT number = '4897' FROM "account" WHERE id = shipping_id), 'Reuse must not renumber shipping';
+ ASSERT (SELECT count(*) = 1 FROM "account" WHERE "companyGroupId" = f.group_id AND name = 'Shipping Revenue'),
+ 'Reuse must not duplicate shipping';
+ RAISE NOTICE 'PASS custom default and custom-number leaf preservation';
+ RAISE SQLSTATE 'P9001';
+ EXCEPTION WHEN SQLSTATE 'P9001' THEN NULL; END;
+
+ BEGIN
+ f := pg_temp.seed_shipping_chart();
+ custom_id := pg_temp.add_revenue_leaf(f, 'Existing account at 4050', '4050');
+ PERFORM pg_temp.run_shipping_backfill();
+ ASSERT (SELECT number = '4060' FROM "account" WHERE "companyGroupId" = f.group_id AND name = 'Shipping Revenue'),
+ 'Occupied 4050: use next free account number';
+ ASSERT (SELECT number = '4050' AND name = 'Existing account at 4050' FROM "account" WHERE id = custom_id),
+ 'Occupied 4050: preserve its owner';
+ RAISE NOTICE 'PASS account-number collision';
+ RAISE SQLSTATE 'P9001';
+ EXCEPTION WHEN SQLSTATE 'P9001' THEN NULL; END;
+
+ BEGIN
+ f := pg_temp.seed_shipping_chart();
+ INSERT INTO "account" (number, name, class, "accountType", "incomeBalance", "consolidatedRate",
+ "parentId", "companyGroupId", "createdBy")
+ SELECT n::text, 'Occupied ' || n, 'Revenue', 'Income', 'Income Statement', 'Average',
+ f.parent_id, f.group_id, 'system' FROM generate_series(4050, 4990, 10) AS n;
+ PERFORM pg_temp.expect_backfill_failure('Cannot resolve Shipping Revenue parent/account/number for groups: ' || f.group_id);
+ ASSERT NOT EXISTS (SELECT 1 FROM "account" WHERE "companyGroupId" = f.group_id AND name = 'Shipping Revenue'),
+ 'Exhausted range: do not insert an unnumbered shipping account';
+ RAISE NOTICE 'PASS exhausted number range rejected with group identity';
+ RAISE SQLSTATE 'P9001';
+ EXCEPTION WHEN SQLSTATE 'P9001' THEN NULL; END;
+
+ BEGIN
+ f := pg_temp.seed_shipping_chart();
+ UPDATE "account" SET name = 'Operating Revenue' WHERE id = f.parent_id;
+ PERFORM pg_temp.run_shipping_backfill();
+ ASSERT (SELECT "parentId" = f.parent_id FROM "account" WHERE "companyGroupId" = f.group_id AND name = 'Shipping Revenue'),
+ 'Renamed Revenue group: use the unique compatible sales parent';
+ RAISE NOTICE 'PASS renamed parent resolution';
+ RAISE SQLSTATE 'P9001';
+ EXCEPTION WHEN SQLSTATE 'P9001' THEN NULL; END;
+
+ BEGIN
+ f := pg_temp.seed_shipping_chart();
+ UPDATE "account" SET name = 'Operating Revenue' WHERE id = f.parent_id;
+ UPDATE "account" SET "parentId" = NULL WHERE id = f.sales_id;
+ PERFORM pg_temp.expect_backfill_failure('Cannot resolve Shipping Revenue');
+ RAISE NOTICE 'PASS missing compatible parent rejected';
+ RAISE SQLSTATE 'P9001';
+ EXCEPTION WHEN SQLSTATE 'P9001' THEN NULL; END;
+
+ BEGIN
+ f := pg_temp.seed_shipping_chart(2);
+ UPDATE "account" SET name = 'Revenue A' WHERE id = f.parent_id;
+ INSERT INTO "account" (name, class, "accountType", "incomeBalance", "isGroup", "companyGroupId", "createdBy")
+ VALUES ('Revenue B', 'Revenue', 'Income', 'Income Statement', true, f.group_id, 'system') RETURNING id INTO second_parent;
+ custom_id := pg_temp.add_revenue_leaf(f, 'Other Sales', '4020');
+ UPDATE "account" SET "parentId" = second_parent WHERE id = custom_id;
+ UPDATE "accountDefault" SET "salesAccount" = custom_id WHERE "companyId" = f.company_ids[2];
+ PERFORM pg_temp.expect_backfill_failure('Cannot resolve Shipping Revenue');
+ ASSERT NOT EXISTS (SELECT 1 FROM "account" WHERE "companyGroupId" = f.group_id AND name = 'Shipping Revenue'),
+ 'Ambiguous parents: no orphaned/guessed shipping account';
+ RAISE NOTICE 'PASS ambiguous sales parents rejected';
+ RAISE SQLSTATE 'P9001';
+ EXCEPTION WHEN SQLSTATE 'P9001' THEN NULL; END;
+
+ BEGIN
+ good := pg_temp.seed_shipping_chart();
+ f := pg_temp.seed_shipping_chart();
+ UPDATE "account" SET class = 'Expense' WHERE id = f.parent_id;
+ SELECT jsonb_agg(to_jsonb(a) ORDER BY a.id) INTO before_accounts FROM "account" a
+ WHERE "companyGroupId" IN (good.group_id, f.group_id);
+ SELECT jsonb_agg(to_jsonb(ad) ORDER BY "companyId") INTO before_defaults FROM "accountDefault" ad
+ WHERE "companyId" = ANY(good.company_ids || f.company_ids);
+ PERFORM pg_temp.expect_backfill_failure('Cannot resolve Shipping Revenue');
+ ASSERT (SELECT jsonb_agg(to_jsonb(a) ORDER BY a.id) FROM "account" a
+ WHERE "companyGroupId" IN (good.group_id, f.group_id)) = before_accounts,
+ 'One incompatible group must roll back all account changes';
+ ASSERT (SELECT jsonb_agg(to_jsonb(ad) ORDER BY "companyId") FROM "accountDefault" ad
+ WHERE "companyId" = ANY(good.company_ids || f.company_ids)) = before_defaults,
+ 'One incompatible group must roll back all default changes';
+ RAISE NOTICE 'PASS incompatible canonical parent and multi-group atomic failure';
+ RAISE SQLSTATE 'P9001';
+ EXCEPTION WHEN SQLSTATE 'P9001' THEN NULL; END;
+
+ BEGIN
+ f := pg_temp.seed_shipping_chart();
+ INSERT INTO "account" (name, class, "accountType", "incomeBalance", "isGroup", "companyGroupId", "createdBy")
+ VALUES ('Shipping Revenue', 'Revenue', 'Income', 'Income Statement', true, f.group_id, 'system');
+ PERFORM pg_temp.expect_backfill_failure('Cannot resolve Shipping Revenue');
+ RAISE NOTICE 'PASS conflicting Shipping Revenue group rejected';
+ RAISE SQLSTATE 'P9001';
+ EXCEPTION WHEN SQLSTATE 'P9001' THEN NULL; END;
+
+ BEGIN
+ f := pg_temp.seed_shipping_chart();
+ shipping_id := pg_temp.add_revenue_leaf(f, 'Shipping Revenue', '4897');
+ UPDATE "account" SET "parentId" = NULL WHERE id = shipping_id;
+ PERFORM pg_temp.expect_backfill_failure('Cannot resolve Shipping Revenue');
+ RAISE NOTICE 'PASS existing incompatible shipping leaf rejected';
+ RAISE SQLSTATE 'P9001';
+ EXCEPTION WHEN SQLSTATE 'P9001' THEN NULL; END;
+
+ BEGIN
+ f := pg_temp.seed_shipping_chart();
+ UPDATE "account" SET name = 'Shipping Revenue' WHERE id = f.sales_id;
+ PERFORM pg_temp.expect_backfill_failure('Cannot resolve Shipping Revenue');
+ RAISE NOTICE 'PASS shipping candidate cannot equal the sales default';
+ RAISE SQLSTATE 'P9001';
+ EXCEPTION WHEN SQLSTATE 'P9001' THEN NULL; END;
+
+ BEGIN
+ f := pg_temp.seed_shipping_chart();
+ UPDATE "accountDefault" SET "salesShippingRevenueAccount" = f.sales_id WHERE "companyId" = f.company_ids[1];
+ PERFORM pg_temp.expect_backfill_failure('Invalid shipping defaults');
+ RAISE NOTICE 'PASS populated shipping default cannot equal sales';
+ RAISE SQLSTATE 'P9001';
+ EXCEPTION WHEN SQLSTATE 'P9001' THEN NULL; END;
+
+ BEGIN
+ f := pg_temp.seed_shipping_chart();
+ good := pg_temp.seed_shipping_chart();
+ custom_id := pg_temp.add_revenue_leaf(good, 'Other group freight', '4801');
+ UPDATE "accountDefault" SET "salesShippingRevenueAccount" = custom_id WHERE "companyId" = f.company_ids[1];
+ PERFORM pg_temp.expect_backfill_failure('Invalid shipping defaults for companies: ' || f.company_ids[1]);
+ RAISE NOTICE 'PASS cross-group shipping default rejected with company identity';
+ RAISE SQLSTATE 'P9001';
+ EXCEPTION WHEN SQLSTATE 'P9001' THEN NULL; END;
+
+ ASSERT NOT EXISTS (SELECT 1 FROM accounting_original_accounts original
+ LEFT JOIN "account" a ON a.id = original.id WHERE to_jsonb(a) IS DISTINCT FROM original.body),
+ 'Harness must not alter any original accounts';
+ ASSERT NOT EXISTS (SELECT 1 FROM accounting_original_defaults original
+ LEFT JOIN "accountDefault" ad ON ad."companyId" = original."companyId" WHERE to_jsonb(ad) IS DISTINCT FROM original.body),
+ 'Harness must not alter any original defaults';
+END;
+$backfill_cases$;
+
+ROLLBACK;
diff --git a/packages/database/supabase/tests/intercompany-elimination.test.sql b/packages/database/supabase/tests/intercompany-elimination.test.sql
index cc8e7d1517..212a8d1e77 100644
--- a/packages/database/supabase/tests/intercompany-elimination.test.sql
+++ b/packages/database/supabase/tests/intercompany-elimination.test.sql
@@ -1,30 +1,13 @@
--- 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.
-
+-- Intercompany elimination against the real capture-driven RPC.
+-- Isolated fixture companies/accounts; no existing business data is read or edited.
+-- Run: pnpm exec tsx scripts/run-local-accounting-check.ts psql -X
+-- -v ON_ERROR_STOP=1 -f packages/database/supabase/tests/intercompany-elimination.test.sql
+-- Seeded SQL capture proves elimination, not TypeScript/HTTP posting wiring.
\set ON_ERROR_STOP on
BEGIN;
+SET LOCAL "app.sync_in_progress" = 'true';
+SET LOCAL statement_timeout = '60s';
--- 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,
@@ -40,7 +23,7 @@ CREATE FUNCTION pg_temp.seed_ic_trade(
) 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;
+ j_s text; j_b text; seller_period text; buyer_period 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();
@@ -52,25 +35,29 @@ BEGIN
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;
+ SELECT id INTO STRICT seller_period FROM "accountingPeriod" WHERE "companyId"=p_seller AND "startDate"<=p_date AND "endDate">=p_date;
+ SELECT id INTO STRICT buyer_period FROM "accountingPeriod" WHERE "companyId"=p_buyer AND "startDate"<=p_date AND "endDate">=p_date;
+
+ -- Original fixture journals are explicitly posted with valid periods/audits.
-- 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;
+ INSERT INTO "journal"("companyId","journalEntryId","postingDate","description","sourceType","status","accountingPeriodId","createdBy")
+ VALUES (p_seller,'HS-'||ref,p_date,'Harness sale','Sales Invoice','Posted',seller_period,p_user) RETURNING id INTO j_s;
+ INSERT INTO "journalLine"("journalId","accountId","amount","journalLineReference","companyId","documentType","documentId","createdBy")
+ VALUES (j_s,a_icrec, p_revenue, ref,p_seller,'Invoice','HARNESS-SALE',p_user) RETURNING id INTO l_icrec;
+ INSERT INTO "journalLine"("journalId","accountId","amount","journalLineReference","companyId","documentType","documentId","createdBy")
+ VALUES (j_s,a_sales, p_revenue, ref,p_seller,'Invoice','HARNESS-SALE',p_user) RETURNING id INTO l_sales;
+ INSERT INTO "journalLine"("journalId","accountId","amount","journalLineReference","companyId","documentType","documentId","createdBy")
+ VALUES (j_s,a_cogs, p_cogs, ref,p_seller,'Invoice','HARNESS-SALE',p_user) RETURNING id INTO l_cogs;
+ INSERT INTO "journalLine"("journalId","accountId","amount","journalLineReference","companyId","documentType","documentId","createdBy")
+ VALUES (j_s,a_fg, -p_cogs, ref,p_seller,'Invoice','HARNESS-SALE',p_user) 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;
+ INSERT INTO "journal"("companyId","journalEntryId","postingDate","description","sourceType","status","accountingPeriodId","createdBy")
+ VALUES (p_buyer,'HB-'||ref,p_date,'Harness purchase','Purchase Invoice','Posted',buyer_period,p_user) RETURNING id INTO j_b;
+ INSERT INTO "journalLine"("journalId","accountId","amount","journalLineReference","companyId","documentType","documentId","createdBy")
+ VALUES (j_b,a_cap, p_revenue, ref,p_buyer,'Invoice','HARNESS-PURCH',p_user) RETURNING id INTO l_cap;
+ INSERT INTO "journalLine"("journalId","accountId","amount","journalLineReference","companyId","documentType","documentId","createdBy")
+ VALUES (j_b,a_icpay, p_revenue, ref,p_buyer,'Invoice','HARNESS-PURCH',p_user) RETURNING id INTO l_icpay;
-- Matched intercompany transactions (both directions). targetJournalLineId is
-- the per-trade seller<->buyer link that matchIntercompanyTransactions sets:
@@ -101,6 +88,11 @@ END $fn$ LANGUAGE plpgsql;
CREATE FUNCTION pg_temp.assert_balanced(p_grp text, p_date date, p_label text) RETURNS void AS $fn$
DECLARE r record;
BEGIN
+ ASSERT NOT EXISTS (
+ SELECT 1 FROM journal j JOIN company c ON c.id=j."companyId"
+ WHERE c."companyGroupId"=p_grp AND c."isEliminationEntity" AND j."eliminationKind" IS NOT NULL
+ AND j."postingDate"=p_date AND j.status<>'Posted'
+ ), p_label||': real elimination RPC must create Posted journals';
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
@@ -124,54 +116,106 @@ CREATE FUNCTION pg_temp.consol(p_grp text, p_num text, p_asof date DEFAULT NULL)
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
+ WHERE c."companyGroupId"=p_grp AND a."number"=p_num AND j.status='Posted'
AND (p_asof IS NULL OR j."postingDate" <= p_asof);
$fn$ LANGUAGE sql;
+-- Multiline capture contract: both controls, both merchandise revenues, both
+-- shipping revenues and both costs are retained. External tax is never captured.
+CREATE FUNCTION pg_temp.seed_ic_multiline(p_grp text,p_seller text,p_buyer text,p_user text,p_date date)
+RETURNS void LANGUAGE plpgsql AS $fn$
+DECLARE seller_j text; buyer_j text; seller_tx text; buyer_tx text; seller_control text; buyer_control text;
+ seller_period text; buyer_period text; r record; line_id text; captures jsonb:='[]'; ref text:=id();
+BEGIN
+ SELECT id INTO STRICT seller_period FROM "accountingPeriod" WHERE "companyId"=p_seller AND "startDate"<=p_date AND "endDate">=p_date;
+ SELECT id INTO STRICT buyer_period FROM "accountingPeriod" WHERE "companyId"=p_buyer AND "startDate"<=p_date AND "endDate">=p_date;
+ INSERT INTO journal ("companyId","journalEntryId","postingDate","sourceType",status,"accountingPeriodId","createdBy")
+ VALUES(p_seller,'HSM-'||ref,p_date,'Sales Invoice','Posted',seller_period,p_user) RETURNING id INTO seller_j;
+ INSERT INTO journal ("companyId","journalEntryId","postingDate","sourceType",status,"accountingPeriodId","createdBy")
+ VALUES(p_buyer,'HBM-'||ref,p_date,'Purchase Invoice','Posted',buyer_period,p_user) RETURNING id INTO buyer_j;
+ FOR r IN SELECT lines.*,a.id AS account_id FROM (VALUES
+ (true,'1130',71::numeric,'Control'),(true,'1130',39,'Control'),
+ (true,'4010',60,'Revenue'),(true,'4010',30,'Revenue'),
+ (true,'4040',4,'Revenue'),(true,'4040',6,'Revenue'),
+ (true,'2110',7,NULL),(true,'2110',3,NULL),
+ (true,'5010',40,'COGS'),(true,'5010',20,'COGS'),(true,'1220',-60,NULL),
+ (false,'2020',71,'Control'),(false,'2020',39,'Control'),
+ (false,'1350',64,'Capitalization'),(false,'1350',36,'Capitalization'),
+ (false,'1410',7,NULL),(false,'1410',3,NULL)
+ ) AS lines(seller,number,amount,role)
+ JOIN account a ON a.number=lines.number AND a."companyGroupId"=p_grp LOOP
+ INSERT INTO "journalLine" ("journalId","accountId",amount,"journalLineReference","companyId","documentType","documentId","createdBy",description)
+ VALUES(CASE WHEN r.seller THEN seller_j ELSE buyer_j END,r.account_id,r.amount,'HML-'||id(),
+ CASE WHEN r.seller THEN p_seller ELSE p_buyer END,'Invoice',ref,p_user,COALESCE(r.role,'External component')) RETURNING id INTO line_id;
+ IF r.role='Control' THEN
+ IF r.seller THEN seller_control:=COALESCE(seller_control,line_id);
+ ELSE buyer_control:=COALESCE(buyer_control,line_id); END IF;
+ END IF;
+ IF r.role IS NOT NULL THEN
+ captures:=captures||jsonb_build_array(jsonb_build_object('seller',r.seller,'role',r.role,'line_id',line_id,'account_id',r.account_id,'amount',r.amount));
+ END IF;
+ END LOOP;
+ INSERT INTO "intercompanyTransaction" ("companyGroupId","sourceCompanyId","targetCompanyId","sourceJournalLineId","targetJournalLineId",amount,"currencyCode",status,"documentType","documentId")
+ VALUES(p_grp,p_seller,p_buyer,seller_control,buyer_control,110,'USD','Matched','Invoice','HSM-'||ref) RETURNING id INTO seller_tx;
+ INSERT INTO "intercompanyTransaction" ("companyGroupId","sourceCompanyId","targetCompanyId","sourceJournalLineId","targetJournalLineId",amount,"currencyCode",status,"documentType","documentId")
+ VALUES(p_grp,p_buyer,p_seller,buyer_control,seller_control,110,'USD','Matched','Invoice','HBM-'||ref) RETURNING id INTO buyer_tx;
+ INSERT INTO "intercompanyEliminationLine" ("companyId","intercompanyTransactionId",role,"journalLineId","accountId",amount,"createdBy")
+ SELECT CASE WHEN c.seller THEN p_seller ELSE p_buyer END,CASE WHEN c.seller THEN seller_tx ELSE buyer_tx END,
+ c.role::"intercompanyEliminationRole",c.line_id,c.account_id,c.amount,p_user
+ FROM jsonb_to_recordset(captures) AS c(seller boolean,role text,line_id text,account_id text,amount numeric);
+ ASSERT (SELECT count(*)=12 AND sum(amount) FILTER(WHERE role='Control')=220 AND sum(amount) FILTER(WHERE role='Revenue')=100
+ FROM "intercompanyEliminationLine" WHERE "intercompanyTransactionId" IN (seller_tx,buyer_tx)), 'Complete multiline captures must retain all four control and four revenue rows';
+ ASSERT NOT EXISTS (SELECT 1 FROM journal j JOIN "journalLine" l ON l."journalId"=j.id JOIN account a ON a.id=l."accountId"
+ WHERE j.id IN (seller_j,buyer_j) GROUP BY j.id HAVING sum(CASE WHEN a.class IN ('Asset','Expense') THEN l.amount ELSE -l.amount END)<>0), 'Multiline original fixture journals must balance';
+END;
+$fn$;
+
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;
+ v_parent text; v_elim text; v_ref text; fixture_company text; account_seed record;
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
+ -- SQLSTATE P9001 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;
+ v_ref := id(); v_user := 'system';
+ INSERT INTO "companyGroup" (name,"createdBy") VALUES ('IC harness '||v_ref,v_user) RETURNING id INTO v_grp;
+ INSERT INTO company (name,"companyGroupId","baseCurrencyCode",timezone)
+ VALUES ('IC harness parent '||v_ref,v_grp,'USD','America/New_York') RETURNING id INTO v_parent;
+ INSERT INTO company (name,"companyGroupId","baseCurrencyCode","parentCompanyId",timezone)
+ VALUES ('IC harness seller '||v_ref,v_grp,'USD',v_parent,'America/New_York') RETURNING id INTO v_seller;
+ INSERT INTO company (name,"companyGroupId","baseCurrencyCode","parentCompanyId",timezone)
+ VALUES ('IC harness buyer '||v_ref,v_grp,'USD',v_parent,'America/New_York') RETURNING id INTO v_buyer;
+ INSERT INTO company (name,"companyGroupId","baseCurrencyCode","parentCompanyId","isEliminationEntity",timezone)
+ VALUES ('IC harness elimination '||v_ref,v_grp,'USD',v_parent,true,'America/New_York') RETURNING id INTO v_elim;
+ INSERT INTO "userToCompany" ("userId","companyId",role) VALUES (v_user,v_parent,'employee');
+ INSERT INTO currency (code,"companyGroupId","decimalPlaces","createdBy") VALUES ('USD',v_grp,2,v_user);
+ FOR account_seed IN SELECT * FROM (VALUES
+ ('1130','IC Receivable','Asset','Accounts Receivable','Balance Sheet'),
+ ('2020','IC Payable','Liability','Accounts Payable','Balance Sheet'),
+ ('4010','Sales','Revenue','Income','Income Statement'),
+ ('4040','Shipping Revenue','Revenue','Income','Income Statement'),
+ ('5010','COGS','Expense','Cost of Goods Sold','Income Statement'),
+ ('1220','Finished Goods','Asset','Inventory','Balance Sheet'),
+ ('1350','Machinery','Asset','Fixed Asset','Balance Sheet'),
+ ('1310','Acquisition Cost','Asset','Fixed Asset','Balance Sheet'),
+ ('2110','External sales tax','Liability','Tax','Balance Sheet'),
+ ('1410','External purchase tax','Asset','Other Current Asset','Balance Sheet')
+ ) AS accounts(number,name,class,account_type,income_balance) LOOP
+ INSERT INTO account (number,name,class,"accountType","incomeBalance","companyGroupId","createdBy")
+ VALUES(account_seed.number,account_seed.name,account_seed.class::"glAccountClass",account_seed.account_type::"accountType",account_seed.income_balance::"glIncomeBalance",v_grp,v_user);
+ END LOOP;
+ FOREACH fixture_company IN ARRAY ARRAY[v_parent,v_seller,v_buyer,v_elim] LOOP
+ INSERT INTO "accountingPeriod" ("startDate","endDate",status,"companyId","createdBy","fiscalYear","periodNumber")
+ VALUES('2026-01-01','2026-12-31','Active',fixture_company,v_user,2026,1);
+ END LOOP;
+ INSERT INTO "fiscalYearSettings" ("companyId","updatedBy") VALUES(v_elim,v_user);
+ INSERT INTO "sequence" ("table",name,prefix,"companyId","updatedBy")
+ VALUES('journalEntry','IC harness journals','HJE-',v_elim,v_user) ON CONFLICT DO NOTHING;
+ INSERT INTO item ("readableId",name,type,"itemTrackingType","companyId","createdBy")
+ VALUES('HI-'||v_ref,'IC harness item','Part','Inventory',v_buyer,v_user) RETURNING id INTO v_item;
-- 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).
@@ -196,8 +240,8 @@ BEGIN
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;
+ RAISE SQLSTATE 'P9001';
+ EXCEPTION WHEN SQLSTATE 'P9001' THEN NULL; END;
-- Scenario 2: INVENTORY buyer, fully held (on-hand >= traded qty -> fraction 1).
BEGIN
@@ -208,8 +252,8 @@ BEGIN
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;
+ RAISE SQLSTATE 'P9001';
+ EXCEPTION WHEN SQLSTATE 'P9001' 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,
@@ -222,8 +266,8 @@ BEGIN
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;
+ RAISE SQLSTATE 'P9001';
+ EXCEPTION WHEN SQLSTATE 'P9001' 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
@@ -237,8 +281,8 @@ BEGIN
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;
+ RAISE SQLSTATE 'P9001';
+ EXCEPTION WHEN SQLSTATE 'P9001' THEN NULL; END;
-- Scenario 5: REGENERATE idempotency. Generate, then regenerate (reverses +
-- re-derives). The consolidated result must be unchanged — no double counting.
@@ -251,8 +295,8 @@ BEGIN
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;
+ RAISE SQLSTATE 'P9001';
+ EXCEPTION WHEN SQLSTATE 'P9001' THEN NULL; END;
-- Scenario 6: MULTI-TRADE per pair with DIFFERENT margins and DIFFERENT
-- capitalization accounts (the per-trade-allocation fix). Two fixed-asset
@@ -269,8 +313,27 @@ BEGIN
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 SQLSTATE 'P9001';
+ EXCEPTION WHEN SQLSTATE 'P9001' THEN NULL; END;
+
+ -- Scenario 7: multiple sales/shipping/tax/control rows from one matched trade.
+ BEGIN
+ PERFORM pg_temp.seed_ic_multiline(v_grp,v_seller,v_buyer,v_user,d);
+ ASSERT "generateEliminationEntries"(v_grp,v_user)=2,'S7 multiline: expected one control and one revenue elimination journal';
+ ASSERT pg_temp.consol(v_grp,'1130')=0 AND pg_temp.consol(v_grp,'2020')=0,'S7 multiline: every IC control must eliminate';
+ ASSERT pg_temp.consol(v_grp,'4010')=0 AND pg_temp.consol(v_grp,'4040')=0,'S7 multiline: every merchandise and shipping revenue row must eliminate';
+ ASSERT pg_temp.consol(v_grp,'5010')=0 AND pg_temp.consol(v_grp,'1350')=60 AND pg_temp.consol(v_grp,'1220')=-60,'S7 multiline: buyer capitalization must retain group cost';
+ ASSERT pg_temp.consol(v_grp,'2110')=10 AND pg_temp.consol(v_grp,'1410')=10,'S7 multiline: external payable/recoverable tax must remain';
+ PERFORM pg_temp.assert_balanced(v_grp,d,'S7 multiline');
+ ASSERT NOT EXISTS(SELECT 1 FROM "journalLine" l JOIN journal j ON j.id=l."journalId" JOIN account a ON a.id=l."accountId"
+ WHERE j."companyId"=v_elim AND a.number IN ('2110','1410')),'S7 multiline: elimination must not touch external tax';
+ PERFORM "generateEliminationEntries"(v_grp,v_user,true);
+ ASSERT pg_temp.consol(v_grp,'1130')=0 AND pg_temp.consol(v_grp,'2020')=0 AND pg_temp.consol(v_grp,'4010')=0 AND pg_temp.consol(v_grp,'4040')=0,'S7 multiline: regeneration must preserve all control/revenue elimination';
+ ASSERT pg_temp.consol(v_grp,'1350')=60 AND pg_temp.consol(v_grp,'2110')=10 AND pg_temp.consol(v_grp,'1410')=10,'S7 multiline: regeneration must preserve group cost and external tax';
+ PERFORM pg_temp.assert_balanced(v_grp,d,'S7 multiline regenerate');
+ RAISE NOTICE 'S7 multiline taxed/shipping full captures and regeneration PASS';
+ RAISE SQLSTATE 'P9001';
+ EXCEPTION WHEN SQLSTATE 'P9001' THEN NULL; END;
RAISE NOTICE '================= ALL SCENARIOS PASSED =================';
END $main$;
diff --git a/packages/ee/src/accounting/core/document-costing.test.ts b/packages/ee/src/accounting/core/document-costing.test.ts
index 1128b0a83e..fc99b2d347 100644
--- a/packages/ee/src/accounting/core/document-costing.test.ts
+++ b/packages/ee/src/accounting/core/document-costing.test.ts
@@ -12,6 +12,16 @@ import {
*/
function makeDb(tables: {
purchaseInvoice?: { currencyCode: string; exchangeRate: number } | null;
+ company?: { baseCurrencyCode: string } | null;
+ foreignCurrencyOnly?: boolean;
+ currency?: { decimalPlaces: number } | null;
+ purchaseInvoiceLine?: Array<{
+ quantity: number;
+ supplierUnitPrice: number;
+ supplierShippingCost: number;
+ supplierTaxAmount: number;
+ }>;
+ purchaseInvoiceDelivery?: { supplierShippingCost: number } | null;
journalLine?: Array<{
id: string;
accountId: string | null;
@@ -33,23 +43,63 @@ function makeDb(tables: {
}>;
}) {
const makeBuilder = (table: string) => {
+ const filters: unknown[][] = [];
const builder: any = {
select: () => builder,
innerJoin: () => builder,
leftJoin: () => builder,
- where: () => builder,
+ where: (...args: unknown[]) => {
+ filters.push(args);
+ return builder;
+ },
orderBy: () => builder,
async execute() {
- if (table === "journalLine") return tables.journalLine ?? [];
+ if (table === "journalLine")
+ return (
+ tables.journalLine ?? [
+ {
+ id: "control",
+ accountId: "ap",
+ amount: 100,
+ description: "Accounts Payable",
+ documentLineReference: null,
+ accountClass: "Liability"
+ }
+ ]
+ );
if (table === "journalLineDimension")
return tables.journalLineDimension ?? [];
if (table === "purchaseOrderLine")
return tables.purchaseOrderLine ?? [];
+ if (table === "purchaseInvoiceLine")
+ return tables.purchaseInvoiceLine ?? [];
return [];
},
async executeTakeFirst() {
if (table === "purchaseInvoice")
- return tables.purchaseInvoice ?? undefined;
+ return tables.purchaseInvoice
+ ? { ...tables.purchaseInvoice, postingDate: "2026-09-07" }
+ : undefined;
+ if (table === "company")
+ return tables.company === null
+ ? undefined
+ : {
+ companyGroupId: "group-1",
+ ...(tables.company ?? { baseCurrencyCode: "USD" })
+ };
+ if (table === "currency" && tables.foreignCurrencyOnly)
+ return filters.some(
+ (filter) =>
+ filter[0] === "companyGroupId" && filter[2] === "group-1"
+ )
+ ? undefined
+ : { decimalPlaces: 3 };
+ if (table === "currency")
+ return tables.currency === null
+ ? undefined
+ : (tables.currency ?? { decimalPlaces: 2 });
+ if (table === "purchaseInvoiceDelivery")
+ return tables.purchaseInvoiceDelivery ?? undefined;
return undefined;
}
};
@@ -84,8 +134,7 @@ describe("loadBillCostingLines", () => {
const result = await loadBillCostingLines(db, {
companyId: "company-1",
- billId: "pi_1",
- payablesAccountId: "acct_ap"
+ billId: "pi_1"
});
expect(result.currencyCode).toBe("USD");
@@ -141,8 +190,7 @@ describe("loadBillCostingLines", () => {
const result = await loadBillCostingLines(db, {
companyId: "company-1",
- billId: "pi_1",
- payablesAccountId: "acct_ap"
+ billId: "pi_1"
});
expect(result.lines).toEqual([
@@ -173,6 +221,14 @@ describe("loadBillCostingLines", () => {
description: "GR/IR",
documentLineReference: null,
accountClass: "Asset"
+ },
+ {
+ id: "ap",
+ accountId: "ap",
+ amount: 100,
+ description: "Accounts Payable",
+ documentLineReference: null,
+ accountClass: "Liability"
}
],
journalLineDimension: [
@@ -182,8 +238,7 @@ describe("loadBillCostingLines", () => {
const result = await loadBillCostingLines(db, {
companyId: "company-1",
- billId: "pi_1",
- payablesAccountId: "acct_ap"
+ billId: "pi_1"
});
expect(result.lines[0]?.dimensions).toEqual([
@@ -191,21 +246,18 @@ describe("loadBillCostingLines", () => {
]);
});
- it("returns no lines when the bill has no posted journal", async () => {
- const db = makeDb({
- purchaseInvoice: { currencyCode: "EUR", exchangeRate: 1.1 },
- journalLine: []
- });
-
- const result = await loadBillCostingLines(db, {
- companyId: "company-1",
- billId: "pi_1",
- payablesAccountId: "acct_ap"
+ it("warns when the bill has no posted journal", async () => {
+ await expect(
+ loadBillCostingLines(
+ makeDb({
+ purchaseInvoice: { currencyCode: "EUR", exchangeRate: 1.1 },
+ journalLine: []
+ }),
+ { companyId: "company-1", billId: "pi_1" }
+ )
+ ).rejects.toMatchObject({
+ failure: { errorCode: "UNMAPPED_ACCOUNTS", warning: true }
});
-
- expect(result.lines).toEqual([]);
- expect(result.currencyCode).toBe("EUR");
- expect(result.exchangeRate).toBe(1.1);
});
});
@@ -216,34 +268,254 @@ describe("toTransactionCurrencyLines", () => {
amount,
description: id
});
-
- it("passes through at rate 1", () => {
- const lines = [line("a", 280), line("b", 20)];
- expect(toTransactionCurrencyLines(lines, 1)).toEqual(lines);
+ it("multiplies base amounts by foreign per base rate", () => {
+ expect(
+ toTransactionCurrencyLines([line("a", 100)], {
+ exchangeRate: 0.8,
+ documentTotal: 80,
+ decimalPlaces: 2
+ })[0]?.amount
+ ).toBe(80);
+ });
+ it("assigns rounding residual to the largest magnitude deterministically", () => {
+ const result = toTransactionCurrencyLines([line("a", 100), line("b", 10)], {
+ exchangeRate: 1 / 3,
+ documentTotal: 36.67,
+ decimalPlaces: 2
+ });
+ expect(result.map((l) => l.amount)).toEqual([33.34, 3.33]);
+ });
+ it("rounds identity rate and preserves labels, dimensions and negative variance", () => {
+ const source = {
+ ...line("a", 100.004),
+ dimensions: [{ dimensionId: "d", valueId: "v" }]
+ };
+ expect(
+ toTransactionCurrencyLines([source, line("ppv", -20.001)], {
+ exchangeRate: 1,
+ documentTotal: 80,
+ decimalPlaces: 2
+ })
+ ).toEqual([{ ...source, amount: 100 }, line("ppv", -20)]);
+ });
+ it.each([
+ [0, 80],
+ [3, 80.003]
+ ])("uses document scale %i", (decimalPlaces, total) => {
+ expect(
+ toTransactionCurrencyLines([line("a", total / 0.8)], {
+ exchangeRate: 0.8,
+ documentTotal: total,
+ decimalPlaces
+ })[0]?.amount
+ ).toBe(total);
+ });
+ it("does not round the base sum to cents before conversion", () => {
+ expect(
+ toTransactionCurrencyLines([line("a", 0.005), line("b", 0.005)], {
+ exchangeRate: 16000,
+ documentTotal: 160,
+ decimalPlaces: 2
+ }).map((l) => l.amount)
+ ).toEqual([80, 80]);
+ });
+ it("rejects an economic mismatch instead of hiding it in a residual", () => {
+ expect(() =>
+ toTransactionCurrencyLines([line("a", 100)], {
+ exchangeRate: 0.8,
+ documentTotal: 90,
+ decimalPlaces: 2
+ })
+ ).toThrow(/total|reconcil/i);
+ });
+ it.each([
+ 0,
+ -1,
+ Number.NaN,
+ Number.POSITIVE_INFINITY
+ ])("rejects invalid rate %s", (exchangeRate) => {
+ expect(() =>
+ toTransactionCurrencyLines([line("a", 100)], {
+ exchangeRate,
+ documentTotal: 80,
+ decimalPlaces: 2
+ })
+ ).toThrow();
+ });
+ it("rejects nonfinite amounts and invalid precision", () => {
+ expect(() =>
+ toTransactionCurrencyLines([line("a", Infinity)], {
+ exchangeRate: 1,
+ documentTotal: 80,
+ decimalPlaces: 2
+ })
+ ).toThrow();
+ expect(() =>
+ toTransactionCurrencyLines([line("a", 100)], {
+ exchangeRate: 1,
+ documentTotal: 100,
+ decimalPlaces: -1
+ })
+ ).toThrow();
+ });
+ it("rejects an authoritative total outside its document precision", () => {
+ expect(() =>
+ toTransactionCurrencyLines([line("a", 80.003)], {
+ exchangeRate: 1,
+ documentTotal: 80.003,
+ decimalPlaces: 2
+ })
+ ).toThrow(/precision/);
});
+ it("allows an empty zero document", () => {
+ expect(
+ toTransactionCurrencyLines([], {
+ exchangeRate: 1,
+ documentTotal: 0,
+ decimalPlaces: 2
+ })
+ ).toEqual([]);
+ });
+});
- it("divides by the rate and balances the residue into the largest line", () => {
- // base 100 @ rate 3 → 33.3333; base 10 @ rate 3 → 3.3333.
- // rounded: 33.33 + 3.33 = 36.66; target round(110/3)=36.67; residue +0.01
- // to the largest-|amount| line (a).
- const converted = toTransactionCurrencyLines(
- [line("a", 100), line("b", 10)],
- 3
+describe("authoritative bill metadata", () => {
+ it("loads supplier document totals once including delivery and line tax", async () => {
+ const result = await loadBillCostingLines(
+ makeDb({
+ purchaseInvoice: { currencyCode: "EUR", exchangeRate: 0.8 },
+ purchaseInvoiceLine: [
+ {
+ quantity: 2,
+ supplierUnitPrice: 32,
+ supplierShippingCost: 4,
+ supplierTaxAmount: 8
+ }
+ ],
+ purchaseInvoiceDelivery: { supplierShippingCost: 4 }
+ }),
+ { companyId: "company-1", billId: "pi-1" }
);
- expect(converted.map((l) => l.amount)).toEqual([33.34, 3.33]);
- const sum = converted.reduce((s, l) => s + Math.round(l.amount * 100), 0);
- expect(sum).toBe(Math.round((110 / 3) * 100));
+ expect(result).toMatchObject({
+ documentTotal: 80,
+ decimalPlaces: 2,
+ baseCurrencyCode: "USD",
+ postingDate: "2026-09-07",
+ exchangeRate: 0.8
+ });
});
+ it.each([
+ { purchaseInvoice: null },
+ { company: null },
+ { currency: null },
+ { purchaseInvoice: { currencyCode: "USD", exchangeRate: 0.8 } }
+ ])("rejects incomplete metadata: %j", async (overrides) => {
+ await expect(
+ loadBillCostingLines(
+ makeDb({
+ purchaseInvoice: { currencyCode: "EUR", exchangeRate: 0.8 },
+ ...overrides
+ }),
+ { companyId: "company-1", billId: "pi-1" }
+ )
+ ).rejects.toThrow();
+ });
+});
+
+it("does not borrow currency precision from another company group", async () => {
+ await expect(
+ loadBillCostingLines(
+ makeDb({
+ purchaseInvoice: { currencyCode: "EUR", exchangeRate: 0.8 },
+ foreignCurrencyOnly: true
+ }),
+ { companyId: "company-1", billId: "pi-1" }
+ )
+ ).rejects.toThrow(/precision/);
+});
- it("preserves negative (credit variance) amounts", () => {
- const converted = toTransactionCurrencyLines(
- [line("a", 300), line("ppv", -20)],
- 2
+describe("original bill control provenance", () => {
+ it.each([
+ "Accounts Payable",
+ "IC Payables"
+ ])("excludes original %s after a default change without dropping a costing row on the same account", async (description) => {
+ const result = await loadBillCostingLines(
+ makeDb({
+ purchaseInvoice: { currencyCode: "EUR", exchangeRate: 1.1 },
+ purchaseInvoiceLine: [
+ {
+ quantity: 1,
+ supplierUnitPrice: 110,
+ supplierShippingCost: 0,
+ supplierTaxAmount: 0
+ }
+ ],
+ journalLine: [
+ {
+ id: "cost",
+ accountId: "old-ap",
+ amount: -100,
+ description: "Explicit account charge",
+ documentLineReference: null,
+ accountClass: "Liability"
+ },
+ {
+ id: "ap",
+ accountId: "old-ap",
+ amount: 100,
+ description,
+ documentLineReference: null,
+ accountClass: "Liability"
+ }
+ ]
+ }),
+ { companyId: "company-1", billId: "pi_1" }
+ );
+ expect(result.lines.map((line) => [line.id, line.amount])).toEqual([
+ ["cost", 100]
+ ]);
+ expect(toTransactionCurrencyLines(result.lines, result)[0]?.amount).toBe(
+ 110
);
- expect(converted.map((l) => l.amount)).toEqual([150, -10]);
});
-
- it("returns [] for empty input", () => {
- expect(toTransactionCurrencyLines([], 1.5)).toEqual([]);
+ it.each(
+ [
+ [],
+ [
+ {
+ id: "cost",
+ accountId: "expense",
+ amount: 100,
+ description: "Cost",
+ documentLineReference: null,
+ accountClass: "Expense"
+ }
+ ],
+ [
+ {
+ id: "ap",
+ accountId: null,
+ amount: 100,
+ description: "Accounts Payable",
+ documentLineReference: null,
+ accountClass: null
+ }
+ ]
+ ].map((rows) => [rows])
+ )("reports missing original posting metadata before numeric reconciliation", async (journalLine) => {
+ await expect(
+ loadBillCostingLines(
+ makeDb({
+ purchaseInvoice: { currencyCode: "USD", exchangeRate: 1 },
+ journalLine
+ }),
+ { companyId: "company-1", billId: "pi_1" }
+ )
+ ).rejects.toMatchObject({
+ failure: {
+ errorCode: "UNMAPPED_ACCOUNTS",
+ warning: true,
+ metadata: { billId: "pi_1" }
+ }
+ });
});
});
diff --git a/packages/ee/src/accounting/core/document-costing.ts b/packages/ee/src/accounting/core/document-costing.ts
index b3fdce730e..b05fdc1a56 100644
--- a/packages/ee/src/accounting/core/document-costing.ts
+++ b/packages/ee/src/accounting/core/document-costing.ts
@@ -1,9 +1,18 @@
import type { Kysely, KyselyDatabase, KyselyTx } from "@carbon/database/client";
+import {
+ assertCurrencyDecimals,
+ assertExchangeRate,
+ classifyAccountingPostingRole,
+ round,
+ SCALE,
+ toDocumentAmount
+} from "@carbon/utils";
import { loadJournalLineDimensions } from "./dimension-mapping";
import {
+ JournalEntrySyncError,
type JournalLineDimensionRef,
- roundCurrency,
- toDebitSignedAmount
+ toDebitSignedAmount,
+ toPostingDateString
} from "./posting";
type Db = Kysely<KyselyDatabase> | KyselyTx;
@@ -58,8 +67,12 @@ export type BillCostingResult = {
lines: CostingLine[];
/** The invoice's transaction currency (ISO-4217). */
currencyCode: string;
- /** Base-per-transaction exchange rate (1 for base-currency bills). */
+ /** Document currency per company-base currency. */
exchangeRate: number;
+ documentTotal: number;
+ decimalPlaces: number;
+ baseCurrencyCode: string;
+ postingDate: string;
};
/**
@@ -72,22 +85,84 @@ export type BillCostingResult = {
* (`documentLineReference = purchase-invoice:<purchaseOrderLineId>`); direct
* no-PO lines and variance lines resolve to `sourceItem: undefined`.
*
- * Returns `lines: []` when the invoice has no posted Purchase Invoice
- * journal (not posted / accounting off) — the caller surfaces the Warning.
+ * Missing original posting/control metadata raises a structured Warning before
+ * any currency reconciliation can hide the actionable source problem.
*/
export async function loadBillCostingLines(
db: Db,
- args: { companyId: string; billId: string; payablesAccountId: string | null }
+ args: { companyId: string; billId: string }
): Promise<BillCostingResult> {
const invoice = await db
.selectFrom("purchaseInvoice")
- .select(["currencyCode", "exchangeRate"])
+ .select(["currencyCode", "exchangeRate", "postingDate"])
.where("id", "=", args.billId)
.where("companyId", "=", args.companyId)
.executeTakeFirst();
- const currencyCode = invoice?.currencyCode ?? "USD";
- const exchangeRate = Number(invoice?.exchangeRate) || 1;
+ const company = await db
+ .selectFrom("company")
+ .select(["baseCurrencyCode", "companyGroupId"])
+ .where("id", "=", args.companyId)
+ .executeTakeFirst();
+ if (
+ !invoice?.currencyCode ||
+ !invoice.postingDate ||
+ !company?.baseCurrencyCode ||
+ !company.companyGroupId
+ ) {
+ throw new Error(
+ "Bill currency, posting date and company base currency are required"
+ );
+ }
+ const currencyCode = invoice.currencyCode;
+ const baseCurrencyCode = company.baseCurrencyCode;
+ const exchangeRate = Number(invoice.exchangeRate);
+ const currency = await db
+ .selectFrom("currency")
+ .select("decimalPlaces")
+ .where("code", "=", currencyCode)
+ .where("companyGroupId", "=", company.companyGroupId)
+ .executeTakeFirst();
+ if (!currency || currency.decimalPlaces == null)
+ throw new Error("Bill currency precision is required");
+ const decimalPlaces = currency.decimalPlaces;
+ assertExchangeRate(exchangeRate);
+ assertCurrencyDecimals(decimalPlaces);
+ if (currencyCode === baseCurrencyCode && exchangeRate !== 1)
+ throw new Error("Base-currency bill requires identity exchange rate");
+ const [invoiceLines, delivery] = await Promise.all([
+ db
+ .selectFrom("purchaseInvoiceLine")
+ .select([
+ "quantity",
+ "supplierUnitPrice",
+ "supplierShippingCost",
+ "supplierTaxAmount"
+ ])
+ .where("invoiceId", "=", args.billId)
+ .where("companyId", "=", args.companyId)
+ .where("invoiceLineType", "!=", "Comment")
+ .execute(),
+ db
+ .selectFrom("purchaseInvoiceDelivery")
+ .select("supplierShippingCost")
+ .where("id", "=", args.billId)
+ .where("companyId", "=", args.companyId)
+ .executeTakeFirst()
+ ]);
+ const documentTotal = round(
+ invoiceLines.reduce(
+ (total, line) =>
+ total +
+ Number(line.quantity) * Number(line.supplierUnitPrice) +
+ Number(line.supplierShippingCost) +
+ Number(line.supplierTaxAmount),
+ Number(delivery?.supplierShippingCost ?? 0)
+ ),
+ decimalPlaces
+ );
+ if (!Number.isFinite(documentTotal))
+ throw new Error("Bill document total must be finite");
const rows = await db
.selectFrom("journalLine")
@@ -105,6 +180,7 @@ export async function loadBillCostingLines(
"journalLine.documentLineReference",
"account.class as accountClass"
])
+ .where("journalLine.documentType", "=", "Invoice")
.where("journalLine.documentId", "=", args.billId)
.where("journalLine.companyId", "=", args.companyId)
.where("journal.sourceType", "=", "Purchase Invoice")
@@ -113,11 +189,43 @@ export async function loadBillCostingLines(
.orderBy("journalLine.journalLineReference", "asc")
.execute();
- // AP control line(s) are re-booked by the provider's own bill mechanics —
- // exclude them; keep null-account lines (they fail preflight as unmapped).
+ const controls = rows.filter(
+ (row) => classifyAccountingPostingRole(row.description) === "Payables"
+ );
+ if (
+ !rows.length ||
+ !controls.length ||
+ controls.some((row) => !row.accountId)
+ ) {
+ throw new JournalEntrySyncError({
+ errorCode: "UNMAPPED_ACCOUNTS",
+ warning: true,
+ message: !rows.length
+ ? "Cannot sync bill: no posted Purchase Invoice journal found. Post the invoice with accounting enabled, then retry."
+ : "Cannot sync bill: its original posted payables control account is missing. Correct the posting, then retry.",
+ metadata: {
+ billId: args.billId,
+ controlLineIds: controls.map((row) => row.id)
+ }
+ });
+ }
+ // The provider creates its own AP control. Exclude the original role rows,
+ // preserving explicit costing even when it happens to use the same account.
const costingRows = rows.filter(
- (row) => row.accountId === null || row.accountId !== args.payablesAccountId
+ (row) => classifyAccountingPostingRole(row.description) !== "Payables"
);
+ const missingAccountLines = costingRows.filter((row) => !row.accountId);
+ if (missingAccountLines.length)
+ throw new JournalEntrySyncError({
+ errorCode: "UNMAPPED_ACCOUNTS",
+ warning: true,
+ message:
+ "Cannot sync bill: posted costing lines have no account. Correct the posting, then retry.",
+ metadata: {
+ billId: args.billId,
+ lineIdsWithoutAccount: missingAccountLines.map((row) => row.id)
+ }
+ });
const dimensionsByLine = await loadJournalLineDimensions(db, {
companyId: args.companyId,
@@ -168,14 +276,22 @@ export async function loadBillCostingLines(
return {
id: row.id,
accountId: row.accountId ?? null,
- amount: toDebitSignedAmount(row.accountClass, Number(row.amount) || 0),
+ amount: toDebitSignedAmount(row.accountClass, Number(row.amount)),
description: row.description ?? null,
...(sourceItem ? { sourceItem } : {}),
...(dimensions ? { dimensions } : {})
};
});
- return { lines, currencyCode, exchangeRate };
+ return {
+ lines,
+ currencyCode,
+ exchangeRate,
+ documentTotal,
+ decimalPlaces,
+ baseCurrencyCode,
+ postingDate: toPostingDateString(invoice.postingDate)
+ };
}
/** The item code/name label for a costing line (`"<code> <name>"`), or null
@@ -205,51 +321,59 @@ function parsePurchaseInvoiceLineReference(
return id.length > 0 ? id : null;
}
-/**
- * Convert base-currency costing lines to the invoice's transaction currency:
- * divide each amount by `exchangeRate` (base = transaction × rate), round to
- * 2dp, then book the post-rounding residue into the largest-|amount| line so
- * the lines sum exactly to the invoice's transaction-currency total. Negative
- * amounts (credit variance lines) are preserved. `exchangeRate === 1` is a
- * pass-through (base-currency bills are byte-identical).
- */
+/** Convert posted base costs once, reconciling only differences explained by rounding. */
export function toTransactionCurrencyLines(
lines: CostingLine[],
- exchangeRate: number
+ args: { exchangeRate: number; documentTotal: number; decimalPlaces: number }
): CostingLine[] {
- if (exchangeRate === 1 || lines.length === 0) {
- return lines.map((line) => ({ ...line }));
+ const { exchangeRate, documentTotal, decimalPlaces } = args;
+ if (
+ !Number.isInteger(decimalPlaces) ||
+ decimalPlaces < 0 ||
+ decimalPlaces > SCALE
+ )
+ throw new Error("Unsupported document decimal scale");
+ toDocumentAmount(documentTotal, exchangeRate, decimalPlaces);
+ if (round(documentTotal, decimalPlaces) !== documentTotal)
+ throw new Error("Bill document total exceeds currency precision");
+ const unroundedTotal = lines.reduce((sum, line) => {
+ if (!Number.isFinite(line.amount))
+ throw new Error("Costing line amount must be finite");
+ return sum + line.amount * exchangeRate;
+ }, 0);
+ // Each posted source is stored at SCALE; the authoritative document
+ // is rounded once at its own boundary. This envelope cannot conceal a cost gap.
+ const envelope =
+ lines.length * (0.5 / 10 ** SCALE) * exchangeRate +
+ 0.5 * 10 ** -decimalPlaces;
+ if (
+ Math.abs(unroundedTotal - documentTotal) >
+ envelope + Number.EPSILON * Math.max(1, Math.abs(documentTotal)) * 8
+ ) {
+ throw new Error(
+ "Posted bill costing does not reconcile to its document total"
+ );
}
-
const converted = lines.map((line) => ({
...line,
- amount: roundCurrency(line.amount / exchangeRate)
+ amount: toDocumentAmount(line.amount, exchangeRate, decimalPlaces)
}));
-
- const baseTotalCents = lines.reduce(
- (sum, line) => sum + Math.round(line.amount * 100),
- 0
- );
- const targetCents = Math.round(baseTotalCents / exchangeRate);
- const convertedCents = converted.reduce(
- (sum, line) => sum + Math.round(line.amount * 100),
- 0
+ const residual = round(
+ documentTotal - converted.reduce((sum, line) => sum + line.amount, 0),
+ decimalPlaces
);
- const residueCents = targetCents - convertedCents;
-
- if (residueCents !== 0) {
- let largestIndex = 0;
- let largestMagnitude = -1;
- for (let i = 0; i < converted.length; i++) {
- const magnitude = Math.abs(converted[i]!.amount);
- if (magnitude > largestMagnitude) {
- largestMagnitude = magnitude;
- largestIndex = i;
- }
+ if (residual !== 0) {
+ if (!converted.length)
+ throw new Error("Bill has a document total but no costing lines");
+ let largest = 0;
+ for (let i = 1; i < converted.length; i++) {
+ if (Math.abs(lines[i]!.amount) > Math.abs(lines[largest]!.amount))
+ largest = i;
}
- const target = converted[largestIndex]!;
- target.amount = roundCurrency(target.amount + residueCents / 100);
+ converted[largest]!.amount = round(
+ converted[largest]!.amount + residual,
+ decimalPlaces
+ );
}
-
return converted;
}
diff --git a/packages/ee/src/accounting/core/models.ts b/packages/ee/src/accounting/core/models.ts
index eb7fafcfb5..ee89e6d8a3 100644
--- a/packages/ee/src/accounting/core/models.ts
+++ b/packages/ee/src/accounting/core/models.ts
@@ -966,6 +966,9 @@ export const SalesInvoiceLineSchema = z.object({
// not every provider selects it; push this to any payload that declares a
// currency code, since unitPrice above is base.
convertedUnitPrice: withNullable(z.number()).optional(),
+ shippingCost: z.number().default(0),
+ addOnCost: z.number().default(0),
+ nonTaxableAddOnCost: z.number().default(0),
taxPercent: z.number(),
lineAmount: z.number()
});
@@ -987,8 +990,15 @@ export const SalesInvoiceSchema = z.object({
"Credit Note Issued",
"Return"
]),
- currencyCode: z.string(),
+ currencyCode: z.string().min(1),
+ baseCurrencyCode: z.string().min(1),
+ baseCurrencyDecimalPlaces: z.number().int().nonnegative(),
+ currencyDecimalPlaces: z.number().int().nonnegative(),
+ headerShippingCost: z.number(),
+ /** Original posted shipping account; null before posting or when no shipping. */
+ shippingRevenueAccountId: z.string().nullable(),
exchangeRate: z.number(),
+ postingDate: z.string().nullish(),
dateIssued: withNullable(z.string()),
dateDue: withNullable(z.string()),
datePaid: withNullable(z.string()),
diff --git a/packages/ee/src/accounting/core/payment-application.test.ts b/packages/ee/src/accounting/core/payment-application.test.ts
new file mode 100644
index 0000000000..46ef5c6d39
--- /dev/null
+++ b/packages/ee/src/accounting/core/payment-application.test.ts
@@ -0,0 +1,227 @@
+import { describe, expect, it } from "vitest";
+import {
+ type NormalizedPayment,
+ upsertLocalPaymentDraft
+} from "./payment-application";
+
+function fixture(
+ options: {
+ family?: "ar" | "ap";
+ rate?: number;
+ sourceRate?: number | null;
+ sourceAmount?: number;
+ currency?: string;
+ baseCurrency?: string;
+ missing?: boolean;
+ mixedParty?: boolean;
+ unmapped?: boolean;
+ foreignCurrencyOnly?: boolean;
+ ambiguous?: boolean;
+ balance?: number;
+ } = {}
+) {
+ const family = options.family ?? "ar";
+ const records: Array<{ table: string; value: any }> = [];
+ const reads: Array<{ table: string; filters: unknown[] }> = [];
+ const invoice = {
+ id: "inv-1",
+ companyId: "company-1",
+ customerId: "party-1",
+ supplierId: "party-1",
+ partyId: "party-1",
+ currencyCode: "EUR",
+ exchangeRate: options.rate ?? 1.25,
+ totalAmount: 1000,
+ balance: options.balance ?? 1000
+ };
+ const tables: Record<string, any[]> = {
+ company: [
+ {
+ baseCurrencyCode: options.baseCurrency ?? "USD",
+ companyGroupId: "group-1"
+ }
+ ],
+ currency: [{ decimalPlaces: 2 }],
+ externalIntegrationMapping: options.unmapped
+ ? []
+ : [
+ { entityId: "inv-1", externalId: "remote-1" },
+ ...(options.ambiguous
+ ? [{ entityId: "inv-2", externalId: "remote-1" }]
+ : []),
+ ...(options.mixedParty
+ ? [{ entityId: "inv-2", externalId: "remote-2" }]
+ : [])
+ ],
+ salesInvoices: options.missing
+ ? []
+ : [
+ invoice,
+ ...(options.mixedParty
+ ? [
+ {
+ ...invoice,
+ id: "inv-2",
+ customerId: "other",
+ partyId: "other"
+ }
+ ]
+ : [])
+ ],
+ purchaseInvoices: options.missing ? [] : [invoice]
+ };
+ const builder = (table: string, write = false) => {
+ const filters: unknown[] = [];
+ let value: unknown;
+ const b: any = {
+ select: () => b,
+ selectAll: () => {
+ tables.externalIntegrationMapping = [];
+ return b;
+ },
+ where: (...args: unknown[]) => {
+ filters.push(args);
+ return b;
+ },
+ innerJoin: () => b,
+ values: (v: unknown) => {
+ value = v;
+ return b;
+ },
+ set: (v: unknown) => {
+ value = v;
+ return b;
+ },
+ returning: () => b,
+ onConflict: () => b,
+ execute: async () => {
+ if (write) records.push({ table, value });
+ else reads.push({ table, filters });
+ return tables[table] ?? [];
+ },
+ executeTakeFirst: async () => {
+ reads.push({ table, filters });
+ if (table === "currency" && options.foreignCurrencyOnly)
+ return filters.some(
+ (filter: any) =>
+ filter[0] === "companyGroupId" && filter[2] === "group-1"
+ )
+ ? undefined
+ : { decimalPlaces: 3 };
+ return tables[table]?.[0];
+ },
+ executeTakeFirstOrThrow: async () => {
+ records.push({ table, value });
+ return { id: "payment-1" };
+ }
+ };
+ return b;
+ };
+ const tx = {
+ selectFrom: (t: string) => builder(t),
+ insertInto: (t: string) => builder(t, true),
+ deleteFrom: (t: string) => builder(t, true),
+ updateTable: (t: string) => builder(t, true)
+ } as never;
+ const normalized: NormalizedPayment = {
+ family,
+ documentRemoteId: "remote-1",
+ paymentRemoteId: "pay-remote",
+ amount: options.sourceAmount ?? 110,
+ currencyCode: options.currency ?? "EUR",
+ exchangeRate: options.sourceRate === undefined ? 1.1 : options.sourceRate,
+ paidDate: "2026-09-07",
+ reference: "remote",
+ status: "settled",
+ ...(options.mixedParty
+ ? {
+ linkedDocuments: [
+ { remoteId: "remote-1", amount: 55 },
+ { remoteId: "remote-2", amount: 55 }
+ ]
+ }
+ : {})
+ };
+ const run = () =>
+ upsertLocalPaymentDraft(tx, {
+ providerId: "qbo",
+ companyId: "company-1",
+ actorId: "actor",
+ bankAccount: "bank",
+ paymentMappingId: "remote-1:pay-remote",
+ getNextReadableId: async () => "PAY-1",
+ normalized
+ });
+ return { records, reads, run };
+}
+
+describe("inbound payment draft currency boundaries", () => {
+ it.each([
+ "ar",
+ "ap"
+ ] as const)("stores exact cash principal and target carrying amount for %s", async (family) => {
+ const f = fixture({ family });
+ await f.run();
+ expect(f.records.find((r) => r.table === "payment")?.value).toMatchObject({
+ totalAmount: 110,
+ exchangeRate: 1.1,
+ currencyCode: "EUR"
+ });
+ expect(
+ f.records.find(
+ (r) => r.table === "invoiceSettlement" && Array.isArray(r.value)
+ )?.value[0]
+ ).toMatchObject({
+ sourceAmount: 110,
+ sourcePaymentId: null,
+ appliedAmount: 88,
+ sourceExchangeRate: 1.1,
+ targetExchangeRate: 1.25,
+ fxGainLossAmount: family === "ar" ? 12 : -12
+ });
+ expect(
+ f.reads.find(
+ (r) =>
+ r.table === (family === "ar" ? "salesInvoices" : "purchaseInvoices")
+ )?.filters
+ ).toContainEqual(["companyId", "=", "company-1"]);
+ });
+ it("keeps document principal beyond a tiny base carrying amount", async () => {
+ const f = fixture({ sourceAmount: 160.01, rate: 16000, sourceRate: 16000 });
+ await f.run();
+ expect(
+ f.records.find(
+ (r) => r.table === "invoiceSettlement" && Array.isArray(r.value)
+ )?.value[0]
+ ).toMatchObject({ sourceAmount: 160.01, appliedAmount: 0.01 });
+ });
+ it.each([
+ { missing: true },
+ { mixedParty: true },
+ { currency: "GBP" },
+ { rate: 0 },
+ { rate: NaN },
+ { sourceRate: null },
+ { sourceRate: 0 },
+ { balance: 0 },
+ { ambiguous: true },
+ { foreignCurrencyOnly: true }
+ ])("rejects invalid authoritative snapshots without draft mutations: %j", async (options) => {
+ const f = fixture(options);
+ await expect(f.run()).rejects.toThrow();
+ expect(f.records).toEqual([]);
+ });
+ it("resolves omitted rates only for an authoritative base-currency document", async () => {
+ const f = fixture({ baseCurrency: "EUR", rate: 1, sourceRate: null });
+ await f.run();
+ expect(f.records.find((r) => r.table === "payment")?.value).toMatchObject({
+ exchangeRate: 1,
+ totalAmount: 110
+ });
+ });
+ it("retains ownership skip only for genuinely unmapped documents", async () => {
+ const f = fixture({ unmapped: true });
+ await expect(f.run()).rejects.toThrow(/mapped/);
+ expect(f.records).toEqual([]);
+ });
+});
diff --git a/packages/ee/src/accounting/core/payment-application.ts b/packages/ee/src/accounting/core/payment-application.ts
index 15c3c37484..c51efb7792 100644
--- a/packages/ee/src/accounting/core/payment-application.ts
+++ b/packages/ee/src/accounting/core/payment-application.ts
@@ -1,4 +1,12 @@
import type { KyselyTx } from "@carbon/database/client";
+import {
+ assertExchangeRate,
+ calculateSettlementFx,
+ round,
+ toBaseAmount,
+ toDocumentAmount
+} from "@carbon/utils";
+import { now as currentTime } from "@internationalized/date";
import { createMappingService } from "./external-mapping";
/**
@@ -31,8 +39,8 @@ export type NormalizedPayment = {
amount: number;
/** Payment currency (falls back to the document currency when absent). */
currencyCode: string | null;
- /** Payment → base exchange rate (v1 same-currency paths record 1). */
- exchangeRate: number;
+ /** Foreign per base rate; null means omitted by the provider, resolved from authoritative currencies. */
+ exchangeRate: number | null;
/** YYYY-MM-DD. */
paidDate: string;
/** Human/provider reference stored on the payment. */
@@ -50,28 +58,6 @@ export type NormalizedPayment = {
linkedDocuments?: { remoteId: string; amount: number }[];
};
-/**
- * Invoice status implied by its settled total (cents-accurate). Returns null
- * for "don't touch": a zero/negative settled total says nothing about what the
- * status should be, and a degenerate zero-total invoice is never restated.
- *
- * Kept as a shared export because the payment tests assert its boundaries. The
- * runtime pull path no longer calls it — `post-payment` owns document status
- * (the invoice/bill status is derived in the `salesInvoices`/`purchaseInvoices`
- * views from Posted-payment settlements).
- */
-export function getSettledInvoiceStatus(args: {
- invoiceTotal: number;
- settledTotal: number;
-}): "Paid" | "Partially Paid" | null {
- const totalCents = Math.round(args.invoiceTotal * 100);
- const settledCents = Math.round(args.settledTotal * 100);
-
- if (totalCents <= 0 || settledCents <= 0) return null;
- if (settledCents >= totalCents) return "Paid";
- return "Partially Paid";
-}
-
/**
* Separator in the outbound push's per-settlement `payment` mapping key
* (`<paymentId>:<targetDocumentId>` — see PaymentSyncerBase.pushToAccounting).
@@ -136,7 +122,7 @@ export async function upsertLocalPaymentDraft(
const { family, status } = normalized;
const mapping = createMappingService(tx, companyId);
const docEntityType = family === "ar" ? "invoice" : "bill";
- const now = new Date().toISOString();
+ const now = currentTime("UTC").toAbsoluteString();
// Resolve linked documents (default: the single documentRemoteId).
const linked =
@@ -144,41 +130,109 @@ export async function upsertLocalPaymentDraft(
? normalized.linkedDocuments
: [{ remoteId: normalized.documentRemoteId, amount: normalized.amount }];
- const resolved: { invoiceId: string; amount: number }[] = [];
+ const mappings = await tx
+ .selectFrom("externalIntegrationMapping")
+ .select(["entityId", "externalId"])
+ .where("integration", "=", providerId)
+ .where("entityType", "=", docEntityType)
+ .where(
+ "externalId",
+ "in",
+ linked.map((doc) => doc.remoteId)
+ )
+ .where("companyId", "=", companyId)
+ .execute();
+ const idByRemote = new Map<string, string>();
+ for (const row of mappings) {
+ if (!row.externalId || !row.entityId)
+ throw new Error("Invalid provider document mapping");
+ if (idByRemote.has(row.externalId))
+ throw new Error("Ambiguous provider document mapping");
+ idByRemote.set(row.externalId, row.entityId);
+ }
+ const ids = [...new Set(mappings.map((row) => row.entityId))];
+ const [company, invoices] = await Promise.all([
+ tx
+ .selectFrom("company")
+ .select(["baseCurrencyCode", "companyGroupId"])
+ .where("id", "=", companyId)
+ .executeTakeFirst(),
+ ids.length === 0
+ ? Promise.resolve([])
+ : family === "ar"
+ ? tx
+ .selectFrom("salesInvoices")
+ .select([
+ "id",
+ "customerId as partyId",
+ "currencyCode",
+ "exchangeRate",
+ "totalAmount",
+ "balance"
+ ])
+ .where("id", "in", ids)
+ .where("companyId", "=", companyId)
+ .execute()
+ : tx
+ .selectFrom("purchaseInvoices")
+ .select([
+ "id",
+ "supplierId as partyId",
+ "currencyCode",
+ "exchangeRate",
+ "totalAmount",
+ "balance"
+ ])
+ .where("id", "in", ids)
+ .where("companyId", "=", companyId)
+ .execute()
+ ]);
+ const invoiceById = new Map(invoices.map((invoice) => [invoice.id, invoice]));
+ const resolved: {
+ invoiceId: string;
+ amount: number;
+ exchangeRate: number;
+ totalAmount: number;
+ balance: number;
+ }[] = [];
let partyId: string | null = null;
let documentCurrency: string | null = null;
-
+ const resolvedIds = new Set<string>();
for (const doc of linked) {
- const localDocId = await mapping.getEntityId(
- providerId,
- doc.remoteId,
- docEntityType
- );
- if (!localDocId) continue; // ownership skip: drop unmapped documents
-
- if (family === "ar") {
- const invoice = await tx
- .selectFrom("salesInvoice")
- .select(["id", "customerId", "currencyCode"])
- .where("id", "=", localDocId)
- .where("companyId", "=", companyId)
- .executeTakeFirst();
- if (!invoice) continue;
- partyId ??= invoice.customerId;
- documentCurrency ??= invoice.currencyCode;
- resolved.push({ invoiceId: invoice.id, amount: doc.amount });
- } else {
- const invoice = await tx
- .selectFrom("purchaseInvoice")
- .select(["id", "supplierId", "currencyCode"])
- .where("id", "=", localDocId)
- .where("companyId", "=", companyId)
- .executeTakeFirst();
- if (!invoice) continue;
- partyId ??= invoice.supplierId;
- documentCurrency ??= invoice.currencyCode;
- resolved.push({ invoiceId: invoice.id, amount: doc.amount });
- }
+ const invoiceId = idByRemote.get(doc.remoteId);
+ if (!invoiceId) continue; // Only genuinely unmapped provider documents are ownership skips.
+ if (resolvedIds.has(invoiceId))
+ throw new Error("Duplicate provider payment document application");
+ resolvedIds.add(invoiceId);
+ const invoice = invoiceById.get(invoiceId);
+ if (!invoice?.partyId || !invoice.currencyCode)
+ throw new Error(
+ `Mapped ${docEntityType} ${invoiceId} is missing or has invalid company/party/currency metadata`
+ );
+ const rate = Number(invoice.exchangeRate);
+ assertExchangeRate(rate);
+ if (invoice.currencyCode === company?.baseCurrencyCode && rate !== 1)
+ throw new Error("Base-currency document requires identity exchange rate");
+ if (partyId && partyId !== invoice.partyId)
+ throw new Error("Payment links documents for different parties");
+ if (documentCurrency && documentCurrency !== invoice.currencyCode)
+ throw new Error("Payment links unsupported document currency pair");
+ partyId = invoice.partyId;
+ documentCurrency = invoice.currencyCode;
+ if (
+ !Number.isFinite(doc.amount) ||
+ doc.amount < 0 ||
+ !Number.isFinite(Number(invoice.totalAmount)) ||
+ !Number.isFinite(Number(invoice.balance))
+ )
+ throw new Error("Payment/document amount must be finite and nonnegative");
+ resolved.push({
+ invoiceId,
+ amount: doc.amount,
+ exchangeRate: rate,
+ totalAmount: Number(invoice.totalAmount),
+ balance: Number(invoice.balance)
+ });
}
if (resolved.length === 0) {
@@ -233,12 +287,57 @@ export async function upsertLocalPaymentDraft(
}
const paymentType = family === "ar" ? "Receipt" : "Disbursement";
- const currencyCode = normalized.currencyCode ?? documentCurrency ?? undefined;
- if (!currencyCode) {
+ const currencyCode = normalized.currencyCode ?? documentCurrency;
+ if (
+ !company?.baseCurrencyCode ||
+ !company.companyGroupId ||
+ !currencyCode ||
+ currencyCode !== documentCurrency
+ )
+ throw new Error("Unsupported payment/document currency pair");
+ const exchangeRate =
+ normalized.exchangeRate ??
+ (currencyCode === company.baseCurrencyCode ? 1 : null);
+ if (exchangeRate === null)
+ throw new Error("Foreign-currency payment exchange rate is required");
+ assertExchangeRate(exchangeRate);
+ if (currencyCode === company.baseCurrencyCode && exchangeRate !== 1)
+ throw new Error("Base-currency payment requires identity exchange rate");
+ const currency = await tx
+ .selectFrom("currency")
+ .select("decimalPlaces")
+ .where("code", "=", currencyCode)
+ .where("companyGroupId", "=", company.companyGroupId)
+ .executeTakeFirst();
+ if (!currency || currency.decimalPlaces == null)
+ throw new Error("Payment currency precision is required");
+ const decimalPlaces = currency.decimalPlaces;
+ if (
+ !Number.isFinite(normalized.amount) ||
+ normalized.amount <= 0 ||
+ toDocumentAmount(normalized.amount, 1, decimalPlaces) !== normalized.amount
+ )
throw new Error(
- `Cannot record ${providerId} payment ${normalized.paymentRemoteId}: no currency on the payment or its document`
+ "Payment total must be positive in document currency precision"
);
+ let resolvedTotal = 0;
+ for (const doc of resolved) {
+ if (
+ toDocumentAmount(doc.amount, 1, decimalPlaces) !== doc.amount ||
+ doc.amount >
+ toDocumentAmount(
+ Math.min(doc.totalAmount, doc.balance),
+ doc.exchangeRate,
+ decimalPlaces
+ )
+ )
+ throw new Error(
+ "Payment principal exceeds invoice balance or document precision"
+ );
+ resolvedTotal += doc.amount;
}
+ if (round(resolvedTotal, decimalPlaces) > normalized.amount)
+ throw new Error("Linked principal exceeds payment total");
let paymentRowId: string;
if (existingPayment) {
@@ -253,7 +352,7 @@ export async function upsertLocalPaymentDraft(
paymentDate: normalized.paidDate,
postingDate: normalized.paidDate,
currencyCode,
- exchangeRate: normalized.exchangeRate,
+ exchangeRate,
totalAmount: normalized.amount,
bankAccount,
reference: normalized.reference,
@@ -281,7 +380,7 @@ export async function upsertLocalPaymentDraft(
paymentDate: normalized.paidDate,
postingDate: normalized.paidDate,
currencyCode,
- exchangeRate: normalized.exchangeRate,
+ exchangeRate,
totalAmount: normalized.amount,
bankAccount,
reference: normalized.reference,
@@ -316,11 +415,19 @@ export async function upsertLocalPaymentDraft(
...(family === "ar"
? { targetSalesInvoiceId: r.invoiceId }
: { targetPurchaseInvoiceId: r.invoiceId }),
- appliedAmount: r.amount,
+ appliedAmount: toBaseAmount(r.amount, r.exchangeRate),
+ sourceAmount: r.amount,
+ sourcePaymentId: null,
+ fxGainLossAmount: calculateSettlementFx({
+ appliedAmount: toBaseAmount(r.amount, r.exchangeRate),
+ sourceAmount: r.amount,
+ sourceExchangeRate: exchangeRate,
+ isAR: family === "ar"
+ }),
discountAmount: 0,
writeOffAmount: 0,
- sourceExchangeRate: normalized.exchangeRate,
- targetExchangeRate: 1,
+ sourceExchangeRate: exchangeRate,
+ targetExchangeRate: r.exchangeRate,
appliedDate: normalized.paidDate,
companyId,
createdBy: actorId
diff --git a/packages/ee/src/accounting/core/payment-syncer.ts b/packages/ee/src/accounting/core/payment-syncer.ts
index f145705299..bb10739e36 100644
--- a/packages/ee/src/accounting/core/payment-syncer.ts
+++ b/packages/ee/src/accounting/core/payment-syncer.ts
@@ -1,4 +1,5 @@
import type { KyselyTx } from "@carbon/database/client";
+import { round } from "@carbon/utils";
import { sql } from "kysely";
import { createMappingService } from "./external-mapping";
import { ProviderID } from "./models";
@@ -392,9 +393,8 @@ export abstract class PaymentSyncerBase<TRemote> extends BaseEntitySyncer<
/**
* Whether this provider can echo a void of a Carbon-pushed payment back out.
- * Off in v1 for every provider (Rillet has no payment-void endpoint) — a
- * voided Carbon-originated payment lands a Skipped op telling the operator to
- * void it in the provider by hand.
+ * Opt-in: Rillet deletes native invoice/bill payments; other providers keep
+ * their existing unsupported-void behavior.
*/
protected supportsPaymentVoidPush = false;
@@ -466,6 +466,10 @@ export abstract class PaymentSyncerBase<TRemote> extends BaseEntitySyncer<
);
}
+ if (payment.status === "Voided") {
+ return await this.pushVoid(entityId);
+ }
+
// Origin routing via the payment mapping. A pulled payment links its
// mapping in the pull upsert BEFORE post-payment flips it to Posted, so
// its Posted event finds a mapping here and skips — the loop guard.
@@ -475,10 +479,6 @@ export abstract class PaymentSyncerBase<TRemote> extends BaseEntitySyncer<
this.provider.id
);
- if (payment.status === "Voided") {
- return this.pushVoid(entityId, mapping);
- }
-
if (mapping?.externalId) {
// Provider-known (pulled) or already pushed — idempotent skip.
return {
@@ -522,6 +522,37 @@ export abstract class PaymentSyncerBase<TRemote> extends BaseEntitySyncer<
`Payment ${entityId} carries a discount or write-off — outbound push of adjusted payments is not supported in v1`
);
}
+ if (settlements.some((s) => s.sourcePaymentId !== null)) {
+ return skipped(
+ entityId,
+ `Payment ${entityId} uses prior credit funding — outbound credit-funded payments are not supported`
+ );
+ }
+ if (
+ settlements.some(
+ (s) =>
+ !Number.isFinite(s.sourceAmount) ||
+ s.sourceAmount <= 0 ||
+ s.fxGainLossAmount !== 0 ||
+ s.targetExchangeRate !== 1 ||
+ s.sourceAmount !== s.appliedAmount
+ )
+ ) {
+ return skipped(
+ entityId,
+ `Payment ${entityId} has unsupported FX or non-cash principal — outbound FX payment push is not supported`
+ );
+ }
+ if (
+ !Number.isFinite(payment.totalAmount) ||
+ round(settlements.reduce((sum, s) => sum + s.sourceAmount, 0)) >
+ payment.totalAmount
+ ) {
+ return skipped(
+ entityId,
+ `Payment ${entityId} settlement principal exceeds its cash total`
+ );
+ }
if (payment.exchangeRate !== 1) {
return skipped(
entityId,
@@ -571,7 +602,7 @@ export abstract class PaymentSyncerBase<TRemote> extends BaseEntitySyncer<
family,
targetDocumentId,
bankAccountId: payment.bankAccount,
- amount: settlement.appliedAmount,
+ amount: settlement.sourceAmount,
currencyCode: payment.currencyCode,
paidDate: payment.paidDate,
reference: payment.reference
@@ -619,37 +650,80 @@ export abstract class PaymentSyncerBase<TRemote> extends BaseEntitySyncer<
}
}
+ /** Provider-native delete; only adapters opting into void push implement it. */
+ protected async voidRemotePayment(_compositeId: string): Promise<void> {
+ throw new Error(
+ `Payment void push is not supported by ${this.provider.id}`
+ );
+ }
+
/**
- * A Carbon payment reaching Voided. Echo the void to the provider ONLY for a
- * payment Carbon originated and pushed (mapping stamped origin:"carbon") — a
- * pulled payment voided in the provider already reversed there, so re-pushing
- * would loop. v1 has no provider void endpoint, so this always Skips with a
- * manual-remediation message; it is the seam a provider void hook plugs into.
+ * Mapping keys are the durable authority for both single and fan-out pushes.
+ * Keep them after deletion, marking completion only after every native delete
+ * succeeds. A partial remote failure retries safely through idempotent deletes.
*/
- private pushVoid(
- entityId: string,
- mapping: { metadata: Record<string, unknown> | null } | null
- ): SyncResult {
- const carbonOrigin =
- mapping?.metadata != null && mapping.metadata.origin === "carbon";
- if (!carbonOrigin) {
+ private async pushVoid(entityId: string): Promise<SyncResult> {
+ if (!this.supportsPaymentVoidPush) {
return skipped(
entityId,
- `Voided payment ${entityId} has no Carbon-originated provider payment to reverse`
+ `Voiding a pushed payment in ${this.provider.id} is not supported`
);
}
- if (!this.supportsPaymentVoidPush) {
+ const mappings = await this.database
+ .selectFrom("externalIntegrationMapping")
+ .select(["entityId", "externalId", "metadata"])
+ .where("companyId", "=", this.companyId)
+ .where("integration", "=", this.provider.id)
+ .where("entityType", "=", "payment")
+ .where(
+ sql<string>`split_part("entityId", ${SETTLEMENT_KEY_SEPARATOR}, 1)`,
+ "=",
+ entityId
+ )
+ .execute();
+ const owned = mappings.filter(
+ (mapping): mapping is typeof mapping & { externalId: string } =>
+ typeof mapping.externalId === "string" &&
+ mapping.externalId.length > 0 &&
+ (mapping.metadata as Record<string, unknown> | null)?.origin ===
+ "carbon"
+ );
+ if (owned.length === 0) {
return skipped(
entityId,
- `Voiding a pushed payment in ${this.provider.id} is not supported in v1 — void it manually in the provider`
+ `Voided payment ${entityId} has no Carbon-originated provider payment to reverse`
);
}
- // No provider implements void push in v1; when one does, call its void
- // adapter here.
- return skipped(
- entityId,
- `Voiding a pushed payment in ${this.provider.id} is not supported in v1`
+ const pending = owned.filter(
+ (mapping) =>
+ (mapping.metadata as Record<string, unknown> | null)?.voided !== true
);
+ for (const mapping of pending) {
+ await this.voidRemotePayment(mapping.externalId);
+ }
+ if (pending.length > 0)
+ await withTriggersDisabled(this.database, async (tx) => {
+ await createMappingService(tx, this.companyId).linkBatch(
+ pending.map((mapping) => ({
+ entityType: "payment",
+ entityId: mapping.entityId,
+ integration: this.provider.id,
+ externalId: mapping.externalId,
+ options: {
+ metadata: {
+ ...(mapping.metadata as Record<string, unknown> | null),
+ voided: true
+ }
+ }
+ }))
+ );
+ });
+ return {
+ status: "success",
+ action: "deleted",
+ localId: entityId,
+ remoteId: owned[0]!.externalId
+ };
}
async pushBatchToAccounting(entityIds: string[]): Promise<BatchSyncResult> {
@@ -686,7 +760,8 @@ export abstract class PaymentSyncerBase<TRemote> extends BaseEntitySyncer<
"exchangeRate",
"paymentDate",
"postingDate",
- "reference"
+ "reference",
+ "totalAmount"
])
.where("id", "=", paymentId)
.where("companyId", "=", this.companyId)
@@ -700,6 +775,10 @@ export abstract class PaymentSyncerBase<TRemote> extends BaseEntitySyncer<
"targetSalesInvoiceId",
"targetPurchaseInvoiceId",
"appliedAmount",
+ "sourceAmount",
+ "sourcePaymentId",
+ "targetExchangeRate",
+ "fxGainLossAmount",
"discountAmount",
"writeOffAmount"
])
@@ -712,7 +791,8 @@ export abstract class PaymentSyncerBase<TRemote> extends BaseEntitySyncer<
paymentType: payment.paymentType,
bankAccount: payment.bankAccount,
currencyCode: payment.currencyCode,
- exchangeRate: Number(payment.exchangeRate ?? 1),
+ exchangeRate: Number(payment.exchangeRate),
+ totalAmount: Number(payment.totalAmount),
// Kysely's pg driver hands DATE columns back as Date objects (local
// midnight) — toPostingDateString recovers the stored calendar date
// for both Date and string values; a bare .slice crashed the push.
@@ -722,6 +802,10 @@ export abstract class PaymentSyncerBase<TRemote> extends BaseEntitySyncer<
targetSalesInvoiceId: s.targetSalesInvoiceId,
targetPurchaseInvoiceId: s.targetPurchaseInvoiceId,
appliedAmount: Number(s.appliedAmount ?? 0),
+ sourceAmount: Number(s.sourceAmount),
+ sourcePaymentId: s.sourcePaymentId,
+ targetExchangeRate: Number(s.targetExchangeRate),
+ fxGainLossAmount: Number(s.fxGainLossAmount),
discountAmount: Number(s.discountAmount ?? 0),
writeOffAmount: Number(s.writeOffAmount ?? 0)
}))
@@ -780,12 +864,17 @@ type LocalPaymentForPush = {
bankAccount: string;
currencyCode: string;
exchangeRate: number;
+ totalAmount: number;
paidDate: string;
reference: string | null;
settlements: Array<{
targetSalesInvoiceId: string | null;
targetPurchaseInvoiceId: string | null;
appliedAmount: number;
+ sourceAmount: number;
+ sourcePaymentId: string | null;
+ targetExchangeRate: number;
+ fxGainLossAmount: number;
discountAmount: number;
writeOffAmount: number;
}>;
diff --git a/packages/ee/src/accounting/core/posting.ts b/packages/ee/src/accounting/core/posting.ts
index d8b9a649fd..bf92041cd5 100644
--- a/packages/ee/src/accounting/core/posting.ts
+++ b/packages/ee/src/accounting/core/posting.ts
@@ -413,6 +413,7 @@ export function parseJournalEntrySyncEntityId(entityId: string): {
export const JOURNAL_ENTRY_SYNC_ERROR_CODES = [
"UNMAPPED_ACCOUNTS",
+ "UNMAPPED_TAX_CODES",
// A slot-configured dimension value on a journal line has no provider
// option mapping (and autoCreate did not resolve it) while the company's
// onUnmappedDimensionValue policy is "warn" — user-fixable by mapping
diff --git a/packages/ee/src/accounting/core/sales-document-components.test.ts b/packages/ee/src/accounting/core/sales-document-components.test.ts
new file mode 100644
index 0000000000..700a1bdde1
--- /dev/null
+++ b/packages/ee/src/accounting/core/sales-document-components.test.ts
@@ -0,0 +1,814 @@
+import { EPSILON, round } from "@carbon/utils";
+import { describe, expect, it } from "vitest";
+import { QboSalesInvoiceSyncer } from "../providers/quickbooks-online/entities/invoice";
+import { RilletSalesInvoiceSyncer } from "../providers/rillet/entities/invoice";
+import { SalesInvoiceSyncer } from "../providers/xero/entities/invoice";
+import { SalesInvoiceSchema } from "./models";
+import { buildSalesDocumentComponents } from "./sales-document-components";
+import { loadSalesInvoices } from "./sales-invoice-source";
+import type { Accounting } from "./types";
+
+function fixture() {
+ return {
+ id: "invoice",
+ invoiceId: "INV-1",
+ companyId: "company",
+ customerId: "customer",
+ customerExternalId: null,
+ status: "Submitted",
+ currencyCode: "EUR",
+ exchangeRate: 0.8,
+ baseCurrencyCode: "USD",
+ baseCurrencyDecimalPlaces: 2,
+ currencyDecimalPlaces: 2,
+ headerShippingCost: 5,
+ shippingRevenueAccountId: "acct-shipping",
+ dateIssued: "2026-09-07",
+ dateDue: null,
+ datePaid: null,
+ customerReference: null,
+ subtotal: 133,
+ totalTax: 13,
+ totalDiscount: 0,
+ totalAmount: 151,
+ balance: 151,
+ updatedAt: "2026-09-07T00:00:00.000Z",
+ lines: [
+ {
+ id: "line",
+ invoiceLineType: "Service",
+ itemId: "item",
+ itemCode: "SERVICE",
+ description: "Work",
+ quantity: 1,
+ unitPrice: 100,
+ convertedUnitPrice: 80,
+ shippingCost: 10,
+ addOnCost: 20,
+ nonTaxableAddOnCost: 3,
+ taxPercent: 0.1,
+ lineAmount: 100
+ }
+ ]
+ };
+}
+const build = (source: ReturnType<typeof fixture>) =>
+ buildSalesDocumentComponents(source as Accounting.SalesInvoice);
+
+describe("buildSalesDocumentComponents", () => {
+ it.each([
+ 1, 3
+ ])("keeps provider quantity × unit price equal to reconciled net for quantity %i", (quantity) => {
+ const source = fixture();
+ source.currencyCode = "JPY";
+ source.currencyDecimalPlaces = 0;
+ source.lines[0]!.quantity = quantity;
+ source.lines[0]!.unitPrice = 100 / quantity;
+ source.lines[0]!.convertedUnitPrice = 80 / quantity;
+ const document = build(source);
+ // 100 base converts to exactly 80 at rate 0.8. The JPY rounding unit is
+ // apportioned to the component with the largest fractional remainder (the
+ // non-taxable add-on, exactly 2.4), not concentrated on merchandise.
+ expect(document.components[0]?.netAmount).toBe(80);
+ for (const component of document.components) {
+ expect(
+ round(component.quantity * component.unitAmount, document.decimalPlaces)
+ ).toBe(component.netAmount);
+ }
+ expect(source.lines[0]!.convertedUnitPrice).toBe(80 / quantity);
+ });
+
+ it("exports base151 as document120.80 with net98.40 Sales, net12 Shipping and native tax10.40", () => {
+ const result = build(fixture());
+ expect(result).toMatchObject({
+ invoiceId: "invoice",
+ currencyCode: "EUR",
+ decimalPlaces: 2,
+ subtotal: 110.4,
+ totalTax: 10.4,
+ totalAmount: 120.8,
+ balance: 120.8
+ });
+ expect(
+ result.components.map(
+ ({
+ id,
+ kind,
+ netAmount,
+ taxAmount,
+ quantity,
+ taxPercent,
+ sourceLineId
+ }) => ({
+ id,
+ kind,
+ netAmount,
+ taxAmount,
+ quantity,
+ taxPercent,
+ sourceLineId
+ })
+ )
+ ).toEqual([
+ {
+ id: "line:Merchandise",
+ kind: "Merchandise",
+ netAmount: 80,
+ taxAmount: 8,
+ quantity: 1,
+ taxPercent: 0.1,
+ sourceLineId: "line"
+ },
+ {
+ id: "line:TaxableAddOn",
+ kind: "TaxableAddOn",
+ netAmount: 16,
+ taxAmount: 1.6,
+ quantity: 1,
+ taxPercent: 0.1,
+ sourceLineId: "line"
+ },
+ {
+ id: "line:NonTaxableAddOn",
+ kind: "NonTaxableAddOn",
+ netAmount: 2.4,
+ taxAmount: 0,
+ quantity: 1,
+ taxPercent: 0,
+ sourceLineId: "line"
+ },
+ {
+ id: "line:LineShipping",
+ kind: "LineShipping",
+ netAmount: 8,
+ taxAmount: 0.8,
+ quantity: 1,
+ taxPercent: 0.1,
+ sourceLineId: "line"
+ },
+ {
+ id: "invoice:HeaderShipping",
+ kind: "HeaderShipping",
+ netAmount: 4,
+ taxAmount: 0,
+ quantity: 1,
+ taxPercent: 0,
+ sourceLineId: null
+ }
+ ]);
+ expect(result.components[0]).toMatchObject({
+ itemId: "item",
+ itemCode: "SERVICE",
+ description: "Work",
+ unitAmount: 80
+ });
+ expect(
+ result.components.find((line) => line.kind === "HeaderShipping")?.itemId
+ ).toBeNull();
+ });
+
+ it("ignores comments and retains positive add-ons when merchandise quantity is zero", () => {
+ const source = fixture();
+ source.headerShippingCost = 0;
+ source.subtotal = 20;
+ source.totalTax = 2;
+ source.totalAmount = 22;
+ source.balance = 22;
+ source.lines[0] = {
+ ...source.lines[0]!,
+ quantity: 0,
+ shippingCost: 0,
+ nonTaxableAddOnCost: 0
+ };
+ source.lines.push({
+ ...source.lines[0]!,
+ id: "comment",
+ invoiceLineType: "Comment",
+ quantity: 100,
+ unitPrice: 100
+ });
+ const result = build(source);
+ expect(result.components).toHaveLength(1);
+ expect(result.components[0]).toMatchObject({
+ kind: "TaxableAddOn",
+ netAmount: 16,
+ taxAmount: 1.6,
+ quantity: 1,
+ itemId: "item"
+ });
+ expect(result.totalAmount).toBe(17.6);
+ });
+
+ it("exports a zero-weight header charge once with its invoice identity", () => {
+ const source = fixture();
+ source.headerShippingCost = 1;
+ source.subtotal = 0;
+ source.totalTax = 0;
+ source.totalAmount = 1;
+ source.balance = 1;
+ source.lines = ["c", "a", "b"].map((id) => ({
+ ...source.lines[0]!,
+ id,
+ quantity: 0,
+ shippingCost: 0,
+ addOnCost: 0,
+ nonTaxableAddOnCost: 0
+ }));
+ const result = build(source);
+ expect(result.components).toEqual([
+ expect.objectContaining({
+ id: "invoice:HeaderShipping",
+ kind: "HeaderShipping",
+ netAmount: 0.8,
+ taxAmount: 0
+ })
+ ]);
+ expect(result.totalAmount).toBe(0.8);
+ });
+
+ it.each([
+ 0, 3
+ ])("honors %i-decimal document amounts and reconciles deterministic fractional residuals", (decimalPlaces) => {
+ const source = fixture();
+ source.currencyDecimalPlaces = decimalPlaces;
+ source.currencyCode = decimalPlaces === 0 ? "JPY" : "BHD";
+ source.headerShippingCost = 0;
+ source.subtotal = 1;
+ source.totalTax = 0;
+ source.totalAmount = 1;
+ source.balance = 0.5;
+ source.lines = ["b", "c", "a"].map((id) => ({
+ ...source.lines[0]!,
+ id,
+ unitPrice: 1 / 3,
+ convertedUnitPrice: 0.8 / 3,
+ shippingCost: 0,
+ addOnCost: 0,
+ nonTaxableAddOnCost: 0,
+ taxPercent: 0
+ }));
+ const result = build(source);
+ expect(result.totalAmount).toBe(decimalPlaces === 0 ? 1 : 0.8);
+ expect(result.balance).toBe(decimalPlaces === 0 ? 0 : 0.4);
+ expect(
+ result.components.reduce((sum, line) => sum + line.netAmount, 0)
+ ).toBeCloseTo(result.subtotal, decimalPlaces);
+ const reversed = build({ ...source, lines: [...source.lines].reverse() });
+ expect(
+ Object.fromEntries(
+ result.components.map((line) => [line.id, line.netAmount])
+ )
+ ).toEqual(
+ Object.fromEntries(
+ reversed.components.map((line) => [line.id, line.netAmount])
+ )
+ );
+ });
+
+ it("preserves merchandise quantity and the precise stored document unit mirror", () => {
+ const source = fixture();
+ source.headerShippingCost = 0;
+ source.subtotal = 59.997;
+ source.totalTax = 0;
+ source.totalAmount = 59.997;
+ source.balance = 59.997;
+ source.lines[0] = {
+ ...source.lines[0]!,
+ quantity: 3,
+ unitPrice: 19.999,
+ convertedUnitPrice: 15.9992,
+ shippingCost: 0,
+ addOnCost: 0,
+ nonTaxableAddOnCost: 0,
+ taxPercent: 0
+ };
+ expect(build(source).components[0]).toMatchObject({
+ quantity: 3,
+ unitAmount: 15.9992,
+ netAmount: 48
+ });
+ });
+
+ it("rejects a document mirror that contradicts the stored FX snapshot", () => {
+ const source = fixture();
+ source.lines[0]!.convertedUnitPrice = 100;
+ expect(() => build(source)).toThrow(/mirror|exchange/i);
+ });
+
+ it("rejects an otherwise scale-valid mirror when a large quantity makes it contradict document net", () => {
+ const source = fixture();
+ source.headerShippingCost = 0;
+ source.subtotal = 1;
+ source.totalTax = 0;
+ source.totalAmount = 1;
+ source.balance = 1;
+ source.lines[0] = {
+ ...source.lines[0]!,
+ quantity: 100000,
+ unitPrice: 0.00001,
+ convertedUnitPrice: 0.00001,
+ shippingCost: 0,
+ addOnCost: 0,
+ nonTaxableAddOnCost: 0,
+ taxPercent: 0
+ };
+ // Stored base × rate implies EUR0.80, but the rounded mirror extends to EUR1.
+ expect(() => build(source)).toThrow(/unit price.*reconcile/i);
+ });
+
+ it.each([
+ "subtotal",
+ "totalTax",
+ "totalAmount"
+ ] as const)("does not conceal an economic mismatch in authoritative %s", (field) => {
+ const source = fixture();
+ source[field] += 1;
+ expect(() => build(source)).toThrow(/reconcil|total|tax|subtotal/i);
+ });
+
+ it.each([
+ Number.NaN,
+ 0,
+ -1,
+ Number.POSITIVE_INFINITY
+ ])("rejects invalid foreign-per-base rate %s", (rate) => {
+ const source = fixture();
+ source.exchangeRate = rate;
+ expect(() => build(source)).toThrow(/rate|finite/i);
+ });
+
+ it("requires authoritative currency precision and an identity rate for the base currency", () => {
+ const source = fixture();
+ expect(() =>
+ build({ ...source, currencyDecimalPlaces: Number.NaN })
+ ).toThrow(/precision|decimal/i);
+ expect(() => build({ ...source, currencyDecimalPlaces: -1 })).toThrow(
+ /precision|decimal/i
+ );
+ expect(() => build({ ...source, baseCurrencyCode: "" })).toThrow(
+ /currency/i
+ );
+ expect(() => build({ ...source, currencyCode: "USD" })).toThrow(
+ /identity|rate/i
+ );
+ });
+
+ it("omits zero components and rejects header shipping without a postable source line", () => {
+ const source = fixture();
+ source.headerShippingCost = 0;
+ source.subtotal = 0;
+ source.totalTax = 0;
+ source.totalAmount = 0;
+ source.balance = 0;
+ source.lines = [];
+ expect(build(source).components).toEqual([]);
+ source.headerShippingCost = 5;
+ source.totalAmount = 5;
+ source.balance = 5;
+ expect(() => build(source)).toThrow(/shipping.*line/i);
+ });
+});
+
+describe("normalized sales invoice currency/component contract", () => {
+ it("retains authoritative currency metadata and charge columns through parsing", () => {
+ const parsed = SalesInvoiceSchema.parse(fixture());
+ expect(parsed).toMatchObject({
+ baseCurrencyCode: "USD",
+ baseCurrencyDecimalPlaces: 2,
+ currencyDecimalPlaces: 2,
+ headerShippingCost: 5
+ });
+ expect(parsed.lines[0]).toMatchObject({
+ shippingCost: 10,
+ addOnCost: 20,
+ nonTaxableAddOnCost: 3,
+ convertedUnitPrice: 80
+ });
+ });
+ it("defaults old normalized line charges to zero but rejects absent currency precision", () => {
+ const source = fixture();
+ const {
+ shippingCost: _shipping,
+ addOnCost: _addOn,
+ nonTaxableAddOnCost: _nonTaxable,
+ ...line
+ } = source.lines[0]!;
+ expect(
+ SalesInvoiceSchema.parse({ ...source, lines: [line] }).lines[0]
+ ).toMatchObject({ shippingCost: 0, addOnCost: 0, nonTaxableAddOnCost: 0 });
+ const { currencyDecimalPlaces: _precision, ...withoutPrecision } = source;
+ expect(SalesInvoiceSchema.safeParse(withoutPrecision).success).toBe(false);
+ });
+});
+
+function sourceDatabase(
+ missingCurrency = false,
+ postingRows = [
+ {
+ documentId: "invoice",
+ accountId: "posted-shipping",
+ description: "Shipping Revenue",
+ amount: 15,
+ accountClass: "Revenue",
+ isGroup: false
+ }
+ ],
+ invoiceIds = ["invoice"]
+) {
+ const source = fixture();
+ const headerValues: Record<string, unknown> = Object.fromEntries(
+ Object.entries(source).map(([key, value]) => [`salesInvoice.${key}`, value])
+ );
+ Object.assign(headerValues, {
+ "salesInvoice.subtotal": 999,
+ "salesInvoice.totalTax": 999,
+ "salesInvoice.totalAmount": 999,
+ "salesInvoices.subtotal": source.subtotal,
+ "salesInvoices.totalTax": source.totalTax,
+ "salesInvoices.totalAmount": source.totalAmount,
+ "salesInvoices.balance": source.balance,
+ "salesInvoiceShipment.shippingCost": source.headerShippingCost,
+ "company.baseCurrencyCode": source.baseCurrencyCode,
+ "baseCurrency.decimalPlaces": source.baseCurrencyDecimalPlaces,
+ "documentCurrency.decimalPlaces": missingCurrency
+ ? null
+ : source.currencyDecimalPlaces
+ });
+ const lineValues: Record<string, unknown> = Object.fromEntries(
+ Object.entries(source.lines[0]!).map(([key, value]) => [
+ `salesInvoiceLine.${key}`,
+ value
+ ])
+ );
+ lineValues["salesInvoiceLine.invoiceId"] = source.id;
+ lineValues["item.readableIdWithRevision"] = "SERVICE";
+ const reads: Array<{
+ table: string;
+ columns: string[];
+ where: unknown[][];
+ joins: string[];
+ on: unknown[][];
+ }> = [];
+ const database = {
+ selectFrom(table: string) {
+ const read = {
+ table,
+ columns: [] as string[],
+ where: [] as unknown[][],
+ joins: [] as string[],
+ on: [] as unknown[][]
+ };
+ reads.push(read);
+ const builder: any = {
+ select(columns: string[] | string) {
+ read.columns.push(...(Array.isArray(columns) ? columns : [columns]));
+ return builder;
+ },
+ where(...args: unknown[]) {
+ read.where.push(args);
+ return builder;
+ },
+ leftJoin(name: string, ...args: unknown[]) {
+ read.joins.push(name);
+ if (typeof args[0] === "function") {
+ const join: any = {
+ onRef(...refs: unknown[]) {
+ read.on.push(refs);
+ return join;
+ },
+ on(...refs: unknown[]) {
+ read.on.push(refs);
+ return join;
+ }
+ };
+ args[0](join);
+ }
+ return builder;
+ },
+ innerJoin(name: string, ...args: unknown[]) {
+ return builder.leftJoin(name, ...args);
+ },
+ async execute() {
+ if (table === "journalLine") return postingRows;
+ const values = table === "salesInvoice" ? headerValues : lineValues;
+ return invoiceIds.map((id) =>
+ Object.fromEntries(
+ read.columns.map((column) => {
+ const [name, alias] = column.split(" as ");
+ const value =
+ name === "salesInvoice.id" ||
+ name === "salesInvoiceLine.invoiceId"
+ ? id
+ : name === "salesInvoiceLine.id"
+ ? `line-${id}`
+ : values[name!];
+ return [alias ?? name!.split(".").at(-1)!, value];
+ })
+ )
+ );
+ }
+ };
+ return builder;
+ }
+ };
+ return { database, reads };
+}
+describe.each([
+ SalesInvoiceSyncer,
+ QboSalesInvoiceSyncer,
+ RilletSalesInvoiceSyncer
+])("provider source fetch %s", (Syncer) => {
+ it("reads authoritative view totals, all charge columns and group-scoped currency metadata through the actual batch path", async () => {
+ const { database, reads } = sourceDatabase();
+ const syncer = new Syncer({
+ database: database as never,
+ companyId: "company",
+ provider: { id: "xero" } as never,
+ config: {
+ enabled: true,
+ direction: "push-to-accounting",
+ owner: "carbon"
+ },
+ entityType: "invoice"
+ });
+ const result = await (
+ syncer as unknown as {
+ fetchLocalBatch(
+ ids: string[]
+ ): Promise<Map<string, Accounting.SalesInvoice>>;
+ }
+ ).fetchLocalBatch(["invoice"]);
+ const source = result.get("invoice");
+ expect(source).toMatchObject({
+ subtotal: 133,
+ totalTax: 13,
+ totalAmount: 151,
+ balance: 151,
+ headerShippingCost: 5,
+ shippingRevenueAccountId: "posted-shipping",
+ baseCurrencyCode: "USD",
+ baseCurrencyDecimalPlaces: 2,
+ currencyDecimalPlaces: 2
+ });
+ expect(source?.lines[0]).toMatchObject({
+ shippingCost: 10,
+ addOnCost: 20,
+ nonTaxableAddOnCost: 3,
+ convertedUnitPrice: 80
+ });
+ expect(buildSalesDocumentComponents(source!)).toMatchObject({
+ subtotal: 110.4,
+ totalTax: 10.4,
+ totalAmount: 120.8
+ });
+ expect(reads).toHaveLength(3);
+ expect(reads[0]?.where).toContainEqual([
+ "salesInvoice.companyId",
+ "=",
+ "company"
+ ]);
+ expect(reads[1]?.where).toContainEqual([
+ "salesInvoiceLine.companyId",
+ "=",
+ "company"
+ ]);
+ expect(reads[0]?.on).toContainEqual([
+ "documentCurrency.companyGroupId",
+ "=",
+ "company.companyGroupId"
+ ]);
+ expect(reads[0]?.on).toContainEqual([
+ "baseCurrency.companyGroupId",
+ "=",
+ "company.companyGroupId"
+ ]);
+ });
+ it("fails source loading when authoritative currency precision is unavailable", async () => {
+ const { database } = sourceDatabase(true);
+ const syncer = new Syncer({
+ database: database as never,
+ companyId: "company",
+ provider: { id: "xero" } as never,
+ config: {
+ enabled: true,
+ direction: "push-to-accounting",
+ owner: "carbon"
+ },
+ entityType: "invoice"
+ });
+ await expect(syncer.fetchLocal("invoice")).rejects.toThrow(
+ /currency|precision/i
+ );
+ });
+});
+
+describe("canonical invoice posting source", () => {
+ it("keeps different original shipping accounts in one batch and scopes every posting read", async () => {
+ const postings = ["a", "b"].map((id) => ({
+ documentId: id,
+ accountId: `shipping-${id}`,
+ description: "Shipping Revenue",
+ amount: 15,
+ accountClass: "Revenue",
+ isGroup: false
+ }));
+ const { database, reads } = sourceDatabase(false, postings, ["a", "b"]);
+ const result = await loadSalesInvoices(database as never, {
+ companyId: "company",
+ ids: ["a", "b"]
+ });
+ expect(
+ [...result.values()].map((invoice) => invoice.shippingRevenueAccountId)
+ ).toEqual(["shipping-a", "shipping-b"]);
+ const read = reads.find((read) => read.table === "journalLine")!;
+ expect(read.where).toEqual(
+ expect.arrayContaining([
+ ["journalLine.companyId", "=", "company"],
+ ["journal.companyId", "=", "company"],
+ ["journal.sourceType", "=", "Sales Invoice"],
+ ["journalLine.documentType", "=", "Invoice"],
+ ["journal.status", "=", "Posted"],
+ ["journalLine.documentId", "in", ["a", "b"]]
+ ])
+ );
+ expect(read.on).toContainEqual([
+ "account.companyGroupId",
+ "=",
+ "company.companyGroupId"
+ ]);
+ expect(reads.some((read) => read.table === "accountDefault")).toBe(false);
+ });
+ it("refuses ambiguous original shipping accounts without choosing today's default", async () => {
+ const postings = ["a", "b"].map((id) => ({
+ documentId: "invoice",
+ accountId: `shipping-${id}`,
+ description: "Shipping Revenue",
+ amount: 15,
+ accountClass: "Revenue",
+ isGroup: false
+ }));
+ const { database } = sourceDatabase(false, postings);
+ await expect(
+ loadSalesInvoices(database as never, {
+ companyId: "company",
+ ids: ["invoice"]
+ })
+ ).rejects.toMatchObject({
+ failure: { errorCode: "UNMAPPED_ACCOUNTS", warning: true }
+ });
+ });
+ it("ignores reversal and arbitrary revenue descriptions as original shipping facts", async () => {
+ const postings = ["VOID: Shipping Revenue", "Some revenue"].map(
+ (description) => ({
+ documentId: "invoice",
+ accountId: "other",
+ description,
+ amount: 15,
+ accountClass: "Revenue",
+ isGroup: false
+ })
+ );
+ const { database } = sourceDatabase(false, postings);
+ expect(
+ (
+ await loadSalesInvoices(database as never, {
+ companyId: "company",
+ ids: ["invoice"]
+ })
+ ).get("invoice")?.shippingRevenueAccountId
+ ).toBeNull();
+ });
+});
+
+describe("document rounding residual distribution", () => {
+ function uniformLines(count: number, unitPrice: number, taxPercent: number) {
+ const lines = Array.from({ length: count }, (_, index) => ({
+ id: `l${String(index).padStart(3, "0")}`,
+ invoiceLineType: "Service",
+ itemId: "item",
+ itemCode: "SVC",
+ description: "Work",
+ quantity: 1,
+ unitPrice,
+ convertedUnitPrice: unitPrice,
+ shippingCost: 0,
+ addOnCost: 0,
+ nonTaxableAddOnCost: 0,
+ taxPercent,
+ lineAmount: unitPrice
+ }));
+ const subtotal = round(count * unitPrice);
+ const totalTax = round(subtotal * taxPercent);
+ return {
+ ...fixture(),
+ currencyCode: "USD",
+ exchangeRate: 1,
+ headerShippingCost: 0,
+ subtotal,
+ totalTax,
+ totalAmount: round(subtotal + totalTax),
+ balance: round(subtotal + totalTax),
+ lines
+ };
+ }
+
+ // Each case below concentrated its whole residual on one component before
+ // largest-remainder distribution, producing a line whose tax no percentage
+ // could reproduce. QuickBooks refuses exactly that (invoice-tax.ts), and the
+ // 30 x 0.10 case previously emitted a negative tax on positive revenue.
+ it.each([
+ [20, 1.99, 0.0825],
+ [30, 0.1, 0.0625],
+ [40, 0.07, 0.07],
+ [15, 0.5, 0.13],
+ [3, 1.2, 0.0625]
+ ])("keeps every component of %i x %d @ %d within one minor unit of its own rate", (count, unitPrice, taxPercent) => {
+ const document = build(
+ uniformLines(count, unitPrice, taxPercent) as ReturnType<typeof fixture>
+ );
+ const net = round(
+ document.components.reduce((sum, c) => sum + c.netAmount, 0),
+ document.decimalPlaces
+ );
+ const tax = round(
+ document.components.reduce((sum, c) => sum + c.taxAmount, 0),
+ document.decimalPlaces
+ );
+ expect(net).toBe(
+ round(document.totalAmount - document.totalTax, document.decimalPlaces)
+ );
+ expect(tax).toBe(document.totalTax);
+ for (const component of document.components) {
+ const implied = round(
+ component.netAmount * component.taxPercent,
+ document.decimalPlaces
+ );
+ // The exact envelope QuickBooks' `tax = net x percent` preflight uses
+ // (invoice-tax.ts), so passing here means the push is accepted.
+ expect(Math.abs(implied - component.taxAmount)).toBeLessThanOrEqual(
+ 1 / 10 ** document.decimalPlaces + EPSILON
+ );
+ // A negative tax on positive revenue is silently postable in Xero.
+ if (component.taxAmount !== 0) {
+ expect(Math.sign(component.taxAmount)).toBe(
+ Math.sign(component.netAmount)
+ );
+ }
+ expect(
+ round(component.quantity * component.unitAmount, document.decimalPlaces)
+ ).toBe(component.netAmount);
+ }
+ });
+
+ // Mixed-sign invariant guard (CodeRabbit, #1599). The distributor could place
+ // a residual unit on a component whose sign it then reversed — a negative tax
+ // against positive revenue. That is pinned directly, red-to-green, by
+ // "never reverses a part's sign" in shared/precision.test.ts. This case is the
+ // integration guard: it does NOT by itself reproduce the flip (these numbers
+ // yield a surplus, not the deficit the flip needs), it asserts the invariant
+ // holds for a credit line sitting alongside a positive one.
+ it("never emits a tax whose sign contradicts its own net", () => {
+ const source = {
+ ...fixture(),
+ currencyCode: "USD",
+ exchangeRate: 1,
+ headerShippingCost: 0,
+ lines: [{ credit: -0.4 }, { credit: -0.4 }, { credit: 0.0143 }].map(
+ (row, index) => ({
+ ...fixture().lines[0]!,
+ id: `l${index}`,
+ quantity: 1,
+ unitPrice: row.credit,
+ convertedUnitPrice: row.credit,
+ shippingCost: 0,
+ addOnCost: 0,
+ nonTaxableAddOnCost: 0,
+ taxPercent: 0.07
+ })
+ )
+ };
+ const subtotal = round(-0.4 - 0.4 + 0.0143);
+ const totalTax = round(subtotal * 0.07);
+ const document = build({
+ ...source,
+ subtotal,
+ totalTax,
+ totalAmount: round(subtotal + totalTax),
+ balance: round(subtotal + totalTax)
+ } as ReturnType<typeof fixture>);
+
+ for (const component of document.components) {
+ if (component.taxAmount !== 0 && component.netAmount !== 0) {
+ expect(Math.sign(component.taxAmount)).toBe(
+ Math.sign(component.netAmount)
+ );
+ }
+ }
+ expect(
+ round(
+ document.components.reduce((sum, c) => sum + c.taxAmount, 0),
+ document.decimalPlaces
+ )
+ ).toBe(document.totalTax);
+ });
+});
diff --git a/packages/ee/src/accounting/core/sales-document-components.ts b/packages/ee/src/accounting/core/sales-document-components.ts
new file mode 100644
index 0000000000..f68620fbeb
--- /dev/null
+++ b/packages/ee/src/accounting/core/sales-document-components.ts
@@ -0,0 +1,291 @@
+import {
+ allocateSalesHeaderShipping,
+ assertExchangeRate,
+ calculateSalesPostingAmounts,
+ distributeRoundingResidual,
+ EPSILON,
+ round,
+ SCALE,
+ toDocumentAmount
+} from "@carbon/utils";
+import type { Accounting } from "./types";
+
+export type SalesDocumentComponent = {
+ id: string;
+ sourceLineId: string | null;
+ kind:
+ | "Merchandise"
+ | "TaxableAddOn"
+ | "NonTaxableAddOn"
+ | "LineShipping"
+ | "HeaderShipping";
+ itemId: string | null;
+ itemCode: string | null;
+ description: string;
+ quantity: number;
+ unitAmount: number;
+ netAmount: number;
+ taxPercent: number;
+ taxAmount: number;
+};
+
+export type SalesDocumentComponents = {
+ invoiceId: string;
+ currencyCode: string;
+ decimalPlaces: number;
+ components: SalesDocumentComponent[];
+ subtotal: number;
+ totalTax: number;
+ totalAmount: number;
+ balance: number;
+};
+
+function finite(value: number, name: string): number {
+ if (!Number.isFinite(value)) throw new Error(`${name} must be finite`);
+ return value;
+}
+
+function precision(value: number): void {
+ if (!Number.isInteger(value) || value < 0 || value > SCALE) {
+ throw new Error("Missing or unsupported currency decimal precision");
+ }
+}
+
+export function buildSalesDocumentComponents(
+ invoice: Accounting.SalesInvoice
+): SalesDocumentComponents {
+ const source = invoice;
+ if (!source.currencyCode?.trim() || !source.baseCurrencyCode?.trim()) {
+ throw new Error("Missing invoice currency metadata");
+ }
+ precision(source.currencyDecimalPlaces);
+ precision(source.baseCurrencyDecimalPlaces);
+ const decimals = source.currencyDecimalPlaces;
+ const rate = source.exchangeRate;
+ assertExchangeRate(rate);
+ if (source.currencyCode === source.baseCurrencyCode && rate !== 1) {
+ throw new Error("Base-currency invoices require an identity exchange rate");
+ }
+ const header = finite(source.headerShippingCost, "Header shipping");
+ const lines = source.lines.filter(
+ (line) => line.invoiceLineType !== "Comment"
+ );
+ if (new Set(lines.map((line) => line.id)).size !== lines.length) {
+ throw new Error("Invoice source line IDs must be unique");
+ }
+ const headerAllocations = allocateSalesHeaderShipping(lines, header);
+ const baseAmounts = lines.map((line) =>
+ calculateSalesPostingAmounts({
+ ...line,
+ allocatedHeaderShipping: headerAllocations.get(line.id) ?? 0
+ })
+ );
+ const sourceEnvelope = (lines.length * 4 + 1) / (2 * 10 ** SCALE) + EPSILON;
+ const reconcileSource = (actual: number, expected: number, label: string) => {
+ finite(actual, label);
+ finite(expected, label);
+ if (Math.abs(actual - expected) > sourceEnvelope) {
+ throw new Error(
+ `Invoice ${label} does not reconcile with its source components`
+ );
+ }
+ };
+ reconcileSource(
+ baseAmounts.reduce(
+ (sum, value) => sum + value.salesRevenueBase + value.shippingRevenueBase,
+ 0
+ ),
+ source.subtotal + header,
+ "subtotal"
+ );
+ reconcileSource(
+ baseAmounts.reduce((sum, value) => sum + value.salesTaxBase, 0),
+ source.totalTax,
+ "tax total"
+ );
+ reconcileSource(
+ source.subtotal + header + source.totalTax,
+ source.totalAmount,
+ "gross total"
+ );
+
+ type RawComponent = {
+ component: SalesDocumentComponent;
+ baseNet: number;
+ baseTax: number;
+ };
+ const raw: RawComponent[] = [];
+ const push = (args: {
+ kind: SalesDocumentComponent["kind"];
+ line?: Accounting.SalesInvoiceLine;
+ baseNet: number;
+ taxPercent: number;
+ description: string;
+ quantity?: number;
+ }) => {
+ const { line, kind, baseNet, taxPercent } = args;
+ const baseTax = finite(baseNet * taxPercent, "Component tax");
+ if (baseNet === 0 && baseTax === 0) return;
+ const quantity = args.quantity ?? 1;
+ let unitAmount = toDocumentAmount(baseNet, rate, decimals);
+ if (kind === "Merchandise" && line) {
+ const convertedUnit = line.convertedUnitPrice;
+ const expectedUnit = finite(line.unitPrice * rate, "Document unit price");
+ if (
+ convertedUnit != null &&
+ Math.abs(
+ finite(convertedUnit, "Document price mirror") - expectedUnit
+ ) >
+ 1 / (2 * 10 ** SCALE) + EPSILON
+ ) {
+ throw new Error(
+ `Invoice line ${line.id} price mirror contradicts its exchange rate`
+ );
+ }
+ unitAmount =
+ convertedUnit ?? toDocumentAmount(line.unitPrice, rate, SCALE);
+ }
+ raw.push({
+ baseNet,
+ baseTax,
+ component: {
+ id: `${line?.id ?? source.id}:${kind}`,
+ sourceLineId: line?.id ?? null,
+ kind,
+ itemId: line?.itemId ?? null,
+ itemCode: line?.itemCode ?? null,
+ description: args.description,
+ quantity,
+ unitAmount,
+ netAmount: toDocumentAmount(baseNet, rate, decimals),
+ taxPercent,
+ taxAmount: toDocumentAmount(baseTax, rate, decimals)
+ }
+ });
+ };
+ for (const line of lines) {
+ push({
+ kind: "Merchandise",
+ line,
+ baseNet: line.quantity * line.unitPrice,
+ taxPercent: line.taxPercent,
+ quantity: line.quantity,
+ description: line.description ?? line.itemCode ?? "Invoice line"
+ });
+ push({
+ kind: "TaxableAddOn",
+ line,
+ baseNet: line.addOnCost ?? 0,
+ taxPercent: line.taxPercent,
+ description: `Add-on — ${line.description ?? line.itemCode ?? "Invoice line"}`
+ });
+ push({
+ kind: "NonTaxableAddOn",
+ line,
+ baseNet: line.nonTaxableAddOnCost ?? 0,
+ taxPercent: 0,
+ description: `Non-taxable add-on — ${line.description ?? line.itemCode ?? "Invoice line"}`
+ });
+ push({
+ kind: "LineShipping",
+ line,
+ baseNet: line.shippingCost ?? 0,
+ taxPercent: line.taxPercent,
+ description: `Shipping — ${line.description ?? line.itemCode ?? "Invoice line"}`
+ });
+ }
+ push({
+ kind: "HeaderShipping",
+ baseNet: header,
+ taxPercent: 0,
+ description: "Shipping"
+ });
+
+ const totalAmount = toDocumentAmount(source.totalAmount, rate, decimals);
+ const totalTax = toDocumentAmount(source.totalTax, rate, decimals);
+ // The rounded authoritative gross and native tax define the document net.
+ // Any one-unit net difference is allocated to an existing component below.
+ const subtotal = round(totalAmount - totalTax, decimals);
+ // Rounding each component independently leaves a residual of up to half a
+ // minor unit per component. Spread it one unit at a time (largest remainder)
+ // rather than concentrating it: a component that absorbs the whole residual
+ // stops matching its own taxPercent, and providers that re-derive
+ // `tax = net × percent` reject the document outright.
+ const reconcileDocument = (
+ key: "netAmount" | "taxAmount",
+ baseKey: "baseNet" | "baseTax",
+ target: number
+ ) => {
+ // A component with no basis on this axis must stay at zero — a zero-rated
+ // line carrying tax is itself a provider refusal. Order by component id so
+ // an exact tie resolves the same way whatever order the lines arrived in;
+ // the distributor's own tie-break is positional.
+ const participants = raw
+ .filter((row) => row[baseKey] !== 0)
+ .sort((a, b) => a.component.id.localeCompare(b.component.id));
+ if (participants.length === 0) {
+ if (round(target, decimals) !== 0) {
+ throw new Error(
+ `Invoice ${key} has no source component for its rounding residual`
+ );
+ }
+ return;
+ }
+ const allocated = distributeRoundingResidual(
+ participants.map((row) =>
+ finite(row[baseKey] * rate, `Component document ${key}`)
+ ),
+ target,
+ decimals
+ );
+ participants.forEach((row, index) => {
+ row.component[key] = allocated[index]!;
+ });
+ };
+ reconcileDocument("netAmount", "baseNet", subtotal);
+ reconcileDocument("taxAmount", "baseTax", totalTax);
+ for (const { component } of raw) {
+ // Providers recompute the extended net from quantity × unit price, so the
+ // unit price has to reproduce the reconciled net. The stored
+ // `convertedUnitPrice` mirror and the converted extension are rounded on two
+ // independent float paths and can straddle a half-unit tie, so derive rather
+ // than refuse. A unit price is a rate: it keeps storage scale, not
+ // settlement decimals.
+ if (
+ round(component.quantity * component.unitAmount, decimals) !==
+ component.netAmount
+ ) {
+ component.unitAmount = round(
+ finite(
+ component.netAmount / component.quantity,
+ "Reconciled document unit price"
+ ),
+ SCALE
+ );
+ // Deriving cannot always converge: past roughly 10^SCALE units, one step
+ // of the unit price moves the extension by more than a minor unit, so no
+ // representable price reproduces the net. That is a real contradiction
+ // between the stored quantity and the document total — refuse it.
+ if (
+ round(component.quantity * component.unitAmount, decimals) !==
+ component.netAmount
+ ) {
+ throw new Error(
+ `Invoice component ${component.id} unit price does not reconcile with its document net`
+ );
+ }
+ }
+ }
+ return {
+ invoiceId: source.id,
+ currencyCode: source.currencyCode,
+ decimalPlaces: decimals,
+ components: raw
+ .map((row) => row.component)
+ .filter((line) => line.netAmount !== 0 || line.taxAmount !== 0),
+ subtotal,
+ totalTax,
+ totalAmount,
+ balance: toDocumentAmount(source.balance, rate, decimals)
+ };
+}
diff --git a/packages/ee/src/accounting/core/sales-invoice-source.ts b/packages/ee/src/accounting/core/sales-invoice-source.ts
new file mode 100644
index 0000000000..14a07938a7
--- /dev/null
+++ b/packages/ee/src/accounting/core/sales-invoice-source.ts
@@ -0,0 +1,267 @@
+import type { Kysely, KyselyDatabase, KyselyTx } from "@carbon/database/client";
+import { datetime } from "@carbon/database/datetime";
+import { classifyAccountingPostingRole } from "@carbon/utils";
+import { JournalEntrySyncError } from "./posting";
+import type { Accounting } from "./types";
+
+/** One provider-neutral source boundary for invoice amounts and original posting facts. */
+export async function loadSalesInvoices(
+ db: Kysely<KyselyDatabase> | KyselyTx,
+ { companyId, ids }: { companyId: string; ids: string[] }
+): Promise<Map<string, Accounting.SalesInvoice>> {
+ if (ids.length === 0) return new Map();
+
+ // Fetch invoice headers
+ const invoiceRows = await db
+ .selectFrom("salesInvoice")
+ // `balance` is derived (totalAmount - posted payment applications) and
+ // lives only on the `salesInvoices` view now, not the base table.
+ .leftJoin("salesInvoices", (join) =>
+ join
+ .onRef("salesInvoices.id", "=", "salesInvoice.id")
+ .onRef("salesInvoices.companyId", "=", "salesInvoice.companyId")
+ )
+ .innerJoin("company", "company.id", "salesInvoice.companyId")
+ .leftJoin("salesInvoiceShipment", (join) =>
+ join
+ .onRef("salesInvoiceShipment.id", "=", "salesInvoice.id")
+ .onRef("salesInvoiceShipment.companyId", "=", "salesInvoice.companyId")
+ )
+ .leftJoin("currency as documentCurrency", (join) =>
+ join
+ .onRef("documentCurrency.code", "=", "salesInvoice.currencyCode")
+ .onRef("documentCurrency.companyGroupId", "=", "company.companyGroupId")
+ )
+ .leftJoin("currency as baseCurrency", (join) =>
+ join
+ .onRef("baseCurrency.code", "=", "company.baseCurrencyCode")
+ .onRef("baseCurrency.companyGroupId", "=", "company.companyGroupId")
+ )
+ .select([
+ "salesInvoice.id",
+ "salesInvoice.invoiceId",
+ "salesInvoice.companyId",
+ "salesInvoice.customerId",
+ "salesInvoice.status",
+ "salesInvoice.currencyCode",
+ "salesInvoice.exchangeRate",
+ "salesInvoice.postingDate",
+ "salesInvoice.dateIssued",
+ "salesInvoice.dateDue",
+ "salesInvoice.datePaid",
+ "salesInvoice.customerReference",
+ "salesInvoices.subtotal",
+ "salesInvoices.totalTax",
+ "salesInvoice.totalDiscount",
+ "salesInvoices.totalAmount",
+ "salesInvoices.balance",
+ "salesInvoiceShipment.shippingCost as headerShippingCost",
+ "company.baseCurrencyCode",
+ "baseCurrency.decimalPlaces as baseCurrencyDecimalPlaces",
+ "documentCurrency.decimalPlaces as currencyDecimalPlaces",
+ "salesInvoice.updatedAt"
+ ])
+ .where("salesInvoice.id", "in", ids)
+ .where("salesInvoice.companyId", "=", companyId)
+ .execute();
+
+ if (invoiceRows.length === 0) return new Map();
+
+ // Fetch invoice lines with item codes
+ const lineRows = await db
+ .selectFrom("salesInvoiceLine")
+ .leftJoin("item", (join) =>
+ join
+ .onRef("item.id", "=", "salesInvoiceLine.itemId")
+ .onRef("item.companyId", "=", "salesInvoiceLine.companyId")
+ )
+ .select([
+ "salesInvoiceLine.id",
+ "salesInvoiceLine.invoiceId",
+ "salesInvoiceLine.invoiceLineType",
+ "salesInvoiceLine.itemId",
+ "salesInvoiceLine.description",
+ "salesInvoiceLine.quantity",
+ "salesInvoiceLine.unitPrice",
+ "salesInvoiceLine.convertedUnitPrice",
+ "salesInvoiceLine.shippingCost",
+ "salesInvoiceLine.addOnCost",
+ "salesInvoiceLine.nonTaxableAddOnCost",
+ "salesInvoiceLine.taxPercent",
+ "item.readableIdWithRevision as itemReadableIdWithRevision"
+ ])
+ .where("salesInvoiceLine.companyId", "=", companyId)
+ .where(
+ "salesInvoiceLine.invoiceId",
+ "in",
+ invoiceRows.map((r) => r.id)
+ )
+ .execute();
+
+ const postingRows = await db
+ .selectFrom("journalLine")
+ .innerJoin("journal", (join) =>
+ join
+ .onRef("journal.id", "=", "journalLine.journalId")
+ .onRef("journal.companyId", "=", "journalLine.companyId")
+ )
+ .innerJoin("company", "company.id", "journalLine.companyId")
+ .leftJoin("account", (join) =>
+ join
+ .onRef("account.id", "=", "journalLine.accountId")
+ .onRef("account.companyGroupId", "=", "company.companyGroupId")
+ )
+ .select([
+ "journalLine.documentId",
+ "journalLine.accountId",
+ "journalLine.description",
+ "account.class as accountClass",
+ "account.isGroup"
+ ])
+ .where(
+ "journalLine.documentId",
+ "in",
+ invoiceRows.map((row) => row.id)
+ )
+ .where("journalLine.documentType", "=", "Invoice")
+ .where("journalLine.companyId", "=", companyId)
+ .where("journal.companyId", "=", companyId)
+ .where("journal.sourceType", "=", "Sales Invoice")
+ .where("journal.status", "=", "Posted")
+ .execute();
+ const shippingAccounts = new Map<string, Set<string>>();
+ for (const row of postingRows) {
+ if (classifyAccountingPostingRole(row.description) !== "ShippingRevenue")
+ continue;
+ if (
+ !row.documentId ||
+ !row.accountId ||
+ row.accountClass !== "Revenue" ||
+ row.isGroup
+ ) {
+ throw new JournalEntrySyncError({
+ errorCode: "UNMAPPED_ACCOUNTS",
+ warning: true,
+ message:
+ "Cannot sync invoice: original Shipping Revenue posting has no valid Revenue leaf account in the company group",
+ metadata: { invoiceId: row.documentId, accountId: row.accountId }
+ });
+ }
+ const accounts = shippingAccounts.get(row.documentId) ?? new Set<string>();
+ accounts.add(row.accountId);
+ shippingAccounts.set(row.documentId, accounts);
+ }
+
+ // Group lines by invoice ID
+ const linesByInvoiceId = new Map<string, (typeof lineRows)[number][]>();
+ for (const line of lineRows) {
+ const existing = linesByInvoiceId.get(line.invoiceId) ?? [];
+ existing.push(line);
+ linesByInvoiceId.set(line.invoiceId, existing);
+ }
+
+ // Transform to Accounting.SalesInvoice
+ const result = new Map<string, Accounting.SalesInvoice>();
+ for (const row of invoiceRows) {
+ if (
+ !row.baseCurrencyCode ||
+ !row.currencyCode ||
+ row.baseCurrencyDecimalPlaces == null ||
+ row.currencyDecimalPlaces == null
+ ) {
+ throw new Error(
+ `Invoice ${row.id} is missing authoritative currency precision metadata`
+ );
+ }
+ if (
+ row.subtotal == null ||
+ row.totalTax == null ||
+ row.totalAmount == null ||
+ row.balance == null
+ ) {
+ throw new Error(
+ `Invoice ${row.id} is missing authoritative source view totals`
+ );
+ }
+ const lines = linesByInvoiceId.get(row.id) ?? [];
+
+ const shippingIds = [...(shippingAccounts.get(row.id) ?? [])];
+ if (shippingIds.length > 1)
+ throw new JournalEntrySyncError({
+ errorCode: "UNMAPPED_ACCOUNTS",
+ warning: true,
+ message:
+ "Cannot sync invoice: original Shipping Revenue posting has multiple accounts",
+ metadata: { invoiceId: row.id, accountIds: shippingIds }
+ });
+ result.set(row.id, {
+ id: row.id,
+ invoiceId: row.invoiceId,
+ companyId: row.companyId,
+ customerId: row.customerId,
+ customerExternalId: null, // Will be resolved during mapToRemote
+ status: row.status,
+ currencyCode: row.currencyCode,
+ baseCurrencyCode: row.baseCurrencyCode,
+ baseCurrencyDecimalPlaces: Number(row.baseCurrencyDecimalPlaces),
+ currencyDecimalPlaces: Number(row.currencyDecimalPlaces),
+ shippingRevenueAccountId: shippingIds[0] ?? null,
+ headerShippingCost: Number(row.headerShippingCost ?? 0),
+ exchangeRate: Number(row.exchangeRate),
+ postingDate: row.postingDate,
+ dateIssued: row.dateIssued,
+ dateDue: row.dateDue,
+ datePaid: row.datePaid,
+ customerReference: row.customerReference,
+ subtotal: Number(row.subtotal),
+ totalTax: Number(row.totalTax),
+ totalDiscount: Number(row.totalDiscount) || 0,
+ totalAmount: Number(row.totalAmount),
+ balance: Number(row.balance),
+ lines: lines.map((line) => {
+ const quantity = Number(line.quantity) || 0;
+ const unitPrice = Number(line.unitPrice) || 0;
+ const taxPercent = Number(line.taxPercent) || 0;
+ const convertedUnitPrice =
+ line.convertedUnitPrice === null ||
+ line.convertedUnitPrice === undefined
+ ? null
+ : Number(line.convertedUnitPrice);
+ return {
+ id: line.id,
+ invoiceLineType: line.invoiceLineType,
+ itemId: line.itemId,
+ itemCode: line.itemReadableIdWithRevision,
+ description: line.description,
+ quantity,
+ unitPrice,
+ shippingCost: Number(line.shippingCost ?? 0),
+ addOnCost: Number(line.addOnCost ?? 0),
+ nonTaxableAddOnCost: Number(line.nonTaxableAddOnCost ?? 0),
+ convertedUnitPrice,
+ taxPercent,
+ lineAmount: quantity * unitPrice
+ };
+ }),
+ updatedAt: row.updatedAt ?? datetime.timestamp(),
+ raw: row
+ });
+ }
+
+ return result;
+}
+
+/** Shipping components must replay an original account, never today's default. */
+export function requirePostedShippingAccountId(
+ invoice: Accounting.SalesInvoice
+): string {
+ if (!invoice.shippingRevenueAccountId)
+ throw new JournalEntrySyncError({
+ errorCode: "UNMAPPED_ACCOUNTS",
+ warning: true,
+ message:
+ "Cannot sync invoice: original Shipping Revenue account is missing from its posted journal",
+ metadata: { invoiceId: invoice.id }
+ });
+ return invoice.shippingRevenueAccountId;
+}
diff --git a/packages/ee/src/accounting/providers/quickbooks-online/entities/__tests__/bill.test.ts b/packages/ee/src/accounting/providers/quickbooks-online/entities/__tests__/bill.test.ts
index f90e310033..bcddca38c2 100644
--- a/packages/ee/src/accounting/providers/quickbooks-online/entities/__tests__/bill.test.ts
+++ b/packages/ee/src/accounting/providers/quickbooks-online/entities/__tests__/bill.test.ts
@@ -261,6 +261,15 @@ function makeBillDb(config: {
orderBy: () => builder,
async execute() {
if (table === "journalLine") return config.journalLine;
+ if (table === "purchaseInvoiceLine")
+ return [
+ {
+ quantity: 1,
+ supplierUnitPrice: 80,
+ supplierShippingCost: 0,
+ supplierTaxAmount: 0
+ }
+ ];
if (table === "journalLineDimension") return [];
if (table === "purchaseOrderLine") return [];
if (table === "externalIntegrationMapping as m")
@@ -276,7 +285,11 @@ function makeBillDb(config: {
return [];
},
async executeTakeFirst() {
- if (table === "purchaseInvoice") return config.purchaseInvoice;
+ if (table === "purchaseInvoice")
+ return { ...config.purchaseInvoice, postingDate: "2026-09-07" };
+ if (table === "company")
+ return { baseCurrencyCode: "USD", companyGroupId: "group-1" };
+ if (table === "currency") return { decimalPlaces: 2 };
if (table === "accountDefault") return config.accountDefault;
return undefined;
}
@@ -290,12 +303,12 @@ describe("QboBillSyncer.mapToRemote (FX currency wiring)", () => {
it("pins CurrencyRef + ExchangeRate and replays transaction-currency amounts", async () => {
const syncer = new QboBillSyncer({
database: makeBillDb({
- purchaseInvoice: { currencyCode: "EUR", exchangeRate: 2 },
+ purchaseInvoice: { currencyCode: "EUR", exchangeRate: 0.8 },
journalLine: [
{
id: "jl-1",
accountId: "acc-grir",
- amount: 300,
+ amount: 100,
description: "GR/IR Clearing",
documentLineReference: null,
accountClass: "Asset"
@@ -303,7 +316,7 @@ describe("QboBillSyncer.mapToRemote (FX currency wiring)", () => {
{
id: "jl-2",
accountId: "acc-ap",
- amount: 300, // Liability natural balance → debit-signed -300
+ amount: 100, // Liability natural balance → debit-signed -100
description: "Accounts Payable",
documentLineReference: null,
accountClass: "Liability"
@@ -332,14 +345,14 @@ describe("QboBillSyncer.mapToRemote (FX currency wiring)", () => {
syncer as unknown as {
mapToRemote(local: Accounting.Bill): Promise<Qbo.Bill>;
}
- ).mapToRemote(billFixture({ currencyCode: "EUR", exchangeRate: 2 }));
+ ).mapToRemote(billFixture({ currencyCode: "EUR", exchangeRate: 0.8 }));
expect(payload.CurrencyRef).toEqual({ value: "EUR" });
- expect(payload.ExchangeRate).toBe(2);
- // Base 300 @ rate 2 → 150 EUR to the mapped GR/IR account only (AP excluded).
+ expect(payload.ExchangeRate).toBe(1.25);
+ // Base 100 @ rate 0.8 → 80 EUR to the mapped GR/IR account only (AP excluded).
expect(payload.Line).toEqual([
{
- Amount: 150,
+ Amount: 80,
Description: "GR/IR Clearing",
DetailType: "AccountBasedExpenseLineDetail",
AccountBasedExpenseLineDetail: { AccountRef: { value: "2125" } }
@@ -397,3 +410,154 @@ describe("deriveCarbonBillStatus (pull status from Balance/TotalAmt/DueDate)", (
).toBeUndefined();
});
});
+
+describe("QBO inbound bill stored currency snapshots", () => {
+ it("persists reciprocal rate before populating supplier document fields", async () => {
+ const writes: Array<{ table: string; values: any }> = [];
+ let header: any = {
+ companyId: "company-1",
+ createdBy: "user-1",
+ exchangeRate: 1
+ };
+ const builder = (table: string, writing = false) => {
+ let values: any;
+ const filters: any[] = [];
+ const b: any = {
+ select: () => b,
+ selectAll: () => b,
+ where: (...args: any[]) => {
+ filters.push(args);
+ return b;
+ },
+ set: (v: any) => {
+ values = v;
+ return b;
+ },
+ values: (v: any) => {
+ values = v;
+ return b;
+ },
+ execute: async () => {
+ if (writing) {
+ writes.push({ table, values });
+ if (table === "purchaseInvoice") header = { ...header, ...values };
+ }
+ return [];
+ },
+ executeTakeFirst: async () =>
+ table === "company"
+ ? { baseCurrencyCode: "USD", companyGroupId: "group-1" }
+ : table === "externalIntegrationMapping"
+ ? {
+ entityId:
+ filters.find((f) => f[0] === "externalId")?.[2] ===
+ "vendor-99"
+ ? "sup-1"
+ : "acc-grir"
+ }
+ : header,
+ executeTakeFirstOrThrow: async () => header
+ };
+ return b;
+ };
+ const db = {
+ selectFrom: (t: string) => builder(t),
+ updateTable: (t: string) => builder(t, true),
+ insertInto: (t: string) => builder(t, true),
+ deleteFrom: (t: string) => builder(t, true)
+ } as never;
+ const syncer = new QboBillSyncer({
+ database: db,
+ companyId: "company-1",
+ provider: { id: "quickbooks" } as never,
+ config: { enabled: true, direction: "two-way", owner: "accounting" },
+ entityType: "bill"
+ }) as any;
+ syncer.getLocalId = async () => "pi_1";
+ const local = await syncer.mapToLocal({
+ Id: "qb-1",
+ VendorRef: { value: "vendor-99" },
+ CurrencyRef: { value: "EUR" },
+ ExchangeRate: 1.25,
+ TotalAmt: 80,
+ Balance: 80,
+ TxnDate: "2026-09-07",
+ Line: [
+ {
+ Amount: 80,
+ DetailType: "AccountBasedExpenseLineDetail",
+ AccountBasedExpenseLineDetail: { AccountRef: { value: "2125" } }
+ }
+ ]
+ });
+ expect(local).toMatchObject({
+ currencyCode: "EUR",
+ exchangeRate: 0.8,
+ totalAmount: 100
+ });
+ await syncer.upsertLocal(db, local, "qb-1");
+ expect(
+ writes.find((w) => w.table === "purchaseInvoice")?.values
+ ).toMatchObject({ currencyCode: "EUR", exchangeRate: 0.8 });
+ const rows = writes.find(
+ (w) => w.table === "purchaseInvoiceLine" && w.values
+ )?.values;
+ expect(rows).toEqual([
+ expect.objectContaining({
+ supplierUnitPrice: 80,
+ supplierTaxAmount: 0,
+ exchangeRate: 0.8
+ })
+ ]);
+ expect(rows[0]).not.toHaveProperty("unitPrice");
+ expect(rows[0]).not.toHaveProperty("totalAmount");
+ expect(rows[0]).not.toHaveProperty("supplierExtendedPrice");
+ });
+});
+
+it("handles a malformed QBO account detail without AccountRef without losing the remaining bill", async () => {
+ const database = {
+ selectFrom: () => {
+ const q: any = {
+ select: () => q,
+ where: () => q,
+ execute: async () => [],
+ executeTakeFirst: async () => ({ baseCurrencyCode: "USD" })
+ };
+ return q;
+ }
+ };
+ const syncer = new QboBillSyncer({
+ database: database as never,
+ companyId: "company-1",
+ provider: { id: "quickbooks" } as never,
+ config: { enabled: true, direction: "two-way", owner: "accounting" },
+ entityType: "bill"
+ }) as any;
+ await expect(
+ syncer.mapToLocal({
+ Id: "remote",
+ VendorRef: { value: "vendor" },
+ CurrencyRef: { value: "USD" },
+ TotalAmt: 10,
+ Balance: 10,
+ Line: [
+ {
+ Id: "bad",
+ Amount: 0,
+ DetailType: "AccountBasedExpenseLineDetail",
+ AccountBasedExpenseLineDetail: {}
+ },
+ {
+ Id: "good",
+ Amount: 10,
+ DetailType: "AccountBasedExpenseLineDetail",
+ AccountBasedExpenseLineDetail: { AccountRef: { value: "cost" } }
+ }
+ ]
+ })
+ ).resolves.toMatchObject({
+ totalAmount: 10,
+ lines: expect.arrayContaining([expect.objectContaining({ id: "good" })])
+ });
+});
diff --git a/packages/ee/src/accounting/providers/quickbooks-online/entities/__tests__/invoice-tax.test.ts b/packages/ee/src/accounting/providers/quickbooks-online/entities/__tests__/invoice-tax.test.ts
new file mode 100644
index 0000000000..a7a169da9c
--- /dev/null
+++ b/packages/ee/src/accounting/providers/quickbooks-online/entities/__tests__/invoice-tax.test.ts
@@ -0,0 +1,364 @@
+import { describe, expect, it, vi } from "vitest";
+import type { SalesDocumentComponents } from "../../../../core/sales-document-components";
+import type { Qbo } from "../../models";
+import type { QboProvider } from "../../provider";
+import {
+ loadQboInvoiceTaxCatalog,
+ type QboInvoiceTaxCatalog,
+ resolveQboInvoiceTax
+} from "../invoice-tax";
+
+function document(): SalesDocumentComponents {
+ return {
+ invoiceId: "invoice",
+ currencyCode: "EUR",
+ decimalPlaces: 2,
+ subtotal: 110.4,
+ totalTax: 10.4,
+ totalAmount: 120.8,
+ balance: 120.8,
+ components: [
+ {
+ id: "merch",
+ sourceLineId: "line",
+ kind: "Merchandise",
+ itemId: "item",
+ itemCode: "PART",
+ description: "Part",
+ quantity: 1,
+ unitAmount: 80,
+ netAmount: 80,
+ taxPercent: 0.1,
+ taxAmount: 8
+ },
+ {
+ id: "addon",
+ sourceLineId: "line",
+ kind: "TaxableAddOn",
+ itemId: "item",
+ itemCode: "PART",
+ description: "Addon",
+ quantity: 1,
+ unitAmount: 16,
+ netAmount: 16,
+ taxPercent: 0.1,
+ taxAmount: 1.6
+ },
+ {
+ id: "shipping",
+ sourceLineId: "line",
+ kind: "LineShipping",
+ itemId: "item",
+ itemCode: "PART",
+ description: "Shipping",
+ quantity: 1,
+ unitAmount: 8,
+ netAmount: 8,
+ taxPercent: 0.1,
+ taxAmount: 0.8
+ },
+ {
+ id: "nontax",
+ sourceLineId: "line",
+ kind: "NonTaxableAddOn",
+ itemId: "item",
+ itemCode: "PART",
+ description: "Non-tax addon",
+ quantity: 1,
+ unitAmount: 2.4,
+ netAmount: 2.4,
+ taxPercent: 0,
+ taxAmount: 0
+ },
+ {
+ id: "header",
+ sourceLineId: null,
+ kind: "HeaderShipping",
+ itemId: null,
+ itemCode: null,
+ description: "Shipping",
+ quantity: 1,
+ unitAmount: 4,
+ netAmount: 4,
+ taxPercent: 0,
+ taxAmount: 0
+ }
+ ]
+ };
+}
+function catalog(country = "US"): {
+ country: string;
+ taxCodes: Qbo.TaxCode[];
+ taxRates: Qbo.TaxRate[];
+} {
+ return {
+ country,
+ taxCodes: [
+ {
+ Id: "ten",
+ Name: "Ten percent",
+ Active: true,
+ SalesTaxRateList: {
+ TaxRateDetail: [
+ {
+ TaxRateRef: { value: "rate-ten" },
+ TaxTypeApplicable: "TaxOnAmount",
+ TaxOrder: 0
+ }
+ ]
+ }
+ },
+ ...(country === "US"
+ ? [
+ { Id: "TAX", Active: true, Taxable: true },
+ { Id: "NON", Active: true, Taxable: false }
+ ]
+ : [
+ {
+ Id: "zero",
+ Name: "Zero",
+ Active: true,
+ SalesTaxRateList: {
+ TaxRateDetail: [{ TaxRateRef: { value: "rate-zero" } }]
+ }
+ }
+ ])
+ ],
+ taxRates: [
+ { Id: "rate-ten", RateValue: 10, Active: true },
+ { Id: "rate-zero", RateValue: 0, Active: true }
+ ]
+ };
+}
+function expectWarning(
+ source: SalesDocumentComponents,
+ remote: QboInvoiceTaxCatalog,
+ reason?: RegExp
+) {
+ let error: unknown;
+ try {
+ resolveQboInvoiceTax({ document: source, catalog: remote });
+ } catch (caught) {
+ error = caught;
+ }
+ expect(error, "Expected tax preflight to fail").toBeDefined();
+ expect(error).toMatchObject({
+ name: "JournalEntrySyncError",
+ failure: {
+ errorCode: "UNMAPPED_TAX_CODES",
+ warning: true,
+ metadata: {
+ invoiceId: "invoice",
+ requestedRates: expect.any(Array),
+ candidateTaxCodeIds: expect.any(Array),
+ reason: expect.any(String)
+ }
+ }
+ });
+ if (reason) expect(String(error)).toMatch(reason);
+}
+
+describe("QuickBooks native invoice tax", () => {
+ it("uses US transaction tax and documented taxable/non-taxable markers, grouping native tax once", () => {
+ const result = resolveQboInvoiceTax({
+ document: document(),
+ catalog: catalog()
+ });
+ expect(Object.fromEntries(result.lineTaxCodeRefs)).toEqual({
+ merch: { value: "TAX" },
+ addon: { value: "TAX" },
+ shipping: { value: "TAX" },
+ nontax: { value: "NON" },
+ header: { value: "NON" }
+ });
+ expect(result.txnTaxDetail).toEqual({
+ TxnTaxCodeRef: { value: "ten" },
+ TotalTax: 10.4,
+ TaxLine: [
+ {
+ Amount: 10.4,
+ DetailType: "TaxLineDetail",
+ TaxLineDetail: {
+ TaxRateRef: { value: "rate-ten" },
+ NetAmountTaxable: 104,
+ PercentBased: true,
+ TaxPercent: 10
+ }
+ }
+ ]
+ });
+ });
+ it("uses global sales tax codes and real member rate IDs without a US transaction code", () => {
+ const result = resolveQboInvoiceTax({
+ document: document(),
+ catalog: catalog("GB")
+ });
+ expect(result.lineTaxCodeRefs.get("merch")).toEqual({ value: "ten" });
+ expect(result.lineTaxCodeRefs.get("header")).toEqual({ value: "zero" });
+ expect(result.txnTaxDetail?.TxnTaxCodeRef).toBeUndefined();
+ expect(
+ result.txnTaxDetail?.TaxLine?.[0]?.TaxLineDetail?.TaxRateRef
+ ).toEqual({ value: "rate-ten" });
+ expect(result.txnTaxDetail?.TotalTax).toBe(10.4);
+ });
+ it("accepts an actual global non-taxable code without fabricating a zero rate", () => {
+ const remote = catalog("GB");
+ remote.taxCodes = [
+ ...remote.taxCodes.filter((code) => code.Id !== "zero"),
+ { Id: "exempt", Active: true, Taxable: false }
+ ];
+ const result = resolveQboInvoiceTax({
+ document: document(),
+ catalog: remote
+ });
+ expect(result.lineTaxCodeRefs.get("header")).toEqual({ value: "exempt" });
+ expect(result.txnTaxDetail?.TaxLine).toHaveLength(1);
+ });
+ it("supports distinct simple global sales rates and refuses incompatible US transaction codes", () => {
+ const source = document();
+ source.components[0]!.taxPercent = 0.2;
+ source.components[0]!.taxAmount = 16;
+ source.totalTax = 18.4;
+ source.totalAmount = 128.8;
+ const remote = catalog("CA");
+ remote.taxCodes.push({
+ Id: "twenty",
+ SalesTaxRateList: {
+ TaxRateDetail: [{ TaxRateRef: { value: "rate-twenty" } }]
+ }
+ });
+ remote.taxRates.push({ Id: "rate-twenty", RateValue: 20 });
+ const result = resolveQboInvoiceTax({ document: source, catalog: remote });
+ expect(result.txnTaxDetail?.TaxLine).toHaveLength(2);
+ expect(result.txnTaxDetail?.TotalTax).toBe(18.4);
+ expectWarning(
+ source,
+ { ...remote, country: "US" },
+ /multiple|transaction/i
+ );
+ });
+ it("uses documented US non-tax markers for all-zero tax and omits empty native tax detail", () => {
+ const source = document();
+ source.components.forEach((line) => {
+ line.taxPercent = 0;
+ line.taxAmount = 0;
+ });
+ source.totalTax = 0;
+ source.totalAmount = source.subtotal;
+ const result = resolveQboInvoiceTax({
+ document: source,
+ catalog: catalog()
+ });
+ expect(result.lineTaxCodeRefs.size).toBe(source.components.length);
+ expect(
+ [...result.lineTaxCodeRefs.values()].every((ref) => ref.value === "NON")
+ ).toBe(true);
+ expect(result.txnTaxDetail).toBeUndefined();
+ });
+ it.each([
+ "missing",
+ "duplicate",
+ "inactive",
+ "purchase-only",
+ "compound",
+ "tax-on-tax",
+ "dated"
+ ])("rejects %s tax setup without inventing an account/code or rate", (kind) => {
+ const remote = catalog();
+ if (kind === "missing") remote.taxRates = [];
+ if (kind === "duplicate")
+ remote.taxCodes.push({ ...remote.taxCodes[0]!, Id: "duplicate" });
+ if (kind === "inactive") remote.taxRates[0]!.Active = false;
+ if (kind === "purchase-only") {
+ remote.taxCodes[0]!.PurchaseTaxRateList =
+ remote.taxCodes[0]!.SalesTaxRateList;
+ delete remote.taxCodes[0]!.SalesTaxRateList;
+ }
+ if (kind === "compound")
+ remote.taxCodes[0]!.SalesTaxRateList!.TaxRateDetail.push({
+ TaxRateRef: { value: "rate-zero" }
+ });
+ if (kind === "tax-on-tax")
+ remote.taxCodes[0]!.SalesTaxRateList!
+ .TaxRateDetail[0]!.TaxTypeApplicable = "TaxOnTax";
+ if (kind === "dated")
+ remote.taxRates[0]!.EffectiveTaxRate = [
+ { EffectiveDate: "2026-01-01", RateValue: 10 }
+ ];
+ expectWarning(document(), remote);
+ });
+ it("fails rather than guessing jurisdiction", () => {
+ expectWarning(document(), { ...catalog(), country: "" });
+ });
+ it("rejects source tax amounts that cannot be reproduced by the resolved percentage", () => {
+ const source = document();
+ source.components[0]!.taxAmount = 12;
+ source.totalTax = 14.4;
+ expectWarning(source, catalog(), /reproduc|reconcil/i);
+ });
+});
+
+describe("loadQboInvoiceTaxCatalog", () => {
+ it("loads company jurisdiction and both complete provider query catalogs and filters inactive rows", async () => {
+ const getCompanyInfo = vi.fn(async () => ({ Country: "GB" }));
+ const query = vi.fn(async (entity: string) =>
+ entity === "TaxCode"
+ ? [{ Id: "active" }, { Id: "inactive", Active: false }]
+ : [{ Id: "rate", RateValue: 10 }]
+ );
+ expect(
+ await loadQboInvoiceTaxCatalog({
+ getCompanyInfo,
+ query
+ } as unknown as QboProvider)
+ ).toEqual({
+ country: "GB",
+ taxCodes: [{ Id: "active" }],
+ taxRates: [{ Id: "rate", RateValue: 10 }]
+ });
+ expect(query.mock.calls).toEqual([["TaxCode"], ["TaxRate"]]);
+ expect(getCompanyInfo).toHaveBeenCalledOnce();
+ });
+ it("propagates catalog read errors and refuses absent company jurisdiction", async () => {
+ const provider = {
+ getCompanyInfo: async () => ({ Country: "US" }),
+ query: async () => {
+ throw new Error("catalog unavailable");
+ }
+ };
+ await expect(
+ loadQboInvoiceTaxCatalog(provider as unknown as QboProvider)
+ ).rejects.toThrow("catalog unavailable");
+ await expect(
+ loadQboInvoiceTaxCatalog({
+ getCompanyInfo: async () => null,
+ query: async () => []
+ } as unknown as QboProvider)
+ ).rejects.toThrow(/jurisdiction|country/i);
+ });
+});
+
+it("uses documented US markers without requiring marker rows in the tax catalog", () => {
+ const source = document();
+ const remote = catalog();
+ remote.taxCodes = remote.taxCodes.filter(
+ (code) => code.Id !== "TAX" && code.Id !== "NON"
+ );
+ expect(
+ resolveQboInvoiceTax({
+ document: source,
+ catalog: remote
+ }).lineTaxCodeRefs.get("merch")
+ ).toEqual({ value: "TAX" });
+ source.components.forEach((line) => {
+ line.taxPercent = 0;
+ line.taxAmount = 0;
+ });
+ source.totalTax = 0;
+ expect(
+ resolveQboInvoiceTax({
+ document: source,
+ catalog: { country: "US", taxCodes: [], taxRates: [] }
+ })
+ ).toMatchObject({ txnTaxDetail: undefined });
+});
diff --git a/packages/ee/src/accounting/providers/quickbooks-online/entities/__tests__/invoice.test.ts b/packages/ee/src/accounting/providers/quickbooks-online/entities/__tests__/invoice.test.ts
index d46e827c38..8bb6bde500 100644
--- a/packages/ee/src/accounting/providers/quickbooks-online/entities/__tests__/invoice.test.ts
+++ b/packages/ee/src/accounting/providers/quickbooks-online/entities/__tests__/invoice.test.ts
@@ -1,6 +1,14 @@
-import { describe, expect, it } from "vitest";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { buildSalesDocumentComponents } from "../../../../core/sales-document-components";
+import { SyncFactory } from "../../../../core/sync";
import type { Accounting } from "../../../../core/types";
-import { buildQboInvoiceLines, deriveCarbonInvoiceStatus } from "../invoice";
+import { Qbo } from "../../models";
+import {
+ buildQboInvoiceLines,
+ deriveCarbonInvoiceStatus,
+ QboSalesInvoiceSyncer
+} from "../invoice";
+import { QboItemSyncer } from "../item";
import { buildQboDocNumberFields, QBO_DOC_NUMBER_MAX_LENGTH } from "../shared";
const makeLine = (
@@ -13,6 +21,9 @@ const makeLine = (
description: "Widget Bracket",
quantity: 3,
unitPrice: 19.999,
+ shippingCost: 0,
+ addOnCost: 0,
+ nonTaxableAddOnCost: 0,
taxPercent: 0,
lineAmount: 59.997,
...overrides
@@ -21,8 +32,7 @@ const makeLine = (
describe("buildQboInvoiceLines (invoice mapping fixture)", () => {
it("builds SalesItemLineDetail lines with ItemRef + Qty/UnitPrice and a rounded Amount", () => {
const lines = buildQboInvoiceLines(
- [makeLine()],
- new Map([["item-1", "77"]])
+ lineArguments([makeLine()], new Map([["item-1", "77"]]))
);
expect(lines).toEqual([
@@ -33,7 +43,8 @@ describe("buildQboInvoiceLines (invoice mapping fixture)", () => {
SalesItemLineDetail: {
ItemRef: { value: "77" },
Qty: 3,
- UnitPrice: 19.999
+ UnitPrice: 19.999,
+ TaxCodeRef: { value: "NON" }
}
}
]);
@@ -41,16 +52,18 @@ describe("buildQboInvoiceLines (invoice mapping fixture)", () => {
it("ships lines without an item without an ItemRef", () => {
const lines = buildQboInvoiceLines(
- [
- makeLine({
- itemId: null,
- itemCode: null,
- description: "Expedite fee",
- quantity: 1,
- unitPrice: 50
- })
- ],
- new Map()
+ lineArguments(
+ [
+ makeLine({
+ itemId: null,
+ itemCode: null,
+ description: "Expedite fee",
+ quantity: 1,
+ unitPrice: 50
+ })
+ ],
+ new Map()
+ )
);
expect(lines[0]?.SalesItemLineDetail?.ItemRef).toBeUndefined();
@@ -102,3 +115,278 @@ describe("deriveCarbonInvoiceStatus (pull status from Balance/TotalAmt)", () =>
expect(deriveCarbonInvoiceStatus(100, undefined)).toBeUndefined();
});
});
+
+function fullInvoice(): Accounting.SalesInvoice {
+ return {
+ id: "invoice",
+ invoiceId: "INV-1",
+ companyId: "company",
+ customerId: "customer",
+ customerExternalId: null,
+ status: "Submitted",
+ currencyCode: "EUR",
+ exchangeRate: 0.8,
+ baseCurrencyCode: "USD",
+ baseCurrencyDecimalPlaces: 2,
+ currencyDecimalPlaces: 2,
+ headerShippingCost: 5,
+ shippingRevenueAccountId: "acct-shipping",
+ dateIssued: "2026-09-07",
+ dateDue: null,
+ datePaid: null,
+ customerReference: null,
+ subtotal: 133,
+ totalTax: 13,
+ totalDiscount: 0,
+ totalAmount: 151,
+ balance: 151,
+ updatedAt: "2026-09-07T00:00:00.000Z",
+ lines: [
+ makeLine({
+ id: "line",
+ quantity: 1,
+ unitPrice: 100,
+ convertedUnitPrice: 80,
+ shippingCost: 10,
+ addOnCost: 20,
+ nonTaxableAddOnCost: 3,
+ taxPercent: 0.1
+ })
+ ]
+ };
+}
+function setupInvoice(
+ options: {
+ missingShipping?: boolean;
+ missingTax?: boolean;
+ country?: string;
+ } = {}
+) {
+ const country = options.country ?? "US";
+ const provider = {
+ id: "quickbooks",
+ getSyncConfig: () => ({
+ enabled: true,
+ direction: "push-to-accounting",
+ owner: "carbon"
+ }),
+ getCompanyInfo: vi.fn(async () => ({ Country: country })),
+ query: vi.fn(async (entity: string) =>
+ entity === "TaxRate"
+ ? [{ Id: "rate-ten", RateValue: 10 }]
+ : [
+ ...(options.missingTax
+ ? []
+ : [
+ {
+ Id: "ten",
+ SalesTaxRateList: {
+ TaxRateDetail: [{ TaxRateRef: { value: "rate-ten" } }]
+ }
+ }
+ ]),
+ ...(country === "US"
+ ? [
+ { Id: "TAX", Taxable: true },
+ { Id: "NON", Taxable: false }
+ ]
+ : [{ Id: "zero", Taxable: false }])
+ ]
+ ),
+ createInvoice: vi.fn(),
+ updateInvoice: vi.fn()
+ };
+ const database = {
+ selectFrom(table: string) {
+ const query: any = {
+ select: () => query,
+ innerJoin: () => query,
+ leftJoin: () => query,
+ where: () => query,
+ orderBy: () => query,
+ executeTakeFirst: async () =>
+ table === "accountDefault"
+ ? { salesShippingRevenueAccount: "replacement-shipping" }
+ : {
+ id: "acct-shipping",
+ class: "Revenue",
+ active: true,
+ isGroup: false
+ },
+ execute: async () =>
+ options.missingShipping
+ ? []
+ : [
+ {
+ id: "mapping",
+ accountId: "acct-shipping",
+ externalId: "shipping-account",
+ metadata: null,
+ lastSyncedAt: null,
+ accountNumber: "4010",
+ accountName: "Shipping"
+ }
+ ]
+ };
+ return query;
+ }
+ };
+ const context = {
+ database: database as never,
+ companyId: "company",
+ provider: provider as never,
+ config: {
+ enabled: true,
+ direction: "push-to-accounting" as const,
+ owner: "carbon" as const
+ },
+ entityType: "invoice" as const
+ };
+ const syncer = new QboSalesInvoiceSyncer(context);
+ const ensureDependencySynced = vi.fn(
+ async (type: string) => `${type}-remote`
+ );
+ (syncer as any).ensureDependencySynced = ensureDependencySynced;
+ const itemSyncer = new QboItemSyncer({ ...context, entityType: "item" });
+ const ensureShippingItem = vi.fn(async () => "shipping-item");
+ itemSyncer.ensureShippingItem = ensureShippingItem;
+ const factory = vi
+ .spyOn(SyncFactory, "getSyncer")
+ .mockReturnValue(itemSyncer);
+ return {
+ map: (source: Accounting.SalesInvoice) =>
+ (syncer as any).mapToRemote(source) as Promise<Qbo.Invoice>,
+ provider,
+ ensureDependencySynced,
+ ensureShippingItem,
+ factory
+ };
+}
+afterEach(() => vi.restoreAllMocks());
+describe("QBO actual invoice component/tax preflight", () => {
+ it.each([
+ "US",
+ "GB"
+ ])("sends one native tax detail and shipping ItemRef with reciprocal FX for %s", async (country) => {
+ const test = setupInvoice({ country });
+ const payload = await test.map(fullInvoice());
+ expect(payload).toMatchObject({
+ CurrencyRef: { value: "EUR" },
+ ExchangeRate: 1.25,
+ TxnTaxDetail: { TotalTax: 10.4 }
+ });
+ expect(
+ payload.Line.map((line) => [
+ line.Amount,
+ line.SalesItemLineDetail?.ItemRef?.value
+ ])
+ ).toEqual([
+ [80, "item-remote"],
+ [16, "item-remote"],
+ [2.4, "item-remote"],
+ [8, "shipping-item"],
+ [4, "shipping-item"]
+ ]);
+ expect(
+ payload.Line.every((line) => line.DetailType === "SalesItemLineDetail")
+ ).toBe(true);
+ expect(
+ payload.Line.reduce((sum, line) => sum + line.Amount, 0) +
+ payload.TxnTaxDetail!.TotalTax
+ ).toBeCloseTo(120.8, 8);
+ expect(
+ Qbo.InvoiceSchema.parse({ ...payload, Id: "remote", SyncToken: "1" })
+ .TxnTaxDetail?.TotalTax
+ ).toBe(10.4);
+ expect(test.ensureShippingItem).toHaveBeenCalledOnce();
+ expect(test.provider.getCompanyInfo).toHaveBeenCalledOnce();
+ expect(payload.GlobalTaxCalculation).toBe(
+ country === "US" ? undefined : "TaxExcluded"
+ );
+ });
+ it.each([
+ "missingShipping",
+ "missingTax"
+ ] as const)("refuses %s before dependencies/helpers/invoice writes", async (option) => {
+ const test = setupInvoice({ [option]: true });
+ await expect(test.map(fullInvoice())).rejects.toMatchObject({
+ failure: {
+ errorCode:
+ option === "missingTax" ? "UNMAPPED_TAX_CODES" : "UNMAPPED_ACCOUNTS",
+ warning: true
+ }
+ });
+ expect(test.ensureDependencySynced).not.toHaveBeenCalled();
+ expect(test.ensureShippingItem).not.toHaveBeenCalled();
+ expect(test.provider.createInvoice).not.toHaveBeenCalled();
+ expect(test.provider.updateInvoice).not.toHaveBeenCalled();
+ });
+ it("rejects a non-finite reciprocal FX rate before provisioning", async () => {
+ const source = fullInvoice();
+ source.exchangeRate = Number.MIN_VALUE;
+ source.lines[0]!.convertedUnitPrice = null;
+ const test = setupInvoice();
+ await expect(test.map(source)).rejects.toThrow(/exchange rate|finite/i);
+ expect(test.ensureDependencySynced).not.toHaveBeenCalled();
+ });
+ it("does not provision a shipping helper for a zero shipping document", async () => {
+ const source = fullInvoice();
+ source.headerShippingCost = 0;
+ source.subtotal = 123;
+ source.totalTax = 12;
+ source.totalAmount = 135;
+ source.balance = 135;
+ source.lines[0]!.shippingCost = 0;
+ const test = setupInvoice();
+ const payload = await test.map(source);
+ expect(payload.Line).toHaveLength(3);
+ expect(test.ensureShippingItem).not.toHaveBeenCalled();
+ expect(test.factory).not.toHaveBeenCalled();
+ });
+});
+
+function lineArguments(
+ lines: Accounting.SalesInvoiceLine[],
+ itemRemoteIds: ReadonlyMap<string, string>
+) {
+ const source = fullInvoice();
+ const subtotal = lines.reduce(
+ (sum, line) => sum + line.quantity * line.unitPrice,
+ 0
+ );
+ const document = buildSalesDocumentComponents({
+ ...source,
+ currencyCode: "USD",
+ exchangeRate: 1,
+ headerShippingCost: 0,
+ shippingRevenueAccountId: "acct-shipping",
+ lines,
+ subtotal,
+ totalTax: 0,
+ totalAmount: subtotal,
+ balance: subtotal
+ });
+ return {
+ document,
+ itemRemoteIds,
+ shippingItemRemoteId: null,
+ lineTaxCodeRefs: new Map(
+ document.components.map((line) => [line.id, { value: "NON" }])
+ )
+ };
+}
+
+it("retries a failed tax catalog read on the same syncer and caches a later success", async () => {
+ const test = setupInvoice();
+ test.provider.getCompanyInfo.mockRejectedValueOnce(
+ new Error("temporary provider outage")
+ );
+ await expect(test.map(fullInvoice())).rejects.toThrow(
+ /temporary provider outage/
+ );
+ await expect(test.map(fullInvoice())).resolves.toMatchObject({
+ TxnTaxDetail: { TotalTax: 10.4 }
+ });
+ await test.map(fullInvoice());
+ expect(test.provider.getCompanyInfo).toHaveBeenCalledTimes(2);
+});
diff --git a/packages/ee/src/accounting/providers/quickbooks-online/entities/__tests__/item.test.ts b/packages/ee/src/accounting/providers/quickbooks-online/entities/__tests__/item.test.ts
index a5e17096e6..8d77b1c8f4 100644
--- a/packages/ee/src/accounting/providers/quickbooks-online/entities/__tests__/item.test.ts
+++ b/packages/ee/src/accounting/providers/quickbooks-online/entities/__tests__/item.test.ts
@@ -1,11 +1,12 @@
-import { describe, expect, it } from "vitest";
+import { beforeEach, describe, expect, it, vi } from "vitest";
import {
isJournalEntrySyncFailure,
JournalEntrySyncError
} from "../../../../core/posting";
import type { Accounting } from "../../../../core/types";
-import type { Qbo } from "../../models";
-import { mapItemToQboItem } from "../item";
+import { AccountingApiError } from "../../../../core/utils";
+import type { Qbo, QboCreatePayload } from "../../models";
+import { mapItemToQboItem, QboItemSyncer } from "../item";
const makeItem = (overrides?: Partial<Accounting.Item>): Accounting.Item => ({
id: "item-1",
@@ -180,3 +181,226 @@ describe("mapItemToQboItem (mapping fixture with account resolution)", () => {
expect(isJournalEntrySyncFailure(failure)).toBe(true);
});
});
+
+const { shippingLinks, linkControl } = vi.hoisted(() => ({
+ shippingLinks: [] as Array<Record<string, unknown>>,
+ linkControl: { failOnce: false }
+}));
+vi.mock("../../../../core/utils", async (original) => ({
+ ...(await original<typeof import("../../../../core/utils")>()),
+ withTriggersDisabled: async (
+ _database: unknown,
+ callback: (tx: unknown) => Promise<unknown>
+ ) => {
+ const builder: any = {
+ values(values: Record<string, unknown>) {
+ shippingLinks.push(values);
+ return builder;
+ },
+ onConflict() {
+ return builder;
+ },
+ async execute() {
+ if (linkControl.failOnce) {
+ linkControl.failOnce = false;
+ throw new Error("link failed");
+ }
+ return [];
+ }
+ };
+ return callback({ insertInto: () => builder });
+ }
+}));
+beforeEach(() => {
+ shippingLinks.length = 0;
+ linkControl.failOnce = false;
+});
+const shippingItem = (overrides: Partial<Qbo.Item> = {}): Qbo.Item => ({
+ Id: "shipping-remote",
+ SyncToken: "1",
+ Name: "Carbon Shipping acct-shipping",
+ Type: "Service",
+ Active: true,
+ UnitPrice: 0,
+ IncomeAccountRef: { value: "income-shipping" },
+ ...overrides
+});
+function shippingSyncer(
+ args: {
+ existingId?: string;
+ existing?: Qbo.Item;
+ matches?: Qbo.Item[];
+ create?: ReturnType<typeof vi.fn>;
+ refs?: Map<string, Qbo.Ref>;
+ } = {}
+) {
+ const query = vi.fn(
+ async (_entity: string, _where?: string) => args.matches ?? []
+ );
+ const getItem = vi.fn(async () => args.existing ?? shippingItem());
+ const createItem =
+ args.create ??
+ vi.fn(async (_payload: QboCreatePayload<Qbo.Item>) => shippingItem());
+ const updateItem = vi.fn(async (payload: Qbo.Item) => payload);
+ const syncer = new QboItemSyncer({
+ database: {} as never,
+ companyId: "company-1",
+ provider: {
+ id: "quickbooks",
+ query,
+ getItem,
+ createItem,
+ updateItem
+ } as never,
+ config: { enabled: true, direction: "push-to-accounting", owner: "carbon" },
+ entityType: "item"
+ });
+ (syncer as any).mappingService = {
+ getExternalId: vi.fn(async () => args.existingId ?? null)
+ };
+ (syncer as any).getAccountRefsById = async () =>
+ args.refs ?? new Map([["acct-shipping", { value: "income-shipping" }]]);
+ return { syncer, query, getItem, createItem, updateItem };
+}
+describe("QBO shipping helper identity", () => {
+ it("creates one sales-only Service per shipping account and caches reuse", async () => {
+ const test = shippingSyncer();
+ expect(
+ await test.syncer.ensureShippingItem({
+ shippingAccountId: "acct-shipping"
+ })
+ ).toBe("shipping-remote");
+ expect(
+ await test.syncer.ensureShippingItem({
+ shippingAccountId: "acct-shipping"
+ })
+ ).toBe("shipping-remote");
+ expect(test.createItem).toHaveBeenCalledOnce();
+ expect(test.createItem.mock.calls[0]?.[0]).toEqual({
+ Name: "Carbon Shipping acct-shipping",
+ Description: "Customer shipping charges",
+ Type: "Service",
+ Active: true,
+ UnitPrice: 0,
+ IncomeAccountRef: { value: "income-shipping" }
+ });
+ expect(shippingLinks[0]).toMatchObject({
+ entityType: "shippingItem",
+ entityId: "acct-shipping",
+ integration: "quickbooks",
+ externalId: "shipping-remote",
+ companyId: "company-1",
+ metadata: { accountId: "acct-shipping", kind: "shipping" }
+ });
+ expect(test.query).toHaveBeenCalledOnce();
+ });
+ it("reuses an owned compatible helper mapping without a create or name lookup", async () => {
+ const test = shippingSyncer({ existingId: "shipping-remote" });
+ expect(
+ await test.syncer.ensureShippingItem({
+ shippingAccountId: "acct-shipping"
+ })
+ ).toBe("shipping-remote");
+ expect(test.createItem).not.toHaveBeenCalled();
+ expect(test.query).not.toHaveBeenCalled();
+ });
+ it("recovers remote-create/local-link retries through the exact compatible remote name", async () => {
+ const test = shippingSyncer();
+ linkControl.failOnce = true;
+ await expect(
+ test.syncer.ensureShippingItem({ shippingAccountId: "acct-shipping" })
+ ).rejects.toThrow("link failed");
+ test.query.mockResolvedValue([shippingItem()]);
+ expect(
+ await test.syncer.ensureShippingItem({
+ shippingAccountId: "acct-shipping"
+ })
+ ).toBe("shipping-remote");
+ expect(test.createItem).toHaveBeenCalledOnce();
+ expect(test.query.mock.calls[1]).toEqual([
+ "Item",
+ "Name = 'Carbon Shipping acct-shipping'"
+ ]);
+ });
+ it("recovers duplicate-name races by rereading and linking the compatible helper", async () => {
+ const error = new AccountingApiError("quickbooks", "create item", {
+ statusCode: 400,
+ statusText: "Bad Request",
+ providerErrorCode: "6240"
+ });
+ const test = shippingSyncer({
+ create: vi.fn(async () => {
+ throw error;
+ })
+ });
+ test.query
+ .mockResolvedValueOnce([])
+ .mockResolvedValueOnce([shippingItem()]);
+ expect(
+ await test.syncer.ensureShippingItem({
+ shippingAccountId: "acct-shipping"
+ })
+ ).toBe("shipping-remote");
+ expect(test.createItem).toHaveBeenCalledOnce();
+ expect(shippingLinks).toHaveLength(1);
+ });
+ it.each([
+ { Type: "NonInventory" },
+ { Active: false },
+ { IncomeAccountRef: { value: "wrong" } }
+ ])("refuses an incompatible unowned helper without mutating it: %s", async (override) => {
+ const test = shippingSyncer({
+ matches: [shippingItem(override as Partial<Qbo.Item>)]
+ });
+ await expect(
+ test.syncer.ensureShippingItem({ shippingAccountId: "acct-shipping" })
+ ).rejects.toMatchObject({
+ failure: { errorCode: "UNMAPPED_ACCOUNTS", warning: true }
+ });
+ expect(test.createItem).not.toHaveBeenCalled();
+ expect(test.updateItem).not.toHaveBeenCalled();
+ expect(shippingLinks).toEqual([]);
+ });
+ it("reconverges only an owned helper with the current SyncToken", async () => {
+ const test = shippingSyncer({
+ existingId: "shipping-remote",
+ existing: shippingItem({ IncomeAccountRef: { value: "old-account" } })
+ });
+ expect(
+ await test.syncer.ensureShippingItem({
+ shippingAccountId: "acct-shipping"
+ })
+ ).toBe("shipping-remote");
+ expect(test.updateItem).toHaveBeenCalledWith(
+ expect.objectContaining({
+ Id: "shipping-remote",
+ SyncToken: "1",
+ IncomeAccountRef: { value: "income-shipping" }
+ })
+ );
+ expect(test.createItem).not.toHaveBeenCalled();
+ expect(test.query).not.toHaveBeenCalled();
+ });
+ it("keeps an owned helper nominally priced at zero", async () => {
+ const test = shippingSyncer({
+ existingId: "shipping-remote",
+ existing: shippingItem({ UnitPrice: 9 })
+ });
+ await test.syncer.ensureShippingItem({
+ shippingAccountId: "acct-shipping"
+ });
+ expect(test.updateItem).toHaveBeenCalledWith(
+ expect.objectContaining({ UnitPrice: 0 })
+ );
+ });
+ it("fails unmapped shipping before remote reads/writes", async () => {
+ const test = shippingSyncer({ refs: new Map() });
+ await expect(
+ test.syncer.ensureShippingItem({ shippingAccountId: "acct-shipping" })
+ ).rejects.toMatchObject({
+ failure: { errorCode: "UNMAPPED_ACCOUNTS", warning: true }
+ });
+ expect(test.query).not.toHaveBeenCalled();
+ expect(test.createItem).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/ee/src/accounting/providers/quickbooks-online/entities/__tests__/payment.test.ts b/packages/ee/src/accounting/providers/quickbooks-online/entities/__tests__/payment.test.ts
index 82faf9c3fa..003f6b9969 100644
--- a/packages/ee/src/accounting/providers/quickbooks-online/entities/__tests__/payment.test.ts
+++ b/packages/ee/src/accounting/providers/quickbooks-online/entities/__tests__/payment.test.ts
@@ -171,7 +171,7 @@ describe("QboPaymentSyncer.mapToNormalized", () => {
paymentRemoteId: "bp-1",
amount: 500,
currencyCode: "USD",
- exchangeRate: 1,
+ exchangeRate: null,
paidDate: "2026-08-01",
reference: "bp-1",
status: "settled",
@@ -228,7 +228,7 @@ describe("QboPaymentSyncer.mapToNormalized", () => {
paymentRemoteId: "pay-1",
amount: 125,
currencyCode: "EUR",
- exchangeRate: 1.1,
+ exchangeRate: 1 / 1.1,
paidDate: "2026-07-15",
reference: "pay-1",
status: "settled",
diff --git a/packages/ee/src/accounting/providers/quickbooks-online/entities/bill.ts b/packages/ee/src/accounting/providers/quickbooks-online/entities/bill.ts
index e9c813c109..95d04cd830 100644
--- a/packages/ee/src/accounting/providers/quickbooks-online/entities/bill.ts
+++ b/packages/ee/src/accounting/providers/quickbooks-online/entities/bill.ts
@@ -1,4 +1,5 @@
import type { KyselyTx } from "@carbon/database/client";
+import { assertExchangeRate, toBaseAmount } from "@carbon/utils";
import { sql } from "kysely";
import {
type CostingLine,
@@ -7,7 +8,7 @@ import {
toTransactionCurrencyLines
} from "../../../core/document-costing";
import { createMappingService } from "../../../core/external-mapping";
-import { JournalEntrySyncError, roundCurrency } from "../../../core/posting";
+import { JournalEntrySyncError } from "../../../core/posting";
import {
type Accounting,
BaseEntitySyncer,
@@ -180,7 +181,7 @@ export function buildQboBillLines(args: {
return args.costingLines.map((line) => {
const description = costingLineItemLabel(line) ?? line.description;
return {
- Amount: roundCurrency(line.amount),
+ Amount: line.amount,
...(description ? { Description: description } : {}),
DetailType: "AccountBasedExpenseLineDetail",
AccountBasedExpenseLineDetail: {
@@ -469,21 +470,23 @@ export class QboBillSyncer extends BaseEntitySyncer<
// the item is a label only, so NO item dependency sync is needed here (the
// PO keeps item lines via buildQboExpenseLines; the bill does not).
const accountRefsById = await this.getAccountRefsById();
- const payablesAccountId = await this.getPayablesAccountId();
const {
lines: costingLines,
currencyCode,
- exchangeRate
+ exchangeRate,
+ documentTotal,
+ decimalPlaces,
+ baseCurrencyCode
} = await loadBillCostingLines(this.database, {
companyId: this.companyId,
- billId: local.id,
- payablesAccountId
+ billId: local.id
});
- const transactionLines = toTransactionCurrencyLines(
- costingLines,
- exchangeRate
- );
+ const transactionLines = toTransactionCurrencyLines(costingLines, {
+ exchangeRate,
+ documentTotal,
+ decimalPlaces
+ });
// Due date: use dateDue if provided, otherwise default to Net 30
// (Xero-syncer parity)
@@ -509,11 +512,11 @@ export class QboBillSyncer extends BaseEntitySyncer<
TxnDate: local.dateIssued ?? undefined,
DueDate: dueDate,
VendorRef: { value: vendorRemoteId },
- // FX: pin the currency + provider rate (omit both at parity rate 1).
- ...(exchangeRate !== 1
+ // QBO quotes company base per document currency, reciprocal to Carbon.
+ ...(currencyCode !== baseCurrencyCode
? {
CurrencyRef: { value: currencyCode },
- ExchangeRate: exchangeRate
+ ExchangeRate: 1 / exchangeRate
}
: {}),
Line: buildQboBillLines({
@@ -524,16 +527,6 @@ export class QboBillSyncer extends BaseEntitySyncer<
};
}
- /** accountDefault.payablesAccount — the AP control line to exclude. */
- private async getPayablesAccountId(): Promise<string | null> {
- const defaults = await this.database
- .selectFrom("accountDefault")
- .select("payablesAccount")
- .where("companyId", "=", this.companyId)
- .executeTakeFirst();
- return defaults?.payablesAccount ?? null;
- }
-
// =================================================================
// 6. TRANSFORMATION (QBO -> Carbon)
// =================================================================
@@ -541,37 +534,65 @@ export class QboBillSyncer extends BaseEntitySyncer<
protected async mapToLocal(
remote: Qbo.Bill
): Promise<Partial<Accounting.Bill>> {
- const mappingService = createMappingService(this.database, this.companyId);
-
+ const company = await this.database
+ .selectFrom("company")
+ .select("baseCurrencyCode")
+ .where("id", "=", this.companyId)
+ .executeTakeFirst();
+ const currencyCode = remote.CurrencyRef?.value ?? company?.baseCurrencyCode;
+ if (!currencyCode || !company?.baseCurrencyCode)
+ throw new Error("QuickBooks bill currency metadata is required");
+ const remoteRate =
+ remote.ExchangeRate ??
+ (currencyCode === company.baseCurrencyCode ? 1 : null);
+ if (remoteRate === null || !Number.isFinite(remoteRate) || remoteRate <= 0)
+ throw new Error(
+ "QuickBooks bill exchange rate must be positive and finite"
+ );
+ if (currencyCode === company.baseCurrencyCode && remoteRate !== 1)
+ throw new Error("Base-currency bill requires identity exchange rate");
+ const exchangeRate = 1 / remoteRate;
+ const referenceIds = [
+ ...new Set(
+ (remote.Line ?? [])
+ .flatMap((line) => [
+ line.ItemBasedExpenseLineDetail?.ItemRef?.value,
+ line.AccountBasedExpenseLineDetail?.AccountRef?.value
+ ])
+ .filter((id): id is string => !!id)
+ )
+ ];
+ const references = referenceIds.length
+ ? await this.database
+ .selectFrom("externalIntegrationMapping")
+ .select(["entityType", "externalId", "entityId"])
+ .where("companyId", "=", this.companyId)
+ .where("integration", "=", this.provider.id)
+ .where("entityType", "in", ["item", "account"])
+ .where("externalId", "in", referenceIds)
+ .execute()
+ : [];
+ const localReference = new Map(
+ references.map((row) => [
+ `${row.entityType}:${row.externalId}`,
+ row.entityId
+ ])
+ );
const lines: Accounting.BillLine[] = [];
for (const [index, line] of (remote.Line ?? []).entries()) {
const isItemLine = line.DetailType === "ItemBasedExpenseLineDetail";
const isAccountLine = line.DetailType === "AccountBasedExpenseLineDetail";
if (!isItemLine && !isAccountLine) continue;
- // Resolve the Carbon item from the QBO ItemRef via the mapping table
- let itemId: string | null = null;
const remoteItemId = line.ItemBasedExpenseLineDetail?.ItemRef?.value;
- if (remoteItemId) {
- itemId = await mappingService.getEntityId(
- this.provider.id,
- remoteItemId,
- "item"
- );
- }
-
- // Resolve the Carbon account from the QBO AccountRef via the account
- // mapping (externalId → account.id)
- let accountId: string | null = null;
+ const itemId = remoteItemId
+ ? (localReference.get(`item:${remoteItemId}`) ?? null)
+ : null;
const remoteAccountId =
- line.AccountBasedExpenseLineDetail?.AccountRef.value;
- if (remoteAccountId) {
- accountId = await mappingService.getEntityId(
- this.provider.id,
- remoteAccountId,
- "account"
- );
- }
+ line.AccountBasedExpenseLineDetail?.AccountRef?.value;
+ const accountId = remoteAccountId
+ ? (localReference.get(`account:${remoteAccountId}`) ?? null)
+ : null;
lines.push({
id: line.Id ?? `temp-${index}`,
@@ -590,6 +611,8 @@ export class QboBillSyncer extends BaseEntitySyncer<
}
return {
+ currencyCode,
+ exchangeRate,
invoiceId: remote.DocNumber ?? remote.Id,
supplierExternalId: remote.VendorRef.value,
status: deriveCarbonBillStatus({
@@ -600,8 +623,8 @@ export class QboBillSyncer extends BaseEntitySyncer<
dateIssued: remote.TxnDate ?? null,
dateDue: remote.DueDate ?? null,
datePaid: remote.Balance === 0 ? new Date().toISOString() : null,
- totalAmount: remote.TotalAmt ?? 0,
- balance: remote.Balance ?? 0,
+ totalAmount: toBaseAmount(remote.TotalAmt ?? 0, exchangeRate),
+ balance: toBaseAmount(remote.Balance ?? 0, exchangeRate),
lines,
updatedAt:
parseQboDate(remote.MetaData?.LastUpdatedTime)?.toISOString() ??
@@ -618,6 +641,11 @@ export class QboBillSyncer extends BaseEntitySyncer<
data: Partial<Accounting.Bill>,
remoteId: string
): Promise<string> {
+ if (!data.currencyCode || data.exchangeRate == null)
+ throw new Error(
+ "Bill currency and exchange rate are required before storing supplier amounts"
+ );
+ assertExchangeRate(data.exchangeRate);
const existingLocalId = await this.getLocalId(remoteId);
// Resolve supplier from the QBO VendorRef via the vendor mapping
@@ -636,6 +664,8 @@ export class QboBillSyncer extends BaseEntitySyncer<
.updateTable("purchaseInvoice")
.set({
supplierId,
+ currencyCode: data.currencyCode,
+ exchangeRate: data.exchangeRate,
status: data.status,
dateIssued: data.dateIssued,
dateDue: data.dateDue,
@@ -696,8 +726,8 @@ export class QboBillSyncer extends BaseEntitySyncer<
dateIssued: data.dateIssued ?? null,
dateDue: data.dateDue ?? null,
datePaid: data.datePaid ?? null,
- currencyCode: data.currencyCode ?? "USD",
- exchangeRate: data.exchangeRate ?? 1,
+ currencyCode: data.currencyCode,
+ exchangeRate: data.exchangeRate,
subtotal: data.subtotal ?? 0,
totalTax: data.totalTax ?? 0,
totalDiscount: data.totalDiscount ?? 0,
@@ -749,6 +779,7 @@ export class QboBillSyncer extends BaseEntitySyncer<
await tx
.deleteFrom("purchaseInvoiceLine")
.where("invoiceId", "=", invoiceId)
+ .where("companyId", "=", this.companyId)
.execute();
if (lines.length === 0) return;
@@ -757,32 +788,29 @@ export class QboBillSyncer extends BaseEntitySyncer<
.selectFrom("purchaseInvoice")
.select(["companyId", "createdBy", "exchangeRate"])
.where("id", "=", invoiceId)
+ .where("companyId", "=", this.companyId)
.executeTakeFirstOrThrow();
- for (const line of lines) {
- await tx
- .insertInto("purchaseInvoiceLine")
- .values({
+ await tx
+ .insertInto("purchaseInvoiceLine")
+ .values(
+ lines.map((line) => ({
invoiceId,
companyId: invoice.companyId,
createdBy: invoice.createdBy,
description: line.description,
quantity: line.quantity,
- unitPrice: line.unitPrice,
supplierUnitPrice: line.unitPrice,
itemId: line.itemId,
accountId: line.accountId ?? null,
taxPercent: line.taxPercent,
- taxAmount: line.taxAmount,
supplierTaxAmount: line.taxAmount ?? 0,
- totalAmount: line.totalAmount,
- supplierExtendedPrice: line.totalAmount,
exchangeRate: invoice.exchangeRate,
invoiceLineType: line.itemId ? "Part" : "G/L Account",
supplierShippingCost: 0
- })
- .execute();
- }
+ }))
+ )
+ .execute();
}
// =================================================================
diff --git a/packages/ee/src/accounting/providers/quickbooks-online/entities/invoice-tax.ts b/packages/ee/src/accounting/providers/quickbooks-online/entities/invoice-tax.ts
new file mode 100644
index 0000000000..911b6f3401
--- /dev/null
+++ b/packages/ee/src/accounting/providers/quickbooks-online/entities/invoice-tax.ts
@@ -0,0 +1,197 @@
+import { EPSILON, round, SCALE } from "@carbon/utils";
+import { JournalEntrySyncError } from "../../../core/posting";
+import type { SalesDocumentComponents } from "../../../core/sales-document-components";
+import type { Qbo } from "../models";
+import type { QboProvider } from "../provider";
+
+export type QboInvoiceTaxCatalog = {
+ country: string;
+ taxCodes: readonly Qbo.TaxCode[];
+ taxRates: readonly Qbo.TaxRate[];
+};
+
+/** Provider.query already paginates; one catalog promise is shared by a syncer batch. */
+export async function loadQboInvoiceTaxCatalog(
+ provider: QboProvider
+): Promise<QboInvoiceTaxCatalog> {
+ const [company, codes, rates] = await Promise.all([
+ provider.getCompanyInfo(),
+ provider.query<Qbo.TaxCode>("TaxCode"),
+ provider.query<Qbo.TaxRate>("TaxRate")
+ ]);
+ if (!company?.Country || !/^[A-Z]{2}$/i.test(company.Country)) {
+ throw new Error(
+ "Cannot resolve QuickBooks tax jurisdiction: company country is missing"
+ );
+ }
+ return {
+ country: company.Country.toUpperCase(),
+ taxCodes: codes.filter((code) => code.Active !== false),
+ taxRates: rates.filter((rate) => rate.Active !== false)
+ };
+}
+
+/** Translate existing Carbon tax facts; never create tax codes or determine new tax. */
+export function resolveQboInvoiceTax(args: {
+ document: SalesDocumentComponents;
+ catalog: QboInvoiceTaxCatalog;
+}): {
+ lineTaxCodeRefs: ReadonlyMap<string, Qbo.Ref>;
+ txnTaxDetail: Qbo.TxnTaxDetail | undefined;
+} {
+ const { document, catalog } = args;
+ const requestedRates = [
+ ...new Set(document.components.map((line) => line.taxPercent))
+ ];
+ const codes = catalog.taxCodes.filter((code) => code.Active !== false);
+ const fail = (
+ reason: string,
+ candidates: readonly Qbo.TaxCode[] = codes
+ ): never => {
+ throw new JournalEntrySyncError({
+ errorCode: "UNMAPPED_TAX_CODES",
+ warning: true,
+ message: `Cannot sync invoice tax (${requestedRates.map((rate) => `${round(rate * 100)}%`).join(", ")}): ${reason}. Resolve the QuickBooks tax configuration, then retry.`,
+ metadata: {
+ invoiceId: document.invoiceId,
+ requestedRates,
+ candidateTaxCodeIds: candidates.map((code) => code.Id),
+ reason
+ }
+ });
+ };
+ if (!/^[A-Z]{2}$/i.test(catalog.country))
+ fail("Company country/jurisdiction is missing");
+ if (
+ !Number.isInteger(document.decimalPlaces) ||
+ document.decimalPlaces < 0 ||
+ document.decimalPlaces > SCALE
+ )
+ fail("Invalid document tax precision");
+ const isUS = catalog.country.toUpperCase() === "US";
+ const rates = new Map(
+ catalog.taxRates
+ .filter((rate) => rate.Active !== false)
+ .map((rate) => [rate.Id, rate])
+ );
+ const resolved = new Map<number, { code: Qbo.TaxCode; rate?: Qbo.TaxRate }>();
+ for (const fraction of requestedRates) {
+ if (!Number.isFinite(fraction) || fraction < 0)
+ fail("Unsupported source fractional tax rate");
+ if (fraction === 0 && isUS) continue;
+ const percentage = round(fraction * 100);
+ const candidates: Array<{ code: Qbo.TaxCode; rate?: Qbo.TaxRate }> = [];
+ for (const code of codes) {
+ const details = code.SalesTaxRateList?.TaxRateDetail ?? [];
+ if (fraction === 0 && code.Taxable === false && details.length === 0) {
+ candidates.push({ code });
+ continue;
+ }
+ if (details.length !== 1) continue;
+ const detail = details[0]!;
+ if (
+ (detail.TaxTypeApplicable &&
+ detail.TaxTypeApplicable !== "TaxOnAmount") ||
+ (detail.TaxOnTaxOrder != null && detail.TaxOnTaxOrder !== 0) ||
+ (detail.TaxOrder != null && detail.TaxOrder > 1)
+ )
+ continue;
+ const rate = rates.get(detail.TaxRateRef.value);
+ if (
+ !rate ||
+ !Number.isFinite(rate.RateValue) ||
+ (rate.EffectiveTaxRate?.length ?? 0) > 0 ||
+ rate.SpecialTaxType
+ )
+ continue;
+ if (Math.abs(round(rate.RateValue!) - percentage) <= EPSILON)
+ candidates.push({ code, rate });
+ }
+ if (candidates.length !== 1)
+ fail(
+ candidates.length === 0
+ ? `No supported simple active sales tax code reproduces ${percentage}% (missing, compound, dated, or purchase-only configuration)`
+ : `Multiple active sales tax codes match ${percentage}%`,
+ candidates.map((match) => match.code)
+ );
+ resolved.set(fraction, candidates[0]!);
+ }
+ const nonzero = [...resolved]
+ .filter(([fraction]) => fraction !== 0)
+ .map(([, match]) => match);
+ if (isUS && new Set(nonzero.map((match) => match.code.Id)).size > 1)
+ fail("US invoices support only one transaction tax code");
+ // US line refs are protocol markers, not query-returned TaxCode IDs.
+ // Intuit's SDK quickstart documents TAX/NON; transaction rates still come
+ // from the actual catalog resolved above.
+ const marker = (taxable: boolean): Qbo.Ref => ({
+ value: taxable ? "TAX" : "NON"
+ });
+ const lineTaxCodeRefs = new Map<string, Qbo.Ref>();
+ const nativeByRate = new Map<
+ string,
+ { amount: number; net: number; percentage: number }
+ >();
+ for (const line of document.components) {
+ if (!Number.isFinite(line.taxAmount) || !Number.isFinite(line.netAmount))
+ fail("Non-finite document tax component");
+ const match = resolved.get(line.taxPercent);
+ const codeRef = isUS
+ ? marker(line.taxPercent !== 0)
+ : { value: match!.code.Id };
+ lineTaxCodeRefs.set(line.id, codeRef);
+ const expected = round(
+ line.netAmount * line.taxPercent,
+ document.decimalPlaces
+ );
+ const envelope = 1 / 10 ** document.decimalPlaces + EPSILON;
+ if (
+ Math.abs(expected - line.taxAmount) > envelope ||
+ (line.taxPercent === 0 && line.taxAmount !== 0)
+ ) {
+ fail(
+ `Supplied tax on component ${line.id} cannot be reproduced by its percentage`
+ );
+ }
+ if (line.taxPercent === 0) continue;
+ const rateId = match!.rate!.Id;
+ const total = nativeByRate.get(rateId) ?? {
+ amount: 0,
+ net: 0,
+ percentage: round(line.taxPercent * 100)
+ };
+ total.amount += line.taxAmount;
+ total.net += line.netAmount;
+ nativeByRate.set(rateId, total);
+ }
+ const totalTax = round(
+ [...nativeByRate.values()].reduce((sum, row) => sum + row.amount, 0),
+ document.decimalPlaces
+ );
+ if (
+ !Number.isFinite(document.totalTax) ||
+ Math.abs(totalTax - document.totalTax) > EPSILON
+ )
+ fail("Native tax detail does not reconcile to the document tax total");
+ if (nativeByRate.size === 0)
+ return { lineTaxCodeRefs, txnTaxDetail: undefined };
+ return {
+ lineTaxCodeRefs,
+ txnTaxDetail: {
+ ...(isUS && nonzero[0]
+ ? { TxnTaxCodeRef: { value: nonzero[0].code.Id } }
+ : {}),
+ TotalTax: document.totalTax,
+ TaxLine: [...nativeByRate].map(([id, total]) => ({
+ Amount: round(total.amount, document.decimalPlaces),
+ DetailType: "TaxLineDetail",
+ TaxLineDetail: {
+ TaxRateRef: { value: id },
+ NetAmountTaxable: round(total.net, document.decimalPlaces),
+ PercentBased: true,
+ TaxPercent: total.percentage
+ }
+ }))
+ }
+ };
+}
diff --git a/packages/ee/src/accounting/providers/quickbooks-online/entities/invoice.ts b/packages/ee/src/accounting/providers/quickbooks-online/entities/invoice.ts
index 5083c202fd..d956f98920 100644
--- a/packages/ee/src/accounting/providers/quickbooks-online/entities/invoice.ts
+++ b/packages/ee/src/accounting/providers/quickbooks-online/entities/invoice.ts
@@ -1,6 +1,19 @@
import type { KyselyTx } from "@carbon/database/client";
+import { datetime } from "@carbon/database/datetime";
+import { parseDate } from "@internationalized/date";
import { createMappingService } from "../../../core/external-mapping";
-import { roundCurrency } from "../../../core/posting";
+import {
+ JournalEntrySyncError,
+ toPostingDateString
+} from "../../../core/posting";
+import {
+ buildSalesDocumentComponents,
+ type SalesDocumentComponents
+} from "../../../core/sales-document-components";
+import {
+ loadSalesInvoices,
+ requirePostedShippingAccountId
+} from "../../../core/sales-invoice-source";
import {
type Accounting,
BaseEntitySyncer,
@@ -8,8 +21,15 @@ import {
} from "../../../core/types";
import { parseQboDate, type Qbo } from "../models";
import type { QboProvider } from "../provider";
+import {
+ loadQboInvoiceTaxCatalog,
+ type QboInvoiceTaxCatalog,
+ resolveQboInvoiceTax
+} from "./invoice-tax";
+import type { QboItemSyncer } from "./item";
import {
buildQboDocNumberFields,
+ loadQboAccountRefsById,
type QboDocNumberSource,
type QboWriteOmit,
updateWithSyncTokenRetry
@@ -43,39 +63,6 @@ const SYNCABLE_STATUSES: Accounting.SalesInvoice["status"][] = [
"Overdue"
];
-// Row shapes for sales invoice queries (mirror the Xero syncer's)
-type InvoiceRow = {
- id: string;
- invoiceId: string;
- companyId: string;
- customerId: string;
- status: Accounting.SalesInvoice["status"];
- currencyCode: string;
- exchangeRate: number;
- dateIssued: string | null;
- dateDue: string | null;
- datePaid: string | null;
- customerReference: string | null;
- subtotal: number;
- totalTax: number;
- totalDiscount: number;
- totalAmount: number;
- balance: number;
- updatedAt: string | null;
-};
-
-type InvoiceLineRow = {
- id: string;
- invoiceId: string;
- invoiceLineType: string;
- itemId: string | null;
- description: string | null;
- quantity: number;
- unitPrice: number;
- taxPercent: number;
- itemReadableIdWithRevision: string | null;
-};
-
/**
* Derive the Carbon invoice status from QBO's Balance/TotalAmt (QBO has no
* invoice status enum). Pure — exported for tests.
@@ -96,21 +83,50 @@ export function deriveCarbonInvoiceStatus(
* (resolved by ensureDependencySynced before mapping); lines without an
* item ship without an ItemRef.
*/
-export function buildQboInvoiceLines(
- lines: Accounting.SalesInvoiceLine[],
- itemRemoteIds: ReadonlyMap<string, string>
-): Array<Omit<Qbo.InvoiceLine, "Id">> {
- return lines.map((line) => {
- const remoteItemId = line.itemId ? itemRemoteIds.get(line.itemId) : null;
-
+export function buildQboInvoiceLines(args: {
+ document: SalesDocumentComponents;
+ itemRemoteIds: ReadonlyMap<string, string>;
+ shippingItemRemoteId: string | null;
+ lineTaxCodeRefs: ReadonlyMap<string, Qbo.Ref>;
+}): Array<Omit<Qbo.InvoiceLine, "Id">> {
+ return args.document.components.map((component) => {
+ const shipping =
+ component.kind === "LineShipping" || component.kind === "HeaderShipping";
+ const itemId = shipping
+ ? args.shippingItemRemoteId
+ : component.itemId
+ ? args.itemRemoteIds.get(component.itemId)
+ : null;
+ if ((shipping || component.itemId) && !itemId)
+ throw new JournalEntrySyncError({
+ errorCode: "UNMAPPED_ACCOUNTS",
+ warning: true,
+ message: `Invoice component ${component.id} has no QuickBooks item mapping`,
+ metadata: {
+ invoiceId: args.document.invoiceId,
+ componentId: component.id
+ }
+ });
+ const taxCode = args.lineTaxCodeRefs.get(component.id);
+ if (!taxCode)
+ throw new JournalEntrySyncError({
+ errorCode: "UNMAPPED_TAX_CODES",
+ warning: true,
+ message: `Invoice component ${component.id} has no resolved QuickBooks tax code`,
+ metadata: {
+ invoiceId: args.document.invoiceId,
+ componentId: component.id
+ }
+ });
return {
- Description: line.description ?? undefined,
- Amount: roundCurrency(line.quantity * line.unitPrice),
+ Description: component.description,
+ Amount: component.netAmount,
DetailType: "SalesItemLineDetail",
SalesItemLineDetail: {
- ItemRef: remoteItemId ? { value: remoteItemId } : undefined,
- Qty: line.quantity,
- UnitPrice: line.unitPrice
+ ItemRef: itemId ? { value: itemId } : undefined,
+ Qty: component.quantity,
+ UnitPrice: component.unitAmount,
+ TaxCodeRef: taxCode
}
};
});
@@ -121,6 +137,59 @@ export class QboSalesInvoiceSyncer extends BaseEntitySyncer<
Qbo.Invoice,
QboWriteOmit
> {
+ private taxCatalogPromise?: Promise<QboInvoiceTaxCatalog>;
+ private shippingAccountRefsPromise?: ReturnType<
+ typeof loadQboAccountRefsById
+ >;
+ private shippingItemSyncerPromise?: Promise<QboItemSyncer>;
+
+ private async getShippingAccountId(
+ local: Accounting.SalesInvoice
+ ): Promise<string> {
+ const id = requirePostedShippingAccountId(local);
+ this.shippingAccountRefsPromise ??= loadQboAccountRefsById(this.database, {
+ companyId: this.companyId,
+ integration: this.provider.id
+ }).catch((error) => {
+ this.shippingAccountRefsPromise = undefined;
+ throw error;
+ });
+ if (!(await this.shippingAccountRefsPromise).has(id))
+ throw new JournalEntrySyncError({
+ errorCode: "UNMAPPED_ACCOUNTS",
+ warning: true,
+ message:
+ "Cannot sync invoice: original Shipping Revenue account has no QuickBooks mapping",
+ metadata: { invoiceId: local.id, unmappedAccountIds: [id] }
+ });
+ return id;
+ }
+
+ private getShippingItemSyncer(): Promise<QboItemSyncer> {
+ if (!this.shippingItemSyncerPromise)
+ this.shippingItemSyncerPromise = (async () => {
+ const [{ SyncFactory }, { QboItemSyncer }] = await Promise.all([
+ import("../../../core/sync"),
+ import("./item")
+ ]);
+ const syncer = SyncFactory.getSyncer({
+ ...this.context,
+ entityType: "item",
+ config: this.provider.getSyncConfig("item") ?? {
+ enabled: true,
+ direction: "push-to-accounting",
+ owner: "carbon"
+ }
+ });
+ if (!(syncer instanceof QboItemSyncer))
+ throw new Error(
+ "QuickBooks shipping requires the existing item syncer"
+ );
+ return syncer;
+ })();
+ return this.shippingItemSyncerPromise;
+ }
+
// Bookkeeping for linkEntities: concurrency metadata per remote id and
// the DocNumber carrier per local id (recorded during mapToRemote)
private remoteMetaById = new Map<
@@ -176,7 +245,7 @@ export class QboSalesInvoiceSyncer extends BaseEntitySyncer<
// Also update updatedAt on salesInvoice (Xero-syncer parity)
await tx
.updateTable("salesInvoice")
- .set({ updatedAt: new Date().toISOString() })
+ .set({ updatedAt: datetime.timestamp() })
.where("id", "=", localId)
.execute();
}
@@ -204,111 +273,10 @@ export class QboSalesInvoiceSyncer extends BaseEntitySyncer<
return this.fetchInvoicesByIds(ids);
}
- private async fetchInvoicesByIds(
+ private fetchInvoicesByIds(
ids: string[]
): Promise<Map<string, Accounting.SalesInvoice>> {
- if (ids.length === 0) return new Map();
-
- const invoiceRows = await this.database
- .selectFrom("salesInvoice")
- // `balance` is derived and lives only on the `salesInvoices` view
- .leftJoin("salesInvoices", "salesInvoices.id", "salesInvoice.id")
- .select([
- "salesInvoice.id",
- "salesInvoice.invoiceId",
- "salesInvoice.companyId",
- "salesInvoice.customerId",
- "salesInvoice.status",
- "salesInvoice.currencyCode",
- "salesInvoice.exchangeRate",
- "salesInvoice.dateIssued",
- "salesInvoice.dateDue",
- "salesInvoice.datePaid",
- "salesInvoice.customerReference",
- "salesInvoice.subtotal",
- "salesInvoice.totalTax",
- "salesInvoice.totalDiscount",
- "salesInvoice.totalAmount",
- "salesInvoices.balance",
- "salesInvoice.updatedAt"
- ])
- .where("salesInvoice.id", "in", ids)
- .where("salesInvoice.companyId", "=", this.companyId)
- .execute();
-
- if (invoiceRows.length === 0) return new Map();
-
- const lineRows = await this.database
- .selectFrom("salesInvoiceLine")
- .leftJoin("item", "item.id", "salesInvoiceLine.itemId")
- .select([
- "salesInvoiceLine.id",
- "salesInvoiceLine.invoiceId",
- "salesInvoiceLine.invoiceLineType",
- "salesInvoiceLine.itemId",
- "salesInvoiceLine.description",
- "salesInvoiceLine.quantity",
- "salesInvoiceLine.unitPrice",
- "salesInvoiceLine.taxPercent",
- "item.readableIdWithRevision as itemReadableIdWithRevision"
- ])
- .where(
- "salesInvoiceLine.invoiceId",
- "in",
- invoiceRows.map((r) => r.id)
- )
- .execute();
-
- const linesByInvoiceId = new Map<string, InvoiceLineRow[]>();
- for (const line of lineRows as InvoiceLineRow[]) {
- const existing = linesByInvoiceId.get(line.invoiceId) ?? [];
- existing.push(line);
- linesByInvoiceId.set(line.invoiceId, existing);
- }
-
- const result = new Map<string, Accounting.SalesInvoice>();
- for (const row of invoiceRows as InvoiceRow[]) {
- const lines = linesByInvoiceId.get(row.id) ?? [];
-
- result.set(row.id, {
- id: row.id,
- invoiceId: row.invoiceId,
- companyId: row.companyId,
- customerId: row.customerId,
- customerExternalId: null, // Resolved during mapToRemote
- status: row.status,
- currencyCode: row.currencyCode,
- exchangeRate: Number(row.exchangeRate) || 1,
- dateIssued: row.dateIssued,
- dateDue: row.dateDue,
- datePaid: row.datePaid,
- customerReference: row.customerReference,
- subtotal: Number(row.subtotal) || 0,
- totalTax: Number(row.totalTax) || 0,
- totalDiscount: Number(row.totalDiscount) || 0,
- totalAmount: Number(row.totalAmount) || 0,
- balance: Number(row.balance) || 0,
- lines: lines.map((line) => {
- const quantity = Number(line.quantity) || 0;
- const unitPrice = Number(line.unitPrice) || 0;
- return {
- id: line.id,
- invoiceLineType: line.invoiceLineType,
- itemId: line.itemId,
- itemCode: line.itemReadableIdWithRevision,
- description: line.description,
- quantity,
- unitPrice,
- taxPercent: Number(line.taxPercent) || 0,
- lineAmount: quantity * unitPrice
- };
- }),
- updatedAt: row.updatedAt ?? new Date().toISOString(),
- raw: row
- });
- }
-
- return result;
+ return loadSalesInvoices(this.database, { companyId: this.companyId, ids });
}
// =================================================================
@@ -339,34 +307,74 @@ export class QboSalesInvoiceSyncer extends BaseEntitySyncer<
protected async mapToRemote(
local: Accounting.SalesInvoice
): Promise<Omit<Qbo.Invoice, QboWriteOmit>> {
- // JIT dependencies: customer, then every line item, before the document
+ const document = buildSalesDocumentComponents(local);
+ const remoteExchangeRate = 1 / local.exchangeRate;
+ if (!Number.isFinite(remoteExchangeRate))
+ throw new Error("QuickBooks exchange rate must be finite");
+ let catalog: QboInvoiceTaxCatalog;
+ try {
+ this.taxCatalogPromise ??= loadQboInvoiceTaxCatalog(
+ this.qboProvider
+ ).catch((error) => {
+ this.taxCatalogPromise = undefined;
+ throw error;
+ });
+ catalog = await this.taxCatalogPromise;
+ } catch (error) {
+ throw new JournalEntrySyncError({
+ errorCode: "UNMAPPED_TAX_CODES",
+ warning: true,
+ message: `Cannot read QuickBooks tax configuration: ${error instanceof Error ? error.message : String(error)}`,
+ metadata: {
+ invoiceId: local.id,
+ requestedRates: [
+ ...new Set(document.components.map((line) => line.taxPercent))
+ ],
+ candidateTaxCodeIds: [],
+ reason: "Tax catalog unavailable"
+ }
+ });
+ }
+ const tax = resolveQboInvoiceTax({ document, catalog });
+ const hasShipping = document.components.some(
+ (line) => line.kind === "LineShipping" || line.kind === "HeaderShipping"
+ );
+ const shippingAccountId = hasShipping
+ ? await this.getShippingAccountId(local)
+ : null;
+ // Tax, account and currency preflight finishes before any dependency writes.
const customerRemoteId = await this.ensureDependencySynced(
"customer",
local.customerId
);
-
const itemRemoteIds = new Map<string, string>();
- for (const line of local.lines) {
- if (line.itemId && !itemRemoteIds.has(line.itemId)) {
- itemRemoteIds.set(
- line.itemId,
- await this.ensureDependencySynced("item", line.itemId)
- );
- }
- }
-
- // Due date: use dateDue if provided, otherwise default to Net 30
- // (Xero-syncer parity)
- let dueDate = local.dateDue;
- if (!dueDate && local.dateIssued) {
- const issued = new Date(local.dateIssued);
- issued.setDate(issued.getDate() + 30);
- dueDate = issued.toISOString().split("T")[0];
- } else if (!dueDate) {
- const now = new Date();
- now.setDate(now.getDate() + 30);
- dueDate = now.toISOString().split("T")[0];
- }
+ const itemIds = [
+ ...new Set(
+ document.components
+ .filter(
+ (line) =>
+ line.kind !== "LineShipping" &&
+ line.kind !== "HeaderShipping" &&
+ line.itemId
+ )
+ .map((line) => line.itemId!)
+ )
+ ];
+ for (const itemId of itemIds)
+ itemRemoteIds.set(
+ itemId,
+ await this.ensureDependencySynced("item", itemId)
+ );
+ const shippingItemRemoteId = shippingAccountId
+ ? await (await this.getShippingItemSyncer()).ensureShippingItem({
+ shippingAccountId
+ })
+ : null;
+ const dueDate =
+ local.dateDue ??
+ parseDate(toPostingDateString(local.dateIssued ?? datetime.timestamp()))
+ .add({ days: 30 })
+ .toString();
const docNumber = buildQboDocNumberFields(local.invoiceId);
this.docNumberSourceByLocalId.set(local.id, docNumber.source);
@@ -377,7 +385,18 @@ export class QboSalesInvoiceSyncer extends BaseEntitySyncer<
TxnDate: local.dateIssued ?? undefined,
DueDate: dueDate,
CustomerRef: { value: customerRemoteId },
- Line: buildQboInvoiceLines(local.lines, itemRemoteIds)
+ CurrencyRef: { value: document.currencyCode },
+ ExchangeRate: remoteExchangeRate,
+ ...(catalog.country.toUpperCase() === "US"
+ ? {}
+ : { GlobalTaxCalculation: "TaxExcluded" as const }),
+ TxnTaxDetail: tax.txnTaxDetail,
+ Line: buildQboInvoiceLines({
+ document,
+ itemRemoteIds,
+ shippingItemRemoteId,
+ lineTaxCodeRefs: tax.lineTaxCodeRefs
+ })
};
}
@@ -398,6 +417,9 @@ export class QboSalesInvoiceSyncer extends BaseEntitySyncer<
description: line.Description ?? null,
quantity: line.SalesItemLineDetail?.Qty ?? 0,
unitPrice: line.SalesItemLineDetail?.UnitPrice ?? 0,
+ shippingCost: 0,
+ addOnCost: 0,
+ nonTaxableAddOnCost: 0,
taxPercent: 0,
lineAmount: line.Amount
}));
@@ -436,7 +458,7 @@ export class QboSalesInvoiceSyncer extends BaseEntitySyncer<
dateIssued: data.dateIssued,
dateDue: data.dateDue,
totalAmount: data.totalAmount,
- updatedAt: new Date().toISOString()
+ updatedAt: datetime.timestamp()
})
.where("id", "=", existingLocalId)
.execute();
diff --git a/packages/ee/src/accounting/providers/quickbooks-online/entities/item.ts b/packages/ee/src/accounting/providers/quickbooks-online/entities/item.ts
index 77a1615f71..8be8452726 100644
--- a/packages/ee/src/accounting/providers/quickbooks-online/entities/item.ts
+++ b/packages/ee/src/accounting/providers/quickbooks-online/entities/item.ts
@@ -1,7 +1,10 @@
import type { KyselyTx } from "@carbon/database/client";
+import { createMappingService } from "../../../core/external-mapping";
import { JournalEntrySyncError } from "../../../core/posting";
import type { Accounting } from "../../../core/types";
+import { withTriggersDisabled } from "../../../core/utils";
import type { Qbo, QboCreatePayload } from "../models";
+import { isQboDuplicateNameError } from "../provider";
import {
escapeQboQueryValue,
loadQboAccountRefsById,
@@ -143,6 +146,121 @@ export function mapItemToQboItem(args: {
}
export class QboItemSyncer extends QboEntitySyncer<Accounting.Item, Qbo.Item> {
+ private shippingItems = new Map<string, Promise<string>>();
+
+ public async ensureShippingItem(args: {
+ shippingAccountId: string;
+ }): Promise<string> {
+ let pending = this.shippingItems.get(args.shippingAccountId);
+ if (!pending) {
+ pending = this.resolveShippingItem(args.shippingAccountId).catch(
+ (error) => {
+ this.shippingItems.delete(args.shippingAccountId);
+ throw error;
+ }
+ );
+ this.shippingItems.set(args.shippingAccountId, pending);
+ }
+ return pending;
+ }
+
+ private async resolveShippingItem(
+ shippingAccountId: string
+ ): Promise<string> {
+ const incomeRef = (await this.getAccountRefsById()).get(shippingAccountId);
+ const fail = (reason: string): never => {
+ throw new JournalEntrySyncError({
+ errorCode: "UNMAPPED_ACCOUNTS",
+ warning: true,
+ message: `Cannot provision Shipping Revenue item: ${reason}`,
+ metadata: { accountId: shippingAccountId, kind: "shipping" }
+ });
+ };
+ if (!incomeRef) fail("the shipping account has no QuickBooks mapping");
+ const name = `Carbon Shipping ${shippingAccountId}`;
+ if (name.length > QBO_NAME_MAX_LENGTH)
+ throw qboNameTooLongError({ entityLabel: "shipping item", name });
+ const payload: QboCreatePayload<Qbo.Item> = {
+ Name: name,
+ Description: "Customer shipping charges",
+ Type: "Service",
+ Active: true,
+ UnitPrice: 0,
+ IncomeAccountRef: incomeRef
+ };
+ const compatible = (item: Qbo.Item, requireAccount = true) => {
+ if (
+ item.Name !== name ||
+ item.Type !== "Service" ||
+ item.Active === false ||
+ (requireAccount && item.IncomeAccountRef?.value !== incomeRef!.value)
+ ) {
+ fail(
+ "an existing helper has an incompatible name, type, active state or revenue account"
+ );
+ }
+ return item;
+ };
+ const mappedId = await this.mappingService.getExternalId(
+ "shippingItem",
+ shippingAccountId,
+ this.provider.id
+ );
+ if (mappedId) {
+ const current = await this.qboProvider.getItem(mappedId);
+ if (!current) fail("the mapped helper no longer exists in QuickBooks");
+ compatible(current!, false);
+ if (
+ current!.IncomeAccountRef?.value !== incomeRef!.value ||
+ current!.UnitPrice !== 0
+ ) {
+ // Only an explicitly owned mapping may be reconverged. An unowned name
+ // match below is validated and never overwritten.
+ const updated = await updateWithSyncTokenRetry({
+ entityLabel: "shipping item",
+ remoteId: mappedId,
+ fetchCurrent: () => this.qboProvider.getItem(mappedId),
+ update: (syncToken) =>
+ this.qboProvider.updateItem({
+ ...payload,
+ Id: mappedId,
+ SyncToken: syncToken
+ })
+ });
+ return compatible(updated).Id;
+ }
+ return current!.Id;
+ }
+ const lookup = async () => {
+ const matches = await this.qboProvider.query<Qbo.Item>(
+ "Item",
+ `Name = '${escapeQboQueryValue(name)}'`
+ );
+ if (matches.length > 1) fail("the exact remote helper name is ambiguous");
+ return matches[0] ? compatible(matches[0]) : undefined;
+ };
+ let remote = await lookup();
+ if (!remote) {
+ try {
+ remote = compatible(await this.qboProvider.createItem(payload));
+ } catch (error) {
+ if (!isQboDuplicateNameError(error)) throw error;
+ remote = await lookup();
+ if (!remote) throw error;
+ }
+ }
+ await withTriggersDisabled(this.database, async (tx) => {
+ await createMappingService(tx, this.companyId).link(
+ "shippingItem",
+ shippingAccountId,
+ this.provider.id,
+ remote!.Id,
+ { metadata: { accountId: shippingAccountId, kind: "shipping" } }
+ );
+ });
+ return remote.Id;
+ }
+
// Cached per instance — a drain reuses one syncer across its claimed
// operations, so mappings and account defaults are fetched at most once
private accountRefsByIdPromise?: Promise<Map<string, Qbo.Ref>>;
diff --git a/packages/ee/src/accounting/providers/quickbooks-online/entities/payment.ts b/packages/ee/src/accounting/providers/quickbooks-online/entities/payment.ts
index 7d498e7ca7..c614bb9f84 100644
--- a/packages/ee/src/accounting/providers/quickbooks-online/entities/payment.ts
+++ b/packages/ee/src/accounting/providers/quickbooks-online/entities/payment.ts
@@ -276,7 +276,8 @@ export class QboPaymentSyncer extends PaymentSyncerBase<QboPayment> {
paymentRemoteId,
amount: totalAmt,
currencyCode: remote.CurrencyRef?.value ?? null,
- exchangeRate: remote.ExchangeRate ?? 1,
+ exchangeRate:
+ remote.ExchangeRate == null ? null : 1 / remote.ExchangeRate,
paidDate,
// The QBO (bill) payment Id is the human/provider reference.
reference: paymentRemoteId,
diff --git a/packages/ee/src/accounting/providers/quickbooks-online/models.ts b/packages/ee/src/accounting/providers/quickbooks-online/models.ts
index 5764597147..2f7bf8622f 100644
--- a/packages/ee/src/accounting/providers/quickbooks-online/models.ts
+++ b/packages/ee/src/accounting/providers/quickbooks-online/models.ts
@@ -101,7 +101,65 @@ export namespace Qbo {
export type Item = z.infer<typeof ItemSchema>;
+ export const TaxRateDetailSchema = z.object({
+ TaxRateRef: RefSchema,
+ TaxTypeApplicable: z.string().optional(),
+ TaxOrder: z.number().optional(),
+ TaxOnTaxOrder: z.number().optional()
+ });
+ export const TaxRateListSchema = z.object({
+ TaxRateDetail: z.array(TaxRateDetailSchema)
+ });
+ export const TaxCodeSchema = z.object({
+ Id: z.string(),
+ Name: z.string().optional(),
+ Active: z.boolean().optional(),
+ Taxable: z.boolean().optional(),
+ TaxGroup: z.boolean().optional(),
+ SalesTaxRateList: TaxRateListSchema.optional(),
+ PurchaseTaxRateList: TaxRateListSchema.optional()
+ });
+ export type TaxCode = z.infer<typeof TaxCodeSchema>;
+ export const TaxRateSchema = z.object({
+ Id: z.string(),
+ Name: z.string().optional(),
+ Active: z.boolean().optional(),
+ RateValue: z.number().optional(),
+ SpecialTaxType: z.string().optional(),
+ EffectiveTaxRate: z
+ .array(
+ z
+ .object({
+ EffectiveDate: z.string().optional(),
+ RateValue: z.number().optional()
+ })
+ .passthrough()
+ )
+ .optional()
+ });
+ export type TaxRate = z.infer<typeof TaxRateSchema>;
+ export const TaxLineDetailSchema = z.object({
+ TaxRateRef: RefSchema,
+ NetAmountTaxable: z.number(),
+ PercentBased: z.literal(true),
+ TaxPercent: z.number()
+ });
+ export type TaxLineDetail = z.infer<typeof TaxLineDetailSchema>;
+ export const TxnTaxDetailSchema = z.object({
+ TxnTaxCodeRef: RefSchema.optional(),
+ TotalTax: z.number(),
+ TaxLine: z.array(
+ z.object({
+ Amount: z.number(),
+ DetailType: z.literal("TaxLineDetail"),
+ TaxLineDetail: TaxLineDetailSchema
+ })
+ )
+ });
+ export type TxnTaxDetail = z.infer<typeof TxnTaxDetailSchema>;
+
export const SalesItemLineDetailSchema = z.object({
+ TaxCodeRef: RefSchema.optional(),
ItemRef: RefSchema.optional(),
Qty: z.number().optional(),
UnitPrice: z.number().optional()
@@ -125,6 +183,12 @@ export namespace Qbo {
export type InvoiceLine = z.infer<typeof InvoiceLineSchema>;
export const InvoiceSchema = z.object({
+ TxnTaxDetail: TxnTaxDetailSchema.optional(),
+ CurrencyRef: RefSchema.optional(),
+ ExchangeRate: z.number().optional(),
+ GlobalTaxCalculation: z
+ .enum(["TaxExcluded", "TaxInclusive", "NotApplicable"])
+ .optional(),
Id: z.string(),
SyncToken: z.string(),
/** QBO caps DocNumber at 21 characters. */
diff --git a/packages/ee/src/accounting/providers/rillet/__tests__/provider.test.ts b/packages/ee/src/accounting/providers/rillet/__tests__/provider.test.ts
index a631059ddb..92db2153a2 100644
--- a/packages/ee/src/accounting/providers/rillet/__tests__/provider.test.ts
+++ b/packages/ee/src/accounting/providers/rillet/__tests__/provider.test.ts
@@ -699,3 +699,34 @@ describe("listChanges (SupportsIncrementalPull)", () => {
]);
});
});
+
+describe("Rillet native void deletion", () => {
+ it.each([
+ ["deleteInvoice", ["inv-1"], "/invoices/inv-1"],
+ ["deleteBill", ["bill-1"], "/bills/bill-1"],
+ [
+ "deleteInvoicePayment",
+ ["inv-1", "pay-1"],
+ "/invoices/inv-1/payments/pay-1"
+ ],
+ ["deleteBillPayment", ["bill-1", "pay-1"], "/bills/bill-1/payments/pay-1"]
+ ] as const)("%s uses the native endpoint and tolerates only an already absent record", async (method, ids, path) => {
+ const provider = makeProvider();
+ fetchMock.mockResolvedValueOnce(new Response(null, { status: 204 }));
+ await (provider[method] as (...ids: string[]) => Promise<void>)(...ids);
+ expect(requestUrl(0)).toBe(`https://api.rillet.com${path}`);
+ expect(requestInit(0)?.method).toBe("DELETE");
+ fetchMock.mockResolvedValueOnce(
+ jsonResponse({ message: "Not found" }, 404)
+ );
+ await expect(
+ (provider[method] as (...ids: string[]) => Promise<void>)(...ids)
+ ).resolves.toBeUndefined();
+ fetchMock.mockResolvedValueOnce(
+ jsonResponse({ message: "Payment is cleared" }, 400)
+ );
+ await expect(
+ (provider[method] as (...ids: string[]) => Promise<void>)(...ids)
+ ).rejects.toThrow();
+ });
+});
diff --git a/packages/ee/src/accounting/providers/rillet/entities/__tests__/bill.test.ts b/packages/ee/src/accounting/providers/rillet/entities/__tests__/bill.test.ts
index 0a18bb8382..a7a56fd4ff 100644
--- a/packages/ee/src/accounting/providers/rillet/entities/__tests__/bill.test.ts
+++ b/packages/ee/src/accounting/providers/rillet/entities/__tests__/bill.test.ts
@@ -1,7 +1,9 @@
import { describe, expect, it } from "vitest";
import { JournalEntrySyncError } from "../../../../core/posting";
import type { Accounting } from "../../../../core/types";
+import { Rillet } from "../../models";
import { type BillPostingJournalLine, mapBillToRilletBill } from "../bill";
+import { toRilletExchangeRate } from "../shared";
// The bill's G/L costing comes from its posted Purchase Invoice journal
// (item-backed invoice lines carry no account of their own): journal lines
@@ -31,33 +33,30 @@ const bill = (): Accounting.Bill =>
}) as unknown as Accounting.Bill;
const journalLines: BillPostingJournalLine[] = [
- // Debit-signed: GR/IR clearing debit +300, AP credit -300
+ // Debit-signed costing: GR/IR clearing debit +300; loader excluded AP.
{
id: "jl-1",
accountId: "acct_grir",
amount: 300,
description: "GR/IR Clearing"
- },
- {
- id: "jl-2",
- accountId: "acct_ap",
- amount: -300,
- description: "Accounts Payable"
}
];
const codes = new Map([["acct_grir", "2125"]]);
describe("mapBillToRilletBill (journal-derived costing)", () => {
- it("builds items from the posting journal minus the AP control line", () => {
+ it("builds items from the loader's costing-only rows", () => {
const payload = mapBillToRilletBill({
+ documentTotal: 300,
+ decimalPlaces: 2,
+ baseCurrencyCode: "USD",
+ postingDate: "2026-09-07",
bill: bill(),
vendorRemoteId: "vendor-remote-1",
accountCodesById: codes,
subsidiaryId: null,
companyId: "company-1",
- postingJournalLines: journalLines,
- payablesAccountId: "acct_ap"
+ postingJournalLines: journalLines
});
expect(payload.vendor_id).toBe("vendor-remote-1");
@@ -74,24 +73,30 @@ describe("mapBillToRilletBill (journal-derived costing)", () => {
it("warns when the invoice has no posted journal", () => {
expect(() =>
mapBillToRilletBill({
+ documentTotal: 300,
+ decimalPlaces: 2,
+ baseCurrencyCode: "USD",
+ postingDate: "2026-09-07",
bill: bill(),
vendorRemoteId: "vendor-remote-1",
accountCodesById: codes,
subsidiaryId: null,
companyId: "company-1",
- postingJournalLines: [],
- payablesAccountId: "acct_ap"
+ postingJournalLines: []
})
).toThrowError(JournalEntrySyncError);
try {
mapBillToRilletBill({
+ documentTotal: 300,
+ decimalPlaces: 2,
+ baseCurrencyCode: "USD",
+ postingDate: "2026-09-07",
bill: bill(),
vendorRemoteId: "vendor-remote-1",
accountCodesById: codes,
subsidiaryId: null,
companyId: "company-1",
- postingJournalLines: [],
- payablesAccountId: "acct_ap"
+ postingJournalLines: []
});
} catch (error) {
expect((error as JournalEntrySyncError).failure.message).toContain(
@@ -101,16 +106,19 @@ describe("mapBillToRilletBill (journal-derived costing)", () => {
}
});
- it("warns on unmapped costing accounts (AP line still excluded)", () => {
+ it("warns on unmapped costing accounts (costing-only input)", () => {
try {
mapBillToRilletBill({
+ documentTotal: 300,
+ decimalPlaces: 2,
+ baseCurrencyCode: "USD",
+ postingDate: "2026-09-07",
bill: bill(),
vendorRemoteId: "vendor-remote-1",
accountCodesById: new Map(),
subsidiaryId: null,
companyId: "company-1",
- postingJournalLines: journalLines,
- payablesAccountId: "acct_ap"
+ postingJournalLines: journalLines
});
expect.unreachable("should have thrown");
} catch (error) {
@@ -122,6 +130,10 @@ describe("mapBillToRilletBill (journal-derived costing)", () => {
it("keeps variance/tax lines as additional items", () => {
const payload = mapBillToRilletBill({
+ documentTotal: 300,
+ decimalPlaces: 2,
+ baseCurrencyCode: "USD",
+ postingDate: "2026-09-07",
bill: bill(),
vendorRemoteId: "vendor-remote-1",
accountCodesById: new Map([
@@ -142,15 +154,8 @@ describe("mapBillToRilletBill (journal-derived costing)", () => {
accountId: "acct_ppv",
amount: 20,
description: "Purchase Price Variance"
- },
- {
- id: "jl-3",
- accountId: "acct_ap",
- amount: -300,
- description: "Accounts Payable"
}
- ],
- payablesAccountId: "acct_ap"
+ ]
});
expect(payload.items.map((i) => [i.account_code, i.amount.amount])).toEqual(
@@ -165,6 +170,10 @@ describe("mapBillToRilletBill (journal-derived costing)", () => {
describe("mapBillToRilletBill — item labels + FX (representation model)", () => {
it("prepends the item code/name label to PO-backed line descriptions", () => {
const payload = mapBillToRilletBill({
+ documentTotal: 300,
+ decimalPlaces: 2,
+ baseCurrencyCode: "USD",
+ postingDate: "2026-09-07",
bill: bill(),
vendorRemoteId: "vendor-remote-1",
accountCodesById: codes,
@@ -178,8 +187,7 @@ describe("mapBillToRilletBill — item labels + FX (representation model)", () =
description: "GR/IR Clearing",
sourceItem: { id: "item-1", code: "WIDGET-1", name: "Widget" }
}
- ],
- payablesAccountId: "acct_ap"
+ ]
});
expect(payload.items[0]?.description).toBe(
@@ -196,6 +204,10 @@ describe("mapBillToRilletBill — item labels + FX (representation model)", () =
it("uses the item label alone when the line has no journal description", () => {
const payload = mapBillToRilletBill({
+ documentTotal: 300,
+ decimalPlaces: 2,
+ baseCurrencyCode: "USD",
+ postingDate: "2026-09-07",
bill: bill(),
vendorRemoteId: "vendor-remote-1",
accountCodesById: codes,
@@ -209,8 +221,7 @@ describe("mapBillToRilletBill — item labels + FX (representation model)", () =
description: null,
sourceItem: { id: "item-1", code: "WIDGET-1", name: null }
}
- ],
- payablesAccountId: "acct_ap"
+ ]
});
expect(payload.items[0]?.description).toBe("WIDGET-1");
});
@@ -219,10 +230,14 @@ describe("mapBillToRilletBill — item labels + FX (representation model)", () =
const fxBill = {
...bill(),
currencyCode: "EUR",
- exchangeRate: 2
+ exchangeRate: 0.8
} as unknown as Accounting.Bill;
const payload = mapBillToRilletBill({
+ documentTotal: 224,
+ decimalPlaces: 2,
+ baseCurrencyCode: "USD",
+ postingDate: "2026-09-07",
bill: fxBill,
vendorRemoteId: "vendor-remote-1",
accountCodesById: new Map([
@@ -231,7 +246,7 @@ describe("mapBillToRilletBill — item labels + FX (representation model)", () =
]),
subsidiaryId: null,
companyId: "company-1",
- // base-currency debit-signed amounts (rate 2 → half in EUR)
+ // Base-currency debit-signed amounts convert once by multiplication.
postingJournalLines: [
{
id: "jl-1",
@@ -245,14 +260,18 @@ describe("mapBillToRilletBill — item labels + FX (representation model)", () =
amount: -20,
description: "Purchase Price Variance"
}
- ],
- payablesAccountId: "acct_ap"
+ ]
});
- expect(payload.exchange_rate).toBe(2);
+ expect(payload.exchange_rate).toEqual({
+ base: "EUR",
+ target: "USD",
+ rate: "1.25",
+ date: "2026-09-07"
+ });
expect(payload.items.map((i) => [i.account_code, i.amount])).toEqual([
- ["2125", { amount: "150.00", currency: "EUR" }],
- ["5210", { amount: "-10.00", currency: "EUR" }]
+ ["2125", { amount: "240.00", currency: "EUR" }],
+ ["5210", { amount: "-16.00", currency: "EUR" }]
]);
});
});
@@ -268,14 +287,6 @@ describe("mapBillToRilletBill — dimensions (Fields)", () => {
amount: 300,
description: "GR/IR Clearing",
dimensions: [{ dimensionId: LOCATION_DIM, valueId: "loc_hq" }]
- },
- {
- id: "jl-2",
- accountId: "acct_ap",
- amount: -300,
- description: "Accounts Payable",
- // AP control line dimensions never push (the line itself is excluded)
- dimensions: [{ dimensionId: LOCATION_DIM, valueId: "loc_other" }]
}
];
@@ -283,13 +294,16 @@ describe("mapBillToRilletBill — dimensions (Fields)", () => {
it("attaches uuid field refs to items from their posting journal line dimensions", () => {
const payload = mapBillToRilletBill({
+ documentTotal: 300,
+ decimalPlaces: 2,
+ baseCurrencyCode: "USD",
+ postingDate: "2026-09-07",
bill: bill(),
vendorRemoteId: "vendor-remote-1",
accountCodesById: codes,
subsidiaryId: null,
companyId: "company-1",
postingJournalLines: dimensionedLines,
- payablesAccountId: "acct_ap",
dimensions: {
fieldIdByDimensionId,
fieldValueIdsByValue: new Map([["dim_loc:loc_hq", "fv-hq"]])
@@ -304,31 +318,41 @@ describe("mapBillToRilletBill — dimensions (Fields)", () => {
it("omits fields for unmapped values (drop path) and when no dimension args are passed", () => {
const dropped = mapBillToRilletBill({
+ documentTotal: 300,
+ decimalPlaces: 2,
+ baseCurrencyCode: "USD",
+ postingDate: "2026-09-07",
bill: bill(),
vendorRemoteId: "vendor-remote-1",
accountCodesById: codes,
subsidiaryId: null,
companyId: "company-1",
postingJournalLines: dimensionedLines,
- payablesAccountId: "acct_ap",
dimensions: { fieldIdByDimensionId, fieldValueIdsByValue: new Map() }
});
expect(dropped.items[0]?.fields).toBeUndefined();
const withoutArgs = mapBillToRilletBill({
+ documentTotal: 300,
+ decimalPlaces: 2,
+ baseCurrencyCode: "USD",
+ postingDate: "2026-09-07",
bill: bill(),
vendorRemoteId: "vendor-remote-1",
accountCodesById: codes,
subsidiaryId: null,
companyId: "company-1",
- postingJournalLines: dimensionedLines,
- payablesAccountId: "acct_ap"
+ postingJournalLines: dimensionedLines
});
expect(withoutArgs.items[0]?.fields).toBeUndefined();
});
it("omits a dimension whose Field was not provisioned (no field mapping)", () => {
const payload = mapBillToRilletBill({
+ documentTotal: 300,
+ decimalPlaces: 2,
+ baseCurrencyCode: "USD",
+ postingDate: "2026-09-07",
bill: bill(),
vendorRemoteId: "vendor-remote-1",
accountCodesById: codes,
@@ -343,7 +367,6 @@ describe("mapBillToRilletBill — dimensions (Fields)", () => {
dimensions: [{ dimensionId: "dim_unprovisioned", valueId: "v1" }]
}
],
- payablesAccountId: "acct_ap",
dimensions: {
fieldIdByDimensionId, // only LOCATION_DIM is mapped
fieldValueIdsByValue: new Map([["dim_unprovisioned:v1", "fv-x"]])
@@ -352,3 +375,77 @@ describe("mapBillToRilletBill — dimensions (Fields)", () => {
expect(payload.items[0]?.fields).toBeUndefined();
});
});
+
+describe("Rillet bill currency contract", () => {
+ it("serializes the directed exchange-rate object without money rounding", () => {
+ const rate = toRilletExchangeRate({
+ baseCurrencyCode: "USD",
+ documentCurrencyCode: "EUR",
+ foreignPerBaseRate: 0.8,
+ date: "2026-09-07"
+ });
+ expect(Rillet.ExchangeRateSchema.parse(rate)).toEqual({
+ base: "EUR",
+ target: "USD",
+ rate: "1.25",
+ date: "2026-09-07"
+ });
+ expect(
+ toRilletExchangeRate({
+ baseCurrencyCode: "USD",
+ documentCurrencyCode: "USD",
+ foreignPerBaseRate: 1,
+ date: "2026-09-07"
+ })
+ ).toBeUndefined();
+ expect(() =>
+ toRilletExchangeRate({
+ baseCurrencyCode: "USD",
+ documentCurrencyCode: "USD",
+ foreignPerBaseRate: 2,
+ date: "2026-09-07"
+ })
+ ).toThrow();
+ });
+ it.each([
+ 0.8, 1.2, 1
+ ])("preserves USD base principal at foreign rate %s", (rate) => {
+ const result = toRilletExchangeRate({
+ baseCurrencyCode: "USD",
+ documentCurrencyCode: "EUR",
+ foreignPerBaseRate: rate,
+ date: "2026-09-09"
+ });
+ expect(result).toMatchObject({ base: "EUR", target: "USD" });
+ expect(100 * rate * Number(result?.rate)).toBeCloseTo(100, 12);
+ });
+ it.each([
+ [0, "80"],
+ [3, "80.003"]
+ ])("serializes bill currency decimal scale %i", (decimalPlaces, expected) => {
+ const total = Number(expected);
+ const payload = mapBillToRilletBill({
+ bill: { ...bill(), currencyCode: "EUR", exchangeRate: 0.8 },
+ vendorRemoteId: "v",
+ accountCodesById: codes,
+ subsidiaryId: null,
+ companyId: "company-1",
+ postingJournalLines: [
+ {
+ id: "j",
+ accountId: "acct_grir",
+ amount: total / 0.8,
+ description: null
+ }
+ ],
+ documentTotal: total,
+ decimalPlaces,
+ baseCurrencyCode: "USD",
+ postingDate: "2026-09-07"
+ });
+ expect(payload.items[0]?.amount).toEqual({
+ amount: expected,
+ currency: "EUR"
+ });
+ });
+});
diff --git a/packages/ee/src/accounting/providers/rillet/entities/__tests__/document-void.test.ts b/packages/ee/src/accounting/providers/rillet/entities/__tests__/document-void.test.ts
new file mode 100644
index 0000000000..def63f1022
--- /dev/null
+++ b/packages/ee/src/accounting/providers/rillet/entities/__tests__/document-void.test.ts
@@ -0,0 +1,103 @@
+import { describe, expect, it, vi } from "vitest";
+import { RilletBillSyncer } from "../bill";
+import { RilletSalesInvoiceSyncer } from "../invoice";
+
+const { linked } = vi.hoisted(() => ({ linked: [] as unknown[] }));
+vi.mock("../../../../core/utils", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("../../../../core/utils")>()),
+ withTriggersDisabled: async (
+ _db: unknown,
+ cb: (tx: unknown) => Promise<unknown>
+ ) => {
+ const b = {
+ values: (row: unknown) => {
+ linked.push(row);
+ return b;
+ },
+ onConflict: () => b,
+ execute: async () => []
+ };
+ return cb({ insertInto: () => b });
+ }
+}));
+
+describe.each([
+ ["invoice", RilletSalesInvoiceSyncer],
+ ["bill", RilletBillSyncer]
+] as const)("Rillet %s void", (entityType, Syncer) => {
+ function setup(status: string, mapping: unknown, failure?: Error) {
+ linked.length = 0;
+ const deletion = failure
+ ? vi.fn().mockRejectedValue(failure)
+ : vi.fn().mockResolvedValue(undefined);
+ const syncer = new Syncer({
+ database: {} as never,
+ companyId: "company-1",
+ entityType,
+ config: {
+ enabled: true,
+ direction: "push-to-accounting",
+ owner: "carbon"
+ },
+ provider: {
+ id: "rillet",
+ deleteInvoice: deletion,
+ deleteBill: deletion
+ } as never
+ });
+ vi.spyOn(syncer, "fetchLocal").mockResolvedValue({
+ id: "doc-1",
+ status
+ } as never);
+ (syncer as any).mappingService = { getByEntity: async () => mapping };
+ return { syncer, deletion };
+ }
+ it("propagates a mapped void before the existing mapping fast bailout", async () => {
+ const { syncer, deletion } = setup("Voided", {
+ externalId: "remote-1",
+ metadata: { retained: true }
+ });
+ expect(await syncer.pushToAccounting("doc-1")).toMatchObject({
+ status: "success",
+ action: "deleted",
+ remoteId: "remote-1"
+ });
+ expect(deletion).toHaveBeenCalledWith("remote-1");
+ expect(linked[0]).toMatchObject({
+ entityId: "doc-1",
+ externalId: "remote-1",
+ metadata: { retained: true, voided: true }
+ });
+ });
+ it("skips repeat deletes after the durable marker", async () => {
+ const { syncer, deletion } = setup("Voided", {
+ externalId: "remote-1",
+ metadata: { voided: true }
+ });
+ expect(await syncer.pushToAccounting("doc-1")).toMatchObject({
+ status: "success",
+ action: "deleted"
+ });
+ expect(deletion).not.toHaveBeenCalled();
+ });
+ it("does not hide failed remote deletion behind the old mapping", async () => {
+ const { syncer } = setup(
+ "Voided",
+ { externalId: "remote-1" },
+ new Error("document has payments")
+ );
+ expect(await syncer.pushToAccounting("doc-1")).toMatchObject({
+ status: "error",
+ error: "document has payments"
+ });
+ expect(linked).toHaveLength(0);
+ });
+ it("keeps ordinary posted replay immutable", async () => {
+ const { syncer, deletion } = setup("Submitted", { externalId: "remote-1" });
+ expect(await syncer.pushToAccounting("doc-1")).toMatchObject({
+ status: "skipped",
+ remoteId: "remote-1"
+ });
+ expect(deletion).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/ee/src/accounting/providers/rillet/entities/__tests__/invoice.test.ts b/packages/ee/src/accounting/providers/rillet/entities/__tests__/invoice.test.ts
index 606fd126ba..a0123ba468 100644
--- a/packages/ee/src/accounting/providers/rillet/entities/__tests__/invoice.test.ts
+++ b/packages/ee/src/accounting/providers/rillet/entities/__tests__/invoice.test.ts
@@ -1,6 +1,13 @@
-import { describe, expect, it } from "vitest";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { buildSalesDocumentComponents } from "../../../../core/sales-document-components";
+import { SyncFactory } from "../../../../core/sync";
import type { Accounting } from "../../../../core/types";
-import { mapSalesInvoiceToRilletInvoice } from "../invoice";
+import { Rillet } from "../../models";
+import {
+ mapSalesInvoiceToRilletInvoice,
+ RilletSalesInvoiceSyncer
+} from "../invoice";
+import { RilletItemSyncer } from "../item";
import { RILLET_CUSTOMER_CUSTOM_REFERENCE_TYPE } from "../shared";
function invoice(): Accounting.SalesInvoice {
@@ -12,6 +19,11 @@ function invoice(): Accounting.SalesInvoice {
customerExternalId: "rillet-cust-1",
status: "Submitted",
currencyCode: "USD",
+ baseCurrencyCode: "USD",
+ baseCurrencyDecimalPlaces: 2,
+ currencyDecimalPlaces: 2,
+ headerShippingCost: 0,
+ shippingRevenueAccountId: "acct-shipping",
exchangeRate: 1,
dateIssued: "2026-08-12",
dateDue: "2026-09-11",
@@ -31,6 +43,9 @@ function invoice(): Accounting.SalesInvoice {
description: "Widget",
quantity: 2,
unitPrice: 50,
+ shippingCost: 0,
+ addOnCost: 0,
+ nonTaxableAddOnCost: 0,
taxPercent: 0,
lineAmount: 100
}
@@ -43,6 +58,9 @@ describe("mapSalesInvoiceToRilletInvoice — external references", () => {
it("tags the invoice and every item with a CUSTOMER_CUSTOM reference (rev-rec accepted type)", () => {
const payload = mapSalesInvoiceToRilletInvoice({
invoice: invoice(),
+ document: buildSalesDocumentComponents(invoice()),
+ shippingProductRemoteId: null,
+ shippingAccountCode: null,
customerRemoteId: "rillet-cust-1",
itemRemoteIds: new Map([["item-1", "rillet-prod-1"]]),
subsidiaryId: null,
@@ -67,8 +85,257 @@ describe("mapSalesInvoiceToRilletInvoice — external references", () => {
payload.items[0]?.external_references.some(
(ref) =>
ref.type === RILLET_CUSTOMER_CUSTOM_REFERENCE_TYPE &&
- ref.id === "sil_1"
+ ref.id === "sil_1:Merchandise"
)
).toBe(true);
});
});
+
+function charges(): Accounting.SalesInvoice {
+ const source = invoice();
+ return {
+ ...source,
+ currencyCode: "EUR",
+ exchangeRate: 0.8,
+ headerShippingCost: 5,
+ shippingRevenueAccountId: "acct-shipping",
+ subtotal: 133,
+ totalTax: 13,
+ totalAmount: 151,
+ balance: 151,
+ lines: [
+ {
+ ...source.lines[0]!,
+ quantity: 1,
+ unitPrice: 100,
+ convertedUnitPrice: 80,
+ shippingCost: 10,
+ addOnCost: 20,
+ nonTaxableAddOnCost: 3,
+ taxPercent: 0.1
+ }
+ ]
+ };
+}
+function mapArguments(source = charges()) {
+ return {
+ invoice: source,
+ document: buildSalesDocumentComponents(source),
+ customerRemoteId: "customer-remote",
+ itemRemoteIds: new Map([["item-1", "product"]]),
+ shippingProductRemoteId: "shipping-product",
+ shippingAccountCode: "4010",
+ subsidiaryId: null,
+ companyId: "company-1",
+ documentUrl: "https://erp.example.test/x/sales-invoice/si_1"
+ };
+}
+describe("Rillet revenue recognition native sales components", () => {
+ it("exports the document currency components with shipping revenue override and native header tax exactly once", () => {
+ const payload = mapSalesInvoiceToRilletInvoice(mapArguments());
+ expect(
+ payload.items.map((line) => [
+ line.product_id,
+ line.total_amount.amount,
+ line.revenue?.account_code
+ ])
+ ).toEqual([
+ ["product", "80.00", undefined],
+ ["product", "16.00", undefined],
+ ["product", "2.40", undefined],
+ ["shipping-product", "8.00", "4010"],
+ ["shipping-product", "4.00", "4010"]
+ ]);
+ expect(payload.tax_amount).toEqual({ amount: "10.40", currency: "EUR" });
+ expect(payload.items.every((line) => !line.tax_amount)).toBe(true);
+ expect(
+ payload.items.every((line) => line.total_amount.currency === "EUR")
+ ).toBe(true);
+ expect(payload.scope).toBe("REVENUE_RECOGNITION_ONLY");
+ expect(payload.exchange_rate).toEqual({
+ base: "EUR",
+ target: "USD",
+ rate: "1.25",
+ date: "2026-08-12"
+ });
+ expect(
+ payload.items.every(
+ (item) =>
+ item.revenue?.period?.start === "2026-08-12" &&
+ item.revenue?.period?.end === "2026-08-12" &&
+ item.revenue?.pattern === "DAILY"
+ )
+ ).toBe(true);
+ expect(
+ Rillet.InvoiceSchema.parse({ ...payload, id: "remote" }).items[3]?.revenue
+ ?.account_code
+ ).toBe("4010");
+ expect(
+ new Set(
+ payload.items.flatMap((line) =>
+ line.external_references.map((ref) => ref.id)
+ )
+ ).size
+ ).toBe(5);
+ });
+ it.each([
+ 0, 3
+ ])("uses %i decimal serialization for document net/native tax", (decimals) => {
+ const source = charges();
+ source.currencyDecimalPlaces = decimals;
+ const payload = mapSalesInvoiceToRilletInvoice(mapArguments(source));
+ expect(payload.tax_amount?.amount).toBe(decimals === 0 ? "10" : "10.400");
+ // Merchandise converts to exactly 80 at rate 0.8, so largest-remainder
+ // leaves it alone; the JPY rounding unit goes to the non-taxable add-on,
+ // whose 2.4 is the only component carrying a fractional remainder.
+ expect(payload.items[0]?.total_amount.amount).toBe(
+ decimals === 0 ? "80" : "80.000"
+ );
+ });
+ it("requires actual products for all nonshipping components and never uses the shipping product as fallback", () => {
+ const source = charges();
+ source.lines[0]!.itemId = null;
+ expect(() => mapSalesInvoiceToRilletInvoice(mapArguments(source))).toThrow(
+ /require.*product|no item/i
+ );
+ expect(() =>
+ mapSalesInvoiceToRilletInvoice({
+ ...mapArguments(),
+ itemRemoteIds: new Map()
+ })
+ ).toThrow(/not been synced|mapping/i);
+ });
+});
+
+vi.mock("@carbon/env", () => ({ getAppUrl: () => "https://erp.example.test" }));
+afterEach(() => vi.restoreAllMocks());
+function setupInvoice(missingShipping = false) {
+ const provider = {
+ id: "rillet",
+ subsidiaryId: null,
+ getSyncConfig: () => ({
+ enabled: true,
+ direction: "push-to-accounting",
+ owner: "carbon"
+ }),
+ createInvoice: vi.fn()
+ };
+ const database = {
+ selectFrom(table: string) {
+ const query: any = {
+ select: () => query,
+ innerJoin: () => query,
+ leftJoin: () => query,
+ where: () => query,
+ orderBy: () => query,
+ executeTakeFirst: async () =>
+ table === "accountDefault"
+ ? { salesShippingRevenueAccount: "replacement-shipping" }
+ : {
+ id: "acct-shipping",
+ class: "Revenue",
+ active: true,
+ isGroup: false
+ },
+ execute: async () =>
+ missingShipping
+ ? []
+ : [
+ {
+ id: "map",
+ accountId: "acct-shipping",
+ externalId: "shipping-account",
+ metadata: { externalCode: "4010" },
+ lastSyncedAt: null,
+ accountNumber: "4010",
+ accountName: "Shipping"
+ }
+ ]
+ };
+ return query;
+ }
+ };
+ const context = {
+ database: database as never,
+ companyId: "company-1",
+ provider: provider as never,
+ config: {
+ enabled: true,
+ direction: "push-to-accounting" as const,
+ owner: "carbon" as const
+ },
+ entityType: "invoice" as const
+ };
+ const syncer = new RilletSalesInvoiceSyncer(context);
+ const ensureDependencySynced = vi.fn(
+ async (type: string) => `${type}-remote`
+ );
+ (syncer as any).ensureDependencySynced = ensureDependencySynced;
+ const itemSyncer = new RilletItemSyncer({ ...context, entityType: "item" });
+ const ensureShippingProduct = vi.fn(async () => "shipping-product");
+ itemSyncer.ensureShippingProduct = ensureShippingProduct;
+ const factory = vi
+ .spyOn(SyncFactory, "getSyncer")
+ .mockReturnValue(itemSyncer);
+ return {
+ map: (source: Accounting.SalesInvoice) =>
+ (syncer as any).mapToRemote(source),
+ ensureDependencySynced,
+ ensureShippingProduct,
+ factory,
+ provider
+ };
+}
+describe("Rillet actual invoice preflight", () => {
+ it("resolves the existing item syncer for shipping only after preflight", async () => {
+ const test = setupInvoice();
+ const payload = await test.map(charges());
+ expect(test.ensureShippingProduct).toHaveBeenCalledWith({
+ shippingAccountId: "acct-shipping",
+ baseCurrencyCode: "USD",
+ baseCurrencyDecimals: 2
+ });
+ expect(payload.items).toHaveLength(5);
+ expect(payload.tax_amount.amount).toBe("10.40");
+ });
+ it("fails shipping account mapping before dependencies or provider document writes", async () => {
+ const test = setupInvoice(true);
+ await expect(test.map(charges())).rejects.toMatchObject({
+ failure: { errorCode: "UNMAPPED_ACCOUNTS", warning: true }
+ });
+ expect(test.ensureDependencySynced).not.toHaveBeenCalled();
+ expect(test.ensureShippingProduct).not.toHaveBeenCalled();
+ expect(test.provider.createInvoice).not.toHaveBeenCalled();
+ });
+ it("preflights unsupported no-item components before provisioning anything", async () => {
+ const test = setupInvoice();
+ const source = charges();
+ source.lines[0]!.itemId = null;
+ await expect(test.map(source)).rejects.toMatchObject({
+ failure: { errorCode: "UNMAPPED_ACCOUNTS", warning: true }
+ });
+ expect(test.ensureDependencySynced).not.toHaveBeenCalled();
+ expect(test.ensureShippingProduct).not.toHaveBeenCalled();
+ });
+ it("does not create a shipping helper for an invoice without shipping", async () => {
+ const test = setupInvoice();
+ const payload = await test.map(invoice());
+ expect(payload.items).toHaveLength(1);
+ expect(test.factory).not.toHaveBeenCalled();
+ expect(test.ensureShippingProduct).not.toHaveBeenCalled();
+ });
+});
+
+it("recognizes revenue and FX on the actual posting date when issue date differs", () => {
+ const source = { ...charges(), postingDate: "2026-09-09" };
+ const payload = mapSalesInvoiceToRilletInvoice(mapArguments(source));
+ expect(payload.invoice_date).toBe("2026-09-09");
+ expect(payload.exchange_rate?.date).toBe("2026-09-09");
+ expect(
+ payload.items.every(
+ (item) =>
+ item.revenue?.period?.start === "2026-09-09" &&
+ item.revenue?.period?.end === "2026-09-09"
+ )
+ ).toBe(true);
+});
diff --git a/packages/ee/src/accounting/providers/rillet/entities/__tests__/item.test.ts b/packages/ee/src/accounting/providers/rillet/entities/__tests__/item.test.ts
new file mode 100644
index 0000000000..ddb3e53c0c
--- /dev/null
+++ b/packages/ee/src/accounting/providers/rillet/entities/__tests__/item.test.ts
@@ -0,0 +1,320 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import type { Rillet, RilletProductWrite } from "../../models";
+import { buildRilletIdempotencyKey } from "../../provider";
+import { RilletItemSyncer } from "../item";
+import { toRilletMoney } from "../shared";
+
+describe("Rillet monetary decimal strings", () => {
+ it.each([
+ [1e21, 2, "1000000000000000000000.00"],
+ [1.005, 2, "1.01"],
+ [-2.5, 3, "-2.500"],
+ [0, 0, "0"]
+ ] as const)("serializes %s at %s decimals without exponent notation or grouping", (amount, decimals, expected) => {
+ expect(toRilletMoney(amount, "USD", decimals)).toEqual({
+ amount: expected,
+ currency: "USD"
+ });
+ });
+});
+
+const { links, control } = vi.hoisted(() => ({
+ links: [] as Array<Record<string, unknown>>,
+ control: { failOnce: false }
+}));
+vi.mock("../../../../core/utils", async (original) => ({
+ ...(await original<typeof import("../../../../core/utils")>()),
+ withTriggersDisabled: async (
+ _db: unknown,
+ callback: (tx: unknown) => Promise<unknown>
+ ) => {
+ const builder: any = {
+ values(value: Record<string, unknown>) {
+ links.push(value);
+ return builder;
+ },
+ onConflict() {
+ return builder;
+ },
+ async execute() {
+ if (control.failOnce) {
+ control.failOnce = false;
+ throw new Error("link failed");
+ }
+ return [];
+ }
+ };
+ return callback({ insertInto: () => builder });
+ }
+}));
+beforeEach(() => {
+ links.length = 0;
+ control.failOnce = false;
+});
+const product = (overrides: Partial<Rillet.Product> = {}): Rillet.Product => ({
+ id: "shipping-product",
+ name: "Carbon Shipping acct-shipping USD",
+ description: "Customer shipping charges",
+ price: { type: "ONE_TIME", amount: { amount: "0.00", currency: "USD" } },
+ account_code: "4010",
+ status: "ACTIVE",
+ include_in_arr_mrr: false,
+ revenue_pattern: "EVEN_PERIOD",
+ ...overrides
+});
+function setup(
+ args: {
+ mappedId?: string;
+ current?: Rillet.Product;
+ codes?: Map<string, string>;
+ } = {}
+) {
+ const getProduct = vi.fn(async (_id: string) => args.current ?? product());
+ const createProduct = vi.fn(
+ async (_payload: RilletProductWrite, _key?: string) => product()
+ );
+ const updateProduct = vi.fn(
+ async (_id: string, payload: RilletProductWrite) => ({
+ id: "shipping-product",
+ ...payload
+ })
+ );
+ const syncer = new RilletItemSyncer({
+ database: {} as never,
+ companyId: "company-1",
+ provider: {
+ id: "rillet",
+ getProduct,
+ createProduct,
+ updateProduct
+ } as never,
+ config: { enabled: true, direction: "push-to-accounting", owner: "carbon" },
+ entityType: "item"
+ });
+ (syncer as any).mappingService = {
+ getExternalId: vi.fn(async () => args.mappedId ?? null)
+ };
+ (syncer as any).getAccountCodesById = async () =>
+ args.codes ?? new Map([["acct-shipping", "4010"]]);
+ return { syncer, getProduct, createProduct, updateProduct };
+}
+const shipping = {
+ shippingAccountId: "acct-shipping",
+ baseCurrencyCode: "USD",
+ baseCurrencyDecimals: 2
+};
+
+describe("Rillet shipping product helper", () => {
+ it("creates a nominal sales product under the shipping account using account+base-currency identity", async () => {
+ const test = setup();
+ expect(await test.syncer.ensureShippingProduct(shipping)).toBe(
+ "shipping-product"
+ );
+ expect(await test.syncer.ensureShippingProduct(shipping)).toBe(
+ "shipping-product"
+ );
+ expect(test.createProduct).toHaveBeenCalledOnce();
+ expect(test.createProduct.mock.calls[0]?.[0]).toMatchObject({
+ name: "Carbon Shipping acct-shipping USD",
+ account_code: "4010",
+ status: "ACTIVE",
+ include_in_arr_mrr: false,
+ revenue_pattern: "EVEN_PERIOD",
+ price: { type: "ONE_TIME", amount: { amount: "0.00", currency: "USD" } }
+ });
+ expect(test.createProduct.mock.calls[0]?.[1]).toBe(
+ buildRilletIdempotencyKey({
+ companyId: "company-1",
+ operation: "product",
+ localId: "acct-shipping:USD"
+ })
+ );
+ expect(links[0]).toMatchObject({
+ entityType: "shippingItem",
+ entityId: "acct-shipping:USD",
+ integration: "rillet",
+ companyId: "company-1",
+ externalId: "shipping-product",
+ metadata: { accountId: "acct-shipping", kind: "shipping" }
+ });
+ });
+ it("reuses an owned compatible mapping without another create", async () => {
+ const test = setup({ mappedId: "shipping-product" });
+ expect(await test.syncer.ensureShippingProduct(shipping)).toBe(
+ "shipping-product"
+ );
+ expect(test.createProduct).not.toHaveBeenCalled();
+ });
+ it("retries a lost local link using the same entity-scoped idempotency key", async () => {
+ const test = setup();
+ control.failOnce = true;
+ await expect(test.syncer.ensureShippingProduct(shipping)).rejects.toThrow(
+ "link failed"
+ );
+ expect(await test.syncer.ensureShippingProduct(shipping)).toBe(
+ "shipping-product"
+ );
+ expect(test.createProduct).toHaveBeenCalledTimes(2);
+ expect(test.createProduct.mock.calls[0]?.[1]).toBe(
+ test.createProduct.mock.calls[1]?.[1]
+ );
+ });
+ it("reads and merges a full owned product before reconverging its shipping account", async () => {
+ const current = {
+ ...product({
+ account_code: "old",
+ external_references: [{ type: "other", id: "keep" }]
+ }),
+ unrelated: { retained: true }
+ };
+ const test = setup({ mappedId: "shipping-product", current });
+ await test.syncer.ensureShippingProduct(shipping);
+ expect(test.getProduct).toHaveBeenCalledWith("shipping-product");
+ expect(test.updateProduct.mock.calls[0]?.[1]).toMatchObject({
+ account_code: "4010",
+ unrelated: { retained: true },
+ external_references: expect.arrayContaining([
+ { type: "other", id: "keep" }
+ ])
+ });
+ });
+ it("reconverges an owned helper's nominal price and recurring-revenue flags", async () => {
+ const test = setup({
+ mappedId: "shipping-product",
+ current: product({
+ include_in_arr_mrr: true,
+ price: { type: "ONE_TIME", amount: { amount: "9.00", currency: "USD" } }
+ })
+ });
+ await test.syncer.ensureShippingProduct(shipping);
+ expect(test.updateProduct.mock.calls[0]?.[1]).toMatchObject({
+ include_in_arr_mrr: false,
+ price: { amount: { amount: "0.00", currency: "USD" } }
+ });
+ });
+ it("serializes nominal product price at the authoritative base currency precision", async () => {
+ const test = setup();
+ await test.syncer.ensureShippingProduct({
+ ...shipping,
+ baseCurrencyCode: "BHD",
+ baseCurrencyDecimals: 3
+ });
+ expect(test.createProduct.mock.calls[0]?.[0].price.amount).toEqual({
+ amount: "0.000",
+ currency: "BHD"
+ });
+ expect(links[0]?.entityId).toBe("acct-shipping:BHD");
+ });
+ it("refuses an unmapped shipping account before any provider write", async () => {
+ const test = setup({ codes: new Map() });
+ await expect(
+ test.syncer.ensureShippingProduct(shipping)
+ ).rejects.toMatchObject({
+ failure: { errorCode: "UNMAPPED_ACCOUNTS", warning: true }
+ });
+ expect(test.createProduct).not.toHaveBeenCalled();
+ expect(test.updateProduct).not.toHaveBeenCalled();
+ });
+ it("preserves unrelated full-product fields on the existing merchandise update path too", async () => {
+ const test = setup({
+ current: { ...product(), unrelated: "keep" } as Rillet.Product
+ });
+ (test.syncer as any).getRemoteId = async () => "shipping-product";
+ const changed = { ...product(), description: "Updated description" };
+ await (
+ test.syncer as unknown as {
+ upsertRemote(data: RilletProductWrite, id: string): Promise<string>;
+ }
+ ).upsertRemote(changed, "local-item");
+ expect(test.getProduct).toHaveBeenCalledOnce();
+ expect(test.updateProduct.mock.calls[0]?.[1]).toMatchObject({
+ description: "Updated description",
+ unrelated: "keep"
+ });
+ });
+});
+
+/**
+ * The merchandise path resolves the product price scale from the company's own
+ * base currency row (company.baseCurrencyCode -> currency.decimalPlaces), the
+ * same authoritative source the bill syncer threads through. A hardcoded
+ * 2-decimal serialization gives a JPY price cents it cannot have and truncates
+ * a 3-decimal BHD price.
+ */
+function makeItemDb(baseCurrencyCode: string, decimalPlaces: number) {
+ const chain = (row: unknown) => {
+ const b: Record<string, unknown> = {};
+ b.select = () => b;
+ b.leftJoin = () => b;
+ b.where = () => b;
+ b.execute = async () => [row];
+ b.executeTakeFirst = async () => row;
+ return b;
+ };
+ return {
+ selectFrom: (table: string) => {
+ if (table === "company")
+ return chain({ baseCurrencyCode, companyGroupId: "group-1" });
+ if (table === "currency") return chain({ decimalPlaces });
+ if (table === "accountDefault")
+ return chain({ salesAccount: "acct-sales" });
+ return chain(undefined);
+ }
+ } as never;
+}
+
+function makeMerchandiseSyncer(
+ baseCurrencyCode: string,
+ decimalPlaces: number
+) {
+ const syncer = new RilletItemSyncer({
+ database: makeItemDb(baseCurrencyCode, decimalPlaces),
+ companyId: "company-1",
+ provider: { id: "rillet" } as never,
+ config: { enabled: true, direction: "push-to-accounting", owner: "carbon" },
+ entityType: "item"
+ });
+ (syncer as any).getAccountCodesById = async () =>
+ new Map([["acct-sales", "4000"]]);
+ return syncer;
+}
+
+const merchandiseItem = {
+ id: "item-1",
+ code: "PART-1",
+ name: "Part 1",
+ description: "Part 1",
+ companyId: "company-1",
+ type: "Part" as const,
+ unitOfMeasureCode: "EA",
+ unitCost: 0,
+ unitSalePrice: 1000,
+ isPurchased: true,
+ isSold: true,
+ isTrackedAsInventory: false,
+ updatedAt: "2026-09-09T00:00:00.000Z"
+};
+
+describe("Rillet merchandise product price precision", () => {
+ it("serializes a 0-decimal base currency (JPY) at its own scale", async () => {
+ const syncer = makeMerchandiseSyncer("JPY", 0);
+ const payload = await (
+ syncer as unknown as {
+ mapToRemote(item: unknown): Promise<RilletProductWrite>;
+ }
+ ).mapToRemote(merchandiseItem);
+
+ expect(payload.price.amount).toEqual({ amount: "1000", currency: "JPY" });
+ });
+
+ it("keeps the third decimal of a 3-decimal base currency (BHD)", async () => {
+ const syncer = makeMerchandiseSyncer("BHD", 3);
+ const payload = await (
+ syncer as unknown as {
+ mapToRemote(item: unknown): Promise<RilletProductWrite>;
+ }
+ ).mapToRemote({ ...merchandiseItem, unitSalePrice: 0.563 });
+
+ expect(payload.price.amount).toEqual({ amount: "0.563", currency: "BHD" });
+ });
+});
diff --git a/packages/ee/src/accounting/providers/rillet/entities/__tests__/payment-push.test.ts b/packages/ee/src/accounting/providers/rillet/entities/__tests__/payment-push.test.ts
index e67d98a68e..13efbc1c16 100644
--- a/packages/ee/src/accounting/providers/rillet/entities/__tests__/payment-push.test.ts
+++ b/packages/ee/src/accounting/providers/rillet/entities/__tests__/payment-push.test.ts
@@ -27,7 +27,7 @@ vi.mock("../../../../core/utils", async (importOriginal) => {
) => {
const insertBuilder: Record<string, unknown> = {};
insertBuilder.values = (v: Record<string, unknown>) => {
- txLinkSink.push(v);
+ txLinkSink.push(...(Array.isArray(v) ? v : [v]));
return insertBuilder;
};
insertBuilder.onConflict = () => insertBuilder;
@@ -47,6 +47,7 @@ type PaymentRow = {
bankAccount: string;
currencyCode: string;
exchangeRate: number;
+ totalAmount?: number;
paymentDate: string;
postingDate: string | null;
reference: string | null;
@@ -56,15 +57,22 @@ type SettlementRow = {
targetSalesInvoiceId: string | null;
targetPurchaseInvoiceId: string | null;
appliedAmount: number;
+ sourceAmount: number;
+ sourcePaymentId: string | null;
+ targetExchangeRate?: number;
+ fxGainLossAmount?: number;
discountAmount: number;
writeOffAmount: number;
};
function makePushDb(opts: {
metadata?: unknown;
+ mappings?: Array<Record<string, unknown>>;
payment?: PaymentRow;
settlements?: SettlementRow[];
linkSink: Array<Record<string, unknown>>;
+ /** `currency.decimalPlaces` of the payment currency (USD unless overridden). */
+ currencyDecimals?: number;
}) {
const selectChain = (rows: unknown[]) => {
const b: Record<string, unknown> = {};
@@ -81,10 +89,17 @@ function makePushDb(opts: {
opts.metadata === undefined ? [] : [{ metadata: opts.metadata }]
);
}
+ if (t === "externalIntegrationMapping")
+ return selectChain(opts.mappings ?? []);
if (t === "payment") {
return selectChain(opts.payment ? [opts.payment] : []);
}
if (t === "invoiceSettlement") return selectChain(opts.settlements ?? []);
+ // The settlement scale is read from the company's group-scoped currency
+ // row — the same authoritative source the bill syncer uses.
+ if (t === "company") return selectChain([{ companyGroupId: "group-1" }]);
+ if (t === "currency")
+ return selectChain([{ decimalPlaces: opts.currencyDecimals ?? 2 }]);
return selectChain([]);
},
transaction: () => ({
@@ -114,6 +129,8 @@ function makeSyncer(opts: {
enabled?: boolean;
createInvoicePayment?: ReturnType<typeof vi.fn>;
createBillPayment?: ReturnType<typeof vi.fn>;
+ deleteInvoicePayment?: ReturnType<typeof vi.fn>;
+ deleteBillPayment?: ReturnType<typeof vi.fn>;
}) {
const createInvoicePayment =
opts.createInvoicePayment ??
@@ -122,13 +139,18 @@ function makeSyncer(opts: {
opts.createBillPayment ??
vi.fn(async () => ({ id: "rillet-pay-1", status: "SUCCESSFUL" }));
+ const deleteInvoicePayment =
+ opts.deleteInvoicePayment ?? vi.fn(async () => {});
+ const deleteBillPayment = opts.deleteBillPayment ?? vi.fn(async () => {});
const syncer = new RilletPaymentSyncer({
database: opts.db,
companyId: "company-1",
provider: {
id: "rillet",
createInvoicePayment,
- createBillPayment
+ createBillPayment,
+ deleteInvoicePayment,
+ deleteBillPayment
} as never,
config: {
enabled: opts.enabled ?? true,
@@ -148,7 +170,13 @@ function makeSyncer(opts: {
opts.accountCodes ?? new Map([["bank-1", "1000"]])
);
- return { syncer, createInvoicePayment, createBillPayment };
+ return {
+ syncer,
+ createInvoicePayment,
+ createBillPayment,
+ deleteInvoicePayment,
+ deleteBillPayment
+ };
}
const apPayment: PaymentRow = {
@@ -157,6 +185,7 @@ const apPayment: PaymentRow = {
bankAccount: "bank-1",
currencyCode: "USD",
exchangeRate: 1,
+ totalAmount: 140,
paymentDate: "2026-08-07",
postingDate: "2026-08-07",
reference: "PAY-1"
@@ -166,6 +195,10 @@ const apSettlement: SettlementRow = {
targetSalesInvoiceId: null,
targetPurchaseInvoiceId: "pinv-1",
appliedAmount: 100,
+ sourceAmount: 100,
+ sourcePaymentId: null,
+ targetExchangeRate: 1,
+ fxGainLossAmount: 0,
discountAmount: 0,
writeOffAmount: 0
};
@@ -297,7 +330,8 @@ describe("RilletPaymentSyncer push — gates (parked as Skipped)", () => {
{
...apSettlement,
targetPurchaseInvoiceId: "pinv-2",
- appliedAmount: 40
+ appliedAmount: 40,
+ sourceAmount: 40
},
apSettlement
],
@@ -336,6 +370,53 @@ describe("RilletPaymentSyncer push — gates (parked as Skipped)", () => {
});
});
+ it("serializes a 0-decimal currency (JPY) at its own scale, not at cents", async () => {
+ // JPY settles at 0 decimals: ¥1000 is "1000". Serializing it as "1000.00"
+ // claims a precision the currency does not have.
+ const { syncer, createBillPayment } = makeSyncer({
+ db: makePushDb({
+ payment: { ...apPayment, currencyCode: "JPY", totalAmount: 1000 },
+ settlements: [
+ { ...apSettlement, appliedAmount: 1000, sourceAmount: 1000 }
+ ],
+ linkSink: [],
+ currencyDecimals: 0
+ }),
+ mapping: null,
+ documentRemoteId: "bill-remote-1"
+ });
+
+ const result = await syncer.pushToAccounting("pay_1");
+
+ expect(result.status).toBe("success");
+ expect(createBillPayment.mock.calls[0]?.[1]).toMatchObject({
+ amount: { amount: "1000", currency: "JPY" }
+ });
+ });
+
+ it("serializes a 3-decimal currency (BHD) without losing its third decimal", async () => {
+ // BHD settles at 3 decimals (1000 fils): 0.563 must survive the wire.
+ const { syncer, createBillPayment } = makeSyncer({
+ db: makePushDb({
+ payment: { ...apPayment, currencyCode: "BHD", totalAmount: 0.563 },
+ settlements: [
+ { ...apSettlement, appliedAmount: 0.563, sourceAmount: 0.563 }
+ ],
+ linkSink: [],
+ currencyDecimals: 3
+ }),
+ mapping: null,
+ documentRemoteId: "bill-remote-1"
+ });
+
+ const result = await syncer.pushToAccounting("pay_1");
+
+ expect(result.status).toBe("success");
+ expect(createBillPayment.mock.calls[0]?.[1]).toMatchObject({
+ amount: { amount: "0.563", currency: "BHD" }
+ });
+ });
+
it("skips a foreign-currency payment", async () => {
const { syncer } = makeSyncer({
db: makePushDb({
@@ -384,19 +465,89 @@ describe("RilletPaymentSyncer push — gates (parked as Skipped)", () => {
});
describe("RilletPaymentSyncer push — void routing", () => {
- it("skips (not supported) a voided Carbon-originated payment", async () => {
- const { syncer } = makeSyncer({
+ it.each([
+ "ar",
+ "ap"
+ ])("voids every Carbon-originated %s settlement and retains idempotent tombstones", async (family) => {
+ const remote = (n: number) =>
+ `${family === "ap" ? "bill:" : ""}doc-${n}:pay-${n}`;
+ const mappings = [1, 2].map((n) => ({
+ entityId: `pay_1:doc-${n}`,
+ externalId: remote(n),
+ metadata: { origin: "carbon", other: "preserved" }
+ }));
+ const { syncer, deleteInvoicePayment, deleteBillPayment } = makeSyncer({
db: makePushDb({
payment: { ...apPayment, status: "Voided" },
settlements: [apSettlement],
+ mappings,
linkSink: []
- }),
- mapping: { metadata: { origin: "carbon" } }
+ })
+ });
+ expect(await syncer.pushToAccounting("pay_1")).toMatchObject({
+ status: "success",
+ action: "deleted"
});
+ const deletion = family === "ar" ? deleteInvoicePayment : deleteBillPayment;
+ expect(deletion.mock.calls).toEqual([
+ ["doc-1", "pay-1"],
+ ["doc-2", "pay-2"]
+ ]);
+ expect(txLinkSink).toHaveLength(2);
+ expect(
+ txLinkSink.every(
+ (row) =>
+ (row.metadata as any)?.voided === true &&
+ (row.metadata as any)?.other === "preserved"
+ )
+ ).toBe(true);
+ });
- const result = await syncer.pushToAccounting("pay_1");
- expect(result.status).toBe("skipped");
- expect(result.error).toContain("not supported");
+ it("retains all mappings on partial delete failure so retry is safe", async () => {
+ const deletion = vi
+ .fn()
+ .mockResolvedValueOnce(undefined)
+ .mockRejectedValueOnce(new Error("cleared payment"));
+ const { syncer } = makeSyncer({
+ deleteBillPayment: deletion,
+ db: makePushDb({
+ payment: { ...apPayment, status: "Voided" },
+ settlements: [apSettlement],
+ linkSink: [],
+ mappings: [1, 2].map((n) => ({
+ entityId: `pay_1:doc-${n}`,
+ externalId: `bill:doc-${n}:pay-${n}`,
+ metadata: { origin: "carbon" }
+ }))
+ })
+ });
+ expect(await syncer.pushToAccounting("pay_1")).toMatchObject({
+ status: "error",
+ error: "cleared payment"
+ });
+ expect(txLinkSink).toHaveLength(0);
+ });
+
+ it("does not delete an already voided mapping again", async () => {
+ const { syncer, deleteBillPayment } = makeSyncer({
+ db: makePushDb({
+ payment: { ...apPayment, status: "Voided" },
+ settlements: [],
+ linkSink: [],
+ mappings: [
+ {
+ entityId: "pay_1",
+ externalId: "bill:doc-1:pay-1",
+ metadata: { origin: "carbon", voided: true }
+ }
+ ]
+ })
+ });
+ expect(await syncer.pushToAccounting("pay_1")).toMatchObject({
+ status: "success",
+ action: "deleted"
+ });
+ expect(deleteBillPayment).not.toHaveBeenCalled();
});
it("skips a voided pulled payment (no Carbon-originated provider payment to reverse)", async () => {
@@ -469,3 +620,21 @@ describe("RilletPaymentSyncer.pushRemotePayment — mapping Warnings", () => {
});
});
});
+
+describe("outbound cash funding validation", () => {
+ it("refuses credit-funded applications before provider writes", async () => {
+ const { syncer, createBillPayment } = makeSyncer({
+ db: makePushDb({
+ payment: apPayment,
+ settlements: [{ ...apSettlement, sourcePaymentId: "prior-credit" }],
+ linkSink: []
+ }),
+ mapping: null,
+ documentRemoteId: "bill-remote-1"
+ });
+ const result = await syncer.pushToAccounting("pay_1");
+ expect(result.status).toBe("skipped");
+ expect(String(result.error)).toMatch(/credit/i);
+ expect(createBillPayment).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/ee/src/accounting/providers/rillet/entities/__tests__/payment.test.ts b/packages/ee/src/accounting/providers/rillet/entities/__tests__/payment.test.ts
index f8ee1dea43..4f84fb12c9 100644
--- a/packages/ee/src/accounting/providers/rillet/entities/__tests__/payment.test.ts
+++ b/packages/ee/src/accounting/providers/rillet/entities/__tests__/payment.test.ts
@@ -9,7 +9,6 @@ import {
getRilletPaymentAmount,
getRilletPaymentCurrency,
getRilletPaymentSyncEntityId,
- getSettledInvoiceStatus,
mapRilletPaymentToLocal,
parseRilletPaymentSyncEntityId,
RilletPaymentSyncer
@@ -79,40 +78,6 @@ describe("composite payment sync entity id", () => {
});
});
-describe("getSettledInvoiceStatus", () => {
- it("covers the zero / partial / exact / over boundaries", () => {
- expect(
- getSettledInvoiceStatus({ invoiceTotal: 100, settledTotal: 0 })
- ).toBeNull();
- expect(
- getSettledInvoiceStatus({ invoiceTotal: 100, settledTotal: 40 })
- ).toBe("Partially Paid");
- expect(
- getSettledInvoiceStatus({ invoiceTotal: 100, settledTotal: 100 })
- ).toBe("Paid");
- expect(
- getSettledInvoiceStatus({ invoiceTotal: 100, settledTotal: 150 })
- ).toBe("Paid");
- });
-
- it("is cents-accurate and never restates degenerate invoices", () => {
- // 99.999 rounds to 10000 cents — exact at 2dp
- expect(
- getSettledInvoiceStatus({ invoiceTotal: 100, settledTotal: 99.999 })
- ).toBe("Paid");
- expect(
- getSettledInvoiceStatus({ invoiceTotal: 100, settledTotal: 99.99 })
- ).toBe("Partially Paid");
-
- expect(
- getSettledInvoiceStatus({ invoiceTotal: 0, settledTotal: 50 })
- ).toBeNull();
- expect(
- getSettledInvoiceStatus({ invoiceTotal: 100, settledTotal: -5 })
- ).toBeNull();
- });
-});
-
describe("mapRilletPaymentToLocal", () => {
it("normalizes the list-endpoint shape (nested amount, date)", () => {
const remote = Rillet.InvoicePaymentSchema.parse({
@@ -456,7 +421,7 @@ describe("RilletPaymentSyncer.mapToNormalized", () => {
paymentRemoteId: "pay-1",
amount: 125,
currencyCode: "USD",
- exchangeRate: 1,
+ exchangeRate: null,
paidDate: "2026-07-15",
reference: "pay-1",
status: "settled"
@@ -492,7 +457,7 @@ describe("RilletPaymentSyncer.mapToNormalized", () => {
paymentRemoteId: "bp-1",
amount: 500,
currencyCode: "USD",
- exchangeRate: 1,
+ exchangeRate: null,
paidDate: "2026-08-01",
reference: "bp-1",
status: "settled"
@@ -537,6 +502,9 @@ function makeFakeTx(store: {
const entityId = store.docMappings[where("externalId") as string];
return entityId ? { entityId } : undefined; // getEntityId
}
+ if (b.table === "company")
+ return { baseCurrencyCode: "USD", companyGroupId: "group-1" };
+ if (b.table === "currency") return { decimalPlaces: 2 };
if (b.table === "salesInvoice") return store.salesInvoice;
if (b.table === "purchaseInvoice") return store.purchaseInvoice;
if (b.table === "payment") {
@@ -591,6 +559,37 @@ function makeFakeTx(store: {
return b;
},
async execute() {
+ if (op === "select") {
+ if (table === "externalIntegrationMapping")
+ return Object.entries(store.docMappings).map(
+ ([externalId, entityId]) => ({ externalId, entityId })
+ );
+ if (table === "salesInvoices")
+ return store.salesInvoice
+ ? [
+ {
+ ...store.salesInvoice,
+ partyId: store.salesInvoice.customerId,
+ exchangeRate: 1,
+ totalAmount: 1000,
+ balance: 1000
+ }
+ ]
+ : [];
+ if (table === "purchaseInvoices")
+ return store.purchaseInvoice
+ ? [
+ {
+ ...store.purchaseInvoice,
+ partyId: store.purchaseInvoice.supplierId,
+ exchangeRate: 1,
+ totalAmount: 1000,
+ balance: 1000
+ }
+ ]
+ : [];
+ return [];
+ }
store.records.push({ op, table, values: b.valuesArg });
return [];
},
diff --git a/packages/ee/src/accounting/providers/rillet/entities/bill.ts b/packages/ee/src/accounting/providers/rillet/entities/bill.ts
index 1064f3d4b3..b8ee81d8d1 100644
--- a/packages/ee/src/accounting/providers/rillet/entities/bill.ts
+++ b/packages/ee/src/accounting/providers/rillet/entities/bill.ts
@@ -23,6 +23,7 @@ import {
carbonExternalReference,
loadRilletAccountCodesById,
RilletTransactionSyncer,
+ toRilletExchangeRate,
toRilletMoney,
writeDroppingUnregisteredReferences
} from "./shared";
@@ -120,24 +121,25 @@ function describeCostingLine(line: CostingLine): string | undefined {
/**
* Map a Carbon bill to the Rillet bill create payload. Pure — exported for
* tests. `postingJournalLines` are the bill's costing lines (AP control line
- * already excluded by `loadBillCostingLines`); the mapper re-runs the AP
- * filter defensively so direct callers may pass raw journal lines too.
+ * already excluded by `loadBillCostingLines`). The mapper accepts costing only.
*
* The costing lines carry base-currency debit-signed amounts;
* `bill.exchangeRate` converts them to the invoice's transaction currency
- * (pass-through at rate 1). Throws structured Warnings when the journal is
+ * (rounded at the document currency boundary). Throws structured Warnings when the journal is
* missing (invoice not posted / accounting off) or an account is unmapped.
*/
export function mapBillToRilletBill(args: {
bill: Accounting.Bill;
+ documentTotal: number;
+ decimalPlaces: number;
+ baseCurrencyCode: string;
+ postingDate: string;
vendorRemoteId: string;
accountCodesById: ReadonlyMap<string, string>;
subsidiaryId: string | null;
companyId: string;
/** Costing lines of the bill's posted Purchase Invoice journal, debit-signed. */
postingJournalLines: BillPostingJournalLine[];
- /** accountDefault.payablesAccount — the AP control line(s) to exclude. */
- payablesAccountId: string | null;
/**
* Slot config + resolved Field-value ids (same contract as the journal
* mapper's RilletJournalDimensionArgs). Slotted line dimensions with no
@@ -158,12 +160,7 @@ export function mapBillToRilletBill(args: {
});
}
- // Defensive re-filter: loadBillCostingLines already dropped the AP control
- // line, but keep the filter so raw journal lines (tests) also work.
- const costingLines = args.postingJournalLines.filter(
- (line) =>
- line.accountId === null || line.accountId !== args.payablesAccountId
- );
+ const costingLines = args.postingJournalLines;
const unmapped = new Set<string>();
const lineIdsWithoutAccount: string[] = [];
@@ -202,11 +199,12 @@ export function mapBillToRilletBill(args: {
}
// FX: convert base-currency amounts to the invoice's transaction currency
- // (pass-through at rate 1) and pin exchange_rate on the payload below.
- const transactionLines = toTransactionCurrencyLines(
- costingLines,
- bill.exchangeRate
- );
+ // (rounded at the document currency boundary) and pin exchange_rate on the payload below.
+ const transactionLines = toTransactionCurrencyLines(costingLines, {
+ exchangeRate: bill.exchangeRate,
+ documentTotal: args.documentTotal,
+ decimalPlaces: args.decimalPlaces
+ });
const items: Rillet.BillItem[] = transactionLines.map((line) => {
const fieldRefs: Rillet.ItemFieldRef[] = [];
@@ -231,15 +229,13 @@ export function mapBillToRilletBill(args: {
return {
account_code: args.accountCodesById.get(line.accountId!)!,
- amount: toRilletMoney(line.amount, currency),
+ amount: toRilletMoney(line.amount, currency, args.decimalPlaces),
...(description ? { description } : {}),
...(fieldRefs.length > 0 ? { fields: fieldRefs } : {})
};
});
- const billDate = toPostingDateString(
- bill.dateIssued ?? new Date().toISOString()
- );
+ const billDate = toPostingDateString(bill.dateIssued ?? args.postingDate);
return {
vendor_id: args.vendorRemoteId,
@@ -249,8 +245,13 @@ export function mapBillToRilletBill(args: {
due_date: toPostingDateString(bill.dateDue ?? billDate),
items,
...(args.subsidiaryId ? { subsidiary_id: args.subsidiaryId } : {}),
- // Pin the provider exchange rate for FX bills (omit at parity rate 1).
- ...(bill.exchangeRate !== 1 ? { exchange_rate: bill.exchangeRate } : {}),
+ // Pin the directed provider exchange rate for foreign-currency bills.
+ exchange_rate: toRilletExchangeRate({
+ baseCurrencyCode: args.baseCurrencyCode,
+ documentCurrencyCode: currency,
+ foreignPerBaseRate: bill.exchangeRate,
+ date: args.postingDate
+ }),
external_references: [
carbonExternalReference(bill.id),
carbonCompanyExternalReference(args.companyId)
@@ -283,6 +284,14 @@ export class RilletBillSyncer extends RilletTransactionSyncer<
// 1. LOCAL FETCH (Single + Batch)
// =================================================================
+ protected isVoided(local: Accounting.Bill): boolean {
+ return local.status === "Voided";
+ }
+
+ protected async deleteRemote(remoteId: string): Promise<void> {
+ await this.rilletProvider.deleteBill(remoteId);
+ }
+
async fetchLocal(id: string): Promise<Accounting.Bill | null> {
const bills = await this.fetchBillsByIds([id]);
return bills.get(id) ?? null;
@@ -491,11 +500,17 @@ export class RilletBillSyncer extends RilletTransactionSyncer<
);
}
- const payablesAccountId = await this.getPayablesAccountId();
- const { lines: costingLines } = await loadBillCostingLines(this.database, {
+ const {
+ lines: costingLines,
+ documentTotal,
+ decimalPlaces,
+ baseCurrencyCode,
+ postingDate,
+ currencyCode,
+ exchangeRate
+ } = await loadBillCostingLines(this.database, {
companyId: this.companyId,
- billId: local.id,
- payablesAccountId
+ billId: local.id
});
// Send ALL dimensions on the bill: auto-provision every Rillet Field +
@@ -506,27 +521,20 @@ export class RilletBillSyncer extends RilletTransactionSyncer<
await this.resolveLineDimensions(costingLines);
return mapBillToRilletBill({
- bill: local,
+ bill: { ...local, currencyCode, exchangeRate },
+ documentTotal,
+ decimalPlaces,
+ baseCurrencyCode,
+ postingDate,
vendorRemoteId,
accountCodesById: await this.getAccountCodesById(),
subsidiaryId: this.rilletProvider.subsidiaryId,
companyId: this.companyId,
postingJournalLines: costingLines,
- payablesAccountId,
dimensions: { fieldIdByDimensionId, fieldValueIdsByValue }
});
}
- /** accountDefault.payablesAccount — the AP control line to exclude. */
- private async getPayablesAccountId(): Promise<string | null> {
- const defaults = await this.database
- .selectFrom("accountDefault")
- .select("payablesAccount")
- .where("companyId", "=", this.companyId)
- .executeTakeFirst();
- return defaults?.payablesAccount ?? null;
- }
-
// =================================================================
// 5. UPSERT REMOTE (create-only; RilletTransactionSyncer hard-skips
// already-mapped ids)
diff --git a/packages/ee/src/accounting/providers/rillet/entities/invoice.ts b/packages/ee/src/accounting/providers/rillet/entities/invoice.ts
index 8f9778cf14..e4d45f648b 100644
--- a/packages/ee/src/accounting/providers/rillet/entities/invoice.ts
+++ b/packages/ee/src/accounting/providers/rillet/entities/invoice.ts
@@ -1,7 +1,16 @@
+import { datetime } from "@carbon/database/datetime";
import {
JournalEntrySyncError,
toPostingDateString
} from "../../../core/posting";
+import {
+ buildSalesDocumentComponents,
+ type SalesDocumentComponents
+} from "../../../core/sales-document-components";
+import {
+ loadSalesInvoices,
+ requirePostedShippingAccountId
+} from "../../../core/sales-invoice-source";
import type { Accounting, ShouldSyncContext } from "../../../core/types";
import type {
Rillet,
@@ -12,35 +21,36 @@ import {
buildRilletIdempotencyKey,
isRilletUnknownExternalReferenceTypeError
} from "../provider";
+import type { RilletItemSyncer } from "./item";
import {
carbonCompanyExternalReference,
carbonExternalReference,
customerCustomExternalReference,
+ loadRilletAccountCodesById,
RILLET_CARBON_COMPANY_REFERENCE_TYPE,
RILLET_CARBON_REFERENCE_TYPE,
RilletTransactionSyncer,
+ toRilletExchangeRate,
toRilletMoney
} from "./shared";
/**
- * RilletSalesInvoiceSyncer — Carbon sales invoices → Rillet AR_ONLY
- * invoices (push-only, create-only; entityType "invoice").
+ * RilletSalesInvoiceSyncer — Carbon sales invoices → Rillet revenue recognition
+ * invoices (push-only; entityType "invoice").
*
- * AR_ONLY is Rillet's external-ERP scope: Carbon keeps generating and
- * sending the invoice; Rillet carries the receivable (and reports
- * payments back through the invoice-payment-updated webhook → the payment
- * syncer). `invoice_number` is Carbon's readable invoice id.
+ * REVENUE_RECOGNITION_ONLY keeps Carbon as the invoice issuer while Rillet
+ * carries receivables and recognizes net revenue on the posting date. Unlike
+ * AR_ONLY, the v4 scope honors the fixed document-to-subsidiary exchange rate.
*
* Customer and line items are JIT-synced via ensureDependencySynced
- * before the document. Rillet AR_ONLY items REQUIRE a product_id, so a
+ * before the document. Rillet revenue recognition items REQUIRE a product_id, so a
* line without a Carbon item cannot be represented — it fails with a
* structured Warning listing the lines (UNMAPPED_ACCOUNTS envelope: the
* closest user-fixable code available; the core error-code list has no
* missing-item code yet).
*
- * Create-only: pushed invoices are never updated from Carbon in v1 —
- * RilletTransactionSyncer hard-skips already-mapped ids (updates are a
- * follow-up).
+ * Posted amounts stay immutable. A local void deletes the native invoice;
+ * its retained mapping prevents duplicate creation or deletion on retries.
*/
// Only posted invoices are pushed (same status gate as the Xero/QBO
@@ -53,54 +63,42 @@ const SYNCABLE_STATUSES: Accounting.SalesInvoice["status"][] = [
"Overdue"
];
-// Row shapes for sales invoice queries (mirror the QBO syncer's)
-type InvoiceRow = {
- id: string;
- invoiceId: string;
- companyId: string;
- customerId: string;
- status: Accounting.SalesInvoice["status"];
- currencyCode: string;
- exchangeRate: number;
- dateIssued: string | null;
- dateDue: string | null;
- datePaid: string | null;
- customerReference: string | null;
- subtotal: number;
- totalTax: number;
- totalDiscount: number;
- totalAmount: number;
- balance: number;
- updatedAt: string | null;
-};
-
-type InvoiceLineRow = {
- id: string;
- invoiceId: string;
- invoiceLineType: string;
- itemId: string | null;
- description: string | null;
- quantity: number;
- /** BASE currency, as stored. */
- unitPrice: number;
- /** Document-currency mirror (unitPrice * exchangeRate). */
- convertedUnitPrice: number | null;
- taxPercent: number;
- itemReadableIdWithRevision: string | null;
-};
-
/**
- * Map a Carbon sales invoice to the Rillet AR_ONLY create payload. Pure —
+ * Map a Carbon sales invoice to the Rillet revenue recognition create payload. Pure —
* exported for tests. `itemRemoteIds` maps Carbon itemId → Rillet product
* id (resolved by ensureDependencySynced before mapping).
*
* Throws the structured UNMAPPED_ACCOUNTS Warning when any line has no
- * item (AR_ONLY items require product_id), and a plain Error when a
+ * item (REVENUE_RECOGNITION_ONLY items require product_id), and a plain Error when a
* line's item was not resolved to a product (a dependency-sync bug, not
* user-fixable).
*/
+function preflightRilletComponents(document: SalesDocumentComponents): void {
+ const unsupported = document.components.filter(
+ (line) =>
+ (line.kind !== "LineShipping" &&
+ line.kind !== "HeaderShipping" &&
+ !line.itemId) ||
+ line.quantity < 0.00001
+ );
+ if (unsupported.length > 0)
+ throw new JournalEntrySyncError({
+ errorCode: "UNMAPPED_ACCOUNTS",
+ warning: true,
+ message:
+ "Cannot sync invoice: Rillet revenue recognition lines require a product and positive quantity; some components have no item or unsupported quantities",
+ metadata: {
+ invoiceId: document.invoiceId,
+ componentIds: unsupported.map((line) => line.id)
+ }
+ });
+}
+
export function mapSalesInvoiceToRilletInvoice(args: {
invoice: Accounting.SalesInvoice;
+ document: SalesDocumentComponents;
+ shippingProductRemoteId: string | null;
+ shippingAccountCode: string | null;
customerRemoteId: string;
itemRemoteIds: ReadonlyMap<string, string>;
subsidiaryId: string | null;
@@ -110,58 +108,53 @@ export function mapSalesInvoiceToRilletInvoice(args: {
documentUrl: string;
}): RilletInvoiceCreate {
const { invoice } = args;
- const currency = invoice.currencyCode;
-
- const lineIdsWithoutItem = invoice.lines
- .filter((line) => !line.itemId)
- .map((line) => line.id);
- if (lineIdsWithoutItem.length > 0) {
- throw new JournalEntrySyncError({
- errorCode: "UNMAPPED_ACCOUNTS",
- message: `Cannot sync invoice ${invoice.invoiceId}: ${lineIdsWithoutItem.length} line(s) have no item — Rillet AR_ONLY invoice lines require a product. Assign an item to the line(s), then retry.`,
- warning: true,
- metadata: { invoiceId: invoice.id, lineIdsWithoutItem }
- });
- }
-
- const items: Rillet.InvoiceItem[] = invoice.lines.map((line) => {
- const productId = args.itemRemoteIds.get(line.itemId!);
- if (!productId) {
- throw new Error(
- `Cannot sync invoice ${invoice.invoiceId}: item ${line.itemId} has not been synced to Rillet`
- );
- }
-
+ const document = args.document;
+ const currency = document.currencyCode;
+ preflightRilletComponents(document);
+ const invoiceDate = toPostingDateString(
+ invoice.postingDate ?? invoice.dateIssued ?? datetime.timestamp()
+ );
+ const items: Rillet.InvoiceItem[] = document.components.map((component) => {
+ const shipping =
+ component.kind === "LineShipping" || component.kind === "HeaderShipping";
+ const productId = shipping
+ ? args.shippingProductRemoteId
+ : args.itemRemoteIds.get(component.itemId!);
+ if (!productId || (shipping && !args.shippingAccountCode))
+ throw new JournalEntrySyncError({
+ errorCode: "UNMAPPED_ACCOUNTS",
+ warning: true,
+ message: `Invoice component ${component.id} has no resolved Rillet product/account mapping`,
+ metadata: { invoiceId: document.invoiceId, componentId: component.id }
+ });
return {
product_id: productId,
- description: line.description ?? line.itemCode ?? "Invoice line",
- quantity: line.quantity,
- // `currency` is the DOCUMENT currency, so the amount must be too.
- // salesInvoiceLine.unitPrice is stored in the company BASE currency;
- // convertedUnitPrice is the document-currency mirror.
+ description: component.description,
+ quantity: component.quantity,
total_amount: toRilletMoney(
- line.quantity * (line.convertedUnitPrice ?? line.unitPrice),
- currency
+ component.netAmount,
+ currency,
+ document.decimalPlaces
),
- // CUSTOMER_CUSTOM satisfies rev-rec validation and carries the line id
- // for audit. NO `carbon` ref here: Rillet counts header + item
- // references together for RESTRICTED types, and organizations that
- // register `carbon` as restricted reject a document carrying it on
- // both the header and a line ("multiple references of a restricted
- // type" — verified on the sandbox 2026-08-12). The header's carbon
- // ref is the document's single origin link.
+ revenue: {
+ period: { start: invoiceDate, end: invoiceDate },
+ pattern: "DAILY",
+ ...(shipping ? { account_code: args.shippingAccountCode! } : {})
+ },
external_references: [
- customerCustomExternalReference(line.id, args.documentUrl)
+ customerCustomExternalReference(component.id, args.documentUrl)
]
};
});
- const invoiceDate = toPostingDateString(
- invoice.dateIssued ?? new Date().toISOString()
- );
-
return {
- scope: "AR_ONLY",
+ scope: "REVENUE_RECOGNITION_ONLY",
+ exchange_rate: toRilletExchangeRate({
+ baseCurrencyCode: invoice.baseCurrencyCode,
+ documentCurrencyCode: currency,
+ foreignPerBaseRate: invoice.exchangeRate,
+ date: invoiceDate
+ }),
customer_id: args.customerRemoteId,
invoice_number: invoice.invoiceId,
invoice_date: invoiceDate,
@@ -169,8 +162,14 @@ export function mapSalesInvoiceToRilletInvoice(args: {
...(invoice.dateDue
? { due_date: toPostingDateString(invoice.dateDue) }
: {}),
- ...(invoice.totalTax > 0
- ? { tax_amount: toRilletMoney(invoice.totalTax, currency) }
+ ...(document.totalTax !== 0
+ ? {
+ tax_amount: toRilletMoney(
+ document.totalTax,
+ currency,
+ document.decimalPlaces
+ )
+ }
: {}),
...(args.subsidiaryId ? { subsidiary_id: args.subsidiaryId } : {}),
items,
@@ -193,10 +192,72 @@ export class RilletSalesInvoiceSyncer extends RilletTransactionSyncer<
return "Sales invoices";
}
+ private shippingAccountCodesPromise?: ReturnType<
+ typeof loadRilletAccountCodesById
+ >;
+ private shippingItemSyncerPromise?: Promise<RilletItemSyncer>;
+
+ private async getShippingAccount(
+ local: Accounting.SalesInvoice
+ ): Promise<{ id: string; code: string }> {
+ const id = requirePostedShippingAccountId(local);
+ this.shippingAccountCodesPromise ??= loadRilletAccountCodesById(
+ this.database,
+ {
+ companyId: this.companyId,
+ integration: this.provider.id
+ }
+ ).catch((error) => {
+ this.shippingAccountCodesPromise = undefined;
+ throw error;
+ });
+ const code = (await this.shippingAccountCodesPromise).get(id);
+ if (!code)
+ throw new JournalEntrySyncError({
+ errorCode: "UNMAPPED_ACCOUNTS",
+ warning: true,
+ message:
+ "Cannot sync invoice: original Shipping Revenue account has no Rillet mapping",
+ metadata: { invoiceId: local.id, unmappedAccountIds: [id] }
+ });
+ return { id, code };
+ }
+
+ private getShippingItemSyncer(): Promise<RilletItemSyncer> {
+ if (!this.shippingItemSyncerPromise)
+ this.shippingItemSyncerPromise = (async () => {
+ const [{ SyncFactory }, { RilletItemSyncer }] = await Promise.all([
+ import("../../../core/sync"),
+ import("./item")
+ ]);
+ const syncer = SyncFactory.getSyncer({
+ ...this.context,
+ entityType: "item",
+ config: this.provider.getSyncConfig("item") ?? {
+ enabled: true,
+ direction: "push-to-accounting",
+ owner: "carbon"
+ }
+ });
+ if (!(syncer instanceof RilletItemSyncer))
+ throw new Error("Rillet shipping requires the existing item syncer");
+ return syncer;
+ })();
+ return this.shippingItemSyncerPromise;
+ }
+
// =================================================================
// 1. LOCAL FETCH (Single + Batch)
// =================================================================
+ protected isVoided(local: Accounting.SalesInvoice): boolean {
+ return local.status === "Voided";
+ }
+
+ protected async deleteRemote(remoteId: string): Promise<void> {
+ await this.rilletProvider.deleteInvoice(remoteId);
+ }
+
async fetchLocal(id: string): Promise<Accounting.SalesInvoice | null> {
const invoices = await this.fetchInvoicesByIds([id]);
return invoices.get(id) ?? null;
@@ -208,118 +269,10 @@ export class RilletSalesInvoiceSyncer extends RilletTransactionSyncer<
return this.fetchInvoicesByIds(ids);
}
- private async fetchInvoicesByIds(
+ private fetchInvoicesByIds(
ids: string[]
): Promise<Map<string, Accounting.SalesInvoice>> {
- if (ids.length === 0) return new Map();
-
- const invoiceRows = await this.database
- .selectFrom("salesInvoice")
- // `balance` is derived and lives only on the `salesInvoices` view
- .leftJoin("salesInvoices", "salesInvoices.id", "salesInvoice.id")
- .select([
- "salesInvoice.id",
- "salesInvoice.invoiceId",
- "salesInvoice.companyId",
- "salesInvoice.customerId",
- "salesInvoice.status",
- "salesInvoice.currencyCode",
- "salesInvoice.exchangeRate",
- "salesInvoice.dateIssued",
- "salesInvoice.dateDue",
- "salesInvoice.datePaid",
- "salesInvoice.customerReference",
- "salesInvoice.subtotal",
- "salesInvoice.totalTax",
- "salesInvoice.totalDiscount",
- "salesInvoice.totalAmount",
- "salesInvoices.balance",
- "salesInvoice.updatedAt"
- ])
- .where("salesInvoice.id", "in", ids)
- .where("salesInvoice.companyId", "=", this.companyId)
- .execute();
-
- if (invoiceRows.length === 0) return new Map();
-
- const lineRows = await this.database
- .selectFrom("salesInvoiceLine")
- .leftJoin("item", "item.id", "salesInvoiceLine.itemId")
- .select([
- "salesInvoiceLine.id",
- "salesInvoiceLine.invoiceId",
- "salesInvoiceLine.invoiceLineType",
- "salesInvoiceLine.itemId",
- "salesInvoiceLine.description",
- "salesInvoiceLine.quantity",
- "salesInvoiceLine.unitPrice",
- "salesInvoiceLine.convertedUnitPrice",
- "salesInvoiceLine.taxPercent",
- "item.readableIdWithRevision as itemReadableIdWithRevision"
- ])
- .where(
- "salesInvoiceLine.invoiceId",
- "in",
- invoiceRows.map((r) => r.id)
- )
- .execute();
-
- const linesByInvoiceId = new Map<string, InvoiceLineRow[]>();
- for (const line of lineRows as InvoiceLineRow[]) {
- const existing = linesByInvoiceId.get(line.invoiceId) ?? [];
- existing.push(line);
- linesByInvoiceId.set(line.invoiceId, existing);
- }
-
- const result = new Map<string, Accounting.SalesInvoice>();
- for (const row of invoiceRows as InvoiceRow[]) {
- const lines = linesByInvoiceId.get(row.id) ?? [];
-
- result.set(row.id, {
- id: row.id,
- invoiceId: row.invoiceId,
- companyId: row.companyId,
- customerId: row.customerId,
- customerExternalId: null, // Resolved during mapToRemote
- status: row.status,
- currencyCode: row.currencyCode,
- exchangeRate: Number(row.exchangeRate) || 1,
- dateIssued: row.dateIssued,
- dateDue: row.dateDue,
- datePaid: row.datePaid,
- customerReference: row.customerReference,
- subtotal: Number(row.subtotal) || 0,
- totalTax: Number(row.totalTax) || 0,
- totalDiscount: Number(row.totalDiscount) || 0,
- totalAmount: Number(row.totalAmount) || 0,
- balance: Number(row.balance) || 0,
- lines: lines.map((line) => {
- const quantity = Number(line.quantity) || 0;
- const unitPrice = Number(line.unitPrice) || 0;
- const convertedUnitPrice =
- line.convertedUnitPrice === null ||
- line.convertedUnitPrice === undefined
- ? null
- : Number(line.convertedUnitPrice);
- return {
- id: line.id,
- invoiceLineType: line.invoiceLineType,
- itemId: line.itemId,
- itemCode: line.itemReadableIdWithRevision,
- description: line.description,
- quantity,
- unitPrice,
- convertedUnitPrice,
- taxPercent: Number(line.taxPercent) || 0,
- lineAmount: quantity * unitPrice
- };
- }),
- updatedAt: row.updatedAt ?? new Date().toISOString(),
- raw: row
- });
- }
-
- return result;
+ return loadSalesInvoices(this.database, { companyId: this.companyId, ids });
}
// =================================================================
@@ -368,21 +321,43 @@ export class RilletSalesInvoiceSyncer extends RilletTransactionSyncer<
protected async mapToRemote(
local: Accounting.SalesInvoice
): Promise<RilletInvoiceCreate> {
- // JIT dependencies: customer, then every line item, before the document
+ const document = buildSalesDocumentComponents(local);
+ preflightRilletComponents(document);
+ const hasShipping = document.components.some(
+ (line) => line.kind === "LineShipping" || line.kind === "HeaderShipping"
+ );
+ const shippingAccount = hasShipping
+ ? await this.getShippingAccount(local)
+ : null;
const customerRemoteId = await this.ensureDependencySynced(
"customer",
local.customerId
);
-
const itemRemoteIds = new Map<string, string>();
- for (const line of local.lines) {
- if (line.itemId && !itemRemoteIds.has(line.itemId)) {
- itemRemoteIds.set(
- line.itemId,
- await this.ensureDependencySynced("item", line.itemId)
- );
- }
- }
+ const itemIds = [
+ ...new Set(
+ document.components
+ .filter(
+ (line) =>
+ line.kind !== "LineShipping" &&
+ line.kind !== "HeaderShipping" &&
+ line.itemId
+ )
+ .map((line) => line.itemId!)
+ )
+ ];
+ for (const itemId of itemIds)
+ itemRemoteIds.set(
+ itemId,
+ await this.ensureDependencySynced("item", itemId)
+ );
+ const shippingProductRemoteId = shippingAccount
+ ? await (await this.getShippingItemSyncer()).ensureShippingProduct({
+ shippingAccountId: shippingAccount.id,
+ baseCurrencyCode: local.baseCurrencyCode,
+ baseCurrencyDecimals: local.baseCurrencyDecimalPlaces
+ })
+ : null;
// Dynamic import: keeps @carbon/env (module-load env validation) out of
// the module graph for consumers and tests that never push an invoice
@@ -391,6 +366,9 @@ export class RilletSalesInvoiceSyncer extends RilletTransactionSyncer<
return mapSalesInvoiceToRilletInvoice({
invoice: local,
+ document,
+ shippingProductRemoteId,
+ shippingAccountCode: shippingAccount?.code ?? null,
customerRemoteId,
itemRemoteIds,
subsidiaryId: this.rilletProvider.subsidiaryId,
@@ -419,13 +397,13 @@ export class RilletSalesInvoiceSyncer extends RilletTransactionSyncer<
);
return created.id;
} catch (error) {
- // AR_ONLY invoices REQUIRE external_references, so the optional-
+ // REVENUE_RECOGNITION_ONLY invoices REQUIRE external_references, so the optional-
// reference strip fallback the master-data syncers use cannot apply —
// registering the slugs in the Rillet dashboard is the only fix.
if (isRilletUnknownExternalReferenceTypeError(error)) {
throw new JournalEntrySyncError({
errorCode: "EXTERNAL_REFERENCE_TYPE_MISSING",
- message: `Cannot sync invoice: Rillet requires external references on AR_ONLY invoices, and this organization has no "${RILLET_CARBON_REFERENCE_TYPE}" / "${RILLET_CARBON_COMPANY_REFERENCE_TYPE}" reference types registered. Add them under Rillet Settings → External References, then retry.`,
+ message: `Cannot sync invoice: Rillet requires external references on REVENUE_RECOGNITION_ONLY invoices, and this organization has no "${RILLET_CARBON_REFERENCE_TYPE}" / "${RILLET_CARBON_COMPANY_REFERENCE_TYPE}" reference types registered. Add them under Rillet Settings → External References, then retry.`,
warning: true,
metadata: { invoiceId: localId }
});
diff --git a/packages/ee/src/accounting/providers/rillet/entities/item.ts b/packages/ee/src/accounting/providers/rillet/entities/item.ts
index 5bbe03c594..c9d57e7e1e 100644
--- a/packages/ee/src/accounting/providers/rillet/entities/item.ts
+++ b/packages/ee/src/accounting/providers/rillet/entities/item.ts
@@ -1,11 +1,15 @@
+import { datetime } from "@carbon/database/datetime";
+import { createMappingService } from "../../../core/external-mapping";
import { JournalEntrySyncError } from "../../../core/posting";
import type { Accounting } from "../../../core/types";
+import { withTriggersDisabled } from "../../../core/utils";
import type { Rillet, RilletProductWrite, RilletWriteOmit } from "../models";
import { buildRilletIdempotencyKey } from "../provider";
import {
carbonCompanyExternalReference,
carbonExternalReference,
loadCompanyBaseCurrency,
+ loadCurrencyDecimalPlaces,
loadRilletAccountCodesById,
RilletEntitySyncer,
toRilletMoney,
@@ -53,6 +57,8 @@ export function mapItemToRilletProduct(args: {
accountCodesById: ReadonlyMap<string, string>;
revenueAccountId: string | null;
currency: string;
+ /** `currency.decimalPlaces` of `currency` — the settlement scale, not a default. */
+ decimalPlaces: number;
}): RilletProductWrite {
const { item } = args;
@@ -98,7 +104,11 @@ export function mapItemToRilletProduct(args: {
description: item.description ?? item.name,
price: {
type: "ONE_TIME",
- amount: toRilletMoney(item.unitSalePrice, args.currency)
+ amount: toRilletMoney(
+ item.unitSalePrice,
+ args.currency,
+ args.decimalPlaces
+ )
},
include_in_arr_mrr: false,
revenue_pattern: "EVEN_PERIOD",
@@ -129,17 +139,147 @@ type ItemRow = {
unitSalePrice: number | null;
};
+function mergeProductWrite(
+ current: Rillet.Product,
+ desired: RilletProductWrite
+): RilletProductWrite {
+ const {
+ id: _id,
+ updated_at: _updatedAt,
+ ...merged
+ } = { ...current, ...desired };
+ const replacedTypes = new Set(
+ desired.external_references?.map((ref) => ref.type) ?? []
+ );
+ return {
+ ...merged,
+ price: { ...current.price, ...desired.price },
+ external_references: [
+ ...(current.external_references ?? []).filter(
+ (ref) => !replacedTypes.has(ref.type)
+ ),
+ ...(desired.external_references ?? [])
+ ]
+ };
+}
+
export class RilletItemSyncer extends RilletEntitySyncer<
Accounting.Item,
Rillet.Product,
RilletWriteOmit
> {
+ private shippingProducts = new Map<string, Promise<string>>();
+
+ public async ensureShippingProduct(args: {
+ shippingAccountId: string;
+ baseCurrencyCode: string;
+ baseCurrencyDecimals: number;
+ }): Promise<string> {
+ const helperId = `${args.shippingAccountId}:${args.baseCurrencyCode}`;
+ let pending = this.shippingProducts.get(helperId);
+ if (!pending) {
+ pending = this.resolveShippingProduct(args, helperId).catch((error) => {
+ this.shippingProducts.delete(helperId);
+ throw error;
+ });
+ this.shippingProducts.set(helperId, pending);
+ }
+ return pending;
+ }
+
+ private async resolveShippingProduct(
+ args: {
+ shippingAccountId: string;
+ baseCurrencyCode: string;
+ baseCurrencyDecimals: number;
+ },
+ helperId: string
+ ): Promise<string> {
+ if (!args.baseCurrencyCode.trim())
+ throw new Error("Missing shipping-product base currency");
+ const codes = await this.getAccountCodesById();
+ const item: Accounting.Item = {
+ id: helperId,
+ code: `Carbon Shipping ${args.shippingAccountId} ${args.baseCurrencyCode}`,
+ name: "Customer shipping charges",
+ description: "Customer shipping charges",
+ companyId: this.companyId,
+ type: "Service",
+ unitOfMeasureCode: "EA",
+ unitCost: 0,
+ unitSalePrice: 0,
+ isPurchased: false,
+ isSold: true,
+ isTrackedAsInventory: false,
+ updatedAt: datetime.timestamp()
+ };
+ const payload = mapItemToRilletProduct({
+ item,
+ accountCodesById: codes,
+ revenueAccountId: args.shippingAccountId,
+ currency: args.baseCurrencyCode,
+ decimalPlaces: args.baseCurrencyDecimals
+ });
+ const mappedId = await this.mappingService.getExternalId(
+ "shippingItem",
+ helperId,
+ this.provider.id
+ );
+ if (mappedId) {
+ const current = await this.rilletProvider.getProduct(mappedId);
+ if (!current || current.name !== payload.name)
+ throw new JournalEntrySyncError({
+ errorCode: "UNMAPPED_ACCOUNTS",
+ warning: true,
+ message:
+ "Cannot reuse Shipping Revenue product: its mapped product is missing or has an incompatible name",
+ metadata: { accountId: args.shippingAccountId, helperId }
+ });
+ if (
+ current.account_code === payload.account_code &&
+ current.status !== "INACTIVE" &&
+ current.price.amount.currency === args.baseCurrencyCode &&
+ current.price.type === "ONE_TIME" &&
+ Number(current.price.amount.amount) === 0 &&
+ !current.include_in_arr_mrr &&
+ current.revenue_pattern === "EVEN_PERIOD"
+ )
+ return current.id;
+ const updated = await writeDroppingUnregisteredReferences(
+ mergeProductWrite(current, payload),
+ (data) => this.rilletProvider.updateProduct(mappedId, data)
+ );
+ return updated.id;
+ }
+ const created = await writeDroppingUnregisteredReferences(payload, (data) =>
+ this.rilletProvider.createProduct(
+ data,
+ buildRilletIdempotencyKey({
+ companyId: this.companyId,
+ operation: "product",
+ localId: helperId
+ })
+ )
+ );
+ await withTriggersDisabled(this.database, async (tx) =>
+ createMappingService(tx, this.companyId).link(
+ "shippingItem",
+ helperId,
+ this.provider.id,
+ created.id,
+ { metadata: { accountId: args.shippingAccountId, kind: "shipping" } }
+ )
+ );
+ return created.id;
+ }
+
// Cached per instance — a drain reuses one syncer across its claimed
// operations, so mappings, the sales-account default and the base
// currency are each fetched at most once
private accountCodesByIdPromise?: Promise<Map<string, string>>;
private revenueAccountIdPromise?: Promise<string | null>;
private baseCurrencyPromise?: Promise<string>;
+ private baseCurrencyDecimalsPromise?: Promise<number>;
protected get pushOnlyEntityLabel(): string {
return "Items";
@@ -188,6 +328,21 @@ export class RilletItemSyncer extends RilletEntitySyncer<
return this.baseCurrencyPromise;
}
+ /**
+ * The base currency's own `currency.decimalPlaces` — the product price is a
+ * settlement amount, so its scale is the currency's, never an assumed 2.
+ */
+ private getBaseCurrencyDecimals(): Promise<number> {
+ if (!this.baseCurrencyDecimalsPromise) {
+ this.baseCurrencyDecimalsPromise = (async () =>
+ loadCurrencyDecimalPlaces(this.database, {
+ companyId: this.companyId,
+ currencyCode: await this.getBaseCurrency()
+ }))();
+ }
+ return this.baseCurrencyDecimalsPromise;
+ }
+
// =================================================================
// 2. LOCAL FETCH (Single + Batch)
// =================================================================
@@ -287,12 +442,14 @@ export class RilletItemSyncer extends RilletEntitySyncer<
const accountCodesById = await this.getAccountCodesById();
const revenueAccountId = await this.getRevenueAccountId();
const currency = await this.getBaseCurrency();
+ const decimalPlaces = await this.getBaseCurrencyDecimals();
return mapItemToRilletProduct({
item: local,
accountCodesById,
revenueAccountId,
- currency
+ currency,
+ decimalPlaces
});
}
@@ -307,8 +464,13 @@ export class RilletItemSyncer extends RilletEntitySyncer<
const existingRemoteId = await this.getRemoteId(localId);
if (existingRemoteId) {
+ const current = await this.rilletProvider.getProduct(existingRemoteId);
+ if (!current)
+ throw new Error(
+ `Mapped Rillet product ${existingRemoteId} was not found`
+ );
const updated = await writeDroppingUnregisteredReferences(
- data,
+ mergeProductWrite(current, data),
(payload) =>
this.rilletProvider.updateProduct(existingRemoteId, payload)
);
diff --git a/packages/ee/src/accounting/providers/rillet/entities/payment.ts b/packages/ee/src/accounting/providers/rillet/entities/payment.ts
index 2fbc3c4eaf..971b5d5c4b 100644
--- a/packages/ee/src/accounting/providers/rillet/entities/payment.ts
+++ b/packages/ee/src/accounting/providers/rillet/entities/payment.ts
@@ -9,6 +9,7 @@ import type { Rillet, RilletLocalPayment } from "../models";
import { buildRilletIdempotencyKey, type RilletProvider } from "../provider";
import {
loadCompanyBaseCurrency,
+ loadCurrencyDecimalPlaces,
loadRilletAccountCodesById,
RILLET_CARBON_REFERENCE_TYPE,
toRilletMoney
@@ -16,14 +17,13 @@ import {
// Re-exported for the payment tests (moved to the family-agnostic core, where
// the runtime document-status boundary now lives — post-payment owns status).
-export { getSettledInvoiceStatus } from "../../../core/payment-application";
/**
* RilletPaymentSyncer — the AR payment syncer for Rillet, on the shared
- * `PaymentSyncerBase`. Rillet invoice payments (recorded against pushed AR_ONLY
+ * `PaymentSyncerBase`. Rillet invoice payments (recorded against pushed native
* invoices) settle Carbon sales invoices; the base writes a Draft `payment` +
* `invoiceSettlement` and then invokes the native `post-payment` edge function
- * (GL journal + Posted/Voided status). Pushing is a rejection stub.
+ * (GL journal + Posted/Voided status). Carbon-originated payments push and void through native payment endpoints.
*
* Entity-id contract: the sync operation's entityId is a COMPOSITE. AR keeps
* the prefix-less `"<invoiceRemoteId>:<paymentRemoteId>"` form (back-compat with
@@ -36,7 +36,7 @@ export { getSettledInvoiceStatus } from "../../../core/payment-application";
* branches on (and the shape later QBO/Xero payment syncers mirror).
*
* v1 simplification (documented): exchange rates are recorded as 1 (Rillet
- * payments settle same-currency AR_ONLY invoices / AP bills).
+ * payments settle same-currency native invoices / AP bills).
*/
const SYNC_ID_SEPARATOR = ":";
@@ -151,6 +151,23 @@ export class RilletPaymentSyncer extends PaymentSyncerBase<RilletPayment> {
/** Rillet accepts Carbon-born payments back out (Phase G). */
protected supportsPaymentPush = true;
+ protected supportsPaymentVoidPush = true;
+
+ protected async voidRemotePayment(compositeId: string): Promise<void> {
+ const { family, documentRemoteId, paymentRemoteId } =
+ parseRilletPaymentSyncEntityId(compositeId);
+ if (family === "ap") {
+ await this.rilletProvider.deleteBillPayment(
+ documentRemoteId,
+ paymentRemoteId
+ );
+ } else {
+ await this.rilletProvider.deleteInvoicePayment(
+ documentRemoteId,
+ paymentRemoteId
+ );
+ }
+ }
/** company.baseCurrencyCode, read once per syncer instance (FX gate). */
private baseCurrencyPromise?: Promise<string>;
@@ -165,6 +182,29 @@ export class RilletPaymentSyncer extends PaymentSyncerBase<RilletPayment> {
return this.baseCurrencyPromise;
}
+ /**
+ * `currency.decimalPlaces` per currency code, read once per code per syncer
+ * instance. A payment is a SETTLEMENT amount, so its scale is the currency's
+ * own: JPY settles at 0 decimals, BHD/KWD at 3. `PaymentPushContext` carries
+ * the currency code but no precision, so the syncer resolves it here.
+ */
+ private currencyDecimalsPromises = new Map<string, Promise<number>>();
+
+ private getCurrencyDecimals(currencyCode: string): Promise<number> {
+ let pending = this.currencyDecimalsPromises.get(currencyCode);
+ if (!pending) {
+ pending = loadCurrencyDecimalPlaces(this.database, {
+ companyId: this.companyId,
+ currencyCode
+ }).catch((error) => {
+ this.currencyDecimalsPromises.delete(currencyCode);
+ throw error;
+ });
+ this.currencyDecimalsPromises.set(currencyCode, pending);
+ }
+ return pending;
+ }
+
/** Carbon account.id → Rillet account code, read once per syncer instance. */
private accountCodesByIdPromise?: Promise<Map<string, string>>;
@@ -334,7 +374,7 @@ export class RilletPaymentSyncer extends PaymentSyncerBase<RilletPayment> {
paymentRemoteId,
amount: getRilletPaymentAmount(bill),
currencyCode: getRilletPaymentCurrency(bill),
- exchangeRate: 1,
+ exchangeRate: null,
paidDate,
// The Rillet bill-payment id is the human/provider reference.
reference: paymentRemoteId,
@@ -350,7 +390,7 @@ export class RilletPaymentSyncer extends PaymentSyncerBase<RilletPayment> {
paymentRemoteId,
amount: local.amount ?? 0,
currencyCode: local.currencyCode ?? null,
- exchangeRate: 1,
+ exchangeRate: null,
paidDate: local.date ?? new Date().toISOString().slice(0, 10),
reference: paymentRemoteId,
status:
@@ -403,8 +443,14 @@ export class RilletPaymentSyncer extends PaymentSyncerBase<RilletPayment> {
});
}
+ const decimalPlaces = await this.getCurrencyDecimals(context.currencyCode);
+
const payload = {
- amount: toRilletMoney(context.amount, context.currencyCode),
+ amount: toRilletMoney(
+ context.amount,
+ context.currencyCode,
+ decimalPlaces
+ ),
date: context.paidDate,
account_code: accountCode,
external_references: [
diff --git a/packages/ee/src/accounting/providers/rillet/entities/shared.ts b/packages/ee/src/accounting/providers/rillet/entities/shared.ts
index 7cf51a0e71..ae323c0044 100644
--- a/packages/ee/src/accounting/providers/rillet/entities/shared.ts
+++ b/packages/ee/src/accounting/providers/rillet/entities/shared.ts
@@ -1,4 +1,10 @@
import type { Kysely, KyselyDatabase, KyselyTx } from "@carbon/database/client";
+import {
+ assertExchangeRate,
+ moneyFormatOptions,
+ toDocumentAmount
+} from "@carbon/utils";
+import { parseDate } from "@internationalized/date";
import { getAccountMappings } from "../../../core/account-mapping";
import {
buildDimensionFieldLookup,
@@ -11,12 +17,12 @@ import {
upsertDimensionMapping,
upsertDimensionValueMapping
} from "../../../core/dimension-mapping";
+import { createMappingService } from "../../../core/external-mapping";
import {
JournalEntrySyncError,
type JournalLineDimensionRef,
type PostingSyncSettings,
- resolvePostingSyncSettings,
- roundCurrency
+ resolvePostingSyncSettings
} from "../../../core/posting";
import {
type Accounting,
@@ -40,10 +46,9 @@ import {
* structured JournalEntrySyncFailure envelopes on `SyncResult.error`
* (the same pushToAccounting-override pattern the Xero/QBO syncers
* established) and centralizes the push-only pull rejections.
- * - `RilletTransactionSyncer` — the create-only variant for documents
- * (invoice, bill, journal entry): pushed documents are immutable in v1,
- * so an existing mapping is a hard skip (the QBO journal-syncer
- * contract), replacing the master-data lastSyncedAt fast bailout.
+ * - `RilletTransactionSyncer` — immutable posting amounts for documents.
+ * Existing mappings skip re-creation; mapped invoice/bill voids delete their
+ * native document and retain a durable voided mapping for safe retries.
* - Pure mapping helpers (money formatting, the all-or-nothing address
* group, payment-terms parsing, the carbon external reference) exported
* for tests.
@@ -125,12 +130,58 @@ export async function writeDroppingUnregisteredReferences<
}
}
-/** Format a number as Rillet money — a 2-dp decimal STRING plus currency. */
+/**
+ * Rillet requires an ungrouped decimal string at the document currency scale.
+ *
+ * `decimalPlaces` has NO default: the settlement scale is the currency's own
+ * `currency.decimalPlaces` (data, never a literal — see
+ * `.claude/rules/numeric-precision.md`). A `= 2` default silently serialised a
+ * JPY payment as "1000.00" (JPY settles at 0) and truncated a BHD/KWD third
+ * decimal, so every caller must supply the authoritative value.
+ */
export function toRilletMoney(
amount: number,
- currency: string
+ currency: string,
+ decimalPlaces: number
): Rillet.MonetaryAmount {
- return { amount: roundCurrency(amount).toFixed(2), currency };
+ if (decimalPlaces > 5) throw new Error("Unsupported document decimal scale");
+ return {
+ amount: new Intl.NumberFormat("en-US", {
+ ...moneyFormatOptions(decimalPlaces),
+ useGrouping: false
+ }).format(toDocumentAmount(amount, 1, decimalPlaces)),
+ currency
+ };
+}
+
+/** Rillet converts document units into subsidiary units; Carbon stores the inverse. */
+export function toRilletExchangeRate(args: {
+ baseCurrencyCode: string;
+ documentCurrencyCode: string;
+ foreignPerBaseRate: number;
+ date: string;
+}): Rillet.ExchangeRate | undefined {
+ const {
+ baseCurrencyCode: base,
+ documentCurrencyCode: target,
+ foreignPerBaseRate: rate,
+ date
+ } = args;
+ if (!base.trim() || !target.trim())
+ throw new Error("Rillet exchange-rate currencies are required");
+ // Validation only — the result is discarded. `toDocumentAmount` refuses a
+ // non-finite/invalid rate, and the internal SCALE is the named constant the
+ // precision standard exposes (a bare scale literal is a violation).
+ assertExchangeRate(rate);
+ parseDate(date);
+ if (base === target) {
+ if (rate !== 1)
+ throw new Error("Identical currencies require identity exchange rate");
+ return undefined;
+ }
+ const inverseRate = 1 / rate;
+ assertExchangeRate(inverseRate);
+ return { base: target, target: base, rate: String(inverseRate), date };
}
/**
@@ -220,6 +271,42 @@ export async function loadCompanyBaseCurrency(
return company?.baseCurrencyCode ?? "USD";
}
+/**
+ * `currency.decimalPlaces` for one currency code — the authoritative
+ * settlement scale, group-scoped exactly like `loadBillCostingLines`'s read
+ * (the source the bill syncer already threads into `toRilletMoney`). Throws
+ * rather than defaulting: a guessed scale is how a JPY amount acquires cents.
+ */
+export async function loadCurrencyDecimalPlaces(
+ database: Kysely<KyselyDatabase>,
+ args: { companyId: string; currencyCode: string }
+): Promise<number> {
+ const company = await database
+ .selectFrom("company")
+ .select("companyGroupId")
+ .where("id", "=", args.companyId)
+ .executeTakeFirst();
+
+ if (!company?.companyGroupId)
+ throw new Error(
+ "Company group is required to resolve currency decimal places"
+ );
+
+ const currency = await database
+ .selectFrom("currency")
+ .select("decimalPlaces")
+ .where("code", "=", args.currencyCode)
+ .where("companyGroupId", "=", company.companyGroupId)
+ .executeTakeFirst();
+
+ if (!currency || currency.decimalPlaces == null)
+ throw new Error(
+ `Currency precision for ${args.currencyCode} is required to serialize Rillet amounts`
+ );
+
+ return currency.decimalPlaces;
+}
+
/** Every Rillet read shape carries an optional updated_at timestamp. */
export type RilletTimestamped = { updated_at?: string };
@@ -455,19 +542,23 @@ export abstract class RilletEntitySyncer<
}
/**
- * Base class for the create-only Rillet document syncers (invoice, bill,
- * journal entry): pushed documents are immutable in v1, so the
- * master-data lastSyncedAt fast bailout is replaced with a HARD
- * skip-when-mapped — an existing mapping means the push already happened
- * (the QBO journal-syncer contract). Everything else (structured
- * failures, sequential batches, push-only pulls) comes from
- * RilletEntitySyncer.
+ * Base class for immutable Rillet posting amounts (invoice, bill, journal).
+ * Invoice/bill adapters opt into native deletion on local void. Journal
+ * reversals retain their separate posting identity.
*/
export abstract class RilletTransactionSyncer<
TLocal,
TRemote extends RilletTimestamped,
TOmit extends string | symbol | number
> extends RilletEntitySyncer<TLocal, TRemote, TOmit> {
+ protected isVoided(_local: TLocal): boolean {
+ return false;
+ }
+
+ protected async deleteRemote(_remoteId: string): Promise<void> {
+ throw new Error("This Rillet transaction does not support native voids");
+ }
+
// Per-instance caches — a drain reuses one syncer across its claimed
// operations, so the posting-sync settings and the dimension-value
// lookup are each fetched at most once per drain
@@ -702,23 +793,44 @@ export abstract class RilletTransactionSyncer<
this.provider.id
);
- if (existingMapping?.externalId) {
+ const localEntity = await this.fetchLocal(entityId);
+ if (!localEntity) {
return {
- status: "skipped",
+ status: "error",
action: "none",
localId: entityId,
- remoteId: existingMapping.externalId,
- error: `${this.pushOnlyEntityLabel} already pushed to Rillet — skipping (idempotent)`
+ error: `Entity ${entityId} not found in Carbon`
};
}
- const localEntity = await this.fetchLocal(entityId);
- if (!localEntity) {
+ if (existingMapping?.externalId && this.isVoided(localEntity)) {
+ if (existingMapping.metadata?.voided !== true) {
+ await this.deleteRemote(existingMapping.externalId);
+ await withTriggersDisabled(this.database, async (tx) => {
+ await createMappingService(tx, this.companyId).link(
+ this.entityType,
+ entityId,
+ this.provider.id,
+ existingMapping.externalId,
+ { metadata: { ...existingMapping.metadata, voided: true } }
+ );
+ });
+ }
return {
- status: "error",
+ status: "success",
+ action: "deleted",
+ localId: entityId,
+ remoteId: existingMapping.externalId
+ };
+ }
+
+ if (existingMapping?.externalId) {
+ return {
+ status: "skipped",
action: "none",
localId: entityId,
- error: `Entity ${entityId} not found in Carbon`
+ remoteId: existingMapping.externalId,
+ error: `${this.pushOnlyEntityLabel} already pushed to Rillet — skipping (idempotent)`
};
}
diff --git a/packages/ee/src/accounting/providers/rillet/models.ts b/packages/ee/src/accounting/providers/rillet/models.ts
index 08fed6813c..01b93fad29 100644
--- a/packages/ee/src/accounting/providers/rillet/models.ts
+++ b/packages/ee/src/accounting/providers/rillet/models.ts
@@ -197,7 +197,7 @@ export namespace Rillet {
/**
* Carbon only ever writes ONE_TIME prices (Rillet also supports
- * FIXED_RECURRING and USAGE; Carbon-generated AR_ONLY invoices carry
+ * FIXED_RECURRING and USAGE; Carbon-generated invoices carry
* their own line totals, so the product price is nominal).
*/
export const ProductPriceSchema = z.object({
@@ -224,8 +224,25 @@ export namespace Rillet {
export type Product = z.infer<typeof ProductSchema>;
- /** AR_ONLY invoice item — product_id is REQUIRED on every line. */
+ export const ExchangeRateSchema = z.object({
+ base: z.string().min(1),
+ target: z.string().min(1),
+ rate: z
+ .string()
+ .refine((value) => Number.isFinite(Number(value)) && Number(value) > 0),
+ date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/)
+ });
+ export type ExchangeRate = z.infer<typeof ExchangeRateSchema>;
+
+ /** External invoice item — product_id is REQUIRED on every line. */
export const InvoiceItemSchema = z.object({
+ revenue: z
+ .object({
+ account_code: z.string().optional(),
+ period: z.object({ start: z.string(), end: z.string() }).optional(),
+ pattern: z.enum(["DAILY", "EVEN_PERIOD"]).optional()
+ })
+ .optional(),
id: z.string().optional(),
product_id: z.string(),
description: z.string(),
@@ -238,12 +255,12 @@ export namespace Rillet {
export type InvoiceItem = z.infer<typeof InvoiceItemSchema>;
/**
- * AR_ONLY invoice: Carbon keeps generating/sending the invoice; Rillet
- * carries the receivable. `invoice_number` is Carbon's readable id.
+ * External invoice: Carbon issues the invoice; Rillet carries the receivable.
+ * New postings use REVENUE_RECOGNITION_ONLY for fixed FX and immediate revenue. `invoice_number` is Carbon's readable id.
*/
export const InvoiceSchema = z.object({
id: z.string(),
- scope: z.literal("AR_ONLY"),
+ scope: z.enum(["AR_ONLY", "REVENUE_RECOGNITION_ONLY"]),
customer_id: z.string(),
/** YYYY-MM-DD. */
invoice_date: z.string(),
@@ -252,7 +269,7 @@ export namespace Rillet {
due_date: z.string().optional(),
tax_amount: MonetaryAmountSchema.optional(),
subsidiary_id: z.string().optional(),
- exchange_rate: z.number().optional(),
+ exchange_rate: ExchangeRateSchema.optional(),
items: z.array(InvoiceItemSchema).min(1),
external_references: z.array(ExternalReferenceSchema).min(1),
status: z.string().optional(),
@@ -295,7 +312,7 @@ export namespace Rillet {
subsidiary_id: z.string().optional(),
impact_date: z.string().optional(),
external_references: z.array(ExternalReferenceSchema).optional(),
- exchange_rate: z.number().optional(),
+ exchange_rate: ExchangeRateSchema.optional(),
status: BillStatusSchema.optional(),
updated_at: z.string().optional()
});
diff --git a/packages/ee/src/accounting/providers/rillet/provider.ts b/packages/ee/src/accounting/providers/rillet/provider.ts
index 7b1840a66a..7070ab5ef9 100644
--- a/packages/ee/src/accounting/providers/rillet/provider.ts
+++ b/packages/ee/src/accounting/providers/rillet/provider.ts
@@ -751,6 +751,40 @@ export class RilletProvider extends BaseProvider {
return unwrapRilletEntity<T>(response.data, envelopeKey);
}
+ private async deleteEntity(path: string, operation: string): Promise<void> {
+ const response = await this.request<unknown>("DELETE", path);
+ // The mapping survives a delete. A retry after a successful remote delete
+ // but failed local transaction must converge when the resource is absent.
+ if (response.error && response.code !== 404) {
+ throwRilletApiError(operation, response);
+ }
+ }
+
+ async deleteInvoice(id: string): Promise<void> {
+ await this.deleteEntity(`/invoices/${id}`, "void invoice");
+ }
+
+ async deleteBill(id: string): Promise<void> {
+ await this.deleteEntity(`/bills/${id}`, "void bill");
+ }
+
+ async deleteInvoicePayment(
+ invoiceId: string,
+ paymentId: string
+ ): Promise<void> {
+ await this.deleteEntity(
+ `/invoices/${invoiceId}/payments/${paymentId}`,
+ "void invoice payment"
+ );
+ }
+
+ async deleteBillPayment(billId: string, paymentId: string): Promise<void> {
+ await this.deleteEntity(
+ `/bills/${billId}/payments/${paymentId}`,
+ "void bill payment"
+ );
+ }
+
private async writeEntity<T>(args: {
method: "POST" | "PUT";
path: string;
@@ -900,7 +934,7 @@ export class RilletProvider extends BaseProvider {
return this.readEntity<Rillet.Invoice>(`/invoices/${id}`, "invoice");
}
- /** Create an AR_ONLY invoice (Carbon invoices; Rillet carries the receivable). */
+ /** Create a native invoice (Carbon issues it; Rillet recognizes the posting). */
async createInvoice(
invoice: RilletInvoiceCreate,
idempotencyKey?: string
diff --git a/packages/ee/src/accounting/providers/xero/entities/__tests__/bill.test.ts b/packages/ee/src/accounting/providers/xero/entities/__tests__/bill.test.ts
index 3cc9f5dd28..a9b9681ab1 100644
--- a/packages/ee/src/accounting/providers/xero/entities/__tests__/bill.test.ts
+++ b/packages/ee/src/accounting/providers/xero/entities/__tests__/bill.test.ts
@@ -181,6 +181,15 @@ function makeBillDb(config: {
orderBy: () => builder,
async execute() {
if (table === "journalLine") return config.journalLine;
+ if (table === "purchaseInvoiceLine")
+ return [
+ {
+ quantity: 1,
+ supplierUnitPrice: 100 * config.purchaseInvoice.exchangeRate,
+ supplierShippingCost: 0,
+ supplierTaxAmount: 0
+ }
+ ];
if (table === "journalLineDimension") return [];
if (table === "purchaseOrderLine") return [];
if (table === "externalIntegrationMapping as m")
@@ -188,7 +197,11 @@ function makeBillDb(config: {
return [];
},
async executeTakeFirst() {
- if (table === "purchaseInvoice") return config.purchaseInvoice;
+ if (table === "purchaseInvoice")
+ return { ...config.purchaseInvoice, postingDate: "2026-09-07" };
+ if (table === "company")
+ return { baseCurrencyCode: "USD", companyGroupId: "group-1" };
+ if (table === "currency") return { decimalPlaces: 2 };
if (table === "accountDefault") return config.accountDefault;
return undefined;
}
@@ -218,14 +231,14 @@ function makeBillSyncer(db: never, remoteId: string | null) {
}
describe("BillSyncer.mapToRemote (FX + guards)", () => {
- const fxDb = () =>
+ const fxDb = (exchangeRate = 0.8) =>
makeBillDb({
- purchaseInvoice: { currencyCode: "EUR", exchangeRate: 2 },
+ purchaseInvoice: { currencyCode: "EUR", exchangeRate },
journalLine: [
{
id: "jl-1",
accountId: "acct_grir",
- amount: 300,
+ amount: 100,
description: "GR/IR Clearing",
documentLineReference: null,
accountClass: "Asset"
@@ -233,7 +246,7 @@ describe("BillSyncer.mapToRemote (FX + guards)", () => {
{
id: "jl-2",
accountId: "acct_ap",
- amount: 300,
+ amount: 100,
description: "Accounts Payable",
documentLineReference: null,
accountClass: "Liability"
@@ -255,15 +268,15 @@ describe("BillSyncer.mapToRemote (FX + guards)", () => {
it("pins CurrencyRate and replays transaction-currency amounts (AP excluded)", async () => {
const payload = await makeBillSyncer(fxDb(), null).mapToRemote(
- bill({ currencyCode: "EUR", exchangeRate: 2 })
+ bill({ currencyCode: "EUR", exchangeRate: 0.8 })
);
expect(payload.CurrencyCode).toBe("EUR");
- expect(payload.CurrencyRate).toBe(2);
+ expect(payload.CurrencyRate).toBe(0.8);
expect(payload.LineItems).toEqual([
{
Description: "GR/IR Clearing",
- LineAmount: 150,
+ LineAmount: 80,
AccountCode: "2125",
TaxType: "NONE"
}
@@ -273,6 +286,13 @@ describe("BillSyncer.mapToRemote (FX + guards)", () => {
expect(payload.TotalTax).toBeUndefined();
});
+ it("pins a foreign identity rate instead of letting Xero choose a rate", async () => {
+ const payload = await makeBillSyncer(fxDb(1), null).mapToRemote(
+ bill({ currencyCode: "EUR", exchangeRate: 1 })
+ );
+ expect(payload.CurrencyRate).toBe(1);
+ });
+
it("lands a DOC_HAS_PAYMENTS Warning when re-pushing a paid bill", async () => {
try {
await makeBillSyncer(fxDb(), "xero-bill-1").mapToRemote(
@@ -294,3 +314,39 @@ describe("BillSyncer.mapToRemote (FX + guards)", () => {
expect(result).toContain("must be posted");
});
});
+
+it("refuses unsupported Xero bill monetary precision without changing principal", () => {
+ expect(() =>
+ buildXeroBillLineItems({
+ bill: bill(),
+ costingLines: [
+ {
+ id: "cost",
+ accountId: "acct_grir",
+ amount: 1.001,
+ description: "Subcent cost"
+ }
+ ],
+ accountCodesById: CODES
+ })
+ ).toThrow(/Xero.*precision|Xero.*decimal/i);
+});
+it.each([
+ false,
+ true
+])("opts into supported unit precision at the actual bill transport (batch=%s)", async (batch) => {
+ const syncer = makeBillSyncer({} as never, null) as any;
+ const requests: string[] = [];
+ syncer.provider.request = async (_method: string, url: string) => {
+ requests.push(url);
+ return { data: { Invoices: [{ InvoiceID: "remote" }] } };
+ };
+ const payload = {
+ Type: "ACCPAY",
+ InvoiceNumber: "AP000001",
+ LineItems: [{ LineAmount: 10, AccountCode: "2125", TaxType: "NONE" }]
+ };
+ if (batch) await syncer.upsertRemoteBatch([{ localId: "pi_1", payload }]);
+ else await syncer.upsertRemote(payload, "pi_1");
+ expect(requests).toEqual(["/Invoices?unitdp=4"]);
+});
diff --git a/packages/ee/src/accounting/providers/xero/entities/__tests__/invoice.test.ts b/packages/ee/src/accounting/providers/xero/entities/__tests__/invoice.test.ts
index 63f4bf76f7..d17881b2fd 100644
--- a/packages/ee/src/accounting/providers/xero/entities/__tests__/invoice.test.ts
+++ b/packages/ee/src/accounting/providers/xero/entities/__tests__/invoice.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, it } from "vitest";
+import { describe, expect, it, vi } from "vitest";
import type { Accounting } from "../../../../core/types";
import type { Xero } from "../../models";
import { SalesInvoiceSyncer } from "../invoice";
@@ -22,6 +22,11 @@ const invoice = (): Accounting.SalesInvoice =>
customerExternalId: null,
status: "Pending",
currencyCode: "USD",
+ baseCurrencyCode: "USD",
+ baseCurrencyDecimalPlaces: 2,
+ currencyDecimalPlaces: 2,
+ headerShippingCost: 0,
+ shippingRevenueAccountId: "acct_shipping",
exchangeRate: 1,
dateIssued: "2026-08-04",
dateDue: null,
@@ -41,6 +46,9 @@ const invoice = (): Accounting.SalesInvoice =>
description: "Widget",
quantity: 2,
unitPrice: 50,
+ shippingCost: 0,
+ addOnCost: 0,
+ nonTaxableAddOnCost: 0,
taxPercent: 0,
lineAmount: 100
}
@@ -49,7 +57,10 @@ const invoice = (): Accounting.SalesInvoice =>
}) as unknown as Accounting.SalesInvoice;
function makeInvoiceDb(config: {
- accountDefault: { salesAccount: string | null };
+ accountDefault: {
+ salesAccount: string | null;
+ salesShippingRevenueAccount?: string | null;
+ };
accountMappings: Array<{
id: string;
accountId: string;
@@ -74,6 +85,13 @@ function makeInvoiceDb(config: {
},
async executeTakeFirst() {
if (table === "accountDefault") return config.accountDefault;
+ if (table === "account as a")
+ return {
+ id: config.accountDefault.salesShippingRevenueAccount,
+ class: "Revenue",
+ active: true,
+ isGroup: false
+ };
return undefined;
}
};
@@ -93,8 +111,9 @@ function makeInvoiceSyncer(db: never) {
entityType: "invoice"
});
(syncer as unknown as Record<string, unknown>).getRemoteId = async () => null;
- (syncer as unknown as Record<string, unknown>).ensureDependencySynced =
- async (type: string) => `${type}-remote`;
+ (syncer as unknown as Record<string, unknown>).ensureDependencySynced = vi.fn(
+ async (type: string) => `${type}-remote`
+ );
return syncer as unknown as {
mapToRemote(local: Accounting.SalesInvoice): Promise<Xero.Invoice>;
};
@@ -188,6 +207,9 @@ const fxInvoice = (): Accounting.SalesInvoice =>
// base currency: 2 x 50 = 100 base, i.e. 80 EUR
unitPrice: 50,
convertedUnitPrice: 40,
+ shippingCost: 0,
+ addOnCost: 0,
+ nonTaxableAddOnCost: 0,
taxPercent: 0,
lineAmount: 100
}
@@ -214,8 +236,9 @@ describe("SalesInvoiceSyncer.mapToRemote (foreign currency)", () => {
it("pushes line amounts in the currency the payload declares", async () => {
const payload = await makeInvoiceSyncer(db()).mapToRemote(fxInvoice());
expect(payload.CurrencyCode).toBe("EUR");
- // 40 EUR/ea, not the 50 base
- expect(payload.LineItems[0]?.UnitAmount).toBe(40);
+ // One monetary unit carries the full 80 EUR net; source detail remains.
+ expect(payload.LineItems[0]?.UnitAmount).toBe(80);
+ expect(payload.LineItems[0]?.Description).toContain("2 × 40 EUR");
expect(payload.LineItems[0]?.LineAmount).toBe(80);
});
@@ -232,3 +255,244 @@ describe("SalesInvoiceSyncer.mapToRemote (foreign currency)", () => {
expect(payload.CurrencyRate).toBeUndefined();
});
});
+
+const mappedAccounts = [
+ {
+ id: "sales-map",
+ accountId: "acct_sales",
+ externalId: "sales-remote",
+ metadata: { externalCode: "4000" },
+ lastSyncedAt: null,
+ accountNumber: "4000",
+ accountName: "Sales"
+ },
+ {
+ id: "shipping-map",
+ accountId: "acct_shipping",
+ externalId: "shipping-remote",
+ metadata: { externalCode: "4010" },
+ lastSyncedAt: null,
+ accountNumber: "4010",
+ accountName: "Shipping"
+ }
+];
+function chargedInvoice(): Accounting.SalesInvoice {
+ const source = invoice();
+ return {
+ ...source,
+ currencyCode: "EUR",
+ exchangeRate: 0.8,
+ headerShippingCost: 5,
+ shippingRevenueAccountId: "acct_shipping",
+ subtotal: 133,
+ totalTax: 13,
+ totalAmount: 151,
+ balance: 151,
+ lines: [
+ {
+ ...source.lines[0]!,
+ quantity: 1,
+ unitPrice: 100,
+ convertedUnitPrice: 80,
+ shippingCost: 10,
+ addOnCost: 20,
+ nonTaxableAddOnCost: 3,
+ taxPercent: 0.1
+ }
+ ]
+ };
+}
+describe("Xero native sales components", () => {
+ it("maps sales/shipping separately and sends fractional native tax exactly once in document currency", async () => {
+ const syncer = makeInvoiceSyncer(
+ makeInvoiceDb({
+ accountDefault: {
+ salesAccount: "acct_sales",
+ salesShippingRevenueAccount: "acct_shipping"
+ },
+ accountMappings: mappedAccounts
+ })
+ );
+ const payload = await syncer.mapToRemote(chargedInvoice());
+ expect(payload).toMatchObject({
+ SubTotal: 110.4,
+ TotalTax: 10.4,
+ Total: 120.8,
+ AmountDue: 120.8,
+ CurrencyCode: "EUR",
+ CurrencyRate: 0.8,
+ LineAmountTypes: "Exclusive"
+ });
+ expect(
+ payload.LineItems.map((line) => [
+ line.AccountCode,
+ line.LineAmount,
+ line.TaxAmount,
+ line.TaxType
+ ])
+ ).toEqual([
+ ["4000", 80, 8, "OUTPUT"],
+ ["4000", 16, 1.6, "OUTPUT"],
+ ["4000", 2.4, 0, "NONE"],
+ ["4010", 8, 0.8, "OUTPUT"],
+ ["4010", 4, 0, "NONE"]
+ ]);
+ });
+ it("preflights unmapped shipping before customer/item provisioning", async () => {
+ const syncer = makeInvoiceSyncer(
+ makeInvoiceDb({
+ accountDefault: {
+ salesAccount: "acct_sales",
+ salesShippingRevenueAccount: "acct_shipping"
+ },
+ accountMappings: mappedAccounts.slice(0, 1)
+ })
+ );
+ await expect(syncer.mapToRemote(chargedInvoice())).rejects.toMatchObject({
+ failure: { errorCode: "UNMAPPED_ACCOUNTS", warning: true }
+ });
+ expect(
+ (syncer as unknown as { ensureDependencySynced: unknown })
+ .ensureDependencySynced
+ ).not.toHaveBeenCalled();
+ });
+});
+
+function reviewSyncer() {
+ const database = makeInvoiceDb({
+ accountDefault: {
+ salesAccount: "acct_sales",
+ salesShippingRevenueAccount: "acct_replacement"
+ },
+ accountMappings: [
+ ...mappedAccounts,
+ {
+ ...mappedAccounts[1]!,
+ id: "replacement-map",
+ accountId: "acct_replacement",
+ metadata: { externalCode: "4050" }
+ }
+ ]
+ });
+ return makeInvoiceSyncer(database);
+}
+describe("Xero posted facts and monetary representation", () => {
+ it("keeps the posted shipping account after changing defaults", async () => {
+ const source = Object.assign(chargedInvoice(), {
+ shippingRevenueAccountId: "acct_shipping"
+ });
+ const payload = await reviewSyncer().mapToRemote(source);
+ expect(
+ payload.LineItems.filter((line) =>
+ line.Description?.startsWith("Shipping")
+ ).map((line) => line.AccountCode)
+ ).toEqual(["4010", "4010"]);
+ });
+ it("represents bulk native tax against a monetary unit without losing the source quantity", async () => {
+ const source = invoice();
+ source.totalTax = 10;
+ source.totalAmount = 110;
+ source.balance = 110;
+ source.lines[0] = {
+ ...source.lines[0]!,
+ quantity: 100,
+ unitPrice: 1,
+ taxPercent: 0.1
+ };
+ const payload = await reviewSyncer().mapToRemote(source);
+ expect(payload.LineItems[0]).toMatchObject({
+ Quantity: 1,
+ UnitAmount: 100,
+ LineAmount: 100,
+ TaxAmount: 10
+ });
+ expect(payload.LineItems[0]?.Description).toContain("100 × 1 USD");
+ });
+ it("refuses subcent document principal before dependency writes", async () => {
+ const source = invoice();
+ source.currencyDecimalPlaces = 3;
+ source.subtotal = 1.001;
+ source.totalAmount = 1.001;
+ source.balance = 1.001;
+ source.lines[0] = { ...source.lines[0]!, quantity: 1, unitPrice: 1.001 };
+ await expect(reviewSyncer().mapToRemote(source)).rejects.toThrow(
+ /Xero.*precision|Xero.*decimal/i
+ );
+ });
+ it("pins an explicit foreign 1:1 rate", async () => {
+ const source = invoice();
+ source.currencyCode = "EUR";
+ expect((await reviewSyncer().mapToRemote(source)).CurrencyRate).toBe(1);
+ });
+ it.each([
+ false,
+ true
+ ])("opts into supported unit precision at the actual invoice transport (batch=%s)", async (batch) => {
+ const syncer = reviewSyncer();
+ const requests: string[] = [];
+ (syncer as any).provider.request = async (_method: string, url: string) => {
+ requests.push(url);
+ return { data: { Invoices: [{ InvoiceID: "remote" }] } };
+ };
+ const payload = await syncer.mapToRemote(invoice());
+ if (batch)
+ await (syncer as any).upsertRemoteBatch([{ localId: "si_1", payload }]);
+ else await (syncer as any).upsertRemote(payload, "si_1");
+ expect(requests).toEqual(["/Invoices?unitdp=4"]);
+ });
+});
+
+it("preserves an exact extended net when the source unit price has four decimals", async () => {
+ const source = fxInvoice();
+ source.subtotal = 59.997;
+ source.totalAmount = 59.997;
+ source.balance = 59.997;
+ source.lines[0] = {
+ ...source.lines[0]!,
+ quantity: 3,
+ unitPrice: 19.999,
+ convertedUnitPrice: 15.9992
+ };
+ const payload = await reviewSyncer().mapToRemote(source);
+ expect(payload.LineItems[0]).toMatchObject({
+ Quantity: 1,
+ UnitAmount: 48,
+ LineAmount: 48
+ });
+ expect(payload.LineItems[0]?.Description).toContain("3 × 15.9992 EUR");
+ expect(payload.Total).toBe(48);
+});
+it("preserves a negative untaxed offset without increasing the invoice principal", async () => {
+ const source = invoice();
+ source.subtotal = 90;
+ source.totalAmount = 90;
+ source.balance = 90;
+ source.lines.push({
+ ...source.lines[0]!,
+ id: "offset",
+ quantity: 5,
+ unitPrice: -2
+ });
+ const payload = await reviewSyncer().mapToRemote(source);
+ expect(
+ payload.LineItems.map((line) => [
+ line.Quantity,
+ line.UnitAmount,
+ line.LineAmount,
+ line.TaxAmount
+ ])
+ ).toEqual([
+ [1, 100, 100, 0],
+ [1, -10, -10, 0]
+ ]);
+ expect(payload.Total).toBe(90);
+});
+it("refuses missing original shipping provenance before provisioning", async () => {
+ const source = chargedInvoice();
+ source.shippingRevenueAccountId = null;
+ const syncer = reviewSyncer();
+ await expect(syncer.mapToRemote(source)).rejects.toMatchObject({
+ failure: { errorCode: "UNMAPPED_ACCOUNTS", warning: true }
+ });
+ expect((syncer as any).ensureDependencySynced).not.toHaveBeenCalled();
+});
diff --git a/packages/ee/src/accounting/providers/xero/entities/__tests__/payment.test.ts b/packages/ee/src/accounting/providers/xero/entities/__tests__/payment.test.ts
index a28f9c0490..c7443513e8 100644
--- a/packages/ee/src/accounting/providers/xero/entities/__tests__/payment.test.ts
+++ b/packages/ee/src/accounting/providers/xero/entities/__tests__/payment.test.ts
@@ -110,7 +110,7 @@ describe("XeroPaymentSyncer.mapToNormalized", () => {
paymentRemoteId: "pay-1",
amount: 500,
currencyCode: "USD",
- exchangeRate: 1,
+ exchangeRate: null,
paidDate: "2026-08-01",
reference: "pay-1",
status: "settled"
@@ -180,7 +180,7 @@ describe("XeroPaymentSyncer.mapToNormalized", () => {
);
expect(normalized.amount).toBe(40);
expect(normalized.currencyCode).toBeNull();
- expect(normalized.exchangeRate).toBe(1);
+ expect(normalized.exchangeRate).toBeNull();
});
});
diff --git a/packages/ee/src/accounting/providers/xero/entities/bill.ts b/packages/ee/src/accounting/providers/xero/entities/bill.ts
index 7b7b841503..2ee990fd2d 100644
--- a/packages/ee/src/accounting/providers/xero/entities/bill.ts
+++ b/packages/ee/src/accounting/providers/xero/entities/bill.ts
@@ -1,4 +1,5 @@
import type { KyselyTx } from "@carbon/database/client";
+import { assertExchangeRate, toBaseAmount } from "@carbon/utils";
import { sql } from "kysely";
import { loadAccountCodesById } from "../../../core/account-mapping";
import {
@@ -8,7 +9,7 @@ import {
toTransactionCurrencyLines
} from "../../../core/document-costing";
import { createMappingService } from "../../../core/external-mapping";
-import { JournalEntrySyncError, roundCurrency } from "../../../core/posting";
+import { JournalEntrySyncError } from "../../../core/posting";
import {
type Accounting,
BaseEntitySyncer,
@@ -17,6 +18,7 @@ import {
import { throwXeroApiError } from "../../../core/utils";
import { parseDotnetDate, type Xero } from "../models";
import type { XeroProvider } from "../provider";
+import { assertXeroMoneyPrecision } from "../serialize";
// Note: This syncer uses the default ID mapping from BaseEntitySyncer
// which uses the externalIntegrationMapping table with entityType "bill"
@@ -177,6 +179,7 @@ export function buildXeroBillLineItems(args: {
});
}
+ assertXeroMoneyPrecision(...args.costingLines.map((line) => line.amount));
const nonTracked = args.nonTrackedItemIds;
return args.costingLines.map((line) => {
const attachItemCode =
@@ -185,7 +188,7 @@ export function buildXeroBillLineItems(args: {
: null;
return {
Description: costingLineItemLabel(line) ?? line.description ?? undefined,
- LineAmount: roundCurrency(line.amount),
+ LineAmount: line.amount,
AccountCode: args.accountCodesById.get(line.accountId!)!,
TaxType: "NONE",
...(attachItemCode ? { ItemCode: attachItemCode.slice(0, 30) } : {})
@@ -453,16 +456,6 @@ export class BillSyncer extends BaseEntitySyncer<
return this.accountCodesByIdPromise;
}
- /** accountDefault.payablesAccount — the AP control line to exclude. */
- private async getPayablesAccountId(): Promise<string | null> {
- const defaults = await this.database
- .selectFrom("accountDefault")
- .select("payablesAccount")
- .where("companyId", "=", this.companyId)
- .executeTakeFirst();
- return defaults?.payablesAccount ?? null;
- }
-
// =================================================================
// 5. TRANSFORMATION (Carbon -> Xero) — account-costed journal replay
// =================================================================
@@ -484,35 +477,25 @@ export class BillSyncer extends BaseEntitySyncer<
});
}
- // Get supplier's Xero ContactID - ensure supplier is synced first
- let contactId = local.supplierExternalId;
- if (!contactId && local.supplierId) {
- contactId = await this.ensureDependencySynced("vendor", local.supplierId);
- }
-
- if (!contactId) {
- throw new Error(
- `Cannot sync bill ${local.id}: No supplier linked or supplier not synced to Xero`
- );
- }
-
// Account-costed replay of the bill's posted Purchase Invoice journal.
- const payablesAccountId = await this.getPayablesAccountId();
const accountCodesById = await this.getAccountCodesById();
const {
lines: costingLines,
currencyCode,
- exchangeRate
+ exchangeRate,
+ documentTotal,
+ decimalPlaces,
+ baseCurrencyCode
} = await loadBillCostingLines(this.database, {
companyId: this.companyId,
- billId: local.id,
- payablesAccountId
+ billId: local.id
});
- const transactionLines = toTransactionCurrencyLines(
- costingLines,
- exchangeRate
- );
+ const transactionLines = toTransactionCurrencyLines(costingLines, {
+ exchangeRate,
+ documentTotal,
+ decimalPlaces
+ });
const lineItems = buildXeroBillLineItems({
bill: local,
@@ -525,6 +508,18 @@ export class BillSyncer extends BaseEntitySyncer<
nonTrackedItemIds: undefined
});
+ // Get supplier's Xero ContactID - ensure supplier is synced first
+ let contactId = local.supplierExternalId;
+ if (!contactId && local.supplierId) {
+ contactId = await this.ensureDependencySynced("vendor", local.supplierId);
+ }
+
+ if (!contactId) {
+ throw new Error(
+ `Cannot sync bill ${local.id}: No supplier linked or supplier not synced to Xero`
+ );
+ }
+
// Calculate due date: use dateDue if provided, otherwise default to Net 30
let dueDate = local.dateDue;
if (!dueDate && local.dateIssued) {
@@ -548,8 +543,9 @@ export class BillSyncer extends BaseEntitySyncer<
DueDate: dueDate,
Status: CARBON_TO_XERO_STATUS[local.status],
CurrencyCode: currencyCode,
- // Pin the provider rate on FX bills (omit at parity rate 1).
- CurrencyRate: exchangeRate !== 1 ? exchangeRate : undefined,
+ // Pin every foreign snapshot, including negotiated 1:1 rates.
+ CurrencyRate:
+ currencyCode !== baseCurrencyCode ? exchangeRate : undefined,
// Tax-neutral replay: lines embed tax; let Xero compute totals from the
// NONE-taxed line amounts (no SubTotal/TotalTax/Total conflict).
LineItems: lineItems
@@ -563,6 +559,23 @@ export class BillSyncer extends BaseEntitySyncer<
protected async mapToLocal(
remote: Xero.Invoice
): Promise<Partial<Accounting.Bill>> {
+ const company = await this.database
+ .selectFrom("company")
+ .select("baseCurrencyCode")
+ .where("id", "=", this.companyId)
+ .executeTakeFirst();
+ const currencyCode = remote.CurrencyCode ?? company?.baseCurrencyCode;
+ if (!currencyCode || !company?.baseCurrencyCode)
+ throw new Error("Xero bill currency metadata is required");
+ const exchangeRate =
+ remote.CurrencyRate ??
+ (currencyCode === company.baseCurrencyCode ? 1 : null);
+ if (exchangeRate === null)
+ throw new Error("Xero foreign bill exchange rate is required");
+ assertExchangeRate(exchangeRate);
+ if (currencyCode === company.baseCurrencyCode && exchangeRate !== 1)
+ throw new Error("Base-currency bill requires identity exchange rate");
+
// Determine Carbon status based on Xero status and amounts
let status = XERO_TO_CARBON_STATUS[remote.Status];
@@ -618,13 +631,13 @@ export class BillSyncer extends BaseEntitySyncer<
dateIssued: remote.Date ?? null,
dateDue: remote.DueDate ?? null,
datePaid: remote.Status === "PAID" ? new Date().toISOString() : null,
- currencyCode: remote.CurrencyCode ?? "USD",
- exchangeRate: remote.CurrencyRate ?? 1,
- subtotal: remote.SubTotal ?? 0,
- totalTax: remote.TotalTax ?? 0,
+ currencyCode,
+ exchangeRate,
+ subtotal: toBaseAmount(remote.SubTotal ?? 0, exchangeRate),
+ totalTax: toBaseAmount(remote.TotalTax ?? 0, exchangeRate),
totalDiscount: 0,
- totalAmount: remote.Total ?? 0,
- balance: remote.AmountDue ?? 0,
+ totalAmount: toBaseAmount(remote.Total ?? 0, exchangeRate),
+ balance: toBaseAmount(remote.AmountDue ?? 0, exchangeRate),
supplierReference: remote.Reference ?? null,
lines,
updatedAt: remote.UpdatedDateUTC
@@ -642,6 +655,11 @@ export class BillSyncer extends BaseEntitySyncer<
data: Partial<Accounting.Bill>,
remoteId: string
): Promise<string> {
+ if (!data.currencyCode || data.exchangeRate == null)
+ throw new Error(
+ "Bill currency and exchange rate are required before storing supplier amounts"
+ );
+ assertExchangeRate(data.exchangeRate);
const existingLocalId = await this.getLocalId(remoteId);
// Resolve supplier from Xero ContactID using mapping service
@@ -734,8 +752,8 @@ export class BillSyncer extends BaseEntitySyncer<
dateIssued: data.dateIssued ?? null,
dateDue: data.dateDue ?? null,
datePaid: data.datePaid ?? null,
- currencyCode: data.currencyCode ?? "USD",
- exchangeRate: data.exchangeRate ?? 1,
+ currencyCode: data.currencyCode,
+ exchangeRate: data.exchangeRate,
subtotal: data.subtotal ?? 0,
totalTax: data.totalTax ?? 0,
totalDiscount: data.totalDiscount ?? 0,
@@ -791,6 +809,7 @@ export class BillSyncer extends BaseEntitySyncer<
await tx
.deleteFrom("purchaseInvoiceLine")
.where("invoiceId", "=", invoiceId)
+ .where("companyId", "=", this.companyId)
.execute();
if (lines.length === 0) return;
@@ -842,39 +861,33 @@ export class BillSyncer extends BaseEntitySyncer<
.selectFrom("purchaseInvoice")
.select(["companyId", "createdBy", "exchangeRate"])
.where("id", "=", invoiceId)
+ .where("companyId", "=", this.companyId)
.executeTakeFirstOrThrow();
- // Insert new lines
- for (const line of lines) {
+ const rows = lines.map((line) => {
const itemId = line.itemCode
? (itemMap.get(line.itemCode) ?? null)
: null;
- await tx
- .insertInto("purchaseInvoiceLine")
- .values({
- invoiceId,
- companyId: invoice.companyId,
- createdBy: invoice.createdBy,
- description: line.description,
- quantity: line.quantity,
- unitPrice: line.unitPrice,
- supplierUnitPrice: line.unitPrice,
- itemId,
- accountId: line.accountNumber
- ? (accountIdMap.get(line.accountNumber) ?? null)
- : null,
- taxPercent: line.taxPercent,
- taxAmount: line.taxAmount,
- supplierTaxAmount: line.taxAmount ?? 0,
- totalAmount: line.totalAmount,
- supplierExtendedPrice: line.totalAmount,
- exchangeRate: invoice.exchangeRate,
- invoiceLineType: itemId ? "Part" : "G/L Account",
- supplierShippingCost: 0
- })
- .execute();
- }
+ return {
+ invoiceId,
+ companyId: invoice.companyId,
+ createdBy: invoice.createdBy,
+ description: line.description,
+ quantity: line.quantity,
+ supplierUnitPrice: line.unitPrice,
+ itemId,
+ accountId: line.accountNumber
+ ? (accountIdMap.get(line.accountNumber) ?? null)
+ : null,
+ taxPercent: line.taxPercent,
+ supplierTaxAmount: line.taxAmount ?? 0,
+ exchangeRate: invoice.exchangeRate,
+ invoiceLineType: itemId ? ("Part" as const) : ("G/L Account" as const),
+ supplierShippingCost: 0
+ };
+ });
+ await tx.insertInto("purchaseInvoiceLine").values(rows).execute();
}
// =================================================================
@@ -892,7 +905,9 @@ export class BillSyncer extends BaseEntitySyncer<
const result = await this.xeroProvider.request<{
Invoices: Xero.Invoice[];
- }>("POST", "/Invoices", { body: JSON.stringify({ Invoices: invoices }) });
+ }>("POST", "/Invoices?unitdp=4", {
+ body: JSON.stringify({ Invoices: invoices })
+ });
if (result.error) {
throwXeroApiError(
@@ -934,7 +949,9 @@ export class BillSyncer extends BaseEntitySyncer<
const response = await this.xeroProvider.request<{
Invoices: Xero.Invoice[];
- }>("POST", "/Invoices", { body: JSON.stringify({ Invoices: invoices }) });
+ }>("POST", "/Invoices?unitdp=4", {
+ body: JSON.stringify({ Invoices: invoices })
+ });
if (response.error) {
throwXeroApiError("batch upsert bills", response);
diff --git a/packages/ee/src/accounting/providers/xero/entities/invoice.ts b/packages/ee/src/accounting/providers/xero/entities/invoice.ts
index 365e4f8524..08c5bf57f3 100644
--- a/packages/ee/src/accounting/providers/xero/entities/invoice.ts
+++ b/packages/ee/src/accounting/providers/xero/entities/invoice.ts
@@ -1,8 +1,21 @@
import type { KyselyTx } from "@carbon/database/client";
-import { getLogger } from "@carbon/logger";
+import { datetime } from "@carbon/database/datetime";
+import { round } from "@carbon/utils";
+import { parseDate } from "@internationalized/date";
import { loadAccountCodesById } from "../../../core/account-mapping";
import { createMappingService } from "../../../core/external-mapping";
-import { JournalEntrySyncError } from "../../../core/posting";
+import {
+ JournalEntrySyncError,
+ toPostingDateString
+} from "../../../core/posting";
+import {
+ buildSalesDocumentComponents,
+ type SalesDocumentComponents
+} from "../../../core/sales-document-components";
+import {
+ loadSalesInvoices,
+ requirePostedShippingAccountId
+} from "../../../core/sales-invoice-source";
import {
type Accounting,
BaseEntitySyncer,
@@ -11,58 +24,11 @@ import {
import { throwXeroApiError } from "../../../core/utils";
import { parseDotnetDate, type Xero } from "../models";
import type { XeroProvider } from "../provider";
-
-const logger = getLogger("ee", "accounting", "xero");
+import { assertXeroMoneyPrecision } from "../serialize";
// Note: This syncer uses the default ID mapping from BaseEntitySyncer
// which uses the externalIntegrationMapping table with entityType "invoice"
-// Type for rows returned from sales invoice queries with line joins
-type InvoiceRow = {
- id: string;
- invoiceId: string;
- companyId: string;
- customerId: string;
- status:
- | "Draft"
- | "Pending"
- | "Submitted"
- | "Partially Paid"
- | "Paid"
- | "Overdue"
- | "Voided"
- | "Credit Note Issued"
- | "Return";
- currencyCode: string;
- exchangeRate: number;
- dateIssued: string | null;
- dateDue: string | null;
- datePaid: string | null;
- customerReference: string | null;
- subtotal: number;
- totalTax: number;
- totalDiscount: number;
- totalAmount: number;
- balance: number;
- updatedAt: string | null;
-};
-
-type InvoiceLineRow = {
- id: string;
- invoiceId: string;
- invoiceLineType: string;
- itemId: string | null;
- description: string | null;
- quantity: number;
- /** BASE currency, as stored. */
- unitPrice: number;
- /** Document-currency mirror (unitPrice * exchangeRate). */
- convertedUnitPrice: number | null;
- taxPercent: number;
- // For item code lookup
- itemReadableIdWithRevision: string | null;
-};
-
// Status mapping: Carbon -> Xero
const CARBON_TO_XERO_STATUS: Record<
Accounting.SalesInvoice["status"],
@@ -101,12 +67,67 @@ const SYNCABLE_STATUSES: Accounting.SalesInvoice["status"][] = [
"Overdue"
];
+export function buildXeroSalesInvoiceLines(args: {
+ document: SalesDocumentComponents;
+ salesAccountCode: string;
+ shippingAccountCode: string | null;
+}): Xero.InvoiceLineItem[] {
+ assertXeroMoneyPrecision(
+ args.document.subtotal,
+ args.document.totalTax,
+ args.document.totalAmount,
+ args.document.balance,
+ ...args.document.components.flatMap((component) => [
+ component.netAmount,
+ component.taxAmount
+ ])
+ );
+ return args.document.components.map((component) => {
+ const shipping =
+ component.kind === "LineShipping" || component.kind === "HeaderShipping";
+ const accountCode = shipping
+ ? args.shippingAccountCode
+ : args.salesAccountCode;
+ if (!accountCode)
+ throw new JournalEntrySyncError({
+ errorCode: "UNMAPPED_ACCOUNTS",
+ warning: true,
+ message: `Cannot sync invoice: missing ${shipping ? "shipping revenue" : "sales"} account mapping`,
+ metadata: { invoiceId: args.document.invoiceId }
+ });
+ if (Math.abs(component.taxAmount) > Math.abs(component.netAmount)) {
+ throw new Error(
+ "Xero tax override cannot exceed its monetary line unit amount"
+ );
+ }
+ // A monetary unit preserves exact net/native tax even for bulk quantities
+ // or source unit prices finer than Xero supports. Keep the source detail.
+ const description =
+ component.quantity === 1 && component.unitAmount === component.netAmount
+ ? component.description
+ : `${component.description} (${component.quantity} × ${component.unitAmount} ${args.document.currencyCode})`;
+ return {
+ Description: description,
+ Quantity: 1,
+ UnitAmount: component.netAmount,
+ LineAmount: component.netAmount,
+ TaxAmount: component.taxAmount,
+ TaxType: component.taxPercent !== 0 ? "OUTPUT" : "NONE",
+ AccountCode: accountCode,
+ ...(component.kind === "Merchandise" && component.itemCode
+ ? { ItemCode: component.itemCode.slice(0, 30) }
+ : {})
+ };
+ });
+}
+
export class SalesInvoiceSyncer extends BaseEntitySyncer<
Accounting.SalesInvoice,
Xero.Invoice,
"UpdatedDateUTC"
> {
private salesAccountCodePromise?: Promise<string>;
+ private shippingAccountCodesPromise?: ReturnType<typeof loadAccountCodesById>;
private get xeroProvider(): XeroProvider {
return this.provider as XeroProvider;
@@ -162,6 +183,29 @@ export class SalesInvoiceSyncer extends BaseEntitySyncer<
return this.salesAccountCodePromise;
}
+ private async getShippingAccountCode(
+ local: Accounting.SalesInvoice
+ ): Promise<string> {
+ const id = requirePostedShippingAccountId(local);
+ this.shippingAccountCodesPromise ??= loadAccountCodesById(this.database, {
+ companyId: this.companyId,
+ integration: this.provider.id
+ }).catch((error) => {
+ this.shippingAccountCodesPromise = undefined;
+ throw error;
+ });
+ const code = (await this.shippingAccountCodesPromise).get(id);
+ if (!code)
+ throw new JournalEntrySyncError({
+ errorCode: "UNMAPPED_ACCOUNTS",
+ warning: true,
+ message:
+ "Cannot sync invoice: original Shipping Revenue account has no Xero mapping",
+ metadata: { invoiceId: local.id, unmappedAccountIds: [id] }
+ });
+ return code;
+ }
+
// =================================================================
// 1. ID MAPPING - Uses default implementation from BaseEntitySyncer
// The entityType "invoice" maps to the salesInvoice table
@@ -189,7 +233,7 @@ export class SalesInvoiceSyncer extends BaseEntitySyncer<
await tx
.updateTable("salesInvoice")
.set({
- updatedAt: new Date().toISOString()
+ updatedAt: datetime.timestamp()
})
.where("id", "=", localId)
.execute();
@@ -219,124 +263,10 @@ export class SalesInvoiceSyncer extends BaseEntitySyncer<
return this.fetchInvoicesByIds(ids);
}
- private async fetchInvoicesByIds(
+ private fetchInvoicesByIds(
ids: string[]
): Promise<Map<string, Accounting.SalesInvoice>> {
- if (ids.length === 0) return new Map();
-
- // Fetch invoice headers
- const invoiceRows = await this.database
- .selectFrom("salesInvoice")
- // `balance` is derived (totalAmount - posted payment applications) and
- // lives only on the `salesInvoices` view now, not the base table.
- .leftJoin("salesInvoices", "salesInvoices.id", "salesInvoice.id")
- .select([
- "salesInvoice.id",
- "salesInvoice.invoiceId",
- "salesInvoice.companyId",
- "salesInvoice.customerId",
- "salesInvoice.status",
- "salesInvoice.currencyCode",
- "salesInvoice.exchangeRate",
- "salesInvoice.dateIssued",
- "salesInvoice.dateDue",
- "salesInvoice.datePaid",
- "salesInvoice.customerReference",
- "salesInvoice.subtotal",
- "salesInvoice.totalTax",
- "salesInvoice.totalDiscount",
- "salesInvoice.totalAmount",
- "salesInvoices.balance",
- "salesInvoice.updatedAt"
- ])
- .where("salesInvoice.id", "in", ids)
- .where("salesInvoice.companyId", "=", this.companyId)
- .execute();
-
- if (invoiceRows.length === 0) return new Map();
-
- // Fetch invoice lines with item codes
- const lineRows = await this.database
- .selectFrom("salesInvoiceLine")
- .leftJoin("item", "item.id", "salesInvoiceLine.itemId")
- .select([
- "salesInvoiceLine.id",
- "salesInvoiceLine.invoiceId",
- "salesInvoiceLine.invoiceLineType",
- "salesInvoiceLine.itemId",
- "salesInvoiceLine.description",
- "salesInvoiceLine.quantity",
- "salesInvoiceLine.unitPrice",
- "salesInvoiceLine.convertedUnitPrice",
- "salesInvoiceLine.taxPercent",
- "item.readableIdWithRevision as itemReadableIdWithRevision"
- ])
- .where(
- "salesInvoiceLine.invoiceId",
- "in",
- invoiceRows.map((r) => r.id)
- )
- .execute();
-
- // Group lines by invoice ID
- const linesByInvoiceId = new Map<string, InvoiceLineRow[]>();
- for (const line of lineRows as InvoiceLineRow[]) {
- const existing = linesByInvoiceId.get(line.invoiceId) ?? [];
- existing.push(line);
- linesByInvoiceId.set(line.invoiceId, existing);
- }
-
- // Transform to Accounting.SalesInvoice
- const result = new Map<string, Accounting.SalesInvoice>();
- for (const row of invoiceRows as InvoiceRow[]) {
- const lines = linesByInvoiceId.get(row.id) ?? [];
-
- result.set(row.id, {
- id: row.id,
- invoiceId: row.invoiceId,
- companyId: row.companyId,
- customerId: row.customerId,
- customerExternalId: null, // Will be resolved during mapToRemote
- status: row.status,
- currencyCode: row.currencyCode,
- exchangeRate: Number(row.exchangeRate) || 1,
- dateIssued: row.dateIssued,
- dateDue: row.dateDue,
- datePaid: row.datePaid,
- customerReference: row.customerReference,
- subtotal: Number(row.subtotal) || 0,
- totalTax: Number(row.totalTax) || 0,
- totalDiscount: Number(row.totalDiscount) || 0,
- totalAmount: Number(row.totalAmount) || 0,
- balance: Number(row.balance) || 0,
- lines: lines.map((line) => {
- const quantity = Number(line.quantity) || 0;
- const unitPrice = Number(line.unitPrice) || 0;
- const taxPercent = Number(line.taxPercent) || 0;
- const convertedUnitPrice =
- line.convertedUnitPrice === null ||
- line.convertedUnitPrice === undefined
- ? null
- : Number(line.convertedUnitPrice);
- return {
- id: line.id,
- invoiceLineType: line.invoiceLineType,
- itemId: line.itemId,
- itemCode: line.itemReadableIdWithRevision,
- description: line.description,
- quantity,
- unitPrice,
- convertedUnitPrice,
- taxPercent,
- lineAmount: quantity * unitPrice
- };
- }),
- updatedAt: row.updatedAt ?? new Date().toISOString(),
- raw: row
- });
- }
-
- return result;
+ return loadSalesInvoices(this.database, { companyId: this.companyId, ids });
}
// =================================================================
@@ -380,67 +310,42 @@ export class SalesInvoiceSyncer extends BaseEntitySyncer<
protected async mapToRemote(
local: Accounting.SalesInvoice
): Promise<Omit<Xero.Invoice, "UpdatedDateUTC">> {
+ const document = buildSalesDocumentComponents(local);
+ const hasShipping = document.components.some(
+ (line) => line.kind === "LineShipping" || line.kind === "HeaderShipping"
+ );
+ const hasSales = document.components.some(
+ (line) => line.kind !== "LineShipping" && line.kind !== "HeaderShipping"
+ );
+ const salesAccountCode = hasSales ? await this.getSalesAccountCode() : "";
+ const shippingAccountCode = hasShipping
+ ? await this.getShippingAccountCode(local)
+ : null;
+ const lineItems = buildXeroSalesInvoiceLines({
+ document,
+ salesAccountCode,
+ shippingAccountCode
+ });
+ // All currency/account/component requirements are checked before dependency writes.
const existingRemoteId = await this.getRemoteId(local.id);
-
- // Resolve customer dependency - ensure customer is synced to Xero
const customerRemoteId = await this.ensureDependencySynced(
"customer",
local.customerId
);
-
- // Item-referenced AR posts to the item's mapped REVENUE account
- // (accountDefault.salesAccount) — throws UNMAPPED_ACCOUNTS when unset
- // or unmapped (see getSalesAccountCode).
- const salesAccountCode = await this.getSalesAccountCode();
-
- logger.info("Sales AccountCode", { salesAccountCode });
-
- // Build line items, resolving item dependencies
- const lineItems: Xero.InvoiceLineItem[] = [];
- for (const line of local.lines) {
- // The payload declares CurrencyCode below, so every amount on it must be
- // in THAT currency. salesInvoiceLine.unitPrice is stored in the company
- // BASE currency; convertedUnitPrice is the document-currency mirror.
- const unitAmount = line.convertedUnitPrice ?? line.unitPrice;
- const taxAmount = (line.quantity * unitAmount * line.taxPercent) / 100;
-
- const lineItem: Xero.InvoiceLineItem = {
- Description: line.description ?? undefined,
- Quantity: line.quantity,
- UnitAmount: unitAmount,
- TaxAmount: taxAmount,
- LineAmount: line.quantity * unitAmount,
- // The item's mapped revenue account (item-referenced AR).
- AccountCode: salesAccountCode,
- // TaxType is required by Xero: OUTPUT for sales tax, NONE for zero tax
- TaxType: line.taxPercent > 0 ? "OUTPUT" : "NONE"
- };
-
- // If line has an item, ensure it's synced and get the ItemCode
- if (line.itemId) {
- // Ensure item is synced
- await this.ensureDependencySynced("item", line.itemId);
- // Use the item code from Carbon (readableIdWithRevision)
- if (line.itemCode) {
- lineItem.ItemCode = line.itemCode.slice(0, 30);
- }
- }
-
- lineItems.push(lineItem);
- }
-
- // Calculate due date: use dateDue if provided, otherwise default to Net 30
- let dueDate = local.dateDue;
- if (!dueDate && local.dateIssued) {
- const issued = new Date(local.dateIssued);
- issued.setDate(issued.getDate() + 30);
- dueDate = issued.toISOString().split("T")[0]; // YYYY-MM-DD format
- } else if (!dueDate) {
- // If no dateIssued either, default to 30 days from now
- const now = new Date();
- now.setDate(now.getDate() + 30);
- dueDate = now.toISOString().split("T")[0];
- }
+ const itemIds = [
+ ...new Set(
+ document.components
+ .filter((line) => line.kind === "Merchandise" && line.itemId)
+ .map((line) => line.itemId!)
+ )
+ ];
+ for (const itemId of itemIds)
+ await this.ensureDependencySynced("item", itemId);
+ const dueDate =
+ local.dateDue ??
+ parseDate(toPostingDateString(local.dateIssued ?? datetime.timestamp()))
+ .add({ days: 30 })
+ .toString();
return {
InvoiceID: existingRemoteId!,
@@ -455,19 +360,21 @@ export class SalesInvoiceSyncer extends BaseEntitySyncer<
Status: CARBON_TO_XERO_STATUS[local.status],
LineAmountTypes: "Exclusive", // Tax is calculated separately
LineItems: lineItems,
- SubTotal: local.subtotal,
- TotalTax: local.totalTax,
- Total: local.totalAmount,
- AmountDue: local.balance,
- AmountPaid: local.totalAmount - local.balance,
+ SubTotal: document.subtotal,
+ TotalTax: document.totalTax,
+ Total: document.totalAmount,
+ AmountDue: document.balance,
+ AmountPaid: round(
+ document.totalAmount - document.balance,
+ document.decimalPlaces
+ ),
CurrencyCode: local.currencyCode,
- // Xero's CurrencyRate is [invoice currency] PER [base currency] -- the
- // same direction Carbon stores exchangeRate in, so it passes through
- // unchanged. Inverting it earns Xero's "inverse rate" warning and books
- // the base amounts wrong. Omit it on base-currency invoices: Xero calls
- // an explicit rate of 1 redundant and warns on a 1 that reaches an FX
- // document.
- CurrencyRate: local.exchangeRate !== 1 ? local.exchangeRate : undefined
+ // Xero stores foreign per base too. A foreign negotiated 1:1 must be
+ // explicit; omission would let Xero choose its own market rate.
+ CurrencyRate:
+ local.currencyCode !== local.baseCurrencyCode
+ ? local.exchangeRate
+ : undefined
};
}
@@ -488,6 +395,9 @@ export class SalesInvoiceSyncer extends BaseEntitySyncer<
description: line.Description ?? null,
quantity: line.Quantity ?? 0,
unitPrice: line.UnitAmount ?? 0,
+ shippingCost: 0,
+ addOnCost: 0,
+ nonTaxableAddOnCost: 0,
taxPercent: line.TaxAmount
? (line.TaxAmount / (line.LineAmount ?? 1)) * 100 || 0
: 0,
@@ -540,7 +450,7 @@ export class SalesInvoiceSyncer extends BaseEntitySyncer<
totalAmount: data.totalAmount,
currencyCode: data.currencyCode,
exchangeRate: data.exchangeRate,
- updatedAt: new Date().toISOString()
+ updatedAt: datetime.timestamp()
})
.where("id", "=", existingLocalId)
.execute();
@@ -566,7 +476,9 @@ export class SalesInvoiceSyncer extends BaseEntitySyncer<
const result = await this.xeroProvider.request<{
Invoices: Xero.Invoice[];
- }>("POST", "/Invoices", { body: JSON.stringify({ Invoices: invoices }) });
+ }>("POST", "/Invoices?unitdp=4", {
+ body: JSON.stringify({ Invoices: invoices })
+ });
if (result.error) {
throwXeroApiError(
@@ -608,7 +520,9 @@ export class SalesInvoiceSyncer extends BaseEntitySyncer<
const response = await this.xeroProvider.request<{
Invoices: Xero.Invoice[];
- }>("POST", "/Invoices", { body: JSON.stringify({ Invoices: invoices }) });
+ }>("POST", "/Invoices?unitdp=4", {
+ body: JSON.stringify({ Invoices: invoices })
+ });
if (response.error) {
throwXeroApiError("batch upsert invoices", response);
diff --git a/packages/ee/src/accounting/providers/xero/entities/payment.ts b/packages/ee/src/accounting/providers/xero/entities/payment.ts
index cba7b251c3..5ff6c742d1 100644
--- a/packages/ee/src/accounting/providers/xero/entities/payment.ts
+++ b/packages/ee/src/accounting/providers/xero/entities/payment.ts
@@ -221,7 +221,7 @@ export class XeroPaymentSyncer extends PaymentSyncerBase<Xero.Payment> {
paymentRemoteId,
amount: remote.Amount ?? 0,
currencyCode: remote.Invoice?.CurrencyCode ?? null,
- exchangeRate: remote.CurrencyRate ?? 1,
+ exchangeRate: remote.CurrencyRate ?? null,
paidDate: getXeroPaymentDate(remote.Date),
// The Xero PaymentID is the human/provider reference.
reference: paymentRemoteId,
diff --git a/packages/ee/src/accounting/providers/xero/serialize.ts b/packages/ee/src/accounting/providers/xero/serialize.ts
index af7767b595..2ccb62aaed 100644
--- a/packages/ee/src/accounting/providers/xero/serialize.ts
+++ b/packages/ee/src/accounting/providers/xero/serialize.ts
@@ -3,9 +3,8 @@ import { round } from "@carbon/utils";
// Xero's API rounds/validates decimal places per field class. These constants
// are the boundary's external contract (not internal scale choices): monetary
// line/total/payment fields carry two decimals, per-unit amounts allow four,
-// and exchange rates allow six. Rounding at serialization keeps payloads valid
-// no matter what precision Carbon carries internally — and stops raw float
-// artifacts (0.45000000000000007) from reaching the API.
+// and exchange rates allow six. Document replay validates exact representability
+// before writing; it must never round away Carbon document principal.
export const XERO_MONEY_DECIMALS = 2;
export const XERO_UNIT_AMOUNT_DECIMALS = 4;
export const XERO_QUANTITY_DECIMALS = 4;
@@ -24,3 +23,16 @@ export const xeroQuantity = (value: number) =>
export const xeroCurrencyRate = (value: number) =>
round(value, XERO_CURRENCY_RATE_DECIMALS);
+
+/** Refuse unsupported principal instead of letting Xero silently round it. */
+export function assertXeroMoneyPrecision(...values: number[]): void {
+ if (
+ values.some(
+ (value) => !Number.isFinite(value) || xeroMoney(value) !== value
+ )
+ ) {
+ throw new Error(
+ "Xero document monetary precision is limited to two decimal places; this document cannot be represented without changing its amounts"
+ );
+ }
+}
diff --git a/packages/glossary/src/terms.ts b/packages/glossary/src/terms.ts
index e4db05673b..ebc63027ff 100644
--- a/packages/glossary/src/terms.ts
+++ b/packages/glossary/src/terms.ts
@@ -558,6 +558,10 @@ export const terms = {
term: msg`Sales (default)`,
definition: msg`Default revenue GL account credited when a sales invoice posts.`
},
+ "account-default-sales-shipping-revenue": {
+ term: msg`Shipping Revenue (default)`,
+ definition: msg`Revenue GL account credited for shipping charged to customers, posted on its own line; it must be a different account from the Sales default.`
+ },
"account-default-sales-discounts": {
term: msg`Sales Discounts (default)`,
definition: msg`Contra-revenue GL account for discounts given on customer invoices.`
diff --git a/packages/jobs/manifests/schema.json b/packages/jobs/manifests/schema.json
index 92ad15b935..c926c647ad 100644
--- a/packages/jobs/manifests/schema.json
+++ b/packages/jobs/manifests/schema.json
@@ -1,11 +1,11 @@
{
"kind": "carbon-company-backup",
"version": 1,
- "schemaVersion": "20260903021021",
+ "schemaVersion": "20260909174352",
"sourceCompanyId": "schema-baseline",
"sourceCompanyGroupId": null,
"sourceCompanyName": null,
- "exportedAt": "2026-09-03T02:33:52.211Z",
+ "exportedAt": "2026-09-09T21:54:43.367Z",
"exportedBy": "schema-baseline",
"label": "schema baseline",
"includeStorage": "none",
@@ -57,6 +57,7 @@
"accumulatedDepreciationOnDisposalAccount",
"realizedExchangeGainAccount",
"purchaseVarianceAccount",
+ "salesShippingRevenueAccount",
"overheadVarianceAccount",
"realizedExchangeLossAccount",
"prepaymentAccount",
@@ -119,99 +120,99 @@
"name": "accountingPeriodBalance",
"rows": 0,
"columns": [
- "endingBalance",
- "createdBy",
- "accountingPeriodId",
- "accountId",
- "endingBalanceDate",
- "updatedBy",
"id",
+ "updatedBy",
+ "endingBalanceDate",
+ "companyId",
"createdAt",
"updatedAt",
- "companyId"
+ "endingBalance",
+ "accountId",
+ "accountingPeriodId",
+ "createdBy"
]
},
{
"name": "accountingSyncOperation",
"rows": 0,
"columns": [
- "trigger",
- "integration",
- "errorMessage",
- "entityType",
- "updatedBy",
- "createdAt",
- "externalId",
- "createdBy",
- "entityId",
- "completedAt",
- "updatedAt",
- "status",
- "attemptCount",
- "metadata",
- "errorCode",
- "companyId",
"direction",
- "idempotencyKey",
+ "lastAttemptAt",
"id",
- "lastAttemptAt"
+ "idempotencyKey",
+ "attemptCount",
+ "status",
+ "companyId",
+ "errorCode",
+ "metadata",
+ "createdBy",
+ "externalId",
+ "updatedAt",
+ "completedAt",
+ "entityId",
+ "trigger",
+ "createdAt",
+ "updatedBy",
+ "entityType",
+ "errorMessage",
+ "integration"
]
},
{
"name": "accountingSyncTieOut",
"rows": 0,
"columns": [
- "computedAt",
- "createdAt",
"accountId",
"providerAmount",
- "syncedAmount",
+ "computedAt",
+ "createdAt",
"updatedAt",
"updatedBy",
- "accountingPeriodId",
"externalDelta",
"integration",
- "carbonPostedAmount",
+ "accountingPeriodId",
+ "syncedAmount",
"blockedAmount",
- "id",
"excludedAmount",
- "pendingAmount",
- "docBackedAmount",
+ "id",
+ "carbonPostedAmount",
"internalDelta",
"companyId",
- "createdBy"
+ "createdBy",
+ "pendingAmount",
+ "docBackedAmount"
]
},
{
"name": "address",
"rows": 0,
"columns": [
- "stateProvince",
- "city",
"addressLine2",
+ "city",
"countryCode",
- "id",
- "fax",
- "postalCode",
+ "stateProvince",
"addressLine1",
"companyId",
- "phone"
+ "phone",
+ "fax",
+ "id",
+ "postalCode"
]
},
{
"name": "agentThread",
"rows": 0,
"columns": [
+ "modelId",
"title",
"userId",
"createdBy",
- "modelId",
- "companyId",
- "updatedAt",
- "createdAt",
"id",
"updatedBy",
- "lastContext"
+ "lastContext",
+ "companyId",
+ "updatedAt",
+ "createdAt"
]
},
{
@@ -230,71 +231,71 @@
"createdAt",
"feedbackNote",
"role",
- "companyId",
- "updatedAt"
+ "updatedAt",
+ "companyId"
]
},
{
"name": "agentMessagePart",
"rows": 0,
"columns": [
- "toolOutput",
- "id",
- "toolCallId",
- "textContent",
- "messageId",
- "toolDurationMs",
- "createdAt",
- "toolInput",
- "toolClassification",
- "toolState",
- "type",
"updatedBy",
"createdBy",
+ "toolState",
+ "type",
+ "toolName",
"updatedAt",
"orderIndex",
- "companyId",
"errorMessage",
- "toolName"
+ "companyId",
+ "textContent",
+ "toolOutput",
+ "id",
+ "toolCallId",
+ "toolInput",
+ "toolClassification",
+ "messageId",
+ "toolDurationMs",
+ "createdAt"
]
},
{
"name": "approvalRequest",
"rows": 0,
"columns": [
+ "requestedAt",
+ "documentId",
+ "createdAt",
+ "status",
"updatedBy",
"companyId",
"amount",
- "requestedAt",
- "status",
- "createdAt",
- "documentId",
- "requestedBy",
- "decisionNotes",
- "id",
- "decisionBy",
"decisionAt",
"documentType",
"createdBy",
- "updatedAt"
+ "updatedAt",
+ "requestedBy",
+ "decisionNotes",
+ "decisionBy",
+ "id"
]
},
{
"name": "approvalRule",
"rows": 0,
"columns": [
- "enabled",
- "approverGroupIds",
- "escalationDays",
- "defaultApproverId",
- "updatedAt",
- "documentType",
- "createdAt",
- "companyId",
+ "lowerBoundAmount",
"updatedBy",
- "createdBy",
"id",
- "lowerBoundAmount"
+ "createdBy",
+ "createdAt",
+ "companyId",
+ "documentType",
+ "defaultApproverId",
+ "updatedAt",
+ "escalationDays",
+ "approverGroupIds",
+ "enabled"
]
},
{
@@ -307,74 +308,74 @@
"companyId",
"endDate",
"sizeBytes",
- "startDate",
- "archivePath"
+ "archivePath",
+ "startDate"
]
},
{
"name": "changeOrderRequiredAction",
"rows": 0,
"columns": [
- "updatedAt",
- "companyId",
- "createdAt",
- "id",
- "customFields",
+ "createdBy",
"updatedBy",
- "active",
"name",
- "createdBy"
+ "active",
+ "createdAt",
+ "customFields",
+ "id",
+ "updatedAt",
+ "companyId"
]
},
{
"name": "changeOrderType",
"rows": 0,
"columns": [
- "createdBy",
- "createdAt",
- "companyId",
"updatedBy",
- "id",
+ "companyId",
+ "createdAt",
+ "createdBy",
+ "name",
"updatedAt",
- "name"
+ "id"
]
},
{
"name": "companyAccountsPayableBillingAddress",
"rows": 0,
"columns": [
+ "postalCode",
+ "addressLine2",
+ "addressLine1",
"updatedAt",
"city",
- "addressLine1",
- "addressLine2",
- "postalCode",
- "email",
- "phone",
- "id",
- "state",
+ "fax",
+ "countryCode",
"name",
"updatedBy",
- "fax",
- "countryCode"
+ "state",
+ "email",
+ "id",
+ "phone"
]
},
{
"name": "companyAccountsReceivableBillingAddress",
"rows": 0,
"columns": [
- "updatedAt",
- "city",
- "postalCode",
- "addressLine2",
- "addressLine1",
"state",
- "email",
- "id",
"phone",
- "fax",
+ "id",
+ "email",
"countryCode",
+ "fax",
+ "updatedBy",
"name",
- "updatedBy"
+ "city",
+ "updatedAt",
+ "postalCode",
+ "addressLine1",
+ "addressLine2"
]
},
{
@@ -435,14 +436,14 @@
"name": "companyUsage",
"rows": 0,
"columns": [
- "users",
+ "createdAt",
+ "tasks",
+ "aiTokens",
+ "nextResetDatetime",
"updatedAt",
- "id",
+ "users",
"companyId",
- "aiTokens",
- "tasks",
- "createdAt",
- "nextResetDatetime"
+ "id"
]
},
{
@@ -465,34 +466,34 @@
"name": "contact",
"rows": 0,
"columns": [
- "email",
"isCustomer",
- "notes",
- "companyId",
+ "email",
"lastName",
+ "companyId",
+ "notes",
"mobilePhone",
"workPhone",
"id",
"title",
"firstName",
- "fax",
- "homePhone"
+ "homePhone",
+ "fax"
]
},
{
"name": "costCenter",
"rows": 0,
"columns": [
- "createdBy",
- "updatedBy",
- "parentCostCenterId",
- "companyId",
+ "updatedAt",
+ "ownerId",
+ "name",
"createdAt",
"customFields",
"id",
- "ownerId",
- "updatedAt",
- "name"
+ "updatedBy",
+ "parentCostCenterId",
+ "companyId",
+ "createdBy"
]
},
{
@@ -539,11 +540,11 @@
"columns": [
"createdBy",
"updatedAt",
- "companyId",
"createdAt",
+ "companyId",
"updatedBy",
- "tags",
"id",
+ "tags",
"customFields",
"name"
]
@@ -552,16 +553,16 @@
"name": "customerType",
"rows": 0,
"columns": [
- "createdBy",
+ "companyId",
+ "protected",
+ "updatedBy",
+ "createdAt",
+ "name",
+ "tags",
+ "updatedAt",
"id",
"customFields",
- "updatedAt",
- "tags",
- "name",
- "createdAt",
- "updatedBy",
- "companyId",
- "protected"
+ "createdBy"
]
},
{
@@ -584,15 +585,15 @@
"name": "depreciationRun",
"rows": 0,
"columns": [
- "createdBy",
"id",
+ "createdBy",
"postedBy",
"depreciationRunId",
"updatedBy",
"createdAt",
"postedAt",
- "periodEnd",
"status",
+ "periodEnd",
"companyId"
]
},
@@ -600,30 +601,30 @@
"name": "dimension",
"rows": 0,
"columns": [
- "active",
- "companyGroupId",
- "entityType",
- "createdBy",
+ "name",
+ "createdAt",
+ "updatedAt",
"id",
"updatedBy",
"required",
- "name",
- "createdAt",
- "updatedAt"
+ "companyGroupId",
+ "entityType",
+ "createdBy",
+ "active"
]
},
{
"name": "dimensionValue",
"rows": 0,
"columns": [
- "id",
"createdAt",
- "dimensionId",
+ "id",
"updatedAt",
+ "dimensionId",
"createdBy",
+ "updatedBy",
"name",
- "companyGroupId",
- "updatedBy"
+ "companyGroupId"
]
},
{
@@ -652,20 +653,20 @@
"name": "documentExtraction",
"rows": 0,
"columns": [
- "createdAt",
- "storagePath",
- "status",
- "sourceDocumentId",
- "updatedAt",
"sourceDocument",
- "documentType",
- "createdBy",
- "id",
- "filteredData",
+ "updatedAt",
+ "sourceDocumentId",
+ "status",
+ "storagePath",
+ "createdAt",
+ "updatedBy",
+ "companyId",
"error",
"extractedData",
- "companyId",
- "updatedBy"
+ "createdBy",
+ "filteredData",
+ "id",
+ "documentType"
]
},
{
@@ -682,35 +683,35 @@
"name": "documentSection",
"rows": 0,
"columns": [
- "content",
- "placement",
- "name",
"createdBy",
- "id",
- "updatedBy",
- "config",
- "companyId",
+ "name",
+ "placement",
+ "content",
"updatedAt",
- "createdAt"
+ "createdAt",
+ "companyId",
+ "config",
+ "updatedBy",
+ "id"
]
},
{
"name": "documentTemplate",
"rows": 0,
"columns": [
- "createdBy",
- "headerSectionId",
- "companyId",
- "updatedAt",
- "theme",
- "createdAt",
- "id",
- "footerSectionId",
- "settings",
+ "blocks",
+ "updatedBy",
"formatVersion",
"documentType",
- "updatedBy",
- "blocks"
+ "settings",
+ "id",
+ "footerSectionId",
+ "createdAt",
+ "theme",
+ "updatedAt",
+ "companyId",
+ "headerSectionId",
+ "createdBy"
]
},
{
@@ -729,19 +730,19 @@
"name": "employeeType",
"rows": 0,
"columns": [
- "systemType",
- "protected",
- "companyId",
"createdAt",
- "name",
+ "companyId",
+ "protected",
+ "systemType",
+ "id",
"updatedAt",
- "id"
+ "name"
]
},
{
"name": "employee",
"rows": 0,
- "columns": ["companyId", "id", "active", "employeeTypeId", "pin"]
+ "columns": ["id", "companyId", "pin", "active", "employeeTypeId"]
},
{
"name": "employeeTypePermission",
@@ -761,16 +762,16 @@
"name": "eventSystemSubscription",
"rows": 0,
"columns": [
- "table",
- "companyId",
- "handlerType",
- "operations",
+ "id",
+ "createdAt",
+ "filter",
"name",
"config",
"active",
- "id",
- "createdAt",
- "filter"
+ "operations",
+ "companyId",
+ "table",
+ "handlerType"
]
},
{
@@ -778,8 +779,8 @@
"rows": 0,
"columns": [
"createdBy",
- "currencyCode",
"rate",
+ "currencyCode",
"updatedBy",
"id",
"createdAt",
@@ -791,20 +792,20 @@
"name": "externalIntegrationMapping",
"rows": 0,
"columns": [
- "updatedAt",
- "id",
- "remoteUpdatedAt",
- "allowDuplicateExternalId",
- "companyId",
- "entityType",
- "createdAt",
- "lastSyncedAt",
"externalId",
"createdBy",
- "integration",
- "entityId",
+ "metadata",
"updatedBy",
- "metadata"
+ "entityId",
+ "integration",
+ "allowDuplicateExternalId",
+ "remoteUpdatedAt",
+ "id",
+ "updatedAt",
+ "lastSyncedAt",
+ "createdAt",
+ "companyId",
+ "entityType"
]
},
{
@@ -816,17 +817,13 @@
"name": "fixedAssetClass",
"rows": 0,
"columns": [
- "name",
- "taxDepreciationMethod",
- "macrsPropertyClass",
- "writeOffAccountId",
- "customFields",
- "accumulatedDepreciationAccountId",
- "writeDownAccountId",
- "depreciationExpenseAccountId",
- "id",
- "gainOnDisposalAccountId",
- "residualValuePercent",
+ "lossOnDisposalAccountId",
+ "createdAt",
+ "usefulLifeMonths",
+ "updatedAt",
+ "macrsConvention",
+ "taxResidualValuePercent",
+ "createdBy",
"bonusDepreciationPercent",
"companyId",
"description",
@@ -834,44 +831,48 @@
"depreciationMethod",
"assetAccountId",
"updatedBy",
- "lossOnDisposalAccountId",
- "createdAt",
- "usefulLifeMonths",
- "updatedAt",
- "macrsConvention",
- "createdBy",
- "taxResidualValuePercent"
+ "writeDownAccountId",
+ "depreciationExpenseAccountId",
+ "id",
+ "gainOnDisposalAccountId",
+ "residualValuePercent",
+ "name",
+ "taxDepreciationMethod",
+ "macrsPropertyClass",
+ "writeOffAccountId",
+ "customFields",
+ "accumulatedDepreciationAccountId"
]
},
{
"name": "gaugeType",
"rows": 0,
"columns": [
+ "updatedAt",
"customFields",
"companyId",
- "updatedAt",
"createdAt",
- "name",
"updatedBy",
- "id",
- "createdBy"
+ "name",
+ "createdBy",
+ "id"
]
},
{
"name": "group",
"rows": 0,
"columns": [
+ "isCustomerOrgGroup",
"updatedAt",
- "isSupplierOrgGroup",
"id",
- "isCustomerOrgGroup",
- "name",
+ "isSupplierOrgGroup",
"createdAt",
"isSupplierTypeGroup",
+ "name",
"isEmployeeTypeGroup",
- "companyId",
+ "isCustomerTypeGroup",
"isIdentityGroup",
- "isCustomerTypeGroup"
+ "companyId"
]
},
{
@@ -894,44 +895,44 @@
"name": "implementationCheckState",
"rows": 0,
"columns": [
- "createdBy",
- "id",
- "updatedAt",
- "updatedBy",
- "companyId",
- "value",
"createdAt",
+ "itemKey",
"kind",
- "itemKey"
+ "value",
+ "updatedBy",
+ "companyId",
+ "createdBy",
+ "updatedAt",
+ "id"
]
},
{
"name": "implementationFieldValue",
"rows": 0,
"columns": [
- "createdBy",
- "value",
- "fieldKey",
"updatedBy",
- "id",
- "createdAt",
+ "fieldKey",
+ "value",
+ "createdBy",
+ "updatedAt",
"companyId",
- "updatedAt"
+ "createdAt",
+ "id"
]
},
{
"name": "implementationRow",
"rows": 0,
"columns": [
+ "updatedBy",
+ "companyId",
"createdBy",
"updatedAt",
"id",
- "updatedBy",
- "companyId",
- "sortOrder",
"createdAt",
"collection",
- "payload"
+ "payload",
+ "sortOrder"
]
},
{
@@ -958,22 +959,22 @@
"rows": 0,
"columns": [
"fullLegalName",
- "type",
- "createdBy",
"userId",
- "updatedAt",
+ "createdBy",
+ "type",
"createdAt",
- "userAgent",
+ "updatedAt",
"docVersion",
- "title",
+ "userAgent",
"certifiedAt",
- "updatedBy",
- "companyId",
+ "title",
"expiresAt",
+ "companyId",
+ "updatedBy",
"docHash",
- "complianceContact",
+ "ipAddress",
"id",
- "ipAddress"
+ "complianceContact"
]
},
{
@@ -1053,40 +1054,40 @@
"name": "intercompanyTransaction",
"rows": 0,
"columns": [
- "updatedAt",
"status",
"sourceJournalLineId",
- "amount",
- "sourceCompanyId",
+ "updatedAt",
"createdAt",
+ "sourceCompanyId",
"targetCompanyId",
- "targetJournalLineId",
+ "amount",
+ "documentId",
"description",
"id",
- "documentId",
- "currencyCode",
- "documentType",
+ "targetJournalLineId",
"companyGroupId",
- "eliminationJournalId"
+ "eliminationJournalId",
+ "documentType",
+ "currencyCode"
]
},
{
"name": "intercompanyEliminationLine",
"rows": 0,
"columns": [
- "quantity",
- "id",
- "createdAt",
- "accountId",
- "updatedAt",
+ "role",
+ "intercompanyTransactionId",
+ "amount",
+ "updatedBy",
+ "journalLineId",
"companyId",
- "itemId",
+ "updatedAt",
"createdBy",
- "journalLineId",
- "updatedBy",
- "intercompanyTransactionId",
- "role",
- "amount"
+ "itemId",
+ "createdAt",
+ "id",
+ "quantity",
+ "accountId"
]
},
{
@@ -1131,70 +1132,70 @@
"name": "fixedAsset",
"rows": 0,
"columns": [
- "depreciationMethod",
+ "bonusDepreciationPercent",
+ "taxResidualValuePercent",
+ "fixedAssetId",
"updatedAt",
+ "depreciationMethod",
"createdBy",
+ "disposalDate",
"customFields",
"residualValuePercent",
- "disposalDate",
- "bonusDepreciationPercent",
- "fixedAssetId",
- "taxResidualValuePercent",
- "serialNumber",
- "disposalMethod",
"id",
"usefulLifeMonths",
"companyId",
"taxDepreciationMethod",
- "createdAt",
- "locationId",
- "status",
- "notes",
+ "serialNumber",
+ "disposalMethod",
"name",
- "fixedAssetClassId",
"macrsPropertyClass",
- "acquisitionDate",
+ "fixedAssetClassId",
"depreciationStartDate",
- "saleProceeds",
- "acquisitionCost",
- "macrsConvention",
- "accumulatedTaxDepreciation",
+ "acquisitionDate",
+ "locationId",
+ "status",
+ "createdAt",
+ "notes",
"assetLifetimeUsage",
+ "description",
"accumulatedDepreciation",
"updatedBy",
"taxUsefulLifeMonths",
- "description"
+ "macrsConvention",
+ "accumulatedTaxDepreciation",
+ "saleProceeds",
+ "acquisitionCost"
]
},
{
"name": "depreciationRunLine",
"rows": 0,
"columns": [
+ "depreciationRunId",
+ "journalId",
+ "id",
"companyId",
"fixedAssetId",
"amount",
- "taxAmount",
- "depreciationRunId",
- "journalId",
- "id"
+ "taxAmount"
]
},
{
"name": "fixedAssetDisposal",
"rows": 0,
"columns": [
- "netBookValueAtDisposal",
+ "fixedAssetId",
+ "journalId",
+ "createdAt",
"companyId",
"id",
"createdBy",
- "journalId",
- "createdAt",
- "fixedAssetId",
- "saleProceeds",
- "updatedBy",
- "gainLoss",
+ "netBookValueAtDisposal",
"disposalMethod",
- "disposalDate"
+ "disposalDate",
+ "gainLoss",
+ "saleProceeds",
+ "updatedBy"
]
},
{
@@ -1216,35 +1217,35 @@
"name": "inventoryCount",
"rows": 0,
"columns": [
- "isBlind",
- "postedAt",
- "id",
- "notes",
- "postedBy",
- "snapshotAt",
+ "customFields",
"createdAt",
"companyId",
- "customFields",
- "updatedAt",
- "status",
- "createdBy",
- "scope",
+ "snapshotAt",
+ "postedBy",
+ "id",
+ "notes",
+ "postedAt",
+ "isBlind",
"locationId",
+ "updatedBy",
"inventoryCountId",
- "updatedBy"
+ "scope",
+ "status",
+ "createdBy",
+ "updatedAt"
]
},
{
"name": "maintenanceFailureMode",
"rows": 0,
"columns": [
- "type",
"name",
- "updatedBy",
+ "type",
"id",
- "updatedAt",
+ "updatedBy",
"companyId",
"createdBy",
+ "updatedAt",
"createdAt"
]
},
@@ -1267,7 +1268,7 @@
{
"name": "materialDimension",
"rows": 0,
- "columns": ["isMetric", "name", "companyId", "materialFormId", "id"]
+ "columns": ["companyId", "isMetric", "name", "id", "materialFormId"]
},
{
"name": "materialSubstance",
@@ -1288,23 +1289,23 @@
{
"name": "materialFinish",
"rows": 0,
- "columns": ["companyId", "materialSubstanceId", "id", "name"]
+ "columns": ["companyId", "materialSubstanceId", "name", "id"]
},
{
"name": "materialGrade",
"rows": 0,
- "columns": ["id", "materialSubstanceId", "companyId", "name"]
+ "columns": ["name", "companyId", "id", "materialSubstanceId"]
},
{
"name": "materialType",
"rows": 0,
"columns": [
- "id",
"companyId",
+ "id",
"name",
"materialFormId",
- "code",
- "materialSubstanceId"
+ "materialSubstanceId",
+ "code"
]
},
{
@@ -1332,7 +1333,7 @@
{
"name": "membership",
"rows": 0,
- "columns": ["memberUserId", "memberGroupId", "groupId", "id"]
+ "columns": ["groupId", "id", "memberUserId", "memberGroupId"]
},
{
"name": "modelUpload",
@@ -1369,16 +1370,16 @@
"rows": 0,
"columns": [
"planPath",
- "error",
- "status",
"kind",
- "stats",
- "id",
+ "status",
+ "error",
"createdBy",
+ "id",
"updatedAt",
+ "stats",
+ "modelUploadId",
"companyId",
- "createdAt",
- "modelUploadId"
+ "createdAt"
]
},
{
@@ -1399,15 +1400,15 @@
"name": "nonConformanceRequiredAction",
"rows": 0,
"columns": [
- "createdAt",
- "updatedAt",
- "name",
- "active",
"createdBy",
"systemType",
"id",
"updatedBy",
- "companyId"
+ "companyId",
+ "createdAt",
+ "updatedAt",
+ "name",
+ "active"
]
},
{
@@ -1481,90 +1482,90 @@
"rows": 0,
"columns": [
"type",
+ "openDate",
"changeOrderTypeId",
"id",
- "openDate",
- "priority",
- "nonConformanceId",
"updatedBy",
- "sourceId",
- "changeOrderId",
+ "nonConformanceId",
+ "priority",
"requiredActionIds",
- "assignee",
- "sourceType",
+ "changeOrderId",
+ "sourceId",
"createdAt",
- "createdBy",
+ "sourceType",
+ "assignee",
+ "description",
"dueDate",
"companyId",
- "description",
+ "createdBy",
"status",
"updatedAt",
+ "tags",
+ "customFields",
"approvalRequirements",
"name",
- "reasonForChange",
- "customFields",
- "tags"
+ "reasonForChange"
]
},
{
"name": "changeOrderActionTask",
"rows": 0,
"columns": [
- "createdAt",
- "dueDate",
- "updatedBy",
+ "status",
"updatedAt",
"name",
- "status",
"assignee",
- "companyId",
- "sortOrder",
- "id",
- "completedDate",
+ "createdAt",
+ "dueDate",
+ "updatedBy",
+ "actionTypeId",
"changeOrderId",
"createdBy",
- "actionTypeId",
+ "notes",
"tags",
- "notes"
+ "id",
+ "sortOrder",
+ "companyId",
+ "completedDate"
]
},
{
"name": "nonConformanceApprovalTask",
"rows": 0,
"columns": [
- "status",
- "updatedAt",
- "approvalType",
- "assignee",
- "createdAt",
- "dueDate",
- "updatedBy",
- "nonConformanceId",
"createdBy",
- "tags",
+ "nonConformanceId",
"notes",
- "companyId",
+ "tags",
"id",
"sortOrder",
- "completedDate"
+ "companyId",
+ "completedDate",
+ "status",
+ "approvalType",
+ "updatedAt",
+ "assignee",
+ "dueDate",
+ "createdAt",
+ "updatedBy"
]
},
{
"name": "nonConformanceReviewer",
"rows": 0,
"columns": [
- "title",
- "createdAt",
- "updatedAt",
+ "notes",
+ "completedDate",
+ "status",
+ "nonConformanceId",
+ "companyId",
"createdBy",
"id",
"updatedBy",
"assignee",
- "status",
- "nonConformanceId",
- "companyId",
- "notes",
- "completedDate"
+ "title",
+ "createdAt",
+ "updatedAt"
]
},
{
@@ -1587,49 +1588,49 @@
"name": "notification",
"rows": 0,
"columns": [
- "description",
- "digestedInto",
- "companyId",
- "topic",
- "createdAt",
- "readAt",
- "event",
+ "title",
+ "id",
+ "documentType",
+ "payload",
"from",
"documentId",
"userId",
"seenAt",
- "title",
- "documentType",
- "id",
- "payload"
+ "createdAt",
+ "readAt",
+ "event",
+ "description",
+ "topic",
+ "companyId",
+ "digestedInto"
]
},
{
"name": "notificationDelivery",
"rows": 0,
"columns": [
- "lastDeliveryId",
- "userId",
- "event",
- "documentId",
- "lastDeliveredAt",
"companyId",
- "successCount",
+ "lastDeliveredAt",
+ "id",
"createdAt",
- "id"
+ "successCount",
+ "event",
+ "userId",
+ "lastDeliveryId",
+ "documentId"
]
},
{
"name": "notificationPreference",
"rows": 0,
"columns": [
- "enabled",
- "id",
"userId",
- "topic",
- "updatedAt",
+ "id",
+ "enabled",
"companyId",
- "channel"
+ "channel",
+ "updatedAt",
+ "topic"
]
},
{
@@ -1691,49 +1692,49 @@
"name": "periodCloseTaskDefinition",
"rows": 0,
"columns": [
+ "updatedAt",
+ "createdBy",
+ "autoCheckKey",
+ "required",
"taskType",
- "updatedBy",
"name",
- "required",
- "autoCheckKey",
- "createdBy",
- "updatedAt",
- "customFields",
- "createdAt",
- "companyId",
- "severity",
- "isSystem",
+ "updatedBy",
+ "sortOrder",
"id",
"active",
"defaultAssigneeId",
- "sortOrder"
+ "severity",
+ "isSystem",
+ "customFields",
+ "companyId",
+ "createdAt"
]
},
{
"name": "periodCloseTask",
"rows": 0,
"columns": [
- "status",
+ "taskType",
"required",
"id",
- "taskType",
- "completedBy",
- "companyId",
- "evidenceJournalId",
- "severity",
+ "status",
"sortOrder",
- "name",
- "assigneeId",
- "updatedBy",
- "updatedAt",
- "skippedReason",
+ "severity",
+ "evidenceJournalId",
+ "companyId",
+ "completedBy",
"notes",
- "createdAt",
- "createdBy",
+ "skippedReason",
+ "updatedAt",
+ "assigneeId",
+ "updatedBy",
+ "name",
+ "autoCheckKey",
"completedAt",
"accountingPeriodId",
"definitionId",
- "autoCheckKey"
+ "createdBy",
+ "createdAt"
]
},
{
@@ -1741,85 +1742,85 @@
"rows": 0,
"columns": [
"notes",
- "locationId",
"status",
- "assignee",
+ "locationId",
"updatedAt",
- "companyId",
+ "assignee",
"createdAt",
- "customFields",
+ "companyId",
"pickingListId",
+ "customFields",
"dueDate",
- "id",
+ "updatedBy",
"createdBy",
- "updatedBy"
+ "id"
]
},
{
"name": "pricingRule",
"rows": 0,
"columns": [
- "itemPostingGroupId",
- "createdAt",
- "amount",
- "updatedAt",
- "active",
- "updatedBy",
- "companyId",
- "createdBy",
- "ruleType",
- "validTo",
- "amountType",
- "minQuantity",
- "itemIds",
+ "validFrom",
+ "name",
+ "maxQuantity",
+ "customerTypeIds",
"customerIds",
"id",
+ "itemIds",
"priority",
- "name",
- "validFrom",
- "customerTypeIds",
- "maxQuantity"
+ "validTo",
+ "ruleType",
+ "amountType",
+ "createdBy",
+ "companyId",
+ "minQuantity",
+ "updatedAt",
+ "amount",
+ "itemPostingGroupId",
+ "createdAt",
+ "updatedBy",
+ "active"
]
},
{
"name": "printJob",
"rows": 0,
"columns": [
- "sourceDocumentId",
- "description",
- "updatedAt",
- "companyId",
- "attempts",
- "printerUrl",
- "id",
- "sourceDocumentReadableId",
- "origin",
- "sourceDocument",
+ "error",
+ "content",
+ "updatedBy",
+ "createdAt",
"contentType",
- "status",
"createdBy",
+ "status",
"completedAt",
- "updatedBy",
- "createdAt",
- "error",
- "content"
+ "sourceDocument",
+ "id",
+ "sourceDocumentReadableId",
+ "origin",
+ "printerUrl",
+ "updatedAt",
+ "companyId",
+ "attempts",
+ "sourceDocumentId",
+ "description"
]
},
{
"name": "printerRoute",
"rows": 0,
"columns": [
+ "printerUrl",
+ "name",
+ "locationId",
+ "format",
"updatedAt",
"apiKey",
"companyId",
"mediaSizeId",
"templateId",
- "createdAt",
"id",
- "printerUrl",
- "locationId",
- "name",
- "format"
+ "createdAt"
]
},
{
@@ -1828,6 +1829,7 @@
"columns": [
"active",
"name",
+ "batchType",
"processType",
"updatedBy",
"tags",
@@ -1839,7 +1841,9 @@
"companyId",
"createdAt",
"customFields",
- "completeAllOnScan"
+ "completeAllOnScan",
+ "batchable",
+ "batchRules"
]
},
{
@@ -1911,77 +1915,77 @@
"name": "purchasingRfq",
"rows": 0,
"columns": [
+ "createdBy",
+ "updatedBy",
+ "employeeId",
+ "companyId",
"expirationDate",
+ "status",
"revisionId",
"createdAt",
- "status",
- "updatedBy",
- "createdBy",
- "companyId",
- "employeeId",
- "locationId",
- "internalNotes",
- "rfqId",
- "customFields",
- "updatedAt",
"rfqDate",
"assignee",
+ "id",
"notes",
- "id"
+ "locationId",
+ "internalNotes",
+ "customFields",
+ "rfqId",
+ "updatedAt"
]
},
{
"name": "purchasingRfqFavorite",
"rows": 0,
- "columns": ["userId", "rfqId"]
+ "columns": ["rfqId", "userId"]
},
{
"name": "qualityDocument",
"rows": 0,
"columns": [
- "status",
- "updatedBy",
"assignee",
- "version",
"description",
- "content",
- "updatedAt",
- "id",
- "createdAt",
- "createdBy",
+ "version",
+ "updatedBy",
+ "status",
"companyId",
+ "createdBy",
+ "name",
"tags",
- "name"
+ "content",
+ "createdAt",
+ "id",
+ "updatedAt"
]
},
{
"name": "reportPin",
"rows": 0,
"columns": [
+ "createdBy",
"updatedBy",
- "pinned",
"companyId",
- "createdBy",
- "updatedAt",
- "userId",
+ "pinned",
"createdAt",
- "reportKey"
+ "reportKey",
+ "updatedAt",
+ "userId"
]
},
{
"name": "reportView",
"rows": 0,
"columns": [
- "visibility",
- "id",
- "updatedBy",
- "createdAt",
- "updatedAt",
- "companyId",
"config",
- "createdBy",
+ "reportKey",
"name",
- "reportKey"
+ "createdBy",
+ "updatedBy",
+ "id",
+ "visibility",
+ "companyId",
+ "updatedAt",
+ "createdAt"
]
},
{
@@ -2001,7 +2005,7 @@
{
"name": "searchIndexRegistry",
"rows": 0,
- "columns": ["lastRebuiltAt", "createdAt", "companyId"]
+ "columns": ["companyId", "createdAt", "lastRebuiltAt"]
},
{
"name": "sequence",
@@ -2092,15 +2096,15 @@
"rows": 0,
"columns": [
"shiftId",
- "date",
- "employeeId",
"createdBy",
- "id",
- "updatedBy",
+ "employeeId",
+ "date",
"note",
- "companyId",
+ "updatedBy",
+ "id",
+ "updatedAt",
"createdAt",
- "updatedAt"
+ "companyId"
]
},
{
@@ -2141,140 +2145,140 @@
"name": "slackDocumentThread",
"rows": 0,
"columns": [
+ "channelId",
"createdAt",
"documentType",
"documentId",
- "channelId",
- "createdBy",
- "updatedBy",
- "companyId",
"threadTs",
"updatedAt",
- "id"
+ "id",
+ "updatedBy",
+ "createdBy",
+ "companyId"
]
},
{
"name": "ssoConnection",
"rows": 0,
"columns": [
- "createdAt",
- "id",
- "updatedAt",
- "active",
+ "metadataUrl",
+ "providerId",
+ "requireSso",
+ "metadataXml",
"companyId",
- "createdBy",
"updatedBy",
- "metadataXml",
- "providerId",
- "metadataUrl",
- "requireSso"
+ "createdBy",
+ "updatedAt",
+ "id",
+ "createdAt",
+ "active"
]
},
{
"name": "ssoDomain",
"rows": 0,
"columns": [
- "status",
- "id",
- "createdAt",
- "updatedAt",
+ "verifiedAt",
+ "connectionId",
+ "domain",
+ "verificationToken",
"createdBy",
"updatedBy",
"companyId",
- "verificationToken",
- "verifiedAt",
- "domain",
- "connectionId"
+ "status",
+ "createdAt",
+ "id",
+ "updatedAt"
]
},
{
"name": "stockTransfer",
"rows": 0,
"columns": [
- "createdAt",
- "status",
- "tags",
- "locationId",
- "completedAt",
- "assignee",
"updatedBy",
"createdBy",
- "customFields",
"stockTransferId",
+ "customFields",
"companyId",
"notes",
"id",
- "updatedAt"
+ "updatedAt",
+ "createdAt",
+ "status",
+ "locationId",
+ "tags",
+ "assignee",
+ "completedAt"
]
},
{
"name": "storageRule",
"rows": 0,
"columns": [
- "conditionAst",
- "filteredItemGroupIds",
+ "createdAt",
+ "id",
+ "active",
+ "severity",
+ "updatedAt",
+ "companyId",
+ "appliesToAll",
+ "createdBy",
+ "surfaces",
+ "message",
+ "updatedBy",
+ "targetType",
+ "filteredItemTypes",
"filteredItemMatchAll",
+ "filteredItemGroupIds",
"description",
- "customFields",
"name",
- "filteredItemTypes",
- "targetType",
- "updatedBy",
- "message",
- "createdBy",
- "surfaces",
- "companyId",
- "updatedAt",
- "appliesToAll",
- "severity",
- "createdAt",
- "id",
- "active"
+ "customFields",
+ "conditionAst"
]
},
{
"name": "storageType",
"rows": 0,
"columns": [
- "createdBy",
- "companyId",
- "updatedAt",
"createdAt",
- "name",
- "customFields",
+ "updatedAt",
+ "companyId",
+ "createdBy",
+ "updatedBy",
"id",
- "updatedBy"
+ "customFields",
+ "name"
]
},
{
"name": "suggestion",
"rows": 0,
"columns": [
- "attachmentPath",
"path",
"emoji",
"userId",
+ "attachmentPath",
+ "suggestion",
+ "companyId",
"id",
"createdAt",
- "tags",
- "suggestion",
- "companyId"
+ "tags"
]
},
{
"name": "supplierType",
"rows": 0,
"columns": [
+ "createdAt",
+ "updatedBy",
"companyId",
"protected",
- "updatedBy",
- "createdAt",
- "name",
- "updatedAt",
- "tags",
+ "createdBy",
"id",
"customFields",
- "createdBy"
+ "updatedAt",
+ "tags",
+ "name"
]
},
{
@@ -2325,17 +2329,17 @@
"name": "timeCardEntry",
"rows": 0,
"columns": [
- "clockOut",
- "autoCloseShiftId",
- "clockIn",
- "companyId",
- "note",
"id",
"createdAt",
"updatedAt",
+ "note",
+ "employeeId",
"createdBy",
"updatedBy",
- "employeeId"
+ "clockOut",
+ "clockIn",
+ "companyId",
+ "autoCloseShiftId"
]
},
{
@@ -2374,24 +2378,24 @@
"name": "training",
"rows": 0,
"columns": [
- "id",
- "content",
- "tags",
- "status",
- "updatedAt",
- "name",
- "companyId",
- "type",
"estimatedDuration",
- "assignee",
- "processId",
- "updatedBy",
- "createdBy",
- "version",
- "createdAt",
- "description",
+ "type",
+ "companyId",
+ "name",
+ "updatedAt",
+ "status",
+ "tags",
+ "content",
+ "id",
+ "frequency",
"grantsAbilityId",
- "frequency"
+ "description",
+ "createdAt",
+ "version",
+ "createdBy",
+ "updatedBy",
+ "processId",
+ "assignee"
]
},
{
@@ -2403,8 +2407,8 @@
"trainingId",
"updatedBy",
"createdAt",
- "groupIds",
"companyId",
+ "groupIds",
"updatedAt"
]
},
@@ -2412,40 +2416,40 @@
"name": "trainingCompletion",
"rows": 0,
"columns": [
- "employeeId",
- "companyId",
- "createdAt",
- "completedAt",
"trainingAssignmentId",
"updatedBy",
"createdBy",
"period",
"updatedAt",
"id",
- "completedBy"
+ "completedBy",
+ "employeeId",
+ "companyId",
+ "createdAt",
+ "completedAt"
]
},
{
"name": "trainingQuestion",
"rows": 0,
"columns": [
- "type",
- "question",
- "createdAt",
- "options",
- "sortOrder",
- "tolerance",
- "createdBy",
- "updatedBy",
- "companyId",
+ "correctNumber",
+ "correctBoolean",
+ "id",
+ "required",
"trainingId",
+ "companyId",
"updatedAt",
"matchingPairs",
"correctAnswers",
- "correctNumber",
- "id",
- "correctBoolean",
- "required"
+ "tolerance",
+ "sortOrder",
+ "updatedBy",
+ "createdBy",
+ "question",
+ "createdAt",
+ "type",
+ "options"
]
},
{
@@ -2501,110 +2505,110 @@
"name": "assemblyComponentMapping",
"rows": 0,
"columns": [
+ "confidence",
+ "geometryHash",
+ "itemId",
+ "createdBy",
"updatedBy",
"id",
"companyId",
"modelUploadId",
"updatedAt",
- "createdAt",
- "confidence",
- "geometryHash",
- "itemId",
- "createdBy"
+ "createdAt"
]
},
{
"name": "assemblyInstruction",
"rows": 0,
"columns": [
- "status",
- "customFields",
- "settings",
- "id",
- "companyId",
- "publishedAt",
"name",
"createdBy",
"updatedAt",
- "rootInstructionId",
- "updatedBy",
- "tags",
- "assemblyPlanJobId",
- "version",
+ "companyId",
+ "publishedAt",
+ "customFields",
+ "id",
+ "settings",
+ "status",
+ "itemId",
"modelUploadId",
"createdAt",
- "itemId"
+ "version",
+ "tags",
+ "assemblyPlanJobId",
+ "rootInstructionId",
+ "updatedBy"
]
},
{
"name": "assemblyInstructionStep",
"rows": 0,
"columns": [
+ "camera",
+ "explode",
"sortOrder",
"parentStepId",
"fileTypes",
- "camera",
- "explode",
"updatedAt",
"durationSeconds",
"description",
- "planConfidence",
"fastener",
"maxValue",
"title",
+ "planConfidence",
"createdAt",
"motion",
- "notes",
"warnings",
- "componentNodeIds",
+ "notes",
"assemblyInstructionId",
"listValues",
+ "componentNodeIds",
+ "unitOfMeasureCode",
+ "companyId",
"instructionText",
"buildWave",
"status",
- "unitOfMeasureCode",
- "companyId",
- "id",
- "required",
"updatedBy",
"minValue",
- "type",
- "createdBy"
+ "id",
+ "required",
+ "createdBy",
+ "type"
]
},
{
"name": "assemblyInstructionStepMaterial",
"rows": 0,
"columns": [
- "id",
- "updatedBy",
- "companyId",
- "stepId",
- "createdAt",
- "updatedAt",
- "sortOrder",
- "quantity",
+ "createdBy",
"itemId",
- "createdBy"
+ "quantity",
+ "sortOrder",
+ "updatedAt",
+ "createdAt",
+ "stepId",
+ "companyId",
+ "updatedBy",
+ "id"
]
},
{
"name": "assemblyInstructionStepSlide",
"rows": 0,
"columns": [
- "stepId",
- "updatedAt",
- "createdBy",
- "annotations",
- "createdAt",
- "id",
- "companyId",
- "sortOrder",
+ "size",
"modelUploadId",
"imagePath",
- "size",
+ "caption",
"updatedBy",
- "caption"
+ "annotations",
+ "createdBy",
+ "updatedAt",
+ "stepId",
+ "sortOrder",
+ "id",
+ "companyId",
+ "createdAt"
]
},
{
@@ -2612,13 +2616,13 @@
"rows": 0,
"columns": [
"stepId",
- "createdAt",
"updatedAt",
- "id",
+ "createdAt",
"updatedBy",
+ "id",
"companyId",
- "quantity",
"itemId",
+ "quantity",
"createdBy",
"sortOrder"
]
@@ -2627,17 +2631,17 @@
"name": "assemblyUnit",
"rows": 0,
"columns": [
- "companyId",
"id",
"updatedBy",
"sourceGroupId",
+ "companyId",
+ "modelUploadId",
"createdAt",
"updatedAt",
- "modelUploadId",
"itemId",
- "createdBy",
"componentNodeIds",
- "name"
+ "name",
+ "createdBy"
]
},
{
@@ -2661,18 +2665,18 @@
"name": "changeOrderSupersession",
"rows": 0,
"columns": [
- "changeOrderId",
- "companyId",
- "createdBy",
+ "updatedBy",
+ "supersessionMode",
+ "successorEffectivityDate",
+ "successorItemId",
+ "predecessorItemId",
+ "discontinuationDate",
"id",
"createdAt",
"updatedAt",
- "discontinuationDate",
- "successorItemId",
- "predecessorItemId",
- "successorEffectivityDate",
- "updatedBy",
- "supersessionMode"
+ "companyId",
+ "createdBy",
+ "changeOrderId"
]
},
{
@@ -2723,136 +2727,136 @@
"name": "demandForecast",
"rows": 0,
"columns": [
+ "companyId",
+ "createdAt",
+ "locationId",
"confidence",
"createdBy",
"itemId",
"updatedAt",
- "companyId",
- "createdAt",
- "locationId",
- "updatedBy",
- "forecastMethod",
"notes",
"periodId",
- "forecastQuantity"
+ "forecastQuantity",
+ "updatedBy",
+ "forecastMethod"
]
},
{
"name": "demandProjection",
"rows": 0,
"columns": [
- "notes",
- "forecastQuantity",
- "periodId",
"forecastMethod",
"updatedBy",
+ "notes",
+ "periodId",
+ "forecastQuantity",
+ "confidence",
+ "createdBy",
+ "itemId",
+ "updatedAt",
"companyId",
"createdAt",
"id",
- "locationId",
- "confidence",
- "itemId",
- "createdBy",
- "updatedAt"
+ "locationId"
]
},
{
"name": "inspectionDocument",
"rows": 0,
"columns": [
- "drawingNumber",
- "updatedBy",
- "partId",
- "samplingPercentage",
- "samplingAql",
- "fileName",
+ "version",
"samplingInspectionLevel",
"createdBy",
- "version",
- "samplingSampleSize",
"updatedAt",
"samplingSeverity",
- "samplingPlanType",
- "companyId",
- "createdAt",
- "pageCount",
- "defaultPageHeight",
+ "samplingSampleSize",
+ "drawingNumber",
+ "partId",
+ "updatedBy",
+ "samplingAql",
+ "samplingPercentage",
+ "fileName",
"id",
"defaultPageWidth",
"uploadedBy",
- "storagePath"
+ "storagePath",
+ "samplingPlanType",
+ "createdAt",
+ "companyId",
+ "pageCount",
+ "defaultPageHeight"
]
},
{
"name": "inspectionFeature",
"rows": 0,
"columns": [
- "description",
- "toleranceMinus",
- "id",
- "createdBy",
- "tolerancePlus",
- "unit",
- "samplingPlanType",
- "updatedBy",
- "inspectionDocumentId",
+ "nominalValue",
+ "samplingAql",
+ "samplingPercentage",
+ "companyId",
+ "updatedAt",
+ "pageNumber",
"type",
"samplingSeverity",
"samplingSampleSize",
"label",
"createdAt",
"samplingInspectionLevel",
- "nominalValue",
- "updatedAt",
- "companyId",
- "pageNumber",
- "samplingAql",
- "samplingPercentage"
+ "unit",
+ "tolerancePlus",
+ "updatedBy",
+ "inspectionDocumentId",
+ "samplingPlanType",
+ "description",
+ "createdBy",
+ "toleranceMinus",
+ "id"
]
},
{
"name": "balloon",
"rows": 0,
"columns": [
- "regionY",
"companyId",
"updatedBy",
"inspectionFeatureId",
- "updatedAt",
- "createdBy",
+ "regionY",
"pageNumber",
+ "createdBy",
+ "updatedAt",
+ "createdAt",
+ "inspectionDocumentId",
"regionWidth",
"xCoordinate",
- "inspectionDocumentId",
- "createdAt",
- "regionX",
"regionHeight",
"id",
- "yCoordinate"
+ "yCoordinate",
+ "regionX"
]
},
{
"name": "inventoryCountLine",
"rows": 0,
"columns": [
- "storageUnitId",
- "systemQuantity",
- "id",
- "countedQuantity",
- "readableId",
- "countedAt",
- "companyId",
- "createdAt",
- "createdBy",
- "updatedBy",
- "locationId",
- "countedBy",
- "trackedEntityId",
- "customFields",
- "updatedAt",
"inventoryCountId",
"postedItemLedgerId",
- "itemId"
+ "itemId",
+ "customFields",
+ "updatedAt",
+ "trackedEntityId",
+ "locationId",
+ "countedBy",
+ "createdBy",
+ "updatedBy",
+ "createdAt",
+ "countedAt",
+ "companyId",
+ "readableId",
+ "countedQuantity",
+ "systemQuantity",
+ "id",
+ "storageUnitId"
]
},
{
@@ -2878,14 +2882,14 @@
"name": "itemInspectionDocumentAssignment",
"rows": 0,
"columns": [
- "createdBy",
- "updatedBy",
"inspectionDocumentId",
"companyId",
- "createdAt",
- "itemId",
+ "updatedBy",
+ "createdBy",
+ "usage",
"updatedAt",
- "usage"
+ "itemId",
+ "createdAt"
]
},
{
@@ -2919,53 +2923,53 @@
"name": "itemSerialSequence",
"rows": 0,
"columns": [
+ "next",
+ "updatedBy",
+ "id",
+ "createdBy",
+ "createdAt",
+ "step",
+ "companyId",
"updatedAt",
"suffix",
- "itemId",
- "prefix",
"size",
- "createdBy",
- "id",
- "updatedBy",
- "next",
- "companyId",
- "step",
- "createdAt"
+ "prefix",
+ "itemId"
]
},
{
"name": "itemShelfLife",
"rows": 0,
"columns": [
- "createdBy",
- "triggerProcessId",
- "days",
- "calculateFromBom",
- "triggerTiming",
- "updatedAt",
- "createdAt",
- "mode",
- "companyId",
- "customFields",
+ "updatedBy",
"itemId",
- "updatedBy"
+ "customFields",
+ "companyId",
+ "mode",
+ "createdAt",
+ "updatedAt",
+ "triggerTiming",
+ "calculateFromBom",
+ "days",
+ "triggerProcessId",
+ "createdBy"
]
},
{
"name": "itemSupersession",
"rows": 0,
"columns": [
- "companyId",
- "updatedBy",
- "createdBy",
"updatedAt",
- "createdAt",
"itemId",
+ "createdAt",
"successorEffectivityDate",
- "supersessionMode",
+ "companyId",
+ "updatedBy",
+ "createdBy",
+ "discontinuationDate",
"successorItemId",
- "conversionFactor",
- "discontinuationDate"
+ "supersessionMode",
+ "conversionFactor"
]
},
{
@@ -3010,39 +3014,39 @@
"name": "changeOrderAffectedItem",
"rows": 0,
"columns": [
- "updatedAt",
- "changeOrderId",
- "companyId",
- "supersessionMode",
- "successorEffectivityDate",
- "discontinuationDate",
- "id",
- "newItemId",
"draftMakeMethodId",
- "itemId",
- "createdAt",
- "sortOrder",
- "baseMakeMethodId",
- "changeSummary",
- "changeType",
+ "newItemId",
+ "id",
+ "discontinuationDate",
+ "successorEffectivityDate",
+ "supersessionMode",
+ "companyId",
+ "changeOrderId",
+ "updatedAt",
+ "createdBy",
"updatedBy",
- "createdBy"
+ "changeType",
+ "changeSummary",
+ "baseMakeMethodId",
+ "sortOrder",
+ "itemId",
+ "createdAt"
]
},
{
"name": "nonConformanceItem",
"rows": 0,
"columns": [
- "updatedAt",
- "companyId",
- "itemId",
- "createdAt",
+ "id",
+ "disposition",
+ "createdBy",
+ "nonConformanceId",
"updatedBy",
"quantity",
- "nonConformanceId",
- "createdBy",
- "id",
- "disposition"
+ "createdAt",
+ "companyId",
+ "itemId",
+ "updatedAt"
]
},
{
@@ -3072,81 +3076,81 @@
"name": "purchasingRfqLine",
"rows": 0,
"columns": [
- "updatedAt",
- "purchasingRfqId",
- "customFields",
- "conversionFactor",
- "internalNotes",
- "id",
- "order",
- "externalNotes",
- "purchaseUnitOfMeasureCode",
+ "createdBy",
+ "updatedBy",
+ "quantity",
+ "companyId",
+ "inventoryUnitOfMeasureCode",
"description",
"createdAt",
"itemId",
- "inventoryUnitOfMeasureCode",
- "companyId",
- "quantity",
- "updatedBy",
- "createdBy"
+ "purchaseUnitOfMeasureCode",
+ "id",
+ "order",
+ "externalNotes",
+ "conversionFactor",
+ "internalNotes",
+ "updatedAt",
+ "customFields",
+ "purchasingRfqId"
]
},
{
"name": "qualityDocumentStep",
"rows": 0,
"columns": [
- "type",
"description",
- "createdAt",
"name",
- "updatedBy",
- "createdBy",
+ "createdAt",
+ "type",
"fileTypes",
"required",
- "unitOfMeasureCode",
- "maxValue",
+ "updatedBy",
+ "createdBy",
"updatedAt",
"qualityDocumentId",
"companyId",
- "sortOrder",
+ "unitOfMeasureCode",
+ "maxValue",
"id",
"minValue",
- "listValues"
+ "listValues",
+ "sortOrder"
]
},
{
"name": "riskRegister",
"rows": 0,
"columns": [
- "createdAt",
- "companyId",
- "type",
- "status",
- "likelihood",
+ "createdBy",
+ "source",
+ "updatedBy",
+ "notes",
+ "updatedAt",
+ "title",
+ "description",
+ "severity",
"assignee",
"itemId",
"id",
"sourceId",
- "title",
- "updatedAt",
- "description",
- "severity",
- "source",
- "createdBy",
- "notes",
- "updatedBy"
+ "companyId",
+ "createdAt",
+ "type",
+ "status",
+ "likelihood"
]
},
{
"name": "storageRuleItemAssignment",
"rows": 0,
"columns": [
- "createdBy",
- "companyId",
"createdAt",
- "ruleId",
+ "companyId",
+ "createdBy",
+ "itemId",
"updatedBy",
- "itemId"
+ "ruleId"
]
},
{
@@ -3173,16 +3177,16 @@
"name": "nonConformanceItemTrackedEntity",
"rows": 0,
"columns": [
- "createdBy",
- "updatedBy",
- "nonConformanceItemId",
- "companyId",
- "id",
- "updatedAt",
+ "quantity",
"createdAt",
- "trackedEntityId",
"nonConformanceId",
- "quantity"
+ "trackedEntityId",
+ "companyId",
+ "updatedAt",
+ "id",
+ "createdBy",
+ "updatedBy",
+ "nonConformanceItemId"
]
},
{
@@ -3229,73 +3233,73 @@
"name": "userAttributeCategory",
"rows": 0,
"columns": [
- "protected",
+ "companyId",
"public",
+ "protected",
"createdAt",
- "companyId",
- "name",
- "createdBy",
- "updatedBy",
- "id",
"updatedAt",
+ "id",
"emoji",
- "active"
+ "active",
+ "name",
+ "createdBy",
+ "updatedBy"
]
},
{
"name": "userAttribute",
"rows": 0,
"columns": [
- "canSelfManage",
- "userAttributeCategoryId",
- "sortOrder",
- "attributeDataTypeId",
- "updatedBy",
- "createdBy",
- "active",
- "name",
+ "updatedBy",
+ "attributeDataTypeId",
+ "canSelfManage",
+ "sortOrder",
+ "userAttributeCategoryId",
"listOptions",
"updatedAt",
+ "createdAt",
"id",
- "createdAt"
+ "createdBy",
+ "active",
+ "name"
]
},
{
"name": "userAttributeValue",
"rows": 0,
"columns": [
- "valueText",
"valueBoolean",
"userId",
+ "valueText",
"valueDate",
"updatedBy",
- "valueUser",
- "createdBy",
"valueFile",
"userAttributeId",
- "valueNumeric",
+ "valueUser",
+ "createdBy",
"id",
"createdAt",
- "updatedAt"
+ "updatedAt",
+ "valueNumeric"
]
},
{
"name": "userModulePreference",
"rows": 0,
"columns": [
- "companyId",
- "module",
- "updatedAt",
- "position",
"userId",
+ "hidden",
"id",
- "hidden"
+ "updatedAt",
+ "companyId",
+ "module",
+ "position"
]
},
{
"name": "userToCompany",
"rows": 0,
- "columns": ["role", "companyId", "userId"]
+ "columns": ["userId", "companyId", "role"]
},
{
"name": "warehouse",
@@ -3321,22 +3325,22 @@
"name": "warehouseTransfer",
"rows": 0,
"columns": [
- "transferDate",
- "createdBy",
- "id",
- "reference",
- "companyId",
- "notes",
- "updatedBy",
- "transferId",
- "tags",
- "customFields",
"status",
"createdAt",
- "expectedReceiptDate",
- "toLocationId",
+ "customFields",
"fromLocationId",
- "updatedAt"
+ "updatedAt",
+ "toLocationId",
+ "expectedReceiptDate",
+ "reference",
+ "id",
+ "createdBy",
+ "transferDate",
+ "tags",
+ "updatedBy",
+ "transferId",
+ "notes",
+ "companyId"
]
},
{
@@ -3357,7 +3361,9 @@
"laborRate",
"customFields",
"departmentId",
+ "batchCapacity",
"defaultStandardFactor",
+ "minimumBatchQuantity",
"tags",
"overheadRate",
"description",
@@ -3365,62 +3371,81 @@
]
},
{
- "name": "maintenanceSchedule",
+ "name": "jobOperationBatch",
"rows": 0,
"columns": [
- "companyId",
- "lastGeneratedAt",
- "id",
- "procedureId",
- "priority",
- "name",
- "createdAt",
- "monday",
- "nextDueAt",
- "locationId",
- "active",
"createdBy",
- "friday",
- "frequency",
- "sunday",
- "tuesday",
- "takesWorkCenterOffline",
- "saturday",
+ "notes",
+ "readableId",
"updatedAt",
- "wednesday",
+ "locationId",
+ "createdAt",
+ "id",
+ "customFields",
+ "status",
+ "processId",
+ "companyId",
+ "updatedBy",
+ "workCenterId"
+ ]
+ },
+ {
+ "name": "maintenanceSchedule",
+ "rows": 0,
+ "columns": [
+ "estimatedDuration",
+ "skipHolidays",
"thursday",
+ "wednesday",
"description",
"updatedBy",
"workCenterId",
- "estimatedDuration",
- "skipHolidays"
+ "saturday",
+ "updatedAt",
+ "tuesday",
+ "takesWorkCenterOffline",
+ "frequency",
+ "createdBy",
+ "friday",
+ "sunday",
+ "locationId",
+ "nextDueAt",
+ "active",
+ "createdAt",
+ "name",
+ "monday",
+ "procedureId",
+ "priority",
+ "companyId",
+ "lastGeneratedAt",
+ "id"
]
},
{
"name": "maintenanceDispatch",
"rows": 0,
"columns": [
- "content",
"actualStartTime",
+ "content",
"status",
- "assignee",
"completedAt",
- "updatedBy",
+ "assignee",
"locationId",
+ "updatedBy",
"createdAt",
- "priority",
"plannedStartTime",
"companyId",
+ "priority",
+ "nonConformanceId",
"actualEndTime",
"createdBy",
- "nonConformanceId",
- "plannedEndTime",
"maintenanceDispatchId",
+ "plannedEndTime",
"procedureId",
- "workCenterId",
"takesWorkCenterOffline",
- "updatedAt",
+ "workCenterId",
"suspectedFailureModeId",
+ "updatedAt",
"maintenanceScheduleId",
"id",
"actualFailureModeId",
@@ -3433,64 +3458,64 @@
"name": "maintenanceDispatchComment",
"rows": 0,
"columns": [
- "updatedAt",
- "maintenanceDispatchId",
- "createdAt",
- "id",
+ "createdBy",
"updatedBy",
- "companyId",
"comment",
- "createdBy"
+ "companyId",
+ "createdAt",
+ "id",
+ "updatedAt",
+ "maintenanceDispatchId"
]
},
{
"name": "maintenanceDispatchEvent",
"rows": 0,
"columns": [
- "updatedAt",
- "maintenanceDispatchId",
"createdBy",
- "createdAt",
- "id",
- "companyId",
+ "maintenanceDispatchId",
+ "updatedAt",
"endTime",
- "workCenterId",
- "employeeId",
+ "companyId",
+ "id",
+ "createdAt",
"notes",
- "startTime",
- "updatedBy"
+ "employeeId",
+ "workCenterId",
+ "updatedBy",
+ "startTime"
]
},
{
"name": "maintenanceDispatchItem",
"rows": 0,
"columns": [
- "unitCost",
+ "unitOfMeasureCode",
+ "updatedAt",
+ "itemId",
+ "quantity",
"updatedBy",
- "id",
"createdBy",
- "createdAt",
- "companyId",
+ "id",
+ "unitCost",
"maintenanceDispatchId",
- "updatedAt",
- "unitOfMeasureCode",
- "quantity",
- "itemId"
+ "createdAt",
+ "companyId"
]
},
{
"name": "maintenanceDispatchItemTrackedEntity",
"rows": 0,
"columns": [
- "companyId",
"createdAt",
- "trackedEntityId",
"quantity",
+ "trackedEntityId",
+ "companyId",
+ "updatedBy",
+ "maintenanceDispatchItemId",
"createdBy",
- "updatedAt",
"id",
- "updatedBy",
- "maintenanceDispatchItemId"
+ "updatedAt"
]
},
{
@@ -3503,56 +3528,56 @@
"maintenanceDispatchId",
"createdBy",
"updatedBy",
- "workCenterId",
- "companyId"
+ "companyId",
+ "workCenterId"
]
},
{
"name": "maintenanceScheduleItem",
"rows": 0,
"columns": [
- "maintenanceScheduleId",
- "createdAt",
- "updatedAt",
- "id",
- "updatedBy",
"companyId",
- "quantity",
- "itemId",
+ "updatedBy",
+ "id",
+ "updatedAt",
+ "createdAt",
+ "maintenanceScheduleId",
+ "unitOfMeasureCode",
"createdBy",
- "unitOfMeasureCode"
+ "itemId",
+ "quantity"
]
},
{
"name": "peopleAssignment",
"rows": 0,
"columns": [
- "employeeId",
- "updatedAt",
"shiftId",
"workCenterId",
- "hours",
"locationId",
+ "hours",
+ "employeeId",
+ "updatedAt",
+ "note",
+ "createdAt",
+ "overtimeHours",
+ "companyId",
"date",
- "updatedBy",
"id",
"createdBy",
- "createdAt",
- "note",
- "overtimeHours",
- "companyId"
+ "updatedBy"
]
},
{
"name": "storageRuleWorkCenterAssignment",
"rows": 0,
"columns": [
- "companyId",
- "createdBy",
- "createdAt",
"ruleId",
+ "updatedBy",
"workCenterId",
- "updatedBy"
+ "companyId",
+ "createdBy",
+ "createdAt"
]
},
{
@@ -3661,30 +3686,30 @@
"name": "workCenterReplacementPart",
"rows": 0,
"columns": [
+ "unitOfMeasureCode",
+ "createdBy",
+ "itemId",
+ "quantity",
"companyId",
"updatedBy",
"id",
- "createdAt",
"updatedAt",
- "workCenterId",
- "unitOfMeasureCode",
- "createdBy",
- "itemId",
- "quantity"
+ "createdAt",
+ "workCenterId"
]
},
{
"name": "workCenterShift",
"rows": 0,
"columns": [
- "updatedAt",
- "companyId",
- "createdAt",
- "id",
- "updatedBy",
- "workCenterId",
+ "createdBy",
"shiftId",
- "createdBy"
+ "workCenterId",
+ "updatedBy",
+ "id",
+ "createdAt",
+ "companyId",
+ "updatedAt"
]
},
{
@@ -3742,85 +3767,85 @@
{
"name": "customer",
"rows": 0,
- "columns": [
- "salesContactId",
- "logo",
- "customerStatusId",
- "customerTypeId",
- "customFields",
- "website",
- "fax",
- "currencyCode",
- "tags",
- "embedding",
- "taxPercent",
- "updatedAt",
+ "columns": [
+ "updatedBy",
+ "name",
+ "phone",
+ "createdAt",
"assignee",
"readableId",
- "createdAt",
- "phone",
- "name",
- "updatedBy",
- "accountManagerId",
- "defaultCc",
+ "intercompanyCompanyId",
+ "createdBy",
"id",
"companyId",
- "intercompanyCompanyId",
- "createdBy"
+ "defaultCc",
+ "accountManagerId",
+ "website",
+ "customerStatusId",
+ "customFields",
+ "customerTypeId",
+ "salesContactId",
+ "logo",
+ "taxPercent",
+ "updatedAt",
+ "embedding",
+ "currencyCode",
+ "tags",
+ "fax"
]
},
{
"name": "customerAccount",
"rows": 0,
- "columns": ["active", "companyId", "id", "customerId"]
+ "columns": ["active", "companyId", "customerId", "id"]
},
{
"name": "customerItemPriceOverride",
"rows": 0,
"columns": [
- "active",
- "companyId",
- "customerId",
- "updatedBy",
- "validFrom",
- "applyRulesOnTop",
- "id",
- "createdBy",
+ "notes",
+ "createdAt",
"validTo",
"updatedAt",
"customerTypeId",
"itemId",
- "createdAt",
- "notes"
+ "validFrom",
+ "createdBy",
+ "applyRulesOnTop",
+ "id",
+ "companyId",
+ "active",
+ "updatedBy",
+ "customerId"
]
},
{
"name": "customerItemPriceOverrideBreak",
"rows": 0,
"columns": [
- "createdBy",
- "quantity",
- "overridePrice",
"active",
- "createdAt",
- "updatedAt",
- "customerItemPriceOverrideId",
- "companyId",
+ "overridePrice",
+ "quantity",
+ "createdBy",
+ "id",
"updatedBy",
- "id"
+ "companyId",
+ "customerItemPriceOverrideId",
+ "updatedAt",
+ "createdAt"
]
},
{
"name": "customerLocation",
"rows": 0,
"columns": [
+ "name",
+ "addressId",
+ "customFields",
"id",
"tags",
"customerId",
- "companyId",
- "name",
- "customFields",
- "addressId"
+ "companyId"
]
},
{
@@ -3828,8 +3853,8 @@
"rows": 0,
"columns": [
"userId",
- "contactId",
"customerLocationId",
+ "contactId",
"tags",
"id",
"customFields",
@@ -3884,17 +3909,17 @@
"name": "customerTax",
"rows": 0,
"columns": [
- "eori",
- "vatNumber",
- "taxExemptionCertificateNumber",
- "taxExempt",
- "taxId",
- "taxExemptionCertificatePath",
- "updatedAt",
- "customerId",
+ "taxExemptionReason",
"companyId",
+ "customerId",
"updatedBy",
- "taxExemptionReason"
+ "taxExemptionCertificatePath",
+ "updatedAt",
+ "taxId",
+ "taxExempt",
+ "taxExemptionCertificateNumber",
+ "vatNumber",
+ "eori"
]
},
{
@@ -4390,143 +4415,138 @@
"name": "capacityReservation",
"rows": 0,
"columns": [
- "endAt",
- "createdBy",
+ "scenarioId",
+ "id",
+ "createdAt",
+ "jobId",
"workHours",
"updatedAt",
"companyId",
- "jobId",
- "id",
- "scenarioId",
- "createdAt",
- "startAt",
- "resourceId",
- "resourceKind",
- "earliestStartAt",
+ "endAt",
+ "createdBy",
+ "operationId",
+ "updatedBy",
"scheduleNote",
"isPlaceholder",
- "operationId",
- "updatedBy"
+ "earliestStartAt",
+ "resourceKind",
+ "resourceId",
+ "jobOperationBatchId",
+ "startAt"
]
},
{
"name": "gauge",
"rows": 0,
"columns": [
- "gaugeRole",
- "gaugeCalibrationStatus",
- "id",
- "description",
- "lastCalibrationDate",
- "gaugeId",
- "storageUnitId",
- "gaugeStatus",
- "gaugeTypeId",
"serialNumber",
"calibrationIntervalInMonths",
"createdBy",
"updatedBy",
- "updatedAt",
"locationId",
+ "updatedAt",
"companyId",
"createdAt",
"customFields",
- "nextCalibrationDate",
"supplierId",
+ "nextCalibrationDate",
"modelNumber",
"dateAcquired",
- "lastCalibrationStatus"
+ "lastCalibrationStatus",
+ "gaugeRole",
+ "gaugeCalibrationStatus",
+ "id",
+ "description",
+ "lastCalibrationDate",
+ "gaugeId",
+ "storageUnitId",
+ "gaugeStatus",
+ "gaugeTypeId"
]
},
{
"name": "gaugeCalibrationRecord",
"rows": 0,
"columns": [
- "calibrationAttempts",
- "createdBy",
- "requiresAction",
- "humidity",
- "supplierId",
- "inspectionStatus",
+ "notes",
+ "companyId",
+ "temperature",
+ "gaugeId",
+ "updatedAt",
+ "requiresAdjustment",
+ "customFields",
+ "id",
+ "createdAt",
+ "requiresRepair",
"updatedBy",
"dateCalibrated",
+ "inspectionStatus",
"approvedBy",
"measurementStandard",
- "requiresRepair",
- "id",
- "customFields",
- "createdAt",
- "requiresAdjustment",
- "temperature",
- "gaugeId",
- "updatedAt",
- "notes",
- "companyId"
+ "humidity",
+ "supplierId",
+ "createdBy",
+ "calibrationAttempts",
+ "requiresAction"
]
},
{
"name": "inspection",
"rows": 0,
"columns": [
- "companyId",
+ "status",
+ "notes",
+ "aql",
+ "sourceDocument",
+ "createdAt",
+ "supplierId",
+ "dispositionedBy",
"acceptanceNumber",
"sourceDocumentReadableId",
- "dispositionedBy",
"itemId",
- "codeLetter",
+ "companyId",
"updatedBy",
+ "codeLetter",
"dispositionedAt",
"inspectionLevel",
- "aql",
- "status",
- "notes",
- "sourceDocument",
- "supplierId",
- "createdAt",
- "samplingStandard",
- "id",
- "sampleSize",
- "inspectionDocumentId",
- "itemReadableId",
- "updatedAt",
- "severity",
"inspectionId",
"rejectionNumber",
- "sourceDocumentId",
+ "severity",
+ "samplingPlanType",
+ "createdBy",
"lotSize",
"sourceDocumentLineId",
- "samplingPlanType",
- "createdBy"
+ "sourceDocumentId",
+ "inspectionDocumentId",
+ "sampleSize",
+ "id",
+ "samplingStandard",
+ "updatedAt",
+ "itemReadableId"
]
},
{
"name": "inspectionSample",
"rows": 0,
"columns": [
+ "inspectedAt",
+ "trackedEntityId",
+ "status",
+ "notes",
+ "updatedBy",
+ "companyId",
+ "createdBy",
+ "inspectionId",
"inspectedBy",
- "updatedAt",
"createdAt",
"id",
- "createdBy",
- "companyId",
- "inspectionId",
- "notes",
- "updatedBy",
- "inspectedAt",
- "trackedEntityId",
- "status"
+ "updatedAt"
]
},
{
"name": "inspectionMeasurement",
"rows": 0,
"columns": [
- "value",
- "createdAt",
- "notes",
- "inspectionFeatureId",
- "inspectionSampleId",
- "updatedAt",
"status",
"createdBy",
"id",
@@ -4534,25 +4554,31 @@
"companyId",
"inspectedBy",
"updatedBy",
- "inspectionId"
+ "inspectionId",
+ "value",
+ "createdAt",
+ "notes",
+ "inspectionFeatureId",
+ "updatedAt",
+ "inspectionSampleId"
]
},
{
"name": "inspectionSamplingPlan",
"rows": 0,
"columns": [
- "createdAt",
- "companyId",
- "inspectionId",
- "rejectionNumber",
"updatedBy",
- "id",
"createdBy",
- "codeLetter",
- "sampleSize",
- "inspectionFeatureId",
+ "id",
+ "rejectionNumber",
+ "inspectionId",
+ "createdAt",
+ "companyId",
"acceptanceNumber",
- "updatedAt"
+ "updatedAt",
+ "inspectionFeatureId",
+ "sampleSize",
+ "codeLetter"
]
},
{
@@ -4568,26 +4594,26 @@
"nonConformanceId"
]
},
- {
- "name": "inspectionHistory",
- "rows": 0,
- "columns": [
- "inspectionId",
- "companyId",
- "updatedBy",
- "sampleSize",
- "aql",
- "defectsFound",
- "lotSize",
- "id",
- "severity",
+ {
+ "name": "inspectionHistory",
+ "rows": 0,
+ "columns": [
+ "outcome",
+ "samplingStandard",
+ "createdBy",
+ "supplierId",
"createdAt",
"itemId",
- "supplierId",
"inspectionLevel",
- "outcome",
- "samplingStandard",
- "createdBy"
+ "id",
+ "lotSize",
+ "defectsFound",
+ "severity",
+ "updatedBy",
+ "inspectionId",
+ "companyId",
+ "aql",
+ "sampleSize"
]
},
{
@@ -4674,29 +4700,29 @@
"name": "stockTransferLine",
"rows": 0,
"columns": [
+ "fromStorageUnitId",
"trackedEntityId",
- "pickedQuantity",
"id",
- "fromStorageUnitId",
+ "pickedQuantity",
+ "quantity",
"requiresSerialTracking",
"stockTransferId",
"createdBy",
- "quantity",
- "itemId",
- "requiresBatchTracking",
"createdAt",
"updatedAt",
+ "itemId",
+ "requiresBatchTracking",
+ "toStorageUnitId",
"updatedBy",
- "jobId",
- "companyId",
"jobMaterialId",
- "toStorageUnitId"
+ "companyId",
+ "jobId"
]
},
{
"name": "jobMaterialStep",
"rows": 0,
- "columns": ["quantity", "jobOperationStepId", "jobMaterialId"]
+ "columns": ["jobMaterialId", "jobOperationStepId", "quantity"]
},
{
"name": "jobOperation",
@@ -4744,6 +4770,7 @@
"priority",
"description",
"quantityScrapped",
+ "jobOperationBatchId",
"order",
"jobMakeMethodId",
"operationOrder",
@@ -4757,11 +4784,11 @@
"name": "jobOperationDependency",
"rows": 0,
"columns": [
- "dependsOnId",
"operationId",
+ "dependsOnId",
+ "createdAt",
"jobId",
- "companyId",
- "createdAt"
+ "companyId"
]
},
{
@@ -4814,23 +4841,23 @@
"name": "pickingListLine",
"rows": 0,
"columns": [
- "id",
"toStorageUnitId",
+ "id",
"itemId",
- "updatedBy",
"pickingListId",
"companyId",
- "quantityPicked",
+ "updatedBy",
"storageUnitId",
+ "quantityPicked",
"status",
"jobOperationId",
"updatedAt",
"createdAt",
+ "customFields",
+ "quantityReturned",
"jobId",
"createdBy",
"jobMaterialId",
- "customFields",
- "quantityReturned",
"quantityToPick"
]
},
@@ -4838,11 +4865,11 @@
"name": "pickingListLineTrackedEntity",
"rows": 0,
"columns": [
- "trackedEntityId",
"pickingListLineId",
- "quantity",
+ "trackedEntityId",
+ "companyId",
"quantityPicked",
- "companyId"
+ "quantity"
]
},
{
@@ -4861,6 +4888,7 @@
"type",
"startTime",
"notes",
+ "jobOperationBatchId",
"endTime",
"updatedAt"
]
@@ -4906,17 +4934,17 @@
"name": "rework",
"rows": 0,
"columns": [
+ "triggeredAtJobOperationId",
+ "targetJobOperationId",
"reason",
"updatedAt",
- "targetJobOperationId",
- "triggeredAtJobOperationId",
- "quantity",
- "createdAt",
- "id",
- "completedAt",
- "companyId",
+ "jobId",
"requestedById",
- "jobId"
+ "companyId",
+ "completedAt",
+ "id",
+ "createdAt",
+ "quantity"
]
},
{
@@ -4967,79 +4995,80 @@
"name": "jobOperationStepSlide",
"rows": 0,
"columns": [
+ "annotations",
+ "sortOrder",
+ "createdBy",
+ "imagePath",
+ "caption",
+ "companyId",
"size",
"updatedBy",
"id",
- "companyId",
- "modelUploadId",
- "stepId",
"updatedAt",
"createdAt",
- "sortOrder",
- "annotations",
- "imagePath",
- "caption",
- "createdBy"
+ "stepId",
+ "modelUploadId"
]
},
{
"name": "jobOperationToolStep",
"rows": 0,
- "columns": ["jobOperationToolId", "jobOperationStepId"]
+ "columns": ["jobOperationStepId", "jobOperationToolId"]
},
{
"name": "kanban",
"rows": 0,
"columns": [
- "companyId",
- "id",
- "conversionFactor",
- "storageUnitId",
- "itemId",
- "createdBy",
- "autoStartJob",
- "autoRelease",
- "purchaseUnitOfMeasureCode",
- "createdAt",
- "locationId",
"completedBarcodeOverride",
"updatedBy",
+ "createdAt",
+ "locationId",
+ "supplierId",
"jobId",
+ "fromStorageUnitId",
"quantity",
- "updatedAt",
"replenishmentSystem",
- "supplierId"
+ "updatedAt",
+ "storageUnitId",
+ "companyId",
+ "id",
+ "conversionFactor",
+ "autoRelease",
+ "purchaseUnitOfMeasureCode",
+ "itemId",
+ "createdBy",
+ "autoStartJob"
]
},
{
"name": "memo",
"rows": 0,
"columns": [
- "postedAt",
- "memoId",
- "reference",
"postingDate",
- "exchangeRate",
"updatedAt",
- "currencyCode",
- "id",
- "amount",
+ "exchangeRate",
+ "postedAt",
+ "reference",
+ "memoId",
"supplierId",
"customFields",
+ "id",
+ "currencyCode",
+ "amount",
+ "updatedBy",
+ "memoDate",
+ "status",
"direction",
"notes",
- "status",
- "voidedAt",
"voidedBy",
- "memoDate",
- "updatedBy",
+ "voidedAt",
+ "journalId",
+ "createdBy",
+ "postedBy",
"createdAt",
- "reasonAccount",
- "companyId",
"customerId",
- "postedBy",
- "journalId",
- "createdBy"
+ "companyId",
+ "reasonAccount"
]
},
{
@@ -5152,19 +5181,19 @@
"name": "methodOperationStepSlide",
"rows": 0,
"columns": [
- "sortOrder",
"annotations",
- "caption",
- "imagePath",
+ "sortOrder",
"createdBy",
- "id",
+ "imagePath",
+ "caption",
+ "companyId",
"updatedBy",
+ "id",
"size",
- "companyId",
- "modelUploadId",
- "stepId",
"createdAt",
- "updatedAt"
+ "updatedAt",
+ "stepId",
+ "modelUploadId"
]
},
{
@@ -5185,20 +5214,20 @@
{
"name": "methodOperationToolStep",
"rows": 0,
- "columns": ["methodOperationToolId", "methodOperationStepId"]
+ "columns": ["methodOperationStepId", "methodOperationToolId"]
},
{
"name": "nonConformanceActionProcess",
"rows": 0,
"columns": [
- "createdAt",
+ "updatedBy",
+ "actionTaskId",
+ "createdBy",
+ "id",
"updatedAt",
"processId",
"companyId",
- "createdBy",
- "id",
- "updatedBy",
- "actionTaskId"
+ "createdAt"
]
},
{
@@ -5259,31 +5288,31 @@
"name": "payment",
"rows": 0,
"columns": [
- "postedAt",
+ "customerId",
+ "bankAccount",
+ "companyId",
+ "createdAt",
+ "journalId",
+ "createdBy",
+ "postedBy",
+ "voidedBy",
+ "voidedAt",
+ "paymentType",
+ "memo",
+ "status",
+ "paymentDate",
+ "updatedBy",
+ "totalAmount",
+ "currencyCode",
+ "id",
+ "customFields",
+ "supplierId",
"reference",
"paymentId",
- "postingDate",
+ "postedAt",
"updatedAt",
"exchangeRate",
- "id",
- "currencyCode",
- "totalAmount",
- "supplierId",
- "customFields",
- "status",
- "memo",
- "paymentType",
- "voidedBy",
- "voidedAt",
- "updatedBy",
- "paymentDate",
- "createdAt",
- "customerId",
- "companyId",
- "bankAccount",
- "createdBy",
- "journalId",
- "postedBy"
+ "postingDate"
]
},
{
@@ -5433,13 +5462,13 @@
"name": "purchasingRfqSupplier",
"rows": 0,
"columns": [
- "purchasingRfqId",
- "id",
- "createdBy",
"supplierId",
"companyId",
"updatedBy",
- "createdAt"
+ "createdAt",
+ "purchasingRfqId",
+ "id",
+ "createdBy"
]
},
{
@@ -5505,7 +5534,7 @@
{
"name": "quoteMaterialStep",
"rows": 0,
- "columns": ["quantity", "quoteOperationStepId", "quoteMaterialId"]
+ "columns": ["quoteMaterialId", "quoteOperationStepId", "quantity"]
},
{
"name": "quoteOperation",
@@ -5589,18 +5618,18 @@
"name": "quoteOperationStepSlide",
"rows": 0,
"columns": [
- "imagePath",
"caption",
+ "imagePath",
"createdBy",
- "annotations",
"sortOrder",
- "stepId",
+ "annotations",
"modelUploadId",
+ "stepId",
"updatedAt",
"createdAt",
"size",
- "updatedBy",
"id",
+ "updatedBy",
"companyId"
]
},
@@ -5622,7 +5651,7 @@
{
"name": "quoteOperationToolStep",
"rows": 0,
- "columns": ["quoteOperationStepId", "quoteOperationToolId"]
+ "columns": ["quoteOperationToolId", "quoteOperationStepId"]
},
{
"name": "receiptFixedAssetLine",
@@ -5685,119 +5714,122 @@
"name": "salesInvoice",
"rows": 0,
"columns": [
- "currencyCode",
- "exchangeRate",
"companyId",
"totalDiscount",
- "exchangeRateUpdatedAt",
- "customerReference",
+ "currencyCode",
+ "exchangeRate",
"createdAt",
"dateDue",
+ "customerReference",
+ "exchangeRateUpdatedAt",
+ "createdBy",
+ "internalNotes",
"opportunityId",
"invoiceCustomerLocationId",
- "internalNotes",
- "createdBy",
+ "totalAmount",
+ "totalTax",
"customerId",
"locationId",
"status",
- "totalTax",
- "totalAmount",
- "invoiceCustomerId",
"assignee",
- "id",
- "paymentTermId",
+ "invoiceCustomerId",
"customFields",
"dateIssued",
- "tags",
- "invoiceCustomerContactId",
- "externalNotes",
- "shipmentId",
+ "id",
+ "paymentTermId",
"updatedAt",
"postingDate",
- "subtotal",
- "datePaid",
+ "shipmentId",
+ "tags",
+ "invoiceCustomerContactId",
+ "externalNotes",
"invoiceId",
- "updatedBy"
+ "updatedBy",
+ "datePaid",
+ "subtotal"
]
},
{
"name": "salesInvoiceLine",
"rows": 0,
"columns": [
- "nonTaxableAddOnCost",
- "opportunityId",
+ "locationId",
+ "companyId",
+ "itemId",
+ "addOnCost",
+ "modelUploadId",
+ "unitPrice",
+ "shippingCost",
+ "sortOrder",
+ "taxPercent",
+ "exchangeRate",
+ "invoiceLineType",
+ "description",
+ "createdAt",
+ "salesOrderId",
+ "updatedBy",
+ "accountId",
"unitOfMeasureCode",
- "id",
+ "opportunityId",
+ "nonTaxableAddOnCost",
"assetId",
+ "id",
"internalNotes",
"methodType",
- "storageUnitId",
- "updatedAt",
"invoiceId",
+ "updatedAt",
+ "storageUnitId",
"setupPrice",
- "externalNotes",
- "createdBy",
"quantity",
- "customFields",
+ "createdBy",
+ "externalNotes",
"salesOrderLineId",
- "itemId",
- "companyId",
- "locationId",
- "unitPrice",
- "modelUploadId",
- "addOnCost",
- "taxPercent",
- "sortOrder",
- "shippingCost",
- "description",
- "invoiceLineType",
- "exchangeRate",
- "createdAt",
- "accountId",
- "updatedBy",
- "salesOrderId"
+ "customFields"
]
},
{
"name": "salesInvoiceShipment",
"rows": 0,
"columns": [
- "shippingCost",
- "incotermLocation",
- "createdAt",
- "updatedAt",
- "createdBy",
+ "customFields",
"id",
+ "createdBy",
"updatedBy",
- "customFields",
- "locationId",
- "shippingMethodId",
- "companyId",
+ "createdAt",
+ "updatedAt",
+ "incotermLocation",
+ "shippingCost",
+ "shippingTermId",
"incoterm",
- "shippingTermId"
+ "companyId",
+ "shippingMethodId",
+ "locationId"
]
},
{
"name": "invoiceSettlement",
"rows": 0,
"columns": [
- "targetExchangeRate",
- "id",
- "writeOffAmount",
"targetMemoId",
+ "writeOffAmount",
+ "id",
+ "targetExchangeRate",
+ "discountAmount",
+ "sourceExchangeRate",
+ "createdAt",
"appliedDate",
"paymentId",
- "createdAt",
- "sourceExchangeRate",
- "discountAmount",
- "targetPurchaseInvoiceId",
"createdBy",
"appliedViaPaymentId",
- "updatedBy",
- "targetSalesInvoiceId",
- "memoId",
+ "targetPurchaseInvoiceId",
+ "fxGainLossAmount",
+ "sourceAmount",
+ "appliedAmount",
"companyId",
- "appliedAmount"
+ "memoId",
+ "targetSalesInvoiceId",
+ "sourcePaymentId",
+ "updatedBy"
]
},
{
@@ -5805,15 +5837,15 @@
"rows": 0,
"columns": [
"serialNumber",
- "createdBy",
"salesOrderLineId",
"shipped",
- "companyId",
+ "createdBy",
"updatedAt",
"id",
- "createdAt",
+ "companyId",
+ "shipmentId",
"updatedBy",
- "shipmentId"
+ "createdAt"
]
},
{
@@ -5861,30 +5893,30 @@
"name": "supplier",
"rows": 0,
"columns": [
- "createdAt",
- "assignee",
- "readableId",
+ "website",
+ "supplierTypeId",
+ "customFields",
+ "intercompanyCompanyId",
+ "purchasingContactId",
+ "logo",
+ "tags",
+ "updatedAt",
+ "embedding",
+ "fax",
+ "taxPercent",
+ "currencyCode",
"name",
"updatedBy",
"phone",
- "defaultCc",
- "accountManagerId",
+ "createdAt",
+ "assignee",
+ "readableId",
"supplierStatus",
"createdBy",
"id",
"companyId",
- "intercompanyCompanyId",
- "purchasingContactId",
- "logo",
- "website",
- "supplierTypeId",
- "customFields",
- "fax",
- "taxPercent",
- "currencyCode",
- "tags",
- "updatedAt",
- "embedding"
+ "defaultCc",
+ "accountManagerId"
]
},
{
@@ -5979,8 +6011,8 @@
"rows": 0,
"columns": [
"name",
- "addressId",
"customFields",
+ "addressId",
"tags",
"id",
"companyId",
@@ -6172,17 +6204,17 @@
"name": "supplierPartPrice",
"rows": 0,
"columns": [
- "createdBy",
+ "sourceDocumentId",
"unitPrice",
"sourceType",
- "sourceDocumentId",
- "updatedAt",
- "createdAt",
- "quantity",
- "companyId",
- "leadTime",
+ "createdBy",
"updatedBy",
- "supplierPartId"
+ "supplierPartId",
+ "leadTime",
+ "companyId",
+ "quantity",
+ "createdAt",
+ "updatedAt"
]
},
{
@@ -6330,51 +6362,51 @@
"name": "supplierTax",
"rows": 0,
"columns": [
- "taxExempt",
- "taxExemptionCertificateNumber",
- "eori",
- "vatNumber",
- "taxExemptionReason",
+ "taxId",
+ "taxExemptionCertificatePath",
+ "updatedAt",
"supplierId",
"companyId",
"updatedBy",
- "taxExemptionCertificatePath",
- "updatedAt",
- "taxId"
+ "taxExemptionReason",
+ "eori",
+ "vatNumber",
+ "taxExemptionCertificateNumber",
+ "taxExempt"
]
},
{
"name": "workflow",
"rows": 0,
"columns": [
- "nextRunAt",
- "createdBy",
- "updatedAt",
- "companyId",
+ "createdAt",
"id",
"canvasState",
- "createdAt",
- "publishedVersionId",
+ "companyId",
+ "updatedAt",
+ "createdBy",
+ "nextRunAt",
+ "updatedBy",
+ "ownerId",
"description",
"name",
- "ownerId",
- "updatedBy"
+ "publishedVersionId"
]
},
{
"name": "workflowVersion",
"rows": 0,
"columns": [
- "createdBy",
- "updatedBy",
"companyId",
- "nodes",
- "id",
- "createdAt",
+ "updatedBy",
+ "createdBy",
"updatedAt",
- "edges",
- "versionNumber",
+ "createdAt",
+ "id",
+ "nodes",
"workflowId",
+ "versionNumber",
+ "edges",
"formatVersion"
]
},
@@ -6382,66 +6414,66 @@
"name": "workflowRun",
"rows": 0,
"columns": [
- "path",
- "rootRunId",
- "companyId",
- "triggerRecordId",
- "status",
- "ownerId",
- "id",
- "statusReason",
- "sourceEventId",
- "workflowId",
- "causedByRunId",
- "workflowVersionId",
- "durationMs",
- "completedAt",
- "triggerTable",
- "createdAt",
"eventId",
"isTest",
"error",
- "compactedAt",
+ "createdAt",
"depth",
- "startedAt"
+ "compactedAt",
+ "startedAt",
+ "durationMs",
+ "completedAt",
+ "workflowId",
+ "causedByRunId",
+ "workflowVersionId",
+ "triggerTable",
+ "statusReason",
+ "ownerId",
+ "id",
+ "sourceEventId",
+ "rootRunId",
+ "companyId",
+ "path",
+ "status",
+ "triggerRecordId"
]
},
{
"name": "workflowStepRun",
"rows": 0,
"columns": [
- "output",
- "id",
- "statusReason",
- "nodeType",
- "startedAt",
+ "createdAt",
+ "detail",
+ "sequence",
+ "completedAt",
+ "runId",
+ "itemKey",
+ "branchTaken",
+ "nodeId",
+ "compactedAt",
+ "durationMs",
"companyId",
+ "startedAt",
"error",
"input",
"status",
- "nodeId",
- "branchTaken",
- "durationMs",
- "compactedAt",
- "detail",
- "createdAt",
- "sequence",
- "runId",
- "completedAt",
- "itemKey"
+ "output",
+ "id",
+ "statusReason",
+ "nodeType"
]
},
{
"name": "workflowTriggerEvent",
"rows": 0,
"columns": [
- "origin",
- "id",
"companyId",
- "eventId",
- "createdAt",
+ "id",
+ "origin",
+ "workflowVersionId",
"workflowId",
- "workflowVersionId"
+ "createdAt",
+ "eventId"
]
}
],
diff --git a/packages/jobs/src/inngest/functions/integrations/accounting-outbound-sweep.ts b/packages/jobs/src/inngest/functions/integrations/accounting-outbound-sweep.ts
index e63dd3a076..05fc23dd27 100644
--- a/packages/jobs/src/inngest/functions/integrations/accounting-outbound-sweep.ts
+++ b/packages/jobs/src/inngest/functions/integrations/accounting-outbound-sweep.ts
@@ -229,7 +229,10 @@ async function sweepCompanyProvider(args: {
const billIds = await pageIds({
ctx,
table: "purchaseInvoice",
- statuses: SWEPT_BILL_STATUSES,
+ statuses:
+ providerId === "rillet"
+ ? [...SWEPT_BILL_STATUSES, "Voided"]
+ : SWEPT_BILL_STATUSES,
dateColumn: "postingDate",
floor
});
@@ -258,7 +261,10 @@ async function sweepCompanyProvider(args: {
const invoiceIds = await pageIds({
ctx,
table: "salesInvoice",
- statuses: SWEPT_INVOICE_STATUSES,
+ statuses:
+ providerId === "rillet"
+ ? [...SWEPT_INVOICE_STATUSES, "Voided"]
+ : SWEPT_INVOICE_STATUSES,
dateColumn: "postingDate",
floor
});
@@ -281,9 +287,23 @@ async function sweepCompanyProvider(args: {
dateColumn: "createdAt",
floor
});
- scanned.payments = paymentIds.length;
+ // A void is a LATE state change, so `createdAt` cannot see it: a payment
+ // created before the lookback floor and voided today is invisible to the
+ // page above, and a lost void event would never recover. Page those by
+ // `voidedAt` as well — the column that actually moved.
+ const lateVoidedPaymentIds = await pageIds({
+ ctx,
+ table: "payment",
+ statuses: ["Voided"],
+ dateColumn: "voidedAt",
+ floor
+ });
+ const sweptPaymentIds = [
+ ...new Set([...paymentIds, ...lateVoidedPaymentIds])
+ ];
+ scanned.payments = sweptPaymentIds.length;
refs.push(
- ...paymentIds.map(
+ ...sweptPaymentIds.map(
(id): ReconcileRef => ({ entityType: "payment", entityId: id })
)
);
diff --git a/packages/jobs/src/inngest/functions/integrations/reconcile-executor.ts b/packages/jobs/src/inngest/functions/integrations/reconcile-executor.ts
index a32cadbaf6..c72fd8bcb8 100644
--- a/packages/jobs/src/inngest/functions/integrations/reconcile-executor.ts
+++ b/packages/jobs/src/inngest/functions/integrations/reconcile-executor.ts
@@ -20,6 +20,7 @@ import {
transitionOperation
} from "@carbon/ee/accounting";
import type { SupabaseClient } from "@supabase/supabase-js";
+import { sql } from "kysely";
import {
enqueueSyncOperations,
insertTerminalSyncOperations,
@@ -58,6 +59,7 @@ const SNAPSHOT_TABLES: Record<
const MAPPED_TYPES: ReadonlySet<ReconcileEntityType> = new Set([
"bill",
"invoice",
+ "payment",
"customer",
"vendor",
"item",
@@ -212,29 +214,43 @@ export async function reconcileEntities(args: {
}
}
- // Push mappings (documents + master data).
+ // Mapping state is loaded in one unbounded SQL query. Payment keys can
+ // fan out as <paymentId>:<documentId>; their prefix is the source identity.
const mappingByEntity = new Map<
string,
{ externalId: string | null; lastSyncedAt: string | null }
>();
+ const unvoidedPushMappings = new Set<string>();
if (MAPPED_TYPES.has(entityType)) {
- const mappings = await args.client
- .from("externalIntegrationMapping")
- .select("entityId, externalId, lastSyncedAt")
- .eq("companyId", args.companyId)
- .eq("integration", args.providerId)
- .eq("entityType", entityType)
- .in("entityId", ids);
- if (mappings.error) {
- throw new Error(
- `Failed to load ${entityType} mappings: ${mappings.error.message}`
- );
- }
- for (const row of mappings.data ?? []) {
- mappingByEntity.set(row.entityId, {
+ const mappings = await args.database
+ .selectFrom("externalIntegrationMapping")
+ .select(["entityId", "externalId", "lastSyncedAt", "metadata"])
+ .where("companyId", "=", args.companyId)
+ .where("integration", "=", args.providerId)
+ .where("entityType", "=", entityType)
+ .where(
+ entityType === "payment"
+ ? sql<string>`split_part("entityId", ':', 1)`
+ : "entityId",
+ "in",
+ ids
+ )
+ .execute();
+ for (const row of mappings) {
+ const sourceId =
+ entityType === "payment" ? row.entityId.split(":")[0]! : row.entityId;
+ mappingByEntity.set(sourceId, {
externalId: row.externalId,
lastSyncedAt: row.lastSyncedAt
});
+ const metadata = row.metadata as Record<string, unknown> | null;
+ if (
+ row.externalId &&
+ metadata?.voided !== true &&
+ (entityType !== "payment" || metadata?.origin === "carbon")
+ ) {
+ unvoidedPushMappings.add(sourceId);
+ }
}
}
@@ -329,6 +345,7 @@ export async function reconcileEntities(args: {
snapshot,
hasMappingWithExternalId:
mappingByEntity.get(entityId)?.externalId != null,
+ hasUnvoidedPushMapping: unvoidedPushMappings.has(entityId),
lastSyncedAt: mappingByEntity.get(entityId)?.lastSyncedAt ?? null,
hasLiveOperation: liveByEntity.has(entityId),
latestOperation: latestByEntity.get(entityId) ?? null,
@@ -352,6 +369,7 @@ export async function reconcileEntities(args: {
}
: {}),
context: {
+ providerSupportsNativeVoid: args.providerId === "rillet",
journalEntryPushEnabled,
entityPushEnabled,
providerSupportsPaymentPush: PAYMENT_PUSH_PROVIDERS.has(
diff --git a/packages/jobs/src/inngest/functions/integrations/reconcile-golden.test.ts b/packages/jobs/src/inngest/functions/integrations/reconcile-golden.test.ts
index 3b8b8bff63..bd42b0f6d8 100644
--- a/packages/jobs/src/inngest/functions/integrations/reconcile-golden.test.ts
+++ b/packages/jobs/src/inngest/functions/integrations/reconcile-golden.test.ts
@@ -18,9 +18,8 @@
* FIX-3 Master data uses updatedAt vs lastSyncedAt instead of the 60s
* completed-row cooldown (no window to swallow a real change, no
* window to wait out for a no-op).
- * FIX-4 A Voided payment with prior operations records nothing (v1 has no
- * void echo — the legacy transition enqueue only produced a Skipped
- * park).
+ * FIX-4 Native Rillet voids reconcile from durable active mapping state;
+ * unsupported providers preserve their prior disposition behavior.
*
* The journal POLICY routing itself (push vs Excluded vs Warning, metadata,
* granularity) is shared by construction — both the legacy path and the
@@ -542,7 +541,7 @@ describe("golden: payments", () => {
).toEqual(["nothing"]);
});
- it("FIX-4: a Voided payment with prior ops records nothing (no void echo in v1)", () => {
+ it("unsupported native-void adapter preserves the prior payment disposition", () => {
expect(
kinds(
computeReconcileDecision(
@@ -619,3 +618,50 @@ describe("golden: master data", () => {
).toEqual(["nothing"]);
});
});
+
+describe("Rillet mapped void reconciliation", () => {
+ it.each([
+ "invoice",
+ "bill",
+ "payment"
+ ] as const)("enqueues %s void after Completed creation until all native mappings are voided", (entityType) => {
+ const source = input({
+ entityType,
+ snapshot: { status: "Voided" },
+ hasUnvoidedPushMapping: true,
+ context: { ...baseContext, providerSupportsNativeVoid: true },
+ latestOperation: {
+ id: "op-post",
+ status: "Completed",
+ errorCode: null,
+ attemptCount: 1,
+ createdAt: "2026-09-09T10:00:00Z"
+ }
+ });
+ expect(kinds(computeReconcileDecision(source))).toEqual(["enqueue"]);
+ expect(
+ kinds(computeReconcileDecision({ ...source, hasLiveOperation: true }))
+ ).toEqual(["nothing"]);
+ expect(
+ kinds(
+ computeReconcileDecision({ ...source, hasUnvoidedPushMapping: false })
+ )
+ ).toEqual(["nothing"]);
+ expect(
+ kinds(
+ computeReconcileDecision({
+ ...source,
+ context: { ...source.context, providerSupportsNativeVoid: false }
+ })
+ )
+ ).toEqual(["nothing"]);
+ expect(
+ kinds(
+ computeReconcileDecision({
+ ...source,
+ latestOperation: { ...source.latestOperation!, status: "Failed" }
+ })
+ )
+ ).toEqual(["re-drive"]);
+ });
+});
diff --git a/packages/jobs/src/inngest/functions/integrations/reconcile.ts b/packages/jobs/src/inngest/functions/integrations/reconcile.ts
index 7312d90fcf..504098f7d7 100644
--- a/packages/jobs/src/inngest/functions/integrations/reconcile.ts
+++ b/packages/jobs/src/inngest/functions/integrations/reconcile.ts
@@ -76,6 +76,8 @@ export type ReconcileEntityInput = {
} | null;
/** externalIntegrationMapping state for the entity (push identity). */
hasMappingWithExternalId: boolean;
+ /** A native push mapping remains remotely active (including payment fan-out). */
+ hasUnvoidedPushMapping?: boolean;
lastSyncedAt: string | null;
/** A Pending/In Flight push op exists for the tuple. */
hasLiveOperation: boolean;
@@ -108,6 +110,8 @@ export type ReconcileContext = {
entityPushEnabled: boolean;
/** Rillet true — the only provider with outbound payment push. */
providerSupportsPaymentPush: boolean;
+ /** Rillet supports native invoice, bill, and Carbon-origin payment deletion. */
+ providerSupportsNativeVoid?: boolean;
/** Inputs the journal policy core needs (planJournalPostingFromState). */
settings: PostingSyncSettings;
docSync: { invoiceEnabled: boolean; billEnabled: boolean };
@@ -239,6 +243,37 @@ function reconcileJournal(input: ReconcileEntityInput): ReconcileDecision {
* data-and-save retries without waiting for a human or the re-drive).
* 4. Otherwise nothing — parked dispositions belong to humans/policy.
*/
+function reconcileNativeVoid(input: ReconcileEntityInput): ReconcileDecision {
+ if (
+ !input.context.providerSupportsNativeVoid ||
+ !input.hasUnvoidedPushMapping
+ ) {
+ return nothing("no active native push mapping to void");
+ }
+ if (input.hasLiveOperation)
+ return nothing("a live operation covers the void");
+ const latest = input.latestOperation;
+ if (latest?.status === "Failed" || latest?.status === "Warning") {
+ // A document can reach the provider before its payment void drains. Retry
+ // that transient ordering failure through the bounded ledger lifecycle.
+ return latest.attemptCount < MAX_REDRIVE_ATTEMPTS
+ ? { actions: [{ kind: "re-drive", operationId: latest.id }] }
+ : nothing("native void exhausted automatic retries");
+ }
+ return {
+ actions: [
+ {
+ kind: "enqueue",
+ request: {
+ entityType: input.entityType,
+ entityId: input.entityId,
+ direction: "push-to-accounting"
+ }
+ }
+ ]
+ };
+}
+
function reconcileDocument(input: ReconcileEntityInput): ReconcileDecision {
const snapshot = input.snapshot;
if (!snapshot) return nothing("entity not found");
@@ -247,6 +282,8 @@ function reconcileDocument(input: ReconcileEntityInput): ReconcileDecision {
return nothing(`${input.entityType} push is disabled in the sync config`);
}
+ if (snapshot.status === "Voided") return reconcileNativeVoid(input);
+
const postedStatuses: readonly string[] =
input.entityType === "bill" ? SWEPT_BILL_STATUSES : SWEPT_INVOICE_STATUSES;
if (!snapshot.status || !postedStatuses.includes(snapshot.status)) {
@@ -318,12 +355,9 @@ function reconcileDocument(input: ReconcileEntityInput): ReconcileDecision {
}
/**
- * Payments (Phase G — Rillet only). Strictest rule: only a Posted/Voided
- * payment with NO push operation at all enqueues (payment mapping ids are
- * composite, so a mapping-based phantom check does not apply; ineligible
- * payments park as Skipped on first drain and leave the set). A Voided
- * payment that already has operations records nothing — v1 has no void
- * echo (the syncer parks voids as Skipped by design).
+ * Payments (Rillet only). Posted payments enqueue once. Voided payments with
+ * active Carbon-originated mappings enqueue again, independently of the prior
+ * posting operation, until native deletion is durably recorded.
*/
function reconcilePayment(input: ReconcileEntityInput): ReconcileDecision {
const snapshot = input.snapshot;
@@ -332,6 +366,12 @@ function reconcilePayment(input: ReconcileEntityInput): ReconcileDecision {
if (!input.context.providerSupportsPaymentPush) {
return nothing("provider has no outbound payment push");
}
+ if (
+ snapshot.status === "Voided" &&
+ input.context.providerSupportsNativeVoid
+ ) {
+ return reconcileNativeVoid(input);
+ }
const posted: readonly string[] = SWEPT_PAYMENT_STATUSES;
if (!snapshot.status || !posted.includes(snapshot.status)) {
return nothing(
diff --git a/packages/locale/locales/de/erp.po b/packages/locale/locales/de/erp.po
index 0492f68f99..197d53190f 100644
--- a/packages/locale/locales/de/erp.po
+++ b/packages/locale/locales/de/erp.po
@@ -1850,12 +1850,18 @@ msgstr "Angewendet"
msgid "Applied amount for {0}"
msgstr "Angewendeter Betrag für {0}"
+msgid "Applied amounts are in company base currency ({baseCurrency})."
+msgstr "Angewendete Beträge sind in der Basiswährung des Unternehmens ({baseCurrency})."
+
msgid "Applied Date"
msgstr "Anwendungsdatum"
msgid "Applied To"
msgstr "Angewendet auf"
+msgid "Applied, discount and write-off amounts are in company base currency ({baseCurrency})."
+msgstr "Angewandte Beträge sowie Rabatt- und Ausbuchungsbeträge werden in der Basiswährung des Unternehmens ({baseCurrency}) angegeben."
+
msgid "Applies to"
msgstr "Gilt für"
@@ -2380,6 +2386,12 @@ msgstr "Sind Sie sicher, dass Sie eine Einladung an diese Benutzer senden möcht
msgid "Are you sure you want to send an invite to this user?"
msgstr "Sind Sie sicher, dass Sie eine Einladung an diesen Benutzer senden möchten?"
+msgid "Are you sure you want to void this memo? This will reverse its accounting entries and applications. This cannot be undone."
+msgstr "Sind Sie sicher, dass Sie diese Notiz stornieren möchten? Dies wird ihre Buchhaltungseinträge und Zuordnungen stornieren. Dies kann nicht rückgängig gemacht werden."
+
+msgid "Are you sure you want to void this payment? This will reverse its accounting entries and applications. This cannot be undone."
+msgstr "Sind Sie sicher, dass Sie diese Zahlung stornieren möchten? Dies wird ihre Buchhaltungseinträge und Zuordnungen stornieren. Dies kann nicht rückgängig gemacht werden."
+
msgid "Are you sure you want to void this purchase invoice? This action will reverse all financial transactions and cannot be undone."
msgstr "Sind Sie sicher, dass Sie diese Eingangsrechnung stornieren möchten? Diese Aktion kehrt alle Finanztransaktionen um und kann nicht rückgängig gemacht werden."
@@ -3440,9 +3452,6 @@ msgstr "Suchanfrage löschen"
msgid "Clear selection"
msgstr "Auswahl löschen"
-msgid "Clear this invoice with the party's posted credits as well as cash. Credits apply directly — no posting needed."
-msgstr "Begleichen Sie diese Rechnung mit den gebuchten Gutschriften des Geschäftspartners sowie Kasse. Gutschriften werden direkt angewendet – keine Buchung erforderlich."
-
msgid "Clear value"
msgstr "Wert löschen"
@@ -4600,6 +4609,9 @@ msgstr "Habenkonto bei der Absorption von Gemeinkosten in WIP"
msgid "Credit accounts used when manufacturing costs are absorbed into WIP"
msgstr "Habenkonten bei der Absorption von Fertigungskosten in WIP"
+msgid "Credit amounts are in company base currency ({currency}). Credits take effect when this payment posts."
+msgstr "Guthabenbeträge werden in der Basiswährung des Unternehmens ({currency}) angegeben. Die Verrechnung der Guthaben wird wirksam, sobald diese Zahlung gebucht wird."
+
msgid "Credit Memo"
msgstr "Gutschrift"
@@ -8564,6 +8576,9 @@ msgstr "Inv"
msgid "Inv Rate"
msgstr "Rechnungskurs"
+msgid "Invalid applications"
+msgstr "Ungültige Verrechnungen"
+
msgid "Invalid Invite"
msgstr "Ungültige Einladung"
@@ -10854,6 +10869,9 @@ msgstr "Niemand zum Zuweisen"
msgid "No open invoices"
msgstr "Keine offenen Rechnungen"
+msgid "No open memos"
+msgstr "Keine offenen Notizen"
+
msgid "No open orders for this item are available to link."
msgstr "Für diesen Artikel sind keine offenen Bestellungen zum Verknüpfen verfügbar."
@@ -11965,6 +11983,9 @@ msgstr "Zahlungsanwendungen"
msgid "Payment Date"
msgstr "Zahlungsdatum"
+msgid "Payment from Customer"
+msgstr "Zahlung vom Kunden"
+
msgid "Payment ID"
msgstr "Zahlungs-ID"
@@ -11986,11 +12007,14 @@ msgstr "Zahlungsbedingungen"
msgid "Payment terms like Net 30 or due on receipt"
msgstr "Zahlungsbedingungen wie Net 30 oder zahlbar bei Erhalt"
+msgid "Payment to Supplier"
+msgstr "Zahlung an den Lieferanten"
+
msgid "Payments"
msgstr "Zahlungen"
-msgid "Payments and credits applied to this invoice. Click a row to open the source document."
-msgstr "Zahlungen und Gutschriften, die auf diese Rechnung angerechnet wurden. Klicken Sie auf eine Zeile, um den Ursprungsbeleg zu öffnen."
+msgid "Payments and credits applied to this invoice. Applied amounts and FX are in company base currency. Click a row to open the source document."
+msgstr "Mit dieser Rechnung verrechnete Zahlungen und Guthaben. Verrechnete Beträge und Kursdifferenzen werden in der Basiswährung des Unternehmens angegeben. Klicken Sie auf eine Zeile, um den Ursprungsbeleg zu öffnen."
msgid "PDF"
msgstr "PDF"
@@ -13280,8 +13304,8 @@ msgstr "Aufnahme"
msgid "Record a credit or debit memo against a customer or supplier. Applications to specific invoices are added after the memo is created."
msgstr "Erfassen Sie eine Gutschrift oder Lastschrift gegen einen Kunden oder Lieferanten. Anwendungen auf spezifische Rechnungen werden nach der Erstellung des Dokuments hinzugefügt."
-msgid "Record cash received from a customer (Receipt) or paid to a supplier (Disbursement). Applications to specific invoices are added after the payment is created."
-msgstr "Erfassen Sie erhaltene Kasse von einem Kunden oder an einen Lieferanten gezahlte Kasse (Auszahlung). Anwendungen auf spezifische Rechnungen werden nach der Erstellung der Zahlung hinzugefügt."
+msgid "Record a customer payment, supplier payment, or refund. Applications to invoices or memos are added after the payment is created."
+msgstr "Erfassen Sie eine Kundenzahlung, Lieferantenzahlung oder Gutschrift. Anwendungen auf Rechnungen oder Notizen werden hinzugefügt, nachdem die Zahlung erstellt wurde."
msgid "Record deleted"
msgstr "Datensatz gelöscht"
@@ -13325,6 +13349,15 @@ msgstr "Aktualisieren"
msgid "Refresh exchange rate"
msgstr "Wechselkurs aktualisieren"
+msgid "Refund from Supplier"
+msgstr "Gutschrift vom Lieferanten"
+
+msgid "Refund memos"
+msgstr "Gutschriftsnotizen"
+
+msgid "Refund to Customer"
+msgstr "Gutschrift an den Kunden"
+
msgid "Regenerate"
msgstr "Neu generieren"
@@ -13829,9 +13862,15 @@ msgstr "Rev {revision}"
msgid "Revenue"
msgstr "Umsatzerlöse"
+msgid "Revenue account for shipping charged to customers"
+msgstr "Umsatzerlöskonto für Versandkosten, die Kunden in Rechnung gestellt werden"
+
msgid "Revenue and expenses over a period"
msgstr "Umsatzerlöse und Aufwand über einen Zeitraum"
+msgid "Revenue GL account credited for shipping charged to customers, posted on its own line; it must be a different account from the Sales default."
+msgstr "Sachkonto für Umsatzerlöse, das für die den Kunden berechneten Versandkosten gutgeschrieben und auf einer eigenen Position gebucht wird; es muss sich vom Standardkonto „Vertrieb“ unterscheiden."
+
msgid "Reverse all inventory adjustments"
msgstr "Alle Bestandskorrektionen rückgängig machen"
@@ -14719,9 +14758,6 @@ msgstr "Oberflächen auswählen"
msgid "Select the groups that should complete this training"
msgstr "Wählen Sie die Gruppen aus, die diese Schulung absolvieren sollen"
-msgid "Select the invoices this payment settles. Discount and write-off are in invoice currency."
-msgstr "Wählen Sie die Rechnungen aus, die diese Zahlung begleicht. Rabatt und Ausbuchung sind in Rechnungswährung."
-
msgid "Select value"
msgstr "Wert auswählen"
@@ -15095,6 +15131,12 @@ msgstr "Versandmethoden"
msgid "Shipping Notes"
msgstr "Versandnotizen"
+msgid "Shipping Revenue"
+msgstr "Umsatzerlöse aus Versand"
+
+msgid "Shipping Revenue (default)"
+msgstr "Umsatzerlöse aus Versand (Standard)"
+
msgid "Shipping Supplier"
msgstr "Versandlieferant"
@@ -16126,6 +16168,9 @@ msgstr "Steuerprozentsatz"
msgid "Tax Residual Value %"
msgstr "Steuerlicher Restwert %"
+msgid "Tax Status"
+msgstr "Steuerstatus"
+
msgid "Tax Useful Life (default)"
msgstr "Steuerliche Nutzungsdauer (Standard)"
@@ -18481,6 +18526,11 @@ msgstr "Sichtbar im öffentlichen Profil eines Benutzers"
msgid "Void"
msgstr "Stornieren"
+#. placeholder {0}: initialValues.memoId
+#. placeholder {0}: initialValues.paymentId
+msgid "Void {0}"
+msgstr "Stornieren {0}"
+
msgid "Void Invoice"
msgstr "Rechnung stornieren"
diff --git a/packages/locale/locales/en/erp.po b/packages/locale/locales/en/erp.po
index 7c848d6ca2..4bfc22a084 100644
--- a/packages/locale/locales/en/erp.po
+++ b/packages/locale/locales/en/erp.po
@@ -1850,12 +1850,18 @@ msgstr "Applied"
msgid "Applied amount for {0}"
msgstr "Applied amount for {0}"
+msgid "Applied amounts are in company base currency ({baseCurrency})."
+msgstr "Applied amounts are in company base currency ({baseCurrency})."
+
msgid "Applied Date"
msgstr "Applied Date"
msgid "Applied To"
msgstr "Applied To"
+msgid "Applied, discount and write-off amounts are in company base currency ({baseCurrency})."
+msgstr "Applied, discount and write-off amounts are in company base currency ({baseCurrency})."
+
msgid "Applies to"
msgstr "Applies to"
@@ -2380,6 +2386,12 @@ msgstr "Are you sure you want to send an invite to these users?"
msgid "Are you sure you want to send an invite to this user?"
msgstr "Are you sure you want to send an invite to this user?"
+msgid "Are you sure you want to void this memo? This will reverse its accounting entries and applications. This cannot be undone."
+msgstr "Are you sure you want to void this memo? This will reverse its accounting entries and applications. This cannot be undone."
+
+msgid "Are you sure you want to void this payment? This will reverse its accounting entries and applications. This cannot be undone."
+msgstr "Are you sure you want to void this payment? This will reverse its accounting entries and applications. This cannot be undone."
+
msgid "Are you sure you want to void this purchase invoice? This action will reverse all financial transactions and cannot be undone."
msgstr "Are you sure you want to void this purchase invoice? This action will reverse all financial transactions and cannot be undone."
@@ -3440,9 +3452,6 @@ msgstr "Clear search query"
msgid "Clear selection"
msgstr "Clear selection"
-msgid "Clear this invoice with the party's posted credits as well as cash. Credits apply directly — no posting needed."
-msgstr "Clear this invoice with the party's posted credits as well as cash. Credits apply directly — no posting needed."
-
msgid "Clear value"
msgstr "Clear value"
@@ -4600,6 +4609,9 @@ msgstr "Credit account when overhead is absorbed into WIP"
msgid "Credit accounts used when manufacturing costs are absorbed into WIP"
msgstr "Credit accounts used when manufacturing costs are absorbed into WIP"
+msgid "Credit amounts are in company base currency ({currency}). Credits take effect when this payment posts."
+msgstr "Credit amounts are in company base currency ({currency}). Credits take effect when this payment posts."
+
msgid "Credit Memo"
msgstr "Credit Memo"
@@ -8564,6 +8576,9 @@ msgstr "inv"
msgid "Inv Rate"
msgstr "Inv Rate"
+msgid "Invalid applications"
+msgstr "Invalid applications"
+
msgid "Invalid Invite"
msgstr "Invalid Invite"
@@ -10854,6 +10869,9 @@ msgstr "No one to assign"
msgid "No open invoices"
msgstr "No open invoices"
+msgid "No open memos"
+msgstr "No open memos"
+
msgid "No open orders for this item are available to link."
msgstr "No open orders for this item are available to link."
@@ -11965,6 +11983,9 @@ msgstr "Payment Applications"
msgid "Payment Date"
msgstr "Payment Date"
+msgid "Payment from Customer"
+msgstr "Payment from Customer"
+
msgid "Payment ID"
msgstr "Payment ID"
@@ -11986,11 +12007,14 @@ msgstr "Payment Terms"
msgid "Payment terms like Net 30 or due on receipt"
msgstr "Payment terms like Net 30 or due on receipt"
+msgid "Payment to Supplier"
+msgstr "Payment to Supplier"
+
msgid "Payments"
msgstr "Payments"
-msgid "Payments and credits applied to this invoice. Click a row to open the source document."
-msgstr "Payments and credits applied to this invoice. Click a row to open the source document."
+msgid "Payments and credits applied to this invoice. Applied amounts and FX are in company base currency. Click a row to open the source document."
+msgstr "Payments and credits applied to this invoice. Applied amounts and FX are in company base currency. Click a row to open the source document."
msgid "PDF"
msgstr "PDF"
@@ -13280,8 +13304,8 @@ msgstr "Record"
msgid "Record a credit or debit memo against a customer or supplier. Applications to specific invoices are added after the memo is created."
msgstr "Record a credit or debit memo against a customer or supplier. Applications to specific invoices are added after the memo is created."
-msgid "Record cash received from a customer (Receipt) or paid to a supplier (Disbursement). Applications to specific invoices are added after the payment is created."
-msgstr "Record cash received from a customer (Receipt) or paid to a supplier (Disbursement). Applications to specific invoices are added after the payment is created."
+msgid "Record a customer payment, supplier payment, or refund. Applications to invoices or memos are added after the payment is created."
+msgstr "Record a customer payment, supplier payment, or refund. Applications to invoices or memos are added after the payment is created."
msgid "Record deleted"
msgstr "Record deleted"
@@ -13325,6 +13349,15 @@ msgstr "Refresh"
msgid "Refresh exchange rate"
msgstr "Refresh exchange rate"
+msgid "Refund from Supplier"
+msgstr "Refund from Supplier"
+
+msgid "Refund memos"
+msgstr "Refund memos"
+
+msgid "Refund to Customer"
+msgstr "Refund to Customer"
+
msgid "Regenerate"
msgstr "Regenerate"
@@ -13829,9 +13862,15 @@ msgstr "Rev {revision}"
msgid "Revenue"
msgstr "Revenue"
+msgid "Revenue account for shipping charged to customers"
+msgstr "Revenue account for shipping charged to customers"
+
msgid "Revenue and expenses over a period"
msgstr "Revenue and expenses over a period"
+msgid "Revenue GL account credited for shipping charged to customers, posted on its own line; it must be a different account from the Sales default."
+msgstr "Revenue GL account credited for shipping charged to customers, posted on its own line; it must be a different account from the Sales default."
+
msgid "Reverse all inventory adjustments"
msgstr "Reverse all inventory adjustments"
@@ -14719,9 +14758,6 @@ msgstr "Select surfaces"
msgid "Select the groups that should complete this training"
msgstr "Select the groups that should complete this training"
-msgid "Select the invoices this payment settles. Discount and write-off are in invoice currency."
-msgstr "Select the invoices this payment settles. Discount and write-off are in invoice currency."
-
msgid "Select value"
msgstr "Select value"
@@ -15095,6 +15131,12 @@ msgstr "Shipping Methods"
msgid "Shipping Notes"
msgstr "Shipping Notes"
+msgid "Shipping Revenue"
+msgstr "Shipping Revenue"
+
+msgid "Shipping Revenue (default)"
+msgstr "Shipping Revenue (default)"
+
msgid "Shipping Supplier"
msgstr "Shipping Supplier"
@@ -16126,6 +16168,9 @@ msgstr "Tax Percent"
msgid "Tax Residual Value %"
msgstr "Tax Residual Value %"
+msgid "Tax Status"
+msgstr "Tax Status"
+
msgid "Tax Useful Life (default)"
msgstr "Tax Useful Life (default)"
@@ -18481,6 +18526,11 @@ msgstr "Visible on a user's public profile"
msgid "Void"
msgstr "Void"
+#. placeholder {0}: initialValues.memoId
+#. placeholder {0}: initialValues.paymentId
+msgid "Void {0}"
+msgstr "Void {0}"
+
msgid "Void Invoice"
msgstr "Void Invoice"
diff --git a/packages/locale/locales/es/erp.po b/packages/locale/locales/es/erp.po
index 82e132511c..f6deab83e0 100644
--- a/packages/locale/locales/es/erp.po
+++ b/packages/locale/locales/es/erp.po
@@ -1850,12 +1850,18 @@ msgstr "Aplicado"
msgid "Applied amount for {0}"
msgstr "Importe aplicado para {0}"
+msgid "Applied amounts are in company base currency ({baseCurrency})."
+msgstr "Los montos aplicados están en la moneda base de la empresa ({baseCurrency})."
+
msgid "Applied Date"
msgstr "Fecha de Aplicación"
msgid "Applied To"
msgstr "Aplicado a"
+msgid "Applied, discount and write-off amounts are in company base currency ({baseCurrency})."
+msgstr "Los importes aplicados, los descuentos y las cancelaciones contables están expresados en la moneda base de la empresa ({baseCurrency})."
+
msgid "Applies to"
msgstr "Se aplica a"
@@ -2380,6 +2386,12 @@ msgstr "¿Estás seguro de que deseas enviar una invitación a estos usuarios?"
msgid "Are you sure you want to send an invite to this user?"
msgstr "¿Estás seguro de que deseas enviar una invitación a este usuario?"
+msgid "Are you sure you want to void this memo? This will reverse its accounting entries and applications. This cannot be undone."
+msgstr "¿Está seguro de que desea anular este memorándum? Esto invertirá sus asientos contables y aplicaciones. No se puede deshacer."
+
+msgid "Are you sure you want to void this payment? This will reverse its accounting entries and applications. This cannot be undone."
+msgstr "¿Está seguro de que desea anular este pago? Esto invertirá sus asientos contables y aplicaciones. No se puede deshacer."
+
msgid "Are you sure you want to void this purchase invoice? This action will reverse all financial transactions and cannot be undone."
msgstr "¿Está seguro de que desea anular esta factura de compra? Esta acción revertirá todas las transacciones financieras y no se puede deshacer."
@@ -3440,9 +3452,6 @@ msgstr "Limpiar consulta de búsqueda"
msgid "Clear selection"
msgstr "Limpiar selección"
-msgid "Clear this invoice with the party's posted credits as well as cash. Credits apply directly — no posting needed."
-msgstr "Liquide esta factura con los créditos contabilizados de la parte así como efectivo. Los créditos se aplican directamente — no se requiere contabilización."
-
msgid "Clear value"
msgstr "Limpiar valor"
@@ -4600,6 +4609,9 @@ msgstr "Cuenta de haber cuando los costos indirectos se absorben en producto en
msgid "Credit accounts used when manufacturing costs are absorbed into WIP"
msgstr "Cuentas de haber utilizadas cuando los costos de manufactura se absorben en producto en proceso"
+msgid "Credit amounts are in company base currency ({currency}). Credits take effect when this payment posts."
+msgstr "Los importes de crédito están expresados en la moneda base de la empresa ({currency}). Los créditos tienen efecto cuando se contabiliza este pago."
+
msgid "Credit Memo"
msgstr "Nota de Crédito"
@@ -8564,6 +8576,9 @@ msgstr "inv"
msgid "Inv Rate"
msgstr "Tasa Inv"
+msgid "Invalid applications"
+msgstr "Aplicaciones no válidas"
+
msgid "Invalid Invite"
msgstr "Invitación Inválida"
@@ -10854,6 +10869,9 @@ msgstr "Nadie para asignar"
msgid "No open invoices"
msgstr "Sin facturas abiertas"
+msgid "No open memos"
+msgstr "Sin memorandos abiertos"
+
msgid "No open orders for this item are available to link."
msgstr "No hay pedidos abiertos disponibles para este artículo."
@@ -11965,6 +11983,9 @@ msgstr "Aplicaciones de Pago"
msgid "Payment Date"
msgstr "Fecha de Pago"
+msgid "Payment from Customer"
+msgstr "Pago del Cliente"
+
msgid "Payment ID"
msgstr "ID de Pago"
@@ -11986,11 +12007,14 @@ msgstr "Condiciones de pago"
msgid "Payment terms like Net 30 or due on receipt"
msgstr "Condiciones de pago como Neto 30 o pagadero a la recepción"
+msgid "Payment to Supplier"
+msgstr "Pago al Proveedor"
+
msgid "Payments"
msgstr "Pagos"
-msgid "Payments and credits applied to this invoice. Click a row to open the source document."
-msgstr "Pagos y créditos aplicados a esta factura. Haz clic en una fila para abrir el documento de origen."
+msgid "Payments and credits applied to this invoice. Applied amounts and FX are in company base currency. Click a row to open the source document."
+msgstr "Pagos y créditos aplicados a esta factura. Los importes aplicados y las diferencias de cambio están expresados en la moneda base de la empresa. Haga clic en una fila para abrir el documento de origen."
msgid "PDF"
msgstr "PDF"
@@ -13280,8 +13304,8 @@ msgstr "Registro"
msgid "Record a credit or debit memo against a customer or supplier. Applications to specific invoices are added after the memo is created."
msgstr "Registrar una nota de crédito o débito contra un cliente o proveedor. Las aplicaciones a facturas específicas se agregan después de que se crea la nota."
-msgid "Record cash received from a customer (Receipt) or paid to a supplier (Disbursement). Applications to specific invoices are added after the payment is created."
-msgstr "Registre el efectivo recibido de un cliente (Recepción) o pagado a un proveedor (Desembolso). Las aplicaciones a facturas específicas se agregan después de que se crea el pago."
+msgid "Record a customer payment, supplier payment, or refund. Applications to invoices or memos are added after the payment is created."
+msgstr "Registre un pago del cliente, un pago al proveedor, o un reembolso. Las aplicaciones a facturas o memorandos se agregan después de que se crea el pago."
msgid "Record deleted"
msgstr "Registro eliminado"
@@ -13325,6 +13349,15 @@ msgstr "Actualizar"
msgid "Refresh exchange rate"
msgstr "Actualizar tipo de cambio"
+msgid "Refund from Supplier"
+msgstr "Reembolso del Proveedor"
+
+msgid "Refund memos"
+msgstr "Memorandos de Reembolso"
+
+msgid "Refund to Customer"
+msgstr "Reembolso al Cliente"
+
msgid "Regenerate"
msgstr "Regenerar"
@@ -13829,9 +13862,15 @@ msgstr "Rev {revision}"
msgid "Revenue"
msgstr "Ingresos por ventas"
+msgid "Revenue account for shipping charged to customers"
+msgstr "Cuenta de ingresos por gastos de envío cobrados a los clientes"
+
msgid "Revenue and expenses over a period"
msgstr "Ingresos por ventas y gastos durante un período"
+msgid "Revenue GL account credited for shipping charged to customers, posted on its own line; it must be a different account from the Sales default."
+msgstr "Cuenta contable de Ingresos por Envío acreditada por gastos de envío cobrados a clientes, contabilizada en su propia línea; debe ser una cuenta diferente de la predeterminada de Ventas."
+
msgid "Reverse all inventory adjustments"
msgstr "Revertir todos los ajustes de inventario"
@@ -14719,9 +14758,6 @@ msgstr "Seleccionar superficies"
msgid "Select the groups that should complete this training"
msgstr "Selecciona los grupos que deben completar esta capacitación"
-msgid "Select the invoices this payment settles. Discount and write-off are in invoice currency."
-msgstr "Seleccione las facturas que este pago liquida. El descuento y la cancelación contable están en la moneda de la factura."
-
msgid "Select value"
msgstr "Seleccionar valor"
@@ -15095,6 +15131,12 @@ msgstr "Métodos de Envío"
msgid "Shipping Notes"
msgstr "Notas de Envío"
+msgid "Shipping Revenue"
+msgstr "Ingresos por gastos de envío"
+
+msgid "Shipping Revenue (default)"
+msgstr "Ingresos por gastos de envío (predeterminado)"
+
msgid "Shipping Supplier"
msgstr "Proveedor de Envío"
@@ -16126,6 +16168,9 @@ msgstr "Porcentaje de Impuesto"
msgid "Tax Residual Value %"
msgstr "Valor residual fiscal %"
+msgid "Tax Status"
+msgstr "Estado fiscal"
+
msgid "Tax Useful Life (default)"
msgstr "Vida útil fiscal (predeterminada)"
@@ -18481,6 +18526,11 @@ msgstr "Visible en el perfil público de un usuario"
msgid "Void"
msgstr "Anular"
+#. placeholder {0}: initialValues.memoId
+#. placeholder {0}: initialValues.paymentId
+msgid "Void {0}"
+msgstr "Anular {0}"
+
msgid "Void Invoice"
msgstr "Anular Factura"
diff --git a/packages/locale/locales/fr/erp.po b/packages/locale/locales/fr/erp.po
index 8bb925e722..1968793811 100644
--- a/packages/locale/locales/fr/erp.po
+++ b/packages/locale/locales/fr/erp.po
@@ -1850,12 +1850,18 @@ msgstr "Appliqué"
msgid "Applied amount for {0}"
msgstr "Montant appliqué pour {0}"
+msgid "Applied amounts are in company base currency ({baseCurrency})."
+msgstr "Les montants appliqués sont dans la devise de base de la société ({baseCurrency})."
+
msgid "Applied Date"
msgstr "Date d'application"
msgid "Applied To"
msgstr "Appliqué à"
+msgid "Applied, discount and write-off amounts are in company base currency ({baseCurrency})."
+msgstr "Les montants appliqués, les remises et les passages en perte sont exprimés dans la devise de base de la société ({baseCurrency})."
+
msgid "Applies to"
msgstr "S'applique à"
@@ -2380,6 +2386,12 @@ msgstr "Êtes-vous sûr de vouloir envoyer une invitation à ces utilisateurs ?"
msgid "Are you sure you want to send an invite to this user?"
msgstr "Êtes-vous sûr de vouloir envoyer une invitation à cet utilisateur ?"
+msgid "Are you sure you want to void this memo? This will reverse its accounting entries and applications. This cannot be undone."
+msgstr "Êtes-vous sûr de vouloir invalider ce mémo ? Cela inversera ses écritures comptables et applications. Ceci ne peut pas être annulé."
+
+msgid "Are you sure you want to void this payment? This will reverse its accounting entries and applications. This cannot be undone."
+msgstr "Êtes-vous sûr de vouloir invalider ce paiement ? Cela inversera ses écritures comptables et applications. Ceci ne peut pas être annulé."
+
msgid "Are you sure you want to void this purchase invoice? This action will reverse all financial transactions and cannot be undone."
msgstr "Êtes-vous sûr de vouloir invalider cette facture d'achat ? Cette action annulera toutes les transactions financières et ne peut pas être annulée."
@@ -3440,9 +3452,6 @@ msgstr "Effacer la requête de recherche"
msgid "Clear selection"
msgstr "Effacer la sélection"
-msgid "Clear this invoice with the party's posted credits as well as cash. Credits apply directly — no posting needed."
-msgstr "Réglez cette facture avec les crédits comptabilisés de la partie ainsi que du numéraire. Les crédits s'appliquent directement — aucune comptabilisation nécessaire."
-
msgid "Clear value"
msgstr "Effacer la valeur"
@@ -4600,6 +4609,9 @@ msgstr "Compte crédit en cas d'absorption des frais généraux dans l'en-cours"
msgid "Credit accounts used when manufacturing costs are absorbed into WIP"
msgstr "Comptes crédit utilisés lors de l'absorption des coûts de production dans l'en-cours"
+msgid "Credit amounts are in company base currency ({currency}). Credits take effect when this payment posts."
+msgstr "Les montants au crédit sont exprimés dans la devise de base de la société ({currency}). Les crédits prennent effet lorsque ce paiement est comptabilisé."
+
msgid "Credit Memo"
msgstr "Avoir"
@@ -8564,6 +8576,9 @@ msgstr "inv"
msgid "Inv Rate"
msgstr "Taux Fact"
+msgid "Invalid applications"
+msgstr "Applications invalides"
+
msgid "Invalid Invite"
msgstr "Invitation invalide"
@@ -10854,6 +10869,9 @@ msgstr "Personne à assigner"
msgid "No open invoices"
msgstr "Aucune facture ouverte"
+msgid "No open memos"
+msgstr "Aucun mémo ouvert"
+
msgid "No open orders for this item are available to link."
msgstr "Aucune commande ouverte pour cet article n'est disponible pour la liaison."
@@ -11965,6 +11983,9 @@ msgstr "Applications de paiement"
msgid "Payment Date"
msgstr "Date de paiement"
+msgid "Payment from Customer"
+msgstr "Paiement du client"
+
msgid "Payment ID"
msgstr "ID de paiement"
@@ -11986,11 +12007,14 @@ msgstr "Conditions de paiement"
msgid "Payment terms like Net 30 or due on receipt"
msgstr "Conditions de paiement comme Net 30 ou à la réception"
+msgid "Payment to Supplier"
+msgstr "Paiement au fournisseur"
+
msgid "Payments"
msgstr "Paiements"
-msgid "Payments and credits applied to this invoice. Click a row to open the source document."
-msgstr "Paiements et crédits appliqués à cette facture. Cliquez sur une ligne pour ouvrir le document d'origine."
+msgid "Payments and credits applied to this invoice. Applied amounts and FX are in company base currency. Click a row to open the source document."
+msgstr "Paiements et crédits appliqués à cette facture. Les montants appliqués et les effets de change sont exprimés dans la devise de base de la société. Cliquez sur une ligne pour ouvrir le document d'origine."
msgid "PDF"
msgstr "PDF"
@@ -13280,8 +13304,8 @@ msgstr "Enregistrer"
msgid "Record a credit or debit memo against a customer or supplier. Applications to specific invoices are added after the memo is created."
msgstr "Enregistrez un avoir ou un débit contre un client ou un fournisseur. Les applications à des factures spécifiques sont ajoutées après la création de l'avoir."
-msgid "Record cash received from a customer (Receipt) or paid to a supplier (Disbursement). Applications to specific invoices are added after the payment is created."
-msgstr "Enregistrer la trésorerie reçue d'un client (Réception) ou versée à un fournisseur (Décaissement). Les allocations aux factures spécifiques sont ajoutées après la création du paiement."
+msgid "Record a customer payment, supplier payment, or refund. Applications to invoices or memos are added after the payment is created."
+msgstr "Enregistrer un paiement client, un paiement fournisseur ou un remboursement. Les applications aux factures ou aux mémos sont ajoutées après la création du paiement."
msgid "Record deleted"
msgstr "Enregistrement supprimé"
@@ -13325,6 +13349,15 @@ msgstr "Actualiser"
msgid "Refresh exchange rate"
msgstr "Actualiser le taux de change"
+msgid "Refund from Supplier"
+msgstr "Remboursement du fournisseur"
+
+msgid "Refund memos"
+msgstr "Mémos de remboursement"
+
+msgid "Refund to Customer"
+msgstr "Remboursement au client"
+
msgid "Regenerate"
msgstr "Régénérer"
@@ -13829,9 +13862,15 @@ msgstr "Rév {revision}"
msgid "Revenue"
msgstr "Revenu"
+msgid "Revenue account for shipping charged to customers"
+msgstr "Compte de revenus pour les frais d’expédition facturés aux clients"
+
msgid "Revenue and expenses over a period"
msgstr "Revenus et charges sur une période"
+msgid "Revenue GL account credited for shipping charged to customers, posted on its own line; it must be a different account from the Sales default."
+msgstr "Compte général de revenus crédité pour l'expédition facturée aux clients, comptabilisé sur sa propre ligne ; il doit être un compte différent du compte par défaut de Ventes."
+
msgid "Reverse all inventory adjustments"
msgstr "Extourner tous les ajustements de stock"
@@ -14719,9 +14758,6 @@ msgstr "Sélectionner les surfaces"
msgid "Select the groups that should complete this training"
msgstr "Sélectionnez les groupes qui doivent suivre cette formation"
-msgid "Select the invoices this payment settles. Discount and write-off are in invoice currency."
-msgstr "Sélectionner les factures que ce paiement règle. La remise et le passage en perte sont à la devise de la facture."
-
msgid "Select value"
msgstr "Sélectionner une valeur"
@@ -15095,6 +15131,12 @@ msgstr "Modes d'expédition"
msgid "Shipping Notes"
msgstr "Notes d'expédition"
+msgid "Shipping Revenue"
+msgstr "Revenus d’expédition"
+
+msgid "Shipping Revenue (default)"
+msgstr "Revenus d’expédition (par défaut)"
+
msgid "Shipping Supplier"
msgstr "Fournisseur d'expédition"
@@ -16126,6 +16168,9 @@ msgstr "Pourcentage de taxe"
msgid "Tax Residual Value %"
msgstr "Valeur résiduelle fiscale %"
+msgid "Tax Status"
+msgstr "Statut fiscal"
+
msgid "Tax Useful Life (default)"
msgstr "Durée d'utilité fiscale (par défaut)"
@@ -18481,6 +18526,11 @@ msgstr "Visible sur le profil public d'un utilisateur"
msgid "Void"
msgstr "Invalider"
+#. placeholder {0}: initialValues.memoId
+#. placeholder {0}: initialValues.paymentId
+msgid "Void {0}"
+msgstr "Invalider {0}"
+
msgid "Void Invoice"
msgstr "Invalider la facture"
diff --git a/packages/locale/locales/glossary.json b/packages/locale/locales/glossary.json
index f772835852..39a978a897 100644
--- a/packages/locale/locales/glossary.json
+++ b/packages/locale/locales/glossary.json
@@ -7689,6 +7689,25 @@
"ko": "배송 방법"
}
},
+ {
+ "term": "Shipping Revenue",
+ "category": "accounting",
+ "context": "The revenue account credited for shipping charged to customers, posted on its own line and distinct from the Sales account. Its account-default field renders as \"Shipping Revenue (default)\" beside it on the Account Defaults screen, so both must use the SAME term.",
+ "translations": {
+ "fr": "Revenus d’expédition",
+ "de": "Umsatzerlöse aus Versand",
+ "es": "Ingresos por gastos de envío",
+ "it": "Ricavi da spedizioni",
+ "ja": "配送売上高",
+ "pl": "Przychody z opłat za wysyłkę",
+ "pt": "Receita de envio",
+ "ru": "Выручка от доставки",
+ "zh": "运输收入",
+ "hi": "शिपिंग राजस्व",
+ "tr": "Kargo hasılatı",
+ "ko": "배송 매출"
+ }
+ },
{
"term": "To Ship",
"category": "sales",
diff --git a/packages/locale/locales/hi/erp.po b/packages/locale/locales/hi/erp.po
index 20b134782d..963189f87b 100644
--- a/packages/locale/locales/hi/erp.po
+++ b/packages/locale/locales/hi/erp.po
@@ -1850,12 +1850,18 @@ msgstr "लागू"
msgid "Applied amount for {0}"
msgstr "{0} के लिए लागू राशि"
+msgid "Applied amounts are in company base currency ({baseCurrency})."
+msgstr "लागू की गई राशि कंपनी की आधार मुद्रा ({baseCurrency}) में है।"
+
msgid "Applied Date"
msgstr "लागू तारीख"
msgid "Applied To"
msgstr "लागू किया गया"
+msgid "Applied, discount and write-off amounts are in company base currency ({baseCurrency})."
+msgstr "लागू की गई राशियाँ, छूट और बट्टे खाते की राशियाँ कंपनी की आधार मुद्रा ({baseCurrency}) में हैं।"
+
msgid "Applies to"
msgstr "लागू होता है"
@@ -2380,6 +2386,12 @@ msgstr "क्या आप सुनिश्चित हैं कि आप
msgid "Are you sure you want to send an invite to this user?"
msgstr "क्या आप सुनिश्चित हैं कि आप इस उपयोगकर्ता को आमंत्रण भेजना चाहते हैं?"
+msgid "Are you sure you want to void this memo? This will reverse its accounting entries and applications. This cannot be undone."
+msgstr "क्या आप सुनिश्चित हैं कि आप इस ज्ञापन को अमान्य करना चाहते हैं? यह इसकी लेखांकन प्रविष्टियों और आवेदनों को उलट देगा। इसे पूर्ववत नहीं किया जा सकता।"
+
+msgid "Are you sure you want to void this payment? This will reverse its accounting entries and applications. This cannot be undone."
+msgstr "क्या आप सुनिश्चित हैं कि आप इस भुगतान को अमान्य करना चाहते हैं? यह इसकी लेखांकन प्रविष्टियों और आवेदनों को उलट देगा। इसे पूर्ववत नहीं किया जा सकता।"
+
msgid "Are you sure you want to void this purchase invoice? This action will reverse all financial transactions and cannot be undone."
msgstr "क्या आप इस क्रय चालान को अमान्य करना चाहते हैं? यह क्रिया सभी वित्तीय लेनदेन को उलट देगी और वापस नहीं की जा सकती।"
@@ -3440,9 +3452,6 @@ msgstr "खोज क्वेरी साफ करें"
msgid "Clear selection"
msgstr "चयन साफ करें"
-msgid "Clear this invoice with the party's posted credits as well as cash. Credits apply directly — no posting needed."
-msgstr "इस चालान को पार्टी के पोस्ट किए गए क्रेडिट के साथ-साथ नकद से साफ़ करें। क्रेडिट सीधे लागू होते हैं — कोई पोस्टिंग की आवश्यकता नहीं है।"
-
msgid "Clear value"
msgstr "मान साफ़ करें"
@@ -4600,6 +4609,9 @@ msgstr "जब उपरिव्यय WIP में अवशोषित ह
msgid "Credit accounts used when manufacturing costs are absorbed into WIP"
msgstr "जब विनिर्माण लागत को WIP में अवशोषित किया जाता है तब उपयोग किए जाने वाले क्रेडिट खाते"
+msgid "Credit amounts are in company base currency ({currency}). Credits take effect when this payment posts."
+msgstr "क्रेडिट राशियाँ कंपनी की आधार मुद्रा ({currency}) में हैं। यह भुगतान पोस्ट होने पर क्रेडिट लागू होते हैं।"
+
msgid "Credit Memo"
msgstr "क्रेडिट नोट"
@@ -8564,6 +8576,9 @@ msgstr "इन्व"
msgid "Inv Rate"
msgstr "इनवॉइस दर"
+msgid "Invalid applications"
+msgstr "अमान्य आवंटन"
+
msgid "Invalid Invite"
msgstr "अमान्य निमंत्रण"
@@ -10854,6 +10869,9 @@ msgstr "असाइन करने के लिए कोई नहीं"
msgid "No open invoices"
msgstr "कोई खुले चालान नहीं"
+msgid "No open memos"
+msgstr "कोई खुला ज्ञापन नहीं"
+
msgid "No open orders for this item are available to link."
msgstr "इस आइटम के लिए लिंक करने के लिए कोई खुले ऑर्डर उपलब्ध नहीं हैं।"
@@ -11965,6 +11983,9 @@ msgstr "भुगतान अनुप्रयोग"
msgid "Payment Date"
msgstr "भुगतान तारीख"
+msgid "Payment from Customer"
+msgstr "ग्राहक से भुगतान"
+
msgid "Payment ID"
msgstr "भुगतान ID"
@@ -11986,11 +12007,14 @@ msgstr "भुगतान शर्तें"
msgid "Payment terms like Net 30 or due on receipt"
msgstr "Net 30 जैसी भुगतान शर्तें या प्राप्ति पर देय"
+msgid "Payment to Supplier"
+msgstr "आपूर्तिकर्ता को भुगतान"
+
msgid "Payments"
msgstr "भुगतान"
-msgid "Payments and credits applied to this invoice. Click a row to open the source document."
-msgstr "इस चालान पर लागू किए गए भुगतान और क्रेडिट। स्रोत दस्तावेज़ खोलने के लिए एक पंक्ति पर क्लिक करें।"
+msgid "Payments and credits applied to this invoice. Applied amounts and FX are in company base currency. Click a row to open the source document."
+msgstr "इस चालान के लिए आवंटित भुगतान और क्रेडिट। आवंटित राशियाँ और विनिमय अंतर की राशियाँ कंपनी की आधार मुद्रा में हैं। स्रोत दस्तावेज़ खोलने के लिए किसी पंक्ति पर क्लिक करें।"
msgid "PDF"
msgstr "PDF"
@@ -13280,8 +13304,8 @@ msgstr "रिकॉर्ड करें"
msgid "Record a credit or debit memo against a customer or supplier. Applications to specific invoices are added after the memo is created."
msgstr "एक ग्राहक या आपूर्तिकर्ता के विरुद्ध एक जमा या नामे ज्ञापन दर्ज करें। विशिष्ट चालान के लिए आवेदन ज्ञापन बनाए जाने के बाद जोड़े जाते हैं।"
-msgid "Record cash received from a customer (Receipt) or paid to a supplier (Disbursement). Applications to specific invoices are added after the payment is created."
-msgstr "एक ग्राहक से प्राप्त नकद (प्राप्ति) या एक आपूर्तिकर्ता को भुगतान की गई नकद (संवितरण) को दर्ज करें। विशिष्ट चालान के लिए आवेदन भुगतान बनाए जाने के बाद जोड़े जाते हैं।"
+msgid "Record a customer payment, supplier payment, or refund. Applications to invoices or memos are added after the payment is created."
+msgstr "एक ग्राहक भुगतान, आपूर्तिकर्ता भुगतान, या धनवापसी दर्ज करें। भुगतान बनाने के बाद चालान या ज्ञापन में आवेदन जोड़े जाते हैं।"
msgid "Record deleted"
msgstr "रिकॉर्ड हटाया गया"
@@ -13325,6 +13349,15 @@ msgstr "ताज़ा करें"
msgid "Refresh exchange rate"
msgstr "विनिमय दर को ताज़ा करें"
+msgid "Refund from Supplier"
+msgstr "आपूर्तिकर्ता से धनवापसी"
+
+msgid "Refund memos"
+msgstr "धनवापसी ज्ञापन"
+
+msgid "Refund to Customer"
+msgstr "ग्राहक को धनवापसी"
+
msgid "Regenerate"
msgstr "पुनर्जीवित करें"
@@ -13829,9 +13862,15 @@ msgstr "Rev {revision}"
msgid "Revenue"
msgstr "राजस्व"
+msgid "Revenue account for shipping charged to customers"
+msgstr "ग्राहकों से लिए गए शिपिंग शुल्क का राजस्व खाता"
+
msgid "Revenue and expenses over a period"
msgstr "एक अवधि में राजस्व और व्यय"
+msgid "Revenue GL account credited for shipping charged to customers, posted on its own line; it must be a different account from the Sales default."
+msgstr "ग्राहकों को चार्ज की गई शिपिंग के लिए जमा किया गया राजस्व लेजर खाता, अपनी पंक्ति पर पोस्ट किया गया; यह बिक्री डिफ़ॉल्ट से अलग खाता होना चाहिए।"
+
msgid "Reverse all inventory adjustments"
msgstr "सभी इन्वेंटरी समायोजन को उलट दें"
@@ -14719,9 +14758,6 @@ msgstr "सतहें चुनें"
msgid "Select the groups that should complete this training"
msgstr "उन समूहों का चयन करें जिन्हें इस प्रशिक्षण को पूरा करना चाहिए"
-msgid "Select the invoices this payment settles. Discount and write-off are in invoice currency."
-msgstr "वह चालान चुनें जो यह भुगतान निपटाता है। छूट और बट्टे खाते चालान मुद्रा में हैं।"
-
msgid "Select value"
msgstr "मान चुनें"
@@ -15095,6 +15131,12 @@ msgstr "शिपिंग विधियां"
msgid "Shipping Notes"
msgstr "शिपिंग नोट्स"
+msgid "Shipping Revenue"
+msgstr "शिपिंग राजस्व"
+
+msgid "Shipping Revenue (default)"
+msgstr "शिपिंग राजस्व (डिफ़ॉल्ट)"
+
msgid "Shipping Supplier"
msgstr "शिपिंग आपूर्तिकर्ता"
@@ -16126,6 +16168,9 @@ msgstr "कर प्रतिशत"
msgid "Tax Residual Value %"
msgstr "कर अवशिष्ट मूल्य %"
+msgid "Tax Status"
+msgstr "कर स्थिति"
+
msgid "Tax Useful Life (default)"
msgstr "कर उपयोगी जीवन (डिफ़ॉल्ट)"
@@ -18481,6 +18526,11 @@ msgstr "उपयोगकर्ता की सार्वजनिक प्
msgid "Void"
msgstr "अमान्य करें"
+#. placeholder {0}: initialValues.memoId
+#. placeholder {0}: initialValues.paymentId
+msgid "Void {0}"
+msgstr "अमान्य करें {0}"
+
msgid "Void Invoice"
msgstr "चालान अमान्य करें"
diff --git a/packages/locale/locales/it/erp.po b/packages/locale/locales/it/erp.po
index ca078883e3..d432db8d7e 100644
--- a/packages/locale/locales/it/erp.po
+++ b/packages/locale/locales/it/erp.po
@@ -1850,12 +1850,18 @@ msgstr "Applicato"
msgid "Applied amount for {0}"
msgstr "Importo applicato per {0}"
+msgid "Applied amounts are in company base currency ({baseCurrency})."
+msgstr "Gli importi applicati sono in valuta base aziendale ({baseCurrency})."
+
msgid "Applied Date"
msgstr "Data di applicazione"
msgid "Applied To"
msgstr "Applicato A"
+msgid "Applied, discount and write-off amounts are in company base currency ({baseCurrency})."
+msgstr "Gli importi applicati, gli sconti e gli stralci sono espressi nella valuta di base dell'azienda ({baseCurrency})."
+
msgid "Applies to"
msgstr "Si applica a"
@@ -2380,6 +2386,12 @@ msgstr "Sei sicuro di voler inviare un invito a questi utenti?"
msgid "Are you sure you want to send an invite to this user?"
msgstr "Sei sicuro di voler inviare un invito a questo utente?"
+msgid "Are you sure you want to void this memo? This will reverse its accounting entries and applications. This cannot be undone."
+msgstr "Sei sicuro di voler stornare questa nota? Questo stornerà le registrazioni contabili e le applicazioni. Questa operazione non può essere annullata."
+
+msgid "Are you sure you want to void this payment? This will reverse its accounting entries and applications. This cannot be undone."
+msgstr "Sei sicuro di voler stornare questo pagamento? Questo stornerà le registrazioni contabili e le applicazioni. Questa operazione non può essere annullata."
+
msgid "Are you sure you want to void this purchase invoice? This action will reverse all financial transactions and cannot be undone."
msgstr "Sei sicuro di voler stornare questa fattura di acquisto? Questa azione annullerà tutte le transazioni finanziarie e non può essere annullata."
@@ -3440,9 +3452,6 @@ msgstr "Cancella query di ricerca"
msgid "Clear selection"
msgstr "Cancella selezione"
-msgid "Clear this invoice with the party's posted credits as well as cash. Credits apply directly — no posting needed."
-msgstr "Cancella questa fattura con i crediti registrati della parte così come il denaro. I crediti si applicano direttamente — nessuna registrazione necessaria."
-
msgid "Clear value"
msgstr "Cancella valore"
@@ -4600,6 +4609,9 @@ msgstr "Conto di credito quando i costi generali vengono assorbiti nel WIP"
msgid "Credit accounts used when manufacturing costs are absorbed into WIP"
msgstr "Conti di credito utilizzati quando i costi di produzione vengono assorbiti nel WIP"
+msgid "Credit amounts are in company base currency ({currency}). Credits take effect when this payment posts."
+msgstr "Gli importi dei crediti sono espressi nella valuta di base dell'azienda ({currency}). I crediti vengono applicati quando questo pagamento viene registrato."
+
msgid "Credit Memo"
msgstr "Nota di Credito"
@@ -8564,6 +8576,9 @@ msgstr "inv"
msgid "Inv Rate"
msgstr "Tasso Fattura"
+msgid "Invalid applications"
+msgstr "Applicazioni non valide"
+
msgid "Invalid Invite"
msgstr "Invito Non Valido"
@@ -10854,6 +10869,9 @@ msgstr "Nessuno da assegnare"
msgid "No open invoices"
msgstr "Nessuna fattura aperta"
+msgid "No open memos"
+msgstr "Nessun memo aperto"
+
msgid "No open orders for this item are available to link."
msgstr "Nessun ordine aperto per questo articolo disponibile per il collegamento."
@@ -11965,6 +11983,9 @@ msgstr "Applicazioni di Pagamento"
msgid "Payment Date"
msgstr "Data di Pagamento"
+msgid "Payment from Customer"
+msgstr "Pagamento da Cliente"
+
msgid "Payment ID"
msgstr "ID Pagamento"
@@ -11986,11 +12007,14 @@ msgstr "Condizioni di Pagamento"
msgid "Payment terms like Net 30 or due on receipt"
msgstr "Condizioni di pagamento come Netto 30 o pagamento al ricevimento"
+msgid "Payment to Supplier"
+msgstr "Pagamento a Fornitore"
+
msgid "Payments"
msgstr "Pagamenti"
-msgid "Payments and credits applied to this invoice. Click a row to open the source document."
-msgstr "Pagamenti e crediti applicati a questa fattura. Fai clic su una riga per aprire il documento di origine."
+msgid "Payments and credits applied to this invoice. Applied amounts and FX are in company base currency. Click a row to open the source document."
+msgstr "Pagamenti e crediti applicati a questa fattura. Gli importi applicati e le differenze di cambio sono espressi nella valuta di base dell'azienda. Fai clic su una riga per aprire il documento di origine."
msgid "PDF"
msgstr "PDF"
@@ -13280,8 +13304,8 @@ msgstr "Registra"
msgid "Record a credit or debit memo against a customer or supplier. Applications to specific invoices are added after the memo is created."
msgstr "Registra una nota di credito o di debito contro un cliente o fornitore. Le applicazioni a fatture specifiche vengono aggiunte dopo la creazione della nota."
-msgid "Record cash received from a customer (Receipt) or paid to a supplier (Disbursement). Applications to specific invoices are added after the payment is created."
-msgstr "Registra denaro ricevuto da un cliente o pagato a un fornitore. Le applicazioni a fatture specifiche vengono aggiunte dopo la creazione del pagamento."
+msgid "Record a customer payment, supplier payment, or refund. Applications to invoices or memos are added after the payment is created."
+msgstr "Registra un pagamento cliente, un pagamento fornitore o un rimborso. Le applicazioni alle fatture o ai memo vengono aggiunte dopo la creazione del pagamento."
msgid "Record deleted"
msgstr "Record eliminato"
@@ -13325,6 +13349,15 @@ msgstr "Aggiorna"
msgid "Refresh exchange rate"
msgstr "Aggiorna tasso di cambio"
+msgid "Refund from Supplier"
+msgstr "Rimborso da Fornitore"
+
+msgid "Refund memos"
+msgstr "Memo di rimborso"
+
+msgid "Refund to Customer"
+msgstr "Rimborso a Cliente"
+
msgid "Regenerate"
msgstr "Rigenera"
@@ -13829,9 +13862,15 @@ msgstr "Rev {revision}"
msgid "Revenue"
msgstr "Ricavi"
+msgid "Revenue account for shipping charged to customers"
+msgstr "Conto ricavi per la spedizione addebitata ai clienti"
+
msgid "Revenue and expenses over a period"
msgstr "Ricavi e spese in un periodo"
+msgid "Revenue GL account credited for shipping charged to customers, posted on its own line; it must be a different account from the Sales default."
+msgstr "Conto contabile ricavi accreditato per le spese di spedizione addebitate ai clienti, registrato su una riga separata; deve essere un conto diverso dal default di Vendite."
+
msgid "Reverse all inventory adjustments"
msgstr "Inverti tutte le rettifiche di magazzino"
@@ -14719,9 +14758,6 @@ msgstr "Seleziona superfici"
msgid "Select the groups that should complete this training"
msgstr "Seleziona i gruppi che dovrebbero completare questa formazione"
-msgid "Select the invoices this payment settles. Discount and write-off are in invoice currency."
-msgstr "Seleziona le fatture che questo pagamento liquida. Lo sconto e lo stralcio sono nella valuta della fattura."
-
msgid "Select value"
msgstr "Seleziona valore"
@@ -15095,6 +15131,12 @@ msgstr "Metodi di Spedizione"
msgid "Shipping Notes"
msgstr "Note di spedizione"
+msgid "Shipping Revenue"
+msgstr "Ricavi da spedizioni"
+
+msgid "Shipping Revenue (default)"
+msgstr "Ricavi da spedizioni (predefinito)"
+
msgid "Shipping Supplier"
msgstr "Fornitore di spedizione"
@@ -16126,6 +16168,9 @@ msgstr "Percentuale Imposta"
msgid "Tax Residual Value %"
msgstr "Valore residuo fiscale %"
+msgid "Tax Status"
+msgstr "Stato dell'Imposta"
+
msgid "Tax Useful Life (default)"
msgstr "Vita utile fiscale (impostazione predefinita)"
@@ -18481,6 +18526,11 @@ msgstr "Visibile sul profilo pubblico di un utente"
msgid "Void"
msgstr "Storna"
+#. placeholder {0}: initialValues.memoId
+#. placeholder {0}: initialValues.paymentId
+msgid "Void {0}"
+msgstr "Storna {0}"
+
msgid "Void Invoice"
msgstr "Storna fattura"
diff --git a/packages/locale/locales/ja/erp.po b/packages/locale/locales/ja/erp.po
index 0f3a686535..915efcb02b 100644
--- a/packages/locale/locales/ja/erp.po
+++ b/packages/locale/locales/ja/erp.po
@@ -1850,12 +1850,18 @@ msgstr "適用"
msgid "Applied amount for {0}"
msgstr "{0}の適用額"
+msgid "Applied amounts are in company base currency ({baseCurrency})."
+msgstr "適用金額は会社基本通貨({baseCurrency})です。"
+
msgid "Applied Date"
msgstr "適用日"
msgid "Applied To"
msgstr "適用先"
+msgid "Applied, discount and write-off amounts are in company base currency ({baseCurrency})."
+msgstr "適用済み金額、値引額、償却額は会社の基本通貨({baseCurrency})で表示されます。"
+
msgid "Applies to"
msgstr "適用対象"
@@ -2380,6 +2386,12 @@ msgstr "これらのユーザーに招待を送信してもよろしいですか
msgid "Are you sure you want to send an invite to this user?"
msgstr "このユーザーに招待を送信してもよろしいですか?"
+msgid "Are you sure you want to void this memo? This will reverse its accounting entries and applications. This cannot be undone."
+msgstr "このメモを取消しますか?会計エントリと適用が反転されます。この操作は元に戻すことができません。"
+
+msgid "Are you sure you want to void this payment? This will reverse its accounting entries and applications. This cannot be undone."
+msgstr "この支払を取消しますか?会計エントリと適用が反転されます。この操作は元に戻すことができません。"
+
msgid "Are you sure you want to void this purchase invoice? This action will reverse all financial transactions and cannot be undone."
msgstr "この仕入先請求書を取消してもよろしいですか?この操作はすべての財務取引を取消し、取り消せません。"
@@ -3440,9 +3452,6 @@ msgstr "検索クエリをクリア"
msgid "Clear selection"
msgstr "選択をクリア"
-msgid "Clear this invoice with the party's posted credits as well as cash. Credits apply directly — no posting needed."
-msgstr "転記済みクレジットと現金を使用して請求書をクリアします。クレジットは直接適用されます。転記は不要です。"
-
msgid "Clear value"
msgstr "値をクリア"
@@ -4600,6 +4609,9 @@ msgstr "間接費が仕掛品に吸収されたときに貸方勘定を計上"
msgid "Credit accounts used when manufacturing costs are absorbed into WIP"
msgstr "製造原価が仕掛品に吸収されたときに使用される貸方勘定"
+msgid "Credit amounts are in company base currency ({currency}). Credits take effect when this payment posts."
+msgstr "クレジット金額は会社の基本通貨({currency})で表示されます。この支払を転記すると、クレジットの適用が反映されます。"
+
msgid "Credit Memo"
msgstr "クレジットメモ"
@@ -8564,6 +8576,9 @@ msgstr "在庫"
msgid "Inv Rate"
msgstr "請求書レート"
+msgid "Invalid applications"
+msgstr "無効な適用"
+
msgid "Invalid Invite"
msgstr "無効な招待"
@@ -10854,6 +10869,9 @@ msgstr "配置する人がいません"
msgid "No open invoices"
msgstr "未処理の請求書がありません"
+msgid "No open memos"
+msgstr "オープンなメモはありません"
+
msgid "No open orders for this item are available to link."
msgstr "この品目にリンク可能なオープンな注文はありません"
@@ -11965,6 +11983,9 @@ msgstr "支払い適用"
msgid "Payment Date"
msgstr "支払日"
+msgid "Payment from Customer"
+msgstr "得意先からの支払"
+
msgid "Payment ID"
msgstr "支払いID"
@@ -11986,11 +12007,14 @@ msgstr "支払条件"
msgid "Payment terms like Net 30 or due on receipt"
msgstr "Net 30のような支払条件または領収時に支払い"
+msgid "Payment to Supplier"
+msgstr "仕入先への支払"
+
msgid "Payments"
msgstr "支払い"
-msgid "Payments and credits applied to this invoice. Click a row to open the source document."
-msgstr "この請求書に充当された支払と調整額。行をクリックして参照伝票を開きます。"
+msgid "Payments and credits applied to this invoice. Applied amounts and FX are in company base currency. Click a row to open the source document."
+msgstr "この請求書に適用された支払とクレジット。適用済み金額と為替差損益は会社の基本通貨で表示されます。行をクリックして参照伝票を開きます。"
msgid "PDF"
msgstr "PDF"
@@ -13280,8 +13304,8 @@ msgstr "記録"
msgid "Record a credit or debit memo against a customer or supplier. Applications to specific invoices are added after the memo is created."
msgstr "得意先または仕入先に対して貸方メモまたは借方メモを記録する。特定の請求書への適用はメモ作成後に追加される。"
-msgid "Record cash received from a customer (Receipt) or paid to a supplier (Disbursement). Applications to specific invoices are added after the payment is created."
-msgstr "得意先から受け取った現金(受取)または仕入先に支払った現金(出金)を記録する。特定の請求書への適用は支払作成後に追加される。"
+msgid "Record a customer payment, supplier payment, or refund. Applications to invoices or memos are added after the payment is created."
+msgstr "得意先支払、仕入先支払、または返金を記録します。請求書またはメモへの適用は、支払が作成された後に追加されます。"
msgid "Record deleted"
msgstr "レコード削除済み"
@@ -13325,6 +13349,15 @@ msgstr "更新"
msgid "Refresh exchange rate"
msgstr "為替レートを更新"
+msgid "Refund from Supplier"
+msgstr "仕入先からの返金"
+
+msgid "Refund memos"
+msgstr "返金メモ"
+
+msgid "Refund to Customer"
+msgstr "得意先への返金"
+
msgid "Regenerate"
msgstr "再生成"
@@ -13829,9 +13862,15 @@ msgstr "Rev {revision}"
msgid "Revenue"
msgstr "売上高"
+msgid "Revenue account for shipping charged to customers"
+msgstr "得意先に請求する配送の売上高勘定"
+
msgid "Revenue and expenses over a period"
msgstr "期間中の売上高と費用"
+msgid "Revenue GL account credited for shipping charged to customers, posted on its own line; it must be a different account from the Sales default."
+msgstr "配送料として顧客に請求される売上高の貸記に用いられる勘定科目。独自の明細行に転記され、販売のデフォルト勘定科目とは異なる必要があります。"
+
msgid "Reverse all inventory adjustments"
msgstr "すべての在庫調整を取り消す"
@@ -14719,9 +14758,6 @@ msgstr "サーフェスを選択"
msgid "Select the groups that should complete this training"
msgstr "この教育訓練を完了すべきグループを選択してください"
-msgid "Select the invoices this payment settles. Discount and write-off are in invoice currency."
-msgstr "この支払いで決済する請求書を選択してください。値引と償却は請求書の通貨で表示されます。"
-
msgid "Select value"
msgstr "値を選択"
@@ -15095,6 +15131,12 @@ msgstr "出荷方法"
msgid "Shipping Notes"
msgstr "配送メモ"
+msgid "Shipping Revenue"
+msgstr "配送売上高"
+
+msgid "Shipping Revenue (default)"
+msgstr "配送売上高(デフォルト)"
+
msgid "Shipping Supplier"
msgstr "配送仕入先"
@@ -16126,6 +16168,9 @@ msgstr "税率"
msgid "Tax Residual Value %"
msgstr "税務残存価額 %"
+msgid "Tax Status"
+msgstr "税務ステータス"
+
msgid "Tax Useful Life (default)"
msgstr "税務耐用年数(デフォルト)"
@@ -18481,6 +18526,11 @@ msgstr "ユーザーの公開プロフィールに表示されます"
msgid "Void"
msgstr "取消"
+#. placeholder {0}: initialValues.memoId
+#. placeholder {0}: initialValues.paymentId
+msgid "Void {0}"
+msgstr "取消 {0}"
+
msgid "Void Invoice"
msgstr "請求書を取消"
diff --git a/packages/locale/locales/ko/erp.po b/packages/locale/locales/ko/erp.po
index 4a65ce2ae3..8653ef8275 100644
--- a/packages/locale/locales/ko/erp.po
+++ b/packages/locale/locales/ko/erp.po
@@ -1850,12 +1850,18 @@ msgstr "적용됨"
msgid "Applied amount for {0}"
msgstr "{0}에 적용된 금액"
+msgid "Applied amounts are in company base currency ({baseCurrency})."
+msgstr "적용 금액은 회사 기본 통화({baseCurrency})입니다."
+
msgid "Applied Date"
msgstr "적용일"
msgid "Applied To"
msgstr "적용 대상"
+msgid "Applied, discount and write-off amounts are in company base currency ({baseCurrency})."
+msgstr "적용된 금액, 할인 금액 및 대손 처리 금액은 회사 기본 통화({baseCurrency})로 표시됩니다."
+
msgid "Applies to"
msgstr "적용 대상"
@@ -2380,6 +2386,12 @@ msgstr "이 사용자들에게 초대를 보내시겠습니까?"
msgid "Are you sure you want to send an invite to this user?"
msgstr "이 사용자에게 초대를 보내시겠습니까?"
+msgid "Are you sure you want to void this memo? This will reverse its accounting entries and applications. This cannot be undone."
+msgstr "이 메모를 무효 처리하시겠습니까? 회계 항목 및 적용 내역이 역변환됩니다. 이 작업은 되돌릴 수 없습니다."
+
+msgid "Are you sure you want to void this payment? This will reverse its accounting entries and applications. This cannot be undone."
+msgstr "이 지불을 무효 처리하시겠습니까? 회계 항목 및 적용 내역이 역변환됩니다. 이 작업은 되돌릴 수 없습니다."
+
msgid "Are you sure you want to void this purchase invoice? This action will reverse all financial transactions and cannot be undone."
msgstr "이 매입 송장을 무효 처리하시겠습니까? 이 작업은 모든 재무 거래를 역입금하며 취소할 수 없습니다."
@@ -3440,9 +3452,6 @@ msgstr "검색 쿼리 지우기"
msgid "Clear selection"
msgstr "선택 해제"
-msgid "Clear this invoice with the party's posted credits as well as cash. Credits apply directly — no posting needed."
-msgstr "이 송장을 거래처의 전기된 대변 및 현금으로 상계하십시오. 대변은 직접 적용됩니다 — 전기가 필요하지 않습니다."
-
msgid "Clear value"
msgstr "값 지우기"
@@ -4600,6 +4609,9 @@ msgstr "간접비가 재공품에 편입될 때의 대변 계정"
msgid "Credit accounts used when manufacturing costs are absorbed into WIP"
msgstr "제조 원가가 재공품에 편입될 때 사용되는 대변 계정"
+msgid "Credit amounts are in company base currency ({currency}). Credits take effect when this payment posts."
+msgstr "크레딧 금액은 회사 기본 통화({currency})로 표시됩니다. 이 지불이 전기되면 크레딧이 적용됩니다."
+
msgid "Credit Memo"
msgstr "대변전표"
@@ -8564,6 +8576,9 @@ msgstr "재고"
msgid "Inv Rate"
msgstr "재고 비율"
+msgid "Invalid applications"
+msgstr "잘못된 적용"
+
msgid "Invalid Invite"
msgstr "유효하지 않은 초대"
@@ -10854,6 +10869,9 @@ msgstr "배정할 사람이 없습니다"
msgid "No open invoices"
msgstr "미결 송장이 없습니다."
+msgid "No open memos"
+msgstr "미결 메모 없음"
+
msgid "No open orders for this item are available to link."
msgstr "이 품목의 연결 가능한 미결 주문이 없습니다."
@@ -11965,6 +11983,9 @@ msgstr "지불 적용"
msgid "Payment Date"
msgstr "지불 날짜"
+msgid "Payment from Customer"
+msgstr "고객 지불"
+
msgid "Payment ID"
msgstr "지불 ID"
@@ -11986,11 +12007,14 @@ msgstr "지불 조건"
msgid "Payment terms like Net 30 or due on receipt"
msgstr "Net 30 또는 입고 시 만기와 같은 지불 조건"
+msgid "Payment to Supplier"
+msgstr "공급업체 지불"
+
msgid "Payments"
msgstr "지불"
-msgid "Payments and credits applied to this invoice. Click a row to open the source document."
-msgstr "이 송장에 적용된 지불 및 대변. 행을 클릭하여 원본 문서를 엽니다."
+msgid "Payments and credits applied to this invoice. Applied amounts and FX are in company base currency. Click a row to open the source document."
+msgstr "이 송장에 적용된 지불 및 크레딧입니다. 적용된 금액과 외환 손익 금액은 회사 기본 통화로 표시됩니다. 원본 문서를 열려면 행을 클릭하세요."
msgid "PDF"
msgstr "PDF"
@@ -13280,8 +13304,8 @@ msgstr "기록"
msgid "Record a credit or debit memo against a customer or supplier. Applications to specific invoices are added after the memo is created."
msgstr "고객 또는 공급업체에 대해 신용증 또는 차감증을 기록하세요. 특정 송장에 대한 적용은 메모가 생성된 후에 추가됩니다."
-msgid "Record cash received from a customer (Receipt) or paid to a supplier (Disbursement). Applications to specific invoices are added after the payment is created."
-msgstr "고객으로부터 수령한 현금 또는 공급업체에 지급한 현금을 기록하세요. 특정 송장에 대한 적용은 지불이 생성된 후에 추가됩니다."
+msgid "Record a customer payment, supplier payment, or refund. Applications to invoices or memos are added after the payment is created."
+msgstr "고객 지불, 공급업체 지불 또는 환불을 기록합니다. 지불 생성 후 송장 또는 메모에 대한 적용이 추가됩니다."
msgid "Record deleted"
msgstr "레코드가 삭제됨"
@@ -13325,6 +13349,15 @@ msgstr "새로고침"
msgid "Refresh exchange rate"
msgstr "환율 새로고침"
+msgid "Refund from Supplier"
+msgstr "공급업체 환불"
+
+msgid "Refund memos"
+msgstr "환불 메모"
+
+msgid "Refund to Customer"
+msgstr "고객 환불"
+
msgid "Regenerate"
msgstr "재생성"
@@ -13829,9 +13862,15 @@ msgstr "Rev {revision}"
msgid "Revenue"
msgstr "매출"
+msgid "Revenue account for shipping charged to customers"
+msgstr "고객에게 청구한 배송 매출 계정"
+
msgid "Revenue and expenses over a period"
msgstr "기간별 매출 및 비용"
+msgid "Revenue GL account credited for shipping charged to customers, posted on its own line; it must be a different account from the Sales default."
+msgstr "고객에게 청구하는 배송료 수익을 대변기입하는 계정과목으로, 자신의 라인에 전기되며, 영업 기본값과는 달라야 합니다."
+
msgid "Reverse all inventory adjustments"
msgstr "모든 재고 조정 취소"
@@ -14719,9 +14758,6 @@ msgstr "표면 선택"
msgid "Select the groups that should complete this training"
msgstr "이 교육을 완료해야 하는 그룹을 선택하세요"
-msgid "Select the invoices this payment settles. Discount and write-off are in invoice currency."
-msgstr "이 지불로 결제되는 송장을 선택하세요. 할인과 대손 처리는 송장 통화로 표시됩니다."
-
msgid "Select value"
msgstr "값 선택"
@@ -15095,6 +15131,12 @@ msgstr "배송 방법"
msgid "Shipping Notes"
msgstr "배송 메모"
+msgid "Shipping Revenue"
+msgstr "배송 매출"
+
+msgid "Shipping Revenue (default)"
+msgstr "배송 매출 (기본값)"
+
msgid "Shipping Supplier"
msgstr "배송 공급업체"
@@ -16126,6 +16168,9 @@ msgstr "세금 비율"
msgid "Tax Residual Value %"
msgstr "세금 잔존가액 %"
+msgid "Tax Status"
+msgstr "세금 상태"
+
msgid "Tax Useful Life (default)"
msgstr "세금 내용연수 (기본값)"
@@ -18481,6 +18526,11 @@ msgstr "사용자의 공개 프로필에 표시됩니다"
msgid "Void"
msgstr "무효 처리"
+#. placeholder {0}: initialValues.memoId
+#. placeholder {0}: initialValues.paymentId
+msgid "Void {0}"
+msgstr "{0} 무효 처리"
+
msgid "Void Invoice"
msgstr "송장 무효 처리"
diff --git a/packages/locale/locales/pl/erp.po b/packages/locale/locales/pl/erp.po
index f561834657..034bca6390 100644
--- a/packages/locale/locales/pl/erp.po
+++ b/packages/locale/locales/pl/erp.po
@@ -1850,12 +1850,18 @@ msgstr "Zastosowano"
msgid "Applied amount for {0}"
msgstr "Zastosowana kwota dla {0}"
+msgid "Applied amounts are in company base currency ({baseCurrency})."
+msgstr "Zastosowane kwoty są w bazowej walucie firmy ({baseCurrency})."
+
msgid "Applied Date"
msgstr "Data zastosowania"
msgid "Applied To"
msgstr "Zastosowano do"
+msgid "Applied, discount and write-off amounts are in company base currency ({baseCurrency})."
+msgstr "Kwoty rozliczeń, rabatów i spisań sald są wyrażone w walucie bazowej firmy ({baseCurrency})."
+
msgid "Applies to"
msgstr "Dotyczy"
@@ -2380,6 +2386,12 @@ msgstr "Czy na pewno chcesz wysłać zaproszenie do tych użytkowników?"
msgid "Are you sure you want to send an invite to this user?"
msgstr "Czy na pewno chcesz wysłać zaproszenie temu użytkownikowi?"
+msgid "Are you sure you want to void this memo? This will reverse its accounting entries and applications. This cannot be undone."
+msgstr "Czy na pewno chcesz unieważnić to memo? Spowoduje to wycofanie jego wpisów księgowych i zastosowań. Nie można tego cofnąć."
+
+msgid "Are you sure you want to void this payment? This will reverse its accounting entries and applications. This cannot be undone."
+msgstr "Czy na pewno chcesz unieważnić tę płatność? Spowoduje to wycofanie jej wpisów księgowych i zastosowań. Nie można tego cofnąć."
+
msgid "Are you sure you want to void this purchase invoice? This action will reverse all financial transactions and cannot be undone."
msgstr "Czy chcesz unieważnić tę fakturę zakupu? Ta czynność odwróci wszystkie transakcje finansowe i nie można jej cofnąć."
@@ -3440,9 +3452,6 @@ msgstr "Wyczyść zapytanie wyszukiwania"
msgid "Clear selection"
msgstr "Wyczyść zaznaczenie"
-msgid "Clear this invoice with the party's posted credits as well as cash. Credits apply directly — no posting needed."
-msgstr "Wyczyść tę fakturę za pomocą zaksięgowanych kredytów strony oraz gotówki. Kredyty są stosowane bezpośrednio — nie jest wymagane żadne zaksięgowanie."
-
msgid "Clear value"
msgstr "Wyczyść wartość"
@@ -4600,6 +4609,9 @@ msgstr "Konto kredytowe dla absorpcji kosztów pośrednich do produkcji w toku"
msgid "Credit accounts used when manufacturing costs are absorbed into WIP"
msgstr "Konta kredytowe używane do absorpcji kosztów produkcji do produkcji w toku"
+msgid "Credit amounts are in company base currency ({currency}). Credits take effect when this payment posts."
+msgstr "Kwoty uznań są wyrażone w walucie bazowej firmy ({currency}). Uznania są uwzględniane po zaksięgowaniu tej płatności."
+
msgid "Credit Memo"
msgstr "Faktura korygująca"
@@ -8564,6 +8576,9 @@ msgstr "inv"
msgid "Inv Rate"
msgstr "Kurs Fakt"
+msgid "Invalid applications"
+msgstr "Nieprawidłowe rozliczenia"
+
msgid "Invalid Invite"
msgstr "Nieprawidłowe zaproszenie"
@@ -10854,6 +10869,9 @@ msgstr "Nikt do przydzielenia"
msgid "No open invoices"
msgstr "Brak otwartych faktur"
+msgid "No open memos"
+msgstr "Brak otwartych notatek"
+
msgid "No open orders for this item are available to link."
msgstr "Brak dostępnych otwartych zamówień dla tego produktu do powiązania."
@@ -11965,6 +11983,9 @@ msgstr "Zastosowania Płatności"
msgid "Payment Date"
msgstr "Data płatności"
+msgid "Payment from Customer"
+msgstr "Płatność od Klienta"
+
msgid "Payment ID"
msgstr "Identyfikator płatności"
@@ -11986,11 +12007,14 @@ msgstr "Warunki Płatności"
msgid "Payment terms like Net 30 or due on receipt"
msgstr "Warunki płatności takie jak Net 30 lub płatne przy odbiorze"
+msgid "Payment to Supplier"
+msgstr "Płatność dla Dostawcy"
+
msgid "Payments"
msgstr "Płatności"
-msgid "Payments and credits applied to this invoice. Click a row to open the source document."
-msgstr "Płatności i kredyty zastosowane do tej faktury. Kliknij wiersz, aby otworzyć dokument źródłowy."
+msgid "Payments and credits applied to this invoice. Applied amounts and FX are in company base currency. Click a row to open the source document."
+msgstr "Płatności i uznania rozliczone z tą fakturą. Kwoty rozliczeń i różnice kursowe są wyrażone w walucie bazowej firmy. Kliknij wiersz, aby otworzyć dokument źródłowy."
msgid "PDF"
msgstr "PDF"
@@ -13280,8 +13304,8 @@ msgstr "Nagrywaj"
msgid "Record a credit or debit memo against a customer or supplier. Applications to specific invoices are added after the memo is created."
msgstr "Zarejestruj notę kredytową lub debetową dla klienta lub dostawcy. Zastosowania do konkretnych faktur są dodawane po utworzeniu noty."
-msgid "Record cash received from a customer (Receipt) or paid to a supplier (Disbursement). Applications to specific invoices are added after the payment is created."
-msgstr "Zarejestruj gotówkę otrzymaną od klienta (Wpłata) lub zapłaconą dostawcy (Wypłata). Aplikacje do konkretnych faktur są dodawane po utworzeniu płatności."
+msgid "Record a customer payment, supplier payment, or refund. Applications to invoices or memos are added after the payment is created."
+msgstr "Zarejestruj płatność od klienta, płatność dla dostawcy lub zwrot. Zastosowania do faktur lub not są dodawane po utworzeniu płatności."
msgid "Record deleted"
msgstr "Rekord usunięty"
@@ -13325,6 +13349,15 @@ msgstr "Odśwież"
msgid "Refresh exchange rate"
msgstr "Odśwież kurs wymiany"
+msgid "Refund from Supplier"
+msgstr "Zwrot od Dostawcy"
+
+msgid "Refund memos"
+msgstr "Noty zwrotu"
+
+msgid "Refund to Customer"
+msgstr "Zwrot dla Klienta"
+
msgid "Regenerate"
msgstr "Ponownie wygeneruj"
@@ -13829,9 +13862,15 @@ msgstr "Wer. {revision}"
msgid "Revenue"
msgstr "Przychody ze sprzedaży"
+msgid "Revenue account for shipping charged to customers"
+msgstr "Konto przychodów z opłat za wysyłkę pobieranych od klientów"
+
msgid "Revenue and expenses over a period"
msgstr "Przychody ze sprzedaży i wydatki za okres"
+msgid "Revenue GL account credited for shipping charged to customers, posted on its own line; it must be a different account from the Sales default."
+msgstr "Konto księgowe przychodów ze wysyłki rozliczanej z klientami, zaksięgowane na osobnej pozycji; musi różnić się od domyślnego konta Sprzedaży."
+
msgid "Reverse all inventory adjustments"
msgstr "Odwróć wszystkie korekty zapasów"
@@ -14719,9 +14758,6 @@ msgstr "Wybierz powierzchnie"
msgid "Select the groups that should complete this training"
msgstr "Wybierz grupy, które powinny ukończyć to szkolenie"
-msgid "Select the invoices this payment settles. Discount and write-off are in invoice currency."
-msgstr "Wybierz faktury, które ta płatność rozlicza. Rabat i spisanie są w walucie faktury."
-
msgid "Select value"
msgstr "Wybierz wartość"
@@ -15095,6 +15131,12 @@ msgstr "Sposoby wysyłki"
msgid "Shipping Notes"
msgstr "Notatki wysyłki"
+msgid "Shipping Revenue"
+msgstr "Przychody z opłat za wysyłkę"
+
+msgid "Shipping Revenue (default)"
+msgstr "Przychody z opłat za wysyłkę (domyślne)"
+
msgid "Shipping Supplier"
msgstr "Dostawca wysyłki"
@@ -16126,6 +16168,9 @@ msgstr "Procent podatku"
msgid "Tax Residual Value %"
msgstr "Podatkowa wartość rezydualna %"
+msgid "Tax Status"
+msgstr "Status podatku"
+
msgid "Tax Useful Life (default)"
msgstr "Okres użytkowania dla podatku (domyślnie)"
@@ -18481,6 +18526,11 @@ msgstr "Widoczne w publicznym profilu użytkownika"
msgid "Void"
msgstr "Unieważnij"
+#. placeholder {0}: initialValues.memoId
+#. placeholder {0}: initialValues.paymentId
+msgid "Void {0}"
+msgstr "Unieważnij {0}"
+
msgid "Void Invoice"
msgstr "Unieważnij fakturę"
diff --git a/packages/locale/locales/pt/erp.po b/packages/locale/locales/pt/erp.po
index 72b87861d5..2123309413 100644
--- a/packages/locale/locales/pt/erp.po
+++ b/packages/locale/locales/pt/erp.po
@@ -1850,12 +1850,18 @@ msgstr "Aplicado"
msgid "Applied amount for {0}"
msgstr "Valor aplicado para {0}"
+msgid "Applied amounts are in company base currency ({baseCurrency})."
+msgstr "Os valores aplicados estão na moeda base da empresa ({baseCurrency})."
+
msgid "Applied Date"
msgstr "Data de Aplicação"
msgid "Applied To"
msgstr "Aplicado a"
+msgid "Applied, discount and write-off amounts are in company base currency ({baseCurrency})."
+msgstr "Os valores aplicados, os descontos e as baixas contábeis estão na moeda base da empresa ({baseCurrency})."
+
msgid "Applies to"
msgstr "Aplica-se a"
@@ -2380,6 +2386,12 @@ msgstr "Tem certeza de que deseja enviar um convite para estes usuários?"
msgid "Are you sure you want to send an invite to this user?"
msgstr "Tem certeza de que deseja enviar um convite para este usuário?"
+msgid "Are you sure you want to void this memo? This will reverse its accounting entries and applications. This cannot be undone."
+msgstr "Tem certeza de que deseja anular este memorando? Isso reverterá seus lançamentos contábeis e aplicações. Isso não pode ser desfeito."
+
+msgid "Are you sure you want to void this payment? This will reverse its accounting entries and applications. This cannot be undone."
+msgstr "Tem certeza de que deseja anular este pagamento? Isso reverterá seus lançamentos contábeis e aplicações. Isso não pode ser desfeito."
+
msgid "Are you sure you want to void this purchase invoice? This action will reverse all financial transactions and cannot be undone."
msgstr "Tem a certeza de que deseja anular esta fatura de compra? Esta ação reverterá todas as transações financeiras e não pode ser desfeita."
@@ -3440,9 +3452,6 @@ msgstr "Limpar consulta de pesquisa"
msgid "Clear selection"
msgstr "Limpar seleção"
-msgid "Clear this invoice with the party's posted credits as well as cash. Credits apply directly — no posting needed."
-msgstr "Liquidar esta fatura com os créditos contabilizados da parte, bem como caixa. Os créditos se aplicam diretamente — nenhuma contabilização necessária."
-
msgid "Clear value"
msgstr "Limpar valor"
@@ -4600,6 +4609,9 @@ msgstr "Conta contábil de crédito quando custos indiretos são absorvidos em P
msgid "Credit accounts used when manufacturing costs are absorbed into WIP"
msgstr "Contas contábeis de crédito usadas quando custos de manufatura são absorvidos em Produto em processo"
+msgid "Credit amounts are in company base currency ({currency}). Credits take effect when this payment posts."
+msgstr "Os valores de crédito estão na moeda base da empresa ({currency}). Os créditos entram em vigor quando este pagamento é contabilizado."
+
msgid "Credit Memo"
msgstr "Nota de crédito"
@@ -8564,6 +8576,9 @@ msgstr "inv"
msgid "Inv Rate"
msgstr "Taxa Inv"
+msgid "Invalid applications"
+msgstr "Aplicações inválidas"
+
msgid "Invalid Invite"
msgstr "Convite Inválido"
@@ -10854,6 +10869,9 @@ msgstr "Ninguém para atribuir"
msgid "No open invoices"
msgstr "Nenhuma fatura aberta"
+msgid "No open memos"
+msgstr "Sem memorandos abertos"
+
msgid "No open orders for this item are available to link."
msgstr "Nenhum pedido aberto para este item está disponível para vincular."
@@ -11965,6 +11983,9 @@ msgstr "Aplicações de Pagamento"
msgid "Payment Date"
msgstr "Data de Pagamento"
+msgid "Payment from Customer"
+msgstr "Pagamento do Cliente"
+
msgid "Payment ID"
msgstr "ID de Pagamento"
@@ -11986,11 +12007,14 @@ msgstr "Condições de Pagamento"
msgid "Payment terms like Net 30 or due on receipt"
msgstr "Condições de pagamento como Líquido 30 ou vencível no recebimento"
+msgid "Payment to Supplier"
+msgstr "Pagamento ao Fornecedor"
+
msgid "Payments"
msgstr "Pagamentos"
-msgid "Payments and credits applied to this invoice. Click a row to open the source document."
-msgstr "Pagamentos e créditos aplicados a esta fatura. Clique em uma linha para abrir o documento de origem."
+msgid "Payments and credits applied to this invoice. Applied amounts and FX are in company base currency. Click a row to open the source document."
+msgstr "Pagamentos e créditos aplicados a esta fatura. Os valores aplicados e de variação cambial estão na moeda base da empresa. Clique em uma linha para abrir o documento de origem."
msgid "PDF"
msgstr "PDF"
@@ -13280,8 +13304,8 @@ msgstr "Gravar"
msgid "Record a credit or debit memo against a customer or supplier. Applications to specific invoices are added after the memo is created."
msgstr "Registre um memorando de crédito ou débito contra um cliente ou fornecedor. As aplicações a faturas específicas são adicionadas após a criação do memorando."
-msgid "Record cash received from a customer (Receipt) or paid to a supplier (Disbursement). Applications to specific invoices are added after the payment is created."
-msgstr "Registre caixa recebido de um cliente (Recebimento) ou pago a um fornecedor (Desembolso). Aplicações a faturas específicas são adicionadas após o pagamento ser criado."
+msgid "Record a customer payment, supplier payment, or refund. Applications to invoices or memos are added after the payment is created."
+msgstr "Registre um pagamento do cliente, pagamento do fornecedor ou reembolso. As aplicações às faturas ou memorandos são adicionadas após o pagamento ser criado."
msgid "Record deleted"
msgstr "Registro eliminado"
@@ -13325,6 +13349,15 @@ msgstr "Atualizar"
msgid "Refresh exchange rate"
msgstr "Atualizar taxa de câmbio"
+msgid "Refund from Supplier"
+msgstr "Reembolso do Fornecedor"
+
+msgid "Refund memos"
+msgstr "Memorandos de Reembolso"
+
+msgid "Refund to Customer"
+msgstr "Reembolso para o Cliente"
+
msgid "Regenerate"
msgstr "Regenerar"
@@ -13829,9 +13862,15 @@ msgstr "Rev {revision}"
msgid "Revenue"
msgstr "Receita"
+msgid "Revenue account for shipping charged to customers"
+msgstr "Conta de receita de envio cobrado aos clientes"
+
msgid "Revenue and expenses over a period"
msgstr "Receita e despesas em um período"
+msgid "Revenue GL account credited for shipping charged to customers, posted on its own line; it must be a different account from the Sales default."
+msgstr "Conta contábil de receita creditada por frete cobrado dos clientes, contabilizada em sua própria linha; deve ser uma conta diferente do padrão de Vendas."
+
msgid "Reverse all inventory adjustments"
msgstr "Reverter todos os ajustes de estoque"
@@ -14719,9 +14758,6 @@ msgstr "Selecionar superfícies"
msgid "Select the groups that should complete this training"
msgstr "Selecione os grupos que devem concluir este treinamento"
-msgid "Select the invoices this payment settles. Discount and write-off are in invoice currency."
-msgstr "Selecione as faturas que este pagamento liquida. Desconto e baixa contábil estão na moeda da fatura."
-
msgid "Select value"
msgstr "Selecionar valor"
@@ -15095,6 +15131,12 @@ msgstr "Métodos de Envio"
msgid "Shipping Notes"
msgstr "Observações de envio"
+msgid "Shipping Revenue"
+msgstr "Receita de envio"
+
+msgid "Shipping Revenue (default)"
+msgstr "Receita de envio (padrão)"
+
msgid "Shipping Supplier"
msgstr "Fornecedor de Envio"
@@ -16126,6 +16168,9 @@ msgstr "Percentual de Imposto"
msgid "Tax Residual Value %"
msgstr "% Valor residual fiscal"
+msgid "Tax Status"
+msgstr "Status de Imposto"
+
msgid "Tax Useful Life (default)"
msgstr "Vida útil fiscal (padrão)"
@@ -18481,6 +18526,11 @@ msgstr "Visível no perfil público de um usuário"
msgid "Void"
msgstr "Anular"
+#. placeholder {0}: initialValues.memoId
+#. placeholder {0}: initialValues.paymentId
+msgid "Void {0}"
+msgstr "Anular {0}"
+
msgid "Void Invoice"
msgstr "Anular Fatura"
diff --git a/packages/locale/locales/ru/erp.po b/packages/locale/locales/ru/erp.po
index ab7816fc4d..eb5e51f017 100644
--- a/packages/locale/locales/ru/erp.po
+++ b/packages/locale/locales/ru/erp.po
@@ -1850,12 +1850,18 @@ msgstr "Применено"
msgid "Applied amount for {0}"
msgstr "Примененная сумма для {0}"
+msgid "Applied amounts are in company base currency ({baseCurrency})."
+msgstr "Применённые суммы указаны в базовой валюте организации ({baseCurrency})."
+
msgid "Applied Date"
msgstr "Дата применения"
msgid "Applied To"
msgstr "Применено к"
+msgid "Applied, discount and write-off amounts are in company base currency ({baseCurrency})."
+msgstr "Примененные суммы, скидки и списания указаны в базовой валюте организации ({baseCurrency})."
+
msgid "Applies to"
msgstr "Применяется к"
@@ -2380,6 +2386,12 @@ msgstr "Вы уверены, что хотите отправить пригла
msgid "Are you sure you want to send an invite to this user?"
msgstr "Вы уверены, что хотите отправить приглашение этому пользователю?"
+msgid "Are you sure you want to void this memo? This will reverse its accounting entries and applications. This cannot be undone."
+msgstr "Вы уверены, что хотите аннулировать эту служебную записку? Это развернет ее бухгалтерские записи и применения. Это невозможно отменить."
+
+msgid "Are you sure you want to void this payment? This will reverse its accounting entries and applications. This cannot be undone."
+msgstr "Вы уверены, что хотите аннулировать этот платеж? Это развернет его бухгалтерские записи и применения. Это невозможно отменить."
+
msgid "Are you sure you want to void this purchase invoice? This action will reverse all financial transactions and cannot be undone."
msgstr "Вы уверены, что хотите аннулировать этот счет-фактуру полученный? Это действие отменит все финансовые операции и не может быть отменено."
@@ -3440,9 +3452,6 @@ msgstr "Очистить поисковый запрос"
msgid "Clear selection"
msgstr "Очистить выделение"
-msgid "Clear this invoice with the party's posted credits as well as cash. Credits apply directly — no posting needed."
-msgstr "Погасите этот счет-фактуру кредитами и денежными средствами стороны. Кредиты применяются напрямую — проведение не требуется."
-
msgid "Clear value"
msgstr "Очистить значение"
@@ -4600,6 +4609,9 @@ msgstr "Кредитовый счет при поглощении накладн
msgid "Credit accounts used when manufacturing costs are absorbed into WIP"
msgstr "Счета кредита, используемые когда производственные затраты поглощаются незавершенным производством"
+msgid "Credit amounts are in company base currency ({currency}). Credits take effect when this payment posts."
+msgstr "Суммы зачётов указаны в базовой валюте организации ({currency}). Зачёты учитываются после проведения этого платежа."
+
msgid "Credit Memo"
msgstr "Кредит-нота"
@@ -8564,6 +8576,9 @@ msgstr "инв"
msgid "Inv Rate"
msgstr "Курс счета"
+msgid "Invalid applications"
+msgstr "Недействительные применения"
+
msgid "Invalid Invite"
msgstr "Недействительное приглашение"
@@ -10854,6 +10869,9 @@ msgstr "Некого назначать"
msgid "No open invoices"
msgstr "Нет открытых счетов-фактур"
+msgid "No open memos"
+msgstr "Нет открытых служебных записок"
+
msgid "No open orders for this item are available to link."
msgstr "Нет открытых заказов для этого товара, доступных для связи."
@@ -11965,6 +11983,9 @@ msgstr "Применение платежей"
msgid "Payment Date"
msgstr "Дата платежа"
+msgid "Payment from Customer"
+msgstr "Платеж от Покупателя"
+
msgid "Payment ID"
msgstr "ID платежа"
@@ -11986,11 +12007,14 @@ msgstr "Условия оплаты"
msgid "Payment terms like Net 30 or due on receipt"
msgstr "Условия оплаты, такие как Net 30 или оплата при получении"
+msgid "Payment to Supplier"
+msgstr "Платеж Поставщику"
+
msgid "Payments"
msgstr "Платежи"
-msgid "Payments and credits applied to this invoice. Click a row to open the source document."
-msgstr "Платежи и кредиты, применные к этому счету-фактуре. Нажмите на строку, чтобы открыть документ-основание."
+msgid "Payments and credits applied to this invoice. Applied amounts and FX are in company base currency. Click a row to open the source document."
+msgstr "Платежи и зачёты по этому счету-фактуре. Зачтённые суммы и курсовые разницы указаны в базовой валюте организации. Нажмите строку, чтобы открыть документ-основание."
msgid "PDF"
msgstr "PDF"
@@ -13280,8 +13304,8 @@ msgstr "Записать"
msgid "Record a credit or debit memo against a customer or supplier. Applications to specific invoices are added after the memo is created."
msgstr "Зарегистрируйте кредит-ноту или дебет-ноту для покупателя или поставщика. Применения к конкретным счетам-фактурам добавляются после создания документа."
-msgid "Record cash received from a customer (Receipt) or paid to a supplier (Disbursement). Applications to specific invoices are added after the payment is created."
-msgstr "Зарегистрируйте денежные средства, полученные от покупателя (Поступление) или выплаченные поставщику (Выплата). Применения к конкретным счетам-фактурам добавляются после создания платежа."
+msgid "Record a customer payment, supplier payment, or refund. Applications to invoices or memos are added after the payment is created."
+msgstr "Зафиксируйте платеж от покупателя, платеж поставщику или возврат. Применения на счета-фактуры или служебные записки добавляются после создания платежа."
msgid "Record deleted"
msgstr "Запись удалена"
@@ -13325,6 +13349,15 @@ msgstr "Обновить"
msgid "Refresh exchange rate"
msgstr "Обновить валютный курс"
+msgid "Refund from Supplier"
+msgstr "Возврат от Поставщика"
+
+msgid "Refund memos"
+msgstr "Служебные записки о возврате"
+
+msgid "Refund to Customer"
+msgstr "Возврат Покупателю"
+
msgid "Regenerate"
msgstr "Пересчитать"
@@ -13829,9 +13862,15 @@ msgstr "Ред. {revision}"
msgid "Revenue"
msgstr "Выручка"
+msgid "Revenue account for shipping charged to customers"
+msgstr "Счет выручки от доставки, начисляемой покупателям"
+
msgid "Revenue and expenses over a period"
msgstr "Выручка и расходы за период"
+msgid "Revenue GL account credited for shipping charged to customers, posted on its own line; it must be a different account from the Sales default."
+msgstr "Счет учета выручки, кредитуемый за доставку, взимаемую с покупателей, проводимый отдельной строкой; должен отличаться от счета Продажи по умолчанию."
+
msgid "Reverse all inventory adjustments"
msgstr "Отменить все корректировки запасов"
@@ -14719,9 +14758,6 @@ msgstr "Выберите поверхности"
msgid "Select the groups that should complete this training"
msgstr "Выберите группы, которые должны пройти это обучение"
-msgid "Select the invoices this payment settles. Discount and write-off are in invoice currency."
-msgstr "Выберите счета-фактуры, которые погашает этот платеж. Скидка и списание указаны в валюте счета-фактуры."
-
msgid "Select value"
msgstr "Выберите значение"
@@ -15095,6 +15131,12 @@ msgstr "Способы доставки"
msgid "Shipping Notes"
msgstr "Примечания к доставке"
+msgid "Shipping Revenue"
+msgstr "Выручка от доставки"
+
+msgid "Shipping Revenue (default)"
+msgstr "Выручка от доставки (по умолчанию)"
+
msgid "Shipping Supplier"
msgstr "Поставщик доставки"
@@ -16126,6 +16168,9 @@ msgstr "Процент налога"
msgid "Tax Residual Value %"
msgstr "Налоговая ликвидационная стоимость %"
+msgid "Tax Status"
+msgstr "Статус налога"
+
msgid "Tax Useful Life (default)"
msgstr "Налоговый срок полезного использования (по умолчанию)"
@@ -18481,6 +18526,11 @@ msgstr "Видно в общедоступном профиле пользова
msgid "Void"
msgstr "Аннулировать"
+#. placeholder {0}: initialValues.memoId
+#. placeholder {0}: initialValues.paymentId
+msgid "Void {0}"
+msgstr "Аннулировать {0}"
+
msgid "Void Invoice"
msgstr "Аннулировать счет-фактуру"
diff --git a/packages/locale/locales/tr/erp.po b/packages/locale/locales/tr/erp.po
index 94002ad914..64686263da 100644
--- a/packages/locale/locales/tr/erp.po
+++ b/packages/locale/locales/tr/erp.po
@@ -1850,12 +1850,18 @@ msgstr "Uygulandı"
msgid "Applied amount for {0}"
msgstr "{0} için uygulanan tutar"
+msgid "Applied amounts are in company base currency ({baseCurrency})."
+msgstr "Uygulanan tutarlar şirket temel para birimindedir ({baseCurrency})."
+
msgid "Applied Date"
msgstr "Uygulama Tarihi"
msgid "Applied To"
msgstr "Uygulandı"
+msgid "Applied, discount and write-off amounts are in company base currency ({baseCurrency})."
+msgstr "Uygulanan tutarlar, iskontolar ve kayıttan düşülen tutarlar şirketin temel para birimi ({baseCurrency}) cinsindendir."
+
msgid "Applies to"
msgstr "Uygulama"
@@ -2380,6 +2386,12 @@ msgstr "Bu kullanıcılara daveti göndermek istediğinizden emin misiniz?"
msgid "Are you sure you want to send an invite to this user?"
msgstr "Bu kullanıcıya daveti göndermek istediğinizden emin misiniz?"
+msgid "Are you sure you want to void this memo? This will reverse its accounting entries and applications. This cannot be undone."
+msgstr "Bu notu hükümsüz kılmak istediğinizden emin misiniz? Bu, muhasebe girişlerini ve uygulamalarını tersine çevirecektir. Bu geri alınamaz."
+
+msgid "Are you sure you want to void this payment? This will reverse its accounting entries and applications. This cannot be undone."
+msgstr "Bu ödemeyi hükümsüz kılmak istediğinizden emin misiniz? Bu, muhasebe girişlerini ve uygulamalarını tersine çevirecektir. Bu geri alınamaz."
+
msgid "Are you sure you want to void this purchase invoice? This action will reverse all financial transactions and cannot be undone."
msgstr "Bu alış faturasını hükümsüz kılmak istediğinizden emin misiniz? Bu işlem tüm mali işlemleri tersine çevirecek ve geri alınamaz."
@@ -3440,9 +3452,6 @@ msgstr "Arama sorgusunu temizle"
msgid "Clear selection"
msgstr "Seçimi temizle"
-msgid "Clear this invoice with the party's posted credits as well as cash. Credits apply directly — no posting needed."
-msgstr "Bu faturayı tarafın muhasebeleştirilmiş alacakları ve nakit ile kapatın. Alacaklar doğrudan uygulanır — muhasebeleştirme gerekmez."
-
msgid "Clear value"
msgstr "Değeri temizle"
@@ -4600,6 +4609,9 @@ msgstr "Genel üretim giderleri WIP'e soğurulduğunda alacak hesabı"
msgid "Credit accounts used when manufacturing costs are absorbed into WIP"
msgstr "Üretim maliyetleri WIP'e soğurulduğunda kullanılan alacak hesapları"
+msgid "Credit amounts are in company base currency ({currency}). Credits take effect when this payment posts."
+msgstr "Alacak tutarları şirketin temel para birimi ({currency}) cinsindendir. Bu ödeme muhasebeleştirildiğinde alacaklar geçerli olur."
+
msgid "Credit Memo"
msgstr "Alacak dekontu"
@@ -8564,6 +8576,9 @@ msgstr "stok"
msgid "Inv Rate"
msgstr "Fatura Oranı"
+msgid "Invalid applications"
+msgstr "Geçersiz uygulamalar"
+
msgid "Invalid Invite"
msgstr "Geçersiz Davetiye"
@@ -10854,6 +10869,9 @@ msgstr "Atanacak kimse yok"
msgid "No open invoices"
msgstr "Açık fatura yok"
+msgid "No open memos"
+msgstr "Açık muhasebe notları yok"
+
msgid "No open orders for this item are available to link."
msgstr "Bu stok kartı için bağlanacak açık sipariş yok."
@@ -11965,6 +11983,9 @@ msgstr "Ödeme Uygulamaları"
msgid "Payment Date"
msgstr "Ödeme Tarihi"
+msgid "Payment from Customer"
+msgstr "Müşteriden Ödeme"
+
msgid "Payment ID"
msgstr "Ödeme Kimliği"
@@ -11986,11 +12007,14 @@ msgstr "Ödeme Koşulları"
msgid "Payment terms like Net 30 or due on receipt"
msgstr "Net 30 gibi ödeme koşulları veya alındığında ödeme"
+msgid "Payment to Supplier"
+msgstr "Tedarikçiye Ödeme"
+
msgid "Payments"
msgstr "Ödemeler"
-msgid "Payments and credits applied to this invoice. Click a row to open the source document."
-msgstr "Bu faturaya uygulanan ödemeler ve krediler. Kaynak belgeyi açmak için bir satıra tıklayın."
+msgid "Payments and credits applied to this invoice. Applied amounts and FX are in company base currency. Click a row to open the source document."
+msgstr "Bu faturaya uygulanan ödemeler ve alacaklar. Uygulanan tutarlar ve kur farkları şirketin temel para birimi cinsindendir. Kaynak belgeyi açmak için bir satıra tıklayın."
msgid "PDF"
msgstr "PDF"
@@ -13280,8 +13304,8 @@ msgstr "Kayıt"
msgid "Record a credit or debit memo against a customer or supplier. Applications to specific invoices are added after the memo is created."
msgstr "Bir müşteri veya tedarikçiye karşı kredi veya borç notu kaydedin. Belirli faturaların uygulamaları, not oluşturulduktan sonra eklenir."
-msgid "Record cash received from a customer (Receipt) or paid to a supplier (Disbursement). Applications to specific invoices are added after the payment is created."
-msgstr "Müşteriden alınan nakiti (Tahsilat) veya tedarikçiye ödenen nakiti (Tediye) kaydedin. Belirli faturaların uygulamaları ödeme oluşturulduktan sonra eklenir."
+msgid "Record a customer payment, supplier payment, or refund. Applications to invoices or memos are added after the payment is created."
+msgstr "Müşteri ödemesi, tedarikçi ödemesi veya iade kaydedin. Faturaların veya muhasebe notlarının uygulamaları, ödeme oluşturulduktan sonra eklenir."
msgid "Record deleted"
msgstr "Kayıt silindi"
@@ -13325,6 +13349,15 @@ msgstr "Yenile"
msgid "Refresh exchange rate"
msgstr "Döviz kurunu yenile"
+msgid "Refund from Supplier"
+msgstr "Tedarikçiden İade"
+
+msgid "Refund memos"
+msgstr "İade Muhasebe Notları"
+
+msgid "Refund to Customer"
+msgstr "Müşteriye İade"
+
msgid "Regenerate"
msgstr "Yeniden oluştur"
@@ -13829,9 +13862,15 @@ msgstr "Sürüm {revision}"
msgid "Revenue"
msgstr "Hasılat"
+msgid "Revenue account for shipping charged to customers"
+msgstr "Müşterilere yansıtılan kargo için hasılat hesabı"
+
msgid "Revenue and expenses over a period"
msgstr "Bir dönem içinde hasılat ve giderler"
+msgid "Revenue GL account credited for shipping charged to customers, posted on its own line; it must be a different account from the Sales default."
+msgstr "Müşterilere yapılan kargo masrafları için alacaklandırılan Hasılat muhasebe hesabı, kendi satırında muhasebeleştirilir; Satış varsayılanından farklı bir hesap olması gerekir."
+
msgid "Reverse all inventory adjustments"
msgstr "Tüm stok düzeltmelerini ters kayıt yap"
@@ -14719,9 +14758,6 @@ msgstr "Yüzeyleri seç"
msgid "Select the groups that should complete this training"
msgstr "Bu eğitimi tamamlaması gereken grupları seçin"
-msgid "Select the invoices this payment settles. Discount and write-off are in invoice currency."
-msgstr "Bu ödemenin kapattığı faturaları seç. İskonto ve Kayıttan Düşme fatura para birimindedir."
-
msgid "Select value"
msgstr "Değer seçin"
@@ -15095,6 +15131,12 @@ msgstr "Sevkiyat yöntemleri"
msgid "Shipping Notes"
msgstr "Sevkiyat Notları"
+msgid "Shipping Revenue"
+msgstr "Kargo hasılatı"
+
+msgid "Shipping Revenue (default)"
+msgstr "Kargo hasılatı (varsayılan)"
+
msgid "Shipping Supplier"
msgstr "Nakliye Tedarikçisi"
@@ -16126,6 +16168,9 @@ msgstr "Vergi Yüzdesi"
msgid "Tax Residual Value %"
msgstr "Vergi Kalıntı Değeri %"
+msgid "Tax Status"
+msgstr "Vergi Durumu"
+
msgid "Tax Useful Life (default)"
msgstr "Vergi faydalı ömrü (varsayılan)"
@@ -18481,6 +18526,11 @@ msgstr "Kullanıcının herkese açık profilinde görünür"
msgid "Void"
msgstr "Hükümsüz kıl"
+#. placeholder {0}: initialValues.memoId
+#. placeholder {0}: initialValues.paymentId
+msgid "Void {0}"
+msgstr "Hükümsüz Kıl {0}"
+
msgid "Void Invoice"
msgstr "Faturayı hükümsüz kıl"
diff --git a/packages/locale/locales/zh/erp.po b/packages/locale/locales/zh/erp.po
index 7f118e92d0..b9764abb1c 100644
--- a/packages/locale/locales/zh/erp.po
+++ b/packages/locale/locales/zh/erp.po
@@ -1850,12 +1850,18 @@ msgstr "已应用"
msgid "Applied amount for {0}"
msgstr "已应用金额 {0}"
+msgid "Applied amounts are in company base currency ({baseCurrency})."
+msgstr "应用的金额采用公司基础货币({baseCurrency})。"
+
msgid "Applied Date"
msgstr "应用日期"
msgid "Applied To"
msgstr "应用于"
+msgid "Applied, discount and write-off amounts are in company base currency ({baseCurrency})."
+msgstr "已应用金额、折扣和核销金额均以公司基本货币({baseCurrency})表示。"
+
msgid "Applies to"
msgstr "适用于"
@@ -2380,6 +2386,12 @@ msgstr "你确定要向这些用户发送邀请吗?"
msgid "Are you sure you want to send an invite to this user?"
msgstr "你确定要向此用户发送邀请吗?"
+msgid "Are you sure you want to void this memo? This will reverse its accounting entries and applications. This cannot be undone."
+msgstr "你确定要作废此备忘录吗?这将反转其会计分录和应用。此操作无法撤销。"
+
+msgid "Are you sure you want to void this payment? This will reverse its accounting entries and applications. This cannot be undone."
+msgstr "你确定要作废此付款吗?这将反转其会计分录和应用。此操作无法撤销。"
+
msgid "Are you sure you want to void this purchase invoice? This action will reverse all financial transactions and cannot be undone."
msgstr "您确定要作废此采购发票吗?此操作将反转所有财务交易,无法撤销。"
@@ -3440,9 +3452,6 @@ msgstr "清除搜索查询"
msgid "Clear selection"
msgstr "清除选择"
-msgid "Clear this invoice with the party's posted credits as well as cash. Credits apply directly — no posting needed."
-msgstr "用交易对方的已过账信用余额和现金清偿此发票。信用直接应用 — 无需过账。"
-
msgid "Clear value"
msgstr "清除值"
@@ -4600,6 +4609,9 @@ msgstr "当制造费用吸收入在制品时的贷方科目"
msgid "Credit accounts used when manufacturing costs are absorbed into WIP"
msgstr "当制造成本吸收入在制品时使用的贷方科目"
+msgid "Credit amounts are in company base currency ({currency}). Credits take effect when this payment posts."
+msgstr "抵扣金额以公司基本货币({currency})表示。此付款过账后,抵扣才会生效。"
+
msgid "Credit Memo"
msgstr "贷项凭证"
@@ -8564,6 +8576,9 @@ msgstr "库存"
msgid "Inv Rate"
msgstr "发票汇率"
+msgid "Invalid applications"
+msgstr "无效应用"
+
msgid "Invalid Invite"
msgstr "无效邀请"
@@ -10854,6 +10869,9 @@ msgstr "没有人员可分配"
msgid "No open invoices"
msgstr "没有未结发票"
+msgid "No open memos"
+msgstr "无未结单据"
+
msgid "No open orders for this item are available to link."
msgstr "此物料没有未结订单可供链接。"
@@ -11965,6 +11983,9 @@ msgstr "付款应用"
msgid "Payment Date"
msgstr "付款日期"
+msgid "Payment from Customer"
+msgstr "来自客户的付款"
+
msgid "Payment ID"
msgstr "付款ID"
@@ -11986,11 +12007,14 @@ msgstr "付款条件"
msgid "Payment terms like Net 30 or due on receipt"
msgstr "付款条件,如净30天或收货即付"
+msgid "Payment to Supplier"
+msgstr "向供应商付款"
+
msgid "Payments"
msgstr "付款"
-msgid "Payments and credits applied to this invoice. Click a row to open the source document."
-msgstr "应用于此发票的付款和贷方。单击一行以打开源单据。"
+msgid "Payments and credits applied to this invoice. Applied amounts and FX are in company base currency. Click a row to open the source document."
+msgstr "分配至此发票的付款和抵扣款。已分配金额和汇兑差额均以公司基本货币表示。点击某一行以打开源单据。"
msgid "PDF"
msgstr "PDF"
@@ -13280,8 +13304,8 @@ msgstr "录音"
msgid "Record a credit or debit memo against a customer or supplier. Applications to specific invoices are added after the memo is created."
msgstr "针对客户或供应商记录贷方或借方备忘录。对特定发票的应用在创建备忘录后添加。"
-msgid "Record cash received from a customer (Receipt) or paid to a supplier (Disbursement). Applications to specific invoices are added after the payment is created."
-msgstr "记录从客户收到的现金(收据)或支付给供应商的现金(支付)。对特定发票的应用在创建付款后添加。"
+msgid "Record a customer payment, supplier payment, or refund. Applications to invoices or memos are added after the payment is created."
+msgstr "记录客户付款、供应商付款或退款。付款创建后,可以添加对发票或单据的应用。"
msgid "Record deleted"
msgstr "记录已删除"
@@ -13325,6 +13349,15 @@ msgstr "刷新"
msgid "Refresh exchange rate"
msgstr "刷新汇率"
+msgid "Refund from Supplier"
+msgstr "来自供应商的退款"
+
+msgid "Refund memos"
+msgstr "退款单据"
+
+msgid "Refund to Customer"
+msgstr "向客户退款"
+
msgid "Regenerate"
msgstr "重新生成"
@@ -13829,9 +13862,15 @@ msgstr "修订版 {revision}"
msgid "Revenue"
msgstr "收入"
+msgid "Revenue account for shipping charged to customers"
+msgstr "向客户收取的运输费用收入科目"
+
msgid "Revenue and expenses over a period"
msgstr "期间的收入和费用"
+msgid "Revenue GL account credited for shipping charged to customers, posted on its own line; it must be a different account from the Sales default."
+msgstr "用于向客户收取的运费收入贷记的总账科目,已过账显示在单独行;必须与销售默认账户不同。"
+
msgid "Reverse all inventory adjustments"
msgstr "反转所有库存调整"
@@ -14719,9 +14758,6 @@ msgstr "选择表面"
msgid "Select the groups that should complete this training"
msgstr "选择应该完成此培训的组"
-msgid "Select the invoices this payment settles. Discount and write-off are in invoice currency."
-msgstr "选择此付款结算的发票。折扣和核销以发票货币计。"
-
msgid "Select value"
msgstr "选择值"
@@ -15095,6 +15131,12 @@ msgstr "发货方式"
msgid "Shipping Notes"
msgstr "运输备注"
+msgid "Shipping Revenue"
+msgstr "运输收入"
+
+msgid "Shipping Revenue (default)"
+msgstr "运输收入(默认)"
+
msgid "Shipping Supplier"
msgstr "运输供应商"
@@ -16126,6 +16168,9 @@ msgstr "税收百分比"
msgid "Tax Residual Value %"
msgstr "税务残值 %"
+msgid "Tax Status"
+msgstr "税状态"
+
msgid "Tax Useful Life (default)"
msgstr "税使用年限(默认)"
@@ -18481,6 +18526,11 @@ msgstr "在用户的公开资料中可见"
msgid "Void"
msgstr "作废"
+#. placeholder {0}: initialValues.memoId
+#. placeholder {0}: initialValues.paymentId
+msgid "Void {0}"
+msgstr "作废 {0}"
+
msgid "Void Invoice"
msgstr "作废发票"
diff --git a/packages/utils/AGENTS.md b/packages/utils/AGENTS.md
index 69c668c9f7..a30274ed04 100644
--- a/packages/utils/AGENTS.md
+++ b/packages/utils/AGENTS.md
@@ -17,7 +17,7 @@ Pure utility functions shared across all Carbon packages and apps. Covers accoun
## Never
-- Import server-only packages (`@carbon/auth`, `@carbon/database`, `@carbon/kv`) from here — `@carbon/utils` must remain client-safe. **Deliberate exceptions:** `precision.ts`, `batch-time-split.ts`, and `batch-compatibility.ts` each re-export their namesake under `packages/database/supabase/functions/shared/` by relative path (`math.ts` consumes the former). Those files are dependency-free pure TS and live there because the Supabase edge runtime only mounts `supabase/functions/`; re-exporting rather than duplicating keeps ONE source of truth so the Node and Deno sides never drift. Not package imports and not something to "fix" (same pattern as `packages/database/src/sampling.ts`).
+- Import server-only packages (`@carbon/auth`, `@carbon/database`, `@carbon/kv`) from here — `@carbon/utils` must remain client-safe. **Deliberate edge-shared utilities:** `precision.ts`, `accounting-currency.ts`, `accounting-posting.ts`, `payment-funding.ts`, `sales-posting-amounts.ts`, `batch-time-split.ts`, and `batch-compatibility.ts` each re-export their namesake under `packages/database/supabase/functions/shared/` by relative path (`math.ts` consumes `precision.ts`). Those implementations live there because the Supabase edge runtime only mounts `supabase/functions/`; re-exporting rather than duplicating keeps ONE source of truth so the Node and Deno sides never drift. They are client-safe source imports, not imports of the server/database package, and not something to "fix" (same pattern as `packages/database/src/sampling.ts`). Keep their dependency graphs pure.
- Add async/IO operations — utilities should be synchronous pure functions (the one exception is `supabase.ts` helpers which are typed wrappers).
- Duplicate what already exists — check the barrel export (`src/index.ts`) before adding a new utility.
@@ -33,12 +33,17 @@ pnpm --filter @carbon/utils typecheck
| Module | Provides |
|--------|----------|
| `accounting` | Currency formatting, financial calculations |
+| `accounting-currency` | Explicit foreign-per-base conversion and settlement FX |
+| `accounting-posting` | Original journal role vocabulary: `classifyAccountingPostingRole` maps a journal line's description by EXACT match — `Accounts Receivable`/`IC Receivables` → Receivables, `Accounts Payable`/`IC Payables` → Payables, `Shipping Revenue`, `Sales Account` — and returns `null` for anything else, which is how a `VOID: …` reversal line falls out (there is no explicit void branch) |
+| `payment-funding` | Shared effective-settlement, invoice/funding balance reducers and exact document-principal allocation; callers own tenant/status/reservation queries |
+| `sales-posting-amounts` | Pure sales component normalization and posting calculations |
| `arrays` | Array manipulation, grouping, deduplication |
| `bom` | Bill of Materials traversal and level computation |
| `date` | Date formatting, parsing, range helpers (uses `@internationalized/date`); `HOUR_MS`/`DAY_MS` millisecond constants for instant arithmetic |
| `datetime` | Server-side date derivation with mandatory explicit timezone: `timestamp()`, `today(tz)`, `now(tz)`, `businessDay(instant, tz)`, `weekBounds(tz, offset?, anchor?)` (DST-safe Monday→Sunday instant bounds), `weekNumber(date)`. DST/exotic-zone stress suite in `datetime.test.ts` (gap/overlap disambiguation, midnight-skipping zones, 167/169h weeks, ±30/45-min offsets). Mirrored for Deno at `packages/database/supabase/functions/lib/datetime.ts` — keep in sync |
| `hash` | The repo's stable content hashes — `fnv1a32`/`fnv1a64` (cache and idempotency keys) and `getBucket`. Browser-safe; never add `node:crypto` here |
-| `math` | `clamp`/`lerp`/`inverseLerp`, plus the whole numeric-precision API re-exported from the edge-runtime module: `SCALE`, `EPSILON`, `round`, `scrapAllowance`, `applyRate`, `deriveRate`, `isBalanced`, `assertBalanced`, `RoundingMode` (re-exported from `precision.ts`) |
+| `math` | `clamp`/`lerp`/`inverseLerp` only — it re-exports nothing |
+| `precision` | The whole numeric-precision API, re-exported from the edge-runtime module: `SCALE`, `EPSILON`, `RoundingMode`, `round`, `distributeRoundingResidual`, `scrapAllowance`, `applyRate`, `deriveRate`, `isBalanced`, `assertBalanced` |
| `format` | The ONLY place display/input digit counts are chosen: `moneyFormatOptions` (settlement — the currency's decimals are floor AND ceiling), `rateFormatOptions` (per-unit RATE — those decimals are only the floor, ceiling is `SCALE`), the `PERCENT_FORMAT` / `PERCENT_POINTS_FORMAT` / `SCALE_FORMAT` constants, `cldrCurrencyDecimals`, their `format*` helpers, and `INPUT_FORMAT` / `INPUT_STEP` for editable fields. Call sites pick a KIND, never a digit count |
| `string` | Slugify, truncate, camelCase/titleCase conversions |
| `revalidate` | `isSearchParamOnlyNavigation` — shared by both apps' shell `shouldRevalidate` |
diff --git a/packages/utils/src/accounting-currency.ts b/packages/utils/src/accounting-currency.ts
new file mode 100644
index 0000000000..dc9f13d55c
--- /dev/null
+++ b/packages/utils/src/accounting-currency.ts
@@ -0,0 +1,2 @@
+// Shared with posting functions; this module has no database/runtime dependencies.
+export * from "../../database/supabase/functions/shared/accounting-currency.ts";
diff --git a/packages/utils/src/accounting-posting.ts b/packages/utils/src/accounting-posting.ts
new file mode 100644
index 0000000000..2bed82c619
--- /dev/null
+++ b/packages/utils/src/accounting-posting.ts
@@ -0,0 +1,2 @@
+// Pure original-journal role classification shared with posting functions.
+export * from "../../database/supabase/functions/shared/accounting-posting.ts";
diff --git a/packages/utils/src/index.ts b/packages/utils/src/index.ts
index 6fd1a0c73f..0f8ed0bbab 100644
--- a/packages/utils/src/index.ts
+++ b/packages/utils/src/index.ts
@@ -1,4 +1,6 @@
export * from "./accounting";
+export * from "./accounting-currency";
+export * from "./accounting-posting";
export * from "./address";
export * from "./all";
export * from "./arrays";
@@ -25,9 +27,11 @@ export * from "./labels";
export * from "./llm";
export * from "./math";
export * from "./object";
+export * from "./payment-funding";
export * from "./precision";
export * from "./receiving";
export * from "./revalidate";
+export * from "./sales-posting-amounts";
export * from "./ssr";
export * from "./status";
export * from "./status-colors";
diff --git a/packages/utils/src/payment-funding.ts b/packages/utils/src/payment-funding.ts
new file mode 100644
index 0000000000..a8ee91c81e
--- /dev/null
+++ b/packages/utils/src/payment-funding.ts
@@ -0,0 +1,2 @@
+// Shared with posting functions; allocation is pure and receives validated snapshots.
+export * from "../../database/supabase/functions/shared/payment-funding.ts";
diff --git a/packages/utils/src/sales-posting-amounts.ts b/packages/utils/src/sales-posting-amounts.ts
new file mode 100644
index 0000000000..2ee6f87710
--- /dev/null
+++ b/packages/utils/src/sales-posting-amounts.ts
@@ -0,0 +1,2 @@
+// Shared arithmetic and journal construction used by sales posting and provider boundaries.
+export * from "../../database/supabase/functions/shared/sales-posting-amounts.ts";
diff --git a/scripts/lib/service-metadata.ts b/scripts/lib/service-metadata.ts
index db4a5aed76..f730dd3e35 100644
--- a/scripts/lib/service-metadata.ts
+++ b/scripts/lib/service-metadata.ts
@@ -100,6 +100,11 @@ const INJECT_AUTH_OVERRIDES: Record<string, AuthField[]> = {
inventory_insertManualInventoryAdjustment: ["companyId", "createdBy"],
accounting_upsertFixedAssetUsageLog: ["companyId", "createdBy"],
account_upsertNotificationPreference: ["companyId"],
+ // Both operations replace settlement rows in a transaction. Their verbs do
+ // not imply INSERT to the name-based rule, but the service requires the
+ // authenticated creator for every replacement row.
+ invoicing_replaceInvoiceSettlements: ["companyId", "createdBy"],
+ invoicing_applyCreditsToInvoices: ["companyId", "createdBy"],
};
// service-module → permission-module. `items` operations are gated by the `parts`
diff --git a/scripts/run-local-accounting-check.ts b/scripts/run-local-accounting-check.ts
new file mode 100644
index 0000000000..57579243ee
--- /dev/null
+++ b/scripts/run-local-accounting-check.ts
@@ -0,0 +1,28 @@
+// Run from the repository root against an existing local database; never creates or resets it.
+import { spawnSync } from "node:child_process";
+import { config } from "dotenv";
+
+config({ path: ".env" });
+config({ path: ".env.local", override: true });
+const dbUrl = process.env.SUPABASE_DB_URL;
+if (!dbUrl) throw new Error("An existing local SUPABASE_DB_URL is required");
+const connection = new URL(dbUrl);
+if (!["localhost", "127.0.0.1", "[::1]"].includes(connection.hostname)) {
+ throw new Error("An existing local SUPABASE_DB_URL is required");
+}
+const [command, ...args] = process.argv.slice(2);
+if (!["psql", "deno", "pnpm"].includes(command ?? "")) throw new Error("Expected a local accounting verification command");
+const result = spawnSync(command, args, {
+ env: {
+ ...process.env,
+ PGHOST: connection.hostname,
+ PGPORT: connection.port || "5432",
+ PGUSER: decodeURIComponent(connection.username),
+ PGPASSWORD: decodeURIComponent(connection.password),
+ PGDATABASE: decodeURIComponent(connection.pathname.slice(1)),
+ PGCONNECT_TIMEOUT: "5"
+ },
+ stdio: "inherit"
+});
+if (result.error) throw new Error("Could not launch local accounting check");
+process.exit(result.status ?? 1);