Skip to content

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

fix(accounting): read Rillet trial balances (negative credit totals, fiscal year start) (#1917)

Brad Barbine77980c6cb77
diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml
index fb78b487cc..edb5df15ed 100644
--- a/.github/workflows/deploy.yml
+++ b/.github/workflows/deploy.yml
@@ -12,25 +12,38 @@ on:
workflow_dispatch:
jobs:
# The images come from build-images.yml, which runs on the same push. This
- # waits for it rather than building them a second time.
+ # waits for that run rather than building them a second time. It watches the
+ # run, not the registry: polling public.ecr.aws anonymously from a shared
+ # runner IP can be refused for the life of the runner, which looked exactly
+ # like an image that never arrived, and a build that failed or was cancelled
+ # left this waiting out its whole timeout.
images:
name: Wait for images
runs-on: ubuntu-latest
timeout-minutes: 30
+ permissions:
+ actions: read
steps:
- - uses: docker/setup-buildx-action@v3
-
- name: Wait for carbon/erp and carbon/mes
env:
+ GH_TOKEN: ${{ github.token }}
+ GH_REPO: ${{ github.repository }}
REGISTRY: ${{ vars.IMAGE_REGISTRY }}
SHA: ${{ github.sha }}
run: |
[ -n "$REGISTRY" ] || { echo "vars.IMAGE_REGISTRY is not set" >&2; exit 1; }
+ until run=$(gh run list --workflow build-images.yml --commit "$SHA" --limit 1 \
+ --json databaseId --jq '.[0].databaseId // empty') && [ -n "$run" ]; do
+ echo "waiting for Build images to start on $SHA"
+ sleep 15
+ done
+ echo "Build images run: $GITHUB_SERVER_URL/$GH_REPO/actions/runs/$run"
+ gh run watch "$run" --interval 15 > /dev/null
for app in erp mes; do
- until docker buildx imagetools inspect "$REGISTRY/carbon/$app:$SHA" >/dev/null 2>&1; do
- echo "waiting for $REGISTRY/carbon/$app:$SHA"
- sleep 15
- done
+ conclusion=$(gh run view "$run" --json jobs \
+ --jq ".jobs[] | select(.name == \"carbon/$app\") | .conclusion")
+ echo "carbon/$app: ${conclusion:-missing}"
+ [ "$conclusion" = success ] || exit 1
done
deploy:
diff --git a/apps/erp/app/modules/settings/settings.models.ts b/apps/erp/app/modules/settings/settings.models.ts
index 29b47e1ab7..83e2193810 100644
--- a/apps/erp/app/modules/settings/settings.models.ts
+++ b/apps/erp/app/modules/settings/settings.models.ts
@@ -542,21 +542,6 @@ export const syncOperationTransitionValidator = z.object({
to: z.enum(["Pending", "Skipped"])
});
-/**
- * Saves one account mapping row (Carbon account.id → provider account id)
- * from the integration drawer's Account Mapping tab. externalCode /
- * externalName are display metadata captured from the selected provider
- * account — the journal syncer resolves provider account codes from the
- * mapping's stored externalCode, so the code must be persisted.
- */
-export const accountMappingUpsertValidator = z.object({
- intent: z.literal("upsert-account-mapping"),
- accountId: z.string().min(1, { message: "Account is required" }),
- externalId: z.string().min(1, { message: "Provider account is required" }),
- externalCode: zfd.text(z.string().optional()),
- externalName: zfd.text(z.string().optional())
-});
-
export const workCenterDeviceUpsertValidator = z.object({
intent: z.literal("upsert-work-center-device"),
externalDeviceId: z.string().min(1, { message: "Device is required" }),
@@ -566,6 +551,12 @@ export const workCenterDeviceUpsertValidator = z.object({
workCenterId: zfd.text(z.string().optional())
});
+/**
+ * One account mapping (Carbon account.id → provider account id).
+ * externalCode / externalName are captured from the selected provider
+ * account — the journal syncer resolves provider account codes from the
+ * mapping's stored externalCode, so the code must be persisted.
+ */
const accountMappingEntrySchema = z.object({
accountId: z.string().min(1),
externalId: z.string().min(1),
@@ -574,10 +565,10 @@ const accountMappingEntrySchema = z.object({
});
/**
- * Confirm-all from the match-by-code drawer. `mappings` is a repeated form
- * field (per the sync-operation `ids` precedent) — each entry a
- * JSON-encoded proposal validated against the same shape as the single-row
- * upsert.
+ * Save from the Account Mapping tab, and confirm-all from match-by-code and
+ * AI suggest. `mappings` is a repeated form field (per the sync-operation
+ * `ids` precedent) — each entry a JSON-encoded account → provider account
+ * pair.
*/
export const accountMappingBulkUpsertValidator = z.object({
intent: z.literal("bulk-upsert-account-mappings"),
diff --git a/apps/erp/app/modules/settings/ui/Integrations/AccountMapping.tsx b/apps/erp/app/modules/settings/ui/Integrations/AccountMapping.tsx
index ae0f81f289..432e994b9d 100644
--- a/apps/erp/app/modules/settings/ui/Integrations/AccountMapping.tsx
+++ b/apps/erp/app/modules/settings/ui/Integrations/AccountMapping.tsx
@@ -2,10 +2,10 @@
// 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 { Combobox, Submit, ValidatedForm } from "@carbon/form";
import { useAction } from "@carbon/query";
import {
Button,
+ Combobox,
Drawer,
DrawerBody,
DrawerContent,
@@ -39,7 +39,6 @@ import { useEffect, useMemo, useRef, useState } from "react";
import { LuArrowRight, LuLink, LuSearch, LuSparkles } from "react-icons/lu";
import { useFetcher } from "react-router";
import { usePermissions } from "~/hooks";
-import { accountMappingUpsertValidator } from "~/modules/settings/settings.models";
/**
* Local structural mirrors of @carbon/ee/accounting's AccountMapping /
@@ -169,7 +168,11 @@ export function AccountMapping({
const [showAiModal, setShowAiModal] = useState(false);
const [search, setSearch] = useState("");
const [highlightedId, setHighlightedId] = useState<string | null>(null);
+ // The provider account the user picked for each Carbon account this
+ // session, saved together by the footer's Save.
+ const [edits, setEdits] = useState<Record<string, string>>({});
const rowRefs = useRef(new Map<string, HTMLDivElement>());
+ const saveFetcher = useAction({ onSuccess: () => setEdits({}) });
const chartById = useMemo(
() => new Map(chart.map((account) => [account.id, account])),
@@ -197,6 +200,38 @@ export function AccountMapping({
[mappings]
);
+ const changes = useMemo(
+ () =>
+ Object.entries(edits).filter(
+ ([accountId, externalId]) =>
+ externalId && externalId !== mappedById.get(accountId)?.externalId
+ ),
+ [edits, mappedById]
+ );
+
+ const save = () => {
+ if (changes.length === 0) return;
+ const formData = new FormData();
+ formData.append("intent", "bulk-upsert-account-mappings");
+ for (const [accountId, externalId] of changes) {
+ const chartAccount = chartById.get(externalId);
+ formData.append(
+ "mappings",
+ JSON.stringify({
+ accountId,
+ externalId,
+ ...(chartAccount
+ ? {
+ externalCode: chartAccount.code,
+ externalName: chartAccount.name
+ }
+ : {})
+ })
+ );
+ }
+ saveFetcher.submit(formData, { method: "post" });
+ };
+
// One list: every account in the chart, plus any account blocking a sync
// that isn't an active leaf (so a block is never hidden).
const displayAccounts = useMemo(() => {
@@ -358,18 +393,18 @@ export function AccountMapping({
{group.accounts.map((account) => {
const mapping = mappedById.get(account.id);
return (
- // The row's ValidatedForm seeds its controlled `externalId`
- // Combobox from `defaultValues` only at hydration, so a row
- // kept mounted across revalidation never repaints when its
- // saved mapping changes (its own save, match-by-code, AI
- // suggest). Keying on the persisted external id remounts the
- // row exactly when the mapping changes, re-seeding it from
- // fresh loader data instead of requiring a full page reload.
- <AccountMappingRowForm
- key={`${account.id}:${mapping?.externalId ?? ""}`}
+ <AccountMappingRow
+ key={account.id}
accountId={account.id}
accountNumber={account.number}
accountName={account.name}
+ value={edits[account.id] ?? mapping?.externalId ?? ""}
+ onChange={(externalId) =>
+ setEdits((current) => ({
+ ...current,
+ [account.id]: externalId
+ }))
+ }
currentExternalId={mapping?.externalId ?? null}
currentExternalCode={mapping?.externalCode ?? null}
currentExternalName={mapping?.externalName ?? null}
@@ -388,6 +423,19 @@ export function AccountMapping({
))
)}
</DrawerBody>
+ <DrawerFooter>
+ <HStack>
+ <Button
+ isDisabled={
+ !canUpdate || changes.length === 0 || saveFetcher.isPending
+ }
+ isLoading={saveFetcher.isPending}
+ onClick={save}
+ >
+ <Trans>Save</Trans>
+ </Button>
+ </HStack>
+ </DrawerFooter>
{showMatchDrawer && (
<MatchByCodeDrawer
@@ -410,15 +458,15 @@ export function AccountMapping({
}
/**
- * One Carbon account → provider account row. Each row is its own
- * ValidatedForm posting intent=upsert-account-mapping; the provider
- * code/name of the selected option travel in hidden fields because the
- * journal syncer resolves account codes from the mapping metadata.
+ * One Carbon account → provider account row. The pick is held by the tab
+ * and saved with every other changed row by the footer's Save.
*/
-function AccountMappingRowForm({
+function AccountMappingRow({
accountId,
accountNumber,
accountName,
+ value,
+ onChange,
currentExternalId,
currentExternalCode,
currentExternalName,
@@ -432,6 +480,8 @@ function AccountMappingRowForm({
accountId: string;
accountNumber: string | null;
accountName: string | null;
+ value: string;
+ onChange: (externalId: string) => void;
currentExternalId: string | null;
currentExternalCode: string | null;
currentExternalName: string | null;
@@ -443,21 +493,6 @@ function AccountMappingRowForm({
highlighted?: boolean;
}) {
const { t } = useLingui();
- // `selected` holds the user's explicit pick this session; `touched` marks
- // whether they have edited this row. The row stays mounted (key=account.id)
- // across parent revalidations, so until the user edits we must derive the
- // hidden provider metadata from the CURRENT mapping props (not a value frozen
- // at mount) — otherwise a save after the mapping changed elsewhere (match-by-
- // code, AI suggest, revalidation) would overwrite the stored code/name with
- // stale or empty values. Once touched, the user's selection wins, and an
- // explicit clear submits empty to unmap.
- const [selected, setSelected] = useState<{
- code: string | null;
- name: string | null;
- } | null>(null);
- const [touched, setTouched] = useState(false);
- const externalCode = touched ? selected?.code : currentExternalCode;
- const externalName = touched ? selected?.name : currentExternalName;
// A mapped provider account can be missing from the chart (archived or
// the chart failed to load): keep it selectable/visible via a fallback
@@ -490,20 +525,7 @@ function AccountMappingRowForm({
: "w-full"
}
>
- <ValidatedForm
- validator={accountMappingUpsertValidator}
- method="post"
- defaultValues={{
- intent: "upsert-account-mapping",
- accountId,
- externalId: currentExternalId ?? undefined
- }}
- className="flex w-full items-center gap-3 p-3"
- >
- <input type="hidden" name="intent" value="upsert-account-mapping" />
- <input type="hidden" name="accountId" value={accountId} />
- <input type="hidden" name="externalCode" value={externalCode ?? ""} />
- <input type="hidden" name="externalName" value={externalName ?? ""} />
+ <div className="flex w-full items-center gap-3 p-3">
<div className="flex min-w-0 flex-1 flex-col">
<div className="flex min-w-0 items-center gap-2">
<span className="truncate text-sm font-medium">
@@ -520,36 +542,14 @@ function AccountMappingRowForm({
<LuArrowRight className="size-4 shrink-0 text-muted-foreground" />
<div className="w-[260px] shrink-0">
<Combobox
- name="externalId"
+ value={value}
options={options}
placeholder={t`Select provider account`}
- onChange={(option) => {
- setTouched(true);
- if (!option) {
- setSelected(null);
- return;
- }
- const chartAccount = chartById.get(option.value);
- if (chartAccount) {
- setSelected({
- code: chartAccount.code,
- name: chartAccount.name
- });
- } else if (option.value === currentExternalId) {
- setSelected({
- code: currentExternalCode,
- name: currentExternalName
- });
- } else {
- setSelected(null);
- }
- }}
+ isReadOnly={!canUpdate}
+ onChange={onChange}
/>
</div>
- <Submit size="sm" variant="secondary" isDisabled={!canUpdate}>
- <Trans>Save</Trans>
- </Submit>
- </ValidatedForm>
+ </div>
</div>
);
}
diff --git a/apps/erp/app/routes/x+/settings+/integrations.$id.tsx b/apps/erp/app/routes/x+/settings+/integrations.$id.tsx
index 1150137988..976ebc8ca4 100644
--- a/apps/erp/app/routes/x+/settings+/integrations.$id.tsx
+++ b/apps/erp/app/routes/x+/settings+/integrations.$id.tsx
@@ -49,7 +49,7 @@ import {
selectUnmappedRequiredAccounts,
suggestAccountMatchesWithAI,
transitionOperation,
- upsertAccountMapping,
+ upsertAccountMappings,
upsertDimensionValueMapping,
validateDimensionSlots,
XERO_MAX_JOURNAL_DIMENSION_SLOTS,
@@ -121,7 +121,6 @@ import {
import {
accountMappingAiSuggestValidator,
accountMappingBulkUpsertValidator,
- accountMappingUpsertValidator,
dimensionSlotsUpdateValidator,
dimensionValueMappingBulkUpsertValidator,
dimensionValueMappingUpsertValidator,
@@ -1239,45 +1238,6 @@ export async function action({ request, params }: ActionFunctionArgs) {
);
}
- // Save one account mapping row (Account Mapping tab). The mapping
- // services are Kysely-based (RLS bypassed) — requirePermissions above +
- // companyId scoping is the auth gate. Stays on the page so the tab
- // revalidates in place.
- if (formData.get("intent") === "upsert-account-mapping") {
- const validation = await validator(accountMappingUpsertValidator).validate(
- formData
- );
-
- if (validation.error) {
- return validationError(validation.error);
- }
-
- const { accountId, externalId, externalCode, externalName } =
- validation.data;
-
- const result = await upsertAccountMapping(getDatabaseClient(), {
- companyId,
- integration: integrationId,
- accountId,
- externalId,
- externalCode,
- externalName,
- userId
- });
-
- if (result.error) {
- return data(
- {},
- await flash(
- request,
- error(result.error, "Failed to save account mapping")
- )
- );
- }
-
- return data({}, await flash(request, success("Saved account mapping")));
- }
-
// "Suggest with AI" from the Account Mapping tab: ask gpt-4o for a
// best-guess pairing of the still-unmapped Carbon accounts to the
// provider chart. Writes nothing — returns proposals for the confirm
@@ -1311,8 +1271,11 @@ export async function action({ request, params }: ActionFunctionArgs) {
return data({ proposals: result.data });
}
- // Confirm-all from the match-by-code drawer: repeated JSON-encoded
- // `mappings` fields, one upsert per proposal.
+ // Save on the Account Mapping tab, match-by-code confirm-all and AI apply:
+ // repeated JSON-encoded `mappings` fields, written in one batch. The
+ // mapping services are Kysely-based (RLS bypassed) — requirePermissions
+ // above + companyId scoping is the auth gate. Stays on the page so the tab
+ // revalidates in place.
if (formData.get("intent") === "bulk-upsert-account-mappings") {
const validation = await validator(
accountMappingBulkUpsertValidator
@@ -1323,33 +1286,19 @@ export async function action({ request, params }: ActionFunctionArgs) {
}
const { mappings } = validation.data;
- const db = getDatabaseClient();
- const failures: string[] = [];
-
- for (const mapping of mappings) {
- const result = await upsertAccountMapping(db, {
- companyId,
- integration: integrationId,
- ...mapping,
- userId
- });
- if (result.error) {
- failures.push(result.error);
- }
- }
+ const result = await upsertAccountMappings(getDatabaseClient(), {
+ companyId,
+ integration: integrationId,
+ userId,
+ mappings
+ });
- if (failures.length > 0) {
- const succeeded = mappings.length - failures.length;
+ if (result.error) {
return data(
- {},
+ { success: false },
await flash(
request,
- error(
- failures[0],
- succeeded > 0
- ? `Saved ${succeeded} of ${mappings.length} account mappings`
- : "Failed to save account mappings"
- )
+ error(result.error, "Failed to save account mappings")
)
);
}
diff --git a/packages/ee/AGENTS.md b/packages/ee/AGENTS.md
index 30bcb01c6b..53cba796f1 100644
--- a/packages/ee/AGENTS.md
+++ b/packages/ee/AGENTS.md
@@ -67,7 +67,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 `/reports/trial-balance` for the year to the date in its subsidiary — `parseRilletTrialBalance` reads `ending_balance` debit-signed or natural-signed by `/accounts` type, whichever agrees with each account's movement and totals zero, else throws). 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`
+- **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 `/reports/trial-balance` from Carbon's fiscal year start (`fiscalYearSettings.startMonth`, `fiscalYearStart`) to the date in its subsidiary — Rillet closes income and expense into retained earnings at `from_date`, so that is the fiscal year to date; it sends `credit_total` negative, read as a magnitude; `parseRilletTrialBalance` reads `ending_balance` debit-signed or natural-signed by `/accounts` type, whichever agrees with each account's movement and totals zero, else throws). 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/account-mapping.ts b/packages/ee/src/accounting/core/account-mapping.ts
index 7f10ee089f..021228b073 100644
--- a/packages/ee/src/accounting/core/account-mapping.ts
+++ b/packages/ee/src/accounting/core/account-mapping.ts
@@ -5,7 +5,6 @@
import type { Database } from "@carbon/database";
import type { Kysely, KyselyDatabase, KyselyTx } from "@carbon/database/client";
import type z from "zod";
-import type { ExternalIntegrationMapping } from "./external-mapping";
import { createMappingService } from "./external-mapping";
import type {
ProviderChartAccountSchema,
@@ -79,7 +78,7 @@ export interface MappableChartAccount {
/**
* A proposed (not written) match between a Carbon account and a provider
- * account. The UI confirms proposals and calls upsertAccountMapping.
+ * account. The UI confirms proposals and calls upsertAccountMappings.
*/
export interface AccountMatchProposal {
accountId: string;
@@ -323,55 +322,66 @@ export async function loadAccountCodesById(
}
/**
- * Upsert an account mapping (Carbon account.id → provider account id).
- * externalCode/externalName go into the mapping metadata for display.
- * Consolidation is a legitimate many-to-one: several Carbon detail
- * accounts may map to a single provider account, so duplicate external
- * ids are allowed.
+ * Upsert account mappings (Carbon account.id → provider account id), all or
+ * none. externalCode/externalName go into the mapping metadata for display.
+ * Consolidation is a legitimate many-to-one: several Carbon detail accounts
+ * may map to a single provider account, so duplicate external ids are
+ * allowed. Returns the number of mappings written.
*/
-export async function upsertAccountMapping(
+export async function upsertAccountMappings(
db: Db,
- args: UpsertAccountMappingInput
-): Promise<{ data: ExternalIntegrationMapping | null; error: string | null }> {
+ args: {
+ companyId: string;
+ integration: string;
+ userId: string;
+ mappings: Array<
+ Pick<
+ UpsertAccountMappingInput,
+ "accountId" | "externalId" | "externalCode" | "externalName"
+ >
+ >;
+ }
+): Promise<{ data: number | null; error: string | null }> {
+ if (args.mappings.length === 0) return { data: 0, error: null };
+
try {
- // The account id comes from the caller (a form field on the mapping tab),
+ // The account ids come from the caller (form fields on the mapping tab),
// and this Kysely client bypasses RLS. Accounts are company-group scoped:
- // refuse one from outside the caller's group, whose number and name the
+ // refuse any from outside the caller's group, whose number and name the
// mapping list would otherwise display.
+ const accountIds = [
+ ...new Set(args.mappings.map((mapping) => mapping.accountId))
+ ];
const companyGroupId = await getCompanyGroupId(db, args.companyId);
- const account = companyGroupId
+ const accounts = companyGroupId
? await db
.selectFrom("account")
.select("id")
- .where("id", "=", args.accountId)
+ .where("id", "in", accountIds)
.where("companyGroupId", "=", companyGroupId)
- .executeTakeFirst()
- : undefined;
- if (!account) {
- return { data: null, error: `Account ${args.accountId} not found` };
+ .execute()
+ : [];
+ const found = new Set(accounts.map((account) => account.id));
+ const missing = accountIds.filter((id) => !found.has(id));
+ if (missing.length > 0) {
+ return { data: null, error: `Account ${missing.join(", ")} not found` };
}
- const mappingService = createMappingService(db, args.companyId);
-
- await mappingService.link(
- ACCOUNT_MAPPING_ENTITY_TYPE,
- args.accountId,
- args.integration,
- args.externalId,
- {
- metadata: buildAccountMappingMetadata(args),
- createdBy: args.userId,
- allowDuplicateExternalId: true
- }
- );
-
- const data = await mappingService.getByEntity(
- ACCOUNT_MAPPING_ENTITY_TYPE,
- args.accountId,
- args.integration
+ await createMappingService(db, args.companyId).linkBatch(
+ args.mappings.map((mapping) => ({
+ entityType: ACCOUNT_MAPPING_ENTITY_TYPE,
+ entityId: mapping.accountId,
+ integration: args.integration,
+ externalId: mapping.externalId,
+ options: {
+ metadata: buildAccountMappingMetadata(mapping),
+ createdBy: args.userId,
+ allowDuplicateExternalId: true
+ }
+ }))
);
- return { data, error: null };
+ return { data: args.mappings.length, error: null };
} catch (err) {
return { data: null, error: toErrorMessage(err) };
}
@@ -577,7 +587,7 @@ export async function getUnmappedRequiredAccounts(
* active, non-group, numbered account without an existing mapping (widened from
* the accountDefault-only set so an arbitrary account can be matched too). The
* proposer already excludes already-mapped Carbon ids and already-used external
- * ids; the UI confirms each proposal and calls upsertAccountMapping.
+ * ids; the UI confirms each proposal and calls upsertAccountMappings.
*/
export async function matchAccountsByCode(
db: Db,
diff --git a/packages/ee/src/accounting/core/remote-trial-balance.test.ts b/packages/ee/src/accounting/core/remote-trial-balance.test.ts
index 33774c9b50..a90fb11f4b 100644
--- a/packages/ee/src/accounting/core/remote-trial-balance.test.ts
+++ b/packages/ee/src/accounting/core/remote-trial-balance.test.ts
@@ -95,7 +95,11 @@ describe("fetchRemoteTrialBalance", () => {
})
);
- const result = await fetchRemoteTrialBalance(makeXero(), "2026-09-30");
+ const result = await fetchRemoteTrialBalance(
+ makeXero(),
+ "2026-09-30",
+ "January"
+ );
expect(result).toEqual({
supported: true,
@@ -115,9 +119,11 @@ describe("fetchRemoteTrialBalance", () => {
jsonResponse({ Title: "Forbidden", Status: 403 }, 403)
);
- const error = await fetchRemoteTrialBalance(makeXero(), "2026-09-30").catch(
- (e: unknown) => e
- );
+ const error = await fetchRemoteTrialBalance(
+ makeXero(),
+ "2026-09-30",
+ "January"
+ ).catch((e: unknown) => e);
expect(error).toBeInstanceOf(AccountingApiError);
expect((error as AccountingApiError).details.statusCode).toBe(403);
@@ -147,7 +153,11 @@ describe("fetchRemoteTrialBalance", () => {
})
);
- const result = await fetchRemoteTrialBalance(makeQbo(), "2026-09-30");
+ const result = await fetchRemoteTrialBalance(
+ makeQbo(),
+ "2026-09-30",
+ "January"
+ );
expect(result).toEqual({
supported: true,
@@ -160,7 +170,7 @@ describe("fetchRemoteTrialBalance", () => {
expect(url.searchParams.has("minorversion")).toBe(true);
});
- it("reads Rillet's trial balance for the year to the date, in its subsidiary", async () => {
+ it("reads Rillet's trial balance from the fiscal year start, in its subsidiary", async () => {
const rillet = new RilletProvider({
companyId: "company-1",
credentials: {
@@ -199,16 +209,20 @@ describe("fetchRemoteTrialBalance", () => {
name: "Payables",
beginning_balance: money("0.00"),
debit_total: money("0.00"),
- credit_total: money("500.00"),
- ending_balance: money("500.00")
+ // Rillet sends credit totals negative.
+ credit_total: money("-500.00"),
+ ending_balance: money("-500.00")
}
]
});
});
- const result = await fetchRemoteTrialBalance(rillet, "2026-09-30");
+ const result = await fetchRemoteTrialBalance(
+ rillet,
+ "2026-09-30",
+ "October"
+ );
- // `ending_balance` was natural-signed here: the payable is a credit.
expect(result).toEqual({
supported: true,
rows: [
diff --git a/packages/ee/src/accounting/core/remote-trial-balance.ts b/packages/ee/src/accounting/core/remote-trial-balance.ts
index 40b54dee75..6c4194900a 100644
--- a/packages/ee/src/accounting/core/remote-trial-balance.ts
+++ b/packages/ee/src/accounting/core/remote-trial-balance.ts
@@ -14,6 +14,7 @@ import { getAccountMappings, getCompanyGroupId } from "./account-mapping";
import type { ProviderID } from "./models";
import { getAccountingIntegration, getProviderIntegration } from "./service";
import {
+ fiscalYearStart,
type MappedTrialBalance,
mapRemoteTrialBalance,
type RemoteTrialBalance,
@@ -30,8 +31,10 @@ import {
* debit-signed per remote account. Dispatches on the concrete provider class,
* the same discrimination `fetchRemoteJournalTotals` uses.
*
- * Rillet's `ending_balance` sign is not documented; `parseRilletTrialBalance`
- * reads it the way the report itself agrees with.
+ * Rillet reads from `fiscalYearStartMonth`'s fiscal year start, where it
+ * closes income and expense into retained earnings — the fiscal year to
+ * date, like Xero's YTD columns. Its signs are not documented;
+ * `parseRilletTrialBalance` reads them the way the report itself agrees with.
*
* Provider errors propagate (AccountingApiError, AccountingAuthError,
* RatelimitError); `pullTrialBalanceFromProvider` turns them into a
@@ -39,7 +42,8 @@ import {
*/
export async function fetchRemoteTrialBalance(
provider: AccountingProvider,
- asOfDate: string
+ asOfDate: string,
+ fiscalYearStartMonth: string
): Promise<RemoteTrialBalance> {
if (provider instanceof XeroProvider) {
return { supported: true, rows: await provider.getTrialBalance(asOfDate) };
@@ -50,7 +54,13 @@ export async function fetchRemoteTrialBalance(
}
if (provider instanceof RilletProvider) {
- return { supported: true, rows: await provider.getTrialBalance(asOfDate) };
+ return {
+ supported: true,
+ rows: await provider.getTrialBalance(
+ asOfDate,
+ fiscalYearStart(asOfDate, fiscalYearStartMonth)
+ )
+ };
}
return { supported: false };
@@ -135,6 +145,12 @@ export async function pullTrialBalanceFromProvider(
);
}
+ const fiscalYear = await db
+ .selectFrom("fiscalYearSettings")
+ .select("startMonth")
+ .where("companyId", "=", companyId)
+ .executeTakeFirst();
+
let remote: RemoteTrialBalance;
try {
const provider = getProviderIntegration(
@@ -143,7 +159,11 @@ export async function pullTrialBalanceFromProvider(
integration.id,
integration.metadata
);
- remote = await fetchRemoteTrialBalance(provider, asOfDate);
+ remote = await fetchRemoteTrialBalance(
+ provider,
+ asOfDate,
+ fiscalYear?.startMonth ?? "January"
+ );
} catch (error) {
throw toPullError(error);
}
diff --git a/packages/ee/src/accounting/core/trial-balance.test.ts b/packages/ee/src/accounting/core/trial-balance.test.ts
index 7348c2628c..fac463e0ea 100644
--- a/packages/ee/src/accounting/core/trial-balance.test.ts
+++ b/packages/ee/src/accounting/core/trial-balance.test.ts
@@ -4,6 +4,7 @@
import { describe, expect, it } from "vitest";
import {
+ fiscalYearStart,
mapRemoteTrialBalance,
parseQboTrialBalance,
parseReportAmount,
@@ -405,6 +406,15 @@ describe("parseQboTrialBalance", () => {
});
});
+describe("fiscalYearStart", () => {
+ it("is the first of the start month on or before the date", () => {
+ expect(fiscalYearStart("2026-09-30", "January")).toBe("2026-01-01");
+ expect(fiscalYearStart("2026-09-30", "October")).toBe("2025-10-01");
+ expect(fiscalYearStart("2026-10-01", "October")).toBe("2026-10-01");
+ expect(fiscalYearStart("2026-03-15", "unknown")).toBe("2026-01-01");
+ });
+});
+
describe("parseRilletTrialBalance", () => {
const money = (amount: string) => ({ amount, currency: "USD" });
const account = (
@@ -473,6 +483,28 @@ describe("parseRilletTrialBalance", () => {
).toThrow(/does not balance/);
});
+ it("reads credit totals Rillet sends negative", () => {
+ // Shaped like a Rillet sandbox report (2026-10-13): debit-signed
+ // balances, credit totals negative, income and expense starting at zero.
+ const rows = parseRilletTrialBalance(
+ {
+ accounts: [
+ account("cash", "220387.54", "49019.18", "-249090.80", "20315.92"),
+ account("ap", "8066.63", "100.00", "-367062.55", "-358895.92"),
+ account("revenue", "0.00", "3900.00", "-3980932.65", "-3977032.65"),
+ account("retained", "4315612.65", "0.00", "0.00", "4315612.65")
+ ]
+ },
+ new Map([...types, ["revenue", "INCOME"], ["retained", "EQUITY"]])
+ );
+ expect(balances(rows)).toEqual({
+ cash: 20315.92,
+ ap: -358895.92,
+ revenue: -3977032.65,
+ retained: 4315612.65
+ });
+ });
+
it("reads the FX totals as movement", () => {
const rows = parseRilletTrialBalance(
{
diff --git a/packages/ee/src/accounting/core/trial-balance.ts b/packages/ee/src/accounting/core/trial-balance.ts
index c02e3dc0e7..a344fea20c 100644
--- a/packages/ee/src/accounting/core/trial-balance.ts
+++ b/packages/ee/src/accounting/core/trial-balance.ts
@@ -3,6 +3,7 @@
// (packages/ee/LICENSE). Not AGPL. Running, modifying, or copying it beyond those terms requires a commercial license.
import { round } from "@carbon/utils";
+import { CalendarDate, parseDate } from "@internationalized/date";
import { ProviderID } from "./models";
/**
@@ -312,6 +313,34 @@ export function parseQboTrialBalance(
// Rillet — GET /reports/trial-balance?from_date&to_date[&subsidiary_id]
// ---------------------------------------------------------------------------
+const MONTHS = [
+ "January",
+ "February",
+ "March",
+ "April",
+ "May",
+ "June",
+ "July",
+ "August",
+ "September",
+ "October",
+ "November",
+ "December"
+] as const;
+
+/**
+ * The first day of the fiscal year that contains `asOfDate` (YYYY-MM-DD),
+ * for a fiscal year starting on the first of `startMonth` (Carbon's
+ * `fiscalYearSettings.startMonth`, e.g. "October"). An unknown month reads
+ * as January.
+ */
+export function fiscalYearStart(asOfDate: string, startMonth: string): string {
+ const date = parseDate(asOfDate);
+ const month = MONTHS.indexOf(startMonth as (typeof MONTHS)[number]) + 1 || 1;
+ const year = date.month >= month ? date.year : date.year - 1;
+ return new CalendarDate(year, month, 1).toString();
+}
+
type RilletAmount = { amount?: string | null } | null | undefined;
export type RilletTrialBalanceAccount = {
@@ -347,14 +376,22 @@ const REPORT_TOLERANCE = 0.005;
* Reduce Rillet's trial balance to one row per account, the balance at the
* report's `to_date`.
*
- * Rillet's docs do not say how `ending_balance` is signed, so the parser
- * reads it both ways — debit-signed, and positive on each account's natural
- * side (credit for LIABILITY, EQUITY and INCOME, by `accountTypes`) — and
- * keeps the reading that agrees with the report itself: every account's
+ * Rillet closes income and expense into retained earnings at the report's
+ * `from_date`: they begin at zero and end at their movement in the report,
+ * so the caller picks `from_date` (the fiscal year start).
+ *
+ * Rillet sends `credit_total` negative (a sandbox ledger, 2026-10-13), and
+ * its docs say nothing either way, so credits are read as a magnitude:
+ * movement = debits − |credits|.
+ *
+ * Rillet's docs do not say how `ending_balance` is signed either, so the
+ * parser reads it both ways — debit-signed, and positive on each account's
+ * natural side (credit for LIABILITY, EQUITY and INCOME, by `accountTypes`) —
+ * and keeps the reading that agrees with the report itself: every account's
* `ending − beginning` must equal its period movement signed the same way,
* and the debit-signed balances must total zero. When neither reading
* agrees, or both do and give different balances, it throws rather than
- * guess.
+ * guess. The sandbox ledger is debit-signed.
*/
export function parseRilletTrialBalance(
response: RilletTrialBalanceResponse,
@@ -365,8 +402,8 @@ export function parseRilletTrialBalance(
parseReportAmount(account.debit_total?.amount) +
parseReportAmount(account.debit_fx_total?.amount);
const credits =
- parseReportAmount(account.credit_total?.amount) +
- parseReportAmount(account.credit_fx_total?.amount);
+ Math.abs(parseReportAmount(account.credit_total?.amount)) +
+ Math.abs(parseReportAmount(account.credit_fx_total?.amount));
const creditNatured = RILLET_CREDIT_NATURED.has(
accountTypes.get(account.id ?? "") ?? ""
);
diff --git a/packages/ee/src/accounting/providers/rillet/provider.ts b/packages/ee/src/accounting/providers/rillet/provider.ts
index d7940af5a3..33a88ace56 100644
--- a/packages/ee/src/accounting/providers/rillet/provider.ts
+++ b/packages/ee/src/accounting/providers/rillet/provider.ts
@@ -3,7 +3,6 @@
// (packages/ee/LICENSE). Not AGPL. Running, modifying, or copying it beyond those terms requires a commercial license.
import { createHash } from "node:crypto";
-import { parseDate } from "@internationalized/date";
import type {
CounterpartSearchKeys,
ExternalIdentityKind,
@@ -599,20 +598,17 @@ export class RilletProvider extends BaseProvider {
/**
* The trial balance as at `date` (YYYY-MM-DD), one row per account
- * (GET /reports/trial-balance), scoped to the configured subsidiary. The
- * report covers the year to `date`, so most accounts move in it: that
- * movement is how `parseRilletTrialBalance` tells which sign
- * `ending_balance` uses. Account types come from GET /accounts, inactive
+ * (GET /reports/trial-balance), scoped to the configured subsidiary.
+ * Rillet closes income and expense into retained earnings at `fromDate`,
+ * so pass the fiscal year start: income and expense then hold the
+ * fiscal year to date. Account types come from GET /accounts, inactive
* accounts included, since a closed account can still carry a balance.
*/
- async getTrialBalance(date: string): Promise<RemoteTrialBalanceRow[]> {
- const params = new URLSearchParams({
- from_date: parseDate(date)
- .subtract({ years: 1 })
- .add({ days: 1 })
- .toString(),
- to_date: date
- });
+ async getTrialBalance(
+ date: string,
+ fromDate: string
+ ): Promise<RemoteTrialBalanceRow[]> {
+ const params = new URLSearchParams({ from_date: fromDate, to_date: date });
if (this.subsidiaryId) params.set("subsidiary_id", this.subsidiaryId);
const [report, accounts] = await Promise.all([