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 Module
Chart of accounts, journal entries, general ledger, fiscal periods, currencies, payment terms, cost centers, dimensions, financial reporting (trial balance, balance sheet, income statement), fixed assets with depreciation, intercompany transactions, and external accounting sync (Xero, QuickBooks Online, Rillet).
The reports hub lives inside the accounting module at /x/accounting/reports (with the module sidebar; single "Reports" sidebar item), while the report pages themselves are full-screen in their own namespace apps/erp/app/routes/x+/reports+/ (/x/reports/{balance-sheet,income-statement,executive-pnl,trial-balance,general-ledger,inventory-valuation,revenue-waterfall,rental-utilization,lease-net-investment} — bare-outlet layout, no module sidebar; /x/reports redirects to the hub). Balance sheet and income statement are multi-period: a Columns filter (Monthly default / Quarterly / Yearly) buckets the selected range fiscal-aware via computeReportPeriodBuckets (@carbon/utils) and the accountTreeBalancePeriodSeries RPC returns per-bucket balanceAtDate/netChange in one snapshot-bounded journal scan. Trial balance stays single-period (Beginning/Debit/Credit/Ending derived from netChange by account class).
The General Ledger (general-ledger.tsx, hub card in Close Reports) lists every line of the journalLines view (Posted and Reversed journals only) for one company and a date range: getGeneralLedgerLines (paged, the shared Table with account / source / document type filters, search and sorts) and getAllGeneralLedgerLines (fetchAll, every line) for the Download, served by the resource route general-ledger[.]csv.tsx. The page and the CSV both carry Customer / Supplier, Invoice Number and Supplier Invoice Number (Supplier Invoice Number hidden by default on the page; none sortable or filterable, since they are not view columns): withGeneralLedgerCounterparties reads each line's documentType + documentId (the source record's id; "Invoice" ids are tried in both invoice tables, and a payment line's documentLineReference is the invoice it settles) and generalLedgerCounterparty (accounting.utils.ts) resolves one line. Lines with no customer/supplier document (jobs, inventory, manual entries) leave them blank. Both routes parse the request with resolveGeneralLedgerRequest (general-ledger.server.ts): one company (lines are in its base currency, so "All Companies" is off — allowAllCompanies={false} on ReportFilters) and the trial balance's default range.
Inventory Valuation (inventory-valuation.tsx, gated on view: "accounting") is an inventory-subledger report that lives here (not in the inventory module): it renders the InventoryValuationWorkbench from ~/modules/inventory/ui (on-hand value by location/item, as-of date, with a GL tie-out and a Reconcile action → inventory-valuation.reconcile posting via createInventoryReconciliationJournal, gated on create: "accounting"). Data/UI live in the inventory module; only the route + hub registration are here.
The Executive P&L (executive-pnl.tsx) shares the income statement's loader (same period series, consolidation, and translation) but renders a condensed summary instead of the account tree: computeExecutivePnl (ui/Reports/executivePnl.ts) rolls income-statement leaves up by accountType into Revenue / Cost of Sales / Operating Expenses / Other Income / Other Expense / Tax, then derives Gross Profit, Operating Income, and Net Income with margin-of-revenue percentages. A class-based catch-all keeps Net Income tied out to the income-statement root; ExecutivePnlSummary renders the fixed lines (no search, no drill-down).
Key Domain Concepts
- Chart of Accounts — hierarchical account tree. Accounts have
class(Asset/Liability/Equity/Revenue/Expense),incomeBalance(Balance Sheet/Income Statement), andaccountType. Group accounts contain children; leaf accounts post transactions. Scoped bycompanyGroupId. - Journal Entries — double-entry bookkeeping in the
journaltable.amountuses natural balances: positive Asset/Expense is debit; positive Liability/Equity/Revenue is credit. Convert by account class before summing debit-signed amounts. Lines carry dimensions and cost center allocations. Statuses (journalEntryStatus): a manual entry is Draft → Posted → Reversed; an automatic posting is bornProvisionalbefore the company's accounting cutover andPostedafter it; the enable turns a Provisional journal intoPosted(dated on or after the cutover) orSuperseded(dated before it).JournalEntryStatuslabels Superseded "Before cutover".getJournalEntriesleaves Superseded journals out unless a status filter asks for them. - The accounting cutover (
.ai/specs/implemented/2026-10-08-accounting-cutover.md) — every posting path writes its journal and its sub-ledger rows (cost layers, finished-goods and asset cost, deferral schedules, contract entries, intercompany rows) for every company.companySettings.accountingCutoverDatedecides only the journal status;hasAccountingCutover(settings)(accounting.utils.ts) is the ERP's one test for it.companySettings.accountingEnabledstill exists, but no code reads it.accountingActivatedAt/accountingActivatedByrecord the enable; thecheck_accounting_config_lockedtrigger then refuses any change to the three cutover columns, tocompany.baseCurrencyCodeand tofiscalYearSettings.startMonth. A new company has no cutover:seed-companyleaves it Provisional (.ai/specs/2026-10-12-chart-of-accounts-import.md), so its chart can be imported before anything is Posted, and it goes through the wizard. A company with no cutover sees the wizard instead of the gated pages:AccountingBetaGateoverlays Reports, Intercompany, Journals, Periods and Depreciation Runs with a "Set up accounting" link (Fixed Assets and rental agreements stay open — a depreciation run or disposal is refused on the server instead), andx+/accounting+/_index.tsxredirects to the wizard. A Provisional journal has no accounting period, so it never locks the fiscal calendar (getFiscalCalendarCommittedcounts Posted and Reversed only) and never blocks a period delete. - Journal status lists (
@carbon/database/accounting-posting) — every journal reader filters by one of three lists.GL_JOURNAL_STATUSES(Posted, Reversed): balances, trial balance, reports, period snapshots, tie-outs, provider sync.DOCUMENT_JOURNAL_STATUSES(Provisional, Posted, Reversed): a reader that follows one document's chain — void builders, GR/IR, WIP sums, intercompany lookups.OPEN_ITEM_JOURNAL_STATUSES(Provisional, Posted): payment control lookups and the memo, charge and reimbursement void checks. Superseded is in none. Thejournal-status-filtercheck (@carbon/checks) fails astatus <> 'Draft'journal filter in TS and in migrations from20261009005144. The AR/AP readers (get_ar_open_by_customer,get_ap_open_by_supplier,get_ar_tie_out,get_ap_tie_out) keep= 'Posted'and also acceptsourceType 'Opening Balance'(20261009014620). - Stand-in lines — before the cutover, a posting that needs an empty nullable account default posts the line to
retainedEarningsAccountand names the default it wanted injournalLine.accountDefaultRole(resolveDefaultAccount,@carbon/database/journal-posting-status). A Provisional journal counts nowhere, so the stand-in moves no balance. The enable re-points every stand-in line dated on or after the cutover to its default and clears the role. After the cutover an empty default fails the posting. See → Journals and the accounting cutover below. - Manual accounting work is refused before the cutover with
ACCOUNTING_NOT_STARTED("Set up accounting before you post journals, runs or period closes."):requireAccountingCutover(accounting.service.ts) inpostJournalEntry,reverseJournalEntry,lockAccountingPeriod,closeAccountingPeriodandcreateDepreciationRun;requireGroupAccountingCutover(every company of the group) inrunIntercompanyMatchingandgenerateEliminations; areadAccountingCutoverDatetest (@carbon/database/journal-posting-status) at the top ofpostDepreciationRun,postDisposalandpostRevenueRecognitionRun(accounting.service.ts); andassertAccountingCutover(shared.service.ts, the same read) in thepropose-revenue-recognition-runandrecalculate-revenue-recognition-runpostings. - The enable wizard —
x+/accounting+/activation.tsx(layout,view: accounting, redirects to Periods once the company has a cutover; the cutover date rides the?cutover=search param (ACTIVATION_CUTOVER_PARAM), read bygetActivationCutoverinaccounting.service.ts, which defaults to the first day of the current month) with six steps, each its own route:activation.chart.tsx(links to the chart of accounts import; Next keeps Carbon's chart),activation.readiness.tsx(the date picker — the first day of the current month or of one of the 3 before it,CUTOVER_MAX_PERIODS_BACK— and the six checks ofgetActivationReadiness: everyaccountDefaultaccount column set to an active account, except a default with a fallback (hasDefaultFallback), which may stay empty, andmigrationClearingAccountan Equity account that is not a group; fiscal year settings and base currency; a valid cutover date; no Draft or Pending receipt, shipment or invoice and no Draft payment or memo dated before the cutover; no open job created before the company's first Provisional or Superseded journal; no PostedOpening Balancejournal. EachActivationCheckcarriesreasons, codes (ActivationCheckReason:no-fiscal-year-settings,no-base-currency,migration-clearing-wrong-kindand the fourCutoverDateReasoncodes) thatReadinessChecklisttranslates;detailsays the same in English for the enable's refusal),activation.inventory.tsx(getCutoverInventoryValuation: on-hand at the cutover per item and its unit cost — the replayed layer value for FIFO / LIFO, standard cost for Standard,itemCost.unitCostfor Average, which is the only one the user edits — with each item's value, the value per inventory account and the total, valued as the opening journal values them),activation.fixed-assets.tsx(getCutoverFixedAssets: the assets on the books the day before the cutover — acquired before it, and not disposed or disposed on or after it, except an asset whose disposal leaves the books with no journal (getAssetsLeavingWithoutJournal: a sale, return to inventory or lease commencement posted before the reset) — with accumulated depreciation as of that day, the asset's own less what Posted runs booked for months on or after the cutover (getDepreciationAfterCutover), since the enable writes those runs' journals again; intentsave-assetwrites the accumulated depreciation as of the day before the cutover throughupdateCutoverAccumulatedDepreciation, which stores it plus that later depreciation),activation.trial-balance.tsx(the prior system's trial balance as of the day before the cutover, kept as ONE DraftOpening Balancejournal with no period bysaveOpeningTrialBalance; one debit-signed balance per account in the editor (a credit is negative; the save still sends a debit and a credit); intentssave-tb(the editor),import-tb(CSVaccountNumber, debit, credit, saves nothing when a row has an error),pull-tb(only when the active accounting integration passesisTrialBalanceProvider— Xero, QuickBooks Online, Rillet:pullTrialBalanceFromProvider(@carbon/ee/accounting) reads the provider's trial balance as of the day before the cutover and maps it through the account mappings, else by account number; it saves what maps and returns the rest, unmapped or mapped to several Carbon accounts, for the editor to list),ignore-invoice(setCutoverInvoiceIgnored) andapply-carbon(applyCarbonToOpeningTrialBalance: every control account set to Carbon's opening total, every other row kept, and what that leaves out of balance — the Migration Clearing total — added to theretainedEarningsAccountrow, so Migration Clearing totals zero; the button is enabled while the total is not zero). The CSV parser is the pure, testedtrial-balance-csv.ts(parseTrialBalanceCsv,mapTrialBalanceAccounts): it returns error codes the editor translates, refuses a duplicate account number, and refuses an amount with a comma (ambiguous-amount) instead of stripping it, since1,234is a thousand in one convention and one and a fraction in another;getMigrationClearingshows, per control account, the trial balance, Carbon's opening total and the difference, and each account opens to the items behind its total. Before the cutover another system kept the books, so an invoice open in Carbon may be settled there: a sales or purchase invoice (isIgnorableOpenItem) can be ignored — unless Carbon itself settles it on or after the cutover (settledFromCutoverIds: a payment or memo application not in effect the day before, or a Paid status dated on or after it), whose journal credits the control account and needs the opening line — which stores it inaccountingCutoverIgnoredInvoice, takes it out ofitemsintoignoredItems, and has the enable mark it Paid the day before the cutover. No other item can be ignored: leaving it out of the opening journal would misstate what reads it later) andactivation.enable.tsx(the summary and the typed company name; it invokesactivateAccounting(accounting.service.ts, ported from theactivate-accountingserver function) and redirects to Periods). The summary lists, under "Documents posted before Carbon kept journals", each family with legacy documents and how many (getLegacyDocumentCounts): documents posted on or after the cutover that have no journal, which the enable journals with today's accounts and costs (see → Legacy documents below). The reads live once, in Kysely, in@carbon/database/accounting-cutover-reads(server-only; one module per step underpackages/database/src/accounting-cutover/). The wizard routes import them from there directly and passgetDatabaseClient();activate-accountingcalls the same functions with its transaction. The pure planners (planInventoryReset,recostOutbound,buildOpeningJournalLines) are@carbon/database/accounting-cutover. Settings → Accounting (x+/settings+/accounting.tsx) shows "Accounting since {date}" or a "Set up accounting" button; there is no switch. - Opening lines — the enable posts one
Opening Balancejournal, dated the day before the cutover, againstaccountDefault.migrationClearingAccount(seeded as 3400 "Migration Clearing" for new companies). A control-account line copies the keys its chain reader matches (documentType,documentId,documentLineReference, description), so a payment, a purchase invoice's GR/IR walk or a job close after the cutover finds it as if the original posting had written it. A PO line invoiced before the cutover for more than it received opens its GR/IR accrual (purchase-invoice:<poLineId>,accrualtrue, the open quantity at the invoices' accrual unit cost), which a receipt after the cutover clears at the invoice's cost. A document partly settled before the cutover gets two lines: its original amount, and the amount settled before the cutover under " (settled before cutover)", which the readers ignore. Every other account comes from the trial balance only. Deferred revenue opens from the Deferral rows dated on or after the cutover of invoices posted before it that were still deferred the day before (Planned, or Posted by a run whose journal the reset deleted, which the enable writes again), on each row's debit account. Lease net investment opens per rental agreement from the lease rows of eachSaleline commenced before the cutover (the lastrentalLeaseScheduleLine.closingNetInvestmentbefore the cutover, elseinitialNetInvestment), not from a commencement journal, which a lease commenced before the reset does not have. Migration Clearing must total zero within 0.01 before the enable. A void of a document dated before the cutover is in → Journals and the accounting cutover below. - Fiscal Year Settings — configurable start month for fiscal and tax years. Accounting periods auto-created via
getOrCreateAccountingPeriod. - Dimensions — analytical tags on journal lines (Location, Department, Project, etc.). Entity-type dimensions resolve values from their source table; Custom dimensions use
dimensionValue. - Cost Centers — hierarchical organizational units for cost allocation via
parentCostCenterId. - Fixed Assets — capital assets with depreciation. Supports straight-line, declining balance, MACRS, and units-of-production methods. Depreciation runs generate journal entries: one
depreciationRunLineper asset per month, each month's journal in that month's period, and Reverse Run (reverseDepreciationRun) undoes the latest posted run — journals, accumulated depreciation and the run's status (see the rule). The fleet bridge links an asset to anitem/trackedEntity/workCenter: a serialized unit is capitalized from stock or built by a Make to Asset job (complete_job_to_inventory), returned to stock at net book value, or accumulated as Construction in Progress (fixedAssetClass.isConstructionInProgress, statusUnder Construction, cost rows infixedAssetCipCost) until capitalized into an in-service class. Construction in progress is built but hidden until it returns with projects:CONSTRUCTION_IN_PROGRESS_ENABLED = false(accounting.models.ts) filters CIP classes out ofgetFixedAssetClasses/getFixedAssetClassesList(every class list and picker), hides Attach Job / Capitalize and the CIP cost card (isCipClassinx+/fixed-asset+/$fixedAssetId.tsx), the Under Construction status filters (visibleFixedAssetStatuses/visibleFleetStatuses) and Complete To → Asset Under Construction (JobForm). Engines and schema are untouched; flip the constant to bring it back. Every inventory ↔ asset move is one PostedfixedAssetTransferdocument written bypostAssetTransfer(accounting.service.ts, ported from thepost-asset-transferserver function) (journalsourceType 'Asset Transfer', off by default in the sync policy). Fleet status is derived by thefleetAssetsview, never stored. See.claude/rules/fixed-asset-lifecycle.md. - Revenue recognition —
revenueRecognitionScheduleis the one "what to post, when" table:typeDeferral / Accrual / Interest / Amortization,statusPlanned / Posted, each row carrying its owndebitAccountId/creditAccountId, linked to asalesInvoiceLineId, arentalAgreementLineId, acustomerContractLineId(contract rows, see Contract revenue below) or a lesseeleaseId+leaseScheduleLineId(see Lessee leases below).postSalesInvoice(invoicing.service.ts) writes Deferral rows for every company (every Service line with service dates; every Rental rent line). There is no revenue recognition flag. Service dates belong to Service lines only: every other item type is a physical good, earned when it ships, so the sales order / invoice line forms show the date fields only on a Service line, the line validators refuse them on any other type (the invoice validator also admitsRental, whose lines carry their billing period),upsertSalesOrderLine/upsertSalesInvoiceLinenull them on any other type, and posting ignores dates left on a non-Service line. A run (revenueRecognitionRun/revenueRecognitionRunLine) has atype(runType): Revenue Recognition or Lease — see Run types below. It claims every Planned row of its type dated on or before itsperiodEndand first runs its type's synthesizers (runRowSynthesizers(type)) inproposeRevenueRecognitionRun(accounting.service.ts, ported from thepropose-revenue-recognition-runserver function) (apps/erp/app/modules/accounting/accounting.service.ts,{ periodEnd, type }, permissioncreate: accounting; the routes call it throughinvokePosting, the monthly job throughposting).postRevenueRecognitionRun(accounting.service.ts) posts the run's journals (sourceType 'Revenue Recognition'or'Lease Run'by run type (buildRecognitionJournals,@carbon/databaserun-journals.ts), bothdefaultEnabled: falsein the sync policy; one per month, below); deferral lines reference the invoice, rental Accrual/Interest linesdocumentType 'Rental Agreement'with Customer / Item / Location dimensions resolved from the agreement, lessee rowsdocumentType 'Lease'+documentLineReference= the asset (leaseLine, fromRecognitionSources.leaseAssets) with Supplier / the asset's Location dimensions. Inngestrevenue-recognition-proposal(cron0 12 1 * *) only proposes Draft runs, one step per run type per company. A period may hold more than one run of a type (a later one picks up rows that fell due after the first posted) but one Draft per type at a time: the routes and the proposal refuse a second Draft, and the partial unique indexrevenueRecognitionRun_one_draft_per_period(companyId, type, periodEndWHERE Draft) is the backstop. No run may end after the company's current month (futureRunPeriodError,accounting.service.ts; the proposal function repeats the check). Posting writes ONE journal per month the rows fall in, each in that month's period — the run's own period when the month is Closed (resolveRunPostingPeriods→RunPostingPeriods);revenueRecognitionRun.journalIdnames the journal of the run's own period, and the Documents panels read every journal through the schedule rows. Reverse Run (reverseRevenueRecognitionRun, route$runId.reverse) reverses those journals with their documents and dimensions (reverseRunJournals, each on its own date or today when Closed,resolveReversalPeriods), puts the rows back to Planned under the same run, clears what posting stamped (lease schedule lines, contract ledger entries, contract revenue months) and returns the run to Draft;reverseJournalEntryrefuses a run's journal (RUN_JOURNAL_SOURCES,accounting.models.ts). A Draft is a snapshot: each run line copies its row's amount. Recalculate (x+/revenue-recognition-run+/$runId.recalculate,recalculateRevenueRecognitionRun(accounting.service.ts, ported from therecalculate-revenue-recognition-runserver function),update: accounting) keeps the run's id and number, releases its rows BEFORE rerunning the synthesizers (a synthesizer that drops a held row would otherwise delete the run it emptied), then claims what is due by itsperiodEndagain; a run with nothing left due is deleted. The proposal'speriodEndmust be a real month end (a 400 otherwise).postRevenueRecognitionRunrefuses a run that is out of date — a held row's amount or status changed, or an unclaimed Planned row is due by itsperiodEnd— withRunOutOfDateError, whose message the post route shows. A write that deletes a held Planned row (an invoice void, orsynthesizeContractRevenuedropping a contract row whose plan month was replaced) keeps Draft runs in step in its own transaction throughsyncDraftRecognitionRuns(shared.service.ts), deleting a run it empties. Close tasks "Recognize revenue for the period" (autoCheckKey 'unposted-revenue-schedules') and "Post lease journals" ('unposted-lease-schedules') ask the run of their type what it would do instead of copying its rules:previewRevenueRecognitionRun(accounting.service.ts, ported from thepreview-revenue-recognition-runserver function) ({ periodEnd, type },view: accounting) runs the synthesizers andselectDueScheduleRowsin a transaction that always rolls back and returns{ count, amount }. The check fails while that preview has rows, the preview failed, or a Draft run holds a Planned row due by the period end. - Run types (
@carbon/database/run-type; spec.ai/specs/2026-10-11-lessee-leases.md§6) — two runs on one engine, one client-safe descriptor:runTypeFilter(type)(Kysely),runTypeOfScheduleRow(row)(the same test on a row in hand),RUN_SEQUENCE,RUN_LABEL/runLabelSentence(messages); the ERP addsRUN_PAGES(ui/RevenueRecognition/runPages.ts: list path, New Run path, list title) for every "back to the run's list" and breadcrumb.runTypeFilter(type): a Lease run claims every row with arentalAgreementLineIdor aleaseId(rental deferrals, rental accruals, sales-type lease interest, lessee interest and amortization) and synthesizes rental accruals; a Revenue Recognition run claims the rest (service-dated invoice lines, contracts) and synthesizes contract revenue.accounting.service.tsuses the same filter; post checks only its own type's unclaimed rows (the contract check only for revenue runs) and stamps lesseeleaseScheduleLine.journalId/postedAt; reverse filters its Draft check on the type, clears lessee stamps, and releases rows of the OTHER type a legacy posted run held (deleting a run left empty). Readable ids come fromRUN_SEQUENCE(revenueRecognitionRun/leaseRun, prefixLR). Lease runs: routex+/accounting+/lease-runs.tsx(+.new); revenue runsx+/accounting+/revenue-recognition-runs*; both in the nav under Accounting → Closing. Both list routes shareloadPeriodRuns/createPeriodRun(period-runs.server.ts) andPeriodRunsPage; a run of either type opens atx+/revenue-recognition-run+/$runId(post, reverse, repeat, recalculate, delete follow the run's type).20261011163211_lessee-leases.sqlreleased rental rows from Draft revenue runs (posted history kept) and20261011192957_lease-run-sync-policy.sqlcopied each accounting integration'sRevenue Recognitionsync setting toLease Run.reverseJournalEntryrefuses aLease Runjournal like the other run sources (RUN_JOURNAL_SOURCES). - Rental accruals —
synthesizeRentalAccruals(the lease run's synthesizer) accrues earned-but-unposted rent ofRental(operating-lease) lines for the run's calendar month (DrcontractAssetAccount/ CrrentalIncomeAccount, both required or it throws "Set the Contract Assets and Rental Income account defaults before recognizing rental revenue"). It takes every non-adjustmentrentalBillingPeriodof aRentalline (On Rent/Returned) that no POSTED invoice covers (Pending, orInvoicedonto a Draft/Pending invoice), clips it to the month and to[deliveredAt, returnedAt], and writes one Accrual row per SLICE (periodStart/End= the slice,scheduledDate= the run's period end) with cumulative rounding from the period's first day. Any existing Accrual row overlapping a slice suppresses it (idempotent); a transaction advisory lock serializes concurrent proposals. Posting a Rental rent line credits Contract Assets for the unbilled Accrual rows of its period (Planned or Posted) and stampsbilledBySalesInvoiceLineId. The close check counts un-accrued rent through the run preview (above), so it sees exactly what a run would accrue. - Contract revenue (contracts Phase B,
.ai/plans/implemented/2026-09-22-revenue-recognition-rentals-and-contracts.mdPart IV D5) —synthesizeContractRevenue(the revenue recognition run's synthesizer,runRowSynthesizers) turns every PlannedcustomerContractRevenuemonth starting on or before the period end, of a non-Draft contract, with no schedule row yet, into a Deferral row (DrdeferredRevenueAccount/ CrsalesAccount) for the part the line's deferred pool covers and an Accrual row (DrcontractAssetAccount/ CrsalesAccount) for the rest, atget_exchange_rate(…, periodEnd); each row carriescustomerContractLineId,customerContractRevenueId,contractAmountand oneRecognitionentry incustomerContractLedgerEntry(cascades with the row). A negative (catch-up) month yields negative rows. It first drops Planned contract rows whose plan month was replaced (customerContractRevenueIdnulled).postRevenueRecognitionRunposts contract rows withdocumentType 'Contract'and Customer / Item / Project (line, else contract) dimensions, flips their plan months toRecognized, stamps the entries'journalId, and treats an unsynthesized due month or a held row with a nulled plan month as out of date. The close check counts unsynthesized due months through the run preview (above). - Sales-type leases — a rental line classified
Sale(a sales-type lease;lessorClassificationvaluesRental/Sale/Financing) at activation (postRentalAgreement,sales.service.ts; see sales AGENTS → Rentals) posts its commencement and end-of-term residual return as journals ofsourceType 'Lease'(POSTING_POLICYLease,defaultEnabled: false; also in the hand-writtenjournalEntrySourceTypesarray with theLuKeyRoundicon), linesdocumentType 'Rental Agreement'with Customer / Item / Location dimensions. Its effective-interest schedule isrentalLeaseScheduleLine; each line thatearnsInterest(lessor-leasein@carbon/utils: not zero, not the one-unit drift an Advance lease closing on zero leaves on its last line) spawns one PlannedInterestrecognition row (DrnetInvestmentInLeasesAccount/ CrleaseInterestIncomeAccount) that the LEASE run posts under'Lease Run', andpostRevenueRecognitionRunthen stamps the schedule line'sjournalId/postedAt; Reverse Run (reverseRevenueRecognitionRun) clears the stamps. Rent and Purchase Option invoice lines of aSaleline creditnetInvestmentInLeasesAccount; a Purchase Option line also settles the rest of the line's NI against the schedule's closing balance (purchaseOptionSettlement,invoicing.service.ts: shortfall DrcostOfGoodsSoldAccount/ Cr NI, excess Dr NI / CrleaseRevenueAccount). A residual return moves the schedule's balance on the return date (netInvestmentAt) and keeps the Interest rows dated on or before it, so later runs still post them and NI closes to zero. A sales-type lease must run whole billing periods (salesTypeRequirementError,lessor-leasein@carbon/utils) so the billed rent equals the valued payment stream. Account defaults seeded 1160 Net Investment in Leases, 4070 Lease Revenue, 4150 Interest Income – Leases. Lease policy (the classification thresholdscompanySettings.leaseMajorPartThresholdPercent75 /leaseSubstantiallyAllThresholdPercent90, shared by lessor and lessee; the lessorleaseDefaultDiscountRate6, label "Lessor Discount Rate (%)"; the lesseeleaseIncrementalBorrowingRate6,leaseShortTermExpedienttrue andleaseReminderDays90) is edited onx+/settings+/accounting.tsx("Lease Classification" card, intentleasePolicy,update: settings) throughupdateAccountingSettings; changes affect later activations only. - Net investment report —
getLeaseNetInvestment(client, companyId, { asOf }), reportx+/reports+/lease-net-investment.tsx(view: accounting; hub card "Net Investment in Leases", category Close Reports;path.to.leaseNetInvestment). Per commencedSaleline live onasOf(Pending / On Rent, or Returned afterasOf; Sold lines omitted; agreementstartDate≤asOf):initialNetInvestment, posted principal (schedule lines withperiodDate≤asOfwhose Interest row has posted (postedAt) or that earn no interest, so have no row to post), current NI, next interest, undiscounted remaining payments by fiscal year (fiscalYearSettings.startMonth), and the last line's closing (option + residuals). ReadsrentalAgreementLineandrentalLeaseScheduleLine, whose RLS issales_view— an accountant without sales view sees an empty report. Principal counts once its Interest row is posted (a no-interest line: once its date passes), so it ties to 1160 only when the run and the rent invoices for the same months are both posted. - Lessee leases (purchasing module, see purchasing AGENTS → Leases) — journals of
sourceType 'Lease'(POSTING_POLICYLease, also used by sales-type rentals) for commencement, opening balance, modification, termination, purchase and the cancel VOID, linesdocumentType 'Lease'(journalLineDocumentTypevalue) +documentLineReference= the leased asset (leaseLine) with Supplier / the asset's Location dimensions;getJournalEntryRelatedItemslinks them, andLease Runjournals, back to their lease or run. Seven account defaults (migration20261011163211, seeded for new companies inseed-data.ts):rightOfUseAssetAccount1450,accumulatedRightOfUseAmortizationAccount1460,leaseLiabilityAccount2440,variableLeaseExpenseAccount6130,operatingLeaseExpenseAccount6140,rightOfUseAmortizationExpenseAccount6330,leaseInterestExpenseAccount7020 — the "Leases (Lessee)" group ofAccountDefaultsForm, all required by the readiness check (ACCOUNT_DEFAULT_COLUMNS,accounting-cutover/shared.ts). Each asset's schedule line spawns anInterestrow (Dr operating lease expense or lease interest expense / Cr lease liability) and anAmortizationrow (Dr operating lease expense or ROU amortization expense / Cr accumulated ROU amortization) for the lease run. - Lease Liabilities report —
getLeaseLiabilities(client, companyId, { asOf, from?, to? })(accounting.service.ts; the pureleaseLiabilityAssets/summarizeLeaseLiabilities/summarizeLeaseCostsinlease-liabilities.ts, pinned bylease-liabilities.test.ts: the balances, maturity and weighted averages, the current portion (12 schedule lines, mid-month and leap-year as-of dates), an asset ended by its own Termination or Purchase event with a truncated schedule, the lease-to-asset mapping, and the lease cost), reportx+/reports+/lease-liabilities.tsx(view: accountingANDview: purchasing; hub card "Lease Liabilities", category Close Reports;path.to.leaseLiabilities): per leased asset (leaseLine, a row with its lease and an Asset column; schedule lines and payments keyed byleaseLineId) the liability and net ROU asset as ofasOf, the maturity analysis by fiscal year with imputed interest, the current / non-current split, weighted-average remaining term and discount rate, and for[from, to](default: fiscal year start toasOf) the lease cost (operating, finance amortization and interest, short-term, variable) and cash paid, classified by each asset (a Lease invoice line through its payment row's asset). The current portion is the principal of the next 12 schedule lines afterasOf(not a 12-month date window); an asset that ends within them (itsleaseEventTermination / Purchase date, neverlease.endDate) is current in full and stays on the report until that date even with no schedule line left. The figures are the schedule's: when a lessee row due byasOfis still Planned the page shows how far the lease run is posted (leaseRunPostedThrough,firstUnpostedLeaseMonth). Schedule lines, payments and events are read only for the Operating / Finance assets of leases past Draft, every read paged (fetchAllRecords/fetchAllByIds). The lease tables' RLS ispurchasing_view, which is why the route requires purchasing view. - Lessee cutover —
getLeaseLiabilityItems(packages/database/src/accounting-cutover/open-items.ts) opens, per Operating / Finance leased asset (leaseLine) of a lease commenced before the cutover and not terminated or purchased before it, three open items (openItemTypeLease Liability,Right-of-Use Asset,Accumulated ROU Amortization,documentType 'Lease',documentLineReference= the asset) read from the asset's schedule and events: the last schedule line's closing liability before the cutover plus later remeasurements, the ROU at cost, and the accumulated amortization. The three defaults are control accounts in the trial-balance step (trial-balance.ts). A lease activated AFTER the cutover but commenced before it posts its own opening balance instead (post-leaseactivate, purchasing AGENTS). - Rental utilization —
getRentalUtilization(client, companyId, { from, to, fixedAssetClassId }), reportx+/reports+/rental-utilization.tsx(view: accounting; hub card "Rental Utilization", category Analytics). Per fleet asset: fleet days =[acquisitionDate, disposalDate ?? to] ∩ [from, to]; on-rent days = union of its lines'[deliveredAt, returnedAt ?? to]within that window; time utilization = on-rent ÷ fleet days; recognized income = Posted schedule rows dated in range crediting Rental Income or Lease Interest Income + posted Charge invoice lines; dollar utilization = income × (365 ÷ range days) ÷ acquisition cost. Class totals perfixedAssetClass. One read per table, joined in TS. - Intercompany — transactions between companies in a group.
runIntercompanyMatchingpairs them;generateEliminationscreates reversing entries on the lowest-common-parent elimination entity, classified byjournal.eliminationKind:'IC Balance'(reverse IC Receivable/Payable) and'IC Revenue'(reverse an intragroup sale's revenue + COGS and write the buyer's capitalized asset down to group cost — removes intragroup profit from consolidated income). The engine is capture-driven, not GL reconstruction: the postings (post-sales-invoice,post-purchase-invoice) record role-tagged references (intercompanyEliminationLine:Control/Revenue/COGS/Capitalization) when each side posts, andgenerateEliminationEntriesreads them — so it writes down whatever account the BUYER capitalized (inventory OR a fixed asset — the latter is now in scope, was the negative-Finished-Goods bug). The writedown scales by the buyer's on-hand fraction (fixed assets: full until disposed); revenue/COGS reversal scale by the same fraction so the entry balances.p_regeneratereverses existing eliminations (reversing entries, never deletes) and re-derives — the workbench "Regenerate" button. Both halves of a trade record their matching amount in the trade's DOCUMENT currency rounded at internalSCALE—calculateSalesIntercompanyAmount(seller) andround(intercompanyAmount)(buyer).generate_intercompany_matchespairs them on exact NUMERIC equality with no tolerance, so rounding either half at settlement precision leaves every trade with sub-cent digits permanentlyUnmatchedand eliminations never run. Investment/NCI and seller fixed-asset disposal (deferred gain) remain out of scope. See.ai/specs/2026-08-17-intercompany-elimination-engine.md. - Currency translation / CTA —
translateCompanyBalancesvalidates the source trial balance using natural debit/credit signs and positive finite pair rates. Missing rates fail explicitly.applyCtaToReportPeriodSeriesForReportresolves only the root company's CTA mapping through a server-only permission and company-group/root check; operating-company ledger reads remain RLS-scoped. The existingapplyCtaToReportPeriodSeriesservice adds the calculated CTA once to the reporting root company's configuredcurrencyTranslationAccount, validates its active Equity posting leaf, then rerolls intermediate groups and roots before filtering/export. Never identify CTA by account number. Financial report chart reads include inactive historical accounts and their ancestors; chart and balance RPC rows are fully paginated before calculation. Active-only filters belong to posting/configuration pickers. Balance RPC trees and period-close snapshots retain inactive posting leaves and ancestors. Report loaders reject company selections outside the available company group (404) before balance reads. - Shipping revenue —
accountDefault.salesShippingRevenueAccountmaps an active Revenue posting leaf distinct from Sales. New groups seed 4050 Shipping Revenue under Revenue; existing groups resolve a compatible leaf and backfill mappings. Nonzero invoice shipping requires a valid mapping; output tax posts separately to tax payable. The full defaults form validates once and saves both sections with one company-scopedupdateDefaultAccountsUPDATE, so a failed mapping cannot half-save the form. - Payments have THREE payee kinds, not two.
payment.employeeIdis a reimbursement payout: always a Disbursement, never AR, never a refund, and it targetsinvoiceSettlement.targetReimbursementIdonly — no invoice target, no discount, no write-off, no prior credit. Its control account isaccountDefault.employeeReimbursementsPayableAccount, falling back topayablesAccountat runtime.journalEntrySourceTypegainedChargeandReimbursement(the former replacingCard Transaction); a Reimbursement journal's payable leg is what a payout clears. Before the cutover a target with no control line (a document posted before every company wrote journals) books the default control account instead. After the cutover a target with no control line, in its own journal or in the opening journal, is refused ("Target is missing its original control account") rather than debiting a liability that was never credited. - Payments and refunds — the customer/supplier determines AR/AP independently of cash direction. Customer Disbursements and supplier Receipts refund posted balance-reducing memos through
invoiceSettlement.targetMemoId, using current cash only (no invoice targets, discounts, writeoffs, or prior credits). Ordinary payments retain invoice targets, memo-source funding, and prior cash credits. Memo availability subtracts effective source and target principal; an effective posted refund blocks memo voiding. Aging and tie-out RPCs sign unallocated refunds opposite ordinary payments and use the applying payment's cash direction for FX consumption. Target memos consume exactsourceAmountprincipal andappliedAmountcarrying base. Unknown memo principal retains the existing exclusion contract; it is not reconstructed or raised as a report error. Payment/invoice application histories page all rows, including embedded parent statuses and refund labels, before totaling. - Customer deposits — a customer payment with
payment.rentalAgreementIdorpayment.salesOrderId(CHECKpayment_deposit_document_check: at most one;paymentValidatorrefines the same and refuses it on a supplier payment) is a deposit.post-paymentbooks its unapplied cash onaccountDefault.prepaymentAccount(2110 Customer Prepayments, class Liability) with descriptionCUSTOMER_DEPOSIT_DESCRIPTION= "Customer Deposit" (@carbon/database/accounting-posting) instead of on-account AR credit; a Disbursement carrying the reference refunds from the same account. Applying it later goes through the existing prior-credit path: the source-control lookup matches either the on-account description or "Customer Deposit", and the release postsCUSTOMER_DEPOSIT_APPLIED_DESCRIPTION("Customer Deposit (applied)") as a debit on the prepayment account. A deposit funds only its own document:allocatePaymentFunding(@carbon/utilspayment-funding) gives eachFundingSourcean optionalscope(fundingScopeOf(payment)→{ type: "rentalAgreement" | "salesOrder", id, readableId? }) and eachFundingRequesttherentalAgreementIds/salesOrderIdsits invoice bills (fromsalesInvoiceLine, one read per call:loadSalesInvoiceDocumentIdsin@carbon/database/deposit-scope); a scoped prior source funds only requests that list its id, an unscoped one funds anything. A payment that is itself a deposit is refused on any other invoice ("A deposit for RA000001 can only be applied to that agreement's invoices", readable id vialoadDepositScope). Source priority is unchanged (current payment, then prior sources bypostingDate,paymentId) but the split is decided over all requests at once (prioritizedTransport), so a deposit's invoice never spends the ordinary cash another invoice needed and the outcome does not depend on request order — with no scoped source it is byte-identical to the old walk.replaceInvoiceSettlementsandpost-paymentboth apply it (post re-derives, so a crafted Draft cannot bypass it).getAvailableOnAccountCreditSourcesreturns deposits insourceswith their scope but leaves them out ofavailableDocumentAmount/availableBaseAmount(andgetAvailableOnAccountCredit);getOpenSalesInvoicesForCustomerreturns each invoice'srentalAgreementIds/salesOrderIds;PaymentApplyTablelists each deposit apart ("Deposit for RA000001 (its invoices only)"), sizes rows withfundableDocumentAmounts, and for a deposit payment lists only its document's invoices. The payment form's "Deposit for" / "Refund deposit for" combobox (PaymentForm, customer payments only) is fed bygetDepositDocuments(invoicing/invoicing.service.ts, server-only, called by the loaders ofx+/payments+/new.tsxandx+/payments+/$paymentId.tsx). It loads every rental agreement, every open sales order, and every sales order a Posted deposit Receipt already references (plus ids the caller must keep), each flaggedopen(open order / Draft or Active agreement). The form narrows to the payment's customer; a Receipt offers onlyopendocuments (plus its current one), a Disbursement also offers documents already holding a posted deposit, so a Closed agreement's or a finished order's deposit can be refunded. Deposits never touch revenue or recognition schedules. - Chart of accounts import (
.ai/specs/2026-10-12-chart-of-accounts-import.md) —x+/accounting+/chart-import.tsx(update: accounting), linked from the chart page's Import button only while the company has no cutover. Two CSVs, both required: the customer's chart (parseChartCsv,account-import-csv.ts, reads the header names other systems export and leaves out inactive rows;chartTemplate, served byapi+/accounting.chart-of-accounts[.]csv.tsx, downloads the current chart in those columns) and the default accounts template (defaultAccountsTemplate, served byapi+/accounting.default-accounts[.]csv.tsx;parseDefaultsCsv) with the customer's number for everyaccountDefaultrole and fixed asset class account. The pure plannerplanAccountImport(@carbon/database/account-import) and its readsloadAccountImportContext(@carbon/database/account-import-reads) back both the review (intentplan) andapplyAccountImport(accounting.service.ts, ported from theapply-account-importserver function; intentapply), which re-plans and applies in one transaction. The Carbon account behind a default becomes the chart row the template names (later defaults naming the same row merge into it); a Carbon account whose number matches an unclaimed row becomes that row; every other leaf is deleted, or is areplacementsentry while documents (posted ones included) or Draft / Provisional journal lines use it, until the review picks the row it merges into; the pick stays on the list, so the review can change it. The import refuses once any company of the group has a cutover, so it never meets Posted history, and the page redirects to the chart then. Opened from the activation wizard (?from=activation), Cancel and a finished import return to it. The parsers read records throughparseCsvLines(@carbon/files/csv), so a blank or comma-only row is skipped and every error names its real line. - Applying the import —
applyAccountImport(accounting.service.ts, ported from theapply-account-importserver function; input{ chart, defaults, resolutions }, trimmed and size-capped, permissionupdate: accounting) in one transaction. It locks every company'scompanySettingsFOR SHARE, then the group's accounts FOR UPDATE, re-plans withplanAccountImport, and refuses a plan with errors or an open replacement — including any company of the group with an accounting cutover. It setsapp.account_import(set_config(…, true)), which lets the charge and reimbursement guards accept an account-only change on a posted row (20261013035046). It frees the number and name of every updated, merged and deleted account (temporary values, so a swap works), creates groups and accounts, sets every company's defaults in one statement and every fixed asset class in one, re-points each merge source byREFERENCE_POLICYplus the references with no foreign key (intercompanyEliminationLine,companyIntegration.metadata.paymentFeeAccount) — posted documents included, since their journals are still Provisional — deletes the removed accounts and theirexternalIntegrationMappingrows, deletes empty groups, and checks a postcondition (every chart row written with its class, type and group; every required default and class account set). A failed postcondition is a 500: the plan and the apply disagree. Live test:apps/erp/test/database/apply-account-import.test.ts. - Net Income — computed equity line on the balance sheet, never a posted account. Uses synthetic
NET_INCOME_ACCOUNT_IDconstant.
Journals and the accounting cutover
Every posting function writes its journal for every company. The company's
companySettings.accountingCutoverDate decides only the journal's status
(.ai/specs/implemented/2026-10-08-accounting-cutover.md). The accountingEnabled column still
exists, but no code reads it.
- Status.
journalPostingStatus(db, companyId)(@carbon/database/journal-posting-status) returnsProvisionalwhen the company has no cutover andPostedwhen it has one.postingStatusFor(cutoverDate)is the same decision without a read, andreadAccountingCutoverDatereturns the date. All reads takeFOR SHARE. The SQL posting functions (complete_job_to_inventory,backflush_job_materials) calljournal_posting_status(company_id). - The double read. Only a posting function that resolves an accounting period
BEFORE its transaction reads the status twice. It reads it once before the
transaction, to decide whether to resolve the period. Inside the transaction it calls
assertPostingStatusUnchanged(@carbon/database/journal-posting-status), which reads it againFOR SHAREand throwsPOSTING_STATUS_CHANGED_ERROR("Accounting was just set up. Post the document again.") on a mismatch. A function that reads the status only inside its transaction needs no second read.activate-accountingtakesFOR UPDATEon the same row, so no posting writes a Provisional journal after the enable commits. - No period before the cutover. A Provisional journal has
accountingPeriodIdnull, and no posting creates a period for it. Resolve a period only when the status isPosted. - Stand-in lines.
resolveDefaultAccount(defaults, role, postingStatus)picks the account for a line that needs one of the nullable defaults inOPTIONAL_DEFAULT_ROLES. A set default is used as is.- An empty default with a fallback in
DEFAULT_FALLBACKSuses the fallback, before and after the cutover (for examplescrapAccount→inventoryAdjustmentVarianceAccount,salesReturnsAccount→salesAccount). It never takes a stand-in, and the enable does not require it. - Only an empty default with no fallback takes a stand-in. Before the cutover it
returns
retainedEarningsAccountwithaccountDefaultRole = role, and the line stores that role injournalLine.accountDefaultRole. After the cutover it throwsMissingAccountDefaultError: status 400, message "Set the - A void copies
accountDefaultRolefrom each original line to its reversal. - A
revenueRecognitionSchedulerow never takes a stand-in.post-sales-invoicerefuses when the deferral, contract asset or rental default it needs is empty, in both states. The invoice's own lines take stand-ins throughsalesInvoiceStandIns(shared.service.ts:leaseRevenueAccount,netInvestmentInLeasesAccount,salesShippingRevenueAccount).
- An empty default with a fallback in
- Journal readers filter by a named status list from
@carbon/database/accounting-posting:GL_JOURNAL_STATUSES(Posted, Reversed) for balances, reports and tie-outs;DOCUMENT_JOURNAL_STATUSES(Provisional, Posted, Reversed) for a reader that follows one document's chain (void builders, GR/IR, WIP sums, intercompany lookups);OPEN_ITEM_JOURNAL_STATUSES(Provisional, Posted) for the payment control lookups and the memo, charge and reimbursement void checks.PRE_CUTOVER_JOURNAL_STATUSES(Provisional, Superseded) is not a reader's list: the enable wizard dates the start of the cost record from it. Thejournal-status-filtercheck (@carbon/checks) fails astatus <> 'Draft'filter on a journal. - Opening lines. The opening journal of the enable (
sourceType 'Opening Balance') copies the document keys and descriptions the original posting wrote. So the payment control lookups inpost-paymentacceptsourceType 'Opening Balance'as well as the invoice, memo andPaymentsource types. - Voids of a document dated before the cutover (
refuseVoidBeforeCutover,shared.service.ts;isBeforeCutoverin@carbon/database/accounting-cutover-dates):- A receipt or shipment void throws
INVENTORY_VOID_BEFORE_CUTOVER_ERROR("… Record a return or an inventory adjustment instead."). - A sales invoice void throws
SALES_INVOICE_VOID_BEFORE_CUTOVER_ERROR("… Issue a credit memo instead."). A purchase invoice void throwsPURCHASE_INVOICE_VOID_BEFORE_CUTOVER_ERROR("… Record a debit memo instead."). - A charge void throws
CHARGE_VOID_BEFORE_CUTOVER_ERRORand a reimbursement void throwsREIMBURSEMENT_VOID_BEFORE_CUTOVER_ERROR("… Record a journal entry to correct it instead."). The date ispostingDate, elsetransactionDateorreimbursementDate, as the posting uses. - A payment or memo void builds the document's posting again
(
rebuildPaymentJournalandrebuildMemoJournal, both in the ERP'sinvoicing.service.ts) and posts it negated, dated today, so it nets the opening lines.assertNoMigrationClearingrefuses a rebuilt line on the Migration Clearing account. A customer credit memo that credits a contract or a rental agreement throwsMEMO_CREDIT_VOID_BEFORE_CUTOVER_ERRORinstead. - A time entry whose journal the enable superseded is not posted again.
post-production-eventrefuses an event posted to GL with a line in a Superseded journal.post-maintenance-eventrefuses an entry whose expense changed (edited or deleted), and drops an unchanged one (withoutSupersededEntries,resources.service.ts). Both throwTIME_ENTRY_BEFORE_CUTOVER_ERROR("… Record a journal entry to correct it instead."). - A company with no cutover has nothing before it, so every void works as before.
- A receipt or shipment void throws
- Zero-cost outbound movements keep their pair. The adjustment core
(
valueMovement,shared.service.ts) skips the journal of an inbound movement at no value, but always writes the pair of an outbound one, at zero too. The enable's re-cost may give that movement a cost, and it adjusts the pair it finds. - Manual accounting work is refused before the cutover.
assertAccountingCutover(shared.service.ts) throwsACCOUNTING_NOT_STARTED("Set up accounting before you post journals, runs or period closes.").propose-revenue-recognition-runandrecalculate-revenue-recognition-runcall it. The ERP service functions refuse the same work with the same message.
activate-accounting
The one-way enable (activateAccounting in apps/erp/app/modules/accounting/accounting.service.ts,
input { cutoverDate, confirmation }, permission update: accounting). The wizard's Enable
step calls the service function enableAccountingCutover (accounting.server.ts), which
runs it through invokePosting. It runs in one Kysely transaction. The steps use the
spec's section 5 numbering, as the code comments do:
- Locks
companySettingsFOR UPDATE. Refuses when the company already has a cutover (ACCOUNTING_ALREADY_SET_UP) or whenconfirmationis not the company name. RunsgetActivationReadinessandgetMigrationClearing(@carbon/database/accounting-cutover-reads) again under the lock. Refuses on a failed check, or when Migration Clearing does not total zero (isMigrationClearingZero). Theaccount-defaultscheck refuses an emptymigrationClearingAccount, and one that is not an active Equity posting account. 1a. Writes the journals of the legacy documents (journalLegacyDocuments, below). - Inventory reset (
resetAndRecostInventory,accounting.service.ts). Closes the cost layers dated before the cutover and inserts one opening layer per item with stock (planInventoryReset). The unit cost comes fromgetCutoverInventory: a Standard item takes its standard cost, a FIFO or LIFO item the value its layers held at the cutover (unitCostAtCutoverreplays the layers dated before it), and an Average itemitemCost.unitCost, the one cost the wizard's inventory step lets a user edit. - Re-cost. Replays the layers and outbound movements of FIFO and LIFO items dated on
or after the cutover (
recostOutbound), and books each document's difference as a Provisional "Cutover recost" journal, one per document and posting date. ARevaluationcost row (a serial recost) keeps its cost. - Sets every Provisional journal dated before the cutover to
Superseded. - Sets every Planned
revenueRecognitionSchedulerow dated before the cutover to Posted with no journal. - Fixed assets: no write. The register already holds the values at the cutover.
- Deletes the Draft trial balance journal and posts the opening journal
(
buildOpeningJournalLines), Posted, dated the day before the cutover. Before that,markIgnoredInvoicesPaidsets every invoice ignored on Migration Clearing (clearing.ignoredItems, rows ofaccountingCutoverIgnoredInvoicestill open at the cutover) toPaidwithdatePaidthe day before the cutover, withapp.sync_in_progresson so no workflow, webhook or provider push fires. They are not in the opening journal, and the AR/AP readers treat a Paid invoice as closed. assignPeriodsgives each Provisional journal dated on or after the cutover the period of its date.repointStandInLinesmoves each stand-in line to the default it names (or that default's fallback). ThenpromoteJournalspromotes those journals toPosted. Both are inaccounting.service.ts.- Closes every period that ends before the cutover and snapshots its balances
(
snapshotAccountingPeriodBalances). It does not callcloseAccountingPeriod, which opens its own transaction. 10a.getCurrentAccountingPeriodmakes the period that holds today Active, as the first posting would. - Sets
accountingCutoverDate,accountingActivatedAtandaccountingActivatedBy. Thecheck_accounting_config_lockedtrigger then refuses any change to them, to the base currency and to the fiscal year start month.
Legacy documents (step 1a)
A legacy document is posted (not Draft, Pending or Voided), dated on or after the
cutover, and has no journal line under its document keys in a journal of any status.
A company with accounting off wrote no journal, and the reset deleted the others'.
journalLegacyDocuments (accounting.service.ts) writes, for each one, the
journal its posting writes today: today's account defaults and item costs, in base
currency at the document's exchange rate, Provisional, dated the document's posting
date. The steps above then re-cost, period, re-point and promote it like any other
Provisional journal.
- Detection is one definition,
@carbon/database/legacy-documents. Each function returns a query; the enable executes it, andgetLegacyDocumentCounts(@carbon/database/accounting-cutover-reads) counts the same rows for the wizard's Enable step. Change the detection there, never in a builder. - Order (
journalLegacyDocuments): first the cost rows of movements that stored none (writeLegacyMovementCosts: sales order shipments, direct sales invoice lines, job issues and completions); then sales invoices, purchase invoices, memos, charges and reimbursements; then payments in posting order, because a payment reads the control line of what it settles; then purchase receipts, sales return receipts, sales shipments, return shipments, the adjustment core's movements, job issues and job completions; then depreciation runs, scrap disposals and revenue recognition runs (also inaccounting.service.ts). - Movement costs.
writeLegacyMovementCosts(accounting.service.ts) costs an outbound FIFO or LIFO movement with no cost row against the layers open now (relieveOpenLayers: one locked read of the layers, thenreplayReliefs). A Standard item costs at its standard cost and an Average one atitemCost.unitCost. The enable then re-costs the FIFO and LIFO rows (step 3); the repair keeps what the open layers gave. - Memos and payments are built by
rebuildMemoJournalsandrebuildPaymentJournals(invoicing.service.ts). The pre-cutover voids use the same code for one document (rebuildMemoJournal,rebuildPaymentJournal). The payment posting and its rebuild assemble thebuildPaymentJournalinput in one place (assemblePaymentJournal,invoicing.service.ts), andapps/erp/test/database/post-payment/rebuild-journal.test.tspins a rebuilt journal to the posted one. - Every rebuilt journal stays out of provider sync. The provider may already hold
the original. So
insertProvisionalJournals(accounting.service.ts) callskeepOutOfProviderSyncfor every journal it writes, in the enable's step 1a and in the repair. It writes anExcludedaccountingSyncOperationper accounting integration witherrorCodeCUTOVER_REBUILT(CUTOVER_REBUILT_SYNC_CODE). Re-send in Sync Activity still pushes one. - Closed periods. Before it writes a batch,
insertProvisionalJournalsrefuses when a period that holds one of the batch's posting dates is Closed or Locked, or hasclosedAtset. TheInvalidInputErrornames the period and says to reopen (Closed) or unlock (Locked) it. The enable never meets one; the repair can. - Not rebuilt (no stored basis): labor and machine absorption of a legacy job, the
offset of a serial recost or an asset cost adjustment, asset registrations and
transfers, and the depreciation of an asset that left the books with no journal
(
assetsLeavingWithoutJournal). - The result's
legacyJournalscounts the journals written per family (LegacyJournalCounts:LegacyDocumentCountsplusmovementCostRows). A document whose journal has no lines gets none.
journal-legacy-documents (the repair after the enable)
A company enabled before step 1a existed, and a demo-template company (migration
20261009004448 backfilled its cutover), can still hold legacy documents. The
building block (repairLegacyJournals, accounting.service.ts; input {}, permission
update: accounting) runs step 1a again. The Settings service function in
settings.server.ts runs it through invokePosting as the caller. It runs in one transaction, under companySettings FOR UPDATE. It refuses a
company with no cutover (ACCOUNTING_NOT_STARTED). When it wrote journals,
assignPeriods, repointStandInLines and promoteJournals take only those
journals, by the ids journalLegacyDocuments returns. Then
getCurrentAccountingPeriod makes the period that holds today Active, as the
enable leaves it. Settings → Accounting shows the count (hasLegacyDocuments,
then getLegacyDocumentCounts) and a "Write missing journals" button.
seedCompany (ERP settings module, ported from seed-company) leaves a new company without a cutover, so it posts Provisional
journals until the activation wizard sets one. A subsidiary copies its accountDefault
ids and fixed asset class accounts from a company already in the group; the seeded
account numbers are only the fallback for a group with none.
Safety
Always
- MUST ensure journal entries balance —
postJournalEntryvalidates total debits = total credits before posting. - MUST use
rootSignMultiplierlogic for root account aggregation — Assets/Revenue add, Liabilities/Equity/Expense subtract. - MUST scope chart of accounts by
companyGroupId(shared across group) and transactions bycompanyId. - MUST use
getOrCreateAccountingPeriodbefore posting a Posted journal — it checks for closed periods and auto-creates missing ones. A Provisional journal (no cutover yet) has no period and creates none. - MUST filter journal status with
GL_JOURNAL_STATUSES,DOCUMENT_JOURNAL_STATUSESorOPEN_ITEM_JOURNAL_STATUSES— never<> 'Draft', which counts Provisional and Superseded journals. - MUST use
toStoredAmount/toDisplayDebit/toDisplayCreditfor amount conversion — respects account class sign conventions.
Ask First
- Modifying the chart of accounts structure — affects all financial reporting.
- Posting depreciation —
postDepreciationRunwrites a journal per asset per month; only the latest posted run can be undone (Reverse Run). - Changing fiscal year settings — impacts period boundaries and reporting.
- Generating intercompany eliminations — creates adjustment entries on elimination entities.
Never
- Delete posted journal entries — MUST use
reverseJournalEntryinstead. - Manually create a "Net Income" account — it is computed via
NET_INCOME_ACCOUNT_ID. - Bypass double-entry balance validation when posting journal entries.
- Write the cutover columns, or change a journal to
PostedorSupersededoutsideactivate-accounting. The enable is one-way; journal UPDATE RLS admits Draft and Posted only, andcheck_posted_record_immutablerefuses any change to a Superseded journal or its lines. - Delete an account any journal line or order / invoice / supplier quote line uses — those foreign keys are
ON DELETE RESTRICT(20261013005642). The delete route disables Delete whenisAccountInUse(@carbon/database/account-import-reads, across the group) is true. The chart lists active accounts only; there is no inactive-account view.
Validation Commands
pnpm exec turbo run typecheck --filter=erp
pnpm --dir apps/erp exec vitest run app/modules/accounting
apps/erp/test/database/post-lease/lease-run.test.ts (a lease run stamps leaseScheduleLine.journalId / postedAt, Reverse Run clears them) runs postRevenueRecognitionRun / reverseRevenueRecognitionRun against the local database through databaseTest, which skips unless SUPABASE_DB_URL points at a local host. It builds on leaseFixture and holdInDraftRun (apps/erp/test/database/fixtures/lease.ts, run.ts).
Key Data Model
| Table / View | Purpose |
|---|---|
account / accounts (view) |
Chart of accounts with class, type, and hierarchy |
journal / journalLine |
Double-entry transactions; lines carry dimension assignments |
journalLineDimension |
Dimension values assigned to journal lines |
accountingPeriod |
Fiscal periods. closeStatus (periodCloseStatus: Open→Locked→Closed lifecycle), fiscalYear/periodNumber (identity from the fiscal start month), lockedAt/lockedBy. Legacy status (Active/Inactive) is deprecated. |
accountingPeriodBalance |
Cumulative per-account GL balance snapshots. closeAccountingPeriod calls snapshotAccountingPeriodBalances inside its close transaction (after the flip to Closed) to write them; reopenAccountingPeriod deletes them (endingBalanceDate ≥ period endDate) before flipping back to Open. Read by accountTreeBalancesByCompany (snapshot + delta; full-scan fallback when empty) and accountTreeBalancePeriodSeries (multi-period: base snapshot before the range start + one bounded scan bucketed by period ends; single uniform branch). Balance RPCs count Posted and Reversed journals only (GL_JOURNAL_STATUSES) and retain inactive leaves/ancestors; the snapshot writer also includes inactive posting accounts. |
periodCloseTaskDefinition / periodCloseTask |
NetSuite-style close checklist: company-level task templates + per-period instances (seeded via seed-company) |
accountDefault |
Default GL account mappings (AR, AP, inventory, etc.) |
currency / currencyCode |
Per-group currency config (decimalPlaces, active, historicalExchangeRate); rates live in the global exchangeRate store + per-company exchangeRateOverride |
paymentTerm |
Payment terms (Net 30, 2/10 Net 30, etc.) |
costCenter |
Hierarchical cost allocation units |
dimension / dimensionValue |
Analytical dimensions and custom values |
fixedAsset / fixedAssetClass |
Capital assets with depreciation configuration. Asset: itemId, trackedEntityId (unique per company while not Disposed), quantity (CHECK = 1), workCenterId, outOfServiceSince / outOfServiceReason (both or neither). Class: isConstructionInProgress, gainOnDisposalAccountId / lossOnDisposalAccountId |
fixedAssetTransfer |
Inventory ↔ asset transfer document (transferId sequence FAT; type Capitalization / Return to Inventory / Cost Adjustment; sourceType Inventory / Job / Construction in Progress / Manual; amount, accumulatedDepreciation, journalId; created and Posted in one step) |
fixedAssetCipCost |
Append-only cost ledger of an asset under construction (sourceType Purchase Invoice / Receipt / Job / Manual, document + line ids, jobId, amount, costDate, journalId); capitalization sums these rows |
fleetAssets (view) |
fixedAsset with an itemId, joined to item, class, tracked entity and work center; netBookValue and the derived fleetStatus (Returned to Stock / Sold / Under Construction / On Rent / In Maintenance / Reserved / Available, in that precedence; On Rent / Reserved come from the live rentalAgreementLine), plus rentalAgreementId, customerId, customerLocationId of that line |
depreciationRun / depreciationRunLine |
Batch depreciation processing |
fixedAssetDisposal / fixedAssetUsageLog |
Asset disposal and usage tracking |
intercompanyTransaction |
Cross-company transaction matching |
fiscalYearSettings |
Fiscal and tax year configuration |
revenueRecognitionSchedule / revenueRecognitionRun / revenueRecognitionRunLine |
Recognition rows (Deferral / Accrual / Interest / Amortization, Planned / Posted) and the runs that post them (revenueRecognitionRun.type Revenue Recognition / Lease); see Revenue recognition and Run types above. A sales-type Interest row carries rentalLeaseScheduleLineId; a lessee row leaseId + leaseScheduleLineId |
rentalLeaseScheduleLine |
Sales-type lease schedule (sales module table, sales_* RLS): one effective-interest row per payment, journalId / postedAt stamped by postRevenueRecognitionRun; see Sales-type leases above |
reportPin |
Per-user pin overrides for the reports hub — explicit pinned boolean per (reportKey, userId, companyId); absent row = the report's default (core statements default pinned) |
Key Service Functions
getChartOfAccounts/getAccounts/upsertAccount— account managementgetTrialBalance— trial balance viatrialBalanceRPCgetFinancialStatementBalances— single-period statement balances with Net Income computation (trial balance report)getFinancialStatementPeriodSeries— multi-period balance sheet / income statement columns via theaccountTreeBalancePeriodSeriesRPC; per-bucket Net Income injection and optional per-bucket translation (translatearg)getConsolidatedBalances/getConsolidatedPeriodSeries— multi-company consolidation with currency translation (single-period / per-bucket)translateCompanyPeriodSeries— per-bucket currency translation (wrapstranslateCompanyBalancesonce per bucket)getAccountPeriodSeries— thin wrapper for theaccountTreeBalancePeriodSeriesRPC (period ends must come fromcomputeReportPeriodBuckets)getReportPins/upsertReportPin— per-user pin overrides for the reports hubcreateJournalEntry/saveJournalEntryWithLines/postJournalEntry/reverseJournalEntry— journal lifecycle.saveJournalEntryWithLinesdiffs the submitted lines against the stored ones (diffJournalLinesinaccounting.utils.ts: a line whoseidmatches is kept or updated in place, anything else inserted, the rest deleted; dimensions rewritten only when they changed) and applies it through thesave_journal_entry_linesRPC (SECURITY INVOKER, one transaction, refuses anything but a Draft journal of the company). A caller that sends no ids replaces every line. Keeps the Supabase-client signature becausesaveJournalEntryand the opening-balance / AR-AP adjust flows call it.getJournalEntryRelatedItems— the journal Documents panel: resolves each line'sdocumentType+documentIdto its document (sourceType settles sales vs purchase "Invoice") plus rows that store the journal's id (disposal, depreciation run line, revenue recognition run, CIP cost — each looked up only for its sourceType).getFixedAssetRelatedItems/getPeriodRunRelatedItemsfeed the fixed asset and run pages.getActivationCutover(accounting.service.ts) — the wizard's cutover date and date range. The wizard's reads and writes (getActivationReadiness,getCutoverInventoryValuation,getCutoverFixedAssets,getLegacyDocumentCounts,hasLegacyDocuments,getMigrationClearing,saveOpeningTrialBalance,updateCutoverAccumulatedDepreciation) are imported from@carbon/database/accounting-cutover-readsdirectly; the accounting module does not re-export them (see The enable wizard). The Opening Balances mode of the Chart of Accounts page (createOpeningBalanceJournal,OpeningBalancePostModal) is gone: the wizard's opening journal replaces it.'Opening Balance'issyncable:falsein@carbon/eePOSTING_POLICY — likeManual, it never syncs (the external ledger owns opening balances).getOrCreateAccountingPeriod/getCurrentAccountingPeriod— period management (lazy create on posting)createFiscalYearPeriods— generate the 12 monthly periods for a fiscal year (idempotent; fromfiscalYearSettings.startMonth)lockAccountingPeriod/unlockAccountingPeriod/closeAccountingPeriod/reopenAccountingPeriod— Open↔Locked↔Closed transitions (sequential close/reopen)getPeriodCloseChecklist/closePeriodWithChecklist/completeCloseTask/skipCloseTask— the close checklist (instantiates tasks, evaluates auto-checks, gates the close). The run checks readgetPeriodRunPreview(what new revenue recognition, lease and depreciation runs for the period end would hold, never throws) plus the Draft runs that wait; eachPeriodReadinessCheckthen carriesamount,dueanddraftRuns, and the close page (periods.$periodId.close.tsx) shows them with a Create Run button (intentscreate-revenue-run/create-lease-run/create-depreciation-run, allcreateRunForPeriod).loadPeriodCloseChecklist/computePeriodReadinesstake the preview as an argument, so the scripted tests pass a value.getAccountingPeriodDeletability/deleteAccountingPeriod— delete an empty, open period (blocks Locked/Closed or periods with journals)getFiscalCalendarCommitted— is the fiscal calendar committed (any posting or Locked/Closed period)? Gates editing the fiscal start monthgetCurrencies/getBaseCurrency/getCurrencyByCode— currency config lookups (decimals/active; no rate —currency.exchangeRatewas dropped)getExchangeRate/getExchangeRates— per-company rate resolution (RPCget_exchange_rate(s): base=1,exchangeRateOverridewins, else globalexchangeRatemarket-store ratio; missing = error, never 1)upsertExchangeRateOverride/deleteExchangeRateOverride— per-company user rate pins (always beat the daily feed)translateCompanyBalances— balance translation for multi-currency consolidationgetDimensions/getActiveDimensionsWithValues/saveJournalLineDimensions— dimension managementgetCostCenters/getCostCentersTree— cost center hierarchygetFixedAssets/insertFixedAsset/insertDepreciationRun— fixed asset lifecycle.buildDepreciationRunLinesis what a depreciation run for a period should hold;createDepreciationRuncreates the Draft from it and refuses "Nothing to depreciate for this period" rather than leave an empty run, and refuses any period a later posted run already covers (laterPostedRunId).postDepreciationRun(accounting.service.ts) locks the run, refuses anything but a Draft whose lines are the ones thepostDepreciationRunoperation checked, reads the lines and locks the assets inside its transaction, and adds toaccumulatedDepreciationin SQL; a month with no book amount posts no journalgetFleetAssets(thefleetAssetsview, search +fleetStatusfilter) /getUnderConstructionAssets/getFixedAssetTransfers/getFixedAssetCipCosts/getWorkCenterCapitalCost(non-Disposed assets of a work center with NBV and straight-line monthly depreciation) /setFixedAssetOutOfService/returnFixedAssetToService/getCapitalizationCost(previewAssetCapitalization, ported from thepreview-asset-capitalizationserver function: the costcapitalizewould book, rolled back) /invokeAssetTransfer(postAssetTransferthroughinvokePosting, run as the caller:capitalize(a unit carried at zero takes an entered cost from an offset account),return,attachJob,capitalizeCip,adjustCost— raise an Active / Fully Depreciated asset's cost from an offset account, and the next depreciation run catches a Straight Line asset up) — the fleet bridge (// -- Fleet --inaccounting.service.ts);postAssetRegistration(accounting.service.ts) takes a requiredposting(accounts, dimensions,resolveAccountingPeriodId) and an optionalstatus, and writes afixedAssetCipCostrow for a registration into a CIP class. It reads the posting status once, inside its transaction (journalPostingStatus(trx, …)): the journal is Provisional before the cutover (no period, no dimension check) and Posted after it, in the same transaction as the asset rowsgetRevenueRecognitionRuns/getRevenueRecognitionRun/getRevenueRecognitionRunLines/getRevenueSchedules/getDeferredRevenueWaterfall(service) andpostRevenueRecognitionRun/reverseRevenueRecognitionRun/deleteRevenueRecognitionRun(Kysely building blocks inaccounting.service.ts, wrapped by the service functions of the same name inaccounting.server.ts) — recognition and lease runs (loadPeriodRuns/createPeriodRuninroutes/x+/accounting+/period-runs.server.tsserve both list routes);resolveRunPostingPeriods/resolveReversalPeriods/reverseRunJournalsare shared with depreciation runs; the proposal builder isproposeRevenueRecognitionRun(accounting.service.ts, ported from thepropose-revenue-recognition-runserver function), andrecalculateRevenueRecognitionRun(accounting.service.ts) rebuilds a Draft through the sameselectDueScheduleRows/claimScheduleRowsgetRentalUtilization— the rental utilization report (above)getLeaseNetInvestment— the net investment in leases report (above)getLeaseLiabilities— the lessee Lease Liabilities report (above)createIntercompanyTransaction/runIntercompanyMatching/generateEliminations— IC processing
Operations (accounting.server.ts)
Each is a defineServiceFn const in accounting.server.ts. The route calls it as api.accounting.<name>(input); the API and MCP publish the ones tagged @mcp as accounting_<name>. It holds every check the route made. Routes validate the request, call one, and answer with respond(request, result).redirect(…) (a flash) or the result.
- Depreciation runs —
createDepreciationRun(the picked month end, else the month after the last run; refuses a period not after the last run, a month that has not started, a period that has a run, and nothing to depreciate),postDepreciationRun(Draft only; refuses a run out of date with the assets or covered by a later posted run, and an asset class without its depreciation accounts),recalculateDepreciationRun,repeatDepreciationRun(a Posted run's period, for the assets no run there covers),reverseDepreciationRun. - Revenue recognition and lease runs, by
type:createRevenueRecognitionRun,postRevenueRecognitionRun,repeatRevenueRecognitionRun(the next month),reverseRevenueRecognitionRun,recalculateRevenueRecognitionRun(recalculate-revenue-recognition-run, run as the caller),deleteRevenueRecognitionRun.createRevenueRecognitionRun,repeatRevenueRecognitionRunandcreateRunForPeriodshareproposeRunAt: a month that has not started and a period that already has a Draft of the type are refused beforepropose-revenue-recognition-runruns. The Draft refusal (andcreateRunForPeriod's depreciation one) carries the Draft's id as itscause;existingDraftRunIdreads it, and New Run, Repeat and the close page's Create Run open that Draft with the refusal as the flash. - Periods —
lockPeriod,unlockPeriod,closePeriod(closePeriodWithChecklist),createRunForPeriod(run: Revenue Recognition, Lease or Depreciation, for the period's end date; needs accounting create AND update). Close tasks —closeTaskComplete,closeTaskSkip. - Journal entries —
createJournalEntry(an empty Draft from the sequence),saveJournalEntry(every line needs an account and exactly one of a debit or a credit;postposts it after the save). - Fixed assets —
registerFixedAsset,disposeFixedAsset(scrap; Active or Fully Depreciated only),purchaseFixedAsset(a Draft PO with one Fixed Asset line; Draft or Under Construction only;create: purchasing),sellFixedAsset(a Draft SO line at net book value; Active or Fully Depreciated only;create: sales) — both delete the new order when its line fails,takeFixedAssetOutOfService(refuses Disposed, already out, and a unit on rent —outOfServiceRefusal, which the page's loader also asks),returnFixedAssetToService. overrideExchangeRate(refuses the base currency),resetExchangeRate.updateCurrency(pins the rate only when it was edited;saveCurrencyWithRateOverride).moveAccount(the parent must be a group of the chart, and not the account or one of its own accounts).importChartOfAccounts(service.applyAccountImport).enableAccountingCutover(activate-accounting). Neither of these two is tagged@mcp: they run from the import page and the activation wizard only.
A building block's own refusal ("Only open periods can be locked") is passed on with its message; a data-layer failure gets the route's old wording. Out of scope so far: the single-call actions (chart, cost center, dimension, payment term, project, asset class and fixed asset CRUD, journal post / reverse / delete, run deletes, period generate / delete, fiscal year, defaults, intercompany, report pins and views, the invokeAssetTransfer routes), the activation wizard's trial balance and fixed asset steps, and reimbursements and charges (invoicing). Each single-call action is still its own thin service function (createCostCenter, postJournalEntry, deleteDepreciationRun, …).
Key Exports
import { getExchangeRate, getPaymentTermsList, getDefaultAccounts } from "~/modules/accounting/accounting.service";
Related Modules
- purchasing — purchase invoices post to AP; receipts create inventory GL entries; lessee leases post
'Lease'journals and their schedule rows post in the lease run - sales — sales invoices post to AR; quotes use
getExchangeRatefor exchange rates - inventory — inventory movements resolve GL accounts through replenishment system and company raw-material/finished-goods defaults; the storage-unit row action Capitalize as Fixed Asset hands a serialized unit to
x+/fixed-asset+/capitalize.tsx - production — a Make to Asset job (
job.fixedAssetClassId/fixedAssetId, Complete To on the job form) completes into fixed assets insidecomplete_job_to_inventory; Attach Job on a CIP asset sweeps a job's WIP onto it - resources —
fixedAsset.workCenterId;work-centers.$id.tsxloadsgetWorkCenterCapitalCostfor the read-only Capital Cost panel onWorkCenterForm - sales (rentals) — rental agreements rent
fleetAssetsunits; Rental invoice lines of aRentalline post to Contract Assets / Deferred Revenue / Rental Income and are recognized by the lease run, those of aSaleline (sales-type lease) to Net Investment in Leases; aSalecommencement disposes the fleet asset and a residual return capitalizes a new one;post-asset-transferreturnrefuses a unit on a live rental line - items —
itemPostingGroupsupplies dimension metadata; company defaults resolve posting accounts - people — employees used as dimension values; cost center assignments
Rules References
.claude/rules/accounting-sync-handlers.md— provider sync architecture, entity syncers, Inngest functions.claude/rules/fixed-asset-lifecycle.md— asset statuses, depreciation methods, disposal flow