Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

84.1 KB
Raw Blame

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), and accountType. Group accounts contain children; leaf accounts post transactions. Scoped by companyGroupId.
  • Journal Entries — double-entry bookkeeping in the journal table. amount uses natural balances: positive Asset/Expense is debit; positive Liability/Equity/Revenue is credit. Convert by account class before summing debit-signed amounts. Lines carry dimensions and cost center allocations. Statuses (journalEntryStatus): a manual entry is Draft → Posted → Reversed; an automatic posting is born Provisional before the company's accounting cutover and Posted after it; the enable turns a Provisional journal into Posted (dated on or after the cutover) or Superseded (dated before it). JournalEntryStatus labels Superseded "Before cutover". getJournalEntries leaves 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.accountingCutoverDate decides only the journal status; hasAccountingCutover(settings) (accounting.utils.ts) is the ERP's one test for it. companySettings.accountingEnabled still exists, but no code reads it. accountingActivatedAt / accountingActivatedBy record the enable; the check_accounting_config_locked trigger then refuses any change to the three cutover columns, to company.baseCurrencyCode and to fiscalYearSettings.startMonth. A new company has no cutover: seed-company leaves 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: AccountingBetaGate overlays 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), and x+/accounting+/_index.tsx redirects to the wizard. A Provisional journal has no accounting period, so it never locks the fiscal calendar (getFiscalCalendarCommitted counts 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. The journal-status-filter check (@carbon/checks) fails a status <> 'Draft' journal filter in TS and in migrations from 20261009005144. 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 accept sourceType 'Opening Balance' (20261009014620).
  • Stand-in lines — before the cutover, a posting that needs an empty nullable account default posts the line to retainedEarningsAccount and names the default it wanted in journalLine.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) in postJournalEntry, reverseJournalEntry, lockAccountingPeriod, closeAccountingPeriod and createDepreciationRun; requireGroupAccountingCutover (every company of the group) in runIntercompanyMatching and generateEliminations; a readAccountingCutoverDate test (@carbon/database/journal-posting-status) at the top of postDepreciationRun, postDisposal and postRevenueRecognitionRun (accounting.service.ts); and assertAccountingCutover (shared.service.ts, the same read) in the propose-revenue-recognition-run and recalculate-revenue-recognition-run postings.
  • 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 by getActivationCutover in accounting.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 of getActivationReadiness: every accountDefault account column set to an active account, except a default with a fallback (hasDefaultFallback), which may stay empty, and migrationClearingAccount an 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 Posted Opening Balance journal. Each ActivationCheck carries reasons, codes (ActivationCheckReason: no-fiscal-year-settings, no-base-currency, migration-clearing-wrong-kind and the four CutoverDateReason codes) that ReadinessChecklist translates; detail says 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.unitCost for 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; intent save-asset writes the accumulated depreciation as of the day before the cutover through updateCutoverAccumulatedDepreciation, 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 Draft Opening Balance journal with no period by saveOpeningTrialBalance; one debit-signed balance per account in the editor (a credit is negative; the save still sends a debit and a credit); intents save-tb (the editor), import-tb (CSV accountNumber, debit, credit, saves nothing when a row has an error), pull-tb (only when the active accounting integration passes isTrialBalanceProvider — 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) and apply-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 the retainedEarningsAccount row, so Migration Clearing totals zero; the button is enabled while the total is not zero). The CSV parser is the pure, tested trial-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, since 1,234 is a thousand in one convention and one and a fraction in another; getMigrationClearing shows, 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 in accountingCutoverIgnoredInvoice, takes it out of items into ignoredItems, 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) and activation.enable.tsx (the summary and the typed company name; it invokes activateAccounting (accounting.service.ts, ported from the activate-accounting server 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 under packages/database/src/accounting-cutover/). The wizard routes import them from there directly and pass getDatabaseClient(); activate-accounting calls 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 Balance journal, dated the day before the cutover, against accountDefault.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>, accrual true, 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 each Sale line commenced before the cutover (the last rentalLeaseScheduleLine.closingNetInvestment before the cutover, else initialNetInvestment), 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 depreciationRunLine per 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 an item / 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, status Under Construction, cost rows in fixedAssetCipCost) 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 of getFixedAssetClasses / getFixedAssetClassesList (every class list and picker), hides Attach Job / Capitalize and the CIP cost card (isCipClass in x+/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 Posted fixedAssetTransfer document written by postAssetTransfer (accounting.service.ts, ported from the post-asset-transfer server function) (journal sourceType 'Asset Transfer', off by default in the sync policy). Fleet status is derived by the fleetAssets view, never stored. See .claude/rules/fixed-asset-lifecycle.md.
  • Revenue recognition — revenueRecognitionSchedule is the one "what to post, when" table: type Deferral / Accrual / Interest / Amortization, status Planned / Posted, each row carrying its own debitAccountId / creditAccountId, linked to a salesInvoiceLineId, a rentalAgreementLineId, a customerContractLineId (contract rows, see Contract revenue below) or a lessee leaseId + 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 admits Rental, whose lines carry their billing period), upsertSalesOrderLine / upsertSalesInvoiceLine null them on any other type, and posting ignores dates left on a non-Service line. A run (revenueRecognitionRun / revenueRecognitionRunLine) has a type (runType): Revenue Recognition or Lease — see Run types below. It claims every Planned row of its type dated on or before its periodEnd and first runs its type's synthesizers (runRowSynthesizers(type)) in proposeRevenueRecognitionRun (accounting.service.ts, ported from the propose-revenue-recognition-run server function) (apps/erp/app/modules/accounting/accounting.service.ts, { periodEnd, type }, permission create: accounting; the routes call it through invokePosting, the monthly job through posting). postRevenueRecognitionRun (accounting.service.ts) posts the run's journals (sourceType 'Revenue Recognition' or 'Lease Run' by run type (buildRecognitionJournals, @carbon/database run-journals.ts), both defaultEnabled: false in the sync policy; one per month, below); deferral lines reference the invoice, rental Accrual/Interest lines documentType 'Rental Agreement' with Customer / Item / Location dimensions resolved from the agreement, lessee rows documentType 'Lease' + documentLineReference = the asset (leaseLine, from RecognitionSources.leaseAssets) with Supplier / the asset's Location dimensions. Inngest revenue-recognition-proposal (cron 0 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 index revenueRecognitionRun_one_draft_per_period (companyId, type, periodEnd WHERE 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.journalId names 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; reverseJournalEntry refuses 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 the recalculate-revenue-recognition-run server 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 its periodEnd again; a run with nothing left due is deleted. The proposal's periodEnd must be a real month end (a 400 otherwise). postRevenueRecognitionRun refuses a run that is out of date — a held row's amount or status changed, or an unclaimed Planned row is due by its periodEnd — with RunOutOfDateError, whose message the post route shows. A write that deletes a held Planned row (an invoice void, or synthesizeContractRevenue dropping a contract row whose plan month was replaced) keeps Draft runs in step in its own transaction through syncDraftRecognitionRuns (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 the preview-revenue-recognition-run server function) ({ periodEnd, type }, view: accounting) runs the synthesizers and selectDueScheduleRows in 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 adds RUN_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 a rentalAgreementLineId or a leaseId (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.ts uses the same filter; post checks only its own type's unclaimed rows (the contract check only for revenue runs) and stamps lessee leaseScheduleLine.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 from RUN_SEQUENCE (revenueRecognitionRun / leaseRun, prefix LR). Lease runs: route x+/accounting+/lease-runs.tsx (+ .new); revenue runs x+/accounting+/revenue-recognition-runs*; both in the nav under Accounting → Closing. Both list routes share loadPeriodRuns / createPeriodRun (period-runs.server.ts) and PeriodRunsPage; a run of either type opens at x+/revenue-recognition-run+/$runId (post, reverse, repeat, recalculate, delete follow the run's type). 20261011163211_lessee-leases.sql released rental rows from Draft revenue runs (posted history kept) and 20261011192957_lease-run-sync-policy.sql copied each accounting integration's Revenue Recognition sync setting to Lease Run. reverseJournalEntry refuses a Lease Run journal like the other run sources (RUN_JOURNAL_SOURCES).
  • Rental accruals — synthesizeRentalAccruals (the lease run's synthesizer) accrues earned-but-unposted rent of Rental (operating-lease) lines for the run's calendar month (Dr contractAssetAccount / Cr rentalIncomeAccount, both required or it throws "Set the Contract Assets and Rental Income account defaults before recognizing rental revenue"). It takes every non-adjustment rentalBillingPeriod of a Rental line (On Rent / Returned) that no POSTED invoice covers (Pending, or Invoiced onto 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 stamps billedBySalesInvoiceLineId. 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.md Part IV D5) — synthesizeContractRevenue (the revenue recognition run's synthesizer, runRowSynthesizers) turns every Planned customerContractRevenue month starting on or before the period end, of a non-Draft contract, with no schedule row yet, into a Deferral row (Dr deferredRevenueAccount / Cr salesAccount) for the part the line's deferred pool covers and an Accrual row (Dr contractAssetAccount / Cr salesAccount) for the rest, at get_exchange_rate(…, periodEnd); each row carries customerContractLineId, customerContractRevenueId, contractAmount and one Recognition entry in customerContractLedgerEntry (cascades with the row). A negative (catch-up) month yields negative rows. It first drops Planned contract rows whose plan month was replaced (customerContractRevenueId nulled). postRevenueRecognitionRun posts contract rows with documentType 'Contract' and Customer / Item / Project (line, else contract) dimensions, flips their plan months to Recognized, 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; lessorClassification values Rental / Sale / Financing) at activation (postRentalAgreement, sales.service.ts; see sales AGENTS → Rentals) posts its commencement and end-of-term residual return as journals of sourceType 'Lease' (POSTING_POLICY Lease, defaultEnabled: false; also in the hand-written journalEntrySourceTypes array with the LuKeyRound icon), lines documentType 'Rental Agreement' with Customer / Item / Location dimensions. Its effective-interest schedule is rentalLeaseScheduleLine; each line that earnsInterest (lessor-lease in @carbon/utils: not zero, not the one-unit drift an Advance lease closing on zero leaves on its last line) spawns one Planned Interest recognition row (Dr netInvestmentInLeasesAccount / Cr leaseInterestIncomeAccount) that the LEASE run posts under 'Lease Run', and postRevenueRecognitionRun then stamps the schedule line's journalId / postedAt; Reverse Run (reverseRevenueRecognitionRun) clears the stamps. Rent and Purchase Option invoice lines of a Sale line credit netInvestmentInLeasesAccount; a Purchase Option line also settles the rest of the line's NI against the schedule's closing balance (purchaseOptionSettlement, invoicing.service.ts: shortfall Dr costOfGoodsSoldAccount / Cr NI, excess Dr NI / Cr leaseRevenueAccount). 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-lease in @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 thresholds companySettings.leaseMajorPartThresholdPercent 75 / leaseSubstantiallyAllThresholdPercent 90, shared by lessor and lessee; the lessor leaseDefaultDiscountRate 6, label "Lessor Discount Rate (%)"; the lessee leaseIncrementalBorrowingRate 6, leaseShortTermExpedient true and leaseReminderDays 90) is edited on x+/settings+/accounting.tsx ("Lease Classification" card, intent leasePolicy, update: settings) through updateAccountingSettings; changes affect later activations only.
  • Net investment report — getLeaseNetInvestment(client, companyId, { asOf }), report x+/reports+/lease-net-investment.tsx (view: accounting; hub card "Net Investment in Leases", category Close Reports; path.to.leaseNetInvestment). Per commenced Sale line live on asOf (Pending / On Rent, or Returned after asOf; Sold lines omitted; agreement startDate ≤ asOf): initialNetInvestment, posted principal (schedule lines with periodDate ≤ asOf whose 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). Reads rentalAgreementLine and rentalLeaseScheduleLine, whose RLS is sales_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_POLICY Lease, also used by sales-type rentals) for commencement, opening balance, modification, termination, purchase and the cancel VOID, lines documentType 'Lease' (journalLineDocumentType value) + documentLineReference = the leased asset (leaseLine) with Supplier / the asset's Location dimensions; getJournalEntryRelatedItems links them, and Lease Run journals, back to their lease or run. Seven account defaults (migration 20261011163211, seeded for new companies in seed-data.ts): rightOfUseAssetAccount 1450, accumulatedRightOfUseAmortizationAccount 1460, leaseLiabilityAccount 2440, variableLeaseExpenseAccount 6130, operatingLeaseExpenseAccount 6140, rightOfUseAmortizationExpenseAccount 6330, leaseInterestExpenseAccount 7020 — the "Leases (Lessee)" group of AccountDefaultsForm, all required by the readiness check (ACCOUNT_DEFAULT_COLUMNS, accounting-cutover/shared.ts). Each asset's schedule line spawns an Interest row (Dr operating lease expense or lease interest expense / Cr lease liability) and an Amortization row (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 pure leaseLiabilityAssets / summarizeLeaseLiabilities / summarizeLeaseCosts in lease-liabilities.ts, pinned by lease-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), report x+/reports+/lease-liabilities.tsx (view: accounting AND view: 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 by leaseLineId) the liability and net ROU asset as of asOf, 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 to asOf) 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 after asOf (not a 12-month date window); an asset that ends within them (its leaseEvent Termination / Purchase date, never lease.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 by asOf is 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 is purchasing_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 (openItemType Lease 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-lease activate, purchasing AGENTS).
  • Rental utilization — getRentalUtilization(client, companyId, { from, to, fixedAssetClassId }), report x+/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 per fixedAssetClass. One read per table, joined in TS.
  • Intercompany — transactions between companies in a group. runIntercompanyMatching pairs them; generateEliminations creates reversing entries on the lowest-common-parent elimination entity, classified by journal.eliminationKind: 'IC Balance' (reverse IC Receivable/Payable) and 'IC Revenue' (reverse an intragroup sale's revenue + COGS and write the buyer's capitalized asset down to group cost — removes intragroup profit from consolidated income). The engine is capture-driven, not GL reconstruction: the postings (post-sales-invoice, post-purchase-invoice) record role-tagged references (intercompanyEliminationLine: Control/Revenue/COGS/Capitalization) when each side posts, and generateEliminationEntries reads them — so it writes down whatever account the BUYER capitalized (inventory OR a fixed asset — the latter is now in scope, was the negative-Finished-Goods bug). The writedown scales by the buyer's on-hand fraction (fixed assets: full until disposed); revenue/COGS reversal scale by the same fraction so the entry balances. p_regenerate reverses existing eliminations (reversing entries, never deletes) and re-derives — the workbench "Regenerate" button. Both halves of a trade record their matching amount in the trade's DOCUMENT currency rounded at internal SCALE — calculateSalesIntercompanyAmount (seller) and round(intercompanyAmount) (buyer). generate_intercompany_matches pairs them on exact NUMERIC equality with no tolerance, so rounding either half at settlement precision leaves every trade with sub-cent digits permanently Unmatched and eliminations never run. Investment/NCI and seller fixed-asset disposal (deferred gain) remain out of scope. See .ai/specs/2026-08-17-intercompany-elimination-engine.md.
  • Currency translation / CTA — translateCompanyBalances validates the source trial balance using natural debit/credit signs and positive finite pair rates. Missing rates fail explicitly. applyCtaToReportPeriodSeriesForReport resolves only the root company's CTA mapping through a server-only permission and company-group/root check; operating-company ledger reads remain RLS-scoped. The existing applyCtaToReportPeriodSeries service adds the calculated CTA once to the reporting root company's configured currencyTranslationAccount, validates its active Equity posting leaf, then rerolls intermediate groups and roots before filtering/export. Never identify CTA by account number. Financial report chart reads include inactive historical accounts and their ancestors; chart and balance RPC rows are fully paginated before calculation. Active-only filters belong to posting/configuration pickers. Balance RPC trees and period-close snapshots retain inactive posting leaves and ancestors. Report loaders reject company selections outside the available company group (404) before balance reads.
  • Shipping revenue — accountDefault.salesShippingRevenueAccount maps an active Revenue posting leaf distinct from Sales. New groups seed 4050 Shipping Revenue under Revenue; existing groups resolve a compatible leaf and backfill mappings. Nonzero invoice shipping requires a valid mapping; output tax posts separately to tax payable. The full defaults form validates once and saves both sections with one company-scoped updateDefaultAccounts UPDATE, so a failed mapping cannot half-save the form.
  • Payments have THREE payee kinds, not two. payment.employeeId is a reimbursement payout: always a Disbursement, never AR, never a refund, and it targets invoiceSettlement.targetReimbursementId only — no invoice target, no discount, no write-off, no prior credit. Its control account is accountDefault.employeeReimbursementsPayableAccount, falling back to payablesAccount at runtime. journalEntrySourceType gained Charge and Reimbursement (the former replacing Card 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 exact sourceAmount principal and appliedAmount carrying base. Unknown memo principal retains the existing exclusion contract; it is not reconstructed or raised as a report error. Payment/invoice application histories page all rows, including embedded parent statuses and refund labels, before totaling.
  • Customer deposits — a customer payment with payment.rentalAgreementId or payment.salesOrderId (CHECK payment_deposit_document_check: at most one; paymentValidator refines the same and refuses it on a supplier payment) is a deposit. post-payment books its unapplied cash on accountDefault.prepaymentAccount (2110 Customer Prepayments, class Liability) with description CUSTOMER_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 posts CUSTOMER_DEPOSIT_APPLIED_DESCRIPTION ("Customer Deposit (applied)") as a debit on the prepayment account. A deposit funds only its own document: allocatePaymentFunding (@carbon/utils payment-funding) gives each FundingSource an optional scope (fundingScopeOf(payment) → { type: "rentalAgreement" | "salesOrder", id, readableId? }) and each FundingRequest the rentalAgreementIds / salesOrderIds its invoice bills (from salesInvoiceLine, one read per call: loadSalesInvoiceDocumentIds in @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 via loadDepositScope). Source priority is unchanged (current payment, then prior sources by postingDate, 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. replaceInvoiceSettlements and post-payment both apply it (post re-derives, so a crafted Draft cannot bypass it). getAvailableOnAccountCreditSources returns deposits in sources with their scope but leaves them out of availableDocumentAmount / availableBaseAmount (and getAvailableOnAccountCredit); getOpenSalesInvoicesForCustomer returns each invoice's rentalAgreementIds / salesOrderIds; PaymentApplyTable lists each deposit apart ("Deposit for RA000001 (its invoices only)"), sizes rows with fundableDocumentAmounts, 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 by getDepositDocuments (invoicing/invoicing.service.ts, server-only, called by the loaders of x+/payments+/new.tsx and x+/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 flagged open (open order / Draft or Active agreement). The form narrows to the payment's customer; a Receipt offers only open documents (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 by api+/accounting.chart-of-accounts[.]csv.tsx, downloads the current chart in those columns) and the default accounts template (defaultAccountsTemplate, served by api+/accounting.default-accounts[.]csv.tsx; parseDefaultsCsv) with the customer's number for every accountDefault role and fixed asset class account. The pure planner planAccountImport (@carbon/database/account-import) and its reads loadAccountImportContext (@carbon/database/account-import-reads) back both the review (intent plan) and applyAccountImport (accounting.service.ts, ported from the apply-account-import server function; intent apply), 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 a replacements entry 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 through parseCsvLines (@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 the apply-account-import server function; input { chart, defaults, resolutions }, trimmed and size-capped, permission update: accounting) in one transaction. It locks every company's companySettings FOR SHARE, then the group's accounts FOR UPDATE, re-plans with planAccountImport, and refuses a plan with errors or an open replacement — including any company of the group with an accounting cutover. It sets app.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 by REFERENCE_POLICY plus the references with no foreign key (intercompanyEliminationLine, companyIntegration.metadata.paymentFeeAccount) — posted documents included, since their journals are still Provisional — deletes the removed accounts and their externalIntegrationMapping rows, 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_ID constant.

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) returns Provisional when the company has no cutover and Posted when it has one. postingStatusFor(cutoverDate) is the same decision without a read, and readAccountingCutoverDate returns the date. All reads take FOR SHARE. The SQL posting functions (complete_job_to_inventory, backflush_job_materials) call journal_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 again FOR SHARE and throws POSTING_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-accounting takes FOR UPDATE on the same row, so no posting writes a Provisional journal after the enable commits.
  • No period before the cutover. A Provisional journal has accountingPeriodId null, and no posting creates a period for it. Resolve a period only when the status is Posted.
  • Stand-in lines. resolveDefaultAccount(defaults, role, postingStatus) picks the account for a line that needs one of the nullable defaults in OPTIONAL_DEFAULT_ROLES. A set default is used as is.
    • An empty default with a fallback in DEFAULT_FALLBACKS uses the fallback, before and after the cutover (for example scrapAccount → 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 retainedEarningsAccount with accountDefaultRole = role, and the line stores that role in journalLine.accountDefaultRole. After the cutover it throws MissingAccountDefaultError: status 400, message "Set the
    • A void copies accountDefaultRole from each original line to its reversal.
    • A revenueRecognitionSchedule row never takes a stand-in. post-sales-invoice refuses when the deferral, contract asset or rental default it needs is empty, in both states. The invoice's own lines take stand-ins through salesInvoiceStandIns (shared.service.ts: leaseRevenueAccount, netInvestmentInLeasesAccount, salesShippingRevenueAccount).
  • 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. The journal-status-filter check (@carbon/checks) fails a status <> '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 in post-payment accept sourceType 'Opening Balance' as well as the invoice, memo and Payment source types.
  • Voids of a document dated before the cutover (refuseVoidBeforeCutover, shared.service.ts; isBeforeCutover in @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 throws PURCHASE_INVOICE_VOID_BEFORE_CUTOVER_ERROR ("… Record a debit memo instead.").
    • A charge void throws CHARGE_VOID_BEFORE_CUTOVER_ERROR and a reimbursement void throws REIMBURSEMENT_VOID_BEFORE_CUTOVER_ERROR ("… Record a journal entry to correct it instead."). The date is postingDate, else transactionDate or reimbursementDate, as the posting uses.
    • A payment or memo void builds the document's posting again (rebuildPaymentJournal and rebuildMemoJournal, both in the ERP's invoicing.service.ts) and posts it negated, dated today, so it nets the opening lines. assertNoMigrationClearing refuses a rebuilt line on the Migration Clearing account. A customer credit memo that credits a contract or a rental agreement throws MEMO_CREDIT_VOID_BEFORE_CUTOVER_ERROR instead.
    • A time entry whose journal the enable superseded is not posted again. post-production-event refuses an event posted to GL with a line in a Superseded journal. post-maintenance-event refuses an entry whose expense changed (edited or deleted), and drops an unchanged one (withoutSupersededEntries, resources.service.ts). Both throw TIME_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.
  • 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) throws ACCOUNTING_NOT_STARTED ("Set up accounting before you post journals, runs or period closes."). propose-revenue-recognition-run and recalculate-revenue-recognition-run call 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:

  1. Locks companySettings FOR UPDATE. Refuses when the company already has a cutover (ACCOUNTING_ALREADY_SET_UP) or when confirmation is not the company name. Runs getActivationReadiness and getMigrationClearing (@carbon/database/accounting-cutover-reads) again under the lock. Refuses on a failed check, or when Migration Clearing does not total zero (isMigrationClearingZero). The account-defaults check refuses an empty migrationClearingAccount, and one that is not an active Equity posting account. 1a. Writes the journals of the legacy documents (journalLegacyDocuments, below).
  2. 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 from getCutoverInventory: a Standard item takes its standard cost, a FIFO or LIFO item the value its layers held at the cutover (unitCostAtCutover replays the layers dated before it), and an Average item itemCost.unitCost, the one cost the wizard's inventory step lets a user edit.
  3. 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. A Revaluation cost row (a serial recost) keeps its cost.
  4. Sets every Provisional journal dated before the cutover to Superseded.
  5. Sets every Planned revenueRecognitionSchedule row dated before the cutover to Posted with no journal.
  6. Fixed assets: no write. The register already holds the values at the cutover.
  7. Deletes the Draft trial balance journal and posts the opening journal (buildOpeningJournalLines), Posted, dated the day before the cutover. Before that, markIgnoredInvoicesPaid sets every invoice ignored on Migration Clearing (clearing.ignoredItems, rows of accountingCutoverIgnoredInvoice still open at the cutover) to Paid with datePaid the day before the cutover, with app.sync_in_progress on 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.
  8. assignPeriods gives each Provisional journal dated on or after the cutover the period of its date.
  9. repointStandInLines moves each stand-in line to the default it names (or that default's fallback). Then promoteJournals promotes those journals to Posted. Both are in accounting.service.ts.
  10. Closes every period that ends before the cutover and snapshots its balances (snapshotAccountingPeriodBalances). It does not call closeAccountingPeriod, which opens its own transaction. 10a. getCurrentAccountingPeriod makes the period that holds today Active, as the first posting would.
  11. Sets accountingCutoverDate, accountingActivatedAt and accountingActivatedBy. The check_accounting_config_locked trigger 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, and getLegacyDocumentCounts (@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 in accounting.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, then replayReliefs). A Standard item costs at its standard cost and an Average one at itemCost.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 rebuildMemoJournals and rebuildPaymentJournals (invoicing.service.ts). The pre-cutover voids use the same code for one document (rebuildMemoJournal, rebuildPaymentJournal). The payment posting and its rebuild assemble the buildPaymentJournal input in one place (assemblePaymentJournal, invoicing.service.ts), and apps/erp/test/database/post-payment/rebuild-journal.test.ts pins 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) calls keepOutOfProviderSync for every journal it writes, in the enable's step 1a and in the repair. It writes an Excluded accountingSyncOperation per accounting integration with errorCode CUTOVER_REBUILT (CUTOVER_REBUILT_SYNC_CODE). Re-send in Sync Activity still pushes one.
  • Closed periods. Before it writes a batch, insertProvisionalJournals refuses when a period that holds one of the batch's posting dates is Closed or Locked, or has closedAt set. The InvalidInputError names 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 legacyJournals counts the journals written per family (LegacyJournalCounts: LegacyDocumentCounts plus movementCostRows). 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 — postJournalEntry validates total debits = total credits before posting.
  • MUST use rootSignMultiplier logic for root account aggregation — Assets/Revenue add, Liabilities/Equity/Expense subtract.
  • MUST scope chart of accounts by companyGroupId (shared across group) and transactions by companyId.
  • MUST use getOrCreateAccountingPeriod before 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_STATUSES or OPEN_ITEM_JOURNAL_STATUSES — never <> 'Draft', which counts Provisional and Superseded journals.
  • MUST use toStoredAmount / toDisplayDebit / toDisplayCredit for amount conversion — respects account class sign conventions.

Ask First

  • Modifying the chart of accounts structure — affects all financial reporting.
  • Posting depreciation — postDepreciationRun writes 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 reverseJournalEntry instead.
  • 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 Posted or Superseded outside activate-accounting. The enable is one-way; journal UPDATE RLS admits Draft and Posted only, and check_posted_record_immutable refuses 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 when isAccountInUse (@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 management
  • getTrialBalance — trial balance via trialBalance RPC
  • getFinancialStatementBalances — single-period statement balances with Net Income computation (trial balance report)
  • getFinancialStatementPeriodSeries — multi-period balance sheet / income statement columns via the accountTreeBalancePeriodSeries RPC; per-bucket Net Income injection and optional per-bucket translation (translate arg)
  • getConsolidatedBalances / getConsolidatedPeriodSeries — multi-company consolidation with currency translation (single-period / per-bucket)
  • translateCompanyPeriodSeries — per-bucket currency translation (wraps translateCompanyBalances once per bucket)
  • getAccountPeriodSeries — thin wrapper for the accountTreeBalancePeriodSeries RPC (period ends must come from computeReportPeriodBuckets)
  • getReportPins / upsertReportPin — per-user pin overrides for the reports hub
  • createJournalEntry / saveJournalEntryWithLines / postJournalEntry / reverseJournalEntry — journal lifecycle. saveJournalEntryWithLines diffs the submitted lines against the stored ones (diffJournalLines in accounting.utils.ts: a line whose id matches is kept or updated in place, anything else inserted, the rest deleted; dimensions rewritten only when they changed) and applies it through the save_journal_entry_lines RPC (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 because saveJournalEntry and the opening-balance / AR-AP adjust flows call it.
  • getJournalEntryRelatedItems — the journal Documents panel: resolves each line's documentType + documentId to 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 / getPeriodRunRelatedItems feed 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-reads directly; 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' is syncable:false in @carbon/ee POSTING_POLICY — like Manual, 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; from fiscalYearSettings.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 read getPeriodRunPreview (what new revenue recognition, lease and depreciation runs for the period end would hold, never throws) plus the Draft runs that wait; each PeriodReadinessCheck then carries amount, due and draftRuns, and the close page (periods.$periodId.close.tsx) shows them with a Create Run button (intents create-revenue-run / create-lease-run / create-depreciation-run, all createRunForPeriod). loadPeriodCloseChecklist / computePeriodReadiness take 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 month
  • getCurrencies / getBaseCurrency / getCurrencyByCode — currency config lookups (decimals/active; no rate — currency.exchangeRate was dropped)
  • getExchangeRate / getExchangeRates — per-company rate resolution (RPC get_exchange_rate(s): base=1, exchangeRateOverride wins, else global exchangeRate market-store ratio; missing = error, never 1)
  • upsertExchangeRateOverride / deleteExchangeRateOverride — per-company user rate pins (always beat the daily feed)
  • translateCompanyBalances — balance translation for multi-currency consolidation
  • getDimensions / getActiveDimensionsWithValues / saveJournalLineDimensions — dimension management
  • getCostCenters / getCostCentersTree — cost center hierarchy
  • getFixedAssets / insertFixedAsset / insertDepreciationRun — fixed asset lifecycle. buildDepreciationRunLines is what a depreciation run for a period should hold; createDepreciationRun creates 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 the postDepreciationRun operation checked, reads the lines and locks the assets inside its transaction, and adds to accumulatedDepreciation in SQL; a month with no book amount posts no journal
  • getFleetAssets (the fleetAssets view, search + fleetStatus filter) / getUnderConstructionAssets / getFixedAssetTransfers / getFixedAssetCipCosts / getWorkCenterCapitalCost (non-Disposed assets of a work center with NBV and straight-line monthly depreciation) / setFixedAssetOutOfService / returnFixedAssetToService / getCapitalizationCost (previewAssetCapitalization, ported from the preview-asset-capitalization server function: the cost capitalize would book, rolled back) / invokeAssetTransfer (postAssetTransfer through invokePosting, 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 -- in accounting.service.ts); postAssetRegistration (accounting.service.ts) takes a required posting (accounts, dimensions, resolveAccountingPeriodId) and an optional status, and writes a fixedAssetCipCost row 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 rows
  • getRevenueRecognitionRuns / getRevenueRecognitionRun / getRevenueRecognitionRunLines / getRevenueSchedules / getDeferredRevenueWaterfall (service) and postRevenueRecognitionRun / reverseRevenueRecognitionRun / deleteRevenueRecognitionRun (Kysely building blocks in accounting.service.ts, wrapped by the service functions of the same name in accounting.server.ts) — recognition and lease runs (loadPeriodRuns / createPeriodRun in routes/x+/accounting+/period-runs.server.ts serve both list routes); resolveRunPostingPeriods / resolveReversalPeriods / reverseRunJournals are shared with depreciation runs; the proposal builder is proposeRevenueRecognitionRun (accounting.service.ts, ported from the propose-revenue-recognition-run server function), and recalculateRevenueRecognitionRun (accounting.service.ts) rebuilds a Draft through the same selectDueScheduleRows / claimScheduleRows
  • getRentalUtilization — 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, repeatRevenueRecognitionRun and createRunForPeriod share proposeRunAt: a month that has not started and a period that already has a Draft of the type are refused before propose-revenue-recognition-run runs. The Draft refusal (and createRunForPeriod's depreciation one) carries the Draft's id as its cause; existingDraftRunId reads 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; post posts 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 getExchangeRate for 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 inside complete_job_to_inventory; Attach Job on a CIP asset sweeps a job's WIP onto it
  • resources — fixedAsset.workCenterId; work-centers.$id.tsx loads getWorkCenterCapitalCost for the read-only Capital Cost panel on WorkCenterForm
  • sales (rentals) — rental agreements rent fleetAssets units; Rental invoice lines of a Rental line post to Contract Assets / Deferred Revenue / Rental Income and are recognized by the lease run, those of a Sale line (sales-type lease) to Net Investment in Leases; a Sale commencement disposes the fleet asset and a residual return capitalizes a new one; post-asset-transfer return refuses a unit on a live rental line
  • items — itemPostingGroup supplies dimension metadata; company defaults resolve posting accounts
  • people — employees used as dimension values; cost center assignments

Rules References

  • .claude/rules/accounting-sync-handlers.md — provider sync architecture, entity syncers, Inngest functions
  • .claude/rules/fixed-asset-lifecycle.md — asset statuses, depreciation methods, disposal flow