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.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
feat(accounting): single-column trial balance, Migration Clearing ignores, provider trial balance pull (#1910)
Brad Barbin83099634b648
diff --git a/.ai/lessons.md b/.ai/lessons.mdindex cf7a1f302f..4bf5943c0f 100644--- a/.ai/lessons.md+++ b/.ai/lessons.md@@ -3649,3 +3649,23 @@ The write was then removed (nothing reads it), so the rail always starts collaps**Rule:** Do not start reading a cookie, local-storage key or column that code has only ever written. Its values were never a user's deliberate choice. Give the new preference a new name, or start every user from the default.**Applies to:** `SidebarProvider` and any other write-only client state (`document.cookie`, `localStorage`) that a loader or component begins to read.++## The manifest-digest hook checks the working tree, not the staged copy++**Context:** The trial balance PR (2026-10-13) left `tool-manifest.digest.json` out of a commit, thinking its diff was unrelated drift.++**Problem:** `check:manifest` regenerates the digest and compares it with the file on disk. The disk copy was the regenerated one, so the hook passed while the commit carried the stale digest. Only running the check against the committed version showed "2 changed".++**Rule:** Never leave a regenerated `tool-manifest.digest.json` unstaged on the assumption that it is drift. Run `pnpm --silent check:manifest` with the committed copy restored; when it fails, the regenerated digest belongs in the commit.++**Applies to:** `apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json`, `scripts/git-hooks/pre-commit`.++## An item left out at the accounting cutover must close in its own sub-ledger++**Context:** Migration Clearing's Ignore (2026-10-13): an invoice another system already settled is left out of the opening journal.++**Problem:** Dropping an item from the opening journal alone leaves its document open. The AR/AP readers fall back to the invoice total when no control line exists, so the invoice stays in aging, the tie-out shows a permanent variance, and a later payment is refused ("Target is missing its original control account"). And an invoice Carbon itself settles on or after the cutover posts a payment journal that credits the control account, which then has no opening line to credit.++**Rule:** Leave an item out only when the sub-ledger can say it is closed: an invoice is marked Paid the day before the cutover by the enable. Refuse it when Carbon settles it on or after the cutover (`settledFromCutoverIds`). Any other item type (memo, payment, WIP, lease, inventory, fixed asset) has no such state and stays in the opening journal.++**Applies to:** `packages/database/src/accounting-cutover/trial-balance.ts`, `packages/server-functions/src/activate-accounting/`.diff --git a/.ai/specs/implemented/2026-10-08-accounting-cutover.md b/.ai/specs/implemented/2026-10-08-accounting-cutover.mdindex 9bda95b441..f6b9867faf 100644--- a/.ai/specs/implemented/2026-10-08-accounting-cutover.md+++ b/.ai/specs/implemented/2026-10-08-accounting-cutover.md@@ -315,7 +315,7 @@ Tier 01 of the dataset seed writes the cutover on every apply: the first day of| # | Decision | Choice | Rationale ||---|---|---|---|-| 1 | Multi-tenancy | No new tables. New columns on `companySettings` (PK = company id) and `accountDefault`. Wizard state lives in `itemCost`, `fixedAsset` and the Draft opening journal. | Each existing table is already company-scoped. A staging table would copy data that has a home. |+| 1 | Multi-tenancy | No new tables. New columns on `companySettings` (PK = company id) and `accountDefault`. Wizard state lives in `itemCost`, `fixedAsset` and the Draft opening journal. Amended 2026-10-13: `accountingCutoverIgnoredInvoice` holds the invoices ignored on Migration Clearing (settled in the prior system); the enable marks them Paid the day before the cutover. | Each existing table is already company-scoped. A staging table would copy data that has a home. The ignore list has no home until the enable writes it onto the invoice. || 2 | Service shape | The reads live in `@carbon/database/accounting-cutover-reads`, one module per wizard step under `packages/database/src/accounting-cutover/`: `getActivationReadiness`, `getCutoverInventory`, `getCutoverFixedAssets`, `getCutoverOpenItems`, `getMigrationClearing`. Each takes a Kysely handle or a transaction and returns its value. The 2 wizard writes before the enable are `saveOpeningTrialBalance` and `updateCutoverAccumulatedDepreciation`. The enable is the `activate-accounting` server function. | The wizard loaders and the enable transaction run the same reads. So the enable checks exactly what the wizard showed, under its lock. || 3 | RLS coverage | No new tables. Users cannot promote: journal UPDATE RLS admits Draft and Posted only. The server function runs as the service connection. | Promotion must not be reachable from a client. || 4 | Permission scoping | Wizard loader `view: "accounting"`. Actions `update: "accounting"`. Activate also needs the typed company name. | The July spec precedent. A one-way event needs friction, not a new role. |diff --git a/.claude/rules/xero-api-contact-structure.md b/.claude/rules/xero-api-contact-structure.mdindex 5341652f45..bf2901b626 100644--- a/.claude/rules/xero-api-contact-structure.md+++ b/.claude/rules/xero-api-contact-structure.md@@ -113,7 +113,10 @@ token once and retries. OAuth scopes (`packages/ee/src/xero/config.tsx`) — **g(Xero retired the broad `accounting.transactions` scope for apps created after2026-03-02; granular also works on older apps): `offline_access`,`accounting.contacts`, `accounting.settings`, `accounting.invoices`,-`accounting.payments`, `accounting.banktransactions`, `accounting.manualjournals`.+`accounting.payments`, `accounting.banktransactions`, `accounting.manualjournals`,+`accounting.reports.trialbalance.read` (the accounting wizard's trial balance pull,+`XeroProvider.getTrialBalance`; a tenant connected before it answers 401/403 and is+told to reconnect).Contact endpoints used:- `GET /Contacts/{id}`, `GET /Contacts?IDs=a,b,c` — fetch.diff --git a/apps/erp/app/modules/accounting/AGENTS.md b/apps/erp/app/modules/accounting/AGENTS.mdindex 9da892903c..b9090fd1bf 100644--- a/apps/erp/app/modules/accounting/AGENTS.md+++ b/apps/erp/app/modules/accounting/AGENTS.md@@ -16,7 +16,7 @@ The **Executive P&L** (`executive-pnl.tsx`) shares the income statement's loader- **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 `packages/server-functions/AGENTS.md` → Journals and the accounting cutover.- **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.server.ts`); and `assertAccountingCutover` (`packages/server-functions/src/lib/require-accounting-cutover.ts`, the same read) in the `propose-revenue-recognition-run` and `recalculate-revenue-recognition-run` server functions.-- **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.server.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`; intents `save-tb` (the editor) and `import-tb` (CSV `accountNumber, debit, credit`, saves nothing when a row has an error). 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 `activation.enable.tsx` (the summary and the typed company name; it invokes 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 `packages/server-functions/AGENTS.md` → Legacy documents). 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.+- **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.server.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: `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). 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 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 `packages/server-functions/AGENTS.md` → Legacy documents). 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 "<description> (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 `packages/server-functions/AGENTS.md`.- **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`.diff --git a/apps/erp/app/modules/accounting/accounting.models.ts b/apps/erp/app/modules/accounting/accounting.models.tsindex 2b4c4ebff5..521e02daa8 100644--- a/apps/erp/app/modules/accounting/accounting.models.ts+++ b/apps/erp/app/modules/accounting/accounting.models.ts@@ -1179,6 +1179,19 @@ export const openingTrialBalanceImportValidator = z.object({csv: z.string().min(1, { message: "The CSV file is empty" })});+/** Ignore an invoice on Migration Clearing, or stop ignoring it. */+export const cutoverIgnoredInvoiceValidator = z.object({+ cutoverDate: cutoverDateField,+ invoiceId: z.string().min(1, { message: "Invoice is required" }),+ ignored: z.enum(["true", "false"]).transform((value) => value === "true")+});++/** A trial balance step action that needs only the cutover date: apply+ * Carbon's totals, or pull the provider's trial balance. */+export const cutoverStepValidator = z.object({+ cutoverDate: cutoverDateField+});+/** The enable: the cutover date and the company name typed to confirm. */export const activateAccountingValidator = z.object({cutoverDate: cutoverDateField,diff --git a/apps/erp/app/modules/accounting/ui/Activation/ApplyCarbonButton.tsx b/apps/erp/app/modules/accounting/ui/Activation/ApplyCarbonButton.tsxnew file mode 100644index 0000000000..185d4ea3bb--- /dev/null+++ b/apps/erp/app/modules/accounting/ui/Activation/ApplyCarbonButton.tsx@@ -0,0 +1,44 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { useAction } from "@carbon/query";+import { Button } from "@carbon/react";+import { Trans } from "@lingui/react/macro";+import { LuArrowLeftToLine } from "react-icons/lu";+import { usePermissions } from "~/hooks";+import { activationStepPath } from "./ActivationSteps";++/**+ * Sets every control account on the trial balance to Carbon's opening total.+ * What is left on Migration Clearing then shows as the trial balance being+ * out of balance, to put on a non-control account.+ */+export default function ApplyCarbonButton({+ cutoverDate,+ hasDifference+}: {+ cutoverDate: string;+ hasDifference: boolean;+}) {+ const permissions = usePermissions();+ const apply = useAction();+ return (+ <apply.Form+ method="post"+ action={activationStepPath("trial-balance", cutoverDate)}+ >+ <input type="hidden" name="intent" value="apply-carbon" />+ <input type="hidden" name="cutoverDate" value={cutoverDate} />+ <Button+ type="submit"+ variant="secondary"+ leftIcon={<LuArrowLeftToLine />}+ isDisabled={!permissions.can("update", "accounting") || !hasDifference}+ isLoading={apply.isPending}+ >+ <Trans>Apply to Trial Balance</Trans>+ </Button>+ </apply.Form>+ );+}diff --git a/apps/erp/app/modules/accounting/ui/Activation/MigrationClearingTable.tsx b/apps/erp/app/modules/accounting/ui/Activation/MigrationClearingTable.tsxindex db7c36d143..125bb0aec2 100644--- a/apps/erp/app/modules/accounting/ui/Activation/MigrationClearingTable.tsx+++ b/apps/erp/app/modules/accounting/ui/Activation/MigrationClearingTable.tsx@@ -4,94 +4,344 @@import {isMigrationClearingZero,- type MigrationClearingRow+ type JournalLineDocumentType,+ type MigrationClearingRow,+ type OpenItemType} from "@carbon/database/accounting-cutover";-import { cn, Table, Tbody, Td, Tfoot, Th, Thead, Tr } from "@carbon/react";-import { Trans } from "@lingui/react/macro";-import { useCurrencyFormatter } from "~/hooks";-import { accountLabel, useAccountsById } from "./ActivationSteps";+import { useAction } from "@carbon/query";+import {+ Button,+ cn,+ IconButton,+ Table,+ Tbody,+ Td,+ Tfoot,+ Th,+ Thead,+ Tr+} from "@carbon/react";+import { Trans, useLingui } from "@lingui/react/macro";+import { useState } from "react";+import { LuChevronDown, LuChevronRight } from "react-icons/lu";+import { Link } from "react-router";+import { useCurrencyFormatter, usePermissions } from "~/hooks";+import { path } from "~/utils/path";+import {+ accountLabel,+ activationStepPath,+ useAccountsById+} from "./ActivationSteps";++/** One item behind a control account's Carbon total. */+export type MigrationClearingItem = {+ key: string;+ accountId: string;+ openItemType: OpenItemType;+ documentType: JournalLineDocumentType | null;+ documentId: string | null;+ /** The document's readable number, or the item's description. */+ label: string;+ partyName: string | null;+ /** Debit-signed, as the table's amounts. */+ amount: number;+ /** A sales or purchase invoice Carbon does not settle after the cutover,+ * which the user may ignore. */+ ignorable: boolean;+};/*** Migration Clearing per control account: what the prior system's trial* balance says, what Carbon's open items hold, and the difference. Amounts- * are debit-signed. Every difference stays on Migration Clearing.+ * are debit-signed. Each account opens to the items behind its Carbon total;+ * an invoice another system already settled can be ignored, which takes it+ * out of Carbon's total. Every difference stays on Migration Clearing.*/export default function MigrationClearingTable({+ cutoverDate,rows,- total+ total,+ items,+ ignoredItems}: {+ cutoverDate: string;rows: MigrationClearingRow[];total: number;+ items: MigrationClearingItem[];+ ignoredItems: MigrationClearingItem[];}) {+ const { t } = useLingui();const formatter = useCurrencyFormatter();const accountsById = useAccountsById();+ const permissions = usePermissions();+ const canEdit = permissions.can("update", "accounting");+ const action = activationStepPath("trial-balance", cutoverDate);+ const ignore = useAction();+ const [expanded, setExpanded] = useState<Set<string>>(new Set());+// A control account with nothing on either side tells the reader nothing.const shown = rows.filter((row) => row.trialBalance !== 0 || row.carbon !== 0);+ const itemsByAccount = new Map<string, MigrationClearingItem[]>();+ for (const item of items) {+ const list = itemsByAccount.get(item.accountId) ?? [];+ list.push(item);+ itemsByAccount.set(item.accountId, list);+ }+ for (const list of itemsByAccount.values()) {+ // The largest amounts drive the difference most.+ list.sort((a, b) => Math.abs(b.amount) - Math.abs(a.amount));+ }++ const toggle = (accountId: string) =>+ setExpanded((prev) => {+ const next = new Set(prev);+ if (next.has(accountId)) next.delete(accountId);+ else next.add(accountId);+ return next;+ });++ const setIgnored = (invoiceId: string, ignored: boolean) =>+ ignore.submit(+ {+ intent: "ignore-invoice",+ cutoverDate,+ invoiceId,+ ignored: String(ignored)+ },+ { method: "post", action }+ );return (- <Table>- <Thead>- <Tr>- <Th>- <Trans>Control Account</Trans>- </Th>- <Th className="text-right">- <Trans>Trial Balance</Trans>- </Th>- <Th className="text-right">- <Trans>Carbon</Trans>- </Th>- <Th className="text-right">- <Trans>Difference</Trans>- </Th>- </Tr>- </Thead>- <Tbody>- {shown.length === 0 ? (+ <div className="flex w-full flex-col gap-8">+ <Table>+ <Thead><Tr>- <Td colSpan={4} className="text-center text-muted-foreground">- <Trans>No control account has a balance at the cutover.</Trans>- </Td>+ <Th>+ <Trans>Control Account</Trans>+ </Th>+ <Th className="text-right">+ <Trans>Trial Balance</Trans>+ </Th>+ <Th className="text-right">+ <Trans>Carbon</Trans>+ </Th>+ <Th className="text-right">+ <Trans>Difference</Trans>+ </Th></Tr>- ) : (- shown.map((row) => (- <Tr key={row.accountId}>- <Td>{accountLabel(accountsById, row.accountId)}</Td>- <Td className="text-right tabular-nums">- {formatter.format(row.trialBalance)}- </Td>- <Td className="text-right tabular-nums">- {formatter.format(row.carbon)}- </Td>- <Td- className={cn(- "text-right tabular-nums",- !isMigrationClearingZero(row.difference) && "text-destructive"- )}- >- {formatter.format(row.difference)}+ </Thead>+ <Tbody>+ {shown.length === 0 ? (+ <Tr>+ <Td colSpan={4} className="text-center text-muted-foreground">+ <Trans>No control account has a balance at the cutover.</Trans></Td></Tr>- ))- )}- </Tbody>- <Tfoot>- <Tr>- <Th colSpan={3}>- <Trans>Migration Clearing</Trans>- </Th>- <Th- className={cn(- "text-right tabular-nums",- !isMigrationClearingZero(total) && "text-destructive"- )}- >- {formatter.format(total)}- </Th>- </Tr>- </Tfoot>- </Table>+ ) : (+ shown.flatMap((row) => {+ const accountItems = itemsByAccount.get(row.accountId) ?? [];+ const isOpen = expanded.has(row.accountId);+ const label = accountLabel(accountsById, row.accountId);+ return [+ <Tr key={row.accountId}>+ <Td>+ <div className="flex items-center gap-1">+ {accountItems.length > 0 ? (+ <IconButton+ aria-label={+ isOpen+ ? t`Hide the items on ${label}`+ : t`Show the items on ${label}`+ }+ icon={isOpen ? <LuChevronDown /> : <LuChevronRight />}+ variant="ghost"+ size="sm"+ onClick={() => toggle(row.accountId)}+ />+ ) : (+ <span className="size-8" />+ )}+ <span>{label}</span>+ </div>+ </Td>+ <Td className="text-right tabular-nums">+ {formatter.format(row.trialBalance)}+ </Td>+ <Td className="text-right tabular-nums">+ {formatter.format(row.carbon)}+ </Td>+ <Td+ className={cn(+ "text-right tabular-nums",+ !isMigrationClearingZero(row.difference) &&+ "text-destructive"+ )}+ >+ {formatter.format(row.difference)}+ </Td>+ </Tr>,+ ...(isOpen+ ? accountItems.map((item) => (+ <Tr key={item.key} className="text-muted-foreground">+ <Td colSpan={2}>+ <div className="flex items-center gap-2 pl-9">+ <ItemLink item={item} cutoverDate={cutoverDate} />+ {item.partyName && <span>{item.partyName}</span>}+ </div>+ </Td>+ <Td className="text-right tabular-nums">+ {formatter.format(item.amount)}+ </Td>+ <Td className="text-right">+ {item.ignorable && item.documentId && (+ <Button+ variant="secondary"+ size="sm"+ isDisabled={!canEdit || ignore.isPending}+ onClick={() => setIgnored(item.documentId!, true)}+ >+ <Trans>Ignore</Trans>+ </Button>+ )}+ </Td>+ </Tr>+ ))+ : [])+ ];+ })+ )}+ </Tbody>+ <Tfoot>+ <Tr>+ <Th colSpan={3}>+ <Trans>Migration Clearing</Trans>+ </Th>+ <Th+ className={cn(+ "text-right tabular-nums",+ !isMigrationClearingZero(total) && "text-destructive"+ )}+ >+ {formatter.format(total)}+ </Th>+ </Tr>+ </Tfoot>+ </Table>++ {ignoredItems.length > 0 && (+ <div className="flex flex-col gap-2">+ <h3 className="text-sm font-medium">+ <Trans>Ignored</Trans>+ </h3>+ <p className="text-sm text-muted-foreground">+ <Trans>+ Settled in the system that kept the books before the cutover.+ Carbon leaves them out of its totals and marks them Paid on the+ day before the cutover when you set up accounting.+ </Trans>+ </p>+ <Table>+ <Thead>+ <Tr>+ <Th>+ <Trans>Invoice</Trans>+ </Th>+ <Th>+ <Trans>Control Account</Trans>+ </Th>+ <Th className="text-right">+ <Trans>Amount</Trans>+ </Th>+ <Th />+ </Tr>+ </Thead>+ <Tbody>+ {ignoredItems.map((item) => (+ <Tr key={item.key}>+ <Td>+ <div className="flex items-center gap-2">+ <ItemLink item={item} cutoverDate={cutoverDate} />+ {item.partyName && (+ <span className="text-muted-foreground">+ {item.partyName}+ </span>+ )}+ </div>+ </Td>+ <Td>{accountLabel(accountsById, item.accountId)}</Td>+ <Td className="text-right tabular-nums">+ {formatter.format(item.amount)}+ </Td>+ <Td className="text-right">+ {item.documentId && (+ <Button+ variant="secondary"+ size="sm"+ isDisabled={!canEdit || ignore.isPending}+ onClick={() => setIgnored(item.documentId!, false)}+ >+ <Trans>Restore</Trans>+ </Button>+ )}+ </Td>+ </Tr>+ ))}+ </Tbody>+ </Table>+ </div>+ )}+ </div>);}++/** The item's label, linked to its document or to the step it comes from. */+function ItemLink({+ item,+ cutoverDate+}: {+ item: MigrationClearingItem;+ cutoverDate: string;+}) {+ const to = itemHref(item, cutoverDate);+ return to ? (+ <Link to={to} className="text-foreground hover:underline">+ {item.label}+ </Link>+ ) : (+ <span className="text-foreground">{item.label}</span>+ );+}++function itemHref(+ item: MigrationClearingItem,+ cutoverDate: string+): string | null {+ const id = item.documentId;+ switch (item.openItemType) {+ case "Receivable":+ case "Deferred Revenue":+ if (!id) return null;+ return item.documentType === "Invoice"+ ? path.to.salesInvoice(id)+ : path.to.memo(id);+ case "Payable":+ if (!id) return null;+ return item.documentType === "Invoice"+ ? path.to.purchaseInvoice(id)+ : path.to.memo(id);+ case "Unapplied Credit":+ case "Customer Deposit":+ return id ? path.to.payment(id) : null;+ case "Work in Progress":+ return id ? path.to.job(id) : null;+ case "Inventory":+ return activationStepPath("inventory", cutoverDate);+ case "Fixed Asset Cost":+ case "Accumulated Depreciation":+ return activationStepPath("fixed-assets", cutoverDate);+ default:+ return null;+ }+}diff --git a/apps/erp/app/modules/accounting/ui/Activation/TrialBalanceEditor.tsx b/apps/erp/app/modules/accounting/ui/Activation/TrialBalanceEditor.tsxindex 8064ece257..1843f5e9a2 100644--- a/apps/erp/app/modules/accounting/ui/Activation/TrialBalanceEditor.tsx+++ b/apps/erp/app/modules/accounting/ui/Activation/TrialBalanceEditor.tsx@@ -30,7 +30,13 @@ import {import { equals, INPUT_FORMAT, INPUT_STEP, round } from "@carbon/utils";import { Trans, useLingui } from "@lingui/react/macro";import { useMemo, useRef, useState } from "react";-import { LuFileUp, LuSave, LuSearch, LuTriangleAlert } from "react-icons/lu";+import {+ LuCloudDownload,+ LuFileUp,+ LuSave,+ LuSearch,+ LuTriangleAlert+} from "react-icons/lu";import {useCurrencyDecimals,useCurrencyFormatter,@@ -41,23 +47,39 @@ import type { TrialBalanceCsvError } from "../../trial-balance-csv";import type { AccountListItem } from "../../types";import { activationStepPath, useAccountsById } from "./ActivationSteps";-type Amounts = { debit: number; credit: number };-/** What the trial balance step's action returns when an import fails. */export type TrialBalanceImportResult = { errors?: TrialBalanceCsvError[] };/**- * The prior system's trial balance as of the day before the cutover: a debit- * and a credit per posting account, entered here or imported from a CSV with- * the columns `accountNumber`, `debit` and `credit`. Saving replaces the- * Draft opening journal's lines.+ * What a pull from the accounting provider returns when some of its balances+ * have no Carbon account: the rest is saved, these are left to the user.+ * `amount` is debit-signed.+ */+export type TrialBalancePullResult = {+ unplaced?: {+ code: string | null;+ name: string;+ amount: number;+ /** Mapped to more than one Carbon account. */+ ambiguous: boolean;+ }[];+};++/**+ * The prior system's trial balance as of the day before the cutover: one+ * debit-signed balance per posting account (a credit is negative), entered+ * here or imported from a CSV with the columns `accountNumber`, `debit` and+ * `credit`. Saving replaces the Draft opening journal's lines.*/export default function TrialBalanceEditor({cutoverDate,+ providerName,lines,controlAccountIds}: {cutoverDate: string;+ /** The connected accounting integration that can provide a trial balance. */+ providerName: string | null;/** The saved trial balance. */lines: TrialBalanceLine[];/** Accounts whose opening balance Carbon posts from its open items. */@@ -75,7 +97,7 @@ export default function TrialBalanceEditor({const [search, setSearch] = useState("");// Only what the user typed since the last save. The saved lines come from// the loader, so a reload after a save shows what was stored.- const [edits, setEdits] = useState<Record<string, Partial<Amounts>>>({});+ const [edits, setEdits] = useState<Record<string, number>>({});const save = useAction({onSettled: (result) => {@@ -88,12 +110,18 @@ export default function TrialBalanceEditor({if (!result) setEdits({});}});+ const puller = useAction<TrialBalancePullResult>({+ // A pull that saved redirects, or returns what it could not place.+ onSettled: (result) => {+ if (!result || result.unplaced) setEdits({});+ }+ });const fileInput = useRef<HTMLInputElement>(null);const saved = useMemo(() => {- const byAccount = new Map<string, Amounts>();+ const byAccount = new Map<string, number>();for (const line of lines) {- byAccount.set(line.accountId, { debit: line.debit, credit: line.credit });+ byAccount.set(line.accountId, round(line.debit - line.credit));}return byAccount;}, [lines]);@@ -121,33 +149,27 @@ export default function TrialBalanceEditor({: sorted;}, [accountsById, search]);- const amountsOf = (accountId: string): Amounts => {- const stored = saved.get(accountId);- const edit = edits[accountId];- return {- debit: edit?.debit ?? stored?.debit ?? 0,- credit: edit?.credit ?? stored?.credit ?? 0- };- };+ const balanceOf = (accountId: string): number =>+ edits[accountId] ?? saved.get(accountId) ?? 0;const allAccountIds = new Set([...saved.keys(), ...Object.keys(edits)]);const entered = [...allAccountIds]- .map((accountId) => ({ accountId, ...amountsOf(accountId) }))- .filter((line) => line.debit !== 0 || line.credit !== 0);- const totalDebit = round(entered.reduce((sum, line) => sum + line.debit, 0));- const totalCredit = round(- entered.reduce((sum, line) => sum + line.credit, 0)- );- const isBalanced = equals(totalDebit, totalCredit);+ .map((accountId) => ({ accountId, balance: balanceOf(accountId) }))+ .filter((line) => line.balance !== 0);+ // The save takes a debit and a credit per account.+ const enteredLines = entered.map(({ accountId, balance }) => ({+ accountId,+ debit: balance > 0 ? balance : 0,+ credit: balance < 0 ? -balance : 0+ }));+ const total = round(entered.reduce((sum, line) => sum + line.balance, 0));+ const isBalanced = equals(total, 0);const hasEdits = Object.keys(edits).length > 0;- const setAmount = (accountId: string, side: keyof Amounts, value: number) => {+ const setBalance = (accountId: string, value: number) => {setEdits((prev) => ({...prev,- [accountId]: {- ...prev[accountId],- [side]: Number.isFinite(value) ? value : 0- }+ [accountId]: Number.isFinite(value) ? value : 0}));};@@ -167,6 +189,7 @@ export default function TrialBalanceEditor({);const step = INPUT_STEP.money(currencyDecimals);const importErrors = importer.data?.errors ?? [];+ const unplaced = puller.data?.unplaced ?? [];return (<div className="flex w-full flex-col gap-4">@@ -189,6 +212,21 @@ export default function TrialBalanceEditor({className="hidden"onChange={(e) => onFile(e.target.files?.[0])}/>+ {providerName && (+ <puller.Form method="post" action={action}>+ <input type="hidden" name="intent" value="pull-tb" />+ <input type="hidden" name="cutoverDate" value={cutoverDate} />+ <Button+ type="submit"+ variant="secondary"+ leftIcon={<LuCloudDownload />}+ isDisabled={!canEdit}+ isLoading={puller.isPending}+ >+ <Trans>Pull from {providerName}</Trans>+ </Button>+ </puller.Form>+ )}<Buttonvariant="secondary"leftIcon={<LuFileUp />}@@ -201,7 +239,11 @@ export default function TrialBalanceEditor({<save.Form method="post" action={action}><input type="hidden" name="intent" value="save-tb" /><input type="hidden" name="cutoverDate" value={cutoverDate} />- <input type="hidden" name="lines" value={JSON.stringify(entered)} />+ <input+ type="hidden"+ name="lines"+ value={JSON.stringify(enteredLines)}+ /><Buttontype="submit"leftIcon={<LuSave />}@@ -215,10 +257,19 @@ export default function TrialBalanceEditor({</div><p className="text-sm text-muted-foreground">- <Trans>- The CSV needs the columns accountNumber, debit and credit. An import- replaces the whole trial balance.- </Trans>+ {providerName ? (+ <Trans>+ Enter debits as positive and credits as negative amounts. The CSV+ needs the columns accountNumber, debit and credit. An import or a+ pull from {providerName} replaces the whole trial balance.+ </Trans>+ ) : (+ <Trans>+ Enter debits as positive and credits as negative amounts. The CSV+ needs the columns accountNumber, debit and credit. An import+ replaces the whole trial balance.+ </Trans>+ )}</p>{importErrors.length > 0 && (@@ -240,6 +291,38 @@ export default function TrialBalanceEditor({</Alert>)}+ {unplaced.length > 0 && (+ <Alert variant="warning">+ <LuTriangleAlert className="h-4 w-4" />+ <AlertTitle>+ <Trans>Some balances have no Carbon account</Trans>+ </AlertTitle>+ <AlertDescription>+ <p>+ <Trans>+ Map these accounts in the {providerName} integration settings+ and pull again, or enter their balances below.+ </Trans>+ </p>+ <ul className="list-disc pl-4">+ {unplaced.map((row, index) => (+ // Two computed provider lines can share a name and no code.+ <li key={`${index}:${row.code ?? ""}:${row.name}`}>+ {row.code ? `${row.code} ` : ""}+ {row.name}: {formatter.format(row.amount)}+ {row.ambiguous && (+ <span className="text-muted-foreground">+ {" "}+ <Trans>(mapped to more than one Carbon account)</Trans>+ </span>+ )}+ </li>+ ))}+ </ul>+ </AlertDescription>+ </Alert>+ )}+<Table><Thead><Tr>@@ -247,16 +330,13 @@ export default function TrialBalanceEditor({<Trans>Account</Trans></Th><Th className="w-48 text-right">- <Trans>Debit</Trans>- </Th>- <Th className="w-48 text-right">- <Trans>Credit</Trans>+ <Trans>Balance</Trans></Th></Tr></Thead><Tbody>{accounts.map((account) => {- const amounts = amountsOf(account.id);+ const balance = balanceOf(account.id);return (<Tr key={account.id}><Td>@@ -284,32 +364,25 @@ export default function TrialBalanceEditor({)}</div></Td>- {(["debit", "credit"] as const).map((side) => (- <Td key={side} className="text-right">- <NumberField- aria-label={- side === "debit"- ? t`Debit for ${account.name}`- : t`Credit for ${account.name}`- }- value={amounts[side]}- minValue={0}- step={step}- formatOptions={formatOptions}- isDisabled={!canEdit}- onChange={(value) => setAmount(account.id, side, value)}- >- <NumberInput- size="sm"- className={cn(- "h-7 text-right tabular-nums",- // Most accounts carry no balance; mute the zeros.- amounts[side] === 0 && "text-muted-foreground"- )}- />- </NumberField>- </Td>- ))}+ <Td className="text-right">+ <NumberField+ aria-label={t`Balance for ${account.name}`}+ value={balance}+ step={step}+ formatOptions={formatOptions}+ isDisabled={!canEdit}+ onChange={(value) => setBalance(account.id, value)}+ >+ <NumberInput+ size="sm"+ className={cn(+ "h-7 text-right tabular-nums",+ // Most accounts carry no balance; mute the zeros.+ balance === 0 && "text-muted-foreground"+ )}+ />+ </NumberField>+ </Td></Tr>);})}@@ -321,18 +394,17 @@ export default function TrialBalanceEditor({<Trans>Total</Trans>) : (<span className="text-destructive">- <Trans>- Total (out of balance by{" "}- {formatter.format(round(totalDebit - totalCredit))})- </Trans>+ <Trans>Total (out of balance)</Trans></span>)}</Th>- <Th className="text-right tabular-nums">- {formatter.format(totalDebit)}- </Th>- <Th className="text-right tabular-nums">- {formatter.format(totalCredit)}+ <Th+ className={cn(+ "text-right tabular-nums",+ !isBalanced && "text-destructive"+ )}+ >+ {formatter.format(total)}</Th></Tr></Tfoot>diff --git a/apps/erp/app/modules/accounting/ui/Activation/index.ts b/apps/erp/app/modules/accounting/ui/Activation/index.tsindex 2eb66c90da..acc85b10cd 100644--- a/apps/erp/app/modules/accounting/ui/Activation/index.ts+++ b/apps/erp/app/modules/accounting/ui/Activation/index.ts@@ -8,19 +8,26 @@ import ActivationSteps, {activationStepPath,activationSteps} from "./ActivationSteps";+import ApplyCarbonButton from "./ApplyCarbonButton";import FixedAssetDepreciationTable from "./FixedAssetDepreciationTable";import InventoryCostTable from "./InventoryCostTable";-import MigrationClearingTable from "./MigrationClearingTable";+import MigrationClearingTable, {+ type MigrationClearingItem+} from "./MigrationClearingTable";import ReadinessChecklist from "./ReadinessChecklist";import TrialBalanceEditor, {- type TrialBalanceImportResult+ type TrialBalanceImportResult,+ type TrialBalancePullResult} from "./TrialBalanceEditor";export {type ActivationStep,+ type MigrationClearingItem,type TrialBalanceImportResult,+ type TrialBalancePullResult,ActivationFooter,ActivationSteps,+ ApplyCarbonButton,activationStepPath,activationSteps,FixedAssetDepreciationTable,diff --git a/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json b/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.jsonindex 39b9e3cd4d..e997e6e248 100644--- a/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json+++ b/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json@@ -325,9 +325,9 @@{"name":"invoicing_getMemo","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"98fffe52edef","injectAuth":"companyId","permission":"invoicing:view","paginates":false},{"name":"invoicing_getMemoApplications","classification":"READ","paramCount":1,"schema":"188417093a55","response":"8b54c25de723","injectAuth":"companyId","permission":"invoicing:view","paginates":false},{"name":"invoicing_getMemos","classification":"READ","paramCount":7,"schema":"8f6810d90c81","response":"f38bef4be63d","injectAuth":"companyId","permission":"invoicing:view","paginates":true,"defaults":"always"},- {"name":"invoicing_getOpenPurchaseInvoicesForSupplier","classification":"READ","paramCount":2,"schema":"da8678ca28c2","response":"0f00d3685738","injectAuth":"companyId","permission":"invoicing:view","paginates":false},+ {"name":"invoicing_getOpenPurchaseInvoicesForSupplier","classification":"READ","paramCount":2,"schema":"da8678ca28c2","response":"a16080b3cb31","injectAuth":"companyId","permission":"invoicing:view","paginates":false},{"name":"invoicing_getOpenReimbursementsForEmployee","classification":"READ","paramCount":2,"schema":"8c83e701c013","response":"84fe5db303b4","injectAuth":"companyId","permission":"invoicing:view","paginates":false},- {"name":"invoicing_getOpenSalesInvoicesForCustomer","classification":"READ","paramCount":2,"schema":"2d555b8aaf06","response":"0f00d3685738","injectAuth":"companyId","permission":"invoicing:view","paginates":false},+ {"name":"invoicing_getOpenSalesInvoicesForCustomer","classification":"READ","paramCount":2,"schema":"2d555b8aaf06","response":"a16080b3cb31","injectAuth":"companyId","permission":"invoicing:view","paginates":false},{"name":"invoicing_getPayment","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"300aea1db7cb","injectAuth":"companyId","permission":"invoicing:view","paginates":false},{"name":"invoicing_getPaymentCurrencyConfiguration","classification":"READ","paramCount":1,"schema":"cc2bce783cc5","response":"35b15cbf37ce","injectAuth":"companyId","permission":"invoicing:view","paginates":false},{"name":"invoicing_getPayments","classification":"READ","paramCount":8,"schema":"fc068ce64697","response":"e786785f266d","injectAuth":"companyId","permission":"invoicing:view","paginates":true,"defaults":"always"},diff --git a/apps/erp/app/routes/x+/accounting+/activation.trial-balance.tsx b/apps/erp/app/routes/x+/accounting+/activation.trial-balance.tsxindex 3d33f5893a..07e6b4aa91 100644--- a/apps/erp/app/routes/x+/accounting+/activation.trial-balance.tsx+++ b/apps/erp/app/routes/x+/accounting+/activation.trial-balance.tsx@@ -5,19 +5,39 @@import { assertIsPost, error, success } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";+import type { Database } from "@carbon/database";import {+ isIgnorableOpenItem,+ isMigrationClearingZero,+ type OpenItem+} from "@carbon/database/accounting-cutover";+import {+ applyCarbonToOpeningTrialBalance,+ dayBeforeCutover,getMigrationClearing,- saveOpeningTrialBalance+ saveOpeningTrialBalance,+ setCutoverInvoiceIgnored} from "@carbon/database/accounting-cutover-reads";+import { debitSigned } from "@carbon/database/ledger";+import { getIntegrationIdsByRole, getIntegrationsByRole } from "@carbon/ee";+import {+ isTrialBalanceProvider,+ isTrialBalancePullError,+ type ProviderID,+ pullTrialBalanceFromProvider+} from "@carbon/ee/accounting";import { validator } from "@carbon/form";import { getLogger } from "@carbon/logger";import { getErrorMessage, redirect } from "@carbon/utils";import { msg } from "@lingui/core/macro";import { Trans } from "@lingui/react/macro";+import type { SupabaseClient } from "@supabase/supabase-js";import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";import { data, useLoaderData } from "react-router";import { SetupBody, SetupSection } from "~/components/Setup";import {+ cutoverIgnoredInvoiceValidator,+ cutoverStepValidator,openingTrialBalanceImportValidator,openingTrialBalanceValidator} from "~/modules/accounting";@@ -28,9 +48,12 @@ import {} from "~/modules/accounting/trial-balance-csv";import {ActivationFooter,+ ApplyCarbonButton,+ type MigrationClearingItem,MigrationClearingTable,TrialBalanceEditor,- type TrialBalanceImportResult+ type TrialBalanceImportResult,+ type TrialBalancePullResult} from "~/modules/accounting/ui/Activation";import { getDatabaseClient } from "~/services/database.server";import type { Handle } from "~/utils/handle";@@ -38,6 +61,37 @@ import { path } from "~/utils/path";const logger = getLogger("erp", "accounting/activation/trial-balance");+/**+ * The company's active accounting integration, when it can provide a trial+ * balance. One accounting integration is active at a time.+ */+async function getTrialBalanceProvider(+ client: SupabaseClient<Database>,+ companyId: string+): Promise<{ id: ProviderID; name: string } | null> {+ const integrations = await client+ .from("companyIntegration")+ .select("id")+ .eq("companyId", companyId)+ .eq("active", true)+ .in("id", getIntegrationIdsByRole("accounting"));+ if (integrations.error) {+ logger.error("Failed to read the accounting integration", {+ companyId,+ error: integrations.error+ });+ return null;+ }+ const id = integrations.data+ ?.map((row) => row.id)+ .find(isTrialBalanceProvider);+ if (!id) return null;+ const config = getIntegrationsByRole("accounting").find(+ (integration) => integration.id === id+ );+ return { id, name: config?.name ?? id };+}+export const handle: Handle = {breadcrumb: msg`Trial Balance`,to: path.to.accountingActivationStep("trial-balance")@@ -52,19 +106,58 @@ export async function loader({ request }: LoaderFunctionArgs) {companyId,request);- const clearing = await getMigrationClearing(getDatabaseClient(), {- companyId,- cutoverDate- });+ const [clearing, provider] = await Promise.all([+ getMigrationClearing(getDatabaseClient(), { companyId, cutoverDate }),+ getTrialBalanceProvider(client, companyId)+ ]);return {cutoverDate,+ provider,trialBalance: clearing.trialBalance,controlAccountIds: [...clearing.controlAccountIds],- clearing: { rows: clearing.rows, total: clearing.total }+ clearing: {+ rows: clearing.rows,+ total: clearing.total,+ items: clearing.items.map((item) =>+ toClearingItem(item, clearing.settledFromCutoverIds)+ ),+ ignoredItems: clearing.ignoredItems.map((item) =>+ toClearingItem(item, clearing.settledFromCutoverIds)+ )+ }+ };+}++/** What Migration Clearing shows of an open item. */+function toClearingItem(+ item: OpenItem,+ settledFromCutoverIds: ReadonlySet<string>+): MigrationClearingItem {+ return {+ key: [+ item.openItemType,+ item.accountId,+ item.documentType,+ item.documentId,+ item.documentLineReference+ ].join("|"),+ accountId: item.accountId,+ openItemType: item.openItemType,+ documentType: item.documentType,+ documentId: item.documentId,+ label: item.reference ?? item.description,+ partyName: item.partyName ?? null,+ amount: debitSigned(item.accountClass, item.amount),+ ignorable: isIgnorableOpenItem(item, settledFromCutoverIds)};}-/** `save-tb` saves the editor's lines; `import-tb` replaces them with a CSV. */+/**+ * `save-tb` saves the editor's lines; `import-tb` replaces them with a CSV;+ * `pull-tb` replaces them with the connected accounting provider's;+ * `ignore-invoice` ignores an invoice on Migration Clearing or restores it;+ * `apply-carbon` sets the control accounts to Carbon's opening totals.+ */export async function action({ request }: ActionFunctionArgs) {assertIsPost(request);const { client, companyId, companyGroupId, userId } =@@ -119,6 +212,160 @@ export async function action({ request }: ActionFunctionArgs) {);}+ if (intent === "pull-tb") {+ const validation = await validator(cutoverStepValidator).validate(formData);+ if (validation.error) {+ return data<TrialBalancePullResult>(+ {},+ await flash(request, error(validation.error, "Invalid cutover date"))+ );+ }+ const provider = await getTrialBalanceProvider(client, companyId);+ if (!provider) {+ return data<TrialBalancePullResult>(+ {},+ await flash(+ request,+ error(null, "No connected accounting integration has a trial balance")+ )+ );+ }+ const { cutoverDate } = validation.data;+ try {+ const pulled = await pullTrialBalanceFromProvider(client, db, {+ companyId,+ providerId: provider.id,+ asOfDate: dayBeforeCutover(cutoverDate)+ });+ await saveOpeningTrialBalance(db, {+ companyId,+ userId,+ cutoverDate,+ lines: pulled.lines+ });+ const unplaced = [+ ...pulled.unmapped.map((row) => ({ ...row, ambiguous: false })),+ ...pulled.ambiguous.map((row) => ({ ...row, ambiguous: true }))+ ].map(({ code, name, amount, ambiguous }) => ({+ code,+ name,+ amount,+ ambiguous+ }));+ if (unplaced.length > 0) {+ // Saved, but some of the provider's balances have no Carbon account+ // yet: stay on the page so the editor can list them.+ return data<TrialBalancePullResult>(+ { unplaced },+ await flash(+ request,+ success(`Trial balance pulled from ${provider.name}`)+ )+ );+ }+ } catch (err) {+ logger.error("Failed to pull the trial balance", {+ companyId,+ provider: provider.id,+ error: err+ });+ return data<TrialBalancePullResult>(+ {},+ await flash(+ request,+ error(+ err,+ isTrialBalancePullError(err)+ ? err.message+ : getErrorMessage(err, "Failed to pull the trial balance")+ )+ )+ );+ }+ throw redirect(+ backToStep,+ await flash(+ request,+ success(`Trial balance pulled from ${provider.name}`)+ )+ );+ }++ if (intent === "ignore-invoice") {+ const validation = await validator(cutoverIgnoredInvoiceValidator).validate(+ formData+ );+ if (validation.error) {+ return data(+ {},+ await flash(request, error(validation.error, "Invalid invoice"))+ );+ }+ try {+ await setCutoverInvoiceIgnored(db, {+ companyId,+ userId,+ invoiceId: validation.data.invoiceId,+ ignored: validation.data.ignored+ });+ } catch (err) {+ logger.error("Failed to ignore the invoice", {+ companyId,+ invoiceId: validation.data.invoiceId,+ error: err+ });+ return data(+ {},+ await flash(+ request,+ error(err, getErrorMessage(err, "Failed to ignore the invoice"))+ )+ );+ }+ throw redirect(+ backToStep,+ await flash(+ request,+ success(+ validation.data.ignored ? "Invoice ignored" : "Invoice restored"+ )+ )+ );+ }++ if (intent === "apply-carbon") {+ const validation = await validator(cutoverStepValidator).validate(formData);+ if (validation.error) {+ return data(+ {},+ await flash(request, error(validation.error, "Invalid cutover date"))+ );+ }+ try {+ await applyCarbonToOpeningTrialBalance(db, {+ companyId,+ userId,+ cutoverDate: validation.data.cutoverDate+ });+ } catch (err) {+ logger.error("Failed to apply Carbon's totals to the trial balance", {+ companyId,+ error: err+ });+ return data(+ {},+ await flash(+ request,+ error(err, getErrorMessage(err, "Failed to update the trial balance"))+ )+ );+ }+ throw redirect(+ backToStep,+ await flash(request, success("Trial balance updated"))+ );+ }+if (intent === "import-tb") {const validation = await validator(openingTrialBalanceImportValidator@@ -211,7 +458,7 @@ export async function action({ request }: ActionFunctionArgs) {/** Step 4: the prior system's trial balance, and Migration Clearing. */export default function AccountingActivationTrialBalanceRoute() {- const { cutoverDate, trialBalance, controlAccountIds, clearing } =+ const { cutoverDate, provider, trialBalance, controlAccountIds, clearing } =useLoaderData<typeof loader>();return (@@ -227,7 +474,11 @@ export default function AccountingActivationTrialBalanceRoute() {}><TrialBalanceEditor+ // A new saved trial balance (a save, import, pull or apply)+ // drops what was typed over the old one.+ key={trialBalanceKey(trialBalance)}cutoverDate={cutoverDate}+ providerName={provider?.name ?? null}lines={trialBalance}controlAccountIds={controlAccountIds}/>@@ -239,14 +490,39 @@ export default function AccountingActivationTrialBalanceRoute() {On a control account, Carbon opens the balance from its own openitems, inventory and fixed assets. The trial balance must agree:every difference stays on Migration Clearing, which must total- zero.+ zero. Open an account to see its items, and ignore an invoice the+ prior system already settled.</Trans>}+ actions={+ <ApplyCarbonButton+ cutoverDate={cutoverDate}+ hasDifference={clearing.rows.some(+ (row) => !isMigrationClearingZero(row.difference)+ )}+ />+ }>- <MigrationClearingTable rows={clearing.rows} total={clearing.total} />+ <MigrationClearingTable+ cutoverDate={cutoverDate}+ rows={clearing.rows}+ total={clearing.total}+ items={clearing.items}+ ignoredItems={clearing.ignoredItems}+ /></SetupSection></SetupBody><ActivationFooter step="trial-balance" cutoverDate={cutoverDate} /></>);}++/** Identifies a saved trial balance, so the editor remounts when it changes. */+function trialBalanceKey(+ lines: { accountId: string; debit: number; credit: number }[]+) {+ return lines+ .map((line) => `${line.accountId}:${line.debit}:${line.credit}`)+ .sort()+ .join("|");+}diff --git a/packages/database/AGENTS.md b/packages/database/AGENTS.mdindex 59a50b04c6..5841ddd3e8 100644--- a/packages/database/AGENTS.md+++ b/packages/database/AGENTS.md@@ -92,8 +92,8 @@ pnpm --filter @carbon/database authz migration <name> # ship unshipped rules/h| `./accounting-cutover-dates` | `isBeforeCutover(postingDate, cutoverDate)` — the date rule of the pre-cutover voids; false when the company has no cutover || `./cost-relief` | The one definition of FIFO / LIFO cost relief, pure: `isCostLayer` / `isCostRelief` (Kysely filters for the `costLedger` rows that open or relieve a layer; a job return is not a layer), `orderLayersForConsumption` (serial units first), `relieveLayers` (one relief) and `replayReliefs` (a sequence of layers and reliefs). Used by `calculateCOGS`, the enable's re-cost (`recostOutbound`), the cutover inventory and the legacy movement costs || `./payment-processor-fee` | Server-only. `readPaymentProcessorFees` — the processor fee a payment withheld, read from its `stripe-connect` `externalIntegrationMapping` row, so a payment journal built again (a pre-cutover void, a legacy payment) books the fee the posting booked. Also `countedProcessorFee`, `processorFeeAccount`, `MISSING_PROCESSOR_FEE_ACCOUNT_ERROR` |-| `./accounting-cutover-reads` | Server-only. The accounting cutover's reads over Kysely (`getActivationReadiness`, `getCutoverOpenItems`, `getCutoverInventory`, `getCutoverFixedAssets`, `getMigrationClearing`, `getCutoverOpeningInputs`, `getLegacyDocumentCounts`, `hasLegacyDocuments` — one statement of `EXISTS` tests over the same detection, for a yes/no) and its two pre-enable writes (`saveOpeningTrialBalance`, `updateCutoverAccumulatedDepreciation`, which refuse after the cutover by reading it FOR SHARE). Each takes a `Kysely` or a `Transaction` first, so the wizard loaders and the enable transaction run the same queries. The file is only the public entry: the reads live in `src/accounting-cutover/` (`shared.ts` — the company, its defaults and `ACCOUNT_DEFAULT_COLUMNS`, the explicit list readiness requires, checked against the table at compile time; `readiness.ts`, `open-items.ts`, `inventory.ts`, `fixed-assets.ts`, `trial-balance.ts`, `legacy-counts.ts`, and `lease-payments.ts` — the payments a lease's schedule and its invoices disagree on at the cutover, which move the opening lease liability and net investment) |-| `./accounting-cutover` | Client-safe. The pure planner (`buildOpeningJournalLines` — takes the Migration Clearing account with its class, refuses one that is not Equity and refuses unbalanced lines — `migrationClearingByAccount`, `planInventoryReset`, `unitCostAtCutover`, `recostOutbound`) and the values the ERP and the enable must agree on: `MIGRATION_CLEARING_TOLERANCE` / `isMigrationClearingZero`, `MIGRATION_CLEARING_ACCOUNT_CLASS`, `ACTIVATION_CUTOVER_PARAM`, `dayBeforeCutover` |+| `./accounting-cutover-reads` | Server-only. The accounting cutover's reads over Kysely (`getActivationReadiness`, `getCutoverOpenItems`, `getCutoverInventory`, `getCutoverFixedAssets`, `getMigrationClearing`, `getCutoverOpeningInputs`, `getLegacyDocumentCounts`, `hasLegacyDocuments` — one statement of `EXISTS` tests over the same detection, for a yes/no) and its pre-enable writes (`saveOpeningTrialBalance`, `applyCarbonToOpeningTrialBalance`, `setCutoverInvoiceIgnored` — the `accountingCutoverIgnoredInvoice` rows `getCutoverOpeningInputs` leaves out of `items` and returns as `ignoredItems`, except an invoice in `settledFromCutoverIds` (settled in Carbon on or after the cutover), which stays open — and `updateCutoverAccumulatedDepreciation`, which refuse after the cutover by reading it FOR SHARE). Each takes a `Kysely` or a `Transaction` first, so the wizard loaders and the enable transaction run the same queries. The file is only the public entry: the reads live in `src/accounting-cutover/` (`shared.ts` — the company, its defaults and `ACCOUNT_DEFAULT_COLUMNS`, the explicit list readiness requires, checked against the table at compile time; `readiness.ts`, `open-items.ts`, `inventory.ts`, `fixed-assets.ts`, `trial-balance.ts`, `legacy-counts.ts`, and `lease-payments.ts` — the payments a lease's schedule and its invoices disagree on at the cutover, which move the opening lease liability and net investment) |+| `./accounting-cutover` | Client-safe. The pure planner (`buildOpeningJournalLines` — takes the Migration Clearing account with its class, refuses one that is not Equity and refuses unbalanced lines — `migrationClearingByAccount`, `isIgnorableOpenItem`, `applyCarbonToTrialBalance`, `planInventoryReset`, `unitCostAtCutover`, `recostOutbound`) and the values the ERP and the enable must agree on: `MIGRATION_CLEARING_TOLERANCE` / `isMigrationClearingZero`, `MIGRATION_CLEARING_ACCOUNT_CLASS`, `ACTIVATION_CUTOVER_PARAM`, `dayBeforeCutover` || `./legacy-documents` | Server-only. The one detection of legacy documents (`.ai/specs/implemented/2026-10-08-accounting-cutover.md` section 5a): posted, dated on or after the cutover, with no journal. Each function (`legacySalesInvoices`, `legacyPayments`, `legacyShipments`, `legacyAdjustmentCostRows`, `legacyJobMovements`, `legacyDepreciationRunLines`, …) returns a Kysely query, not rows: the `activate-accounting` server function executes it, and `getLegacyDocumentCounts` (`./accounting-cutover-reads`) counts the same rows for the wizard. Also `LEGACY_DOCUMENT_FAMILIES` (the families in the order the enable writes them), `LegacyDocumentCounts`, `assetsLeavingWithoutJournal` and `REBUILT_DISPOSAL_METHOD` || `./deposit-scope` | `loadSalesInvoiceDocumentIds` (the rental agreements / sales orders each sales invoice bills, one query) and `loadDepositScope` (a deposit payment's document + readable id) — the reads behind "a customer deposit funds only its own document", shared by `replaceInvoiceSettlements` and `post-payment` || `./sequence` | `getNextSequences` (`count` numbers in one statement; `getNextSequence` is its count-of-one) / `getNextRevisionSequence` / `getNextSerialNumbers` — the one allocator for document and serial numbers (date tokens in the company timezone) |diff --git a/packages/database/src/accounting-cutover-reads.ts b/packages/database/src/accounting-cutover-reads.tsindex 47f1306cce..dac56e7b13 100644--- a/packages/database/src/accounting-cutover-reads.ts+++ b/packages/database/src/accounting-cutover-reads.ts@@ -51,11 +51,13 @@ export {type CutoverDb} from "./accounting-cutover/shared";export {+ applyCarbonToOpeningTrialBalance,type CutoverOpeningInputs,getCutoverOpeningInputs,getMigrationClearing,getOpeningTrialBalance,- saveOpeningTrialBalance+ saveOpeningTrialBalance,+ setCutoverInvoiceIgnored} from "./accounting-cutover/trial-balance";export {type LegacyDocumentCounts,diff --git a/packages/database/src/accounting-cutover.test.ts b/packages/database/src/accounting-cutover.test.tsindex 37565df652..cb7f4a609b 100644--- a/packages/database/src/accounting-cutover.test.ts+++ b/packages/database/src/accounting-cutover.test.ts@@ -4,8 +4,10 @@import { describe, expect, it } from "vitest";import {+ applyCarbonToTrialBalance,buildOpeningJournalLines,dayBeforeCutover,+ isIgnorableOpenItem,isMigrationClearingZero,MIGRATION_CLEARING_DESCRIPTION,type MigrationClearingAccount,@@ -339,6 +341,101 @@ describe("buildOpeningJournalLines", () => {});});+describe("isIgnorableOpenItem", () => {+ const none = new Set<string>();++ it("lets a receivable or payable invoice be ignored", () => {+ expect(isIgnorableOpenItem(receivable("inv-1", 100), none)).toBe(true);+ expect(+ isIgnorableOpenItem(+ {+ ...receivable("pinv-1", 100),+ openItemType: "Payable",+ accountId: AP,+ accountClass: "Liability"+ },+ none+ )+ ).toBe(true);+ });++ it("keeps a memo, and an invoice's deferred revenue, in the opening journal", () => {+ expect(+ isIgnorableOpenItem(+ { ...receivable("memo-1", 100), documentType: "Memo" },+ none+ )+ ).toBe(false);+ expect(+ isIgnorableOpenItem(+ { ...receivable("inv-1", 100), openItemType: "Deferred Revenue" },+ none+ )+ ).toBe(false);+ });++ it("keeps an invoice Carbon settles on or after the cutover", () => {+ expect(+ isIgnorableOpenItem(receivable("inv-1", 100), new Set(["inv-1"]))+ ).toBe(false);+ });+});++describe("applyCarbonToTrialBalance", () => {+ it("sets each control account to Carbon's total and keeps every other row", () => {+ const items = [receivable("inv-1", 100), receivable("inv-2", 20)];+ const trialBalance: TrialBalanceLine[] = [+ { accountId: AR, accountClass: "Asset", debit: 105, credit: 0 },+ { accountId: CASH, accountClass: "Asset", debit: 50, credit: 0 },+ { accountId: EQUITY, accountClass: "Equity", debit: 0, credit: 155 }+ ];+ const { rows } = migrationClearingByAccount(items, trialBalance, controls);++ const applied = applyCarbonToTrialBalance(trialBalance, rows, controls);++ expect(applied).toEqual([+ { accountId: CASH, debit: 50, credit: 0 },+ { accountId: EQUITY, debit: 0, credit: 155 },+ { accountId: AR, debit: 120, credit: 0 }+ ]);+ const after = migrationClearingByAccount(+ items,+ applied.map((line) => ({+ ...line,+ accountClass: classOf[line.accountId] ?? "Asset"+ })),+ controls+ );+ expect(after.rows.every((row) => row.difference === 0)).toBe(true);+ // The total only moves when the non-control rows change.+ expect(after.total).toBe(+ migrationClearingByAccount(items, trialBalance, controls).total+ );+ });++ it("writes a credit-natured control account as a credit, and drops one Carbon has nothing on", () => {+ const payables = new Set([AP, AR]);+ const payable: OpenItem = {+ ...receivable("pinv-1", 300),+ openItemType: "Payable",+ accountId: AP,+ accountClass: "Liability"+ };+ const trialBalance: TrialBalanceLine[] = [+ { accountId: AR, accountClass: "Asset", debit: 40, credit: 0 }+ ];+ const { rows } = migrationClearingByAccount(+ [payable],+ trialBalance,+ payables+ );++ expect(applyCarbonToTrialBalance(trialBalance, rows, payables)).toEqual([+ { accountId: AP, debit: 0, credit: 300 }+ ]);+ });+});+describe("planInventoryReset", () => {it("refuses stock with no unit cost", () => {expect(() =>diff --git a/packages/database/src/accounting-cutover.ts b/packages/database/src/accounting-cutover.tsindex 3b2b3e4e8a..c42ff36c1e 100644--- a/packages/database/src/accounting-cutover.ts+++ b/packages/database/src/accounting-cutover.ts@@ -91,6 +91,12 @@ export type OpenItem = {documentId: string | null;documentLineReference: string | null;description: string;+ /**+ * What the wizard shows for the item: the document's readable number and+ * its customer or supplier. Never written to the opening journal.+ */+ reference?: string | null;+ partyName?: string | null;/** The original line's quantity, for a reader that costs by quantity. */quantity?: number | null;/**@@ -332,6 +338,55 @@ export function migrationClearingByAccount(return { rows, total: total === 0 ? 0 : total };}+/**+ * An open item the user may ignore on Migration Clearing: a sales or purchase+ * invoice. Before the cutover another system kept the books, so an invoice+ * open in Carbon may already be settled there. The enable marks an ignored+ * invoice Paid as of the day before the cutover, which every receivables and+ * payables reader already treats as closed. Any other item has no such state:+ * leaving it out of the opening journal would misstate what reads it later.+ *+ * Not an invoice Carbon itself settles on or after the cutover+ * (`settledFromCutoverIds`): that payment's journal credits the control+ * account, which with no opening line would leave it short by the payment.+ */+export function isIgnorableOpenItem(+ item: OpenItem,+ settledFromCutoverIds: ReadonlySet<string>+): boolean {+ return (+ (item.openItemType === "Receivable" || item.openItemType === "Payable") &&+ item.documentType === "Invoice" &&+ item.documentId !== null &&+ !settledFromCutoverIds.has(item.documentId)+ );+}++/**+ * The trial balance with every control account set to Carbon's opening total+ * for it, debit-signed as `migrationClearingByAccount` reports it. Every other+ * row is kept. Each control account's difference becomes zero; the Migration+ * Clearing total does not move, and shows up instead as the trial balance+ * being out of balance, to be put on a non-control account.+ */+export function applyCarbonToTrialBalance(+ trialBalance: TrialBalanceLine[],+ rows: MigrationClearingRow[],+ controlAccountIds: ReadonlySet<string>+): { accountId: string; debit: number; credit: number }[] {+ const kept = trialBalance+ .filter((line) => !controlAccountIds.has(line.accountId))+ .map(({ accountId, debit, credit }) => ({ accountId, debit, credit }));+ const control = rows+ .filter((row) => Math.abs(row.carbon) > EPSILON)+ .map((row) => ({+ accountId: row.accountId,+ debit: row.carbon > 0 ? row.carbon : 0,+ credit: row.carbon < 0 ? -row.carbon : 0+ }));+ return [...kept, ...control];+}+/** The layer that opens an item's stock at the cutover. */export type OpeningLayer = {itemId: string;diff --git a/packages/database/src/accounting-cutover/open-items.ts b/packages/database/src/accounting-cutover/open-items.tsindex 55c73efa7a..2568e4c5f8 100644--- a/packages/database/src/accounting-cutover/open-items.ts+++ b/packages/database/src/accounting-cutover/open-items.ts@@ -69,6 +69,9 @@ export type DraftItem = {accrual?: boolean;/** How the part settled before the cutover is keyed, when not the default. */settledLine?: OpenItem["settled"];+ /** For the wizard only. */+ reference?: string | null;+ partyName?: string | null;};type OpenDocumentRow = {@@ -212,7 +215,7 @@ async function getReceivableAndPayableItems(customerIds.length? db.selectFrom("customer")- .select(["id", "intercompanyCompanyId"])+ .select(["id", "name", "intercompanyCompanyId"]).where("companyId", "=", companyId).where("id", "in", [...new Set(customerIds)]).execute()@@ -220,12 +223,15 @@ async function getReceivableAndPayableItems(supplierIds.length? db.selectFrom("supplier")- .select(["id", "intercompanyCompanyId"])+ .select(["id", "name", "intercompanyCompanyId"]).where("companyId", "=", companyId).where("id", "in", [...new Set(supplierIds)]).execute(): Promise.resolve([])]);+ const partyNames = new Map<string, string>(+ [...customers, ...suppliers].map((row) => [row.id, row.name])+ );const intercompanyCustomers = new Set(customers.filter((row) => row.intercompanyCompanyId).map((row) => row.id));@@ -309,7 +315,9 @@ async function getReceivableAndPayableItems(documentType: isInvoice ? "Invoice" : "Memo",documentId: row.documentId,documentLineReference: null,- description+ description,+ reference: row.documentNumber,+ partyName: row.partyId ? (partyNames.get(row.partyId) ?? null) : null});};for (const row of receivables.rows) build(row, true);@@ -1613,7 +1621,9 @@ export async function finishItems(description: draft.description,...(draft.quantity != null ? { quantity: draft.quantity } : {}),...(draft.accrual ? { accrual: true } : {}),- ...(draft.settledLine ? { settled: draft.settledLine } : {})+ ...(draft.settledLine ? { settled: draft.settledLine } : {}),+ ...(draft.reference ? { reference: draft.reference } : {}),+ ...(draft.partyName ? { partyName: draft.partyName } : {})});}return items;diff --git a/packages/database/src/accounting-cutover/trial-balance.ts b/packages/database/src/accounting-cutover/trial-balance.tsindex d1513124ac..2e94bbf364 100644--- a/packages/database/src/accounting-cutover/trial-balance.ts+++ b/packages/database/src/accounting-cutover/trial-balance.ts@@ -10,7 +10,9 @@import { sql } from "kysely";import { nanoid } from "nanoid";import {+ applyCarbonToTrialBalance,dayBeforeCutover,+ isIgnorableOpenItem,type MigrationClearingAccount,type MigrationClearingRow,migrationClearingByAccount,@@ -104,6 +106,14 @@ async function openingTrialBalanceFor(export type CutoverOpeningInputs = {/** Open items, inventory per account and fixed assets per class account. */items: OpenItem[];+ /**+ * Invoices open in Carbon that the user ignored on Migration Clearing. They+ * are not in `items`; the enable marks them Paid as of the day before the+ * cutover.+ */+ ignoredItems: OpenItem[];+ /** Open invoices Carbon settles on or after the cutover; never ignorable. */+ settledFromCutoverIds: Set<string>;trialBalance: TrialBalanceLine[];/** Accounts whose opening balance comes from Carbon, not the trial balance. */controlAccountIds: Set<string>;@@ -128,7 +138,7 @@ export async function getCutoverOpeningInputs(): Promise<CutoverOpeningInputs> {const context = await loadCutoverContext(db, args);const { companyId, company, defaults } = context;- const [openItems, inventory, fixedAssets, classes, trialBalance] =+ const [openItems, inventory, fixedAssets, classes, trialBalance, ignored] =await Promise.all([openItemsFor(db, context),inventoryFor(db, context),@@ -138,8 +148,22 @@ export async function getCutoverOpeningInputs(.select(["assetAccountId", "accumulatedDepreciationAccountId"]).where("companyId", "=", companyId).execute(),- openingTrialBalanceFor(db, company)+ openingTrialBalanceFor(db, company),+ getIgnoredInvoiceIds(db, companyId)]);+ const settledFromCutoverIds = await getInvoicesSettledFromCutover(+ db,+ args,+ openItems.flatMap((item) =>+ item.documentType === "Invoice" && item.documentId+ ? [item.documentId]+ : []+ )+ );+ const isIgnored = (item: OpenItem) =>+ isIgnorableOpenItem(item, settledFromCutoverIds) &&+ ignored.has(item.documentId ?? "");+ const ignoredItems = openItems.filter(isIgnored);const costByAccount = new Map<string, number>();const depreciationByAccount = new Map<string, number>();@@ -195,7 +219,7 @@ export async function getCutoverOpeningInputs()];const items = [- ...openItems,+ ...openItems.filter((item) => !isIgnored(item)),...(await finishItems(db, company.companyGroupId, drafts))];@@ -245,6 +269,8 @@ export async function getCutoverOpeningInputs(return {items,+ ignoredItems,+ settledFromCutoverIds,trialBalance: trialBalance.lines,controlAccountIds,migrationClearingAccountId,@@ -386,3 +412,165 @@ export async function saveOpeningTrialBalance(return { journalId };});}++/**+ * Of `invoiceIds`, the invoices Carbon settles on or after the cutover: a+ * payment or memo application that is not in effect the day before it (the+ * complement of `getSettlementsBeforeCutover`, Voided documents aside), or a+ * Paid status dated on or after it. Such an invoice was open at the cutover+ * by Carbon's own record, so it cannot be ignored.+ */+async function getInvoicesSettledFromCutover(+ db: CutoverDb,+ { companyId, cutoverDate }: CutoverArgs,+ invoiceIds: string[]+): Promise<Set<string>> {+ if (invoiceIds.length === 0) return new Set();+ const [settlements, paidSales, paidPurchases] = await Promise.all([+ db+ .selectFrom("invoiceSettlement as s")+ .leftJoin("payment as p", (join) =>+ join+ .onRef("p.id", "=", "s.paymentId")+ .onRef("p.companyId", "=", "s.companyId")+ )+ .leftJoin("memo as m", (join) =>+ join+ .onRef("m.id", "=", "s.memoId")+ .onRef("m.companyId", "=", "s.companyId")+ )+ .leftJoin("payment as vp", (join) =>+ join+ .onRef("vp.id", "=", "s.appliedViaPaymentId")+ .onRef("vp.companyId", "=", "s.companyId")+ )+ .select(["s.targetSalesInvoiceId", "s.targetPurchaseInvoiceId"])+ .where("s.companyId", "=", companyId)+ .where((eb) =>+ eb.or([+ eb("s.targetSalesInvoiceId", "in", invoiceIds),+ eb("s.targetPurchaseInvoiceId", "in", invoiceIds)+ ])+ )+ .where((eb) => {+ // Draft, or Posted on or after the cutover.+ const fromCutover = (table: "p" | "m" | "vp") =>+ eb.or([+ eb(`${table}.status`, "=", "Draft"),+ eb.and([+ eb(`${table}.status`, "=", "Posted"),+ eb(`${table}.postingDate`, ">=", cutoverDate)+ ])+ ]);+ return eb.or([+ eb.and([eb("s.paymentId", "is not", null), fromCutover("p")]),+ eb.and([+ eb("s.memoId", "is not", null),+ eb("m.status", "!=", "Voided"),+ eb.or([+ fromCutover("m"),+ eb.and([+ eb("s.appliedViaPaymentId", "is", null),+ eb("s.appliedDate", ">=", cutoverDate)+ ]),+ eb.and([+ eb("s.appliedViaPaymentId", "is not", null),+ fromCutover("vp")+ ])+ ])+ ])+ ]);+ })+ .execute(),+ db+ .selectFrom("salesInvoice")+ .select("id")+ .where("companyId", "=", companyId)+ .where("id", "in", invoiceIds)+ .where("status", "=", "Paid")+ .where("datePaid", ">=", cutoverDate)+ .execute(),+ db+ .selectFrom("purchaseInvoice")+ .select("id")+ .where("companyId", "=", companyId)+ .where("id", "in", invoiceIds)+ .where("status", "=", "Paid")+ .where("datePaid", ">=", cutoverDate)+ .execute()+ ]);+ return new Set([+ ...settlements.flatMap((row) =>+ [row.targetSalesInvoiceId, row.targetPurchaseInvoiceId].filter(+ (id): id is string => id !== null+ )+ ),+ ...paidSales.map((row) => row.id),+ ...paidPurchases.map((row) => row.id)+ ]);+}++/** The invoices the user ignored on Migration Clearing. */+async function getIgnoredInvoiceIds(+ db: CutoverDb,+ companyId: string+): Promise<Set<string>> {+ const rows = await db+ .selectFrom("accountingCutoverIgnoredInvoice")+ .select("invoiceId")+ .where("companyId", "=", companyId)+ .execute();+ return new Set(rows.map((row) => row.invoiceId));+}++/**+ * Ignores an invoice on Migration Clearing, or stops ignoring it. Refused+ * after the cutover: the enable has already applied the list.+ */+export async function setCutoverInvoiceIgnored(+ db: CutoverDb,+ {+ companyId,+ userId,+ invoiceId,+ ignored+ }: { companyId: string; userId: string; invoiceId: string; ignored: boolean }+): Promise<void> {+ await withTransaction(db, async (trx) => {+ await refuseAfterCutover(trx, companyId);+ if (ignored) {+ await trx+ .insertInto("accountingCutoverIgnoredInvoice")+ .values({ companyId, invoiceId, createdBy: userId })+ .onConflict((oc) => oc.columns(["companyId", "invoiceId"]).doNothing())+ .execute();+ } else {+ await trx+ .deleteFrom("accountingCutoverIgnoredInvoice")+ .where("companyId", "=", companyId)+ .where("invoiceId", "=", invoiceId)+ .execute();+ }+ });+}++/**+ * Sets every control account on the trial balance to Carbon's opening total+ * for it, keeping every other row (`applyCarbonToTrialBalance`).+ */+export async function applyCarbonToOpeningTrialBalance(+ db: CutoverDb,+ args: CutoverArgs & { userId: string }+): Promise<{ journalId: string }> {+ return withTransaction(db, async (trx) => {+ const clearing = await getMigrationClearing(trx, args);+ return saveOpeningTrialBalance(trx, {+ ...args,+ lines: applyCarbonToTrialBalance(+ clearing.trialBalance,+ clearing.rows,+ clearing.controlAccountIds+ )+ });+ });+}diff --git a/packages/database/src/authz/manifest.ts b/packages/database/src/authz/manifest.tsindex fbcbc34f6e..da4a9fe499 100644--- a/packages/database/src/authz/manifest.ts+++ b/packages/database/src/authz/manifest.ts@@ -99,6 +99,9 @@ export const manifest = {create: false,delete: false}),+ accountingCutoverIgnoredInvoice: company("accounting", {+ read: "accounting_view"+ }),accountingPeriod: company("accounting", { read: "accounting_view" }),accountingPeriodBalance: company("accounting", {read: "accounting_view",diff --git a/packages/database/src/swagger-docs-schema.ts b/packages/database/src/swagger-docs-schema.tsindex 3cfb8e04a8..eeae056501 100644--- a/packages/database/src/swagger-docs-schema.ts+++ b/packages/database/src/swagger-docs-schema.ts@@ -26805,6 +26805,159 @@ export default {tags: ["nonConformanceReceiptLine"]}},+ "/accountingCutoverIgnoredInvoice": {+ get: {+ parameters: [+ {+ $ref: "#/parameters/rowFilter.accountingCutoverIgnoredInvoice.id"+ },+ {+ $ref: "#/parameters/rowFilter.accountingCutoverIgnoredInvoice.companyId"+ },+ {+ $ref: "#/parameters/rowFilter.accountingCutoverIgnoredInvoice.invoiceId"+ },+ {+ $ref: "#/parameters/rowFilter.accountingCutoverIgnoredInvoice.createdBy"+ },+ {+ $ref: "#/parameters/rowFilter.accountingCutoverIgnoredInvoice.createdAt"+ },+ {+ $ref: "#/parameters/rowFilter.accountingCutoverIgnoredInvoice.updatedBy"+ },+ {+ $ref: "#/parameters/rowFilter.accountingCutoverIgnoredInvoice.updatedAt"+ },+ {+ $ref: "#/parameters/select"+ },+ {+ $ref: "#/parameters/order"+ },+ {+ $ref: "#/parameters/range"+ },+ {+ $ref: "#/parameters/rangeUnit"+ },+ {+ $ref: "#/parameters/offset"+ },+ {+ $ref: "#/parameters/limit"+ },+ {+ $ref: "#/parameters/preferCount"+ }+ ],+ responses: {+ "200": {+ description: "OK",+ schema: {+ items: {+ $ref: "#/definitions/accountingCutoverIgnoredInvoice"+ },+ type: "array"+ }+ },+ "206": {+ description: "Partial Content"+ }+ },+ tags: ["accountingCutoverIgnoredInvoice"]+ },+ post: {+ parameters: [+ {+ $ref: "#/parameters/body.accountingCutoverIgnoredInvoice"+ },+ {+ $ref: "#/parameters/select"+ },+ {+ $ref: "#/parameters/preferPost"+ }+ ],+ responses: {+ "201": {+ description: "Created"+ }+ },+ tags: ["accountingCutoverIgnoredInvoice"]+ },+ delete: {+ parameters: [+ {+ $ref: "#/parameters/rowFilter.accountingCutoverIgnoredInvoice.id"+ },+ {+ $ref: "#/parameters/rowFilter.accountingCutoverIgnoredInvoice.companyId"+ },+ {+ $ref: "#/parameters/rowFilter.accountingCutoverIgnoredInvoice.invoiceId"+ },+ {+ $ref: "#/parameters/rowFilter.accountingCutoverIgnoredInvoice.createdBy"+ },+ {+ $ref: "#/parameters/rowFilter.accountingCutoverIgnoredInvoice.createdAt"+ },+ {+ $ref: "#/parameters/rowFilter.accountingCutoverIgnoredInvoice.updatedBy"+ },+ {+ $ref: "#/parameters/rowFilter.accountingCutoverIgnoredInvoice.updatedAt"+ },+ {+ $ref: "#/parameters/preferReturn"+ }+ ],+ responses: {+ "204": {+ description: "No Content"+ }+ },+ tags: ["accountingCutoverIgnoredInvoice"]+ },+ patch: {+ parameters: [+ {+ $ref: "#/parameters/rowFilter.accountingCutoverIgnoredInvoice.id"+ },+ {+ $ref: "#/parameters/rowFilter.accountingCutoverIgnoredInvoice.companyId"+ },+ {+ $ref: "#/parameters/rowFilter.accountingCutoverIgnoredInvoice.invoiceId"+ },+ {+ $ref: "#/parameters/rowFilter.accountingCutoverIgnoredInvoice.createdBy"+ },+ {+ $ref: "#/parameters/rowFilter.accountingCutoverIgnoredInvoice.createdAt"+ },+ {+ $ref: "#/parameters/rowFilter.accountingCutoverIgnoredInvoice.updatedBy"+ },+ {+ $ref: "#/parameters/rowFilter.accountingCutoverIgnoredInvoice.updatedAt"+ },+ {+ $ref: "#/parameters/body.accountingCutoverIgnoredInvoice"+ },+ {+ $ref: "#/parameters/preferReturn"+ }+ ],+ responses: {+ "204": {+ description: "No Content"+ }+ },+ tags: ["accountingCutoverIgnoredInvoice"]+ }+ },"/webhookTable": {get: {parameters: [@@ -129545,6 +129698,49 @@ export default {},type: "object"},+ accountingCutoverIgnoredInvoice: {+ required: ["id", "companyId", "invoiceId", "createdBy", "createdAt"],+ properties: {+ id: {+ default: "public.id('acii'::text)",+ description: "Note:\nThis is a Primary Key.<pk/>",+ format: "text",+ type: "string"+ },+ companyId: {+ description:+ "Note:\nThis is a Primary Key.<pk/>\nThis is a Foreign Key to `company.id`.<fk table='company' column='id'/>",+ format: "text",+ type: "string"+ },+ invoiceId: {+ format: "text",+ type: "string"+ },+ createdBy: {+ description:+ "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",+ format: "text",+ type: "string"+ },+ createdAt: {+ default: "now()",+ format: "timestamp with time zone",+ type: "string"+ },+ updatedBy: {+ description:+ "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",+ format: "text",+ type: "string"+ },+ updatedAt: {+ format: "timestamp with time zone",+ type: "string"+ }+ },+ type: "object"+ },webhookTable: {required: ["table", "module", "name"],properties: {@@ -180568,6 +180764,57 @@ export default {in: "query",type: "string"},+ "body.accountingCutoverIgnoredInvoice": {+ name: "accountingCutoverIgnoredInvoice",+ description: "accountingCutoverIgnoredInvoice",+ required: false,+ in: "body",+ schema: {+ $ref: "#/definitions/accountingCutoverIgnoredInvoice"+ }+ },+ "rowFilter.accountingCutoverIgnoredInvoice.id": {+ name: "id",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.accountingCutoverIgnoredInvoice.companyId": {+ name: "companyId",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.accountingCutoverIgnoredInvoice.invoiceId": {+ name: "invoiceId",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.accountingCutoverIgnoredInvoice.createdBy": {+ name: "createdBy",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.accountingCutoverIgnoredInvoice.createdAt": {+ name: "createdAt",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.accountingCutoverIgnoredInvoice.updatedBy": {+ name: "updatedBy",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.accountingCutoverIgnoredInvoice.updatedAt": {+ name: "updatedAt",+ required: false,+ in: "query",+ type: "string"+ },"body.webhookTable": {name: "webhookTable",description: "webhookTable",diff --git a/packages/database/src/types.ts b/packages/database/src/types.tsindex cb3c73f160..17e70a332d 100644--- a/packages/database/src/types.ts+++ b/packages/database/src/types.ts@@ -1565,6 +1565,135 @@ export type Database = {}]}+ accountingCutoverIgnoredInvoice: {+ Row: {+ companyId: string+ createdAt: string+ createdBy: string+ id: string+ invoiceId: string+ updatedAt: string | null+ updatedBy: string | null+ }+ Insert: {+ companyId: string+ createdAt?: string+ createdBy: string+ id?: string+ invoiceId: string+ updatedAt?: string | null+ updatedBy?: string | null+ }+ Update: {+ companyId?: string+ createdAt?: string+ createdBy?: string+ id?: string+ invoiceId?: string+ updatedAt?: string | null+ updatedBy?: string | null+ }+ Relationships: [+ {+ foreignKeyName: "accountingCutoverIgnoredInvoice_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "companies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "accountingCutoverIgnoredInvoice_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "company"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "accountingCutoverIgnoredInvoice_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "customFieldTables"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "accountingCutoverIgnoredInvoice_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "integrations"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "accountingCutoverIgnoredInvoice_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "accountingCutoverIgnoredInvoice_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "accountingCutoverIgnoredInvoice_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "accountingCutoverIgnoredInvoice_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "accountingCutoverIgnoredInvoice_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ {+ foreignKeyName: "accountingCutoverIgnoredInvoice_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "accountingCutoverIgnoredInvoice_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "accountingCutoverIgnoredInvoice_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "accountingCutoverIgnoredInvoice_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "accountingCutoverIgnoredInvoice_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ }+ ]+ }accountingPeriod: {Row: {closedAt: string | nulldiff --git a/packages/database/supabase/migrations/20261013131847_accounting-cutover-ignored-invoice.sql b/packages/database/supabase/migrations/20261013131847_accounting-cutover-ignored-invoice.sqlnew file mode 100644index 0000000000..ec96e0bbbb--- /dev/null+++ b/packages/database/supabase/migrations/20261013131847_accounting-cutover-ignored-invoice.sql@@ -0,0 +1,35 @@+-- Invoices the accounting enable wizard leaves out of the opening journal.+--+-- Before the cutover another system kept the books, so an invoice can be open+-- in Carbon and already settled there. The user ignores it on Migration+-- Clearing: it drops out of Carbon's open items, and the enable marks it Paid+-- as of the day before the cutover, as the Xero and QuickBooks pulls do.+-- Only wizard state: the enable reads it once, and a row whose invoice is no+-- longer open at the cutover does nothing. No foreign key on "invoiceId": it+-- is a sales or a purchase invoice, and a stale row is harmless.++CREATE TABLE IF NOT EXISTS "accountingCutoverIgnoredInvoice" (+ "id" TEXT NOT NULL DEFAULT id('acii'),+ "companyId" TEXT NOT NULL,+ "invoiceId" TEXT NOT NULL,++ "createdBy" TEXT NOT NULL REFERENCES "user"("id"),+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),+ "updatedBy" TEXT REFERENCES "user"("id"),+ "updatedAt" TIMESTAMP WITH TIME ZONE,++ CONSTRAINT "accountingCutoverIgnoredInvoice_pkey" PRIMARY KEY ("id", "companyId"),+ CONSTRAINT "accountingCutoverIgnoredInvoice_companyId_invoiceId_key"+ UNIQUE ("companyId", "invoiceId"),+ CONSTRAINT "accountingCutoverIgnoredInvoice_companyId_fkey" FOREIGN KEY ("companyId")+ REFERENCES "company"("id") ON DELETE CASCADE+);++CREATE INDEX IF NOT EXISTS "accountingCutoverIgnoredInvoice_companyId_idx"+ ON "accountingCutoverIgnoredInvoice" ("companyId");+CREATE INDEX IF NOT EXISTS "accountingCutoverIgnoredInvoice_createdBy_idx"+ ON "accountingCutoverIgnoredInvoice" ("createdBy");+CREATE INDEX IF NOT EXISTS "accountingCutoverIgnoredInvoice_updatedBy_idx"+ ON "accountingCutoverIgnoredInvoice" ("updatedBy");++ALTER TABLE "accountingCutoverIgnoredInvoice" ENABLE ROW LEVEL SECURITY;diff --git a/packages/database/supabase/migrations/20261013171656_accounting-cutover-ignored-invoice-rls.sql b/packages/database/supabase/migrations/20261013171656_accounting-cutover-ignored-invoice-rls.sqlnew file mode 100644index 0000000000..18a7d12d3a--- /dev/null+++ b/packages/database/supabase/migrations/20261013171656_accounting-cutover-ignored-invoice-rls.sql@@ -0,0 +1,18 @@+-- Generated by `pnpm --filter @carbon/database authz migration` from packages/database/src/authz. Do not edit.++-- Ships these rules to databases where `authz sync` does not run after migrations yet.++-- accountingCutoverIgnoredInvoice+DO $authz$+DECLARE p record;+BEGIN+ FOR p IN SELECT policyname FROM pg_policies WHERE schemaname = 'public' AND tablename = 'accountingCutoverIgnoredInvoice' LOOP+ EXECUTE format('DROP POLICY %I ON public.%I', p.policyname, 'accountingCutoverIgnoredInvoice');+ END LOOP;+END+$authz$;+ALTER TABLE public."accountingCutoverIgnoredInvoice" ENABLE ROW LEVEL SECURITY;+CREATE POLICY "SELECT" ON "public"."accountingCutoverIgnoredInvoice" FOR SELECT USING ("companyId" = ANY ((SELECT get_companies_with_employee_permission('accounting_view'))::text[]));+CREATE POLICY "INSERT" ON "public"."accountingCutoverIgnoredInvoice" FOR INSERT WITH CHECK ("companyId" = ANY ((SELECT get_companies_with_employee_permission('accounting_create'))::text[]));+CREATE POLICY "UPDATE" ON "public"."accountingCutoverIgnoredInvoice" FOR UPDATE USING ("companyId" = ANY ((SELECT get_companies_with_employee_permission('accounting_update'))::text[]));+CREATE POLICY "DELETE" ON "public"."accountingCutoverIgnoredInvoice" FOR DELETE USING ("companyId" = ANY ((SELECT get_companies_with_employee_permission('accounting_delete'))::text[]));diff --git a/packages/ee/AGENTS.md b/packages/ee/AGENTS.mdindex 203006f562..88fe08b05e 100644--- a/packages/ee/AGENTS.md+++ b/packages/ee/AGENTS.md@@ -64,6 +64,7 @@ pnpm --filter @carbon/ee typecheck- **Truthful ledger**: a drain no-op with no remote copy closes `Skipped` via `skipOperation()` (reason in `errorMessage`), never `Completed`; `Skipped → Pending` retry is allowed- **Rillet idempotency keys are entity-scoped**: `buildRilletIdempotencyKey({companyId, operation, localId})` — the payload is deliberately NOT hashed, so a crash-retry with a drifted payload cannot double-create the remote document- **Tie-out remote reads**: `accounting/core/remote-journal.ts` `fetchRemoteJournalTotals()` — provider-agnostic debit-signed per-account journal totals for the reconciliation tie-out+- **Trial balance pull**: `accounting/core/remote-trial-balance.ts` `pullTrialBalanceFromProvider(client, db, { companyId, providerId, asOfDate })` → `{ lines, unmapped, ambiguous }` on Carbon accounts, for the accounting activation wizard. `fetchRemoteTrialBalance()` dispatches like `fetchRemoteJournalTotals` (Xero `/Reports/TrialBalance` YTD columns, QBO `/reports/TrialBalance` Debit/Credit; Rillet `supported: false`). The parsers and the pure mapper `mapRemoteTrialBalance` (mapping by external id → mapping by code → Carbon account number; several targets = ambiguous) live in `core/trial-balance.ts`. Failures throw `TrialBalancePullError` with a `reason` (`not_connected`/`unsupported`/`reconnect`/`rate_limited`/`failed`). `isTrialBalanceProvider(id)` says which providers the dispatch reads (the ERP shows the Pull button by it; `remote-trial-balance.test.ts` pins the two together). Xero needs the `accounting.reports.trialbalance.read` scope; older tokens get `reconnect`- **Dependency sync**: transaction syncers use `ensureDependencySynced()` for JIT deps (e.g. push customer before invoice)- **Master data import**: ALL THREE accounting descriptors (`src/{rillet,xero,quickbooks}/config.tsx`) declare `actions` posting to `/api/integrations/master-sync?provider=…&direction=…`, which fires `accounting-master-sync` (`@carbon/jobs`). It is the only on-demand PULL of master data — every `build*SyncConfig` still forces customer/vendor `push-to-accounting`, and the job enqueues `pull-from-accounting` ledger rows by hand. Enumeration goes through `provider.listRemoteEntityIds` + `capabilities.importableEntities` (`providerSupportsMasterDataImport` needs both), so adding a provider needs no edit to the job. `RilletCustomerSyncer`/`RilletVendorSyncer` implement `mapToLocal`/`upsertLocal` for it and extend `RilletEntitySyncer`; the pull rejections now live in `RilletPushOnlyEntitySyncer` (item + every transaction syncer). Importing exists to write the mapping row: `upsertRemote` reads `getRemoteId(localId)` first, so a Carbon sales invoice for an imported customer PUTs the original Rillet customer instead of creating a duplicate- **Permissions** (`./permissions.server`, `src/permissions.server.ts`): the licensed RBAC-authoring logic, gated to Business via the `PERMISSIONS` feature. `updatePermissions` (builds/persists the flattened `userPermission.permissions` object + audit diff + claims-cache bust), `updateEmployee`, employee-type CRUD (`insert/upsert/deleteEmployeeType`, `upsertEmployeeTypePermissions`), and the translators (`makeEmptyPermissionsFromModules`, `makeCompanyPermissionsFromClaims`, `makeCompanyPermissionsFromEmployeeType`). This is the ONLY copy of `updatePermissions` — the `@carbon/jobs` `carbon/update-permissions` (bulk-edit) task imports it here. **Server-only.** The ERP authoring UI stays `.ee.tsx` in `apps/erp` (couples to `~/components/Form`); routes stay in the app and gate with `requireFeature({ feature: "PERMISSIONS" })`. The community invite primitives (`setUserPermissions`, `makePermissionsFromEmployeeType`) deliberately stay in the app's `users.server.ts`. Console/kiosk mode is a sibling: `./console.server` — `updateConsoleSetting(client, db, companyId, enabled, userId?)` → `{ error, pin, pinError }` writes `companySettings.consoleEnabled` over `db` (a trigger refuses API-role writes) behind `requireEntitlement("PERMISSIONS")`, provisions the protected "Console Operator" employee type and a PIN for the enabling user (returned once as `pin`; `pinError` when it could not be created); `isConsoleModeEnabledForCompany(client, companyId, { consoleEnabled? })` is the runtime DEGRADE gate (flag AND entitlement; `null` when the settings read failed — never tear a live console session down on `null`); `generateConsolePin`, `setEmployeePin(db, …)`, `verifyEmployeePin(db, …)` → `{ hasPin, valid }` work on the bcrypt `employeePin` table, reachable only over the server's Kysely connection.diff --git a/packages/ee/src/accounting/core/remote-trial-balance.test.ts b/packages/ee/src/accounting/core/remote-trial-balance.test.tsnew file mode 100644index 0000000000..62b84c9c68--- /dev/null+++ b/packages/ee/src/accounting/core/remote-trial-balance.test.ts@@ -0,0 +1,188 @@+// SPDX-License-Identifier: LicenseRef-Carbon-Commercial+// Carbon Enterprise file, licensed only under the Carbon Commercial License+// (packages/ee/LICENSE). Not AGPL. Running, modifying, or copying it beyond those terms requires a commercial license.++import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { QboProvider } from "../providers/quickbooks-online";+import { RilletProvider } from "../providers/rillet";+import { XeroProvider } from "../providers/xero";+import { DEFAULT_SYNC_CONFIG } from "./models";+import { fetchRemoteTrialBalance } from "./remote-trial-balance";+import { isTrialBalanceProvider } from "./trial-balance";+import { AccountingApiError } from "./utils";++function jsonResponse(body: unknown, status = 200): Response {+ return new Response(JSON.stringify(body), {+ status,+ headers: { "Content-Type": "application/json" }+ });+}++const fetchMock = vi.fn<typeof fetch>();++beforeEach(() => {+ vi.stubGlobal("fetch", fetchMock);+});++afterEach(() => {+ vi.unstubAllGlobals();+ fetchMock.mockReset();+});++function makeXero() {+ return new XeroProvider({+ companyId: "company-1",+ clientId: "client-id",+ clientSecret: "client-secret",+ accessToken: "token",+ refreshToken: "refresh",+ tenantId: "tenant-1",+ syncConfig: DEFAULT_SYNC_CONFIG+ });+}++function makeQbo() {+ return new QboProvider({+ companyId: "company-1",+ clientId: "client-id",+ clientSecret: "client-secret",+ accessToken: "token",+ refreshToken: "refresh",+ realmId: "realm-1",+ syncConfig: DEFAULT_SYNC_CONFIG+ });+}++describe("fetchRemoteTrialBalance", () => {+ it("reads Xero's trial balance as at the date", async () => {+ fetchMock.mockResolvedValueOnce(+ jsonResponse({+ Reports: [+ {+ Rows: [+ {+ RowType: "Header",+ Cells: [+ { Value: "Account" },+ { Value: "Debit" },+ { Value: "Credit" },+ { Value: "YTD Debit" },+ { Value: "YTD Credit" }+ ]+ },+ {+ RowType: "Section",+ Title: "Assets",+ Rows: [+ {+ RowType: "Row",+ Cells: [+ {+ Value: "Bank (090)",+ Attributes: [{ Id: "account", Value: "acc-bank" }]+ },+ { Value: "" },+ { Value: "" },+ { Value: "500.00" },+ { Value: "" }+ ]+ }+ ]+ }+ ]+ }+ ]+ })+ );++ const result = await fetchRemoteTrialBalance(makeXero(), "2026-09-30");++ expect(result).toEqual({+ supported: true,+ rows: [+ { externalId: "acc-bank", code: "090", name: "Bank", debitSigned: 500 }+ ]+ });+ const [url, init] = fetchMock.mock.calls[0]!;+ expect(String(url)).toBe(+ "https://api.xero.com/api.xro/2.0/Reports/TrialBalance?date=2026-09-30"+ );+ expect(init?.method).toBe("GET");+ });++ it("throws an AccountingApiError carrying a Xero 403 (token without the report scope)", async () => {+ fetchMock.mockResolvedValueOnce(+ jsonResponse({ Title: "Forbidden", Status: 403 }, 403)+ );++ const error = await fetchRemoteTrialBalance(makeXero(), "2026-09-30").catch(+ (e: unknown) => e+ );++ expect(error).toBeInstanceOf(AccountingApiError);+ expect((error as AccountingApiError).details.statusCode).toBe(403);+ });++ it("reads QuickBooks Online's accrual trial balance ending at the date", async () => {+ fetchMock.mockResolvedValueOnce(+ jsonResponse({+ Columns: {+ Column: [+ { ColTitle: "", ColType: "Account" },+ { ColTitle: "Debit", ColType: "Money" },+ { ColTitle: "Credit", ColType: "Money" }+ ]+ },+ Rows: {+ Row: [+ {+ ColData: [+ { value: "Sales", id: "79" },+ { value: "" },+ { value: "900.00" }+ ]+ }+ ]+ }+ })+ );++ const result = await fetchRemoteTrialBalance(makeQbo(), "2026-09-30");++ expect(result).toEqual({+ supported: true,+ rows: [{ externalId: "79", code: null, name: "Sales", debitSigned: -900 }]+ });+ const url = new URL(String(fetchMock.mock.calls[0]![0]));+ expect(url.pathname).toBe("/v3/company/realm-1/reports/TrialBalance");+ expect(url.searchParams.get("end_date")).toBe("2026-09-30");+ expect(url.searchParams.get("accounting_method")).toBe("Accrual");+ expect(url.searchParams.has("minorversion")).toBe(true);+ });++ it("reports Rillet as unsupported without calling it", async () => {+ const rillet = new RilletProvider({+ companyId: "company-1",+ credentials: { type: "apiKey", apiKey: "key", environment: "production" },+ syncConfig: DEFAULT_SYNC_CONFIG+ });++ expect(await fetchRemoteTrialBalance(rillet, "2026-09-30")).toEqual({+ supported: false+ });+ expect(fetchMock).not.toHaveBeenCalled();+ });++ it("offers the pull for exactly the providers it reads", () => {+ // The wizard shows the button by `isTrialBalanceProvider`; the tests+ // above show which providers `fetchRemoteTrialBalance` reads.+ const rillet = new RilletProvider({+ companyId: "company-1",+ credentials: { type: "apiKey", apiKey: "key", environment: "production" },+ syncConfig: DEFAULT_SYNC_CONFIG+ });+ expect(isTrialBalanceProvider(makeXero().id)).toBe(true);+ expect(isTrialBalanceProvider(makeQbo().id)).toBe(true);+ expect(isTrialBalanceProvider(rillet.id)).toBe(false);+ });+});diff --git a/packages/ee/src/accounting/core/remote-trial-balance.ts b/packages/ee/src/accounting/core/remote-trial-balance.tsnew file mode 100644index 0000000000..5994f8281f--- /dev/null+++ b/packages/ee/src/accounting/core/remote-trial-balance.ts@@ -0,0 +1,193 @@+// SPDX-License-Identifier: LicenseRef-Carbon-Commercial+// Carbon Enterprise file, licensed only under the Carbon Commercial License+// (packages/ee/LICENSE). Not AGPL. Running, modifying, or copying it beyond those terms requires a commercial license.++import type { Database } from "@carbon/database";+import type { Kysely, KyselyDatabase } from "@carbon/database/client";+import { parseDate } from "@internationalized/date";+import type { SupabaseClient } from "@supabase/supabase-js";+import type { AccountingProvider } from "../providers";+import { QboProvider } from "../providers/quickbooks-online";+import { XeroProvider } from "../providers/xero";+import { getAccountMappings, getCompanyGroupId } from "./account-mapping";+import type { ProviderID } from "./models";+import { getAccountingIntegration, getProviderIntegration } from "./service";+import {+ type MappedTrialBalance,+ mapRemoteTrialBalance,+ type RemoteTrialBalance,+ TrialBalancePullError+} from "./trial-balance";+import {+ AccountingApiError,+ AccountingAuthError,+ RatelimitError+} from "./utils";++/**+ * Provider-agnostic read of the trial balance as at `asOfDate` (YYYY-MM-DD),+ * debit-signed per remote account. Dispatches on the concrete provider class,+ * the same discrimination `fetchRemoteJournalTotals` uses.+ *+ * Rillet resolves `supported: false`. Its API has+ * `GET /reports/trial-balance?from_date&to_date` returning per-account+ * `beginning_balance` / `debit_total` / `credit_total` / `ending_balance`,+ * but the docs state neither the sign of `ending_balance` nor whether profit+ * and loss accounts are closed into retained earnings at year end — and the+ * opening balance depends on both. Wire it once those are confirmed against a+ * real Rillet ledger.+ *+ * Provider errors propagate (AccountingApiError, AccountingAuthError,+ * RatelimitError); `pullTrialBalanceFromProvider` turns them into a+ * TrialBalancePullError.+ */+export async function fetchRemoteTrialBalance(+ provider: AccountingProvider,+ asOfDate: string+): Promise<RemoteTrialBalance> {+ if (provider instanceof XeroProvider) {+ return { supported: true, rows: await provider.getTrialBalance(asOfDate) };+ }++ if (provider instanceof QboProvider) {+ return { supported: true, rows: await provider.getTrialBalance(asOfDate) };+ }++ return { supported: false };+}++const RECONNECT_MESSAGE =+ "The accounting integration did not allow Carbon to read the trial balance. Reconnect the integration to grant access to reports, then try again.";++function toPullError(error: unknown): TrialBalancePullError {+ if (error instanceof TrialBalancePullError) return error;++ if (error instanceof AccountingAuthError) {+ return new TrialBalancePullError("reconnect", RECONNECT_MESSAGE, {+ cause: error+ });+ }++ if (+ error instanceof AccountingApiError &&+ (error.details.statusCode === 401 || error.details.statusCode === 403)+ ) {+ return new TrialBalancePullError("reconnect", RECONNECT_MESSAGE, {+ cause: error+ });+ }++ if (error instanceof RatelimitError) {+ return new TrialBalancePullError(+ "rate_limited",+ `The accounting provider is limiting requests. Try again in ${error.retryAfterSeconds} seconds.`,+ { cause: error }+ );+ }++ const detail = error instanceof Error ? error.message : String(error);+ return new TrialBalancePullError(+ "failed",+ `Could not read the trial balance from the accounting provider: ${detail}`,+ { cause: error }+ );+}++/**+ * Pull the connected provider's trial balance as at `asOfDate` (YYYY-MM-DD)+ * and put it onto the company's Carbon accounts (see `mapRemoteTrialBalance`).+ *+ * Throws TrialBalancePullError — check `reason` — when the provider is not+ * connected, has no trial balance reader, refused the token, throttled the+ * request, or failed. Server-only: it reads vaulted credentials.+ */+export async function pullTrialBalanceFromProvider(+ client: SupabaseClient<Database>,+ db: Kysely<KyselyDatabase>,+ args: { companyId: string; providerId: ProviderID; asOfDate: string }+): Promise<MappedTrialBalance> {+ const { companyId, providerId, asOfDate } = args;++ try {+ parseDate(asOfDate);+ } catch {+ throw new TrialBalancePullError(+ "failed",+ `"${asOfDate}" is not a date (YYYY-MM-DD)`+ );+ }++ const integration = await getAccountingIntegration(+ client,+ companyId,+ providerId+ ).catch((error: unknown) => {+ throw new TrialBalancePullError(+ "not_connected",+ "The accounting integration is not connected.",+ { cause: error }+ );+ });+ if (!integration.active) {+ throw new TrialBalancePullError(+ "not_connected",+ "The accounting integration is not connected."+ );+ }++ let remote: RemoteTrialBalance;+ try {+ const provider = getProviderIntegration(+ client,+ companyId,+ integration.id,+ integration.metadata+ );+ remote = await fetchRemoteTrialBalance(provider, asOfDate);+ } catch (error) {+ throw toPullError(error);+ }++ if (!remote.supported) {+ throw new TrialBalancePullError(+ "unsupported",+ "This accounting integration cannot provide a trial balance. Enter the balances by hand."+ );+ }++ const mappings = await getAccountMappings(db, {+ companyId,+ integration: providerId+ });+ if (mappings.error || !mappings.data) {+ throw new TrialBalancePullError(+ "failed",+ `Could not read the account mappings: ${mappings.error ?? "no data"}`+ );+ }++ const companyGroupId = await getCompanyGroupId(db, companyId);+ if (!companyGroupId) {+ throw new TrialBalancePullError(+ "failed",+ `No company group found for company ${companyId}`+ );+ }++ const accounts = await db+ .selectFrom("account")+ .select(["id", "number", "isGroup", "active"])+ .where("companyGroupId", "=", companyGroupId)+ .execute();++ return mapRemoteTrialBalance(+ remote.rows,+ mappings.data,+ accounts.map((account) => ({+ id: account.id,+ number: account.number ?? null,+ isGroup: Boolean(account.isGroup),+ active: Boolean(account.active)+ }))+ );+}diff --git a/packages/ee/src/accounting/core/trial-balance.test.ts b/packages/ee/src/accounting/core/trial-balance.test.tsnew file mode 100644index 0000000000..7a49cdb717--- /dev/null+++ b/packages/ee/src/accounting/core/trial-balance.test.ts@@ -0,0 +1,558 @@+// SPDX-License-Identifier: LicenseRef-Carbon-Commercial+// Carbon Enterprise file, licensed only under the Carbon Commercial License+// (packages/ee/LICENSE). Not AGPL. Running, modifying, or copying it beyond those terms requires a commercial license.++import { describe, expect, it } from "vitest";+import {+ mapRemoteTrialBalance,+ parseQboTrialBalance,+ parseReportAmount,+ parseXeroTrialBalance,+ type QboTrialBalanceResponse,+ type RemoteTrialBalanceRow,+ splitXeroAccountLabel,+ type XeroReportCell,+ type XeroTrialBalanceResponse+} from "./trial-balance";++function xeroCells(+ accountId: string | null,+ values: [string, string, string, string, string]+): XeroReportCell[] {+ return values.map((value) => ({+ Value: value,+ Attributes: accountId ? [{ Value: accountId, Id: "account" }] : undefined+ }));+}++// Shaped like Xero's documented example (Reports/TrialBalance): a header row,+// one Section per account class, a Retained Earnings row carrying extra+// fromDate/toDate attributes, and a trailing Section holding the Total.+// Columns deliberately reordered against the docs to prove they are found+// by title, not position.+const XERO_FIXTURE: XeroTrialBalanceResponse = {+ Reports: [+ {+ ReportName: "Trial Balance",+ ReportType: "TrialBalance",+ Rows: [+ {+ RowType: "Header",+ Cells: [+ { Value: "Account" },+ { Value: "Debit" },+ { Value: "Credit" },+ { Value: "YTD Credit" },+ { Value: "YTD Debit" }+ ]+ },+ {+ RowType: "Section",+ Title: "Revenue",+ Rows: [+ {+ RowType: "Row",+ Cells: xeroCells("acc-sales", [+ "Sales (400)",+ "",+ "200.00",+ "1020.22",+ ""+ ])+ }+ ]+ },+ {+ RowType: "Section",+ Title: "Expenses",+ Rows: [+ {+ RowType: "Row",+ Cells: xeroCells("acc-rent", [+ "Rent (469)",+ "40.00",+ "",+ "",+ "480.00"+ ])+ }+ ]+ },+ {+ RowType: "Section",+ Title: "Assets",+ Rows: [+ {+ RowType: "Row",+ Cells: xeroCells("acc-bank", [+ "Business Bank (090)",+ "0.00",+ "",+ "",+ "1,340.22"+ ])+ },+ {+ // An overdrawn asset shows its balance in the credit column.+ RowType: "Row",+ Cells: xeroCells("acc-clearing", [+ "Card Clearing (8002)",+ "",+ "",+ "100.00",+ ""+ ])+ }+ ]+ },+ {+ RowType: "Section",+ Title: "Equity",+ Rows: [+ {+ RowType: "Row",+ Cells: [+ {+ Value: "Retained Earnings (320)",+ Attributes: [+ { Value: "acc-re", Id: "account" },+ { Value: "", Id: "fromDate" },+ { Value: "12/31/2025", Id: "toDate" }+ ]+ },+ { Value: "" },+ { Value: "" },+ { Value: "700.00" },+ { Value: "" }+ ]+ },+ {+ // A computed line with no account attribute.+ RowType: "Row",+ Cells: xeroCells(null, [+ "Unrealised Currency Gains",+ "",+ "",+ "",+ "0.00"+ ])+ }+ ]+ },+ {+ RowType: "Section",+ Title: "",+ Rows: [+ {+ RowType: "SummaryRow",+ Cells: [+ { Value: "Total" },+ { Value: "40.00" },+ { Value: "200.00" },+ { Value: "1820.22" },+ { Value: "1820.22" }+ ]+ }+ ]+ }+ ]+ }+ ]+};++describe("parseReportAmount", () => {+ it("reads blanks as zero, separators and accounting negatives", () => {+ expect(parseReportAmount("")).toBe(0);+ expect(parseReportAmount(undefined)).toBe(0);+ expect(parseReportAmount("1,234.50")).toBe(1234.5);+ expect(parseReportAmount("(12.30)")).toBe(-12.3);+ expect(parseReportAmount("-5")).toBe(-5);+ });++ it("refuses an unreadable value rather than reading it as zero", () => {+ expect(() => parseReportAmount("abc")).toThrow(/Unreadable/);+ });+});++describe("splitXeroAccountLabel", () => {+ it("splits the trailing code off the name", () => {+ expect(splitXeroAccountLabel("Sales (400)")).toEqual({+ name: "Sales",+ code: "400"+ });+ expect(splitXeroAccountLabel("Retained Earnings")).toEqual({+ name: "Retained Earnings",+ code: null+ });+ });+});++describe("parseXeroTrialBalance", () => {+ it("reads YTD Debit − YTD Credit per account, found by header title", () => {+ const rows = parseXeroTrialBalance(XERO_FIXTURE);++ expect(rows).toEqual([+ {+ externalId: "acc-sales",+ code: "400",+ name: "Sales",+ debitSigned: -1020.22+ },+ { externalId: "acc-rent", code: "469", name: "Rent", debitSigned: 480 },+ {+ externalId: "acc-bank",+ code: "090",+ name: "Business Bank",+ debitSigned: 1340.22+ },+ {+ externalId: "acc-clearing",+ code: "8002",+ name: "Card Clearing",+ debitSigned: -100+ },+ {+ externalId: "acc-re",+ code: "320",+ name: "Retained Earnings",+ debitSigned: -700+ },+ {+ externalId: null,+ code: null,+ name: "Unrealised Currency Gains",+ debitSigned: 0+ }+ ]);++ // The YTD columns are the balanced pair.+ const net = rows.reduce((sum, row) => sum + row.debitSigned, 0);+ expect(Math.abs(net)).toBeLessThan(1e-9);+ });++ it("refuses a report without YTD columns", () => {+ expect(() =>+ parseXeroTrialBalance({+ Reports: [+ {+ Rows: [+ {+ RowType: "Header",+ Cells: [{ Value: "Account" }, { Value: "Debit" }]+ }+ ]+ }+ ]+ })+ ).toThrow(/YTD/);+ });++ it("refuses a response with no report", () => {+ expect(() => parseXeroTrialBalance({ Reports: [] })).toThrow();+ });+});++// Shaped like QBO's TrialBalance report: an Account column plus Debit and+// Credit Money columns, Data rows nested inside Sections, a Section Summary,+// and the GrandTotal section.+const QBO_FIXTURE: QboTrialBalanceResponse = {+ Header: { ReportName: "TrialBalance", EndPeriod: "2026-09-30" },+ Columns: {+ Column: [+ { ColTitle: "", ColType: "Account" },+ { ColTitle: "Debit", ColType: "Money" },+ { ColTitle: "Credit", ColType: "Money" }+ ]+ },+ Rows: {+ Row: [+ {+ type: "Data",+ ColData: [+ { value: "Checking", id: "35" },+ { value: "1201.00" },+ { value: "" }+ ]+ },+ {+ type: "Section",+ Header: {+ ColData: [+ { value: "Utilities", id: "24" },+ { value: "" },+ { value: "" }+ ]+ },+ Rows: {+ Row: [+ {+ type: "Data",+ ColData: [+ { value: "Utilities:Gas and Electric", id: "76" },+ { value: "200.00" },+ { value: "" }+ ]+ },+ {+ type: "Data",+ ColData: [+ { value: "Utilities:Telephone", id: "77" },+ { value: "74.36" },+ { value: "" }+ ]+ }+ ]+ },+ Summary: {+ ColData: [+ { value: "Total Utilities" },+ { value: "274.36" },+ { value: "" }+ ]+ }+ },+ {+ type: "Data",+ ColData: [+ { value: "Accounts Payable (A/P)", id: "33" },+ { value: "" },+ { value: "1,475.36" }+ ]+ },+ {+ type: "Data",+ ColData: [+ { value: "Opening Balance Adjustment" },+ { value: "" },+ { value: "0.00" }+ ]+ },+ {+ type: "Section",+ group: "GrandTotal",+ Summary: {+ ColData: [+ { value: "TOTAL" },+ { value: "1475.36" },+ { value: "1475.36" }+ ]+ }+ }+ ]+ }+};++describe("parseQboTrialBalance", () => {+ it("walks nested rows and skips section headers, summaries and the grand total", () => {+ expect(parseQboTrialBalance(QBO_FIXTURE)).toEqual([+ { externalId: "35", code: null, name: "Checking", debitSigned: 1201 },+ {+ externalId: "76",+ code: null,+ name: "Utilities:Gas and Electric",+ debitSigned: 200+ },+ {+ externalId: "77",+ code: null,+ name: "Utilities:Telephone",+ debitSigned: 74.36+ },+ {+ externalId: "33",+ code: null,+ name: "Accounts Payable (A/P)",+ debitSigned: -1475.36+ },+ {+ externalId: null,+ code: null,+ name: "Opening Balance Adjustment",+ debitSigned: 0+ }+ ]);+ });++ it("finds Debit and Credit by title when the columns are reordered", () => {+ const rows = parseQboTrialBalance({+ Columns: {+ Column: [+ { ColTitle: "" },+ { ColTitle: "Credit" },+ { ColTitle: "Debit" }+ ]+ },+ Rows: {+ Row: [+ {+ ColData: [+ { value: "Sales", id: "1" },+ { value: "50" },+ { value: "" }+ ]+ }+ ]+ }+ });+ expect(rows[0]?.debitSigned).toBe(-50);+ });++ it("refuses a report without Debit and Credit columns", () => {+ expect(() =>+ parseQboTrialBalance({ Columns: { Column: [{ ColTitle: "Amount" }] } })+ ).toThrow(/Debit and Credit/);+ });+});++describe("mapRemoteTrialBalance", () => {+ const accounts = [+ { id: "a-bank", number: "1000", isGroup: false, active: true },+ { id: "a-ar", number: "1100", isGroup: false, active: true },+ { id: "a-sales", number: "4000", isGroup: false, active: true },+ { id: "a-sales-2", number: "4010", isGroup: false, active: true },+ { id: "a-re", number: "3200", isGroup: false, active: true },+ { id: "a-rent", number: "6100", isGroup: false, active: true },+ { id: "a-old", number: "6200", isGroup: false, active: false },+ { id: "a-group", number: "6000", isGroup: true, active: true },+ { id: "a-dup-1", number: "7000", isGroup: false, active: true },+ { id: "a-dup-2", number: "7000", isGroup: false, active: true }+ ];++ const row = (+ externalId: string | null,+ code: string | null,+ name: string,+ debitSigned: number+ ): RemoteTrialBalanceRow => ({ externalId, code, name, debitSigned });++ it("resolves by mapping, then mapped code, then account number", () => {+ const result = mapRemoteTrialBalance(+ [+ row("x-bank", "090", "Bank", 1500),+ row(null, "200", "Receivables", 250),+ row("x-unknown", "6100", "Rent", 75.5),+ row("x-re", "320", "Retained Earnings", -1825.5)+ ],+ [+ { accountId: "a-bank", externalId: "x-bank", externalCode: "090" },+ { accountId: "a-ar", externalId: "x-ar", externalCode: "200" },+ { accountId: "a-re", externalId: "x-re", externalCode: "320" }+ ],+ accounts+ );++ expect(result.lines).toEqual([+ { accountId: "a-bank", debit: 1500, credit: 0 },+ { accountId: "a-ar", debit: 250, credit: 0 },+ { accountId: "a-rent", debit: 75.5, credit: 0 },+ { accountId: "a-re", debit: 0, credit: 1825.5 }+ ]);+ expect(result.unmapped).toEqual([]);+ expect(result.ambiguous).toEqual([]);+ });++ it("sums several remote accounts that land on one Carbon account", () => {+ const result = mapRemoteTrialBalance(+ [+ row("x-s1", "400", "Product Sales", -100.1),+ row("x-s2", "410", "Service Sales", -200.2),+ row("x-s3", "420", "Refunds", 50.05)+ ],+ [+ { accountId: "a-sales", externalId: "x-s1", externalCode: "400" },+ { accountId: "a-sales", externalId: "x-s2", externalCode: "410" },+ { accountId: "a-sales", externalId: "x-s3", externalCode: "420" }+ ],+ accounts+ );++ expect(result.lines).toEqual([+ { accountId: "a-sales", debit: 0, credit: 250.25 }+ ]);+ });++ it("drops a Carbon account whose remote rows net to zero", () => {+ const result = mapRemoteTrialBalance(+ [row("x-s1", null, "A", 10), row("x-s2", null, "B", -10)],+ [+ { accountId: "a-sales", externalId: "x-s1", externalCode: null },+ { accountId: "a-sales", externalId: "x-s2", externalCode: null }+ ],+ accounts+ );+ expect(result.lines).toEqual([]);+ });++ it("does not guess when one remote account maps to several Carbon accounts", () => {+ const result = mapRemoteTrialBalance(+ [row("x-sales", "400", "Sales", -500)],+ [+ { accountId: "a-sales", externalId: "x-sales", externalCode: "400" },+ { accountId: "a-sales-2", externalId: "x-sales", externalCode: "400" }+ ],+ accounts+ );++ expect(result.lines).toEqual([]);+ expect(result.ambiguous).toEqual([+ {+ externalId: "x-sales",+ code: "400",+ name: "Sales",+ amount: -500,+ accountIds: ["a-sales", "a-sales-2"]+ }+ ]);+ });++ it("treats a duplicated Carbon account number as ambiguous", () => {+ const result = mapRemoteTrialBalance(+ [row("x-7", "7000", "Other", 12)],+ [],+ accounts+ );+ expect(result.ambiguous[0]?.accountIds).toEqual(["a-dup-1", "a-dup-2"]);+ });++ it("returns what it cannot place as unmapped, skipping zero balances", () => {+ const result = mapRemoteTrialBalance(+ [+ row("x-none", "999", "Suspense", 42),+ row(null, null, "Unrealised Currency Gains", -3),+ row("x-zero", "998", "Empty", 0),+ // Inactive and group accounts are not targets, by mapping or number.+ row("x-old", "6200", "Old Expense", 9),+ row(null, "6000", "Expense Group", 8)+ ],+ [{ accountId: "a-old", externalId: "x-old", externalCode: "6200" }],+ accounts+ );++ expect(result.lines).toEqual([]);+ expect(result.unmapped).toEqual([+ { externalId: "x-none", code: "999", name: "Suspense", amount: 42 },+ {+ externalId: null,+ code: null,+ name: "Unrealised Currency Gains",+ amount: -3+ },+ { externalId: "x-old", code: "6200", name: "Old Expense", amount: 9 },+ { externalId: null, code: "6000", name: "Expense Group", amount: 8 }+ ]);+ });++ it("rounds once, after summing", () => {+ const result = mapRemoteTrialBalance(+ [row("x-a", null, "A", 0.1), row("x-b", null, "B", 0.2)],+ [+ { accountId: "a-bank", externalId: "x-a", externalCode: null },+ { accountId: "a-bank", externalId: "x-b", externalCode: null }+ ],+ accounts+ );+ expect(result.lines).toEqual([+ { accountId: "a-bank", debit: 0.3, credit: 0 }+ ]);+ });+});diff --git a/packages/ee/src/accounting/core/trial-balance.ts b/packages/ee/src/accounting/core/trial-balance.tsnew file mode 100644index 0000000000..564e6bf1e6--- /dev/null+++ b/packages/ee/src/accounting/core/trial-balance.ts@@ -0,0 +1,456 @@+// SPDX-License-Identifier: LicenseRef-Carbon-Commercial+// Carbon Enterprise file, licensed only under the Carbon Commercial License+// (packages/ee/LICENSE). Not AGPL. Running, modifying, or copying it beyond those terms requires a commercial license.++import { round } from "@carbon/utils";+import { ProviderID } from "./models";++/**+ * Trial balance pulled from the connected accounting provider, as of one+ * date, and mapped onto Carbon accounts. Used by the accounting activation+ * wizard to fill the prior system's balances as of the day before the+ * cutover.+ *+ * This file is PURE (no provider classes, no database) so the provider+ * adapters can import their parsers from here without a cycle, and the+ * tests need nothing but fixtures. The provider dispatch and the server+ * entry live in `remote-trial-balance.ts`.+ */++/**+ * One account line of a provider's trial balance. `debitSigned` is the+ * account's balance as at the report date: debit positive, credit negative.+ * `externalId` is the provider's account id (Xero AccountID, QBO Id) — null+ * for a computed line the provider does not tie to an account; such a line is+ * still returned so the user can see it.+ */+export type RemoteTrialBalanceRow = {+ externalId: string | null;+ code: string | null;+ name: string;+ debitSigned: number;+};++/**+ * The providers `fetchRemoteTrialBalance` can read a trial balance from. The+ * wizard offers the pull only for these; `remote-trial-balance.test.ts` pins+ * the two together.+ */+const TRIAL_BALANCE_PROVIDERS: ReadonlySet<string> = new Set<ProviderID>([+ ProviderID.XERO,+ ProviderID.QUICKBOOKS+]);++export function isTrialBalanceProvider(id: string): id is ProviderID {+ return TRIAL_BALANCE_PROVIDERS.has(id);+}++export type RemoteTrialBalance =+ | { supported: false }+ | { supported: true; rows: RemoteTrialBalanceRow[] };++/**+ * Why a trial balance could not be pulled. The route turns each into a+ * message for the user; `message` is already written for the user.+ *+ * - `not_connected` — the company has no active integration for the provider+ * - `unsupported` — the provider has no trial balance reader+ * - `reconnect` — the provider refused the token (expired grant, or a token+ * minted before the report scope was requested); reconnecting fixes it+ * - `rate_limited` — the provider throttled the request; retry later+ * - `failed` — anything else (provider error, unexpected report shape)+ */+export type TrialBalancePullErrorReason =+ | "not_connected"+ | "unsupported"+ | "reconnect"+ | "rate_limited"+ | "failed";++export class TrialBalancePullError extends Error {+ constructor(+ public readonly reason: TrialBalancePullErrorReason,+ message: string,+ options?: { cause?: unknown }+ ) {+ super(message, options);+ this.name = "TrialBalancePullError";+ }+}++export function isTrialBalancePullError(+ error: unknown+): error is TrialBalancePullError {+ return error instanceof TrialBalancePullError;+}++/**+ * Parse a report amount string. Reports send "" for an empty cell, and may+ * format with thousands separators or accounting parentheses for negatives.+ * An unreadable value throws: reading it as 0 would silently drop a balance.+ */+export function parseReportAmount(value: string | number | null | undefined) {+ if (value === null || value === undefined) return 0;+ if (typeof value === "number") {+ if (!Number.isFinite(value)) {+ throw new Error(`Unreadable report amount "${value}"`);+ }+ return value;+ }++ let text = value.trim().replace(/,/g, "");+ if (text === "") return 0;++ let negative = false;+ if (text.startsWith("(") && text.endsWith(")")) {+ negative = true;+ text = text.slice(1, -1).trim();+ }++ const amount = Number(text);+ if (text === "" || !Number.isFinite(amount)) {+ throw new Error(`Unreadable report amount "${value}"`);+ }++ return negative ? -amount : amount;+}++function normalizeTitle(title: string | null | undefined): string {+ return (title ?? "").trim().replace(/\s+/g, " ").toLowerCase();+}++// ---------------------------------------------------------------------------+// Xero — GET /Reports/TrialBalance?date=YYYY-MM-DD+// ---------------------------------------------------------------------------++export type XeroReportCell = {+ Value?: string | null;+ Attributes?: Array<{ Id?: string | null; Value?: string | null }> | null;+};++export type XeroReportRow = {+ RowType?: string | null;+ Title?: string | null;+ Cells?: XeroReportCell[] | null;+ Rows?: XeroReportRow[] | null;+};++export type XeroTrialBalanceResponse = {+ Reports?: Array<{+ ReportName?: string | null;+ ReportType?: string | null;+ Rows?: XeroReportRow[] | null;+ }> | null;+};++/** Xero writes an account as "Name (Code)"; a code-less account is just "Name". */+export function splitXeroAccountLabel(label: string): {+ name: string;+ code: string | null;+} {+ const match = /^(.*\S)\s*\(([^()]+)\)\s*$/.exec(label.trim());+ if (!match) return { name: label.trim(), code: null };+ return { name: match[1]!.trim(), code: match[2]!.trim() };+}++function xeroAccountId(cells: XeroReportCell[]): string | null {+ for (const cell of cells) {+ for (const attribute of cell.Attributes ?? []) {+ if (attribute.Id === "account" && attribute.Value) {+ return attribute.Value;+ }+ }+ }+ return null;+}++/**+ * Reduce Xero's Trial Balance report to one row per account.+ *+ * The report has five columns: Account, Debit, Credit, YTD Debit, YTD Credit.+ * Debit / Credit are the MOVEMENT in the month of the report date. YTD Debit /+ * YTD Credit are the balance as at the date: cumulative for balance sheet+ * accounts, fiscal-year-to-date for profit and loss accounts, with prior years+ * closed into Retained Earnings — the column pair that totals to a balanced+ * trial balance. So the balance is YTD Debit − YTD Credit. The columns are+ * found by their header titles, not by position.+ *+ * SummaryRow lines (section and grand totals) are skipped. A Row without an+ * `account` attribute is a line Xero computes; it is returned with a null+ * `externalId` so the caller can show it as unmapped.+ */+export function parseXeroTrialBalance(+ response: XeroTrialBalanceResponse+): RemoteTrialBalanceRow[] {+ const report = response.Reports?.[0];+ if (!report) {+ throw new Error("Xero returned no trial balance report");+ }++ const rows = report.Rows ?? [];+ const header = rows.find((row) => row.RowType === "Header");+ const titles = (header?.Cells ?? []).map((cell) =>+ normalizeTitle(cell.Value)+ );+ const debitIndex = titles.indexOf("ytd debit");+ const creditIndex = titles.indexOf("ytd credit");+ if (debitIndex < 0 || creditIndex < 0) {+ throw new Error(+ "Xero trial balance has no YTD Debit and YTD Credit columns"+ );+ }++ const result: RemoteTrialBalanceRow[] = [];++ const visit = (row: XeroReportRow) => {+ if (row.RowType === "Section") {+ for (const child of row.Rows ?? []) visit(child);+ return;+ }+ if (row.RowType !== "Row") return;++ const cells = row.Cells ?? [];+ const label = cells[0]?.Value?.trim() ?? "";+ const { name, code } = splitXeroAccountLabel(label);+ const debit = parseReportAmount(cells[debitIndex]?.Value);+ const credit = parseReportAmount(cells[creditIndex]?.Value);++ result.push({+ externalId: xeroAccountId(cells),+ code,+ name,+ debitSigned: round(debit - credit)+ });+ };++ for (const row of rows) visit(row);++ return result;+}++// ---------------------------------------------------------------------------+// QuickBooks Online — GET /reports/TrialBalance?end_date=YYYY-MM-DD+// ---------------------------------------------------------------------------++export type QboReportColData = {+ value?: string | null;+ id?: string | null;+};++export type QboReportRow = {+ type?: string | null;+ group?: string | null;+ ColData?: QboReportColData[] | null;+ Header?: { ColData?: QboReportColData[] | null } | null;+ Rows?: { Row?: QboReportRow[] | null } | null;+ Summary?: { ColData?: QboReportColData[] | null } | null;+};++export type QboTrialBalanceResponse = {+ Header?: Record<string, unknown> | null;+ Columns?: {+ Column?: Array<{+ ColTitle?: string | null;+ ColType?: string | null;+ }> | null;+ } | null;+ Rows?: { Row?: QboReportRow[] | null } | null;+};++/**+ * Reduce QuickBooks Online's TrialBalance report to one row per account.+ *+ * The report has an Account column and a Debit and a Credit column, found by+ * `ColTitle`. Account lines are Data rows (`ColData`, first cell carries the+ * account `id`); Section rows nest more rows under `Rows.Row`. Only Data rows+ * are read: a Section's `Header` is a label and its `Summary` is a total+ * (including the GrandTotal), so reading either would count balances twice.+ * QBO shows no account code on the row, so `code` is null and the caller+ * resolves by id.+ */+export function parseQboTrialBalance(+ response: QboTrialBalanceResponse+): RemoteTrialBalanceRow[] {+ const titles = (response.Columns?.Column ?? []).map((column) =>+ normalizeTitle(column.ColTitle)+ );+ const debitIndex = titles.indexOf("debit");+ const creditIndex = titles.indexOf("credit");+ if (debitIndex < 0 || creditIndex < 0) {+ throw new Error(+ "QuickBooks Online trial balance has no Debit and Credit columns"+ );+ }++ const result: RemoteTrialBalanceRow[] = [];++ const visit = (row: QboReportRow) => {+ for (const child of row.Rows?.Row ?? []) visit(child);++ const cells = row.ColData;+ if (!cells || cells.length === 0) return;++ const debit = parseReportAmount(cells[debitIndex]?.value);+ const credit = parseReportAmount(cells[creditIndex]?.value);+ const id = cells[0]?.id;++ result.push({+ externalId: id ? id : null,+ code: null,+ name: cells[0]?.value?.trim() ?? "",+ debitSigned: round(debit - credit)+ });+ };++ for (const row of response.Rows?.Row ?? []) visit(row);++ return result;+}++// ---------------------------------------------------------------------------+// Mapping onto Carbon accounts+// ---------------------------------------------------------------------------++export type TrialBalanceAccountMapping = {+ accountId: string;+ externalId: string | null;+ externalCode: string | null;+};++export type TrialBalanceCarbonAccount = {+ id: string;+ number: string | null;+ isGroup: boolean;+ active: boolean;+};++/** A Carbon trial balance line: positive debit OR positive credit. */+export type PulledTrialBalanceLine = {+ accountId: string;+ debit: number;+ credit: number;+};++export type UnmappedTrialBalanceRow = {+ externalId: string | null;+ code: string | null;+ name: string;+ /** Debit-signed balance: debit positive, credit negative. */+ amount: number;+};++export type AmbiguousTrialBalanceRow = UnmappedTrialBalanceRow & {+ accountIds: string[];+};++export type MappedTrialBalance = {+ lines: PulledTrialBalanceLine[];+ unmapped: UnmappedTrialBalanceRow[];+ ambiguous: AmbiguousTrialBalanceRow[];+};++function addToIndex(+ index: Map<string, Set<string>>,+ key: string | null | undefined,+ accountId: string+) {+ if (!key) return;+ const set = index.get(key) ?? new Set<string>();+ set.add(accountId);+ index.set(key, set);+}++/**+ * Put a provider trial balance onto Carbon accounts.+ *+ * Each remote row resolves through the first of these that names at least+ * one active, non-group Carbon account:+ * 1. an account mapping on the row's external id+ * 2. an account mapping whose external code equals the row's code+ * 3. a Carbon account whose number equals the row's code+ * One account → the row's balance is added to it. Several → the row is+ * AMBIGUOUS (several Carbon accounts mapped to one remote account, or a+ * duplicated number) and is not guessed. None → UNMAPPED.+ *+ * Several remote rows on one Carbon account are summed, then rounded once.+ * Zero balances are dropped from every list.+ */+export function mapRemoteTrialBalance(+ rows: RemoteTrialBalanceRow[],+ mappings: TrialBalanceAccountMapping[],+ carbonAccounts: TrialBalanceCarbonAccount[]+): MappedTrialBalance {+ const postable = new Set(+ carbonAccounts+ .filter((account) => account.active && !account.isGroup)+ .map((account) => account.id)+ );++ const byExternalId = new Map<string, Set<string>>();+ const byExternalCode = new Map<string, Set<string>>();+ for (const mapping of mappings) {+ if (!postable.has(mapping.accountId)) continue;+ addToIndex(byExternalId, mapping.externalId, mapping.accountId);+ addToIndex(byExternalCode, mapping.externalCode, mapping.accountId);+ }++ const byNumber = new Map<string, Set<string>>();+ for (const account of carbonAccounts) {+ if (!postable.has(account.id)) continue;+ addToIndex(byNumber, account.number, account.id);+ }++ const resolve = (row: RemoteTrialBalanceRow): string[] => {+ const tiers = [+ row.externalId ? byExternalId.get(row.externalId) : undefined,+ row.code ? byExternalCode.get(row.code) : undefined,+ row.code ? byNumber.get(row.code) : undefined+ ];+ for (const tier of tiers) {+ if (tier && tier.size > 0) return [...tier];+ }+ return [];+ };++ const netByAccount = new Map<string, number>();+ const unmapped: UnmappedTrialBalanceRow[] = [];+ const ambiguous: AmbiguousTrialBalanceRow[] = [];++ for (const row of rows) {+ const amount = round(row.debitSigned);+ if (amount === 0) continue;++ const remote = {+ externalId: row.externalId,+ code: row.code,+ name: row.name,+ amount+ };++ const accountIds = resolve(row);+ if (accountIds.length === 0) {+ unmapped.push(remote);+ } else if (accountIds.length > 1) {+ ambiguous.push({ ...remote, accountIds });+ } else {+ const accountId = accountIds[0]!;+ netByAccount.set(+ accountId,+ (netByAccount.get(accountId) ?? 0) + row.debitSigned+ );+ }+ }++ const lines: PulledTrialBalanceLine[] = [];+ for (const [accountId, total] of netByAccount) {+ const net = round(total);+ if (net === 0) continue;+ lines.push({+ accountId,+ debit: net > 0 ? net : 0,+ credit: net < 0 ? -net : 0+ });+ }++ return { lines, unmapped, ambiguous };+}diff --git a/packages/ee/src/accounting/index.ts b/packages/ee/src/accounting/index.tsindex a961b79cba..61cfaac3ae 100644--- a/packages/ee/src/accounting/index.ts+++ b/packages/ee/src/accounting/index.ts@@ -20,9 +20,11 @@ export * from "./core/payment-tombstone";export * from "./core/posting";export * from "./core/reimbursement-source";export * from "./core/remote-journal";+export * from "./core/remote-trial-balance";export * from "./core/service";export * from "./core/subscriptions";export * from "./core/sync";+export * from "./core/trial-balance";export * from "./core/types";export * from "./core/utils";export * from "./providers";diff --git a/packages/ee/src/accounting/providers/quickbooks-online/provider.ts b/packages/ee/src/accounting/providers/quickbooks-online/provider.tsindex 0980f5baf7..214b646d28 100644--- a/packages/ee/src/accounting/providers/quickbooks-online/provider.ts+++ b/packages/ee/src/accounting/providers/quickbooks-online/provider.ts@@ -10,6 +10,11 @@ import type {RemoteCandidate} from "../../core/counterpart-types";import { ProviderID } from "../../core/models";+import {+ parseQboTrialBalance,+ type QboTrialBalanceResponse,+ type RemoteTrialBalanceRow+} from "../../core/trial-balance";import type {AccountingEntityType,DimensionTarget,@@ -1188,6 +1193,31 @@ export class QboProvider extends BaseProvider {);}+ /**+ * The trial balance as at `date` (YYYY-MM-DD), accrual basis, one row per+ * account (GET /reports/TrialBalance). Only `end_date` is sent: balance+ * sheet accounts are cumulative to it and profit and loss accounts run+ * from the start of its fiscal year, prior years sitting in Retained+ * Earnings. A refused token is thrown as an AccountingApiError carrying+ * the 401/403.+ */+ async getTrialBalance(date: string): Promise<RemoteTrialBalanceRow[]> {+ const params = new URLSearchParams({+ end_date: date,+ accounting_method: "Accrual"+ });+ const response = await this.request<QboTrialBalanceResponse>(+ "GET",+ `/reports/TrialBalance?${params.toString()}`+ );++ if (response.error || !response.data) {+ throwQboApiError("read trial balance", response);+ }++ return parseQboTrialBalance(response.data);+ }+/*** Create a QBO journal entry. No update counterpart: pushed journals are* immutable (the journal syncer hard-skips already-mapped ids), so thediff --git a/packages/ee/src/accounting/providers/xero/provider.ts b/packages/ee/src/accounting/providers/xero/provider.tsindex 27b46712c1..bd748b7182 100644--- a/packages/ee/src/accounting/providers/xero/provider.ts+++ b/packages/ee/src/accounting/providers/xero/provider.ts@@ -9,6 +9,11 @@ import type {RemoteCandidate} from "../../core/counterpart-types";import { ProviderID } from "../../core/models";+import {+ parseXeroTrialBalance,+ type RemoteTrialBalanceRow,+ type XeroTrialBalanceResponse+} from "../../core/trial-balance";import type {AccountingEntityType,AuthProvider,@@ -545,6 +550,25 @@ export class XeroProvider implements BaseProvider, SupportsIncrementalPull {return response.data?.ManualJournals?.[0] ?? null;}+ /**+ * The trial balance as at `date` (YYYY-MM-DD), one row per account+ * (GET /Reports/TrialBalance). Needs the `accounting.reports.trialbalance.read`+ * scope; a token minted before Carbon requested it gets a 401/403, thrown+ * as an AccountingApiError carrying that status.+ */+ async getTrialBalance(date: string): Promise<RemoteTrialBalanceRow[]> {+ const response = await this.request<XeroTrialBalanceResponse>(+ "GET",+ `/Reports/TrialBalance?date=${encodeURIComponent(date)}`+ );++ if (response.error || !response.data) {+ throwXeroApiError("read trial balance", response);+ }++ return parseXeroTrialBalance(response.data);+ }+/*** Create a payment (PUT /Payments) applying an amount to a Xero invoice.* Xero's single /Payments endpoint settles BOTH families — an ACCREC (salesdiff --git a/packages/ee/src/xero/config.tsx b/packages/ee/src/xero/config.tsxindex 4709944314..8173e34795 100644--- a/packages/ee/src/xero/config.tsx+++ b/packages/ee/src/xero/config.tsx@@ -77,7 +77,12 @@ export const Xero = defineIntegration({"accounting.invoices","accounting.payments","accounting.banktransactions",- "accounting.manualjournals"+ "accounting.manualjournals",+ // Read-only: the accounting activation wizard pulls the trial balance+ // as at the day before the cutover (GET /Reports/TrialBalance). A tenant+ // connected before this scope was added gets a 401/403 there, surfaced as+ // "reconnect the integration" — no forced reconnect.+ "accounting.reports.trialbalance.read"],tokenUrl: "https://login.xero.com/identity/connect/token"},diff --git a/packages/jobs/manifests/schema.json b/packages/jobs/manifests/schema.jsonindex 930df495b8..d3f55d2fe2 100644--- a/packages/jobs/manifests/schema.json+++ b/packages/jobs/manifests/schema.json@@ -1,11 +1,11 @@{"kind": "carbon-company-backup","version": 1,- "schemaVersion": "20261013004700",+ "schemaVersion": "20261013171656","sourceCompanyId": "schema-baseline","sourceCompanyGroupId": null,"sourceCompanyName": null,- "exportedAt": "2026-10-13T00:04:42.459Z",+ "exportedAt": "2026-10-13T19:01:57.412Z","exportedBy": "schema-baseline","label": "schema baseline","includeStorage": "none",@@ -110,6 +110,19 @@"leaseInterestExpenseAccount"]},+ {+ "name": "accountingCutoverIgnoredInvoice",+ "rows": 0,+ "columns": [+ "id",+ "companyId",+ "invoiceId",+ "createdBy",+ "createdAt",+ "updatedBy",+ "updatedAt"+ ]+ },{"name": "accountingPeriod","rows": 0,diff --git a/packages/locale/locales/de/erp.po b/packages/locale/locales/de/erp.poindex e706e85634..74e51be49e 100644--- a/packages/locale/locales/de/erp.po+++ b/packages/locale/locales/de/erp.po@@ -54,6 +54,9 @@ msgstr "(inaktives Konto)"msgid "(Inactive)"msgstr "(Inaktiv)"+msgid "(mapped to more than one Carbon account)"+msgstr "(auf mehr als ein Carbon-Konto abgebildet)"+msgid "(not an Equity posting account)"msgstr "(kein Eigenkapital-Buchungskonto)"@@ -2804,6 +2807,9 @@ msgstr "Auf Rechnungen anwenden"msgid "Apply to reimbursements"msgstr "Auf Kostenerstattungen anwenden"+msgid "Apply to Trial Balance"+msgstr "Auf Probebilanz anwenden"+msgid "Applying"msgstr "Wird angewendet"@@ -3812,6 +3818,10 @@ msgstr "Sicherungen"msgid "Balance"msgstr "Saldo"+#. placeholder {0}: account.name+msgid "Balance for {0}"+msgstr "Saldo für {0}"+msgid "Balance Sheet"msgstr "Bilanz"@@ -6402,10 +6412,6 @@ msgstr "Gutschriften und Belastungsnotizen"msgid "Credit applied"msgstr "Haben angewendet"-#. placeholder {0}: account.name-msgid "Credit for {0}"-msgstr "Gutschrift für {0}"-msgid "Credit Memo"msgstr "Gutschrift"@@ -6887,10 +6893,6 @@ msgstr "Soll ({0})"msgid "Debit Account"msgstr "Sollkonto"-#. placeholder {0}: account.name-msgid "Debit for {0}"-msgstr "Belastung für {0}"-msgid "Debit Memo"msgstr "Sollschrift"@@ -8915,6 +8917,12 @@ msgstr "Erfassen und genehmigen Sie Lieferantenrechnungen gegen eine Bestellungmsgid "Enter at least one debit and credit"msgstr "Geben Sie mindestens einen Soll und ein Haben ein"+msgid "Enter debits as positive and credits as negative amounts. The CSV needs the columns accountNumber, debit and credit. An import or a pull from {providerName} replaces the whole trial balance."+msgstr "Geben Sie Sollbeträge als positive und Habenbeträge als negative Beträge ein. Die CSV muss die Spalten accountNumber, debit und credit enthalten. Ein Import oder ein Abruf von {providerName} ersetzt die gesamte Probebilanz."++msgid "Enter debits as positive and credits as negative amounts. The CSV needs the columns accountNumber, debit and credit. An import replaces the whole trial balance."+msgstr "Geben Sie Sollbeträge als positive und Habenbeträge als negative Beträge ein. Die CSV muss die Spalten accountNumber, debit und credit enthalten. Ein Import ersetzt die gesamte Probebilanz."+msgid "Enter number…"msgstr "Zahl eingeben…"@@ -10729,6 +10737,9 @@ msgstr "Ausgewählte in diesem Schritt ausblenden"msgid "Hide system quantities until the review step"msgstr "Systemmengen bis zum Überprüfungsschritt ausblenden"+msgid "Hide the items on {label}"+msgstr "Die Artikel auf {label} ausblenden"+msgid "Hide, pin and reorder columns"msgstr "Spalten ausblenden, fixieren und neu anordnen"@@ -11062,6 +11073,9 @@ msgstr "IFSC-Code"msgid "Ignore"msgstr "Ignorieren"+msgid "Ignored"+msgstr "Ignoriert"+msgid "II (normal default)"msgstr "II (normalstandard)"@@ -12946,6 +12960,9 @@ msgstr "Extrahierte Zeilen zuordnen"msgid "Map Lines Now"msgstr "Zeilen jetzt zuordnen"+msgid "Map these accounts in the {providerName} integration settings and pull again, or enter their balances below."+msgstr "Ordnen Sie diese Konten in den {providerName}-Integrationseinstellungen zu, rufen Sie erneut ab, oder geben Sie ihre Salden unten ein."+msgid "Map your chart of accounts to the provider's. Posting-default and expense accounts are marked Required; posted journals push using the mapped provider account code."msgstr "Ordnen Sie Ihren Kontenplan dem des Anbieters zu. Buchungs-Standardkonten und Aufwandkonten sind als erforderlich gekennzeichnet. Gebuchte Buchungssätze werden mit dem zugeordneten Anbieterkontokode übertragen."@@ -15121,8 +15138,8 @@ msgstr "Ein"msgid "On {sentDate}"msgstr "An"-msgid "On a control account, Carbon opens the balance from its own open items, inventory and fixed assets. The trial balance must agree: every difference stays on Migration Clearing, which must total zero."-msgstr "Bei einem Kontrollkonto eröffnet Carbon den Saldo aus seinen eigenen offenen Posten, Beständen und Anlagegütern. Die Rohbilanz muss zustimmen: Jede Differenz bleibt auf dem Migrations-Clearing, das sich auf Null summieren muss."+msgid "On a control account, Carbon opens the balance from its own open items, inventory and fixed assets. The trial balance must agree: every difference stays on Migration Clearing, which must total zero. Open an account to see its items, and ignore an invoice the prior system already settled."+msgstr "Auf einem Kontrolkonto eröffnet Carbon den Saldo aus seinen offenen Positionen, Beständen und Anlagegut. Die Probebilanz muss sich decken: jede Differenz bleibt auf Migration Clearing, welche insgesamt null betragen muss. Öffnen Sie ein Konto, um seine Artikel anzuzeigen, und ignorieren Sie eine Rechnung, die das Vorsystem bereits abgewickelt hat."msgid "On a transfer kanban, the minimum quantity for the To storage unit. When on-hand plus open inbound transfers drops below it, Carbon creates a Released stock transfer for the kanban quantity."msgstr "Bei einer Umlagerungs-Kanban ist die Mindestmenge für die Ziel-Lagereinheit der Schwellwert. Wenn der verfügbare Bestand plus offene eingehende Umlagerungen darunter fällt, erstellt Carbon eine ausgelöste Umlagerung für die Kanban-Menge."@@ -17091,6 +17108,9 @@ msgstr "Abrufen"msgid "Pull From"msgstr "Aus entnehmen"+msgid "Pull from {providerName}"+msgstr "Von {providerName} abrufen"+msgid "Pull from accounting"msgstr "Aus der Buchhaltung abrufen"@@ -20182,6 +20202,9 @@ msgstr "Bestimmt den Buchwert dieser Einheit im Lager. Die Differenz wird zwischmsgid "Settings"msgstr "Einstellungen"+msgid "Settled in the system that kept the books before the cutover. Carbon leaves them out of its totals and marks them Paid on the day before the cutover when you set up accounting."+msgstr "Im System abgewickelt, das die Bücher vor dem Stichtag führte. Carbon lässt sie aus seinen Summen weg und markiert sie als Bezahlt am Tag vor dem Stichtag, wenn Sie Buchhaltung einrichten."+msgid "Setup"msgstr "Einrichtung"@@ -20522,6 +20545,9 @@ msgstr "Lieferanten-IDs anzeigen"msgid "Show sync options"msgstr "Synchronisierungsoptionen anzeigen"+msgid "Show the items on {label}"+msgstr "Die Artikel auf {label} anzeigen"+msgid "Show Trailing Zeros"msgstr "Nachgestellte Nullen anzeigen"@@ -20681,6 +20707,9 @@ msgstr "Verkauft"msgid "Solutions Engineer"msgstr "Lösungsingenieur"+msgid "Some balances have no Carbon account"+msgstr "Einige Salden haben kein Carbon-Konto"+msgid "Some lines are invoiced for more or less than they total. Fix the amounts before confirming."msgstr "Einige Positionen sind für mehr oder weniger fakturiert als ihr Gesamtbetrag. Korrigieren Sie die Beträge vor dem Bestätigen."@@ -22049,9 +22078,6 @@ msgstr "Die CSV-Datei ist leer."msgid "The CSV has no {columns} column."msgstr "Die CSV hat keine {columns} Spalte."-msgid "The CSV needs the columns accountNumber, debit and credit. An import replaces the whole trial balance."-msgstr "Die CSV benötigt die Spalten accountNumber, Soll und Haben. Ein Import ersetzt die gesamte Rohbilanz."-msgid "The CSV was not imported"msgstr "Die CSV wurde nicht importiert."@@ -23683,9 +23709,8 @@ msgstr "Themen"msgid "Total"msgstr "Gesamt"-#. placeholder {0}: formatter.format(round(totalDebit - totalCredit))-msgid "Total (out of balance by {0})"-msgstr "Gesamtbetrag (Differenz: {0})"+msgid "Total (out of balance)"+msgstr "Summe (nicht ausgeglichen)"#. placeholder {0}: total.classNamemsgid "Total {0}"diff --git a/packages/locale/locales/en/erp.po b/packages/locale/locales/en/erp.poindex df3138b42b..a07a5126c4 100644--- a/packages/locale/locales/en/erp.po+++ b/packages/locale/locales/en/erp.po@@ -54,6 +54,9 @@ msgstr "(inactive account)"msgid "(Inactive)"msgstr "(Inactive)"+msgid "(mapped to more than one Carbon account)"+msgstr "(mapped to more than one Carbon account)"+msgid "(not an Equity posting account)"msgstr "(not an Equity posting account)"@@ -2804,6 +2807,9 @@ msgstr "Apply to invoices"msgid "Apply to reimbursements"msgstr "Apply to reimbursements"+msgid "Apply to Trial Balance"+msgstr "Apply to Trial Balance"+msgid "Applying"msgstr "Applying"@@ -3812,6 +3818,10 @@ msgstr "Backups"msgid "Balance"msgstr "Balance"+#. placeholder {0}: account.name+msgid "Balance for {0}"+msgstr "Balance for {0}"+msgid "Balance Sheet"msgstr "Balance Sheet"@@ -6402,10 +6412,6 @@ msgstr "Credit and debit memos"msgid "Credit applied"msgstr "Credit applied"-#. placeholder {0}: account.name-msgid "Credit for {0}"-msgstr "Credit for {0}"-msgid "Credit Memo"msgstr "Credit Memo"@@ -6887,10 +6893,6 @@ msgstr "Debit ({0})"msgid "Debit Account"msgstr "Debit Account"-#. placeholder {0}: account.name-msgid "Debit for {0}"-msgstr "Debit for {0}"-msgid "Debit Memo"msgstr "Debit Memo"@@ -8915,6 +8917,12 @@ msgstr "Enter and approve vendor bills against a PO (three-way match)"msgid "Enter at least one debit and credit"msgstr "Enter at least one debit and credit"+msgid "Enter debits as positive and credits as negative amounts. The CSV needs the columns accountNumber, debit and credit. An import or a pull from {providerName} replaces the whole trial balance."+msgstr "Enter debits as positive and credits as negative amounts. The CSV needs the columns accountNumber, debit and credit. An import or a pull from {providerName} replaces the whole trial balance."++msgid "Enter debits as positive and credits as negative amounts. The CSV needs the columns accountNumber, debit and credit. An import replaces the whole trial balance."+msgstr "Enter debits as positive and credits as negative amounts. The CSV needs the columns accountNumber, debit and credit. An import replaces the whole trial balance."+msgid "Enter number…"msgstr "Enter number…"@@ -10729,6 +10737,9 @@ msgstr "Hide selected on this step"msgid "Hide system quantities until the review step"msgstr "Hide system quantities until the review step"+msgid "Hide the items on {label}"+msgstr "Hide the items on {label}"+msgid "Hide, pin and reorder columns"msgstr "Hide, pin and reorder columns"@@ -11062,6 +11073,9 @@ msgstr "IFSC Code"msgid "Ignore"msgstr "Ignore"+msgid "Ignored"+msgstr "Ignored"+msgid "II (normal default)"msgstr "II (normal default)"@@ -12946,6 +12960,9 @@ msgstr "Map Extracted Lines"msgid "Map Lines Now"msgstr "Map Lines Now"+msgid "Map these accounts in the {providerName} integration settings and pull again, or enter their balances below."+msgstr "Map these accounts in the {providerName} integration settings and pull again, or enter their balances below."+msgid "Map your chart of accounts to the provider's. Posting-default and expense accounts are marked Required; posted journals push using the mapped provider account code."msgstr "Map your chart of accounts to the provider's. Posting-default and expense accounts are marked Required; posted journals push using the mapped provider account code."@@ -15121,8 +15138,8 @@ msgstr "On"msgid "On {sentDate}"msgstr "On {sentDate}"-msgid "On a control account, Carbon opens the balance from its own open items, inventory and fixed assets. The trial balance must agree: every difference stays on Migration Clearing, which must total zero."-msgstr "On a control account, Carbon opens the balance from its own open items, inventory and fixed assets. The trial balance must agree: every difference stays on Migration Clearing, which must total zero."+msgid "On a control account, Carbon opens the balance from its own open items, inventory and fixed assets. The trial balance must agree: every difference stays on Migration Clearing, which must total zero. Open an account to see its items, and ignore an invoice the prior system already settled."+msgstr "On a control account, Carbon opens the balance from its own open items, inventory and fixed assets. The trial balance must agree: every difference stays on Migration Clearing, which must total zero. Open an account to see its items, and ignore an invoice the prior system already settled."msgid "On a transfer kanban, the minimum quantity for the To storage unit. When on-hand plus open inbound transfers drops below it, Carbon creates a Released stock transfer for the kanban quantity."msgstr "On a transfer kanban, the minimum quantity for the To storage unit. When on-hand plus open inbound transfers drops below it, Carbon creates a Released stock transfer for the kanban quantity."@@ -17091,6 +17108,9 @@ msgstr "Pull"msgid "Pull From"msgstr "Pull From"+msgid "Pull from {providerName}"+msgstr "Pull from {providerName}"+msgid "Pull from accounting"msgstr "Pull from accounting"@@ -20182,6 +20202,9 @@ msgstr "Sets what this unit is carried at in inventory. The difference is bookedmsgid "Settings"msgstr "Settings"+msgid "Settled in the system that kept the books before the cutover. Carbon leaves them out of its totals and marks them Paid on the day before the cutover when you set up accounting."+msgstr "Settled in the system that kept the books before the cutover. Carbon leaves them out of its totals and marks them Paid on the day before the cutover when you set up accounting."+msgid "Setup"msgstr "Setup"@@ -20522,6 +20545,9 @@ msgstr "Show Supplier IDs"msgid "Show sync options"msgstr "Show sync options"+msgid "Show the items on {label}"+msgstr "Show the items on {label}"+msgid "Show Trailing Zeros"msgstr "Show Trailing Zeros"@@ -20681,6 +20707,9 @@ msgstr "Sold"msgid "Solutions Engineer"msgstr "Solutions Engineer"+msgid "Some balances have no Carbon account"+msgstr "Some balances have no Carbon account"+msgid "Some lines are invoiced for more or less than they total. Fix the amounts before confirming."msgstr "Some lines are invoiced for more or less than they total. Fix the amounts before confirming."@@ -22049,9 +22078,6 @@ msgstr "The CSV file is empty."msgid "The CSV has no {columns} column."msgstr "The CSV has no {columns} column."-msgid "The CSV needs the columns accountNumber, debit and credit. An import replaces the whole trial balance."-msgstr "The CSV needs the columns accountNumber, debit and credit. An import replaces the whole trial balance."-msgid "The CSV was not imported"msgstr "The CSV was not imported"@@ -23683,9 +23709,8 @@ msgstr "Topics"msgid "Total"msgstr "Total"-#. placeholder {0}: formatter.format(round(totalDebit - totalCredit))-msgid "Total (out of balance by {0})"-msgstr "Total (out of balance by {0})"+msgid "Total (out of balance)"+msgstr "Total (out of balance)"#. placeholder {0}: total.classNamemsgid "Total {0}"diff --git a/packages/locale/locales/es/erp.po b/packages/locale/locales/es/erp.poindex 530f6c7674..d0643f35e0 100644--- a/packages/locale/locales/es/erp.po+++ b/packages/locale/locales/es/erp.po@@ -54,6 +54,9 @@ msgstr "(cuenta inactiva)"msgid "(Inactive)"msgstr "(Inactivo)"+msgid "(mapped to more than one Carbon account)"+msgstr "(asignado a más de una cuenta de Carbon)"+msgid "(not an Equity posting account)"msgstr "(no es una cuenta de Contabilización de Patrimonio)"@@ -2804,6 +2807,9 @@ msgstr "Aplicar a facturas"msgid "Apply to reimbursements"msgstr "Aplicar a reembolsos"+msgid "Apply to Trial Balance"+msgstr "Aplicar al Saldo de Prueba"+msgid "Applying"msgstr "Aplicando"@@ -3812,6 +3818,10 @@ msgstr "Copias de seguridad"msgid "Balance"msgstr "Saldo"+#. placeholder {0}: account.name+msgid "Balance for {0}"+msgstr "Saldo de {0}"+msgid "Balance Sheet"msgstr "Balance General"@@ -6402,10 +6412,6 @@ msgstr "Notas de crédito y débito"msgid "Credit applied"msgstr "Haber aplicado"-#. placeholder {0}: account.name-msgid "Credit for {0}"-msgstr "Haber para {0}"-msgid "Credit Memo"msgstr "Nota de Crédito"@@ -6887,10 +6893,6 @@ msgstr "Debe ({0})"msgid "Debit Account"msgstr "Cuenta de debe"-#. placeholder {0}: account.name-msgid "Debit for {0}"-msgstr "Debe para {0}"-msgid "Debit Memo"msgstr "Nota de débito"@@ -8915,6 +8917,12 @@ msgstr "Registra y aprueba facturas de proveedores contra una orden de compra (cmsgid "Enter at least one debit and credit"msgstr "Ingrese al menos un debe y un haber"+msgid "Enter debits as positive and credits as negative amounts. The CSV needs the columns accountNumber, debit and credit. An import or a pull from {providerName} replaces the whole trial balance."+msgstr "Ingrese débitos como cantidades positivas y créditos como cantidades negativas. El CSV necesita las columnas accountNumber, debit y credit. Una importación o una extracción de {providerName} reemplaza el saldo de prueba completo."++msgid "Enter debits as positive and credits as negative amounts. The CSV needs the columns accountNumber, debit and credit. An import replaces the whole trial balance."+msgstr "Ingrese débitos como cantidades positivas y créditos como cantidades negativas. El CSV necesita las columnas accountNumber, debit y credit. Una importación reemplaza el saldo de prueba completo."+msgid "Enter number…"msgstr "Ingrese número…"@@ -10729,6 +10737,9 @@ msgstr "Ocultar seleccionado en este paso"msgid "Hide system quantities until the review step"msgstr "Ocultar cantidades del sistema hasta el paso de revisión"+msgid "Hide the items on {label}"+msgstr "Ocultar los artículos en {label}"+msgid "Hide, pin and reorder columns"msgstr "Ocultar, anclar y reordenar columnas"@@ -11062,6 +11073,9 @@ msgstr "Código IFSC"msgid "Ignore"msgstr "Ignorar"+msgid "Ignored"+msgstr "Ignorado"+msgid "II (normal default)"msgstr "II (normal predeterminado)"@@ -12946,6 +12960,9 @@ msgstr "Mapear Líneas Extraídas"msgid "Map Lines Now"msgstr "Mapear líneas ahora"+msgid "Map these accounts in the {providerName} integration settings and pull again, or enter their balances below."+msgstr "Asigne estas cuentas en la configuración de integración {providerName} y extraiga nuevamente, o ingrese sus saldos a continuación."+msgid "Map your chart of accounts to the provider's. Posting-default and expense accounts are marked Required; posted journals push using the mapped provider account code."msgstr "Asigne su Plan de cuentas al del proveedor. Las cuentas predeterminadas de contabilización y de gasto están marcadas como Requeridas; los asientos contabilizados se impulsan utilizando el código de cuenta del proveedor asignado."@@ -15121,8 +15138,8 @@ msgstr "Activado"msgid "On {sentDate}"msgstr "El {sentDate}"-msgid "On a control account, Carbon opens the balance from its own open items, inventory and fixed assets. The trial balance must agree: every difference stays on Migration Clearing, which must total zero."-msgstr "En una cuenta de control, Carbon abre el saldo de sus propios artículos abiertos, existencias y activos fijos. El balance de comprobación debe coincidir: toda diferencia permanece en Liquidación de migración, que debe totalizar cero."+msgid "On a control account, Carbon opens the balance from its own open items, inventory and fixed assets. The trial balance must agree: every difference stays on Migration Clearing, which must total zero. Open an account to see its items, and ignore an invoice the prior system already settled."+msgstr "En una cuenta de control, Carbon calcula el saldo de sus propias partidas abiertas, inventario y activos fijos. El saldo de prueba debe coincidir: cada diferencia se mantiene en Liquidación de Migración, que debe sumar cero. Abra una cuenta para ver sus partidas e ignore una factura que el sistema anterior ya liquidó."msgid "On a transfer kanban, the minimum quantity for the To storage unit. When on-hand plus open inbound transfers drops below it, Carbon creates a Released stock transfer for the kanban quantity."msgstr "En un kanban de transferencia, la cantidad mínima para la unidad de almacenamiento de destino. Cuando las existencias disponibles más las transferencias entrantes abiertas caen por debajo de esto, Carbon crea una transferencia de existencias Liberada por la cantidad del kanban."@@ -17091,6 +17108,9 @@ msgstr "Extraer"msgid "Pull From"msgstr "Extraer de"+msgid "Pull from {providerName}"+msgstr "Extraer de {providerName}"+msgid "Pull from accounting"msgstr "Extraer de contabilidad"@@ -20182,6 +20202,9 @@ msgstr "Define el costo al que esta unidad se registra en el inventario. La difemsgid "Settings"msgstr "Configuración"+msgid "Settled in the system that kept the books before the cutover. Carbon leaves them out of its totals and marks them Paid on the day before the cutover when you set up accounting."+msgstr "Liquidado en el sistema que mantenía los registros contables antes del corte. Carbon los excluye de sus totales y los marca como Pagado el día anterior al corte cuando activa la contabilidad."+msgid "Setup"msgstr "Configuración"@@ -20522,6 +20545,9 @@ msgstr "Mostrar IDs de Proveedores"msgid "Show sync options"msgstr "Mostrar opciones de sincronización"+msgid "Show the items on {label}"+msgstr "Mostrar los artículos en {label}"+msgid "Show Trailing Zeros"msgstr "Mostrar Ceros Finales"@@ -20681,6 +20707,9 @@ msgstr "Vendido"msgid "Solutions Engineer"msgstr "Ingeniero de Soluciones"+msgid "Some balances have no Carbon account"+msgstr "Algunos saldos no tienen ninguna cuenta de Carbon"+msgid "Some lines are invoiced for more or less than they total. Fix the amounts before confirming."msgstr "Algunas líneas se facturan por más o menos de lo que totalizan. Corrija los montos antes de confirmar."@@ -22049,9 +22078,6 @@ msgstr "El archivo CSV está vacío."msgid "The CSV has no {columns} column."msgstr "El CSV no tiene columna {columns}."-msgid "The CSV needs the columns accountNumber, debit and credit. An import replaces the whole trial balance."-msgstr "El CSV necesita las columnas accountNumber, Debe y Haber. Una importación reemplaza el balance de comprobación completo."-msgid "The CSV was not imported"msgstr "El CSV no fue importado."@@ -23683,9 +23709,8 @@ msgstr "Temas"msgid "Total"msgstr "Total"-#. placeholder {0}: formatter.format(round(totalDebit - totalCredit))-msgid "Total (out of balance by {0})"-msgstr "Total (diferencia de {0})"+msgid "Total (out of balance)"+msgstr "Total (sin cuadrar)"#. placeholder {0}: total.classNamemsgid "Total {0}"diff --git a/packages/locale/locales/fr/erp.po b/packages/locale/locales/fr/erp.poindex a01ba40785..a8f8f0e3a6 100644--- a/packages/locale/locales/fr/erp.po+++ b/packages/locale/locales/fr/erp.po@@ -54,6 +54,9 @@ msgstr "(compte inactif)"msgid "(Inactive)"msgstr "(Inactif)"+msgid "(mapped to more than one Carbon account)"+msgstr "(Associé à plusieurs comptes Carbon)"+msgid "(not an Equity posting account)"msgstr "(pas un compte de comptabilisation de capitaux propres)"@@ -2804,6 +2807,9 @@ msgstr "Appliquer aux factures"msgid "Apply to reimbursements"msgstr "Appliquer aux remboursements"+msgid "Apply to Trial Balance"+msgstr "Appliquer à la balance de vérification"+msgid "Applying"msgstr "Application en cours"@@ -3812,6 +3818,10 @@ msgstr "Sauvegardes"msgid "Balance"msgstr "Solde"+#. placeholder {0}: account.name+msgid "Balance for {0}"+msgstr "Solde de {0}"+msgid "Balance Sheet"msgstr "Bilan"@@ -6402,10 +6412,6 @@ msgstr "Mémos de crédit et de débit"msgid "Credit applied"msgstr "Crédit appliqué"-#. placeholder {0}: account.name-msgid "Credit for {0}"-msgstr "Crédit pour {0}"-msgid "Credit Memo"msgstr "Avoir"@@ -6887,10 +6893,6 @@ msgstr "Débit ({0})"msgid "Debit Account"msgstr "Compte Débiteur"-#. placeholder {0}: account.name-msgid "Debit for {0}"-msgstr "Débit pour {0}"-msgid "Debit Memo"msgstr "Note de débit"@@ -8915,6 +8917,12 @@ msgstr "Entrer et approuver les factures fournisseurs par rapport à un bon de cmsgid "Enter at least one debit and credit"msgstr "Entrer au moins un Débit et un Crédit"+msgid "Enter debits as positive and credits as negative amounts. The CSV needs the columns accountNumber, debit and credit. An import or a pull from {providerName} replaces the whole trial balance."+msgstr "Entrez les débits en montants positifs et les crédits en montants négatifs. Le CSV doit contenir les colonnes accountNumber, debit et credit. Une importation ou une extraction depuis {providerName} remplace l'intégralité de la balance de vérification."++msgid "Enter debits as positive and credits as negative amounts. The CSV needs the columns accountNumber, debit and credit. An import replaces the whole trial balance."+msgstr "Entrez les débits en montants positifs et les crédits en montants négatifs. Le CSV doit contenir les colonnes accountNumber, debit et credit. Une importation remplace l'intégralité de la balance de vérification."+msgid "Enter number…"msgstr "Entrez un nombre…"@@ -10729,6 +10737,9 @@ msgstr "Masquer la sélection à cette étape"msgid "Hide system quantities until the review step"msgstr "Masquer les quantités système jusqu'à l'étape de revue"+msgid "Hide the items on {label}"+msgstr "Masquer les éléments sur {label}"+msgid "Hide, pin and reorder columns"msgstr "Masquer, épingler et réorganiser les colonnes"@@ -11062,6 +11073,9 @@ msgstr "Code IFSC"msgid "Ignore"msgstr "Ignorer"+msgid "Ignored"+msgstr "Ignoré"+msgid "II (normal default)"msgstr "II (normal par défaut)"@@ -12946,6 +12960,9 @@ msgstr "Mapper les lignes extraites"msgid "Map Lines Now"msgstr "Mapper les lignes maintenant"+msgid "Map these accounts in the {providerName} integration settings and pull again, or enter their balances below."+msgstr "Mettez en correspondance ces comptes dans les paramètres {providerName} et récupérez à nouveau, ou entrez leurs soldes ci-dessous."+msgid "Map your chart of accounts to the provider's. Posting-default and expense accounts are marked Required; posted journals push using the mapped provider account code."msgstr "Mappez votre plan comptable au plan comptable du fournisseur. Les comptes de comptabilisation par défaut et les comptes de charge sont marqués Requis ; les écritures comptabilisées utilisent le code de compte du fournisseur mappé."@@ -15121,8 +15138,8 @@ msgstr "Activé"msgid "On {sentDate}"msgstr "Le {sentDate}"-msgid "On a control account, Carbon opens the balance from its own open items, inventory and fixed assets. The trial balance must agree: every difference stays on Migration Clearing, which must total zero."-msgstr "Sur un compte de contrôle, Carbon établit le solde d'ouverture à partir de ses propres articles ouverts, stocks et immobilisations. La balance d'essai doit concorder : toute différence reste dans le compte de transition, qui doit totaliser zéro."+msgid "On a control account, Carbon opens the balance from its own open items, inventory and fixed assets. The trial balance must agree: every difference stays on Migration Clearing, which must total zero. Open an account to see its items, and ignore an invoice the prior system already settled."+msgstr "Sur un compte de contrôle, Carbon récupère le solde à partir de ses articles non fermés, des stocks et des immobilisations. La balance de vérification doit correspondre : toute différence reste sur Migration Clearing, qui doit totaliser zéro. Ouvrez un compte pour voir ses articles, et ignorez une facture que le système précédent a déjà apurée."msgid "On a transfer kanban, the minimum quantity for the To storage unit. When on-hand plus open inbound transfers drops below it, Carbon creates a Released stock transfer for the kanban quantity."msgstr "Sur un kanban de transfert, la quantité minimale pour l'unité de stockage de destination. Lorsque le stock disponible plus les transferts entrants ouverts descend au-dessous, Carbon crée un transfert de stock lancé pour la quantité du kanban."@@ -17091,6 +17108,9 @@ msgstr "Récupérer"msgid "Pull From"msgstr "Prélever de"+msgid "Pull from {providerName}"+msgstr "Importer depuis {providerName}"+msgid "Pull from accounting"msgstr "Récupérer de la comptabilité"@@ -20182,6 +20202,9 @@ msgstr "Définit le coût auquel cette unité est portée en stocks. La différemsgid "Settings"msgstr "Paramètres"+msgid "Settled in the system that kept the books before the cutover. Carbon leaves them out of its totals and marks them Paid on the day before the cutover when you set up accounting."+msgstr "Apurées dans le système qui tenait les livres avant le basculement. Carbon les exclut de ses totaux et les marque Payées la veille du basculement comptable lorsque vous activez la comptabilité."+msgid "Setup"msgstr "Configuration"@@ -20522,6 +20545,9 @@ msgstr "Afficher les ID fournisseur"msgid "Show sync options"msgstr "Afficher les options de synchronisation"+msgid "Show the items on {label}"+msgstr "Afficher les éléments sur {label}"+msgid "Show Trailing Zeros"msgstr "Afficher les zéros de fin"@@ -20681,6 +20707,9 @@ msgstr "Vendu"msgid "Solutions Engineer"msgstr "Ingénieur Solutions"+msgid "Some balances have no Carbon account"+msgstr "Certains soldes n'ont pas de compte Carbon"+msgid "Some lines are invoiced for more or less than they total. Fix the amounts before confirming."msgstr "Certaines lignes sont facturées pour plus ou moins que leur total. Corriger les montants avant de confirmer."@@ -22049,9 +22078,6 @@ msgstr "Le fichier CSV est vide."msgid "The CSV has no {columns} column."msgstr "Le CSV n'a pas de colonne {columns}."-msgid "The CSV needs the columns accountNumber, debit and credit. An import replaces the whole trial balance."-msgstr "Le CSV nécessite les colonnes accountNumber, débit et crédit. Une importation remplace l'ensemble de la balance de vérification."-msgid "The CSV was not imported"msgstr "Le CSV n'a pas été importé"@@ -23683,9 +23709,8 @@ msgstr "Sujets"msgid "Total"msgstr "Total"-#. placeholder {0}: formatter.format(round(totalDebit - totalCredit))-msgid "Total (out of balance by {0})"-msgstr "Total (écart de {0})"+msgid "Total (out of balance)"+msgstr "Total (non équilibré)"#. placeholder {0}: total.classNamemsgid "Total {0}"diff --git a/packages/locale/locales/hi/erp.po b/packages/locale/locales/hi/erp.poindex 78e69b1200..8498e18810 100644--- a/packages/locale/locales/hi/erp.po+++ b/packages/locale/locales/hi/erp.po@@ -54,6 +54,9 @@ msgstr "(निष्क्रिय खाता)"msgid "(Inactive)"msgstr "(निष्क्रिय)"+msgid "(mapped to more than one Carbon account)"+msgstr "(एक से अधिक Carbon खातों में मैप किया गया)"+msgid "(not an Equity posting account)"msgstr "(इक्विटी पोस्टिंग खाता नहीं है)"@@ -2804,6 +2807,9 @@ msgstr "चालानों पर लागू करें"msgid "Apply to reimbursements"msgstr "प्रतिपूर्ति में लागू करें"+msgid "Apply to Trial Balance"+msgstr "Trial Balance पर लागू करें"+msgid "Applying"msgstr "लागू कर रहे हैं"@@ -3812,6 +3818,10 @@ msgstr "बैकअप"msgid "Balance"msgstr "शेष राशि"+#. placeholder {0}: account.name+msgid "Balance for {0}"+msgstr "{0} के लिए शेष राशि"+msgid "Balance Sheet"msgstr "तुलन पत्र"@@ -6402,10 +6412,6 @@ msgstr "जमा और नामे मेमो"msgid "Credit applied"msgstr "जमा लागू किया गया"-#. placeholder {0}: account.name-msgid "Credit for {0}"-msgstr "{0} के लिए जमा"-msgid "Credit Memo"msgstr "क्रेडिट नोट"@@ -6887,10 +6893,6 @@ msgstr "नामे ({0})"msgid "Debit Account"msgstr "नामे खाता"-#. placeholder {0}: account.name-msgid "Debit for {0}"-msgstr "{0} के लिए नामे"-msgid "Debit Memo"msgstr "डेबिट नोट"@@ -8915,6 +8917,12 @@ msgstr "PO के विरुद्ध विक्रेता बिलोंmsgid "Enter at least one debit and credit"msgstr "कम से कम एक नामे और जमा दर्ज करें"+msgid "Enter debits as positive and credits as negative amounts. The CSV needs the columns accountNumber, debit and credit. An import or a pull from {providerName} replaces the whole trial balance."+msgstr "डेबिट्स को सकारात्मक और क्रेडिट्स को नकारात्मक राशि के रूप में दर्ज करें। CSV को accountNumber, नामे और जमा कॉलम की आवश्यकता है। एक आयात या {providerName} से खींचना पूरे trial balance को प्रतिस्थापित करता है।"++msgid "Enter debits as positive and credits as negative amounts. The CSV needs the columns accountNumber, debit and credit. An import replaces the whole trial balance."+msgstr "डेबिट्स को सकारात्मक और क्रेडिट्स को नकारात्मक राशि के रूप में दर्ज करें। CSV को accountNumber, नामे और जमा कॉलम की आवश्यकता है। एक आयात पूरे trial balance को प्रतिस्थापित करता है।"+msgid "Enter number…"msgstr "संख्या दर्ज करें…"@@ -10729,6 +10737,9 @@ msgstr "इस चरण पर चयनित को छिपाएँ"msgid "Hide system quantities until the review step"msgstr "समीक्षा चरण तक सिस्टम मात्रा को छिपाएं"+msgid "Hide the items on {label}"+msgstr "{label} पर आइटम्स को छिपाएं"+msgid "Hide, pin and reorder columns"msgstr "कॉलम को छिपाएं, पिन करें और पुनः क्रमित करें"@@ -11062,6 +11073,9 @@ msgstr "IFSC कोड"msgid "Ignore"msgstr "अनदेखा करें"+msgid "Ignored"+msgstr "अनदेखा किया गया"+msgid "II (normal default)"msgstr "II (सामान्य डिफ़ॉल्ट)"@@ -12946,6 +12960,9 @@ msgstr "निकाली गई लाइनों को मैप करेmsgid "Map Lines Now"msgstr "अभी लाइनें मैप करें"+msgid "Map these accounts in the {providerName} integration settings and pull again, or enter their balances below."+msgstr "{providerName} एकीकरण सेटिंग्स में इन खातों को मैप करें और फिर से खींचें, या नीचे उनकी शेष राशि दर्ज करें।"+msgid "Map your chart of accounts to the provider's. Posting-default and expense accounts are marked Required; posted journals push using the mapped provider account code."msgstr "अपने खातों का चार्ट को प्रदाता के साथ मैप करें। पोस्टिंग-डिफ़ॉल्ट और व्यय खाते आवश्यक के रूप में चिह्नित हैं; पोस्ट किए गए जर्नल मैप किए गए प्रदाता खाता कोड का उपयोग करके पुश किए जाते हैं।"@@ -15121,8 +15138,8 @@ msgstr "चालू"msgid "On {sentDate}"msgstr "{sentDate} को"-msgid "On a control account, Carbon opens the balance from its own open items, inventory and fixed assets. The trial balance must agree: every difference stays on Migration Clearing, which must total zero."-msgstr "एक नियंत्रण खाते पर, कार्बन अपने खुली आइटम, इन्वेंटरी और अचल संपत्ति से शेष राशि खोलता है। ट्रायल बैलेंस सहमत होना चाहिए: हर अंतर माइग्रेशन साफी पर रहता है, जो शून्य होना चाहिए।"+msgid "On a control account, Carbon opens the balance from its own open items, inventory and fixed assets. The trial balance must agree: every difference stays on Migration Clearing, which must total zero. Open an account to see its items, and ignore an invoice the prior system already settled."+msgstr "एक नियंत्रण खाते पर, Carbon अपने खुले आइटम्स, इन्वेंटरी और अचल संपत्ति से शेष राशि निकालता है। Trial balance सहमत होना चाहिए: हर अंतर Migration Clearing पर रहता है, जो शून्य होना चाहिए। एक खाता खोलें इसके आइटम्स को देखने के लिए, और एक चालान को अनदेखा करें जो पूर्व प्रणाली पहले ही निपटा चुकी है।"msgid "On a transfer kanban, the minimum quantity for the To storage unit. When on-hand plus open inbound transfers drops below it, Carbon creates a Released stock transfer for the kanban quantity."msgstr "एक स्थानांतरण कानबान पर, To भंडारण इकाई के लिए न्यूनतम मात्रा। जब हाथ पर प्लस खुली आने वाली स्थानांतरण इससे नीचे चली जाती है, तो Carbon कानबान मात्रा के लिए एक जारी स्टॉक स्थानांतरण बनाता है।"@@ -17091,6 +17108,9 @@ msgstr "खींचें"msgid "Pull From"msgstr "से खींचें"+msgid "Pull from {providerName}"+msgstr "{providerName} से खींचें"+msgid "Pull from accounting"msgstr "लेखांकन से खींचें"@@ -20182,6 +20202,9 @@ msgstr "यह निर्धारित करता है कि यह इmsgid "Settings"msgstr "सेटिंग्स"+msgid "Settled in the system that kept the books before the cutover. Carbon leaves them out of its totals and marks them Paid on the day before the cutover when you set up accounting."+msgstr "कटऑफ से पहले बहीयां रखने वाली प्रणाली में निपटाए गए। Carbon उन्हें अपने योग से बाहर छोड़ देता है और कटऑफ से एक दिन पहले उन्हें भुगतान किया गया के रूप में चिह्नित करता है जब आप लेखांकन सेटअप करते हैं।"+msgid "Setup"msgstr "सेटअप"@@ -20522,6 +20545,9 @@ msgstr "आपूर्तिकर्ता आईडी दिखाएं"msgid "Show sync options"msgstr "सिंक विकल्प दिखाएं"+msgid "Show the items on {label}"+msgstr "{label} पर आइटम्स दिखाएं"+msgid "Show Trailing Zeros"msgstr "अनुगामी शून्य दिखाएं"@@ -20681,6 +20707,9 @@ msgstr "बेचा गया"msgid "Solutions Engineer"msgstr "समाधान इंजीनियर"+msgid "Some balances have no Carbon account"+msgstr "कुछ शेष राशियों के लिए कोई Carbon खाता नहीं है"+msgid "Some lines are invoiced for more or less than they total. Fix the amounts before confirming."msgstr "कुछ पंक्तियों को उनकी कुल से अधिक या कम के लिए चालान दिया गया है। पुष्टि करने से पहले राशियों को ठीक करें।"@@ -22049,9 +22078,6 @@ msgstr "CSV फ़ाइल खाली है।"msgid "The CSV has no {columns} column."msgstr "CSV के पास कोई {columns} कॉलम नहीं है।"-msgid "The CSV needs the columns accountNumber, debit and credit. An import replaces the whole trial balance."-msgstr "CSV को accountNumber, नामे और जमा कॉलम की आवश्यकता है। आयात पूरे trial balance को बदल देता है।"-msgid "The CSV was not imported"msgstr "CSV को आयात नहीं किया गया था।"@@ -23683,9 +23709,8 @@ msgstr "विषय"msgid "Total"msgstr "कुल"-#. placeholder {0}: formatter.format(round(totalDebit - totalCredit))-msgid "Total (out of balance by {0})"-msgstr "कुल (असंतुलित {0} द्वारा)"+msgid "Total (out of balance)"+msgstr "कुल (असंतुलित)"#. placeholder {0}: total.classNamemsgid "Total {0}"diff --git a/packages/locale/locales/it/erp.po b/packages/locale/locales/it/erp.poindex 9144d9712a..47371b81e0 100644--- a/packages/locale/locales/it/erp.po+++ b/packages/locale/locales/it/erp.po@@ -54,6 +54,9 @@ msgstr "(conto inattivo)"msgid "(Inactive)"msgstr "(Inattivo)"+msgid "(mapped to more than one Carbon account)"+msgstr "(associato a più di un account Carbon)"+msgid "(not an Equity posting account)"msgstr "(non un account di registrazione Patrimonio netto)"@@ -2804,6 +2807,9 @@ msgstr "Applica alle fatture"msgid "Apply to reimbursements"msgstr "Applica ai rimborsi"+msgid "Apply to Trial Balance"+msgstr "Applica al Bilancio di Verifica"+msgid "Applying"msgstr "Applicazione in corso"@@ -3812,6 +3818,10 @@ msgstr "Backup"msgid "Balance"msgstr "Saldo"+#. placeholder {0}: account.name+msgid "Balance for {0}"+msgstr "Saldo per {0}"+msgid "Balance Sheet"msgstr "Stato patrimoniale"@@ -6402,10 +6412,6 @@ msgstr "Note di credito e di addebito"msgid "Credit applied"msgstr "Avere applicato"-#. placeholder {0}: account.name-msgid "Credit for {0}"-msgstr "Avere per {0}"-msgid "Credit Memo"msgstr "Nota di Credito"@@ -6887,10 +6893,6 @@ msgstr "Dare ({0})"msgid "Debit Account"msgstr "Conto addebito"-#. placeholder {0}: account.name-msgid "Debit for {0}"-msgstr "Dare per {0}"-msgid "Debit Memo"msgstr "Nota di debito"@@ -8915,6 +8917,12 @@ msgstr "Inserire e Approvare Fatture di acquisto in base a un Ordine di acquistomsgid "Enter at least one debit and credit"msgstr "Inserisci almeno un dare e un avere"+msgid "Enter debits as positive and credits as negative amounts. The CSV needs the columns accountNumber, debit and credit. An import or a pull from {providerName} replaces the whole trial balance."+msgstr "Inserisci i dare come importi positivi e gli avere come importi negativi. Il file CSV deve contenere le colonne accountNumber, dare e avere. Un'importazione o un estrazione da {providerName} sostituisce l'intero bilancio di verifica."++msgid "Enter debits as positive and credits as negative amounts. The CSV needs the columns accountNumber, debit and credit. An import replaces the whole trial balance."+msgstr "Inserisci i dare come importi positivi e gli avere come importi negativi. Il file CSV deve contenere le colonne accountNumber, dare e avere. Un'importazione sostituisce l'intero bilancio di verifica."+msgid "Enter number…"msgstr "Inserisci numero…"@@ -10729,6 +10737,9 @@ msgstr "Nascondi selezionati in questo passo"msgid "Hide system quantities until the review step"msgstr "Nascondi le quantità di sistema fino al passaggio di revisione"+msgid "Hide the items on {label}"+msgstr "Nascondi gli articoli su {label}"+msgid "Hide, pin and reorder columns"msgstr "Nascondi, fissa e riordina le colonne"@@ -11062,6 +11073,9 @@ msgstr "Codice IFSC"msgid "Ignore"msgstr "Ignora"+msgid "Ignored"+msgstr "Ignorato"+msgid "II (normal default)"msgstr "II (normale predefinito)"@@ -12946,6 +12960,9 @@ msgstr "Mappa Righe Estratte"msgid "Map Lines Now"msgstr "Mappa Righe Ora"+msgid "Map these accounts in the {providerName} integration settings and pull again, or enter their balances below."+msgstr "Associa questi account nelle impostazioni di integrazione {providerName} ed estrai di nuovo, oppure inserisci i loro saldi di seguito."+msgid "Map your chart of accounts to the provider's. Posting-default and expense accounts are marked Required; posted journals push using the mapped provider account code."msgstr "Associa il tuo piano dei conti a quello del provider. I conti di registrazione predefiniti e i conti spese sono contrassegnati come Obbligatori; la prima nota registrata viene inviata utilizzando il codice conto provider associato."@@ -15121,8 +15138,8 @@ msgstr "Attivato"msgid "On {sentDate}"msgstr "Acceso"-msgid "On a control account, Carbon opens the balance from its own open items, inventory and fixed assets. The trial balance must agree: every difference stays on Migration Clearing, which must total zero."-msgstr "Su un conto di controllo, Carbon apre il saldo dai propri articoli aperti, magazzino e cespiti. Il bilancio di verifica deve corrispondere: ogni differenza rimane sulla compensazione della migrazione, che deve essere a zero."+msgid "On a control account, Carbon opens the balance from its own open items, inventory and fixed assets. The trial balance must agree: every difference stays on Migration Clearing, which must total zero. Open an account to see its items, and ignore an invoice the prior system already settled."+msgstr "Su un conto di controllo, Carbon apre il saldo dalle sue partite aperte, magazzino e cespiti. Il bilancio di verifica deve corrispondere: ogni differenza rimane su Migration Clearing, che deve sommare a zero. Apri un account per vederne gli articoli, e ignora una fattura che il sistema precedente ha già liquidato."msgid "On a transfer kanban, the minimum quantity for the To storage unit. When on-hand plus open inbound transfers drops below it, Carbon creates a Released stock transfer for the kanban quantity."msgstr "Su un kanban di trasferimento, la quantità minima per l'unità di stoccaggio di destinazione. Quando la giacenza più i trasferimenti in entrata aperti scendono al di sotto di essa, Carbon crea un trasferimento di giacenza Autorizzato per la quantità del kanban."@@ -17091,6 +17108,9 @@ msgstr "Estrai"msgid "Pull From"msgstr "Preleva da"+msgid "Pull from {providerName}"+msgstr "Estrai da {providerName}"+msgid "Pull from accounting"msgstr "Estrai dalla contabilità"@@ -20182,6 +20202,9 @@ msgstr "Definisce il valore con cui questa unità è riportata nel magazzino. Lamsgid "Settings"msgstr "Impostazioni"+msgid "Settled in the system that kept the books before the cutover. Carbon leaves them out of its totals and marks them Paid on the day before the cutover when you set up accounting."+msgstr "Liquidato nel sistema che ha tenuto i libri prima del cambio. Carbon li esclude dai suoi totali e li contrassegna come Pagati il giorno prima del cambio quando configuri la contabilità."+msgid "Setup"msgstr "Configurazione"@@ -20522,6 +20545,9 @@ msgstr "Mostra ID Fornitore"msgid "Show sync options"msgstr "Mostra opzioni di sincronizzazione"+msgid "Show the items on {label}"+msgstr "Mostra gli articoli su {label}"+msgid "Show Trailing Zeros"msgstr "Mostra Zeri Finali"@@ -20681,6 +20707,9 @@ msgstr "Venduto"msgid "Solutions Engineer"msgstr "Solutions Engineer"+msgid "Some balances have no Carbon account"+msgstr "Alcuni saldi non hanno un account Carbon"+msgid "Some lines are invoiced for more or less than they total. Fix the amounts before confirming."msgstr "Alcune righe sono fatturate per più o meno di quanto ammontano. Correggi gli importi prima di confermare."@@ -22049,9 +22078,6 @@ msgstr "Il file CSV è vuoto."msgid "The CSV has no {columns} column."msgstr "Il CSV non ha la colonna {columns}."-msgid "The CSV needs the columns accountNumber, debit and credit. An import replaces the whole trial balance."-msgstr "Il CSV necessita delle colonne accountNumber, Dare e Avere. Un'importazione sostituisce l'intera bilancia di verifica."-msgid "The CSV was not imported"msgstr "Il CSV non è stato importato"@@ -23683,9 +23709,8 @@ msgstr "Argomenti"msgid "Total"msgstr "Totale"-#. placeholder {0}: formatter.format(round(totalDebit - totalCredit))-msgid "Total (out of balance by {0})"-msgstr "Totale (sbilanciato di {0})"+msgid "Total (out of balance)"+msgstr "Totale (fuori bilancio)"#. placeholder {0}: total.classNamemsgid "Total {0}"diff --git a/packages/locale/locales/ja/erp.po b/packages/locale/locales/ja/erp.poindex 1177753637..aaae636805 100644--- a/packages/locale/locales/ja/erp.po+++ b/packages/locale/locales/ja/erp.po@@ -54,6 +54,9 @@ msgstr "(無効な勘定)"msgid "(Inactive)"msgstr "(無効)"+msgid "(mapped to more than one Carbon account)"+msgstr "(複数のCarbonアカウントにマップされています)"+msgid "(not an Equity posting account)"msgstr "(純資産転記勘定科目ではありません)"@@ -2804,6 +2807,9 @@ msgstr "請求書に適用"msgid "Apply to reimbursements"msgstr "払戻に充当する"+msgid "Apply to Trial Balance"+msgstr "試算表に適用"+msgid "Applying"msgstr "適用中"@@ -3812,6 +3818,10 @@ msgstr "バックアップ"msgid "Balance"msgstr "残高"+#. placeholder {0}: account.name+msgid "Balance for {0}"+msgstr "{0}の残高"+msgid "Balance Sheet"msgstr "貸借対照表"@@ -6402,10 +6412,6 @@ msgstr "クレジットメモとデビットメモ"msgid "Credit applied"msgstr "貸方が適用されました"-#. placeholder {0}: account.name-msgid "Credit for {0}"-msgstr "{0}の貸方"-msgid "Credit Memo"msgstr "クレジットメモ"@@ -6887,10 +6893,6 @@ msgstr "借方 ({0})"msgid "Debit Account"msgstr "借方勘定"-#. placeholder {0}: account.name-msgid "Debit for {0}"-msgstr "{0}の借方"-msgid "Debit Memo"msgstr "借方メモ"@@ -8915,6 +8917,12 @@ msgstr "発注書に対する仕入先請求書を入力して承認します(msgid "Enter at least one debit and credit"msgstr "少なくとも1つの借方と貸方を入力してください"+msgid "Enter debits as positive and credits as negative amounts. The CSV needs the columns accountNumber, debit and credit. An import or a pull from {providerName} replaces the whole trial balance."+msgstr "借方を正の数で、貸方を負の数で入力してください。CSVには accountNumber、debit、credit の列が必要です。インポートまたは{providerName}からのプルにより、試算表全体が置き換わります。"++msgid "Enter debits as positive and credits as negative amounts. The CSV needs the columns accountNumber, debit and credit. An import replaces the whole trial balance."+msgstr "借方を正の数で、貸方を負の数で入力してください。CSVには accountNumber、debit、credit の列が必要です。インポートにより、試算表全体が置き換わります。"+msgid "Enter number…"msgstr "数字を入力..."@@ -10729,6 +10737,9 @@ msgstr "選択したものをこのステップで非表示"msgid "Hide system quantities until the review step"msgstr "レビューステップまでシステム数量を非表示にする"+msgid "Hide the items on {label}"+msgstr "{label}の品目を非表示にする"+msgid "Hide, pin and reorder columns"msgstr "列を非表示、ピン留め、並び替え"@@ -11062,6 +11073,9 @@ msgstr "IFSC コード"msgid "Ignore"msgstr "無視"+msgid "Ignored"+msgstr "無視"+msgid "II (normal default)"msgstr "II(通常デフォルト)"@@ -12946,6 +12960,9 @@ msgstr "抽出行をマップ"msgid "Map Lines Now"msgstr "今すぐラインをマップ"+msgid "Map these accounts in the {providerName} integration settings and pull again, or enter their balances below."+msgstr "これらのアカウントを{providerName}の連携設定でマップしてからもう一度プルするか、以下に残高を入力してください。"+msgid "Map your chart of accounts to the provider's. Posting-default and expense accounts are marked Required; posted journals push using the mapped provider account code."msgstr "勘定科目表をプロバイダーの表にマップしてください。転記用デフォルト科目と費用科目は「必須」とマークされています。転記済の仕訳はマップされたプロバイダー科目を使用して送信されます。"@@ -15121,8 +15138,8 @@ msgstr "オン"msgid "On {sentDate}"msgstr "{sentDate}に送信"-msgid "On a control account, Carbon opens the balance from its own open items, inventory and fixed assets. The trial balance must agree: every difference stays on Migration Clearing, which must total zero."-msgstr "管理勘定では、Carbonが未決済品目、在庫、固定資産から残高を決定します。試算表は一致する必要があります。すべての差異はマイグレーションクリアリングに留まり、合計はゼロである必要があります。"+msgid "On a control account, Carbon opens the balance from its own open items, inventory and fixed assets. The trial balance must agree: every difference stays on Migration Clearing, which must total zero. Open an account to see its items, and ignore an invoice the prior system already settled."+msgstr "管理勘定では、Carbonはその独自のオープン品目、在庫管理、および固定資産から残高を開きます。試算表は一致する必要があります。すべての差異は移行クリアリングに留まり、合計がゼロになる必要があります。勘定を開いてその品目を確認し、前のシステムで既に決済された請求書を無視してください。"msgid "On a transfer kanban, the minimum quantity for the To storage unit. When on-hand plus open inbound transfers drops below it, Carbon creates a Released stock transfer for the kanban quantity."msgstr "転送かんばんでは、宛先保管ユニットの最小数量です。手持ちプラス未処理の受信転送がそれ以下に落ちると、Carbon はかんばん数量のためにリリース済の在庫転送を作成します。"@@ -17091,6 +17108,9 @@ msgstr "プル"msgid "Pull From"msgstr "から取得"+msgid "Pull from {providerName}"+msgstr "{providerName}からプル"+msgid "Pull from accounting"msgstr "会計から引き出す"@@ -20182,6 +20202,9 @@ msgstr "この個が在庫で計上されている価値を設定します。差msgid "Settings"msgstr "設定"+msgid "Settled in the system that kept the books before the cutover. Carbon leaves them out of its totals and marks them Paid on the day before the cutover when you set up accounting."+msgstr "カットオーバー前に帳簿をつけていたシステムで決済されています。Carbonはそれらを合計から除外し、会計をセットアップするときにカットオーバーの前日に支払い済みとしてマークします。"+msgid "Setup"msgstr "セットアップ"@@ -20522,6 +20545,9 @@ msgstr "仕入先IDを表示"msgid "Show sync options"msgstr "同期オプションを表示"+msgid "Show the items on {label}"+msgstr "{label}の品目を表示"+msgid "Show Trailing Zeros"msgstr "末尾のゼロを表示"@@ -20681,6 +20707,9 @@ msgstr "売却"msgid "Solutions Engineer"msgstr "ソリューションズエンジニア"+msgid "Some balances have no Carbon account"+msgstr "いくつかの残高にはCarbonアカウントがありません"+msgid "Some lines are invoiced for more or less than they total. Fix the amounts before confirming."msgstr "いくつかの明細は、合計より多くまたは少なく請求されています。確認する前に金額を修正してください。"@@ -22049,9 +22078,6 @@ msgstr "CSV ファイルが空です。"msgid "The CSV has no {columns} column."msgstr "CSV に {columns} 列がありません。"-msgid "The CSV needs the columns accountNumber, debit and credit. An import replaces the whole trial balance."-msgstr "CSVには、accountNumber、借方、貸方のカラムが必要です。インポートは試算表全体を置き換えます。"-msgid "The CSV was not imported"msgstr "CSVはインポートされませんでした。"@@ -23683,9 +23709,8 @@ msgstr "トピック"msgid "Total"msgstr "合計"-#. placeholder {0}: formatter.format(round(totalDebit - totalCredit))-msgid "Total (out of balance by {0})"-msgstr "合計({0}だけ不一致)"+msgid "Total (out of balance)"+msgstr "合計(残高不一致)"#. placeholder {0}: total.classNamemsgid "Total {0}"diff --git a/packages/locale/locales/ko/erp.po b/packages/locale/locales/ko/erp.poindex 8eb20be059..390af6e205 100644--- a/packages/locale/locales/ko/erp.po+++ b/packages/locale/locales/ko/erp.po@@ -54,6 +54,9 @@ msgstr "(비활성 계정)"msgid "(Inactive)"msgstr "(비활성)"+msgid "(mapped to more than one Carbon account)"+msgstr "(하나 이상의 Carbon 계정에 매핑됨)"+msgid "(not an Equity posting account)"msgstr "(자본 전기 계정이 아님)"@@ -2804,6 +2807,9 @@ msgstr "송장에 적용"msgid "Apply to reimbursements"msgstr "환급금에 배정"+msgid "Apply to Trial Balance"+msgstr "시산표에 적용"+msgid "Applying"msgstr "적용 중"@@ -3812,6 +3818,10 @@ msgstr "백업"msgid "Balance"msgstr "잔액"+#. placeholder {0}: account.name+msgid "Balance for {0}"+msgstr "{0}의 잔액"+msgid "Balance Sheet"msgstr "재무상태표"@@ -6402,10 +6412,6 @@ msgstr "신용 메모 및 차변 메모"msgid "Credit applied"msgstr "대변 적용됨"-#. placeholder {0}: account.name-msgid "Credit for {0}"-msgstr "{0}의 대변"-msgid "Credit Memo"msgstr "대변전표"@@ -6887,10 +6893,6 @@ msgstr "차변 ({0})"msgid "Debit Account"msgstr "차변 계정"-#. placeholder {0}: account.name-msgid "Debit for {0}"-msgstr "{0}의 차변"-msgid "Debit Memo"msgstr "차변전표"@@ -8915,6 +8917,12 @@ msgstr "PO에 대한 공급업체 청구서를 입력하고 승인하세요 (3msgid "Enter at least one debit and credit"msgstr "차변과 대변을 각각 하나 이상 입력하세요."+msgid "Enter debits as positive and credits as negative amounts. The CSV needs the columns accountNumber, debit and credit. An import or a pull from {providerName} replaces the whole trial balance."+msgstr "차변을 양수로, 대변을 음수로 입력하세요. CSV는 accountNumber, debit, credit 열이 필요합니다. 가져오기 또는 {providerName}에서 끌어오기는 전체 시산표를 바꿉니다."++msgid "Enter debits as positive and credits as negative amounts. The CSV needs the columns accountNumber, debit and credit. An import replaces the whole trial balance."+msgstr "차변을 양수로, 대변을 음수로 입력하세요. CSV는 accountNumber, debit, credit 열이 필요합니다. 가져오기는 전체 시산표를 바꿉니다."+msgid "Enter number…"msgstr "숫자 입력…"@@ -10729,6 +10737,9 @@ msgstr "이 단계에서 선택된 항목 숨기기"msgid "Hide system quantities until the review step"msgstr "검토 단계 전까지 시스템 수량 숨기기"+msgid "Hide the items on {label}"+msgstr "{label}의 항목 숨기기"+msgid "Hide, pin and reorder columns"msgstr "열 숨기기, 고정, 순서 변경"@@ -11062,6 +11073,9 @@ msgstr "IFSC 코드"msgid "Ignore"msgstr "무시"+msgid "Ignored"+msgstr "무시됨"+msgid "II (normal default)"msgstr "II(일반 기본값)"@@ -12946,6 +12960,9 @@ msgstr "추출된 라인 매핑"msgid "Map Lines Now"msgstr "지금 라인 매핑"+msgid "Map these accounts in the {providerName} integration settings and pull again, or enter their balances below."+msgstr "이 계정들을 {providerName} 연동 설정에서 매핑한 후 다시 끌어오기하거나, 아래에 잔액을 입력하세요."+msgid "Map your chart of accounts to the provider's. Posting-default and expense accounts are marked Required; posted journals push using the mapped provider account code."msgstr "계정과목표를 공급자와 매핑하세요. 전기 기본 및 비용 계정은 필수로 표시되며, 전기된 전표는 매핑된 공급자 계정 코드를 사용하여 전송됩니다."@@ -15121,8 +15138,8 @@ msgstr "켜짐"msgid "On {sentDate}"msgstr "켬"-msgid "On a control account, Carbon opens the balance from its own open items, inventory and fixed assets. The trial balance must agree: every difference stays on Migration Clearing, which must total zero."-msgstr "제어 계정에서 Carbon은 자신의 미결 항목, 재고 및 고정자산에서 잔액을 개설합니다. 시산표가 일치해야 합니다. 모든 차이는 마이그레이션 정산에 유지되며, 이는 합계가 0이어야 합니다."+msgid "On a control account, Carbon opens the balance from its own open items, inventory and fixed assets. The trial balance must agree: every difference stays on Migration Clearing, which must total zero. Open an account to see its items, and ignore an invoice the prior system already settled."+msgstr "통제 계정에서 Carbon은 자신의 미결 항목, 재고 관리 및 고정자산에서 잔액을 가져옵니다. 시산표는 일치해야 합니다. 모든 차이는 Migration Clearing에 남으며, 이는 총계가 0이어야 합니다. 계정을 열어 항목을 확인하고, 이전 시스템에서 이미 정산된 송장은 무시하세요."msgid "On a transfer kanban, the minimum quantity for the To storage unit. When on-hand plus open inbound transfers drops below it, Carbon creates a Released stock transfer for the kanban quantity."msgstr "이송 칸반에서 도착 보관 단위의 최소 수량입니다. 현재 재고와 미결 인바운드 이송의 합이 이 수준 아래로 내려가면, Carbon은 칸반 수량만큼의 릴리스됨 재고 이송을 생성합니다."@@ -17091,6 +17108,9 @@ msgstr "가져오기"msgid "Pull From"msgstr "가져오기 출처"+msgid "Pull from {providerName}"+msgstr "{providerName}에서 끌어오기"+msgid "Pull from accounting"msgstr "회계에서 가져오기"@@ -20182,6 +20202,9 @@ msgstr "이 자산의 재고 계상 금액을 설정합니다. 차이는 재고msgid "Settings"msgstr "설정"+msgid "Settled in the system that kept the books before the cutover. Carbon leaves them out of its totals and marks them Paid on the day before the cutover when you set up accounting."+msgstr "전환 전에 장부를 관리하던 시스템에서 정산됨. Carbon은 이들을 총계에서 제외하고, 회계를 설정할 때 전환 전날에 결제됨으로 표시합니다."+msgid "Setup"msgstr "설정"@@ -20522,6 +20545,9 @@ msgstr "공급업체 ID 표시"msgid "Show sync options"msgstr "동기화 옵션 표시"+msgid "Show the items on {label}"+msgstr "{label}의 항목 표시"+msgid "Show Trailing Zeros"msgstr "후행 0 표시"@@ -20681,6 +20707,9 @@ msgstr "판매됨"msgid "Solutions Engineer"msgstr "솔루션 엔지니어"+msgid "Some balances have no Carbon account"+msgstr "일부 잔액에는 Carbon 계정이 없습니다"+msgid "Some lines are invoiced for more or less than they total. Fix the amounts before confirming."msgstr "일부 라인의 송장 발행액이 총계보다 많거나 적습니다. 확인하기 전에 금액을 수정하세요."@@ -22049,9 +22078,6 @@ msgstr "CSV 파일이 비어있습니다."msgid "The CSV has no {columns} column."msgstr "CSV에 {columns} 열이 없습니다."-msgid "The CSV needs the columns accountNumber, debit and credit. An import replaces the whole trial balance."-msgstr "CSV에는 accountNumber, 차변, 대변 열이 필요합니다. 가져오기는 전체 시산표를 교체합니다."-msgid "The CSV was not imported"msgstr "CSV를 가져오지 못했습니다."@@ -23683,9 +23709,8 @@ msgstr "주제"msgid "Total"msgstr "합계"-#. placeholder {0}: formatter.format(round(totalDebit - totalCredit))-msgid "Total (out of balance by {0})"-msgstr "총계 ({0}만큼 차이남)"+msgid "Total (out of balance)"+msgstr "총계 (불균형)"#. placeholder {0}: total.classNamemsgid "Total {0}"diff --git a/packages/locale/locales/pl/erp.po b/packages/locale/locales/pl/erp.poindex b79499d7aa..5fb60e6481 100644--- a/packages/locale/locales/pl/erp.po+++ b/packages/locale/locales/pl/erp.po@@ -54,6 +54,9 @@ msgstr "(nieaktywne konto)"msgid "(Inactive)"msgstr "(Nieaktywny)"+msgid "(mapped to more than one Carbon account)"+msgstr "(zmapowane na więcej niż jedno konto Carbon)"+msgid "(not an Equity posting account)"msgstr "(nie jest kontem Kapitału własnego do księgowania)"@@ -2804,6 +2807,9 @@ msgstr "Zastosuj do faktur"msgid "Apply to reimbursements"msgstr "Zastosuj do zwrotów kosztów"+msgid "Apply to Trial Balance"+msgstr "Zastosuj do Bilansu Otwarcia"+msgid "Applying"msgstr "Stosowanie"@@ -3812,6 +3818,10 @@ msgstr "Kopie zapasowe"msgid "Balance"msgstr "Saldo"+#. placeholder {0}: account.name+msgid "Balance for {0}"+msgstr "Saldo dla {0}"+msgid "Balance Sheet"msgstr "Bilans"@@ -6402,10 +6412,6 @@ msgstr "Noty kredytowe i debetowe"msgid "Credit applied"msgstr "Kredyt zastosowany"-#. placeholder {0}: account.name-msgid "Credit for {0}"-msgstr "Ma dla {0}"-msgid "Credit Memo"msgstr "Faktura korygująca"@@ -6887,10 +6893,6 @@ msgstr "Winien ({0})"msgid "Debit Account"msgstr "Konto Winien"-#. placeholder {0}: account.name-msgid "Debit for {0}"-msgstr "Winien dla {0}"-msgid "Debit Memo"msgstr "Nota debetowa"@@ -8915,6 +8917,12 @@ msgstr "Wprowadź i zatwierdź faktury od dostawców względem zamówienia zakupmsgid "Enter at least one debit and credit"msgstr "Wprowadź co najmniej jeden Winien i jeden Ma"+msgid "Enter debits as positive and credits as negative amounts. The CSV needs the columns accountNumber, debit and credit. An import or a pull from {providerName} replaces the whole trial balance."+msgstr "Wpisz debety jako wartości dodatnie, a kredyty jako wartości ujemne. CSV musi zawierać kolumny accountNumber, debit i credit. Import lub pobranie z {providerName} zastępuje całe saldo otwarcia."++msgid "Enter debits as positive and credits as negative amounts. The CSV needs the columns accountNumber, debit and credit. An import replaces the whole trial balance."+msgstr "Wpisz debety jako wartości dodatnie, a kredyty jako wartości ujemne. CSV musi zawierać kolumny accountNumber, debit i credit. Import zastępuje całe saldo otwarcia."+msgid "Enter number…"msgstr "Wprowadź liczbę…"@@ -10729,6 +10737,9 @@ msgstr "Ukryj zaznaczenie na tym kroku"msgid "Hide system quantities until the review step"msgstr "Ukryj ilości systemowe do kroku przeglądu"+msgid "Hide the items on {label}"+msgstr "Ukryj artykuły na {label}"+msgid "Hide, pin and reorder columns"msgstr "Ukryj, przypnij i zmień kolejność kolumn"@@ -11062,6 +11073,9 @@ msgstr "Kod IFSC"msgid "Ignore"msgstr "Ignoruj"+msgid "Ignored"+msgstr "Ignorowane"+msgid "II (normal default)"msgstr "II (normalne domyślne)"@@ -12946,6 +12960,9 @@ msgstr "Mapuj Wyodrębnione Linie"msgid "Map Lines Now"msgstr "Mapuj linie teraz"+msgid "Map these accounts in the {providerName} integration settings and pull again, or enter their balances below."+msgstr "Zmapuj te konta w ustawieniach integracji {providerName} i pobierz ponownie lub wpisz ich salda poniżej."+msgid "Map your chart of accounts to the provider's. Posting-default and expense accounts are marked Required; posted journals push using the mapped provider account code."msgstr "Zmapuj swój plan kont na plan kont dostawcy. Konta domyślne dla księgowania i wydatkowe są oznaczone jako Wymagane; zaksięgowane dowody księgowe będą wysyłane przy użyciu zmapowanego kodu konta dostawcy."@@ -15121,8 +15138,8 @@ msgstr "Włączone"msgid "On {sentDate}"msgstr "W dniu {sentDate}"-msgid "On a control account, Carbon opens the balance from its own open items, inventory and fixed assets. The trial balance must agree: every difference stays on Migration Clearing, which must total zero."-msgstr "Na koncie kontrolnym Carbon otwiera saldo na podstawie własnych pozycji otwartych, zapasów i środków trwałych. Bilans próbny musi się zgadzać: każda różnica pozostaje na koncie Przejście Migracji, które musi sumować się do zera."+msgid "On a control account, Carbon opens the balance from its own open items, inventory and fixed assets. The trial balance must agree: every difference stays on Migration Clearing, which must total zero. Open an account to see its items, and ignore an invoice the prior system already settled."+msgstr "Na koncie kontrolnym Carbon otwiera saldo ze swoich otwartych artykułów, zapasów i środków trwałych. Bilans otwarcia musi się zgadzać: każda różnica pozostaje na Migration Clearing, które musi wynosić zero. Otwórz konto, aby zobaczyć jego artykuły, i zignoruj fakturę rozliczoną przez poprzedni system."msgid "On a transfer kanban, the minimum quantity for the To storage unit. When on-hand plus open inbound transfers drops below it, Carbon creates a Released stock transfer for the kanban quantity."msgstr "W kanban transferu minimalna ilość dla jednostki magazynowej docelowej. Gdy zapas dostępny plus otwarte przychodzące przesunięcia spadną poniżej tej wartości, Carbon tworzy zwolnione przesunięcie zapasu dla ilości kanban."@@ -17091,6 +17108,9 @@ msgstr "Pobierz"msgid "Pull From"msgstr "Pobierz z"+msgid "Pull from {providerName}"+msgstr "Pobierz z {providerName}"+msgid "Pull from accounting"msgstr "Pobierz z systemu księgowego"@@ -20182,6 +20202,9 @@ msgstr "Ustawia, za ile ta sztuka jest wyceniana w zapasach. Różnica jest ksimsgid "Settings"msgstr "Ustawienia"+msgid "Settled in the system that kept the books before the cutover. Carbon leaves them out of its totals and marks them Paid on the day before the cutover when you set up accounting."+msgstr "Rozliczone w systemie, który prowadził księgi przed przejściem. Carbon wyklucza je ze swoich sum i oznacza je jako Zapłacone na dzień przed przejściem, gdy skonfigurujesz księgowość."+msgid "Setup"msgstr "Konfiguracja"@@ -20522,6 +20545,9 @@ msgstr "Pokaż identyfikatory dostawców"msgid "Show sync options"msgstr "Pokaż opcje synchronizacji"+msgid "Show the items on {label}"+msgstr "Pokaż artykuły na {label}"+msgid "Show Trailing Zeros"msgstr "Wyświetlaj zera końcowe"@@ -20681,6 +20707,9 @@ msgstr "Sprzedane"msgid "Solutions Engineer"msgstr "Inżynier Rozwiązań"+msgid "Some balances have no Carbon account"+msgstr "Niektóre salda nie mają konta Carbon"+msgid "Some lines are invoiced for more or less than they total. Fix the amounts before confirming."msgstr "Niektóre pozycje są zafakturowane za więcej lub mniej niż wynoszą ich sumy. Popraw kwoty przed potwierdzeniem."@@ -22049,9 +22078,6 @@ msgstr "Plik CSV jest pusty."msgid "The CSV has no {columns} column."msgstr "Plik CSV nie zawiera kolumny {columns}."-msgid "The CSV needs the columns accountNumber, debit and credit. An import replaces the whole trial balance."-msgstr "CSV wymaga kolumn accountNumber, Winien i Ma. Import zastępuje cały bilans próbny."-msgid "The CSV was not imported"msgstr "CSV nie został zaimportowany"@@ -23683,9 +23709,8 @@ msgstr "Tematy"msgid "Total"msgstr "Razem"-#. placeholder {0}: formatter.format(round(totalDebit - totalCredit))-msgid "Total (out of balance by {0})"-msgstr "Suma (różnica {0})"+msgid "Total (out of balance)"+msgstr "Suma (niezgodna)"#. placeholder {0}: total.classNamemsgid "Total {0}"diff --git a/packages/locale/locales/pt/erp.po b/packages/locale/locales/pt/erp.poindex 784a9b301c..ef03295414 100644--- a/packages/locale/locales/pt/erp.po+++ b/packages/locale/locales/pt/erp.po@@ -54,6 +54,9 @@ msgstr "(conta inativa)"msgid "(Inactive)"msgstr "(Inativo)"+msgid "(mapped to more than one Carbon account)"+msgstr "(mapeado para mais de uma conta Carbon)"+msgid "(not an Equity posting account)"msgstr "(não é uma conta de contabilização de Patrimônio líquido)"@@ -2804,6 +2807,9 @@ msgstr "Aplicar a faturas"msgid "Apply to reimbursements"msgstr "Aplicar para reembolsos"+msgid "Apply to Trial Balance"+msgstr "Aplicar ao Saldo de Verificação"+msgid "Applying"msgstr "Aplicando"@@ -3812,6 +3818,10 @@ msgstr "Backups"msgid "Balance"msgstr "Saldo"+#. placeholder {0}: account.name+msgid "Balance for {0}"+msgstr "Saldo para {0}"+msgid "Balance Sheet"msgstr "Balanço Patrimonial"@@ -6402,10 +6412,6 @@ msgstr "Notas de crédito e débito"msgid "Credit applied"msgstr "Crédito aplicado"-#. placeholder {0}: account.name-msgid "Credit for {0}"-msgstr "Crédito para {0}"-msgid "Credit Memo"msgstr "Nota de crédito"@@ -6887,10 +6893,6 @@ msgstr "Débito ({0})"msgid "Debit Account"msgstr "Conta contábil de débito"-#. placeholder {0}: account.name-msgid "Debit for {0}"-msgstr "Débito para {0}"-msgid "Debit Memo"msgstr "Memorando de Débito"@@ -8915,6 +8917,12 @@ msgstr "Insira e aprove faturas de fornecedores em relação a um pedido de compmsgid "Enter at least one debit and credit"msgstr "Insira pelo menos um débito e crédito"+msgid "Enter debits as positive and credits as negative amounts. The CSV needs the columns accountNumber, debit and credit. An import or a pull from {providerName} replaces the whole trial balance."+msgstr "Digite débitos como valores positivos e créditos como valores negativos. O CSV precisa das colunas accountNumber, debit e credit. Uma importação ou uma extração de {providerName} substitui o saldo de verificação completo."++msgid "Enter debits as positive and credits as negative amounts. The CSV needs the columns accountNumber, debit and credit. An import replaces the whole trial balance."+msgstr "Digite débitos como valores positivos e créditos como valores negativos. O CSV precisa das colunas accountNumber, debit e credit. Uma importação substitui o saldo de verificação completo."+msgid "Enter number…"msgstr "Digite o número…"@@ -10729,6 +10737,9 @@ msgstr "Ocultar selecionados nesta etapa"msgid "Hide system quantities until the review step"msgstr "Ocultar quantidades do sistema até a etapa de revisão"+msgid "Hide the items on {label}"+msgstr "Ocultar os itens em {label}"+msgid "Hide, pin and reorder columns"msgstr "Ocultar, fixar e reordenar colunas"@@ -11062,6 +11073,9 @@ msgstr "Código IFSC"msgid "Ignore"msgstr "Ignorar"+msgid "Ignored"+msgstr "Ignorado"+msgid "II (normal default)"msgstr "II (padrão normal)"@@ -12946,6 +12960,9 @@ msgstr "Mapear Linhas Extraídas"msgid "Map Lines Now"msgstr "Mapear Linhas Agora"+msgid "Map these accounts in the {providerName} integration settings and pull again, or enter their balances below."+msgstr "Mapeie essas contas nas configurações de integração do {providerName} e extraia novamente, ou digite seus saldos abaixo."+msgid "Map your chart of accounts to the provider's. Posting-default and expense accounts are marked Required; posted journals push using the mapped provider account code."msgstr "Mapeie seu plano de contas para o do provedor. Contas padrão de lançamento e contas de despesas são marcadas como Obrigatórias; os diários lançados são enviados usando o código de conta do provedor mapeado."@@ -15121,8 +15138,8 @@ msgstr "Ativado"msgid "On {sentDate}"msgstr "Ligado"-msgid "On a control account, Carbon opens the balance from its own open items, inventory and fixed assets. The trial balance must agree: every difference stays on Migration Clearing, which must total zero."-msgstr "Em uma conta de controle, o Carbon abre o saldo a partir de seus próprios itens abertos, estoque e ativos fixos. O balanço de verificação deve concordar: toda diferença fica na Limpeza de Migração, que deve totalizar zero."+msgid "On a control account, Carbon opens the balance from its own open items, inventory and fixed assets. The trial balance must agree: every difference stays on Migration Clearing, which must total zero. Open an account to see its items, and ignore an invoice the prior system already settled."+msgstr "Em uma conta de controle, o Carbon exibe o saldo de seus próprios itens em aberto, inventário e ativos fixos. O saldo de verificação deve concordar: cada diferença fica em Limpeza de Migração, que deve somar zero. Abra uma conta para ver seus itens, e ignore uma fatura que o sistema anterior já liquidou."msgid "On a transfer kanban, the minimum quantity for the To storage unit. When on-hand plus open inbound transfers drops below it, Carbon creates a Released stock transfer for the kanban quantity."msgstr "Em um kanban de transferência, a quantidade mínima para a unidade de armazenamento de destino. Quando o estoque em mão mais as transferências de entrada abertas caem abaixo disso, Carbon cria uma transferência de estoque confirmada para a quantidade do kanban."@@ -17091,6 +17108,9 @@ msgstr "Puxar"msgid "Pull From"msgstr "Puxar De"+msgid "Pull from {providerName}"+msgstr "Extrair de {providerName}"+msgid "Pull from accounting"msgstr "Puxar da contabilidade"@@ -20182,6 +20202,9 @@ msgstr "Define o valor pelo qual esta unidade é registrada no inventário. A dimsgid "Settings"msgstr "Configurações"+msgid "Settled in the system that kept the books before the cutover. Carbon leaves them out of its totals and marks them Paid on the day before the cutover when you set up accounting."+msgstr "Liquidado no sistema que manteve os registros antes da mudança. O Carbon os deixa de fora de seus totais e os marca como Pagos no dia anterior à mudança quando você configura a contabilidade."+msgid "Setup"msgstr "Configuração"@@ -20522,6 +20545,9 @@ msgstr "Mostrar IDs de Fornecedor"msgid "Show sync options"msgstr "Mostrar opções de sincronização"+msgid "Show the items on {label}"+msgstr "Mostrar os itens em {label}"+msgid "Show Trailing Zeros"msgstr "Mostrar Zeros Decimais"@@ -20681,6 +20707,9 @@ msgstr "Vendido"msgid "Solutions Engineer"msgstr "Engenheiro de Soluções"+msgid "Some balances have no Carbon account"+msgstr "Alguns saldos não têm conta Carbon"+msgid "Some lines are invoiced for more or less than they total. Fix the amounts before confirming."msgstr "Algumas linhas são faturadas por mais ou menos do que totalizam. Corrija os valores antes de confirmar."@@ -22049,9 +22078,6 @@ msgstr "O arquivo CSV está vazio."msgid "The CSV has no {columns} column."msgstr "O CSV não tem coluna {columns}."-msgid "The CSV needs the columns accountNumber, debit and credit. An import replaces the whole trial balance."-msgstr "O CSV precisa das colunas accountNumber, Débito e Crédito. Uma importação substitui todo o Balancete de Verificação."-msgid "The CSV was not imported"msgstr "O CSV não foi importado"@@ -23683,9 +23709,8 @@ msgstr "Tópicos"msgid "Total"msgstr "Total"-#. placeholder {0}: formatter.format(round(totalDebit - totalCredit))-msgid "Total (out of balance by {0})"-msgstr "Total (desbalanceado por {0})"+msgid "Total (out of balance)"+msgstr "Total (fora de balanço)"#. placeholder {0}: total.classNamemsgid "Total {0}"diff --git a/packages/locale/locales/ru/erp.po b/packages/locale/locales/ru/erp.poindex 1a0b80f375..fc10531127 100644--- a/packages/locale/locales/ru/erp.po+++ b/packages/locale/locales/ru/erp.po@@ -54,6 +54,9 @@ msgstr "(неактивный счет)"msgid "(Inactive)"msgstr "(Неактивный)"+msgid "(mapped to more than one Carbon account)"+msgstr "(сопоставлено с несколькими счетами Carbon)"+msgid "(not an Equity posting account)"msgstr "(не счет проведения собственного капитала)"@@ -2804,6 +2807,9 @@ msgstr "Применить к счет-фактурам"msgid "Apply to reimbursements"msgstr "Применить к возмещениям"+msgid "Apply to Trial Balance"+msgstr "Применить к пробному балансу"+msgid "Applying"msgstr "Применение"@@ -3812,6 +3818,10 @@ msgstr "Резервные копии"msgid "Balance"msgstr "Остаток"+#. placeholder {0}: account.name+msgid "Balance for {0}"+msgstr "Остаток для {0}"+msgid "Balance Sheet"msgstr "Бухгалтерский баланс"@@ -6402,10 +6412,6 @@ msgstr "Кредитовые и дебетовые записки"msgid "Credit applied"msgstr "Кредит применен"-#. placeholder {0}: account.name-msgid "Credit for {0}"-msgstr "Кредит для {0}"-msgid "Credit Memo"msgstr "Кредит-нота"@@ -6887,10 +6893,6 @@ msgstr "Дебет ({0})"msgid "Debit Account"msgstr "Счет дебета"-#. placeholder {0}: account.name-msgid "Debit for {0}"-msgstr "Дебет для {0}"-msgid "Debit Memo"msgstr "Дебет-нота"@@ -8915,6 +8917,12 @@ msgstr "Введите и утвердите счета от поставщикmsgid "Enter at least one debit and credit"msgstr "Введите хотя бы один дебет и кредит"+msgid "Enter debits as positive and credits as negative amounts. The CSV needs the columns accountNumber, debit and credit. An import or a pull from {providerName} replaces the whole trial balance."+msgstr "Введите дебеты как положительные значения, а кредиты как отрицательные. CSV должен содержать столбцы accountNumber, debit и credit. Импорт или получение из {providerName} заменяет весь пробный баланс."++msgid "Enter debits as positive and credits as negative amounts. The CSV needs the columns accountNumber, debit and credit. An import replaces the whole trial balance."+msgstr "Введите дебеты как положительные значения, а кредиты как отрицательные. CSV должен содержать столбцы accountNumber, debit и credit. Импорт заменяет весь пробный баланс."+msgid "Enter number…"msgstr "Введите число…"@@ -10729,6 +10737,9 @@ msgstr "Скрыть выбранные на этом шаге"msgid "Hide system quantities until the review step"msgstr "Скрывать системные количества до шага рассмотрения"+msgid "Hide the items on {label}"+msgstr "Скрыть строки на {label}"+msgid "Hide, pin and reorder columns"msgstr "Скрывать, закреплять и переупорядочивать столбцы"@@ -11062,6 +11073,9 @@ msgstr "Код IFSC"msgid "Ignore"msgstr "Игнорировать"+msgid "Ignored"+msgstr "Игнорировано"+msgid "II (normal default)"msgstr "II (обычно по умолчанию)"@@ -12946,6 +12960,9 @@ msgstr "Сопоставить извлеченные строки"msgid "Map Lines Now"msgstr "Сопоставить строки сейчас"+msgid "Map these accounts in the {providerName} integration settings and pull again, or enter their balances below."+msgstr "Сопоставьте эти счета в параметрах интеграции {providerName} и получите их снова, или введите их остатки ниже."+msgid "Map your chart of accounts to the provider's. Posting-default and expense accounts are marked Required; posted journals push using the mapped provider account code."msgstr "Сопоставьте ваш план счетов с планом счетов провайдера. Счета проведения по умолчанию и счета расходов отмечены как требуемые; проведенные операции отправляются, используя сопоставленный код счета провайдера."@@ -15121,8 +15138,8 @@ msgstr "Включено"msgid "On {sentDate}"msgstr "На {sentDate}"-msgid "On a control account, Carbon opens the balance from its own open items, inventory and fixed assets. The trial balance must agree: every difference stays on Migration Clearing, which must total zero."-msgstr "На контрольном счете Carbon открывает остаток из собственных открытых позиций, запасов и основных средств. Пробный баланс должен совпадать: каждая разница остается на переводной разнице миграции, которая должна быть нулевой."+msgid "On a control account, Carbon opens the balance from its own open items, inventory and fixed assets. The trial balance must agree: every difference stays on Migration Clearing, which must total zero. Open an account to see its items, and ignore an invoice the prior system already settled."+msgstr "Для контрольного счета Carbon получает остаток из своих открытых документов, запасов и основных средств. Пробный баланс должен совпадать: каждое различие остается на счете миграции, сумма которого должна быть равна нулю. Откройте счет, чтобы увидеть его документы, и игнорируйте счет-фактуру, которую предыдущая система уже обработала."msgid "On a transfer kanban, the minimum quantity for the To storage unit. When on-hand plus open inbound transfers drops below it, Carbon creates a Released stock transfer for the kanban quantity."msgstr "На канбане перемещения минимальное количество для целевой единицы хранения. Когда наличие плюс открытые входящие перемещения упадут ниже этого значения, Carbon создает перемещение запаса в объеме канбана."@@ -17091,6 +17108,9 @@ msgstr "Получить"msgid "Pull From"msgstr "Извлечь из"+msgid "Pull from {providerName}"+msgstr "Получить из {providerName}"+msgid "Pull from accounting"msgstr "Из бухгалтерии"@@ -20182,6 +20202,9 @@ msgstr "Задает себестоимость единицы в запасахmsgid "Settings"msgstr "Настройки"+msgid "Settled in the system that kept the books before the cutover. Carbon leaves them out of its totals and marks them Paid on the day before the cutover when you set up accounting."+msgstr "Рассчитано в системе, которая вела бухгалтерский учет до перехода. Carbon исключает их из своих итогов и отмечает их как оплаченные в день перед переходом, когда вы настраиваете бухгалтерию."+msgid "Setup"msgstr "Настройка"@@ -20522,6 +20545,9 @@ msgstr "Показать ID поставщиков"msgid "Show sync options"msgstr "Показать параметры синхронизации"+msgid "Show the items on {label}"+msgstr "Показать строки на {label}"+msgid "Show Trailing Zeros"msgstr "Показывать завершающие нули"@@ -20681,6 +20707,9 @@ msgstr "Продано"msgid "Solutions Engineer"msgstr "Инженер решений"+msgid "Some balances have no Carbon account"+msgstr "Некоторые остатки не имеют счета Carbon"+msgid "Some lines are invoiced for more or less than they total. Fix the amounts before confirming."msgstr "Некоторые строки выставлены счетом на сумму, большую или меньшую, чем их итоговая сумма. Исправьте суммы перед подтверждением."@@ -22049,9 +22078,6 @@ msgstr "Файл CSV пуст."msgid "The CSV has no {columns} column."msgstr "В файле CSV нет столбца {columns}."-msgid "The CSV needs the columns accountNumber, debit and credit. An import replaces the whole trial balance."-msgstr "CSV должен содержать столбцы accountNumber, Дебет и Кредит. Импортирование заменяет весь пробный баланс."-msgid "The CSV was not imported"msgstr "CSV не была импортирована"@@ -23683,9 +23709,8 @@ msgstr "Темы"msgid "Total"msgstr "Итого"-#. placeholder {0}: formatter.format(round(totalDebit - totalCredit))-msgid "Total (out of balance by {0})"-msgstr "Итого (разница {0})"+msgid "Total (out of balance)"+msgstr "Итого (несбалансировано)"#. placeholder {0}: total.classNamemsgid "Total {0}"diff --git a/packages/locale/locales/tr/erp.po b/packages/locale/locales/tr/erp.poindex 3e14994a09..d78c9dd9ce 100644--- a/packages/locale/locales/tr/erp.po+++ b/packages/locale/locales/tr/erp.po@@ -54,6 +54,9 @@ msgstr "(pasif hesap)"msgid "(Inactive)"msgstr "(Pasif)"+msgid "(mapped to more than one Carbon account)"+msgstr "(birden fazla Carbon hesabına eşleştirildi)"+msgid "(not an Equity posting account)"msgstr "(Özkaynak muhasebeleştirme hesabı değildir)"@@ -2804,6 +2807,9 @@ msgstr "Faturaları uygula"msgid "Apply to reimbursements"msgstr "Gider Talebilerine Uygula"+msgid "Apply to Trial Balance"+msgstr "Deneme Dengesine Uygula"+msgid "Applying"msgstr "Uygulanıyor"@@ -3812,6 +3818,10 @@ msgstr "Yedeklemeler"msgid "Balance"msgstr "Bakiye"+#. placeholder {0}: account.name+msgid "Balance for {0}"+msgstr "{0} için Bakiye"+msgid "Balance Sheet"msgstr "Bilanço"@@ -6402,10 +6412,6 @@ msgstr "Alacak ve Borç Notları"msgid "Credit applied"msgstr "Alacak uygulandı"-#. placeholder {0}: account.name-msgid "Credit for {0}"-msgstr "{0} için alacak"-msgid "Credit Memo"msgstr "Alacak dekontu"@@ -6887,10 +6893,6 @@ msgstr "Borç ({0})"msgid "Debit Account"msgstr "Borç Hesabı"-#. placeholder {0}: account.name-msgid "Debit for {0}"-msgstr "{0} için borç"-msgid "Debit Memo"msgstr "Borç Notu"@@ -8915,6 +8917,12 @@ msgstr "Bir satın alma siparişine (PO) karşı satıcı faturalarını girin vmsgid "Enter at least one debit and credit"msgstr "En az bir borç ve alacak girin"+msgid "Enter debits as positive and credits as negative amounts. The CSV needs the columns accountNumber, debit and credit. An import or a pull from {providerName} replaces the whole trial balance."+msgstr "Borçları pozitif, alacakları negatif tutarlar olarak girin. CSV için accountNumber, debit ve credit sütunları gereklidir. {providerName} adresinden bir içe aktarma veya çekme tüm deneme dengesini değiştirir."++msgid "Enter debits as positive and credits as negative amounts. The CSV needs the columns accountNumber, debit and credit. An import replaces the whole trial balance."+msgstr "Borçları pozitif, alacakları negatif tutarlar olarak girin. CSV için accountNumber, debit ve credit sütunları gereklidir. Bir içe aktarma tüm deneme dengesini değiştirir."+msgid "Enter number…"msgstr "Sayı girin…"@@ -10729,6 +10737,9 @@ msgstr "Seçilenleri bu adımda gizle"msgid "Hide system quantities until the review step"msgstr "Sistem miktarlarını inceleme adımına kadar gizle"+msgid "Hide the items on {label}"+msgstr "{label} üzerindeki öğeleri gizle"+msgid "Hide, pin and reorder columns"msgstr "Sütunları gizle, sabitle ve yeniden sırala"@@ -11062,6 +11073,9 @@ msgstr "IFSC Kodu"msgid "Ignore"msgstr "Yoksay"+msgid "Ignored"+msgstr "Yoksayıldı"+msgid "II (normal default)"msgstr "II (normal varsayılan)"@@ -12946,6 +12960,9 @@ msgstr "Çıkarılan Satırları Eşle"msgid "Map Lines Now"msgstr "Satırları Şimdi Eşle"+msgid "Map these accounts in the {providerName} integration settings and pull again, or enter their balances below."+msgstr "Bu hesapları {providerName} entegrasyon ayarlarında eşleyin ve tekrar çekin, ya da aşağıda bakiyelerini girin."+msgid "Map your chart of accounts to the provider's. Posting-default and expense accounts are marked Required; posted journals push using the mapped provider account code."msgstr "Hesap planınızı sağlayıcının hesap planına eşleyin. Muhasebeleştirme varsayılanı ve Gider hesapları Gerekli olarak işaretlenmiştir; Muhasebeleştirildi Muhasebe fişleri eşlenen sağlayıcı hesap kodunu kullanarak gönderilir."@@ -15121,8 +15138,8 @@ msgstr "Açık"msgid "On {sentDate}"msgstr "{sentDate} tarihinde"-msgid "On a control account, Carbon opens the balance from its own open items, inventory and fixed assets. The trial balance must agree: every difference stays on Migration Clearing, which must total zero."-msgstr "Bir kontrol hesabında, Carbon, açık kalemlerinin, envanterinin ve sabit kıymetlerinin bakiyesini açar. Deneme bakiyesi eşleşmelidir: her fark Geçiş Temizliğinde kalır, bu toplam sıfır olmalıdır."+msgid "On a control account, Carbon opens the balance from its own open items, inventory and fixed assets. The trial balance must agree: every difference stays on Migration Clearing, which must total zero. Open an account to see its items, and ignore an invoice the prior system already settled."+msgstr "Kontrol hesabında, Carbon bakiyeyi kendi açık kalemlerinden, envanterden ve sabit kıymetlerden açar. Deneme dengesi uyuşmalıdır: her fark Göç Temizlemesi'nde kalır, bunun toplamı sıfır olmalıdır. Öğelerini görmek için bir hesabı açın ve önceki sistem tarafından zaten kapatılmış bir faturayı yoksayın."msgid "On a transfer kanban, the minimum quantity for the To storage unit. When on-hand plus open inbound transfers drops below it, Carbon creates a Released stock transfer for the kanban quantity."msgstr "Transfer kanban'ında To depolama birimi için minimum miktar. Eldeki + açık gelen transferler bunun altına düştüğünde, Carbon kanban miktarı için Serbest bırakıldı stok transferi oluşturur."@@ -17091,6 +17108,9 @@ msgstr "Çek"msgid "Pull From"msgstr "Çekme Kaynağından"+msgid "Pull from {providerName}"+msgstr "{providerName} adresinden çek"+msgid "Pull from accounting"msgstr "Muhasebeden çek"@@ -20182,6 +20202,9 @@ msgstr "Bu öğenin envanterde muhasebeleştirildiği değeri ayarlar. Fark, envmsgid "Settings"msgstr "Ayarlar"+msgid "Settled in the system that kept the books before the cutover. Carbon leaves them out of its totals and marks them Paid on the day before the cutover when you set up accounting."+msgstr "Kesme tarihinden önceki muhasebe sisteminde çözümlendi. Carbon onları toplam tutarlarından dışarıda bırakır ve muhasebeleştirmeyi ayarladığınızda kesme tarihinin bir gün öncesinde Ödendi olarak işaretler."+msgid "Setup"msgstr "Kurulum"@@ -20522,6 +20545,9 @@ msgstr "Tedarikçi Kimliklerini Göster"msgid "Show sync options"msgstr "Senkronizasyon seçeneklerini göster"+msgid "Show the items on {label}"+msgstr "{label} üzerindeki öğeleri göster"+msgid "Show Trailing Zeros"msgstr "Sondaki Sıfırları Göster"@@ -20681,6 +20707,9 @@ msgstr "Satıldı"msgid "Solutions Engineer"msgstr "Çözüm Mühendisi"+msgid "Some balances have no Carbon account"+msgstr "Bazı bakiyeler Carbon hesabına sahip değil"+msgid "Some lines are invoiced for more or less than they total. Fix the amounts before confirming."msgstr "Bazı satırlar, toplamından daha fazla veya daha az fatura kesilmiş. Onaylamadan önce tutarları düzeltin."@@ -22049,9 +22078,6 @@ msgstr "CSV dosyası boştur."msgid "The CSV has no {columns} column."msgstr "CSV dosyasında {columns} sütunu yoktur."-msgid "The CSV needs the columns accountNumber, debit and credit. An import replaces the whole trial balance."-msgstr "CSV, accountNumber, borç ve alacak sütunlarına ihtiyaç duyuyor. Bir içe aktarma tüm deneme bakiyesini değiştirir."-msgid "The CSV was not imported"msgstr "CSV içe aktarılmadı"@@ -23683,9 +23709,8 @@ msgstr "Konular"msgid "Total"msgstr "Toplam"-#. placeholder {0}: formatter.format(round(totalDebit - totalCredit))-msgid "Total (out of balance by {0})"-msgstr "Toplam ({0} kadar dengesiz)"+msgid "Total (out of balance)"+msgstr "Toplam (dengesiz)"#. placeholder {0}: total.classNamemsgid "Total {0}"diff --git a/packages/locale/locales/zh/erp.po b/packages/locale/locales/zh/erp.poindex 18525fbb18..987365a73c 100644--- a/packages/locale/locales/zh/erp.po+++ b/packages/locale/locales/zh/erp.po@@ -54,6 +54,9 @@ msgstr "(已停用账户)"msgid "(Inactive)"msgstr "(已停用)"+msgid "(mapped to more than one Carbon account)"+msgstr "(映射到多个 Carbon 账户)"+msgid "(not an Equity posting account)"msgstr "(非所有者权益过账账户)"@@ -2804,6 +2807,9 @@ msgstr "应用于发票"msgid "Apply to reimbursements"msgstr "应用到报销单"+msgid "Apply to Trial Balance"+msgstr "应用到试算表"+msgid "Applying"msgstr "正在应用"@@ -3812,6 +3818,10 @@ msgstr "备份"msgid "Balance"msgstr "余额"+#. placeholder {0}: account.name+msgid "Balance for {0}"+msgstr "{0} 的余额"+msgid "Balance Sheet"msgstr "资产负债表"@@ -6402,10 +6412,6 @@ msgstr "贷方和借方备忘录"msgid "Credit applied"msgstr "已应用信用"-#. placeholder {0}: account.name-msgid "Credit for {0}"-msgstr "{0}的贷方"-msgid "Credit Memo"msgstr "贷项凭证"@@ -6887,10 +6893,6 @@ msgstr "借方 ({0})"msgid "Debit Account"msgstr "借方账户"-#. placeholder {0}: account.name-msgid "Debit for {0}"-msgstr "{0}的借方"-msgid "Debit Memo"msgstr "借方备忘录"@@ -8915,6 +8917,12 @@ msgstr "输入和审批供应商账单与采购单进行三单匹配"msgid "Enter at least one debit and credit"msgstr "至少输入一个借方和贷方"+msgid "Enter debits as positive and credits as negative amounts. The CSV needs the columns accountNumber, debit and credit. An import or a pull from {providerName} replaces the whole trial balance."+msgstr "输入借方为正数,贷方为负数。CSV 需要包含以下列:accountNumber、借方 和 贷方。从 {providerName} 导入或拉取会替换整个试算表。"++msgid "Enter debits as positive and credits as negative amounts. The CSV needs the columns accountNumber, debit and credit. An import replaces the whole trial balance."+msgstr "输入借方为正数,贷方为负数。CSV 需要包含以下列:accountNumber、借方 和 贷方。导入会替换整个试算表。"+msgid "Enter number…"msgstr "输入数字…"@@ -10729,6 +10737,9 @@ msgstr "隐藏此步骤中的选定项"msgid "Hide system quantities until the review step"msgstr "在评审步骤前隐藏系统数量"+msgid "Hide the items on {label}"+msgstr "隐藏 {label} 上的物料"+msgid "Hide, pin and reorder columns"msgstr "隐藏、固定和重新排序列"@@ -11062,6 +11073,9 @@ msgstr "IFSC代码"msgid "Ignore"msgstr "忽略"+msgid "Ignored"+msgstr "已忽略"+msgid "II (normal default)"msgstr "II(正常默认值)"@@ -12946,6 +12960,9 @@ msgstr "映射提取的行"msgid "Map Lines Now"msgstr "立即映射行"+msgid "Map these accounts in the {providerName} integration settings and pull again, or enter their balances below."+msgstr "在 {providerName} 集成设置中映射这些账户并重新拉取,或在下方输入它们的余额。"+msgid "Map your chart of accounts to the provider's. Posting-default and expense accounts are marked Required; posted journals push using the mapped provider account code."msgstr "将您的会计科目表映射到提供商的。过账默认账户和费用账户标记为必需;已过账凭证使用映射的提供商账户代码进行推送。"@@ -15121,8 +15138,8 @@ msgstr "开"msgid "On {sentDate}"msgstr "打开"-msgid "On a control account, Carbon opens the balance from its own open items, inventory and fixed assets. The trial balance must agree: every difference stays on Migration Clearing, which must total zero."-msgstr "在控制帐户上,Carbon从其自身的未结项目、库存和固定资产获取余额。试算平衡表必须一致:每项差异保留在迁差账户上,该账户必须合计为零。"+msgid "On a control account, Carbon opens the balance from its own open items, inventory and fixed assets. The trial balance must agree: every difference stays on Migration Clearing, which must total zero. Open an account to see its items, and ignore an invoice the prior system already settled."+msgstr "对于控制账户,Carbon 从其自己的未结项目、库存和固定资产中获取期初余额。试算表必须一致:每个差异都保留在迁移清除账户上,必须合计为零。打开一个账户来查看其项目明细,并忽略先前系统已经结清的发票。"msgid "On a transfer kanban, the minimum quantity for the To storage unit. When on-hand plus open inbound transfers drops below it, Carbon creates a Released stock transfer for the kanban quantity."msgstr "在转移看板上,指目标存储单元的最小数量。当现有库存加上未完成的入库调拨降至此水位以下时,Carbon 会创建一个已下达的库存调拨,调拨数量为看板数量。"@@ -17091,6 +17108,9 @@ msgstr "拉取"msgid "Pull From"msgstr "从以下位置提取"+msgid "Pull from {providerName}"+msgstr "从 {providerName} 拉取"+msgid "Pull from accounting"msgstr "从会计系统拉取"@@ -20182,6 +20202,9 @@ msgstr "设置此项在库存中的账面价值。差异将在库存和原支出msgid "Settings"msgstr "设置"+msgid "Settled in the system that kept the books before the cutover. Carbon leaves them out of its totals and marks them Paid on the day before the cutover when you set up accounting."+msgstr "在先前系统中已结清。Carbon 将它们排除在总计之外,并在设置会计时将它们标记为在截断日期前一天已付款。"+msgid "Setup"msgstr "换型"@@ -20522,6 +20545,9 @@ msgstr "显示供应商ID"msgid "Show sync options"msgstr "显示同步选项"+msgid "Show the items on {label}"+msgstr "显示 {label} 上的物料"+msgid "Show Trailing Zeros"msgstr "显示尾随零"@@ -20681,6 +20707,9 @@ msgstr "已售出"msgid "Solutions Engineer"msgstr "解决方案工程师"+msgid "Some balances have no Carbon account"+msgstr "某些余额没有 Carbon 账户"+msgid "Some lines are invoiced for more or less than they total. Fix the amounts before confirming."msgstr "某些行的开票金额比总额多或少。确认前修复金额。"@@ -22049,9 +22078,6 @@ msgstr "CSV 文件为空。"msgid "The CSV has no {columns} column."msgstr "CSV 没有「{columns}」列。"-msgid "The CSV needs the columns accountNumber, debit and credit. An import replaces the whole trial balance."-msgstr "CSV 需要包含 accountNumber、借方 和 贷方 列。导入将替换整个试算平衡表。"-msgid "The CSV was not imported"msgstr "CSV 未被导入"@@ -23683,9 +23709,8 @@ msgstr "主题"msgid "Total"msgstr "总计"-#. placeholder {0}: formatter.format(round(totalDebit - totalCredit))-msgid "Total (out of balance by {0})"-msgstr "总计(差额 {0})"+msgid "Total (out of balance)"+msgstr "总计(未平衡)"#. placeholder {0}: total.classNamemsgid "Total {0}"diff --git a/packages/server-functions/AGENTS.md b/packages/server-functions/AGENTS.mdindex f1334a5d44..96dd30ebb8 100644--- a/packages/server-functions/AGENTS.md+++ b/packages/server-functions/AGENTS.md@@ -239,7 +239,12 @@ spec's section 5 numbering, as the code comments do: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.+ (`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 theperiod of its date.9. `repointStandInLines` moves each stand-in line to the default it names (or thatdiff --git a/packages/server-functions/src/activate-accounting/ignored-invoices.test.ts b/packages/server-functions/src/activate-accounting/ignored-invoices.test.tsnew file mode 100644index 0000000000..a0b735788c--- /dev/null+++ b/packages/server-functions/src/activate-accounting/ignored-invoices.test.ts@@ -0,0 +1,163 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++// Migration Clearing's ignore and apply, against the live database. Another+// system kept the books before the cutover, so an invoice open in Carbon may+// be settled there: the user ignores it, Carbon leaves it out of its opening+// total, and the enable closes it as Paid the day before the cutover.++import {+ applyCarbonToOpeningTrialBalance,+ getMigrationClearing,+ getOpeningTrialBalance,+ setCutoverInvoiceIgnored+} from "@carbon/database/accounting-cutover-reads";+import { sql } from "kysely";+import { expect } from "vitest";+import { databaseTest } from "../local-database-test-fixture";+import postPayment from "../post-payment";+import activateAccounting from ".";+import {+ activationFixture,+ moveBeforeCutover,+ pay,+ postServiceInvoice,+ USER,+ unwrap+} from "./activation-test-fixture";++databaseTest(+ "an ignored invoice leaves Carbon's opening total and closes as Paid the day before the cutover",+ async () => {+ const f = await activationFixture();+ try {+ const invoiceId = await postServiceInvoice(f);+ await moveBeforeCutover(f);+ const args = { companyId: f.companyId, cutoverDate: f.cutoverDate };++ const before = await getMigrationClearing(f.db, args);+ expect(before.items.map((item) => item.documentId)).toContain(invoiceId);+ expect(before.total).toBe(-100);++ await setCutoverInvoiceIgnored(f.db, {+ ...args,+ userId: USER,+ invoiceId,+ ignored: true+ });+ const ignored = await getMigrationClearing(f.db, args);+ expect(ignored.items.map((item) => item.documentId)).not.toContain(+ invoiceId+ );+ expect(ignored.ignoredItems).toEqual([+ expect.objectContaining({+ openItemType: "Receivable",+ documentId: invoiceId,+ reference: "INV-1",+ amount: 100+ })+ ]);+ expect(ignored.total).toBe(0);++ unwrap(+ await activateAccounting(f.ctx, {+ ...args,+ confirmation: f.companyName+ })+ );++ const invoice = await f.db+ .selectFrom("salesInvoice")+ .select(["status", "datePaid"])+ .where("id", "=", invoiceId)+ .executeTakeFirstOrThrow();+ expect(invoice).toEqual({+ status: "Paid",+ datePaid: f.beforeCutover+ });+ const open = await sql<{ documentId: string }>`+ SELECT "documentId"+ FROM get_ar_open_by_customer(${f.companyId}, ${f.cutoverDate}::date)+ `.execute(f.db);+ expect(open.rows).toEqual([]);+ } finally {+ await f.cleanup();+ }+ }+);++databaseTest(+ "stops ignoring an invoice, and applies Carbon's totals to the trial balance's control accounts",+ async () => {+ const f = await activationFixture();+ try {+ const invoiceId = await postServiceInvoice(f);+ await moveBeforeCutover(f);+ const args = { companyId: f.companyId, cutoverDate: f.cutoverDate };+ const ignore = (ignored: boolean) =>+ setCutoverInvoiceIgnored(f.db, {+ ...args,+ userId: USER,+ invoiceId,+ ignored+ });+ await ignore(true);+ await ignore(true);+ await ignore(false);+ expect((await getMigrationClearing(f.db, args)).ignoredItems).toEqual([]);++ await applyCarbonToOpeningTrialBalance(f.db, { ...args, userId: USER });++ const { lines } = await getOpeningTrialBalance(f.db, args);+ expect(lines).toEqual([+ expect.objectContaining({+ accountId: f.account("receivables"),+ debit: 100,+ credit: 0+ })+ ]);+ const clearing = await getMigrationClearing(f.db, args);+ expect(clearing.rows.every((row) => row.difference === 0)).toBe(true);+ // The receivable is still not offset anywhere in the trial balance.+ expect(clearing.total).toBe(-100);+ } finally {+ await f.cleanup();+ }+ }+);++databaseTest(+ "an invoice Carbon is paid on after the cutover cannot be ignored",+ async () => {+ const f = await activationFixture();+ try {+ const invoiceId = await postServiceInvoice(f);+ await moveBeforeCutover(f);+ // Paid in Carbon after the cutover: its journal credits receivables,+ // so the invoice must open there.+ unwrap(+ await postPayment(f.ctx, {+ type: "post",+ paymentId: await pay(f, { id: "pay-1", invoiceId, amount: 100 })+ })+ );+ const args = { companyId: f.companyId, cutoverDate: f.cutoverDate };+ await setCutoverInvoiceIgnored(f.db, {+ ...args,+ userId: USER,+ invoiceId,+ ignored: true+ });++ const clearing = await getMigrationClearing(f.db, args);+ expect(clearing.settledFromCutoverIds.has(invoiceId)).toBe(true);+ expect(clearing.ignoredItems).toEqual([]);+ expect(clearing.items.map((item) => item.documentId)).toContain(+ invoiceId+ );+ } finally {+ await f.cleanup();+ }+ }+);diff --git a/packages/server-functions/src/activate-accounting/index.ts b/packages/server-functions/src/activate-accounting/index.tsindex b3df5344c0..bea4b63c3a 100644--- a/packages/server-functions/src/activate-accounting/index.ts+++ b/packages/server-functions/src/activate-accounting/index.ts@@ -13,7 +13,8 @@import {buildOpeningJournalLines,- isMigrationClearingZero+ isMigrationClearingZero,+ type OpenItem} from "@carbon/database/accounting-cutover";import {ACCOUNTING_ALREADY_SET_UP,@@ -22,6 +23,7 @@ import {getCutoverInventory,getMigrationClearing} from "@carbon/database/accounting-cutover-reads";+import type { KyselyTx } from "@carbon/database/client";import { missingDefaultMessage } from "@carbon/database/journal-posting-status";import { getNextSequence } from "@carbon/database/sequence";import { getLogger } from "@carbon/logger";@@ -177,6 +179,21 @@ const activateAccounting = defineServerFn({// Step 7. The opening journal, the day before the cutover. It replaces// the Draft trial balance the wizard kept.const openingDate = dayBeforeCutover(cutoverDate);++ // The invoices ignored on Migration Clearing were settled in the+ // system that kept the books before the cutover. They are not in the+ // opening journal, so they close as Paid on the day before it, as the+ // Xero and QuickBooks pulls close them; every receivables and payables+ // reader treats that as settled. A sync write: no workflow, webhook or+ // provider push fires for it.+ await markIgnoredInvoicesPaid(trx, {+ companyId,+ items: clearing.ignoredItems,+ datePaid: openingDate,+ userId,+ now+ });+const draftTrialBalances = trx.selectFrom("journal").select("id")@@ -330,3 +347,64 @@ const activateAccounting = defineServerFn({});export default activateAccounting;++/** Marks the ignored invoices Paid, with the sync flag on. */+async function markIgnoredInvoicesPaid(+ trx: KyselyTx,+ {+ companyId,+ items,+ datePaid,+ userId,+ now+ }: {+ companyId: string;+ items: OpenItem[];+ datePaid: string;+ userId: string;+ now: string;+ }+) {+ const idsOf = (openItemType: OpenItem["openItemType"]) =>+ items.flatMap((item) =>+ item.openItemType === openItemType && item.documentId+ ? [item.documentId]+ : []+ );+ const salesInvoiceIds = idsOf("Receivable");+ const purchaseInvoiceIds = idsOf("Payable");+ if (salesInvoiceIds.length === 0 && purchaseInvoiceIds.length === 0) return;++ const { rows } = await sql<{ previous: string | null }>`+ SELECT current_setting('app.sync_in_progress', true) AS previous+ `.execute(trx);+ const previous = rows[0]?.previous ?? "";+ await sql`SELECT set_config('app.sync_in_progress', 'true', true)`.execute(+ trx+ );+ const set = {+ status: "Paid" as const,+ datePaid,+ updatedBy: userId,+ updatedAt: now+ };+ for (const ids of chunkArray(salesInvoiceIds, ROWS_PER_STATEMENT)) {+ await trx+ .updateTable("salesInvoice")+ .set(set)+ .where("companyId", "=", companyId)+ .where("id", "in", ids)+ .execute();+ }+ for (const ids of chunkArray(purchaseInvoiceIds, ROWS_PER_STATEMENT)) {+ await trx+ .updateTable("purchaseInvoice")+ .set(set)+ .where("companyId", "=", companyId)+ .where("id", "in", ids)+ .execute();+ }+ await sql`SELECT set_config('app.sync_in_progress', ${previous}, true)`.execute(+ trx+ );+}diff --git a/packages/server-functions/src/activate-accounting/reads.test.ts b/packages/server-functions/src/activate-accounting/reads.test.tsindex b62a09417e..f55459c1a6 100644--- a/packages/server-functions/src/activate-accounting/reads.test.ts+++ b/packages/server-functions/src/activate-accounting/reads.test.ts@@ -741,7 +741,9 @@ databaseTest(documentType: "Invoice",documentId: invoiceId,documentLineReference: null,- description: "Accounts Receivable"+ description: "Accounts Receivable",+ reference: expect.any(String),+ partyName: expect.any(String)});expect(items).toContainEqual({openItemType: "Received Not Invoiced",@@ -772,7 +774,9 @@ databaseTest(documentType: "Invoice",documentId: purchaseInvoiceId,documentLineReference: null,- description: "Accounts Payable"+ description: "Accounts Payable",+ reference: expect.any(String),+ partyName: expect.any(String)});// 10 received, 4 shipped: 6 on hand at the receipt's layer cost; the