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.
Chart of Accounts Import — implementation plan
Spec: .ai/specs/2026-10-12-chart-of-accounts-import.md Research: .ai/research/chart-of-accounts-remap.md Branch: chart-of-accounts-mapping-import
Tasks 1–19 below build the first design: one sheet with a
Carbon Accountcolumn, reclass journals and inactive accounts. The user's review replaced it with 2 required files and an import that runs only before the cutover. The spec's changelog ("Redesign after user review") has the new design. Tasks 21–27 are the redesign. Read the spec, not Tasks 10–15, for the current behavior.
Progress
- Task 1: Make account deletes refuse while lines refer to the account
- Task 2: Regenerate the database types
- Task 3: Add the import constants and types to
@carbon/database - Task 4: Write the planner tests (red)
- Task 5: Implement
planAccountImport(green) - Task 6: Implement
loadAccountImportContext - Task 7: Add the
apply-account-importserver function - Task 8: Add the live-database tests for the server function
- Task 9: Stop stamping a cutover on new companies, and seed subsidiary defaults by id
- Task 10: Add
activeto the account form - Task 11: Offer Deactivate when an account is in use
- Task 12: Add the CSV parser for the import
- Task 13: Add the template download route
- Task 14: Add the import route and review page
- Task 15: Add Import, Download and Show inactive to the Chart of Accounts page
- Task 16: Add the Chart of accounts step to the activation wizard
- Task 17: Show the Accounting module in the Implementation Hub before cutover
- Task 18: Add the sync callout to accounting integrations
- Task 19: Update the docs, rules and AGENTS.md files
- Task 20: Verify in the browser
- Task 21: Plan from 2 files:
planAccountImport(chartRows, defaultRows, ctx, resolutions), refuse on any cutover, drop reclass and deactivate - Task 22: Apply from 2 files: set every company's defaults and fixed asset class accounts, delete instead of deactivate
- Task 23: Copy a subsidiary's fixed asset class accounts from the group in
seed-company - Task 24: Remove the Active switch, Show inactive, Download and the deactivate intent; disable Delete for an account with journal lines
- Task 25: Add
parseChartCsv,parseDefaultsCsv,defaultAccountsTemplateand the template route - Task 26: Rewrite the import page for 2 uploads; no header rule on a setup page with no steps
- Task 27: Update the spec, docs and AGENTS.md files
- Task 28: Move posted documents with their journals (
20261013035046) - Task 29: Fix the self-review findings (spec changelog 2026-10-13)
Dependencies
- Task 2 needs Task 1.
- Tasks 3 → 4 → 5 → 6 → 7 → 8 run in order.
- Task 9 is independent. It may run in parallel with Tasks 3–8.
- Tasks 10, 11 and 12 are independent of each other. They need Task 2.
- Task 13 needs Task 3 (
ROLE_NAMES). - Task 14 needs Tasks 7 and 12.
- Task 15 needs Tasks 13 and 14.
- Task 16 needs Task 14.
- Tasks 17 and 18 are independent.
- Task 19 needs Tasks 1–18.
- Task 20 needs every other task.
Shared terms
| Term | Meaning |
|---|---|
| leaf account | An account row with isGroup = false |
| group | An account row with isGroup = true |
| control role | An entry of CONTROL_ROLES (Task 3) |
| required role | An ACCOUNT_DEFAULT_COLUMNS entry that hasDefaultFallback returns false for |
| posted lines | journalLine rows whose journal status is in GL_JOURNAL_STATUSES or is Superseded (hasPostedLines) |
| reclass balance | Σ amount of lines whose journal status is in GL_JOURNAL_STATUSES only. Never Superseded. |
| movable reference | A reference that REFERENCE_POLICY lets the apply re-point (Task 3) |
Task 1: Make account deletes refuse while lines refer to the account
Depends on: none Files:
- Create:
packages/database/supabase/migrations/{timestamp}_account-delete-restrict.sql(via the command below) - Copy from (precedent):
packages/database/supabase/migrations/20260315000000_reset-chart-of-accounts.sqllines 461–478
Steps:
- Run
pnpm db:migrate:new account-delete-restrict. - Write this SQL into the new file:
-- A journal line or a document line must never lose its account. SET NULL
-- silently emptied Draft and Provisional lines when an account was deleted.
-- RESTRICT refuses the delete, so the user deactivates the account instead.
ALTER TABLE "journalLine" DROP CONSTRAINT IF EXISTS "journalLine_accountId_fkey";
ALTER TABLE "journalLine" ADD CONSTRAINT "journalLine_accountId_fkey"
FOREIGN KEY ("accountId") REFERENCES "account"("id") ON UPDATE CASCADE ON DELETE RESTRICT;
ALTER TABLE "purchaseOrderLine" DROP CONSTRAINT IF EXISTS "purchaseOrderLine_accountId_fkey";
ALTER TABLE "purchaseOrderLine" ADD CONSTRAINT "purchaseOrderLine_accountId_fkey"
FOREIGN KEY ("accountId") REFERENCES "account"("id") ON UPDATE CASCADE ON DELETE RESTRICT;
ALTER TABLE "salesOrderLine" DROP CONSTRAINT IF EXISTS "salesOrderLine_accountId_fkey";
ALTER TABLE "salesOrderLine" ADD CONSTRAINT "salesOrderLine_accountId_fkey"
FOREIGN KEY ("accountId") REFERENCES "account"("id") ON UPDATE CASCADE ON DELETE RESTRICT;
ALTER TABLE "salesInvoiceLine" DROP CONSTRAINT IF EXISTS "salesInvoiceLine_accountId_fkey";
ALTER TABLE "salesInvoiceLine" ADD CONSTRAINT "salesInvoiceLine_accountId_fkey"
FOREIGN KEY ("accountId") REFERENCES "account"("id") ON UPDATE CASCADE ON DELETE RESTRICT;
ALTER TABLE "purchaseInvoiceLine" DROP CONSTRAINT IF EXISTS "purchaseInvoiceLine_accountId_fkey";
ALTER TABLE "purchaseInvoiceLine" ADD CONSTRAINT "purchaseInvoiceLine_accountId_fkey"
FOREIGN KEY ("accountId") REFERENCES "account"("id") ON UPDATE CASCADE ON DELETE RESTRICT;
ALTER TABLE "supplierQuoteLine" DROP CONSTRAINT IF EXISTS "supplierQuoteLine_accountId_fkey";
ALTER TABLE "supplierQuoteLine" ADD CONSTRAINT "supplierQuoteLine_accountId_fkey"
FOREIGN KEY ("accountId") REFERENCES "account"("id") ON UPDATE CASCADE ON DELETE RESTRICT;
- Run
pnpm db:migrate.
Verify:
pnpm exec tsx scripts/run-local-accounting-check.ts psql -X -At -c "SELECT conname, confdeltype FROM pg_constraint WHERE conname IN ('journalLine_accountId_fkey','purchaseOrderLine_accountId_fkey','salesOrderLine_accountId_fkey','salesInvoiceLine_accountId_fkey','purchaseInvoiceLine_accountId_fkey','supplierQuoteLine_accountId_fkey') ORDER BY 1"
# Expected: 6 rows, each ending in |r
Out of scope: shippingMethod_carrierAccountId_fkey keeps SET NULL. Do not touch any other foreign key.
Task 2: Regenerate the database types
Depends on: 1 Files:
- Modify:
packages/database/src/types.ts(generated)
Steps:
- Run
pnpm run generate:types.
Verify:
git status --short packages/database/src
# Expected: no error from generate:types. types.ts may be unchanged, because foreign key actions do not appear in the types.
Out of scope: Never hand-edit types.ts.
Task 3: Add the import constants and types to @carbon/database
Depends on: 2 Files:
- Create:
packages/database/src/account-import.ts - Modify:
packages/database/package.json— add"./account-import": "./src/account-import.ts"next to"./supersession-pick" - Copy from (precedent):
packages/database/src/supersession-pick.ts(a pure module with a sibling test),packages/database/src/accounting-cutover/shared.tslines 65–141 (ACCOUNT_DEFAULT_COLUMNSand the compile-timeNevercheck)
Steps:
- Start the file with its SPDX header. Run
pnpm --filter @carbon/checks license-headersto write it. - Export
ROLE_NAMES: Record<AccountDefaultColumn, string>. Copy each English label fromapps/erp/app/modules/accounting/ui/AccountDefaults/AccountDefaultsForm.tsx. Usesatisfiesso a missing column fails the build. - Export
CONTROL_ROLESwith exactly these 14 entries:receivablesAccount,payablesAccount,rawMaterialsAccount,finishedGoodsAccount,workInProgressAccount,costOfGoodsSoldAccount,goodsReceivedNotInvoicedAccount,retainedEarningsAccount,migrationClearingAccount,intercompanyReceivablesAccount,intercompanyPayablesAccount,bankCashAccount,bankLocalCurrencyAccount,bankForeignCurrencyAccount. - Export
requiredRoles(): AccountDefaultColumn[]. It returns everyACCOUNT_DEFAULT_COLUMNSentry wherehasDefaultFallback(role)is false. - Export
REFERENCE_POLICYas a readonly array of the following entries. Each entry is{ table, column, policy, parent? }.policyis"repoint","repoint-if-draft","repoint-if-unposted-journal"or"history".parentis{ table, column, statusColumn, draftStatuses }. A row that a conditional policy does not move counts as a history reference.
| table | column | policy | parent |
|---|---|---|---|
fixedAssetClass |
each of assetAccountId, accumulatedDepreciationAccountId, depreciationExpenseAccountId, writeOffAccountId, writeDownAccountId, lossOnDisposalAccountId, gainOnDisposalAccountId |
repoint | — |
shippingMethod |
carrierAccountId |
repoint | — |
purchaseOrderLine |
accountId |
repoint | — |
salesOrderLine |
accountId |
repoint | — |
supplierQuoteLine |
accountId |
repoint | — |
revenueRecognitionSchedule |
debitAccountId, creditAccountId |
repoint | — |
salesInvoiceLine |
accountId |
repoint-if-draft | salesInvoice.id via invoiceId, status = 'Draft' |
purchaseInvoiceLine |
accountId |
repoint-if-draft | purchaseInvoice.id via invoiceId, status = 'Draft' |
chargeLine |
accountId |
repoint-if-draft | charge.id via chargeId, status = 'Draft' |
charge |
cardAccountId, offsetAccountId |
repoint-if-draft | the row itself, status = 'Draft' |
reimbursementLine |
accountId |
repoint-if-draft | reimbursement.id via reimbursementId, status = 'Draft' |
reimbursement |
payableAccountId |
repoint-if-draft | the row itself, status = 'Draft' |
payment |
bankAccount |
repoint-if-draft | the row itself, status = 'Draft' |
memo |
reasonAccount |
repoint-if-draft | the row itself, status = 'Draft' |
journalLine |
accountId |
repoint-if-unposted-journal | journal.id via journalId, status IN ('Draft','Provisional') |
accountingPeriodBalance |
accountId |
history | — |
accountingSyncTieOut |
accountId |
history | — |
- Do not list
accountDefaultoraccount.parentIdinREFERENCE_POLICY. The apply moves default roles throughroleMoves, and a leaf has no children. - If the tables
project,projectElement,indirectPool,indirectPoolAccountandindirectExpenseStatementexist inpackages/database/src/types.tswhen you run this task, add these entries:
| table | column | policy |
|---|---|---|
project |
costAccountId |
repoint |
projectElement |
costAccountId |
repoint |
indirectPool |
appliedAccountId |
repoint |
indirectPoolAccount |
accountId |
repoint, with dedupeOn: ["indirectPoolId", "accountId", "dimensionValueId", "role"] |
indirectExpenseStatement |
accountId |
history |
If they do not exist, add a comment above REFERENCE_POLICY that lists the same 5 entries. The branch that merges second adds them.
8. Export SOFT_REFERENCES, which lists the 3 references without a foreign key: intercompanyEliminationLine.accountId (re-point when its journalLineId's journal is Draft or Provisional), externalIntegrationMapping rows with entityType = 'account' (delete the source's rows), and companyIntegration.metadata.paymentFeeAccount (re-point).
9. Export these types. Use AccountClass from ./ledger and AccountDefaultColumn from ./accounting-cutover/shared:
export type AccountImportRow = {
line: number; // file line; the header is line 1
number: string;
name: string;
class: AccountClass | null;
accountType: string | null;
group: string;
carbonAccounts: string[]; // numbers or role names, split on ";" and trimmed
};
export type ChartAccount = {
id: string; number: string | null; name: string; class: AccountClass | null;
accountType: string | null; incomeBalance: "Balance Sheet" | "Income Statement";
parentId: string | null; isGroup: boolean; isSystem: boolean; active: boolean;
};
export type AccountUsage = {
// Lines on Posted, Reversed or Superseded journals. Blocks a class change and
// a control-account merge, and forces deactivate instead of delete.
hasPostedLines: boolean;
// Σ amount on Posted and Reversed journals only (GL_JOURNAL_STATUSES), per
// company, nonzero only. Superseded is excluded: activation replaced it.
reclassBalanceByCompany: Record<string, number>;
movableReferencesByCompany: Record<string, number>; // rows REFERENCE_POLICY moves
historyReferences: number; // rows it never moves
};
export type AccountImportCompany = { id: string; name: string; hasCutover: boolean };
export type AccountImportContext = {
chart: ChartAccount[]; // active AND inactive
companies: AccountImportCompany[];
defaultsByCompany: Record<string, Record<AccountDefaultColumn, string | null>>;
usage: Record<string, AccountUsage>; // by account id
importingCompanyId: string;
};
export type AccountImportResolutions = {
targets: Record<string, number>; // unclaimed account id → row line it merges into
};
- Export the error and exception unions:
export type AccountImportError =
| { code: "duplicate-number"; line: number; firstLine: number; value: string }
| { code: "duplicate-name"; line: number; firstLine: number; value: string }
| { code: "unknown-carbon-account"; line: number; value: string }
| { code: "carbon-account-claimed-twice"; line: number; firstLine: number; accountId: string }
| { code: "class-mismatch"; line: number; accountId: string }
| { code: "missing-class"; line: number }
| { code: "class-change-with-history"; line: number; accountId: string }
| { code: "control-account-with-history"; accountId: string; role: AccountDefaultColumn }
| { code: "migration-clearing-not-equity"; line: number }
| { code: "taken-by-inactive-account"; line: number; field: "number" | "name"; accountId: string; retiredByThisImport: boolean }
| { code: "target-not-in-sheet"; accountId: string; line: number };
export type AccountImportException = {
code: "account-needs-target";
accountId: string;
reasons: ("references" | "required-role" | "balance")[];
companyIds: string[];
};
- Export the plan type:
export type AccountImportPlan = {
renames: { accountId: string; line: number; number: string; name: string; group: string; accountType: string | null; reactivate: boolean }[];
creates: { line: number; number: string; name: string; class: AccountClass; accountType: string | null; group: string }[];
merges: { sourceId: string; targetLine: number }[];
retires: { accountId: string; mode: "delete" | "deactivate" }[];
roleMoves: { companyId: string; role: AccountDefaultColumn; fromAccountId: string; toLine: number | null }[]; // null = clear
reclasses: { companyId: string; sourceId: string; targetLine: number; amount: number }[];
groupCreates: { name: string; class: AccountClass }[];
companies: { companyId: string; repointedReferences: number; roleMoves: number; reclasses: number }[];
errors: AccountImportError[];
exceptions: AccountImportException[];
};
Verify:
pnpm exec turbo run typecheck --filter=@carbon/database
# Expected: Tasks: 1 successful
Out of scope: No planner logic yet. No database reads in this file except in Task 6.
Task 4: Write the planner tests (red)
Depends on: 3 Files:
- Create:
packages/database/src/account-import.test.ts - Copy from (precedent):
packages/database/src/supersession-pick.test.ts
Steps:
- Build a fixture chart in the test file: a Balance Sheet root, an Income Statement root, 3 groups ("Current Assets", "Revenue", "Equity") and 9 leaf accounts. The leaves are 1010 Cash, 1110 Receivables, 1310 Raw Materials, 1320 Finished Goods, 3400 Migration Clearing, 3900 Retained Earnings, 4010 Sales, 4050 Shipping Revenue and an inactive 4090 Old Sales.
- Build 2 companies:
c1(no cutover) andc2(has a cutover). Give both the same defaults. PointreceivablesAccountat 1110,rawMaterialsAccountat 1310,finishedGoodsAccountat 1320,salesAccountat 4010,salesShippingRevenueAccountat 4050,migrationClearingAccountat 3400 andretainedEarningsAccountat 3900. - Add a helper
templateRows(chart)that returns one row per ACTIVE leaf withcarbonAccounts: [number]. - Add a helper
usage(partial)that fills the emptyAccountUsagedefaults. - Write one
itper case below. Each asserts the exact plan fields named.
| # | Case | Expected |
|---|---|---|
| 1 | templateRows unchanged |
every action array is empty; no errors; no exceptions |
| 2 | 1110 renumbered to 1200 and renamed | one renames entry with reactivate: false; no other action |
| 3 | 1010 ↔ 4010 numbers swapped (class kept) | 2 renames; no errors |
| 4 | 4010 row says 4010; 4050, 4050 row removed |
merges has 4050 → the 4010 row; roleMoves moves salesShippingRevenueAccount in c1 and c2; retires has 4050 as delete |
| 5 | 1310 row says 1310; 1320, 1320 row removed, no posted lines |
merge allowed (control roles with no history) |
| 6 | case 5, but 1320 hasPostedLines |
error control-account-with-history |
| 7 | 4050 row removed, no row names it, no resolution | exception account-needs-target with reason required-role (only if hasDefaultFallback("salesShippingRevenueAccount") is false; else the role is cleared and 4050 deleted — assert whichever hasDefaultFallback returns) |
| 8 | case 7 with resolutions.targets[4050.id] = the 4010 row |
no exception; merges has 4050 → 4010 row; the role moves |
| 9 | an account with no roles and no usage removed | retires entry with mode delete; no exception |
| 10 | an account with no roles and movableReferencesByCompany: { c1: 2 } removed |
exception with reason references and companyIds: ["c1"] |
| 11 | case 10 with a target | merges entry; retires mode delete; companies has c1 with repointedReferences: 2 |
| 12 | an account with reclassBalanceByCompany: { c2: 500 } and a target |
reclasses entry for c2 with amount 500; retires mode deactivate |
| 13 | an account with hasPostedLines: true and reclassBalanceByCompany: {} (Superseded only), removed |
no exception; no reclass; retires mode deactivate |
| 14 | a new row with empty carbonAccounts |
one creates entry |
| 15 | a new row with no class | error missing-class |
| 16 | 2 rows with the same number | error duplicate-number with both lines |
| 17 | 2 rows naming 1110 | error carbon-account-claimed-twice |
| 18 | a row naming Accounts Receivable |
resolves to 1110 through ROLE_NAMES and defaultsByCompany[importingCompanyId] |
| 19 | a row naming 9999 |
error unknown-carbon-account |
| 20 | row for 4010 with class Asset | error class-mismatch |
| 21 | 3400 row with class Revenue | error migration-clearing-not-equity |
| 22 | a row with group "Other Assets" | groupCreates has "Other Assets" with the row's class |
| 23 | a new row with number 4090 | error taken-by-inactive-account, field: "number", retiredByThisImport: false |
| 24 | a row whose carbonAccounts is 4090 |
renames entry with reactivate: true; no error |
| 25 | case 12 (4050 deactivated) plus a new row with number 4050 | error taken-by-inactive-account, retiredByThisImport: true |
| 26 | an unclaimed inactive account | no action; it is not retired again |
- Run the tests. They must fail, because
planAccountImportdoes not exist yet.
Verify:
pnpm --filter @carbon/database exec vitest run src/account-import.test.ts
# Expected: FAIL — planAccountImport is not exported (or not a function)
Out of scope: No implementation in this task.
Task 5: Implement planAccountImport (green)
Depends on: 4 Files:
- Modify:
packages/database/src/account-import.ts
Steps:
- Add
export function planAccountImport(rows: AccountImportRow[], ctx: AccountImportContext, resolutions: AccountImportResolutions): AccountImportPlan. - Keep the function pure. It reads only its arguments.
- Implement these passes in order:
- Validate rows. Check duplicate numbers and names (trimmed, case-insensitive), and a missing class on rows with no
carbonAccounts. - Resolve each
carbonAccountsvalue. First match a leafnumber, active or inactive. Else match aROLE_NAMESvalue, case-insensitive, throughctx.defaultsByCompany[ctx.importingCompanyId]. Else addunknown-carbon-account. - Record which row claims each account. A second claim adds
carbon-account-claimed-twice. - For each row with claims: the first claimed account is the rename target. Set
reactivatewhen it is inactive. Every other claimed account becomes a merge source into that row. - Compare classes. A row's class defaults to its first claimed account's class. Any claimed account with a different class adds
class-mismatch. A rename that changes the class of an account withhasPostedLinesaddsclass-change-with-history. - Unclaimed accounts are the ACTIVE leaves that no row claims. Inactive leaves and groups are never unclaimed.
- Sort each unclaimed account:
- Collect its reasons:
referencesif anymovableReferencesByCompanyvalue is above 0;required-roleif arequiredRoles()column points at it in any company;balanceifreclassBalanceByCompanyhas any entry. - If there are reasons and
resolutions.targets[id]names a row, make it a merge source into that row. If that line is not a row, addtarget-not-in-sheet. - If there are reasons and no target, add exception
account-needs-targetwith the reasons and the companies involved. - If there are no reasons, clear each role that points at it (all of them have a fallback, by step 7.1), and retire it.
- Collect its reasons:
- Role moves: for every company and every role whose account is a merge source, move the role to the merge row.
- Control check: if a merge source backs a
CONTROL_ROLESrole in any company andhasPostedLinesis true, addcontrol-account-with-history. - Reclasses: for each merge source, add one
reclassesentry per company inreclassBalanceByCompany. - Retires: each merge source and each unclaimed account without reasons retires. Use
deactivatewhenhistoryReferences > 0orhasPostedLines. Else usedelete. - Inactive collisions: build the set of numbers and names held by inactive leaves that no row claims, plus accounts that step 11 deactivates. A row whose
numberornameis in that set addstaken-by-inactive-account. SetretiredByThisImportfor the second kind. - Groups: collect each
groupvalue that matches no existing group name. Add it togroupCreateswith the row's class. - Migration Clearing: if the row that ends up holding
migrationClearingAccountfor the importing company has a class other than Equity, addmigration-clearing-not-equity. - Companies: for each company, sum the merge sources'
movableReferencesByCompany, count itsroleMovesand itsreclasses. List each company with a nonzero total.
- Validate rows. Check duplicate numbers and names (trimmed, case-insensitive), and a missing class on rows with no
- Sort every output array by
line, then by account number, so the output is deterministic. - Use
roundfrom./precisionon each reclass amount. Useequalsfrom./precisionto drop zero balances.
Verify:
pnpm --filter @carbon/database exec vitest run src/account-import.test.ts
# Expected: 26 passed
Out of scope: No database access. No writes.
Task 6: Implement loadAccountImportContext
Depends on: 5 Files:
- Modify:
packages/database/src/account-import.ts - Copy from (precedent):
packages/database/src/accounting-cutover/readiness.ts(Kysely reads that takedb)
Steps:
- Add
export async function loadAccountImportContext(db: Kysely<KyselyDatabase> | Transaction<KyselyDatabase>, companyGroupId: string, importingCompanyId: string): Promise<AccountImportContext>. - Read the chart with one query on
accountwherecompanyGroupIdmatches. Include inactive accounts. - Read the group's companies with one query on
companyjoined tocompanySettings. SethasCutoverfromaccountingCutoverDate IS NOT NULL. - Read
accountDefaultwith one query joined tocompanyoncompany.companyGroupId. - Read journal usage with one query. Join
journalLinetojournal. Filterjournal.statusin[...GL_JOURNAL_STATUSES, "Superseded"]andjournal.companyIdin the group's companies. Group byjournalLine.accountId,journal.companyIdandjournal.status.- Any row sets
hasPostedLines. - Only rows with a status in
GL_JOURNAL_STATUSESadd toreclassBalanceByCompany.
- Any row sets
- Read reference counts with one
UNION ALLquery built fromREFERENCE_POLICY. Each branch selectsaccountId,companyIdand amovableflag. The flag is true when the policy's parent filter matches. Group by all 3. Never query once per account. - Return the context. An account with no usage rows gets
{ hasPostedLines: false, reclassBalanceByCompany: {}, movableReferencesByCompany: {}, historyReferences: 0 }.
Verify:
pnpm exec turbo run typecheck --filter=@carbon/database
# Expected: Tasks: 1 successful
Out of scope: Do not change readiness.ts.
Task 7: Add the apply-account-import server function
Depends on: 6 Files:
- Create:
packages/server-functions/src/apply-account-import/index.ts - Modify:
packages/server-functions/src/invoke.ts— add"apply-account-import": () => import("./apply-account-import"),in alphabetical order - Modify:
packages/server-functions/src/__snapshots__/permissions-manifest.test.ts.snap(regenerated by the test run) - Copy from (precedent):
packages/server-functions/src/activate-accounting/index.tslines 45–76 and 207–255 (the opening journal insert)
Steps:
- Define the input:
export const applyAccountImportInput = z.object({
rows: z.array(z.object({
line: z.number().int(), number: z.string().min(1), name: z.string().min(1),
class: z.enum(["Asset","Liability","Equity","Revenue","Expense"]).nullable(),
accountType: z.string().nullable(), group: z.string().min(1),
carbonAccounts: z.array(z.string())
})).min(1),
resolutions: z.object({ targets: z.record(z.string(), z.number().int()) })
});
- Use
defineServerFn({ name: "apply-account-import", input: applyAccountImportInput, permissions: { update: "accounting" }, run }). Export it as the default export. - In
run, opendb.transaction().execute(async (trx) => …). - Read the company's
companyGroupIdfromcompanyontrx. - Lock the chart:
SELECT id FROM account WHERE "companyGroupId" = $1 FOR UPDATE. - Call
loadAccountImportContext(trx, companyGroupId, companyId)and thenplanAccountImport. - If
plan.errorsorplan.exceptionsis non-empty, throwInvalidInputErrorwith the counts. - Create each
groupCreatesgroup under the root whoseincomeBalancematches the class. UseisGroup: true,number: nullandcreatedBy: userId. - Rename in 2 passes:
- Set
number = '__import_' || idandname = '__import_' || idon every renamed account. - Set the final
number,name,accountTypeandparentId. TakeparentIdfrom the group's id. Setactive = truewhenreactivateis true.
- Set
- Insert each
createsrow as a leaf. DeriveincomeBalancefrom the class. UseconsolidatedRate: "Average". Build aline → accountIdmap that covers renamed rows and created rows. - For each merge, run one
UPDATEperREFERENCE_POLICYentry. Re-point the source id to the target id. Apply the policy's parent filter:repoint-if-draftusesWHERE <parent>.status = 'Draft'.repoint-if-unposted-journalusesWHERE journal.status IN ('Draft','Provisional').- An entry with
dedupeOnthen deletes every row but the oldest in eachdedupeOngroup that holds the target id.
- For each merge, also run the 3
SOFT_REFERENCESsteps. - Apply
roleMoveswith oneUPDATE "accountDefault"per company. Set each role column to the target row's account id, ornullfor a clear. - Post each
reclassesentry as one journal per company:- Resolve the period with
resolveAccountingPeriod(trx, companyId, today, "current"). Gettodayfromdatetime.todayin the company's timezone. - Insert the journal:
sourceType: "Manual",status: "Posted",description: "Chart of accounts import: <source number> → <target number>". - Get the id with
getNextSequence(trx, "journalEntry", companyId). - Insert 2 lines. The source line is
-amount. The target line is+amount. Both accounts have the same class, so the amounts move the balance as it is stored. - Use
journalLineReference: nanoid()on each line.
- Resolve the period with
- Apply
retires. UseDELETEfor modedelete. UseUPDATE account SET active = falsefor modedeactivate. - Delete each non-system group that has no children. Repeat until no group is deleted.
- Check the postcondition. If any check fails, throw
InvalidInputError:- The active leaf accounts of the group equal the rows by number, name and class.
- In every company of the group, each
requiredRoles()column points at an active leaf account. migrationClearingAccountpoints at an Equity account.
- Return
{ counts: { renamed, reactivated, created, merged, deleted, deactivated }, reclassJournalIds }. - If
resolveAccountingPeriodrefuses because no period is open, STOP and report. Do not create a period here.
Verify:
pnpm --filter @carbon/server-functions exec vitest run src/permissions-manifest.test.ts -u
pnpm exec turbo run typecheck --filter=@carbon/server-functions --concurrency=1
# Expected: the snapshot gains "apply-account-import" with { update: "accounting" }; typecheck: Tasks: 1 successful
Out of scope: Do not change activate-accounting. Do not add a Reclass journal source type.
Task 8: Add the live-database tests for the server function
Depends on: 7 Files:
- Create:
packages/server-functions/src/apply-account-import/apply-account-import.test.ts - Copy from (precedent):
packages/server-functions/src/activate-accounting/activation-test-fixture.ts,packages/server-functions/src/local-database-test-fixture.ts(databaseTest)
Steps:
- Build a fixture group with one Provisional company (no cutover) and one company that has a cutover and an open period.
- Write one
databaseTestper case:
| # | Case | Expected |
|---|---|---|
| 1 | Rename and swap numbers on the Provisional company | accountDefault ids unchanged; numbers swapped |
| 2 | Merge 4050 into 4010 with a Provisional line on 4050 | the line's accountId is 4010's id; 4050 deleted |
| 3 | Remove the 4050 row with a Provisional line on 4050 and a target of the 4010 row | the line moves; 4050 deleted; no foreign key error |
| 4 | Merge with a Posted line on 4050 in the cutover company | one reclass journal, Posted, balanced; 4050 inactive; the Posted line still on 4050 |
| 5 | Merge with only a Superseded line on 4050 | no reclass journal; 4050 inactive |
| 6 | Remove a row that a required role needs, with no target | InvalidInputError; nothing changed |
| 7 | Reference completeness | a query of pg_constraint for every foreign key with confrelid = 'account'::regclass returns only columns that REFERENCE_POLICY lists, plus accountDefault columns and account.parentId |
- Write case 7's query as in
packages/database/supabase/tests/ramp-charge-integrity.test.sqllines 12–28.
Verify:
pnpm --filter @carbon/server-functions exec vitest run src/apply-account-import
# Expected: 7 passed (they skip if SUPABASE_DB_URL is not localhost — then run `pnpm db:migrate` and rerun)
Out of scope: Do not change existing fixtures.
Task 9: Stop stamping a cutover on new companies, and seed subsidiary defaults by id
Depends on: none Files:
- Modify:
packages/server-functions/src/seed-company/index.ts— lines 394–444 and 492–506 - Modify:
packages/database/src/datasets/tiers/01-foundation.ts— the comment at lines 57–63 only
Steps:
- Delete the cutover block at
seed-company/index.tslines 492–506 ("A new company keeps its ledger in Carbon from day one…"). - Remove the imports that only that block used (
startOfMonth,getCompanyTimeZone), if nothing else uses them. - In the subsidiary branch, read one
accountDefaultrow from a company in the same group. UseparentCompanyIdfirst, else any company withcompany.companyGroupId = companyGroupId. - If that row exists, copy every
ACCOUNT_DEFAULT_COLUMNSvalue intoresolvedDefaults. Skip the number lookup at lines 441–444 for those columns. - Keep the number lookup only as the fallback when the group has no
accountDefaultrow. - Keep
resolveShippingDefaultforsalesShippingRevenueAccountwhen the copied row has none. - Change the comment in
01-foundation.tsto say that seed-company no longer stamps a cutover, so tier 01 sets the only one.
Verify:
pnpm --filter @carbon/server-functions exec vitest run src/seed-company
pnpm exec turbo run typecheck --filter=@carbon/server-functions --concurrency=1
# Expected: all seed-company tests pass (shipping-default.test.ts included); typecheck: Tasks: 1 successful
Out of scope: Do not change dataset tier 01's UPSERT. Do not touch existing companies' cutover state.
Task 10: Add active to the account form
Depends on: 2 Files:
- Modify:
apps/erp/app/modules/accounting/accounting.models.ts—accountValidator(lines 329–384): addactive: zfd.checkbox() - Modify:
apps/erp/app/modules/accounting/ui/ChartOfAccounts/ChartOfAccountForm.tsx— add<Boolean name="active" label={tActive} bordered />after thenameinput - Modify:
apps/erp/app/routes/x+/accounting+/charts.$accountId.tsx— addactive: account.activetoinitialValues(lines 163–174) - Modify:
apps/erp/app/routes/x+/accounting+/charts.new.tsx— defaultactive: true - Copy from (precedent):
apps/erp/app/modules/accounting/ui/Dimensions/DimensionForm.tsxline 130
Steps:
- Add the field to the validator.
- Import
Booleanfrom~/components/Formin the form. - Add the switch.
- Set the initial values in both routes.
Verify:
pnpm exec turbo run typecheck --filter=erp
# Expected: Tasks: 1 successful
Out of scope: Do not add active to groupAccountValidator.
Task 11: Offer Deactivate when an account is in use
Depends on: 2 Files:
- Modify:
apps/erp/app/routes/x+/accounting+/charts.delete.$accountId.tsx - Modify:
apps/erp/app/modules/accounting/accounting.service.ts— addgetAccountInUse(client, accountId)anddeactivateAccount(client, accountId, userId) - Copy from (precedent):
apps/erp/app/routes/x+/sales+/no-quote-reasons.delete.$id.tsxlines 55–65 (getDatabaseErrorMessage)
Steps:
- Add
getAccountInUse. It returns true when onejournalLinerow hasaccountId = accountId(.limit(1)). - Add
deactivateAccount. It runsupdate({ active: false, updatedBy })on the account. - In the loader, return
inUsewith the account. - In the action, read
intent. Forintent === "deactivate", calldeactivateAccountand redirect with "Account deactivated". - For a delete error, call
getDatabaseErrorMessage(error, "Failed to delete account", { referenced: "This account has postings. Deactivate it instead." }). - In the component, if
inUse, renderConfirmDeletewith the text "This account has postings. Deactivate it instead." and submitintent=deactivate. IfConfirmDeletecannot take a custom button label, use theModalandButtonfrom@carbon/reactthatConfirmDeleteitself uses.
Verify:
pnpm exec turbo run typecheck --filter=erp
# Expected: Tasks: 1 successful
Out of scope: Do not change the @mcp delete tag on deleteAccount.
Task 12: Add the CSV parser for the import
Depends on: 3 Files:
- Create:
apps/erp/app/modules/accounting/account-import-csv.ts - Create:
apps/erp/app/modules/accounting/account-import-csv.test.ts - Copy from (precedent):
apps/erp/app/modules/accounting/trial-balance-csv.tsand its test
Steps:
- Export
ACCOUNT_IMPORT_CSV_COLUMNS = ["Number","Name","Class","Type","Group","Carbon Account","Used For"] as const. - Export
parseAccountImportCsv(csv: string). It usesparseCsvfrom@carbon/files/csv. - It returns
{ rows: AccountImportRow[]; errors: null } | { rows: null; errors: AccountImportCsvError[] }. - Define the error codes:
empty-file,missing-columns,missing-number(withline),missing-name(withline),missing-group(withline),invalid-class(withlineandvalue). - Split
Carbon Accounton;and trim each part. Drop empty parts. IgnoreUsed For. - Write tests for each error code and for a 3-row valid file.
Verify:
pnpm --filter erp exec vitest run app/modules/accounting/account-import-csv.test.ts
# Expected: all tests pass
Out of scope: Do not touch trial-balance-csv.ts.
Task 13: Add the template download route
Depends on: 3 Files:
- Create:
apps/erp/app/routes/api+/accounting.chart-of-accounts[.]csv.tsx - Modify:
apps/erp/app/utils/path.ts— addchartOfAccountsCsv: \${api}/accounting/chart-of-accounts.csv`next tocostCentersin theapi` block - Modify:
apps/erp/app/modules/accounting/accounting.service.ts— addgetAccountImportTemplate(client, companyGroupId, companyId) - Copy from (precedent):
apps/erp/app/routes/api+/items.methods.$id.bom[.]csv.tsx(theResponsewithContent-Disposition)
Steps:
- Add
getAccountImportTemplate. It reads the active leaf accounts, their group names and the company'saccountDefaultrow. - It builds one row per leaf: number, name, class, type, group name, its own number, and the
ROLE_NAMESof every role that points at it joined with"; ". - In the route loader, call
requirePermissions(request, { view: "accounting" }). - Encode the rows with
encodeCsvfrom@carbon/files/csvandfields: [...ACCOUNT_IMPORT_CSV_COLUMNS]. - Return
new Response(csv, { headers: { "Content-Type": CSV_CONTENT_TYPE, "Content-Disposition": "attachment; filename=chart-of-accounts.csv" } }).
Verify:
pnpm exec turbo run typecheck --filter=erp
# Expected: Tasks: 1 successful
Out of scope: No upload in this task.
Task 14: Add the import route and review page
Depends on: 7, 12 Files:
- Create:
apps/erp/app/routes/x+/accounting+/charts.import.tsx - Create:
apps/erp/app/modules/accounting/ui/ChartOfAccounts/AccountImportReview.tsx - Modify:
apps/erp/app/modules/accounting/ui/ChartOfAccounts/index.ts— export the component - Modify:
apps/erp/app/utils/path.ts— addchartOfAccountsImport: \${x}/accounting/charts/import`next tochartOfAccounts` - Copy from (precedent):
apps/erp/app/routes/x+/accounting+/activation.trial-balance.tsx(intentimport-tb, lines 122–204),apps/erp/app/modules/accounting/ui/Activation/TrialBalanceEditor.tsx(file input,useAction, errorAlert),apps/erp/app/components/Setup/SetupLayout.tsx(SetupFrame,SetupBody,SetupSection,SetupFooter)
Steps:
- Route loader: call
requirePermissions(request, { update: "accounting" }). Return the importing company'scompanyGroupId. - Route action, intent
plan:- Parse
csvwithparseAccountImportCsv. On errors, return{ csvErrors }. - Call
loadAccountImportContext(getDatabaseClient(), companyGroupId, companyId). - Call
planAccountImport(rows, ctx, resolutions). Readresolutionsfrom a JSON form field. Default it to{ targets: {} }. - Return
{ plan, rows, chart, companies }. The review needs the account numbers and names and the company names.
- Parse
- Route action, intent
apply:- Parse
csvagain. - Call
serverFns.as({ client, db: getDatabaseClient(), companyId, userId }).invoke("apply-account-import", { rows, resolutions }). - On error, return a flash error with
getErrorMessage(result.error, "Failed to import the chart of accounts"). - On success, redirect to
path.to.chartOfAccountswith a success flash that states the counts.
- Parse
- Component: render a
SetupFrametitled "Import chart of accounts". - Keep
csvandresolutionsinuseState. On file select, readfile.text(), store it, and submit intentplan. AccountImportReviewrenders:- A summary line with the 5 counts and the reclass count.
- A destructive
Alertthat lists each error with its line, one<li>per error code, asTrialBalanceCsvErrorMessagedoes. - One row per
account-needs-targetexception. Show the account, its reasons asBadges ("References", "Required role", "Balance") and its companies. Add aComboboxof the sheet's rows (number name). On change, setresolutions.targets[accountId]and submit intentplanagain. - A "Companies affected" list from
plan.companies: name, re-pointed references, role moves, reclass journals. Mark a company withhasCutoverwith a "Live"Badge. - One read-only
Tableper action (renamed, merged, new, retired), using~/components/Table. Show "Reactivated" on a rename withreactivate: true.
- The footer has a "Download template" link (
path.to.api.chartOfAccountsCsv) and an Apply button. Disable Apply while any error or exception remains. - Wrap every user-facing string in
tor<Trans>from@lingui/react/macro.
Verify:
pnpm exec turbo run typecheck --filter=erp
pnpm run lint
# Expected: typecheck Tasks: 1 successful; lint reports no errors in the new files
Out of scope: No editable grid. The sheet is the only editor.
Task 15: Add Import, Download and Show inactive to the Chart of Accounts page
Depends on: 13, 14 Files:
- Modify:
apps/erp/app/modules/accounting/ui/ChartOfAccounts/ChartOfAccountsTableFilters.tsx— lines 67–89 - Modify:
apps/erp/app/modules/accounting/accounting.service.ts—getChartOfAccounts(line 2111) gainsargs.includeInactive: boolean - Modify:
apps/erp/app/routes/x+/accounting+/charts.tsx— read?inactive=trueand passincludeInactive - Copy from (precedent): the existing
AppBarActionin the same file
Steps:
- In
getChartOfAccounts, apply.eq("active", true)only whenincludeInactiveis false. - Pass
includeInactive: falsefrom every other caller ofgetChartOfAccounts. Find them withgrep -rn "getChartOfAccounts(" apps/erp/app. - In the filters, add a
Button"Import" linking topath.to.chartOfAccountsImport. Show it whenpermissions.can("update", "accounting"). - Add a
Button"Download" linking topath.to.api.chartOfAccountsCsvwithreloadDocument. - Add a "Show inactive"
Switchthat sets theinactivesearch param.
Verify:
pnpm exec turbo run typecheck --filter=erp
# Expected: Tasks: 1 successful
Out of scope: Do not change ChartOfAccountsTree rendering.
Task 16: Add the Chart of accounts step to the activation wizard
Depends on: 14 Files:
- Modify:
apps/erp/app/modules/accounting/ui/Activation/ActivationSteps.tsx— add"chart"as the first entry ofactivationSteps, and the labelchart: t\Chart of Accounts`` - Modify:
apps/erp/app/utils/path.ts— add"chart"to theaccountingActivationStepunion (lines 50–57) - Modify:
apps/erp/app/routes/x+/accounting+/activation.tsx— change theuseCurrentStepfallback (line 64) to"chart" - Modify:
apps/erp/app/routes/x+/accounting+/activation._index.tsx— redirect to"chart" - Create:
apps/erp/app/routes/x+/accounting+/activation.chart.tsx - Copy from (precedent):
apps/erp/app/routes/x+/accounting+/activation.readiness.tsx
Steps:
- Make the 4 edits above.
- In the new route, render one
SetupSectionwith 2 actions:- A link "Import your chart" to
path.to.chartOfAccountsImport. - A note "Keep Carbon's chart" that the Next button covers.
- A link "Import your chart" to
- Render
<ActivationFooter step="chart" cutoverDate={cutoverDate} canContinue />. - Update the "five steps" doc comment in
ActivationSteps.tsxto "six steps".
Verify:
pnpm exec turbo run typecheck --filter=erp
# Expected: Tasks: 1 successful
Out of scope: Do not change readiness checks.
Task 17: Show the Accounting module in the Implementation Hub before cutover
Depends on: none Files:
- Modify:
apps/erp/app/routes/x+/get-started+/_layout.tsx— theforcedModulesline (about line 239) - Modify:
packages/onboarding/src/content/setup.ts— thechart-of-accountsrow detail (line 57)
Steps:
- Change
forcedModules: accountingSetUp ? [] : ["acc"]toforcedModules: []. - Remove the
accountingSetUpvariable and its import if nothing else uses them. - Change the
chart-of-accountsrow detail tomsg\Import your chart of accounts from a spreadsheet``. - Point
SETUP_SCREEN_PATHS["chart-of-accounts"]atpath.to.chartOfAccountsImport.
Verify:
pnpm exec turbo run typecheck --filter=erp
pnpm exec turbo run typecheck --filter=@carbon/onboarding
# Expected: Tasks: 1 successful for each
Out of scope: Do not change spine.ts or the detection probes.
Task 18: Add the sync callout to accounting integrations
Depends on: none Files:
- Modify:
apps/erp/app/routes/x+/settings+/integrations.$id.tsx— theheaderExtrapassed toIntegrationForm(IntegrationRoute, about line 2145) - Copy from (precedent):
apps/erp/app/modules/settings/ui/ApiKeys/ApiKeysForm.tsxline 195 (Alert variant="info")
Steps:
- In the loader's installed branch, return
accountingSetUp: hasAccountingCutover(companySettings). LoadcompanySettingswithgetCompanySettingsfrom~/modules/settings. - When
providerRole === "accounting"and!accountingSetUp, add anAlert variant="info"toheaderExtra. - The alert title is "Invoices and bills sync after you activate accounting". Link it to
path.to.accountingActivation.
Verify:
pnpm exec turbo run typecheck --filter=erp
# Expected: Tasks: 1 successful
Out of scope: Do not change the syncers in packages/ee.
Task 19: Update the docs, rules and AGENTS.md files
Depends on: 1–18 Files:
- Modify:
apps/erp/app/modules/accounting/AGENTS.md— the wizard has 6 steps; add the import and the RESTRICT rule - Modify:
packages/server-functions/AGENTS.md— listapply-account-import - Modify:
.claude/rules/onboarding-company-templates.md— the cutover section says seed-company stamps a cutover; change it - Modify:
.ai/specs/implemented/2026-10-08-accounting-cutover.md— add a changelog line: §7 is reversed by.ai/specs/2026-10-12-chart-of-accounts-import.md - Modify:
docs/content/docs/reference/account.mdx— add an "Import a chart of accounts" section - Modify:
.ai/lessons.md— add one lesson: "Account deletes are RESTRICT; deactivate an account in use"
Steps:
- Make each edit. Ground each claim in the code from Tasks 1–18.
- Use the
carbon-docsskill for the docs page. - Run the license header fixer.
Verify:
pnpm --filter @carbon/checks license-headers
pnpm --filter docs typecheck
# Expected: no files changed by the fixer on the second run; docs typecheck passes
Out of scope: No changelog entry. That ships separately.
Task 20: Verify in the browser
Depends on: all Files: none
Steps:
- Run
pnpm db:migrate. - Run
pnpm db:check:datasets. - Use
/testwith these flows:- Chart of Accounts → Download → the CSV has one row per leaf and a filled
Used Forcolumn. - Upload the unchanged CSV → the review shows 0 actions.
- Edit the CSV: renumber 1110, merge 4050 into 4010, delete an unused row, add a new row → the review shows each action.
- Remove the Migration Clearing row → the review shows an
account-needs-targetexception with a picker. - Apply → the Chart of Accounts page matches the CSV.
- Delete a row whose account has a Provisional journal line → the review shows "needs a target". Pick a row → Apply succeeds and the line moves.
- Add a row that reuses an inactive account's number → the review shows
taken-by-inactive-account. - Delete an account with a journal line → the modal offers Deactivate.
- Accounting → Activation → the first step is Chart of Accounts.
- Chart of Accounts → Download → the CSV has one row per leaf and a filled
- Save the screenshots under
.context/.
Verify:
pnpm db:check:datasets
# Expected: all four datasets pass
Out of scope: Do not rebuild the database.