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 Cutover — implementation plan
Spec: .ai/specs/implemented/2026-10-08-accounting-cutover.md Research: .ai/research/accounting-cutover.md Branch: accounting-reset-plan
Terms
This plan uses each term below with one meaning only.
| Term | Meaning |
|---|---|
| The cutover | The company's companySettings.accountingCutoverDate, the first day of a fiscal period. "Before the cutover" and "on or after the cutover" compare a posting date with this date. A company with no cutover has a null date. The UI calls it the "cutover date". |
| The accounting reset | The migration 20261008211304_reset-accounting.sql. It deleted the journals of every company except the demo-template companies and turned accounting off. |
| Inventory reset | Step 2 of the enable. It closes the cost layers dated before the cutover and opens one layer per item. |
| L | The createdAt of the company's first Provisional or Superseded journal. If the company has none, L is now. |
| The enable | The activate-accounting server function. It runs in one Kysely transaction and sets the cutover. |
| The enable wizard | The 5 steps under /x/accounting/activation: Readiness, Inventory, Fixed Assets, Trial Balance, Enable. The short form is "the wizard". |
| Stand-in line | A journal line on retainedEarningsAccount whose accountDefaultRole names the empty default it wanted. Only a Provisional journal has one. |
| Re-cost | The enable's new valuation of each outbound movement dated on or after the cutover, against the reset cost layers. |
| Legacy document | A posted document dated on or after the cutover that has no journal line under its document keys. |
| Legacy backfill | Step 1a of the enable. It writes the journal of each legacy document, as Provisional. |
| The repair | The journal-legacy-documents server function. It runs the legacy backfill again for a company that has a cutover already. |
Progress
Phase A — Foundation (no behavior change)
- Task 1: Add the Provisional and Superseded journal statuses
- Task 2: Add the cutover columns, the stand-in role column, triggers and the status function
- Task 3: Add Migration Clearing to the seed data
- Task 4: Regenerate the database types
- Task 5: Add the journal status lists and
journalPostingStatus - Task 6: Change the SQL readers that filter on
<> 'Draft' - Task 7: Exclude the new statuses from the dataset coverage check
- Task 8: Add the
journal-status-filterconformance check - Task 9: Change the journal readers in the server functions
- Task 10: Change the journal counts in the ERP period services
Phase B — Post journals for every company
- Task 11: Always post in the shared adjustment journal and its callers
- Task 12: Always post in
post-receipt - Task 13: Always post in
post-shipment - Task 14: Always post in
post-sales-invoice - Task 15: Always post in
post-purchase-invoice - Task 16: Always post in
post-paymentandpost-memo - Task 17: Always post in
post-chargeandpost-reimbursement - Task 18: Always post in
issue - Task 19: Always post in
close-jobandpost-production-event - Task 20: Always post in
post-asset-transferandpost-rental-agreement - Task 21: Always post in the SQL job-costing functions
- Task 22: Always post in the ERP fixed-asset paths, Stripe fees and the revenue recognition cron
- Task 23: Refuse manual accounting work before the cutover
- Task 24: Prove a company with no cutover can post every document
Phase C — The cutover
- Task 25: Accept the Opening Balance source type in the AR/AP readers and payment lookups
- Task 26: Add the pure cutover planner
- Task 27: Add the cutover read services
- Task 28: Add the
activate-accountingserver function - Task 29: Handle voids of documents dated before the cutover
- Task 30: Start depreciation at the cutover
- Task 31: Build the 5-step enable wizard
Phase D — Retire the flag
- Task 32: Replace every ERP read of
accountingEnabled - Task 33: Remove Mark Paid and Mark Unpaid
- Task 34: Replace the settings switch
- Task 35: Set the cutover for new companies and demo datasets
- Task 36: Show the Provisional and Superseded statuses
- Task 37: Update the docs, rules and AGENTS.md files
Phase E — Verify
- Task 38: Run every gate and verify the enable flow in the browser
Phase F — Legacy documents on or after the cutover (spec section 5a)
- Task 39: Write the journals of legacy sales and purchase invoices at enable
- Task 40: Write the journals of legacy memos, payments, charges and reimbursements
- Task 41: Write the journals of legacy movements that stored a cost row
- Task 42: Write the cost rows and journals of legacy movements that stored none
- Task 43: Write the journals of legacy asset and revenue runs again
- Task 44: Show the legacy journals in the enable wizard and update the docs
- Task 45: Verify the legacy window in the browser
Dependencies
- Task 1 must commit before Task 2. Postgres refuses a new enum value in the transaction that adds it.
- Task 4 needs Tasks 1–3. Every later task needs Task 4.
- Tasks 6, 7, 8, 9 and 10 need Task 5. They are independent of each other.
- 🛑 Phase B (Tasks 11–24) must not start until every Phase A task is done. A Provisional journal written before the readers change counts in the balances.
- Tasks 11–20 need Task 5 and are independent of each other. Task 21 needs Task 2.
- Task 24 needs Tasks 11–23.
- Phase C needs Phase B. Task 28 needs Tasks 26 and 27. Task 31 needs Tasks 27 and 28.
- Phase D needs Task 31. Tasks 32–37 are independent of each other.
- Task 38 needs every other task.
Shared conventions for every task
- Run every command from the repository root
/Users/barbinbrad/conductor/workspaces/carbon/lagos. - Create each migration with
pnpm db:migrate:new <name>. Never pick a timestamp by hand. - Apply migrations with
pnpm db:migrate. It needs the local stack (crbn up). If the stack is down, STOP and ask the user to start it. - Typecheck one package at a time:
pnpm exec turbo run typecheck --filter=<pkg>. Never run a whole-repo typecheck. - Before you write a journal line, read 2 sections of
.ai/lessons.md:- "Journal debit/credit is derived from account class + amount sign"
- "Carbon journal amounts are natural-balance-signed"
- A server function database test uses
databaseTestfrompackages/server-functions/src/local-database-test-fixture.ts. It skips without a local database. Run it with the stack up. - The 3 status lists from Task 5 are the only allowed journal status filters in new code.
Task 1: Add the Provisional and Superseded journal statuses
Depends on: none Files:
- Create:
packages/database/supabase/migrations/<timestamp>_journal-provisional-status.sql - Copy from (precedent):
packages/database/supabase/migrations/20260901165008_opening-balance-source-type.sql
Steps:
- Run
pnpm db:migrate:new journal-provisional-status. - Write this SQL in the new file:
-- A journal written before the company's accounting cutover counts nowhere -- (Provisional). At the cutover, Provisional journals dated before the -- cutover date become Superseded. See .ai/specs/implemented/2026-10-08-accounting-cutover.md. ALTER TYPE "journalEntryStatus" ADD VALUE IF NOT EXISTS 'Provisional'; ALTER TYPE "journalEntryStatus" ADD VALUE IF NOT EXISTS 'Superseded'; - Run
pnpm db:migrate.
Verify:
docker exec carbon-carbon-accounting-reset-plan-postgres-1 psql -U postgres -d postgres -Atc "select enum_range(null::\"journalEntryStatus\")"
# Expected: {Draft,Posted,Reversed,Provisional,Superseded}
If the container has another name, find it with docker ps --format '{{.Names}}' | grep postgres.
Out of scope: any use of the new values. Task 2 uses them in a separate migration.
Task 2: Add the cutover columns, the stand-in role column, triggers and the status function
Depends on: Task 1 Files:
- Create:
packages/database/supabase/migrations/<timestamp>_accounting-cutover.sql - Copy from (precedent):
packages/database/supabase/migrations/20260712142905_reconcile-period-close-definitions.sql:22-63(check_posted_record_immutableand its 2 triggers)packages/database/supabase/migrations/20260713235930_close-snapshot-posting-lock.sql:33-100(check_accounting_period_open).ai/specs/archived/2026-07-04-accounting-cutover-activation.mdlines 140-169 (the config-lock trigger)
Steps:
- Run
pnpm db:migrate:new accounting-cutover. - Add the columns:
ALTER TABLE "companySettings" ADD COLUMN IF NOT EXISTS "accountingCutoverDate" DATE, ADD COLUMN IF NOT EXISTS "accountingActivatedAt" TIMESTAMP WITH TIME ZONE, ADD COLUMN IF NOT EXISTS "accountingActivatedBy" TEXT REFERENCES "user"("id"); ALTER TABLE "accountDefault" ADD COLUMN IF NOT EXISTS "migrationClearingAccount" TEXT; - Add the stand-in role column:
-- The accountDefault column a stand-in line wanted. Before the cutover, a -- posting that needs an empty default writes the line to -- retainedEarningsAccount and names the default here; the enable re-points -- it. Null on every other line. ALTER TABLE "journalLine" ADD COLUMN IF NOT EXISTS "accountDefaultRole" TEXT; - Do not create any account. Do not fill any
accountDefaultcolumn. Do not add NOT NULL to any column. Account numbers and names are user-editable, so a match by number can point a default at an unrelated account (spec Q7, revised). - Add the status function:
CREATE OR REPLACE FUNCTION journal_posting_status(p_company_id TEXT) RETURNS "journalEntryStatus" LANGUAGE sql STABLE SET search_path = public AS $$ SELECT CASE WHEN cs."accountingCutoverDate" IS NULL THEN 'Provisional'::"journalEntryStatus" ELSE 'Posted'::"journalEntryStatus" END FROM "companySettings" cs WHERE cs."id" = p_company_id; $$; - Copy
check_posted_record_immutablefrom20260712142905:22-53. Make 3 changes:- Line 32: refuse DELETE when
OLD."status" IN ('Posted', 'Reversed', 'Superseded'). - Before line 37: refuse any UPDATE when
OLD."status" = 'Superseded'. - Line 43: refuse a line change when
v_parent_status IN ('Posted', 'Reversed', 'Superseded'). KeepSECURITY DEFINERas in the source. Do not recreate the triggers; they call the function by name.
- Line 32: refuse DELETE when
- Copy
check_accounting_period_openfrom20260713235930:33-100. Change the early return at lines 60-65 to:
A change from Provisional to Posted now runs the closed-period check.AND NOT (OLD."status" IN ('Draft', 'Provisional') AND NEW."status" = 'Posted') THEN - Add the config-lock trigger. Adapt the July SQL: read
accountingActivatedAtfrom"companySettings"(cs."id" = company id), not fromcompany. Add 3 triggers:company, BEFORE UPDATE: refuse a change ofbaseCurrencyCodeonceaccountingActivatedAtis set.fiscalYearSettings, BEFORE UPDATE: refuse a change ofstartMonthonce it is set.companySettings, BEFORE UPDATE: refuse a change ofaccountingCutoverDate,accountingActivatedAtoraccountingActivatedByonceOLD."accountingActivatedAt"is set.
- Set the cutover of the demo-template companies:
The review fix in 38602af774 changed this filter. The committed migration selects a company that has aUPDATE "companySettings" cs SET "accountingCutoverDate" = sub."cutover", "accountingActivatedAt" = NOW(), "accountingActivatedBy" = 'system' FROM ( SELECT j."companyId", MIN(ap."startDate") AS "cutover" FROM "journal" j JOIN "accountingPeriod" ap ON ap."id" = j."accountingPeriodId" WHERE j."status" = 'Posted' GROUP BY j."companyId" ) sub WHERE sub."companyId" = cs."id" AND cs."accountingEnabled" = true AND cs."accountingCutoverDate" IS NULL;JE-SEED-%journal, notaccountingEnabled = true. See Execution notes. - Run
pnpm db:migrate.
Verify:
docker exec carbon-carbon-accounting-reset-plan-postgres-1 psql -U postgres -d postgres -Atc "select count(*) from information_schema.columns where table_name = 'journalLine' and column_name = 'accountDefaultRole' and is_nullable = 'YES'"
# Expected: 1
docker exec carbon-carbon-accounting-reset-plan-postgres-1 psql -U postgres -d postgres -Atc "select journal_posting_status(id) from company limit 1"
# Expected: Provisional or Posted (not empty)
docker exec carbon-carbon-accounting-reset-plan-postgres-1 psql -U postgres -d postgres -Atc "select count(*) from \"companySettings\" where \"accountingEnabled\" and \"accountingCutoverDate\" is null"
# Expected: 0
Out of scope: the SQL readers (Task 6), the AR/AP readers (Task 25), the job-costing functions (Task 21). Do not drop accountingEnabled. Do not create the Migration Clearing account in existing company groups.
Task 3: Add Migration Clearing to the seed data
Depends on: Task 2 Files:
- Modify:
packages/database/src/seed-data.ts— theaccountsarray (Equity block near line 1380) andaccountDefaults(lines 2125-2186)
Steps:
- In
accounts, add a leaf after account 3300:key: "3400",number: "3400",name: "Migration Clearing",class: "Equity",incomeBalance: "Balance Sheet",parentKey: "equity". Copy the remaining fields from account 3300. - In
accountDefaults, addmigrationClearingAccount: "3400". - Do not change
seed-company/index.tsordatasets/bootstrap.ts. Both readaccountDefaultsby key (seed-company/index.ts:441,bootstrap.ts:353-369).
Verify:
grep -n "migrationClearingAccount" packages/database/src/seed-data.ts
# Expected: 1 line
Out of scope: existing company groups. Their users pick or create Migration Clearing in the wizard (Task 31).
Task 4: Regenerate the database types
Depends on: Tasks 1–3 Files:
- Modify (generated):
packages/database/src/types.ts,packages/database/src/swagger-docs-schema.ts
Steps:
- Run
pnpm run generate:types.
Verify:
grep -c "accountingCutoverDate\|\"Provisional\"\|migrationClearingAccount" packages/database/src/types.ts
# Expected: a number greater than 3
pnpm exec turbo run typecheck --filter=@carbon/database
# Expected: Tasks: 1 successful (or more), 0 failed
Out of scope: hand edits of the generated files.
Task 5: Add the journal status lists and journalPostingStatus
Depends on: Task 4 Files:
- Modify:
packages/database/src/accounting-posting.ts— add the 3 status lists - Modify:
packages/database/src/accounting-posting.test.ts - Create:
packages/database/src/journal-posting-status.ts - Create:
packages/database/src/journal-posting-status.test.ts - Modify:
packages/database/package.json— add the export"./journal-posting-status": "./src/journal-posting-status.ts"next to"./accounting-posting"(line 54)
Steps:
- Add to
accounting-posting.ts:// Statuses a balance, report, snapshot, tie-out or sync counts. export const GL_JOURNAL_STATUSES = ["Posted", "Reversed"] as const; // Statuses a reader that follows one document's chain reads (void builders, // GR/IR, WIP sums, intercompany lookups). export const DOCUMENT_JOURNAL_STATUSES = ["Provisional", "Posted", "Reversed"] as const; // Statuses an open-item lookup reads (payment control lines, memo, charge // and reimbursement void checks). export const OPEN_ITEM_JOURNAL_STATUSES = ["Provisional", "Posted"] as const; - Keep
accounting-posting.tsfree of runtime database imports.@carbon/utilsre-exports it into client bundles. - Write
journal-posting-status.ts:export type AutomaticJournalStatus = "Provisional" | "Posted"; export function postingStatusFor(cutoverDate: string | null): AutomaticJournalStatus; export async function journalPostingStatus( db: Kysely<KyselyDatabase>, companyId: string ): Promise<AutomaticJournalStatus>;journalPostingStatusselectsaccountingCutoverDatefromcompanySettingswhereid = companyId, with.forShare(). It returnspostingStatusFor(row.accountingCutoverDate). If the row is missing, it throwsError("Company settings not found"). Also export the stand-in resolver:export const OPTIONAL_DEFAULT_ROLES = [ "contractAssetAccount", "deferredRevenueAccount", "deferredTaxExpenseAccountId", "deferredTaxLiabilityAccountId", "employeeReimbursementsPayableAccount", "intercompanyPayablesAccount", "intercompanyReceivablesAccount", "laborAbsorptionAccount", "leaseInterestIncomeAccount", "leaseRevenueAccount", "netInvestmentInLeasesAccount", "overheadAbsorptionAccount", "rentalIncomeAccount", "salesReturnsAccount", "salesShippingRevenueAccount", "scrapAccount", "migrationClearingAccount" ] as const; export type OptionalDefaultRole = (typeof OPTIONAL_DEFAULT_ROLES)[number]; export function resolveDefaultAccount( defaults: Partial<Record<OptionalDefaultRole, string | null>> & { retainedEarningsAccount: string }, role: OptionalDefaultRole, postingStatus: AutomaticJournalStatus ): { accountId: string; accountDefaultRole: OptionalDefaultRole | null };- If
defaults[role]is set, return it withaccountDefaultRole: null. - Else, if
rolehas a fallback inDEFAULT_FALLBACKS, return the fallback withaccountDefaultRole: null. This rule holds before and after the cutover. - Else, if
postingStatusis"Provisional", returnretainedEarningsAccountwithaccountDefaultRole: role. - Else throw
MissingAccountDefaultError(role). Its status is 400. Its message is "Set the
- If
- Import
Kyselyas a type only. ImportKyselyDatabasefrom./clientas a type. - Write tests:
postingStatusFor(null)is"Provisional";postingStatusFor("2026-10-01")is"Posted".- Each list has the members in step 1.
resolveDefaultAccountreturns the default when set, the stand-in with the role before cutover, and throws after cutover.
Verify:
pnpm --filter @carbon/database exec vitest run src/accounting-posting.test.ts src/journal-posting-status.test.ts
# Expected: all tests pass
pnpm exec turbo run typecheck --filter=@carbon/database
# Expected: 0 failed
Out of scope: using the helper (Phase B).
Task 6: Change the SQL readers that filter on <> 'Draft'
Depends on: Task 5 Files:
Create:
packages/database/supabase/migrations/<timestamp>_journal-gl-status-readers.sqlCopy from (precedent), the latest definition of each object:
Object Source Line(s) to change accountTreeBalances20260909173619_preserve_inactive_account_report_balances.sql:5-6343-45 accountTreeBalancesByCompanysame file :65-221123-125, 175 accountTreeBalancePeriodSeriessame file :223-352284 snapshotAccountingPeriodBalancessame file :354-408391 journalLinesByAccountNumber20260713225803_ledger-balance-posted-filter.sql:145-171162-164 journalDimensionPivot20260809204137_analytics-account-filter.sql:18-14366 journalDimensionPivotLinessame file :145-256200 get_inventory_tie_out20260925121735_rpc-function-guards.sql:1425-14861461 journalLinesview20260811123614_widen-ledger-amounts.sql:177-188188
Steps:
- Run
pnpm db:migrate:new journal-gl-status-readers. - Before you edit, record each function's security mode:
docker exec carbon-carbon-accounting-reset-plan-postgres-1 psql -U postgres -d postgres -Atc "select proname, prosecdef from pg_proc where proname in ('accountTreeBalances','accountTreeBalancesByCompany','accountTreeBalancePeriodSeries','snapshotAccountingPeriodBalances','journalLinesByAccountNumber','journalDimensionPivot','journalDimensionPivotLines','get_inventory_tie_out') order by 1" - Copy each function into the new migration. Replace each
<> 'Draft'or!= 'Draft'on a journal status withIN ('Posted', 'Reversed'). Change nothing else. - End each function with the security mode from step 2 (
SECURITY DEFINERwhenprosecdefist, elseSECURITY INVOKER).20260925121735:2781alteredsnapshotAccountingPeriodBalancesto INVOKER. - Keep the
assert_company_accesscall inget_inventory_tie_out(:1435). - For the
journalLinesview:DROP VIEW IF EXISTS "journalLines";thenCREATE VIEWwithWHERE j."status" IN ('Posted', 'Reversed'). CopyWITH (SECURITY_INVOKER=true)if the source has it. - If
DROP VIEWfails because another object depends on the view, STOP and report. - Run
pnpm db:migrate, thenpnpm run generate:types.
Verify:
docker exec carbon-carbon-accounting-reset-plan-postgres-1 psql -U postgres -d postgres -Atc "select count(*) from pg_proc where prosrc ilike '%status\" <> ''Draft''%' and proname in ('accountTreeBalances','accountTreeBalancesByCompany','accountTreeBalancePeriodSeries','snapshotAccountingPeriodBalances','journalLinesByAccountNumber','journalDimensionPivot','journalDimensionPivotLines','get_inventory_tie_out')"
# Expected: 0
# Then rerun the step 2 query. Expected: the same prosecdef values as before.
Out of scope: trialBalance (it reads accountTreeBalancesByCompany), the = 'Posted' AR/AP readers (Task 25), complete_job_to_inventory (Task 21).
Task 7: Exclude the new statuses from the dataset coverage check
Depends on: Task 4 Files:
- Modify:
packages/database/src/datasets/validate.ts:387-390 - Copy from (precedent):
validate.ts:196-198(shipmentStatuswith an exclusion)
Steps:
- Change
journalStatus: { values: enumValues("journalEntryStatus") }to pass exclusions:enumValues("journalEntryStatus", { Provisional: "a demo company starts with a cutover, so it posts no Provisional journal", Superseded: "only the enable turns a Provisional journal into Superseded" })
Verify:
pnpm db:check:datasets
# Expected: all 4 datasets pass (needs the local stack)
Out of scope: datasets/types.ts:1776 (JournalEntrySpec.status stays 3 values).
Task 8: Add the journal-status-filter conformance check
Depends on: Task 6 Files:
- Create:
packages/checks/src/conformance/journal-status-filter.ts - Create:
packages/checks/src/conformance/journal-status-filter.test.ts - Modify:
packages/checks/src/run.ts— register inCONFORMANCE_CHECKS(line 70) andTS_CHECKS(line 85) - Modify:
packages/checks/src/index.ts— export the check - Modify:
packages/checks/src/conformance/baseline.json(regenerated) - Copy from (precedent):
packages/checks/src/conformance/no-derived-percent-column.ts(SQL side),no-raw-rounding.ts:14-46(TS side)
Steps:
- Write one
ConformanceCheckwithid: "journal-status-filter". Itsscanbranches onfile.endsWith(".sql"). - SQL side: flag a line that matches
/"?status"?\s*(<>|!=)\s*'Draft'/. Flag it only when both of these are true:- The file mentions
"journal". - The migration is not older than the Task 6 migration.
- The file mentions
- Set
provenance.sinceto the timestamp of the Task 6 migration. Older files have false positives (jis also the alias ofjob). - TS side: flag a line in a file that contains the text
"journal". The line matches one of these:.neq("status", "Draft")"status", "<>", "Draft""status", "!=", "Draft"
- Set
messageto: "Filter journal status with GL_JOURNAL_STATUSES, DOCUMENT_JOURNAL_STATUSES or OPEN_ITEM_JOURNAL_STATUSES (@carbon/database/accounting-posting)." - Write 4 tests:
- one SQL hit;
- one SQL miss on an older file;
- one TS hit;
- one TS miss in a file without
"journal".
- Run
pnpm --filter @carbon/checks baseline. Read the diff ofbaseline.json. Each new entry must be an existing hit, never a line you wrote.
The review fix in 188a710e24 changed the check after this task. It now checks one statement at a time, not one line. It also sees a qualified or aliased journal status and raw SQL in TS.
Verify:
pnpm --filter @carbon/checks test
# Expected: all tests pass, including run.test.ts "introduces no NEW deprecated patterns"
Out of scope: fixing the baselined existing hits.
Task 9: Change the journal readers in the server functions
Depends on: Task 5
Files (all under packages/server-functions/src/):
| File:line | Today | Change to |
|---|---|---|
post-receipt/index.ts:340, :594 |
no filter | join journal, DOCUMENT_JOURNAL_STATUSES |
post-receipt/index.ts:1547 |
no filter | DOCUMENT_JOURNAL_STATUSES |
post-shipment/index.ts:3093, :4124, :4410 |
no filter | DOCUMENT_JOURNAL_STATUSES |
post-sales-invoice/index.ts:2375 |
no filter, no companyId |
DOCUMENT_JOURNAL_STATUSES and .where("companyId", "=", companyId) |
post-sales-invoice/index.ts:2420 |
no filter | DOCUMENT_JOURNAL_STATUSES |
post-purchase-invoice/index.ts:115, :906 |
no filter | DOCUMENT_JOURNAL_STATUSES |
post-sales-invoice/index.ts:2212; post-purchase-invoice/index.ts:2403, :2448 |
intercompany lookups | DOCUMENT_JOURNAL_STATUSES |
close-job/index.ts:66 |
no filter | DOCUMENT_JOURNAL_STATUSES |
post-production-event/index.ts:206, :229 |
no filter, no join | join journal, DOCUMENT_JOURNAL_STATUSES |
post-maintenance-event/index.ts:84 |
no filter, no join | join journal, DOCUMENT_JOURNAL_STATUSES |
post-asset-transfer/index.ts:1090 |
<> 'Draft' |
DOCUMENT_JOURNAL_STATUSES |
post-payment/post-payment-transaction.ts:162 |
no filter | DOCUMENT_JOURNAL_STATUSES |
post-payment/post-payment-transaction.ts:534, :810 |
= 'Posted' |
OPEN_ITEM_JOURNAL_STATUSES |
post-memo/post-memo-transaction.ts:147, :155 |
!== "Posted", no filter |
OPEN_ITEM_JOURNAL_STATUSES / DOCUMENT_JOURNAL_STATUSES |
post-charge/post-charge-void.ts:38, :44 |
!== "Posted", no filter |
OPEN_ITEM_JOURNAL_STATUSES / DOCUMENT_JOURNAL_STATUSES |
post-reimbursement/post-reimbursement-void.ts:63, :69 |
!== "Posted", no filter |
OPEN_ITEM_JOURNAL_STATUSES / DOCUMENT_JOURNAL_STATUSES |
Steps:
- Import the lists from
@carbon/database/accounting-posting. - For a Kysely reader, use
.where("journal.status", "in", [...LIST]). For a check on a loaded row, useLIST.includes(row.status). - For a reader with no
journaljoin, add.innerJoin("journal", "journal.id", "journalLine.journalId")with acompanyIdmatch, aspost-payment-transaction.ts:498-503does. - Do not change anything else in these files.
Verify:
pnpm exec turbo run typecheck --filter=@carbon/server-functions
# Expected: 0 failed
pnpm --filter @carbon/server-functions test
# Expected: the same pass count as before this task (database tests need the stack)
Out of scope: the accountingEnabled branches (Phase B).
Task 10: Change the journal counts in the ERP period services
Depends on: Task 5 Files:
- Modify:
apps/erp/app/modules/accounting/accounting.service.ts:2622-2624(getFiscalCalendarCommitted) - Modify:
apps/erp/app/modules/accounting/accounting.periods.test.ts
Steps:
- Add
.in("status", [...GL_JOURNAL_STATUSES])to the journal count ingetFiscalCalendarCommitted. - Leave
getAccountingPeriodDeletabilityas it is. A Provisional journal has no period, so it never blocks a delete. - Add a test: a Provisional journal does not commit the fiscal calendar.
Verify:
pnpm --filter erp exec vitest run app/modules/accounting/accounting.periods.test.ts
# Expected: all tests pass
Out of scope: other ERP readers (Task 32).
Tasks 11–20: the shared steps for "always post"
Each of Tasks 11–20 applies these steps to the files it lists. Read them once.
- Replace the function's
accountingEnabledread withconst postingStatus = await journalPostingStatus(trx, companyId);from@carbon/database/journal-posting-status. Call it inside the posting transaction, so theFOR SHARElock holds until commit. - If the function needs the status before its transaction opens, do these 3 things. (One example: the function resolves the accounting period first.)
- Read the status there with
journalPostingStatus(db, companyId). - Inside the transaction, call
assertPostingStatusUnchanged(trx, companyId, postingStatus). It reads the status again and throwsPOSTING_STATUS_CHANGED_ERROR("Accounting was just set up. Post the document again.") when the two differ. - Do not restructure the function.
The review fix in b9f897608c added
assertPostingStatusUnchanged. It replaced about 40 inline copies of this check.
- Read the status there with
- Delete each branch on the flag that the task lists. Keep the branch body and make it unconditional.
- At each journal insert the task lists, replace
status: "Posted"withstatus: postingStatus. KeeppostedAtandpostedBy. - A branch marked J* also resolved the accounting period. Resolve it only when
postingStatusis"Posted". A Provisional journal getsaccountingPeriodId: null, and no posting creates a period before the cutover (spec section 1 item 3). - If a builder reads one of the
OPTIONAL_DEFAULT_ROLESfromaccountDefault, change it in 3 ways:- Call
resolveDefaultAccount(defaults, role, postingStatus). - Write the returned
accountIdon the line. Write the returnedaccountDefaultRolein the line'saccountDefaultRolecolumn. - Remove an existing runtime fallback for that role only when
resolveDefaultAccountcovers the same case. KeepemployeeReimbursementsPayableAccount ?? payablesAccount(post-reimbursement-post.ts:80,post-payment-transaction.ts:1020) as it is. Since the review fix in b9f897608c,DEFAULT_FALLBACKSholds this fallback and 4 others.
- Call
- Run the task's Verify block. A test that set
accountingEnabled: falseand expected no journal now expects a Provisional journal. Update it.
Task 11: Always post in the shared adjustment journal and its callers
Depends on: Task 5
Files (under packages/server-functions/src/):
- Modify:
lib/post-adjustment.ts—createAdjustmentJournal(:124, status at :142) takes astatus: AutomaticJournalStatusargument - Modify:
post-inventory-adjustment/index.ts— flag :227/:257/:260; branches :262, :266, :275, :308, :311, :440 - Modify:
post-inventory-count/index.ts— flag :168-179; branches :180, :184, :189, :196, :221 - Modify:
post-nonconformance/index.ts— flag :127-172; branches :173, :177, :186, :216, :245 - Modify:
correct-stock-movement/index.ts— flag :157-262; branches :263, :267, :274, :305, :308 - Modify:
import-csv/stock-quantity-import.ts— flag :257-267; branches :268, :271, :274, :281, :306, :375, :492 - Modify:
recost-serial-unit/index.ts— flag :128-135,loadAccounting:249; branch :188 - Modify:
post-maintenance-event/index.ts— flag :40-46; early return :46 - Modify:
issue/index.ts— maintenance branch :1248 andvalueMaintenanceMovements:1202 only
Steps:
- Add the
statusargument tocreateAdjustmentJournal. Pass it to the insert at :134. valueMovement(:313) writes the journal only whenaccountingis non-null. Make every caller pass a non-nullaccountingobject, withpostingStatusfrom the shared steps.- Apply the shared steps to each listed file.
Verify:
pnpm exec turbo run typecheck --filter=@carbon/server-functions
# Expected: 0 failed
pnpm --filter @carbon/server-functions exec vitest run src/post-inventory-count src/post-inventory-adjustment src/import-csv src/post-maintenance-event src/issue
# Expected: all tests pass
grep -rn "accountingEnabled" packages/server-functions/src/lib/post-adjustment.ts packages/server-functions/src/post-inventory-adjustment packages/server-functions/src/post-inventory-count packages/server-functions/src/post-nonconformance packages/server-functions/src/correct-stock-movement packages/server-functions/src/import-csv/stock-quantity-import.ts packages/server-functions/src/recost-serial-unit packages/server-functions/src/post-maintenance-event
# Expected: no output
Out of scope: the job paths of issue (Task 18).
Task 12: Always post in post-receipt
Depends on: Task 5 Files:
- Modify:
packages/server-functions/src/post-receipt/index.ts— flag :98-104- Sales Return Order void: :404 (J*), :440
- Purchase Order void: :636
- Purchase Order post: :1506, :1510, :1521 (S, invoice-first maps), :1682 (and its else at :1793), :1944, :2009 (S, fixed asset cost and CIP rows), :2172 (J*), :2419
- Sales Return Order receipt: :2804, :2809, :3013, :3075 (J*), :3156
- Inbound Transfer: :3343, :3347, :3401, :3440, :3483 (J*), :3512
- Journal inserts: :447/:455, :1026/:1034, :2427/:2435, :3167/:3175, :3520/:3528
Steps:
- Apply the shared steps.
- At :1682, the else branch (:1793) consumed layers for a negative line when the flag was off. Keep one path: the body of the
ifalready relieves the layers throughnegativeReceiptConsumptions. Confirm no line consumes layers twice. - If both branches at :1682 relieve layers in different ways, STOP and report.
Verify:
pnpm exec turbo run typecheck --filter=@carbon/server-functions
# Expected: 0 failed
pnpm --filter @carbon/server-functions exec vitest run src/post-receipt
# Expected: all tests pass
grep -n "accountingEnabled" packages/server-functions/src/post-receipt/index.ts
# Expected: no output
Out of scope: the void cost-layer planner (void-cost-ledger.ts, done).
Task 13: Always post in post-shipment
Depends on: Task 5 Files:
- Modify:
packages/server-functions/src/post-shipment/index.ts- Flag reads: :232-239, :2023-2026, :2446-2449, :3103-3114, :4113-4116, :4398-4401
- Sales Order post: :241, :245, :251, :504 (S+J, COGS lines), :659 (S, fixed asset disposal), :1222 (S+J,
calculateCOGS:1251 andcostLedger:1281) - Sales Return Order post: :2028-2053, :2173 (J*), :2238, :2290
- Purchase Return Order post: :2455-2480, :2647 (J*), :2819, :2872
- Sales Order void: :3119, :3433 (J*), :3585
- Sales Return Order void: :4153 (J*), :4210
- Purchase Return Order void: :4456 (J*), :4513
- Journal inserts: :1305/:1313, :2300/:2313, :2882/:2890, :3596/:3604, :4245/:4253, :4548/:4556
Steps:
- Apply the shared steps.
- After the change, a sales-order shipment always calls
calculateCOGSand writes the SalecostLedgerrow. This is the intended change (spec Q2).
Verify:
pnpm exec turbo run typecheck --filter=@carbon/server-functions
# Expected: 0 failed
pnpm --filter @carbon/server-functions exec vitest run src/post-shipment
# Expected: all tests pass
grep -n "accountingEnabled" packages/server-functions/src/post-shipment/index.ts
# Expected: no output
Out of scope: post-shipment/rental-agreement.ts (no flag, no journal).
Task 14: Always post in post-sales-invoice
Depends on: Task 5 Files:
- Modify:
packages/server-functions/src/post-sales-invoice/index.ts— flag :113-121- Post setup: :173, :344 (S), :316, :320, :349, :401 (G), :504, :508, :527, :545, :551, :590 (S), :644 (S), :673
- Post lines: :1157 (S), :1233 (S+J), :1323, :1382 (S), :1483 (S), :1659 (J*)
- Post transaction: :1880 (S+J), :2144 (S)
- Void: :2512, :2568 (J*), :2782 (S), :2897 (S+J)
- Journal inserts: :1888/:1896, :2905/:2913
Steps:
- Apply the shared steps.
- The guard at :401 (company group and exchange-rate asserts) now runs for every company. If it can refuse an invoice that posts today with accounting off, STOP and report. Do not weaken it.
Verify:
pnpm exec turbo run typecheck --filter=@carbon/server-functions
# Expected: 0 failed
pnpm --filter @carbon/server-functions exec vitest run src/post-sales-invoice
# Expected: all tests pass
grep -n "accountingEnabled" packages/server-functions/src/post-sales-invoice/index.ts
# Expected: no output
Out of scope: rental-posting.ts, contract-posting.ts (pure, no flag).
Task 15: Always post in post-purchase-invoice
Depends on: Task 5 Files:
- Modify:
packages/server-functions/src/post-purchase-invoice/index.ts— flag :73-81- Void: :374, :449 (J*)
- Post: :946, :950, :1074, :1205 (S+J, purchase price variance children), :1545, :1651 (G), :1657 (S, fixed asset cost and CIP), :1979, :2051 (J*), :2186 (S+J, intercompany :2328-2494)
- Journal inserts: :500/:508, :2194/:2202
Steps:
- Apply the shared steps.
- The guard at :1651 refuses a Fixed Asset line with no asset. It now applies to every company. Keep it.
Verify:
pnpm exec turbo run typecheck --filter=@carbon/server-functions
# Expected: 0 failed
pnpm --filter @carbon/server-functions exec vitest run src/post-purchase-invoice
# Expected: all tests pass
grep -n "accountingEnabled" packages/server-functions/src/post-purchase-invoice/index.ts
# Expected: no output
Out of scope: none.
Task 16: Always post in post-payment and post-memo
Depends on: Task 5 Files:
- Modify:
packages/server-functions/src/post-payment/post-payment-transaction.ts— flag :108-113; branches :116 (J*), :144 (G), :644 (G), :987, :1156; inserts :170/:182, :1158/:1166 - Modify:
packages/server-functions/src/post-memo/post-memo-transaction.ts— flag :64-69; branches :72 (J*), :135 (G), :319 (S+J); inserts :165/:177, :560/:569 - Modify:
packages/server-functions/src/post-payment/post-payment-transaction.test.ts(the test at :169),post-memo/post-memo-transaction.test.ts(:234)
Steps:
- Apply the shared steps.
- Delete the refusals at :144 (payment) and :135 (memo). Each refused a void when a journal existed and the flag was off. A journal now always exists.
- Change the guard at :644 to:
if (postingStatus === "Posted" && !targetControlById.has(invoice.id)) { throw new Error("Target is missing its original control account"); } - When the company has no cutover and the target has no control line, use the default control account. Copy the fallback from
packages/database/src/build-payment-journal.ts:274-275. - If the journal builder cannot take a default control account for a target, STOP and report.
- Update the 2 tests. Each test sets up a company with no cutover and an invoice with no journal. A payment against the invoice must post a Provisional journal on the default receivables account.
Verify:
pnpm exec turbo run typecheck --filter=@carbon/server-functions
# Expected: 0 failed
pnpm --filter @carbon/server-functions exec vitest run src/post-payment src/post-memo
# Expected: all tests pass (with the stack up)
Out of scope: voids of documents dated before the cutover (Task 29).
The review fix in b9f897608c moved the payment and memo rebuilds into their own modules: post-payment/rebuild-journal.ts and post-memo/rebuild-journal.ts. Payment posting and the payment rebuild now share one input assembler, assemblePaymentJournal in post-payment/journal-input.ts. A parity test covers the 2.
Task 17: Always post in post-charge and post-reimbursement
Depends on: Task 5
Files (under packages/server-functions/src/):
- Modify:
post-charge/post-charge-transaction.ts(flag :60-84,context.accountingEnabled),post-charge/post-charge-post.ts(:149 J*; insert :211/:219),post-charge/post-charge-void.ts(:24 G; insert :66/:74) - Modify:
post-reimbursement/post-reimbursement-transaction.ts(flag :65-89),post-reimbursement-post.ts(:164 J*; insert :275/:283),post-reimbursement-void.ts(:49 G; insert :92/:100)
Steps:
- Replace
context.accountingEnabledwithcontext.postingStatus. - Apply the shared steps.
- Delete the refusals at
post-charge-void.ts:24andpost-reimbursement-void.ts:49.
Verify:
pnpm exec turbo run typecheck --filter=@carbon/server-functions
# Expected: 0 failed
pnpm --filter @carbon/server-functions exec vitest run src/post-charge src/post-reimbursement
# Expected: all tests pass (with the stack up)
Out of scope: the paid-out refusal at post-reimbursement-void.ts:21-44.
Task 18: Always post in issue
Depends on: Task 11 Files:
- Modify:
packages/server-functions/src/issue/index.ts- Flag reads: :2040-2052,
loadConsumeAccountingContext:1120/:2118, :2296-2309, :2587-2610, :3029-3041, :3421-3434, :4361-4374, :3935, :3980 - Branches: :385 (S+J), :1849 (S+J), :3331 (S+J), :4587 (S+J), :2838, :3477 (J*), :3643, :3676, :3988 (J*)
- Journal inserts: :525/:533, :812/:820, :2893/:2901, :3687/:3695
- Flag reads: :2040-2052,
Steps:
- Apply the shared steps.
issueJobOperationMaterials(:385) andcreateMaterialWipEntries(:603) now relieve cost layers for every company.
Verify:
pnpm exec turbo run typecheck --filter=@carbon/server-functions
# Expected: 0 failed
pnpm --filter @carbon/server-functions exec vitest run src/issue
# Expected: all tests pass
grep -n "accountingEnabled" packages/server-functions/src/issue/index.ts
# Expected: no output
Out of scope: the maintenance path (Task 11).
Task 19: Always post in close-job and post-production-event
Depends on: Task 9 Files:
- Modify:
packages/server-functions/src/close-job/index.ts— flag :34-52; early return :54; insert :158/:166 - Modify:
packages/server-functions/src/post-production-event/index.ts— flag :53-71; early return :73; insert :382/:396;postedToGL:267, :490
Steps:
- Delete both early returns.
- Apply the shared steps.
post-production-eventnow setspostedToGLfor every company.
Verify:
pnpm exec turbo run typecheck --filter=@carbon/server-functions
# Expected: 0 failed
grep -n "accountingEnabled" packages/server-functions/src/close-job/index.ts packages/server-functions/src/post-production-event/index.ts
# Expected: no output
Out of scope: complete_job_to_inventory (Task 21).
Task 20: Always post in post-asset-transfer and post-rental-agreement
Depends on: Task 11
Files (under packages/server-functions/src/):
- Modify:
post-asset-transfer/index.ts—loadAccounting:100-112; branches :530, :688, :926, :1088 (S,fixedAssetTransferandfixedAssetCipCost:1118-1189), :1355, :1446, :1499; journal viapostAssetJournal:178 - Modify:
post-rental-agreement/index.ts— flag :136-144, passed at :354; :483 (J*), :538, :658 (S), :697 (S) - Modify:
post-rental-agreement/return-unit.ts— flag :356-360, :403; :463, :592 - Modify:
post-rental-agreement/agreement.ts—postLeaseJournal:222 passes the status tocreateAdjustmentJournal:237
Steps:
loadAccountingreturns null today when the flag is off. Make it always return the accounting context, withpostingStatus.- Apply the shared steps.
Verify:
pnpm exec turbo run typecheck --filter=@carbon/server-functions
# Expected: 0 failed
pnpm --filter @carbon/server-functions exec vitest run src/post-asset-transfer src/post-rental-agreement src/lib
# Expected: all tests pass
grep -rn "accountingEnabled" packages/server-functions/src/post-asset-transfer packages/server-functions/src/post-rental-agreement
# Expected: no output
Out of scope: none.
Task 21: Always post in the SQL job-costing functions
Depends on: Task 4 Files:
- Create:
packages/database/supabase/migrations/<timestamp>_job-costing-always-post.sql - Copy from (precedent):
complete_job_to_inventory:20261006221601_complete-job-to-asset.sql:13-1132backflush_job_materials:20260805023439_company-timezone-sql-functions.sql:31-469
Steps:
- Run
pnpm db:migrate:new job-costing-always-post. - Copy
complete_job_to_inventory. Make 4 changes:- Delete the flag read and early return at :600-610. Delete the variable at :38.
- Replace
'Posted'in the journal inserts at :734 and :952 withjournal_posting_status(p_company_id). - If
journal_posting_status(p_company_id)is'Provisional', give those journals aNULLperiod. Create no period in that case. - Add
AND j."status" IN ('Provisional', 'Posted', 'Reversed')to the WIP sum at :873-880.
- Copy
backflush_job_materials. Delete the flag read and early return at :193-203. Replace'Posted'at :274 withjournal_posting_status(p_company_id). Insert aNULLperiod for a Provisional journal, as in step 2. - End
backflush_job_materialswithSECURITY INVOKER(set by20260925121735:2761). Checkcomplete_job_to_inventory's currentprosecdefand keep it. - Run
pnpm db:migrate, thenpnpm run generate:types.
Verify:
docker exec carbon-carbon-accounting-reset-plan-postgres-1 psql -U postgres -d postgres -Atc "select count(*) from pg_proc where proname in ('complete_job_to_inventory','backflush_job_materials') and prosrc ilike '%accountingEnabled%'"
# Expected: 0
Out of scope: sync_finish_job_operation (no flag).
Task 22: Always post in the ERP fixed-asset paths, Stripe fees and the revenue recognition cron
Depends on: Task 5 Files:
- Modify:
apps/erp/app/routes/x+/fixed-asset+/$fixedAssetId.register.tsx:99-119— always post the registration journal, with the status fromjournalPostingStatus(getDatabaseClient(), companyId) - Modify:
apps/erp/app/modules/accounting/accounting.server.ts—postAssetRegistration(:379) andpostDisposal(:198) take and write the status - Modify:
packages/ee/src/stripe-connect/payment.server.ts:255-259,:353-357— always resolve the fee account - Modify:
packages/jobs/src/inngest/functions/scheduled/revenue-recognition-proposal.ts:67-72— selectcompanySettingsids whereaccountingCutoverDateis not null (.not("accountingCutoverDate", "is", null)) - Modify:
packages/jobs/src/inngest/functions/scheduled/revenue-recognition-proposal.test.ts
Steps:
- Make each change above.
- Keep
companiesToPropose(companies, ids)as it is. Only the id source changes. - Update the comment above
companiesToProposeto say "only those with an accounting cutover".
Verify:
pnpm exec turbo run typecheck --filter=erp --filter=@carbon/ee --filter=@carbon/jobs
# Expected: 0 failed
pnpm --filter @carbon/jobs exec vitest run src/inngest/functions/scheduled/revenue-recognition-proposal.test.ts
# Expected: all tests pass
Out of scope: the UI reads of the flag (Task 32).
Task 23: Refuse manual accounting work before the cutover
Depends on: Task 4 Files:
- Modify:
apps/erp/app/modules/accounting/accounting.service.ts— addrequireAccountingCutoverand call it - Modify:
apps/erp/app/modules/accounting/accounting.server.ts— call it - Modify:
packages/server-functions/src/propose-revenue-recognition-run/index.ts,packages/server-functions/src/recalculate-revenue-recognition-run/index.ts - Create:
apps/erp/app/modules/accounting/accounting.cutover.test.ts
Steps:
- Add to
accounting.service.ts. It uses only the Supabase client, so the browser-bundled barrel stays safe:
It selectsexport const ACCOUNTING_NOT_STARTED = "Set up accounting before you post journals, runs or period closes."; export async function requireAccountingCutover( client: SupabaseClient<Database>, companyId: string ): Promise<{ error: { message: string } | null }>;accountingCutoverDatefromcompanySettingswhereid = companyId. It returns{ error: { message: ACCOUNTING_NOT_STARTED } }when the date is null, else{ error: null }. - Call it first in these functions. If it returns an error, return
{ data: null, error }:accounting.service.ts:lockAccountingPeriod:2638,closeAccountingPeriod:2709,runIntercompanyMatching:5598,generateEliminations:5608,postJournalEntry:6380,reverseJournalEntry:6662,createDepreciationRun:7370accounting.server.ts:postDisposal:198,postDepreciationRun:723,postRevenueRecognitionRun:1231
- In
propose-revenue-recognition-run/index.ts:639andrecalculate-revenue-recognition-run/index.ts:37: selectaccountingCutoverDatewith the function'sdb. If it is null, thrownew InvalidInputError("Set up accounting before you post journals, runs or period closes.")from../errors. - Write 2 tests for
requireAccountingCutover. Use a client stub that returns onecompanySettingsrow.- A null date returns the error.
- A date returns no error.
Verify:
pnpm exec turbo run typecheck --filter=erp --filter=@carbon/server-functions
# Expected: 0 failed
pnpm --filter erp exec vitest run app/modules/accounting
# Expected: all tests pass
Out of scope: previewRevenueRecognitionRun (read-only), postAssetRegistration (Task 22).
Task 24: Prove a company with no cutover can post every document
Depends on: Tasks 11–23 Files:
- Create:
packages/server-functions/src/always-post.test.ts - Copy from (precedent):
packages/server-functions/src/post-receipt/rental-agreement.test.ts(live database test withdatabaseTest)
Steps:
- Create a company with
createand the seed path the precedent uses. LeaveaccountingCutoverDatenull. - Post 9 documents, in this order: receipt, shipment, sales invoice, purchase invoice, payment, memo, inventory adjustment, job material issue, job completion.
- After each post, assert that every journal of the document has status
Provisionaland a nullaccountingPeriodId. Assert that the company has noaccountingPeriodrow. - Assert that
accountTreeBalancesfor the company returns 0 on every account. - Assert that the shipment wrote a Sale
costLedgerrow. - Set the company's
salesShippingRevenueAccountto null. Post a sales invoice with shipping. Assert 2 things about the shipping line:- Its
accountIdis the company'sretainedEarningsAccount. - Its
accountDefaultRoleissalesShippingRevenueAccount.
- Its
- Set the company's
scrapAccountto null. Post a scrap. Assert that the scrap line is oninventoryAdjustmentVarianceAccount, with noaccountDefaultRole.
The first version of step 6 used scrapAccount. The review fix in b9f897608c gave scrapAccount a fallback in every state, so it never makes a stand-in line. The committed tests are in always-post.test.ts and always-post-invoice.test.ts.
Verify:
pnpm --filter @carbon/server-functions exec vitest run src/always-post.test.ts
# Expected: all tests pass (the stack must be up, else the test skips — run it with the stack up)
Out of scope: the cutover (Phase C).
Task 25: Accept the Opening Balance source type in the AR/AP readers and payment lookups
Depends on: Task 24 Files:
- Create:
packages/database/supabase/migrations/<timestamp>_opening-balance-subledger-readers.sql - Copy from (precedent):
get_ar_open_by_customerandget_ap_open_by_supplier(20260909174352_account_for_memo_refunds_in_subledger_reports.sql:5-134,:136-265),get_ap_tie_out(same file:338-404),get_ar_tie_out(20261006221801_ar-subledger-excludes-deposits.sql:10-81) - Modify:
packages/server-functions/src/post-payment/post-payment-transaction.ts:521-532,:790-810
Steps:
- Copy the 4 functions. Wherever a query requires
j."sourceType" = 'Sales Invoice','Purchase Invoice','Credit Memo'or'Debit Memo', also accept'Opening Balance'. Example:j."sourceType" IN ('Sales Invoice', 'Opening Balance'). - Keep every
j."status" = 'Posted'filter. - Keep each function's security mode (check
prosecdefbefore and after, as in Task 6). - In the 2 payment lookups, accept
"Opening Balance"in thesourceTypefilter. - Run
pnpm db:migrate, thenpnpm run generate:types.
Verify:
pnpm exec turbo run typecheck --filter=@carbon/server-functions
# Expected: 0 failed
docker exec carbon-carbon-accounting-reset-plan-postgres-1 psql -U postgres -d postgres -Atc "select count(*) from pg_proc where proname in ('get_ar_open_by_customer','get_ap_open_by_supplier','get_ar_tie_out','get_ap_tie_out') and prosrc ilike '%Opening Balance%'"
# Expected: 4
Out of scope: get_ar_aging, get_ap_aging (no journal join).
Task 26: Add the pure cutover planner
Depends on: Task 5 Files:
- Create:
packages/database/src/accounting-cutover.ts - Create:
packages/database/src/accounting-cutover.test.ts - Modify:
packages/database/package.json— export"./accounting-cutover": "./src/accounting-cutover.ts" - Copy from (precedent):
packages/database/src/build-payment-journal.ts(pure journal builder),packages/database/src/accounting-posting.test.ts(test style)
Steps:
- Define the input types. Each amount is in base currency, positive on the natural side of its account.
export type OpenItemType = | "Receivable" | "Payable" | "Unapplied Credit" | "Customer Deposit" | "Received Not Invoiced" | "Work in Progress" | "Inventory" | "Fixed Asset Cost" | "Accumulated Depreciation" | "Deferred Revenue" | "Lease Net Investment"; export type OpenItem = { openItemType: OpenItemType; accountId: string; accountClass: "Asset" | "Liability" | "Equity" | "Revenue" | "Expense"; amount: number; documentType: string | null; documentId: string | null; documentLineReference: string | null; description: string; }; export type TrialBalanceLine = { accountId: string; accountClass: OpenItem["accountClass"]; debit: number; credit: number }; - Give
OpenItem2 more fields:originalAmount: the document's original control amount, in base currency.settledBeforeCutover: the base amount settled before the cutover.
- 6 open item types are not documents: Inventory, Work in Progress, Fixed Asset Cost, Accumulated Depreciation, Deferred Revenue and Lease Net Investment. For these, set
originalAmount = amountandsettledBeforeCutover = 0. amountis alwaysoriginalAmount − settledBeforeCutover.- Write
buildOpeningJournalLines(items, trialBalance, controlAccountIds, migrationClearing). It returns journal line inserts with natural-balance-signedamount, as the lessons require:- Per open item: one line for
originalAmount, with its description and document keys. - Per open item with
settledBeforeCutovernot 0: a second line for−settledBeforeCutover. It has the same keys and the description${description} (settled before cutover). The AR/AP readers and the payment lookup match descriptions exactly, so they ignore it. The account then nets toamount(spec section 4). - One Migration Clearing line per control account, offsetting the open items of that account.
- One line per trial balance row on a non-control account, and one Migration Clearing line offsetting it.
- No line for a trial balance row on a control account.
- Per open item: one line for
- Write
migrationClearingByAccount(items, trialBalance, controlAccountIds). It returns, per control account,{ accountId, trialBalance, carbon, difference }and atotal. The enable needsequals(total, 0, 0.01). - Write
planInventoryReset(onHandAtCutover, unitCostByItem, layersBeforeCutover). Input on-hand is per item (sum across locations). It returnslayerIdsToCloseand one opening layer per item with on-hand above zero:{ itemId, quantity, cost: round(quantity × unitCost), remainingQuantity: quantity }. - Write
recostOutbound(layers, outbound).layersare the opening layers and the inbound layers dated on or after the cutover, oldest first.outboundare the outboundcostLedgerrows dated on or after the cutover, in date thenentryNumberorder. It relieves FIFO and returns{ costLedgerId, newCost, delta }per outbound row and the newremainingQuantityper layer. Copy the FIFO rule frompackages/server-functions/src/lib/calculate-cogs.ts. - Use
round,equalsanddistributeRoundingResidualfrom@carbon/utils. Never useMath.round. - Write tests for each function:
- 2 open invoices on one receivables account and a trial balance that matches: difference 0, the journal balances.
- An invoice of 100 with 40 settled before the cutover: 2 lines (+100 "Accounts Receivable", −40 "Accounts Receivable (settled before cutover)"), net 60.
- The same with a trial balance 5.00 higher: difference 5.00 on that account.
- A trial balance row on cash: one cash line and one clearing line.
- Inventory reset closes every layer before the cutover and opens 1 layer per item.
recostOutboundrelieves the opening layer first, then the next inbound layer.
Verify:
pnpm --filter @carbon/database exec vitest run src/accounting-cutover.test.ts
# Expected: all tests pass
pnpm exec turbo run typecheck --filter=@carbon/database
# Expected: 0 failed
Out of scope: database reads (Task 27), writes (Task 28).
At HEAD, 2 signatures differ from steps 7 and 8:
planInventoryResettakes the on-hand and the unit cost per item only. The enable closes the old layers in SQL (resetAndRecostInventory,activate-accounting/recost.ts).recostOutboundtakes one ordered list of layer and outbound events. It relieves them throughreplayReliefsin@carbon/database/cost-relief.calculateCOGSand the legacy movement costs use the same module (review fix b9f897608c).
Task 27: Add the cutover read services
Depends on: Tasks 25, 26 Files:
- Modify:
apps/erp/app/modules/accounting/accounting.service.ts— add the functions below - Modify:
apps/erp/app/modules/accounting/accounting.models.ts— add the validators below - Copy from (precedent):
computePeriodReadiness(accounting.service.ts:3304, Draft and Pending document queries :3315-3326),getPeriodCloseChecklist(:3823)
Steps:
- Add
getActivationReadiness(client, db, { companyId, cutoverDate }). It returns a list of checks{ key, label, passed, detail }:account-defaults: everyaccountDefaultaccount column is set to an active account,migrationClearingAccountincluded. Return the empty column names indetail. At HEAD, 2 rules changed this check. A default with a fallback inDEFAULT_FALLBACKSmay stay empty. Migration Clearing must be an active Equity account that is not a group (review fix 38602af774).fiscal-settings: afiscalYearSettingsrow exists.cutover-date: the date is the start of a fiscal period. It is not after today in the company time zone. It is at most 3 periods before the current one.pending-documents: no Draft or Pending receipt, shipment, invoice, payment or memo dated before the cutover. Return the documents, ascomputePeriodReadinessdoes.legacy-jobs: no open job created before L (see Terms). The read takesMIN("createdAt")of the company's Provisional and Superseded journals.opening-balance: no Posted journal withsourceType 'Opening Balance'.
- Add
getCutoverOpenItems(client, db, { companyId, cutoverDate }). It returnsOpenItem[](Task 26) from these sources:- Receivables and payables, per open invoice:
originalAmountis its base total. This is the original control amount its posting writes.settledBeforeCutoveris the base sum of itsinvoiceSettlement.appliedAmountfrom payments posted before the cutover.- Cross-check the open amount against
get_ar_open_by_customer/get_ap_open_by_supplieras of the day before the cutover. - An invoice with status Paid and no settlement counts as settled.
- Unapplied credits and deposits, per payment posted before the cutover:
originalAmountis its unapplied cash at posting.settledBeforeCutoveris the part of it that later settlements before the cutover applied.- A deposit (
payment.rentalAgreementIdorpayment.salesOrderId) goes toprepaymentAccountwith descriptionCUSTOMER_DEPOSIT_DESCRIPTION.
- Received not invoiced, per purchase order line:
quantityReceived − quantityInvoicedat the cutover × the receipt layer's unit cost. The document line reference isjournalReference.to.receipt(poLineId). - Work in progress: per open job, the sum of its
DOCUMENT_JOURNAL_STATUSESlines onworkInProgressAccountdated before the cutover. - Deferred revenue:
revenueRecognitionSchedulerows still Planned, dated on or after the cutover, on their credit account. - Lease net investment:
rentalLeaseScheduleLine.closingNetInvestmentof the last line before the cutover.
- Receivables and payables, per open invoice:
- Add
getCutoverInventory(client, db, { companyId, cutoverDate }). It returns 3 values per item:- On-hand: the sum of
itemLedger.quantitydated before the cutover. - Default unit cost, by costing method:
- Standard:
itemCost.standardCost. - FIFO or LIFO: the value of the stock at the cutover, replayed from the layers dated before it (
unitCostAtCutover). - Average:
itemCost.unitCost. The first version of this task used the average of the open layers. Task 28 execution note 4 and the review fix in 188a710e24 replaced it.
- Standard:
- Inventory account: from the item's posting group.
- On-hand: the sum of
- Add
getCutoverFixedAssets(client, { companyId }). Per asset not Disposed: cost, accumulated depreciation, class accounts. - Add
saveOpeningTrialBalance(client, db, { companyId, cutoverDate, userId, lines }). It keeps one Draft journal withsourceType 'Opening Balance', dated the day before the cutover. It replaces the Draft's lines withlines. - Add
getMigrationClearing(client, db, { companyId, cutoverDate }). It callsmigrationClearingByAccountwith the open items, the inventory and asset totals, and the Draft trial balance. - Add
updateCutoverAccumulatedDepreciation(client, { companyId, fixedAssetId, accumulatedDepreciation }). - Add validators:
activationCutoverValidator(cutoverDate),openingTrialBalanceValidator(lines JSON{ accountId, debit, credit }),cutoverAccumulatedDepreciationValidator. - Each read uses at most one query per table. Collect ids and use
.in(). Never query in a loop.
Verify:
pnpm exec turbo run typecheck --filter=erp
# Expected: 0 failed
pnpm --filter erp exec vitest run app/modules/accounting
# Expected: all tests pass
Out of scope: writes beyond the Draft trial balance and accumulated depreciation (Task 28).
Task 28: Add the activate-accounting server function
Depends on: Tasks 26, 27 Files:
- Create:
packages/server-functions/src/activate-accounting/index.ts - Create:
packages/server-functions/src/activate-accounting/activate-accounting.test.ts - Modify: the server function registry and permissions manifest. Follow "Adding a server function" in
packages/server-functions/AGENTS.md. - Copy from (precedent):
packages/server-functions/src/propose-revenue-recognition-run/index.ts(structure,defineServerFn, input schema, permission)
Steps:
Input:
{ cutoverDate: string; confirmation: string }. Permission:update: accounting.Open one Kysely transaction. Do the steps of spec section 5 in this order. The step numbers match the spec and the code comments in
activate-accounting/index.ts,promote.tsandrecost.ts.- Step 1. Lock and check.
- Select
companySettingsfor the companyFOR UPDATE. IfaccountingCutoverDateis set, throw "Accounting is already set up." - If
confirmationis not the company name, throw "Type the company name to confirm." - Re-run every readiness check and
getMigrationClearingwith the transaction. If one fails, throw its message.
- Select
- Step 1a. Legacy backfill. Call
journalLegacyDocuments(Tasks 39–43). - Step 2. Inventory reset.
- Set
remainingQuantity = 0on each cost layer dated before the cutover. - Run
planInventoryReset. - Insert the opening layers with
documentType 'Purchase Receipt',costLedgerType 'Direct Cost',itemLedgerType 'Purchase',postingDate= the cutover.
- Set
- Step 3. Re-cost.
- Run
recostOutbound. - Update
costLedger.costof each outbound row with a delta. - Update
remainingQuantityof each layer. - For each document and posting date with a delta, write one Provisional journal with the description "Cutover recost". Date it that posting date.
- Find the document's inventory line and its pair by
journalLineReference. Move the delta between those 2 accounts. - If a document's inventory line has no pair by
journalLineReference, STOP and report. Do not guess the offset account.
- Run
- Step 4. Supersede. Set every Provisional journal dated before the cutover to
Superseded. - Step 5. Revenue recognition rows. Set each Planned
revenueRecognitionSchedulerow dated before the cutover to Posted, withjournalIdnull. Lease Interest rows arerevenueRecognitionSchedulerows of typeInterest, so the same UPDATE covers them. - Step 6. Fixed assets. Write nothing. The register already holds the values at the cutover.
- Step 7. Opening journal.
- Delete the Draft trial balance journal of Task 27.
- Insert the opening journal with
sourceType 'Opening Balance'and status Posted. Date it the day before the cutover. - Take its lines from
buildOpeningJournalLines. - Resolve its period with
resolveAccountingPeriod, mode historical.
- Step 8. Assign periods. For each Provisional journal dated on or after the cutover, set
accountingPeriodIdwithresolveAccountingPeriod(packages/server-functions/src/lib/get-accounting-period.ts:49, mode historical). Resolve once per distinct month. Superseded journals keep a null period. - Step 9. Re-point the stand-in lines, then promote.
- Select the lines with
accountDefaultRoleset, in Provisional journals dated on or after the cutover. - Set each line's
accountIdto the company'saccountDefaultvalue for its role. SetaccountDefaultRoleto null. Use one UPDATE per role. - Move each intercompany elimination line copied from a stand-in line to the same account.
- Set every Provisional journal dated on or after the cutover to
Posted, withpostedAtandpostedBy.
- Select the lines with
- Step 10. Close the periods before the cutover. Take the periods that end before the cutover, oldest first. Set
closeStatus 'Closed',closedAtandclosedBy. Then callsnapshotAccountingPeriodBalancesfor each. - Step 10a. Make the current period Active. Call
getCurrentAccountingPeriod, as the first posting would. The cutover is never after today, so step 10 never closes this period. - Step 11. Stamp. Update
companySettings:accountingCutoverDate,accountingActivatedAt = now,accountingActivatedBy = userId.
The first version of this task also re-pointed stand-in
revenueRecognitionSchedulerows by account. The review fix in b9f897608c removed that step: a schedule row never takes a stand-in. A service invoice with dates refuses an empty deferred revenue default before the cutover.- Step 1. Lock and check.
Write a database test (
databaseTest) with 1 open invoice, 1 receipt not invoiced and stock of 1 item. Assert after the enable:- No journal has status
Provisional. - The opening journal balances and Migration Clearing sums to 0.
- A payment against the open invoice posts.
- A second call throws "Accounting is already set up."
- No line in a Posted journal has
accountDefaultRoleset.
- No journal has status
Verify:
pnpm exec turbo run typecheck --filter=@carbon/server-functions
# Expected: 0 failed
pnpm --filter @carbon/server-functions exec vitest run src/activate-accounting
# Expected: all tests pass (with the stack up)
pnpm --filter @carbon/server-functions exec vitest run src/permissions-manifest.test.ts
# Expected: pass
Out of scope: the UI (Task 31).
Task 29: Handle voids of documents dated before the cutover
Depends on: Task 28 Files:
- Create:
packages/database/src/accounting-cutover-dates.ts—isBeforeCutover(postingDate: string, cutoverDate: string | null): boolean, with a test - Create:
packages/server-functions/src/lib/cutover-void.ts—refuseVoidBeforeCutover,assertNoMigrationClearingand the refusal messages - Modify:
packages/server-functions/src/post-sales-invoice/index.ts,post-purchase-invoice/index.ts(the invoice voids) - Modify:
packages/server-functions/src/post-payment/post-payment-transaction.ts,post-memo/post-memo-transaction.ts(the payment and memo voids) - Modify:
packages/server-functions/src/post-receipt/index.ts,post-shipment/index.ts(the inventory voids) - Modify:
packages/server-functions/src/post-charge/post-charge-void.ts,post-reimbursement/post-reimbursement-void.ts
Steps:
If a payment or memo is dated before the cutover, build its posting again and negate it. Use
rebuildPaymentJournal(post-payment/rebuild-journal.ts) andrebuildMemoJournal(post-memo/rebuild-journal.ts). Date the void today, in the current period, with status Posted.Never post a void line to
migrationClearingAccount.assertNoMigrationClearingrefuses one.Refuse the void of each of these documents when it is dated before the cutover. Call
refuseVoidBeforeCutoverbefore any write.Document Message constant Message Sales invoice SALES_INVOICE_VOID_BEFORE_CUTOVER_ERROR"This invoice is from before your accounting cutover. Issue a credit memo instead." Purchase invoice PURCHASE_INVOICE_VOID_BEFORE_CUTOVER_ERROR"This invoice is from before your accounting cutover. Record a debit memo instead." Receipt, shipment INVENTORY_VOID_BEFORE_CUTOVER_ERROR"This document is from before your accounting cutover. Record a return or an inventory adjustment instead." Charge CHARGE_VOID_BEFORE_CUTOVER_ERROR"This charge is from before your accounting cutover. Record a journal entry to correct it instead." Reimbursement REIMBURSEMENT_VOID_BEFORE_CUTOVER_ERROR"This reimbursement is from before your accounting cutover. Record a journal entry to correct it instead." A contract or rental credit memo dated before the cutover also refuses its void, with
MEMO_CREDIT_VOID_BEFORE_CUTOVER_ERROR(post-memo/rebuild-journal.ts).Inventory adjustments and inventory counts have no void, so they need no change.
Add database tests:
- A void of a payment or a memo dated before the cutover nets against its opening line.
- A void of each document in the step 3 table, dated before the cutover, throws its message.
The committed tests are in
activate-accounting/pre-cutover-voids.test.ts,always-post-cutover.test.tsandpost-memo/memo-cutover.test.ts.
Verify:
pnpm exec turbo run typecheck --filter=@carbon/server-functions --filter=@carbon/database
# Expected: 0 failed
pnpm --filter @carbon/server-functions test
# Expected: all tests pass (with the stack up)
Out of scope: none.
This task changed while it ran. The first version built every invoice void again and refused nothing for charges and reimbursements. See Execution notes.
Task 30: Start depreciation at the cutover
Depends on: Task 4 Files:
- Modify:
apps/erp/app/modules/accounting/accounting.service.ts:7301(buildDepreciationRunLines) - Modify:
apps/erp/app/modules/accounting/accounting.utils.test.ts(neardescribe("buildDepreciationLines")at :946)
Steps:
- Read
companySettings.accountingCutoverDateinbuildDepreciationRunLines. - At :7301, set
lastPostedPeriodEndto the later of 2 dates:- the posted run's
periodEnd; - the last day of the month before the cutover.
Compare
YYYY-MM-DDstrings. Use@internationalized/datefor the month end.
- the posted run's
- Add a test: an asset that started before the cutover, with no posted run, depreciates from the cutover month only.
Verify:
pnpm --filter erp exec vitest run app/modules/accounting/accounting.utils.test.ts
# Expected: all tests pass
Out of scope: tax depreciation calculators (they read the same lastPostedPeriodEnd).
Task 31: Build the 5-step enable wizard
Depends on: Tasks 27, 28 Files:
- Create routes under
apps/erp/app/routes/x+/accounting+/:activation.tsx(layout),activation._index.tsx(redirect),activation.readiness.tsx,activation.inventory.tsx,activation.fixed-assets.tsx,activation.trial-balance.tsx,activation.enable.tsx - Create components in
apps/erp/app/modules/accounting/ui/Activation/:ActivationSteps.tsx,ReadinessChecklist.tsx,InventoryCostTable.tsx,FixedAssetDepreciationTable.tsx,TrialBalanceEditor.tsx,MigrationClearingTable.tsx,index.ts - Modify:
apps/erp/app/utils/path.ts— addaccountingActivation(${x}/accounting/activation) andaccountingActivationStep(step)in theaccounting*block (:48-66) - Modify:
apps/erp/app/modules/accounting/ui/AccountingBetaGate.tsx— never gate the activation routes - Modify: the Account Defaults form and its validator — add a
migrationClearingAccountfield (Equity accounts). Find the form withgrep -rln "retainedEarningsAccount" apps/erp/app/modules/accounting/ui/AccountDefaults; the validator is inaccounting.models.ts - Copy from (precedent):
- Wizard:
apps/erp/app/routes/x+/contract+/$id.setup.tsx(useCurrentStep:47-55, footer Back/Next, last-step confirm),apps/erp/app/modules/sales/ui/Contracts/ContractSetupSteps.tsx,apps/erp/app/components/Setup/(SetupSteps,SetupFrame,SetupBody,SetupSection,SetupFooter) - Readiness rows:
PeriodCloseTaskRowinapps/erp/app/routes/x+/accounting+/periods.$periodId.close.tsx:449; document list:apps/erp/app/modules/accounting/ui/Periods/PeriodCloseUnpostedDocumentsPopover.tsx - Trial balance editor: the inline Opening Balances mode in
apps/erp/app/routes/x+/accounting+/charts.tsx:132-175andChartOfAccountsTree.tsx:185,:288-315 - CSV upload:
apps/erp/app/components/ImportCSVModal/UploadCSV.tsx(PapaParse) - Inline unit cost edit:
apps/erp/app/routes/x+/items+/cost.$itemId.tsx(path.to.itemCostUpdate)
- Wizard:
Steps:
- Steps, in order:
readiness,inventory,fixed-assets,trial-balance,enable. Labels: "Readiness", "Inventory", "Fixed Assets", "Trial Balance", "Enable". activation.tsxloader:requirePermissions(request, { view: "accounting" }). IfaccountingCutoverDateis set,throw redirect(path.to.accountingPeriods). Keep the chosen cutover in the URL search paramcutover.activation._index.tsx: redirect to the readiness step. Exportmiddleware = [redirectBeforeLoaders(loader)].readiness: a period-start date picker (default: start of the current period) and the checklist fromgetActivationReadiness. The step disables Next until every check passes. Theaccount-defaultsrow lists each empty default and links topath.to.accountingDefaults.inventory:InventoryCostTablefromgetCutoverInventory. Show the total per inventory account.- An Average item's unit cost is an inline
NumberControlledwithINPUT_FORMAT.rate. It posts topath.to.itemCostUpdate. - Show the cost as read-only for a FIFO or LIFO item, a Standard item, or a user without
update: parts. The first version made every unit cost editable. See the Task 31 execution notes.
- An Average item's unit cost is an inline
fixed-assets:FixedAssetDepreciationTablefromgetCutoverFixedAssets. Accumulated depreciation is inline editable; the action intentsave-assetcallsupdateCutoverAccumulatedDepreciation.trial-balance:TrialBalanceEditor(the chart of accounts with debit and credit inputs) and a CSV upload (accountNumber, debit, credit).- Intent
save-tbcallssaveOpeningTrialBalancewith the editor's lines. - Intent
import-tbparses the CSV withparseTrialBalanceCsv(trial-balance-csv.ts). It maps account numbers to ids and lists unknown numbers as errors. If a row has an error, it saves nothing. - Below the editor,
MigrationClearingTableshowsgetMigrationClearing.
- Intent
enableshows these things, in this order:- A summary: the cutover, the opening balance date, the open item count and the Migration Clearing total.
- A link back to Readiness when a check fails. A link back to Trial Balance when Migration Clearing is not 0.
- The section "Documents Posted Before Carbon Kept Journals", when legacy documents exist. It shows the count per family (Task 44).
- The warning "This cannot be undone."
- A text field for the company name.
- The button "Enable accounting".
- Enable the button only when 3 things are true:
- Every readiness check passes.
- The clearing total is 0 within 0.01.
- The user has
update: accounting.
- The enable action invokes
activate-accountingthroughserverFns. Then it throwsredirect(path.to.accountingPeriods)with a success flash. - Every action validates with
validator(schema).validate(formData). On failure, returndata({}, await flash(request, error(...))). - Render
<RecordOutlet />in the layout. - Wrap every user-visible string in Lingui (
Transort).
Verify:
pnpm exec turbo run typecheck --filter=erp
# Expected: 0 failed
pnpm --filter @carbon/checks test
# Expected: pass (no-bare-outlet, index-redirect-before-loaders)
Out of scope: the Settings link (Task 34).
Task 32: Replace every ERP read of accountingEnabled
Depends on: Task 31
Files (under apps/erp/app/):
| File:line | Change |
|---|---|
modules/accounting/ui/AccountingBetaGate.tsx:38 |
gate on accountingCutoverDate == null; the overlay's button links to path.to.accountingActivation with "Set up accounting" |
routes/x+/accounting+/_index.tsx:17-21 |
redirect to reports when the cutover is set, else to the enable wizard |
routes/x+/accounting+/charts.tsx:132-143 |
remove the Opening Balances button and mode; the wizard replaces it |
modules/accounting/ui/ChartOfAccounts/ChartOfAccountsTree.tsx:131,190,319 |
show balances when the cutover is set |
routes/x+/get-started+/_layout.tsx:177,241 |
read the cutover |
routes/x+/reports+/ar-aging.tsx:55-60, ap-aging.tsx:55-60, inventory-valuation.tsx:42-48 |
read the cutover |
routes/x+/invoicing+/receivables.tsx:55-60, payables.tsx:55-60, receivables.adjust.tsx:33-44, payables.adjust.tsx:33-44, _index.tsx:78-122 |
read the cutover |
routes/x+/fixed-asset+/capitalize.tsx:113,136,224, $fixedAssetId.adjust-cost.tsx:63,72,149 |
always show the Offset Account field |
modules/inventory/ui/Inventory/InventoryStorageUnits.tsx:343,715,737 |
always show the Offset Account field |
Steps:
- Add
hasAccountingCutover(settings): boolean. It returnssettings?.accountingCutoverDate != null. The review fix in f1fe2b6c81 moved it fromaccounting.models.tstoaccounting.utils.ts. It is now the one way the ERP asks whether a company has a cutover. - Make each change in the table. Client components read
useSettings(). Loaders readgetCompanySettings. - Delete
createOpeningBalanceJournal,getExistingOpeningBalanceEntry(accounting.service.ts:6472,:6497),OpeningBalancePostModal.tsxandopeningBalanceValidator, if nothing else uses them.
Verify:
grep -rn "accountingEnabled" apps/erp/app packages/ee/src --include='*.ts' --include='*.tsx'
# Expected: no output, except comments you rewrite
pnpm exec turbo run typecheck --filter=erp --filter=@carbon/ee
# Expected: 0 failed
Out of scope: the settings switch (Task 34), Mark Paid (Task 33).
Task 33: Remove Mark Paid and Mark Unpaid
Depends on: Task 31 Files:
- Delete:
apps/erp/app/routes/x+/sales-invoice+/$invoiceId.status.tsx,apps/erp/app/routes/x+/purchase-invoice+/$invoiceId.status.tsx - Modify:
apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceHeader.tsx— delete :116-129, :258-261, :302-341, importsLuCircleCheck,LuCircleX(:30-31) anduseSettings(:50); keepuseFetcher - Modify:
apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceHeader.tsx— delete :125-138, :258-297, imports :28-29 anduseSettings(:45); deleteuseFetcher(:38) only if nothing else uses it - Modify:
apps/erp/app/utils/path.ts— deletesalesInvoiceStatus(:2247) andpurchaseInvoiceStatus(:1991) - Modify:
apps/erp/app/modules/invoicing/invoicing.service.ts— deleteupdateSalesInvoiceStatus(:589) andupdatePurchaseInvoiceStatus(:542)
Steps:
- Make each change.
- Grep for each deleted name. If a caller remains, STOP and report.
Verify:
grep -rn "salesInvoiceStatus\|purchaseInvoiceStatus\|updateSalesInvoiceStatus\|updatePurchaseInvoiceStatus\|Mark as Paid" apps/erp/app
# Expected: no output
pnpm exec turbo run typecheck --filter=erp
# Expected: 0 failed
pnpm run generate:mcp
# Expected: the MCP manifest regenerates without errors (the service functions were MCP tools)
Out of scope: the .po files (the pre-commit hook extracts them).
Task 34: Replace the settings switch
Depends on: Task 31 Files:
- Modify:
apps/erp/app/routes/x+/settings+/accounting.tsx— delete the intent at :119-127; replace the General Ledger card at :311-338 - Modify:
apps/erp/app/modules/settings/settings.service.ts— deleteupdateAccountingEnabledSetting(:1031-1040)
Steps:
- In the General Ledger card: if the cutover is set, show "Accounting since {date}" with
formatDate. Else show a button "Set up accounting" that links topath.to.accountingActivation. - Delete the switch, the
isInternalgate and the Alpha badge. - Run
pnpm run generate:mcp. The toolsettings_updateAccountingEnabledSettingleaves the manifest.
Verify:
grep -rn "updateAccountingEnabledSetting" apps packages --include='*.ts' --include='*.tsx' --include='*.json' | grep -v node_modules
# Expected: no output
pnpm exec turbo run typecheck --filter=erp
# Expected: 0 failed
Out of scope: the column (it stays).
Task 35: Set the cutover for new companies and demo datasets
Depends on: Task 4 Files:
- Modify:
packages/server-functions/src/seed-company/index.ts— insideif (!identityOnly)(:234-514), afterfiscalYearSettings(:484-487) - Modify:
packages/database/src/datasets/tiers/01-foundation.ts—runTier1(:32) - Modify:
packages/database/src/datasets/bootstrap.ts:106-109,packages/database/src/seed-dev.ts:76-79 - Copy from (precedent):
packages/database/src/datasets/tiers/04-sales.ts:65-75(insertRowwithonConflictoncompanySettings)
Steps:
- In
seed-company, updatecompanySettings:accountingCutoverDate: the first day of the current period, fromdatetime.today(tz)in the company time zone.accountingActivatedAt:datetime.timestamp().accountingActivatedBy: the user id.
- In tier 01: upsert the same 3 columns. The cutover is the first day of
monthBack(ctx.anchor, 11)fromdatasets/dates.ts, so every seeded journal of tier 09 falls on or after it. - Delete the
accountingEnabled = trueupdates inbootstrap.tsandseed-dev.ts.
Verify:
pnpm exec turbo run typecheck --filter=@carbon/server-functions --filter=@carbon/database
# Expected: 0 failed
pnpm db:check:datasets
# Expected: all 4 datasets pass
Out of scope: existing companies (Task 2 step 9).
Task 36: Show the Provisional and Superseded statuses
Depends on: Task 4 Files:
- Modify:
packages/utils/src/status-colors.ts:259-263—Provisional: "yellow",Superseded: "gray" - Modify:
apps/erp/app/modules/accounting/ui/JournalEntries/JournalEntryStatus.tsx— labels "Provisional" and "Before cutover" - Modify:
apps/erp/app/modules/accounting/accounting.models.ts:781— add both tojournalEntryStatuses - Modify:
apps/erp/app/modules/accounting/ui/JournalEntries/JournalEntriesTable.tsx:142-158andaccounting.service.ts:5660(getJournalEntries) — excludeSupersededunless the filter asks for it - Modify:
apps/erp/app/modules/invoicing/invoicing.service.ts:2137-2143,routes/x+/reimbursements+/$reimbursementId.tsx:86-92,routes/x+/invoicing+/charges.$id.tsx:100-106— selectstatusand show the badge
Steps:
- Make each change.
- Check the 6 importers of
journalEntryStatuses. If one switches on every value exhaustively, add the 2 cases.
Verify:
pnpm exec turbo run typecheck --filter=erp --filter=@carbon/utils
# Expected: 0 failed
Out of scope: the MES (it shows no journals).
Task 37: Update the docs, rules and AGENTS.md files
Depends on: Tasks 31–36 Files:
- Modify:
apps/erp/app/modules/accounting/AGENTS.md— the cutover, the 3 status lists,activate-accounting, the removed opening balance mode - Modify:
packages/server-functions/AGENTS.md—activate-accounting,journalPostingStatus - Modify:
packages/jobs/AGENTS.md— therevenue-recognition-proposalrow (cutover, not the flag) - Modify:
.claude/rules/accounting-sync-handlers.md— Provisional and Superseded never sync; promotion syncs - Modify:
.claude/rules/onboarding-company-templates.md— tier 01 sets the cutover - Modify:
docs/content/docs/reference/accounting.mdx— use thecarbon-docsskill; describe the enable wizard - Modify:
.ai/specs/2026-10-08-accounting-cutover.md— when Task 38 passes, set the status toimplementedand move the file to.ai/specs/implemented/
Steps:
- Update each file. Ground each sentence in the code you wrote.
- Run
pnpm --filter docs typecheckafter the docs change.
Verify:
pnpm --filter docs typecheck
# Expected: 0 errors
grep -rn "accountingEnabled" apps/erp/app/modules/accounting/AGENTS.md packages/server-functions/AGENTS.md .claude/rules
# Expected: only text that says the column is unused
Out of scope: a changelog entry (ask the user).
Task 38: Run every gate and verify the enable flow in the browser
Depends on: all other tasks Files: none
Steps:
- Run
pnpm db:migrate. - Run
pnpm db:check:datasetsandpnpm db:check:backups. - Run typecheck for
@carbon/database,@carbon/server-functions,@carbon/jobs,@carbon/ee,@carbon/utils,erp, one at a time. - Run
pnpm --filter @carbon/database test,pnpm --filter @carbon/server-functions test,pnpm --filter @carbon/jobs test,pnpm --filter @carbon/checks test,pnpm --filter erp test. - Invoke
/testwith this playbook, on a company with no cutover:- Post a receipt and a sales invoice. Open Accounting → Journals: the journals show "Provisional"; the trial balance is empty.
- Settings → Accounting: click "Set up accounting".
- Readiness: choose the start of the current period. Every check passes.
- Inventory: change one unit cost.
- Fixed assets: continue.
- Trial balance: enter a balance that ties. Migration Clearing shows 0.
- Enable: type the company name. Click "Enable accounting".
- Accounting → Periods: periods before the cutover are Closed.
- Pay the sales invoice. The payment posts.
- Try to void the receipt. The cutover message shows.
Verify:
# Every command in steps 2-4 exits 0.
# /test reports every playbook step as passed, with screenshots under .context/.
Out of scope: pushing or opening a pull request (ask the user).
Task 39: Write the journals of legacy sales and purchase invoices at enable
Depends on: Task 28 Files:
- Create:
packages/server-functions/src/activate-accounting/legacy/:index.ts:journalLegacyDocuments(trx, { companyId, userId, cutoverDate }). It returns the count per family.write.ts: one helper that inserts a Provisional journal, its lines and their dimensions.sales-invoice.ts,purchase-invoice.tsand a test.
- Create:
packages/database/src/legacy-documents.ts(export@carbon/database/legacy-documents). It holds the detection query of each family. The enable andgetLegacyDocumentCounts(Task 44) read the same queries. The first version of this task put the detection inlegacy/detect.ts; the review fixes moved it here. - Modify:
packages/server-functions/src/activate-accounting/index.ts— call it as step 1a, after the readiness re-check and before the inventory reset.
Steps:
Detect a legacy invoice. It has 3 properties:
- Its status is not Draft, Pending or Voided.
- Its
postingDateis on or after the cutover. - No
journalLinewithdocumentType 'Invoice'and its id exists, in a journal of any status.
Sales invoice: build the lines with
buildSalesPostingLines. Take the accounts fromaccountDefault, with the stand-in rule ofresolveDefaultAccount.Book a contract, rental or fixed-asset line as plain revenue on the sales account.
Use the same
documentLineReferencevalues and descriptions aspost-sales-invoice. Payments find the control line by them.Purchase invoice: take the amounts from
calculatePurchasePostingAmounts. Copy the reference and description shapes ofpost-purchase-invoice(purchase-invoice:<poLineId>on GR/IR lines). Book each line type as follows:Line Booking Received PO line Clear GR/IR at its receipt cost (receipt costLedgerrows, elsereceiptLine.unitPrice). Book the price difference to the purchase variance account.Unreceived quantity Accrue GR/IR. G/L line Book its own accountId.Stock line with no PO Book the inventory account. Convert to base at the document's
exchangeRate.Write each journal
Provisional, with no period. Date it the invoice'spostingDate. Use thesourceTypethe posting writes.Add a database test:
- In a company with no cutover, post a sales invoice and a purchase invoice.
- Delete their journals, as the accounting reset did.
- Enable with a trial balance that ties.
- Assert that receivables and payables carry the invoices.
- Assert that a payment against the sales invoice posts.
- Assert that Migration Clearing is 0.
Verify: typecheck @carbon/server-functions; the new test and src/activate-accounting pass.
Task 40: Write the journals of legacy memos, payments, charges and reimbursements
Depends on: Task 39 Steps:
- Build the memo and payment journals again from their stored rows. At HEAD the builders are
rebuildMemoJournals(post-memo/rebuild-journal.ts) andrebuildPaymentJournals(post-payment/rebuild-journal.ts). Each takes a list of documents. The void of one document uses the single formsrebuildMemoJournalandrebuildPaymentJournal(Task 29). - Take each payment's processor fee from
readPaymentProcessorFees(@carbon/database/payment-processor-fee). It reads the payment'sexternalIntegrationMappingrow with the same rules asrecordStripeConnectPayment. - Book a contract or rental credit memo as a plain memo on the sales account.
- Extract the charge and reimbursement loaders so that
buildChargeJournalandbuildReimbursementJournalcan run from stored rows. - Write memos, charges and reimbursements together with the invoices. Write payments after them, in
postingDatethencreatedAtorder. - Extend the test. Post a legacy payment against a legacy invoice dated on or after the cutover. Assert that receivables net to the open balance.
Task 41: Write the journals of legacy movements that stored a cost row
Depends on: Task 40 Steps:
- Find the movements from the
costLedgerrows dated on or after the cutover whose document has no journal line. - PO receipt: book inventory against GR/IR, with
receipt:<poLineId>and the quantity, aspost-receiptwrites them. A Non-Inventory line books indirect cost instead of inventory. An outside processing line books WIP. - Return receipt: book inventory against COGS.
- Return shipments: book them as
post-shipmentwrites them. - Adjustments, scrap, counts, non-conformance scrap and maintenance parts: use
buildAdjustmentJournalLineswith the offset each posting uses. - Skip transfers, because they have no cost row. Skip corrections, because they share the original document's keys.
- A sales shipment with a "Sale" cost row belongs here. (The company had accounting on before the accounting reset.) Book COGS against inventory at the stored cost.
- Extend the test: post a legacy receipt dated on or after the cutover. After the enable, a purchase invoice clears GR/IR to 0.
Task 42: Write the cost rows and journals of legacy movements that stored none
Depends on: Task 41 Steps:
- Sales shipment and direct sales invoice line: find each negative
itemLedgerrow with no outboundcostLedgerrow. Write a "Sale" cost row for it. The shipment and invoice builders of Tasks 39 and 41 then write its COGS/inventory pair. - Job material issue and backflush: write the outbound cost row and a WIP/inventory pair (
material-issue:<operationId>). - Job output: write the finished-goods layer at the cost of the job's material issued on or after the cutover. Write an inventory/WIP pair.
- Cost each outbound row as
calculateCOGSdoes. A FIFO or LIFO item relieves the open layers. A Standard item costs at its standard cost. An Average item costs atitemCost.unitCost. A return costs at today's unit cost. - Run this step first in the legacy backfill, before the invoice and shipment builders. The inventory reset and the re-cost (steps 2 and 3) then value FIFO and LIFO items against the layers.
- Extend the test: post a legacy shipment dated on or after the cutover. After the enable, inventory on the GL equals the open layers.
Task 43: Write the journals of legacy asset and revenue runs again
Depends on: Task 42 Steps:
- Find the depreciation run lines and disposals dated on or after the cutover with a null
journalId. Write their journals again from the stored lines, aspostDepreciationRunandpostDisposalbuild them. SetjournalId. - Do the same for the revenue recognition schedule rows Posted on or after the cutover with a null
journalId. Build them aspostRevenueRecognitionRundoes. - Write them Provisional. Step 9 of the enable promotes them.
- Keep the recreated run journals out of provider sync. The accounting provider can already hold a copy. The accounting reset deleted the journal and its mapping, but not the provider's copy. At HEAD,
insertProvisionalJournals(legacy/write.ts) records an Excluded sync operation with the codeCUTOVER_REBUILTfor every journal that the legacy backfill writes. getLeaseNetInvestmentItemsjoins the commencement journal, and a legacy sales-type lease has none. Read the opening Net Investment from the lease rows instead. The lease then opens with no journal before the cutover.
Task 44: Show the legacy journals in the enable wizard and update the docs
Steps:
- Add
getLegacyDocumentCounts(db, { companyId, cutoverDate })to the reads (accounting-cutover/legacy-counts.ts). - On the Enable step, show the section "Documents Posted Before Carbon Kept Journals". Its description is "Carbon writes their journals when you enable accounting, with today's accounts and costs." Show one count per family.
- Update
packages/server-functions/AGENTS.md, the accounting module AGENTS.md anddocs/content/docs/reference/accounting.mdx.
Task 45: Verify the legacy window in the browser
Steps:
- Build a local company with legacy documents dated on or after the cutover:
- Post the documents.
- Delete their journals, as the accounting reset did.
- Clear the cutover.
- Run the enable wizard and enable accounting.
- Pay a legacy invoice.
- Check the receivables balance.
Acceptance criteria coverage
| Spec acceptance criterion | Tasks |
|---|---|
| A company with no cutover posts Provisional journals, and reports show nothing | 6, 11–21, 24 |
| A shipment relieves cost layers with no cutover | 13, 24 |
| A job completion writes the finished-goods layer with no cutover | 21, 24 |
| A payment against an invoice posted before L posts with no cutover | 16, 24 |
An empty default with no fallback gives a stand-in line with its role, and the enable re-points it. (At HEAD an empty scrapAccount falls back to inventoryAdjustmentVarianceAccount, so the test uses salesShippingRevenueAccount.) |
5, 11, 14, 24, 28 |
| Readiness lists each empty account default | 27, 31 |
| Mark Paid and Mark Unpaid are gone | 33 |
| The wizard refuses a bad cutover | 27, 31 |
| One opening line per open invoice | 26, 27, 28 |
| A 5.00 difference keeps "Enable accounting" disabled | 26, 31 |
| After the enable: Provisional on or after the cutover is Posted, before the cutover is Superseded, none remain | 28 |
| A shipment between the cutover and the enable carries the reset cost | 26, 28 |
| A payment against an invoice dated before the cutover posts | 25, 28 |
| A purchase invoice clears the opening GR/IR line | 27, 28 |
| A void of a payment dated before the cutover reverses in the current period, never on Migration Clearing | 29 |
| A void of an invoice dated before the cutover fails with the credit memo or debit memo message | 29 |
| A void of a receipt dated before the cutover fails with the cutover message | 29 |
| A receipt dated before the cutover fails; currency and fiscal start month are locked | 2, 28 |
| A Superseded journal cannot change; Provisional to Posted in a Closed period fails | 2 |
| A posting waits for the enable lock, then posts as Posted | 5, 28 |
| A new company posts as Posted | 35 |
journal-status-filter flags <> 'Draft' |
8 |
| Datasets, typecheck, tests and lint pass | 38 |
Execution notes
Changes while the tasks ran
- Task 10 changed while it ran: a Provisional journal has no accounting period (spec section 1 item 3). Phase B shared step 5, Task 21, Task 24 and Task 28 follow from it.
- Task 1 widened
journalEntryStatus. The ERP typecheck then failed in the status badge and the provider journal schema. The Task 10 commit holds that fix (labels, colors,journalEntryStatuses,core/models.ts), ahead of Task 36. Task 36 keeps the journal list filter and the document panels. - Shared step 2 changed while it ran. A function that reads the status before its transaction reads it again under the lock inside it. A mismatch throws. The rule applies to each posting function that resolves the period before its transaction.
- Task 21 copies both functions from
pg_get_functiondef(the live definition). IflaborAbsorptionAccountoroverheadAbsorptionAccountis empty, it still skips the labor-absorption journal, as before. It writes no stand-in line. - Task 11:
recost-serial-unitnow always needs an offset account, so the serial unit cost form inInventoryStorageUnits.tsxmust always show that field (Task 32). An emptyscrapAccountfalls back toinventoryAdjustmentVarianceAccountbefore and after the cutover. It never makes a stand-in line (review fix b9f897608c). - The full server-functions suite can fail 1 or 2 database tests under parallel load (
rows.test.ts,post-charge-transaction.test.ts). Run them alone before you treat a failure as real. - Task 14: before the cutover, the sales invoice builders write a stand-in line for an empty optional default with no fallback. They use a class-typed placeholder and write the role on the journal line and on its intercompany elimination line. The base-currency identity-rate guard and the currency-row check now run for every company (Q7, fail closed).
- Task 14, first version: the builders also wrote retained earnings on
revenueRecognitionSchedulerows, and Task 28 re-pointed them by account. The review fix in b9f897608c removed both. A schedule row never takes a stand-in. - Task 16: before the cutover, a rental or contract credit memo still refuses when
deferredRevenueAccount,contractAssetAccountorrentalIncomeAccountis empty. Its error names the default. - Voids copy
accountDefaultRolefrom each original line to its reversal (Tasks 14, 15, 16). - Task 23: the guard tests live in
accounting.periods.test.ts, because it already has the client stub and the module mocks. The payment test fixture now gives its company a cutover. - Task 20: capitalize with an entered cost and adjustCost now always need an offset account. So
capitalize.tsxand$fixedAssetId.adjust-cost.tsxmust always show that field (Task 32). If their defaults are empty, lease Interest schedule rows refuse with the existing message. A non-journal row has no stand-in. - Task 26:
recostOutboundtakes FIFO and LIFO movements only. Standard and Average items cost fromitemCost, not from layers. - Task 30: the floor is the pure
depreciationFloorinaccounting.utils.ts, tested there. - Task 27 changed while it ran. The cutover reads live once, in Kysely, in
packages/database/src/accounting-cutover-reads.ts(export./accounting-cutover-reads, server-only). Two implementations of the open-item reads would drift.- Task 28 calls the same functions with its transaction.
- The writes (
saveOpeningTrialBalance,updateCutoverAccumulatedDepreciation) take a Kysely handle too. - The wizard loaders first called the reads through
accounting.server.ts. Since the review fix in f1fe2b6c81, they import them directly, withgetDatabaseClient().
- Task 27: a deferred revenue opening item uses the schedule row's DEBIT account. A Deferral row is the future recognition entry, Dr Deferred Revenue / Cr Sales. A purchase invoice always has the description "Accounts Payable", as the posting writes it. Received-not-invoiced must carry the quantity for the GR/IR walk of the purchase invoice. Task 28 adds it (spec section 4).
- Task 35: tier 01 sets the cutover only when the company has none. A re-apply keeps it, because the cutover is one-way.
- Run
/translateonce at the end of Phase D for the new UI strings, not once per commit. - The Task 1 commit holds Task 7 too. The pre-commit dataset check refuses the new enum values until the exclusions exist.
pnpm db:migrate:newwaits on stdin when stdin is not a terminal. Run it aspnpm db:migrate:new <name> < /dev/null.- Before a commit that touches a migration or
packages/database/src, runpnpm generate:mcp. Then stageapps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json. - The dataset and backup checks read
SUPABASE_DB_URLfrom.env(port 54322). This worktree's stack is on.env.local(port 65067 since the stack restart). Export it before a commit:export $(grep -E "^SUPABASE_DB_URL=" .env.local | xargs). - Task 28 changed while it ran:
- The enable writes one re-cost journal per document and posting date, not one per document. A job can issue material on more than one day.
- A re-cost offset line takes its sign from the original pair, not from the account class. A stand-in line sits on retained earnings but carries the sign of the account it stands in for.
recostOutboundtakes only layers dated on or before a movement. For a LIFO item it takes the newest layer first.- The default unit cost of a FIFO or LIFO item replays its layers dated before the cutover (
unitCostAtCutover). Today's remaining quantity is wrong, because relief after the cutover changed it. An Average item usesitemCost.unitCost. A Standard item usesitemCost.standardCost. - Open gaps: a PO line invoiced past its receipts before the cutover gets no open item. After the enable, an invoice clears GR/IR at the average cost of the opening line. So receipts at different costs can leave a residual.
- Task 29 changed while it ran:
- The void of a sales or purchase invoice dated before the cutover fails. Its message points to a credit memo or a debit memo. No builder covers a whole invoice posting.
- Only payment and memo voids build the posting again and negate it.
- Charge and reimbursement voids dated before the cutover fail too (
CHARGE_VOID_BEFORE_CUTOVER_ERROR,REIMBURSEMENT_VOID_BEFORE_CUTOVER_ERRORinlib/cutover-void.ts). - Inventory adjustments and inventory counts have no void, so the receipt and shipment voids are the only inventory voids that refuse.
- Task 31 changed while it ran:
- The inventory step edits the unit cost of an Average item only. A FIFO or LIFO item shows the value its layers had at the cutover. A Standard item shows its standard cost. For those items, an edit to
itemCost.unitCostdoes not reach the inventory reset. - The trial balance CSV import is its own intent,
import-tb. If a row has an error, it saves nothing. no-unscoped-kysely-writefirst exemptedcompanySettings. Since the review fix in 188a710e24, a write tocompanyorcompanySettingsmust filter byid, because theiridis the company id.
- The inventory step edits the unit cost of an Average item only. A FIFO or LIFO item shows the value its layers had at the cutover. A Standard item shows its standard cost. For those items, an edit to
- Task 39: the detection lives in
packages/database/src/legacy-documents.ts, not inlegacy/detect.ts. The enable andgetLegacyDocumentCountsread the same queries. - Task 40 added migration
20261009060609_legacy-journal-attach.sql. The charge and reimbursement draft guards refused every change from Posted to Posted, so the enable could not setjournalId. The guards now allow one more change: a Posted row with no journal gets one, and nothing else changes. - Task 42 also journals job issue and job completion cost rows whose journals the accounting reset deleted (companies that had accounting on). Without it, the re-cost refuses such a row with 409. In
postRecostJournals, a zero-cost pair takes its sign from the class of the offset account. - Task 38: every scripted gate passed on 2026-10-09: migrate, datasets, backups, 8 typechecks, 5 test suites and lint.
rows.test.tsfails under parallel load and passes alone.- The browser runs covered the wizard, the enable, a payment against a legacy invoice and the readiness list.
- A database test covers the void of a receipt dated before the cutover. The browser company had no document before its cutover.
- The translation run used a clean worktree at HEAD, so uncommitted work stayed out of the catalogs. The glossary checker reports 34 terminology violations in the new strings. To fix them, follow
.ai/plans/2026-08-27-translation-consistency-runbook.md. Do not run/translateagain.
Review fixes (2026-10-09)
38602af774 — the cutover schema and reads
- The migration
20261009004448sets the cutover of a demo-template company by itsJE-SEED-%journal, the test the accounting reset used. It no longer readsaccountingEnabled, because only the dev CLI set that flag. - A dataset apply can move a cutover that is already set. The tiers set the session flag
app.dataset_apply, and the config-lock trigger allows the change only under it. journal_posting_statusreadscompanySettingsFOR SHARE. So the SQL job costing waits for the enable, as the TSjournalPostingStatusdoes.- Migration Clearing must be an Equity account. The opening journal signs each line by its account class, and
buildOpeningJournalLinesasserts that it balances. - The unapplied credit of a legacy payment opens from the payment and its settlements.
- RLS keeps clients off Provisional and Superseded journals (
20261009145218). The journal attach guard of a charge or reimbursement takes only a journal with a line for that document (20261009145057). - The cutover reads split into one module per wizard step under
packages/database/src/accounting-cutover/. The shared constants and the natural-sign helper live inshared.ts.
b9f897608c — the posting paths, the enable and the legacy backfill
- Return shipments and the sales return receipt refuse when the defaults read fails. Before, they skipped the journal.
assertPostingStatusUnchanged(@carbon/database/journal-posting-status) replaces about 40 inline copies of the status re-read.- Payment posting and its rebuild share one input assembler,
assemblePaymentJournal(post-payment/journal-input.ts). A parity test covers them. The rebuilds moved topost-payment/rebuild-journal.tsandpost-memo/rebuild-journal.ts. - A default with a fallback (
DEFAULT_FALLBACKS) uses the fallback before and after the cutover. A schedule row never takes a stand-in. A missing default throwsMissingAccountDefaultError, status 400, with the label fromOPTIONAL_DEFAULT_LABELS. - The AGPL helper
@carbon/database/payment-processor-feereplaces the copied processor fee logic. - After the enable, a time entry posted before the cutover refuses a re-post, a reversal or an edit (
TIME_ENTRY_BEFORE_CUTOVER_ERROR). - One cost-relief engine,
@carbon/database/cost-relief, drives COGS, the legacy backfill and the re-cost. A job return is not a cost layer. The re-cost keeps the cost of a serial unit revaluation (recost-serial-unit,costLedgerType"Revaluation"). - The legacy detection leaves out a document whose builder writes no line. Each outbound cost row carries a journal pair, so the re-cost never refuses with a 409.
- A legacy backfill journal with a stored cost stays out of provider sync. An intercompany elimination line moves with the stand-in line it copies.
- The repair (
journal-legacy-documents) skips only data refusals. A one-off script can defer with exit code 75 (ONE_OFF_SCRIPT_DEFERRED) instead of failing the deploy.
f1fe2b6c81 — the enable wizard and the accounting module
hasAccountingCutover(accounting.utils.ts) is the one way the ERP asks whether a company has a cutover. Shared constants come from@carbon/database/accounting-cutover. The routes import the reads directly, with no pass-through layer.- Asset registration requires its posting. It reads the status once, inside the transaction.
- The trial balance CSV import uses a pure parser with tests (
trial-balance-csv.ts). It refuses an ambiguous amount. Before, it stripped commas. - The server computes the inventory totals. A user without
update: partssees each cost as read-only. The wizard translates the readiness details, plurals, statuses and CSV errors. - The settings action checks permissions before it reads the form.
188a710e24 — the journal status check and the last review gaps
journal-status-filterchecks one statement at a time. It sees a qualified or aliased journal status and raw SQL in TS, and it drops 2 false positives. The dead Draft filter onjournalLinesis gone fromaccounting.service.ts.insertProvisionalJournalskeeps each journal that the legacy backfill or the repair writes out of provider sync (codeCUTOVER_REBUILT). The sync warnings stay true after the cutover.- A write to
companyorcompanySettingsmust filter byid(no-unscoped-kysely-write). - The ee Stripe fees use the AGPL processor-fee helper. The sync code uses the shared status lists. The revenue recognition cron reads its companies in one query.
- Settings asks
hasLegacyDocuments(one EXISTS) and streams the count. Readiness returns reason codes that the wizard translates. The opening inventory and the reads share one valuation and layer rule. - An outbound adjustment always writes its journal pair, also at zero (
lib/post-adjustment.ts).