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.
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.
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 !== isARrefusal is treated as an accidental regression, not a deliberate scope reduction. sourceAmountbackfill: 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)
- Add
distributeRoundingResidual(exactValues, target, scale)topackages/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.tsis the sanctioned home (it is exempt fromno-raw-roundingas the implementation of rounding). - Unit tests in
shared/precision.test.ts. - Rewrite
reconcileDocumentinpackages/ee/src/accounting/core/sales-document-components.tsto allocate net and tax through the new helper instead of concentrating the whole residual on one component. - Derive
unitAmountfrom the reconcilednetAmountinstead of throwing when the storedconvertedUnitPricemirror and the computed net straddle a rounding tie. - Verify:
pnpm --dir packages/ee exec vitest run src/accountingand a regression test proving 20 × $1.99 @ 8.25% keeps every component within one minor unit ofround(net × taxPercent).
T2 — Intercompany matching scale (Must fix #2)
-
shared/sales-posting-amounts.ts—calculateSalesIntercompanyAmountrounds atSCALE, matching the buyer'sround(...)inpost-purchase-invoice/index.ts:2022. The IC amount is an exact matching key, not a settlement amount. - Drop the now-unused
currencyDecimalsparameter and update the call site. - Verify: new test asserting both sides agree on a 5dp document amount.
T3 — Restore refund applications (Must fix #3)
- Remove the
cashIn !== isARrefusal inpost-payment/post-payment-transaction.ts; the two-axis journal logic inbuild-payment-journal.tsalready handles it. - Regression test covering a Disbursement settling a sales invoice and a Receipt settling a purchase invoice.
T4 — Rillet money precision (Must fix #5)
-
providers/rillet/entities/shared.ts— remove thedecimalPlaces = 2default so the scale is always supplied; replace thetoDocumentAmount(0, rate, 2)scale literal intoRilletExchangeRate. - Thread real
decimalPlacesthroughentities/payment.tsandentities/item.ts.
T5 — On-account control description (Must fix #6)
- Add the on-account credit role to
shared/accounting-posting.tsand use it from bothpost-payment-transaction.tsandbuild-payment-journal.ts.
T6 — Report SQL (Must fix #7, #8)
- New migration: align the AR/AP tie-out
payment_unappliedparty filters with their aging counterparts. -
ALTER COLUMN "fxGainLossAmount" SET NOT NULL(safe: the column wasGENERATED ALWAYSso no row can be NULL). - Replace the eight bare
round(x,5)scale literals with a namedaccounting_internal_scale()helper.
T7 — Cheap wins
- Delete dead defaults writers
updateDefaultBalanceSheetAccounts(zero callers) andupdateDefaultIncomeAccounts(test-only), both still MCP-exposed as unvalidated/duplicateWRITEtools. - Delete dead
getSettledInvoiceStatusand its baselined raw-rounding violations. - Export
assertExchangeRate/assertCurrencyDecimalsfromshared/accounting-currency.tsand replace the discarded-conversion validation sites with named assertions. - Docs freshness:
payments.mdx(settlement field table, the CHECK sentence, the FX plug sentence),accounting.mdx(shipping revenue), glossary term, and the two unsupportedpackages/utils/AGENTS.mdclaims.
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
rowsstate and raw engine errors surfaced to users,new.tsxloader/action asymmetry,getCompanyHasOpenCreditsregression, unboundedFOR UPDATE, the Xero explicitCurrencyRate: 1reversal and 3-decimal refusal, the inbound XerotaxPercent100x, and the two questionable new MCP tools. - The structural items — edge-function extraction,
invoicing.service.ts(3,188 lines) andaccounting.ee.service.ts(6,849 lines) splits, the duplicated currency-decimals loader and double-spend block, and wiringapps/erp+packages/databaseinto CI'sturbo run test(todaypnpm testruns neither, so ~7,400 lines of this branch's tests are unenforced — the single highest-leverage follow-up). sourceAmountbackfill — 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, thex/schedule→x/priorityroute move plus in-process scheduling). It renamedpath.to.scheduleDatesUpdate→priorityDatesUpdateand replacedinvoke("schedule")withrunLocationSchedule. Two test files were never re-pointed. Indrag-lifecycle.test.tsxthe stale~/utils/pathmock madepath.to.priorityDatesUpdateundefined, which both blanked the submittedactionAND 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.tsasserted a ZodError is suppressed entirely. The code deliberately surfaces a compactzodIssueSummaryinstead — documented at length inresponse.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.tsbanned the@lingui/core/macroMODULE, flagging 284 files for importingmsg— the exact pattern.claude/rules/i18n-lingui-system.mdprescribes for route breadcrumbs. The gate contradicted the documented convention, so it could never pass. Narrowed to what the rule actually prohibits:tfromcore/macro(0 offenders) and unwrapping a literal at runtime,i18n._(msg…)(3 offenders, fixed —i18n._(dynamicDescriptor)from a lookup map, as inworkflows/ui/Builder/catalog.ts, is legitimate and is deliberately not matched).localized-submodule-ui.test.tshad two bugs..test()on a shared/gregex 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 resettinglastIndex, 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_URLgate throwing. They now SKIP viadatabaseTest(ignore: !hasLocalDatabase) — a baredeno testis 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.jsongains"test": "vitest run".turbo run testpicks it up, so the existingtestjob in.github/workflows/check.ymlgains 990 tests with no infrastructure change (pnpm test: 28/28 tasks, was 27).- New
edge-functionsjob incheck.yml—denoland/setup-denothendeno task testfrompackages/database/supabase/functions, covering 257 tests (20 DB-backed ones skip). Deliberately NOT added toturbo run test, sopnpm testkeeps working for anyone without Deno installed. deno.json'stesttask is nowdeno 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.hasLocalDatabasecatchesPermissionDeniedas well as an absent variable, because it runs at module scope — without that,deno testwith 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.