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
Accounting sync switch, Sync Activity CSV export, inventory running balance, Xero item-code fix (#1819)
Brad Barbin449c4c99b301
diff --git a/.claude/rules/accounting-sync-handlers.md b/.claude/rules/accounting-sync-handlers.mdindex 186682f431..56845fd08e 100644--- a/.claude/rules/accounting-sync-handlers.md+++ b/.claude/rules/accounting-sync-handlers.md@@ -43,6 +43,36 @@ These live in `packages/jobs/src/inngest/functions/integrations/` (+ `events/syn| `accounting-reconciliation` | — | `accounting-reconciliation.ts` | cron `0 3 * * 1` (Mondays 03:00 UTC) — presence drift check + `accountingSyncTieOut` writer; see the tie-out section below || `event-handler-sync` | `carbon/event-sync` | `events/sync.ts` | the SYNC event-system handler (see event-system.md) — DB writes -> push to the provider |+### The sync switch — off until accounts are mapped++`metadata.settings.syncEnabled`, read ONLY through `isAccountingSyncEnabled` (`core/models.ts`).+Absent reads as ON (rows that predate the switch were already syncing); every connect path writes+an explicit value. A new connection starts OFF so the customer can map accounts first: the+OAuth callbacks (`integrations.{xero,quickbooks}.oauth.ts`) use `syncEnabledOnConnect`, which+keeps the existing value only for a reconnect to the SAME tenant/realm (a dead-grant reconnect+must not pause a live integration), and the form install (Rillet) writes `false` when+`!wasInstalled`. It is NOT `companyIntegration.active` — the role trigger, topology, Installed+badge and account-mapping tabs all key on `active`, and they must keep working while sync is off.++The drawer header's `AccountingSyncControl` posts intent `update-sync-enabled`; the action+refuses ON while `getUnmappedRequiredAccounts` (`core/account-mapping.ts`) is non-empty. The+"required" set — `selectRequiredMappingAccountIds`: every `accountDefault` account plus every+Expense account, among active leaf accounts — is the same one the Account Mapping tab badges.++While off, nothing moves: `events/sync.ts` skips before reconciling, the four crons filter their+targets, `sync-external-accounting` enqueues nothing, a master-data PUSH and the journal backfill+refuse (route) and no-op (job), the three webhooks acknowledge before any provider call, and+`drainSyncOperations` returns before claiming — the backstop for a Retry clicked in Sync+Activity, which then drains once sync is on. The one thing that runs is **Import customers &+vendors**: it only writes into Carbon, and the mapping rows it creates are what stop the first+push after sync is on from duplicating contacts in the ledger. Its drain passes+`only: { entityTypes: [<customer|vendor>], direction: "pull-from-accounting" }`+(`claimPendingOperations` filters on both), and that scoped pull is the drain's single exception —+so the import never flushes a Retry or anything else that is waiting. Period close's external-GL check treats a sync-off+integration like a disconnected one (it inlines the flag read — `accounting.service.ts` cannot+import the barrel). Turning sync on starts the pull cursor from `integration.updatedAt` (the+toggle bumps it); the outbound sweep covers the last 7 days and the journal backfill the rest.+### Per-tenant isolation and dead OAuth grantsThe four crons (`pull-sweep`, `outbound-sweep`, `reconciliation`, `consolidation`) walk every active integration with one `step.run` per company, through `runIsolatedCompanyStep` (`accounting-auth-failure.ts`). Two invariants: a tenant that exhausts its step retries returns `{ error }` and the loop continues — it never fails the run for every tenant after it (it used to: one company with a dead token skipped every later company on every sweep); and an `AccountingAuthError` (the provider's token endpoint answered 400/401 — `invalid_grant` "Refresh token not found", revoked, rotated-and-lost) is NOT retried, because nothing retries a dead grant back to life. It returns `{ authFailed }`, `recordIntegrationAuthFailure` increments a redis counter (`integrations:<companyId>:<providerId>:auth-failures`, cleared by any successful pass), notifies the configurer (`integration.updatedBy`, `NotificationEvent.IntegrationSync`, deduped to one per day), and at `AUTH_FAILURE_DISABLE_THRESHOLD` (12 consecutive ≈ 3 h across both sweeps — `drainSyncOperations` rethrows `AccountingAuthError` like `RatelimitError` instead of parking it as Failed rows, so drain-path auth failures count too) sets `companyIntegration.active = false`, clears the integration cache keys, and notifies "disabled — reconnect". The OAuth callback routes upsert `active: true`, so reconnecting is the whole recovery. Note a deactivated accounting integration makes the period-close "External GL sync complete" blocker auto-pass (it only checks ACTIVE integrations) — that is the trade-off the user chose over an integration that sits active and silently syncs nothing.diff --git a/apps/erp/app/modules/accounting/accounting.service.ts b/apps/erp/app/modules/accounting/accounting.service.tsindex eb5b386423..bc59c01f32 100644--- a/apps/erp/app/modules/accounting/accounting.service.ts+++ b/apps/erp/app/modules/accounting/accounting.service.ts@@ -3031,14 +3031,25 @@ export async function getPeriodExternalGlSyncReadiness(): Promise<{ failing: boolean; count: number; postingSyncEnabled: boolean }> {const integrations = await client.from("companyIntegration")- .select("id")+ .select("id, metadata").eq("companyId", companyId).eq("active", true).in("id", ACCOUNTING_SYNC_INTEGRATION_IDS);- const enabledIntegrationIds = (integrations.data ?? []).map(- (integration) => integration.id- );+ // An integration with sync turned off (still being set up) delivers nothing,+ // so it is treated like a disconnected one. Mirrors `isAccountingSyncEnabled`+ // in @carbon/ee/accounting, which this module cannot import (see above):+ // absent means on, only an explicit false is off.+ const enabledIntegrationIds = (integrations.data ?? [])+ .filter(+ (integration) =>+ (+ integration.metadata as {+ settings?: { syncEnabled?: unknown };+ } | null+ )?.settings?.syncEnabled !== false+ )+ .map((integration) => integration.id);if (enabledIntegrationIds.length === 0) {return { failing: false, count: 0, postingSyncEnabled: false };diff --git a/apps/erp/app/modules/inventory/AGENTS.md b/apps/erp/app/modules/inventory/AGENTS.mdindex 91b70697bd..1a30d24fcf 100644--- a/apps/erp/app/modules/inventory/AGENTS.md+++ b/apps/erp/app/modules/inventory/AGENTS.md@@ -61,6 +61,7 @@ pnpm exec turbo run typecheck --filter=erp # the app's package name is "erp",- `getInventoryItems` / `getInventoryItemsCount` — calls `get_inventory_quantities` RPC for on-hand quantities- `getItemLedgerPage` / `getItemLedgerActivity` — paginated ledger history+- `getItemLedgerBalance` — `get_item_ledger_balance` RPC: on-hand right after one ledger entry, on the `quantityOnHand` definition (Rejected tracked stock counts zero). The item Activity feed fetches it ONCE for its newest loaded row; `withRunningBalance` (`ui/Inventory/ledgerFeed.ts`) derives every row's before → after from it as pages load, so paging adds no queries. Run it on raw rows, before `collapseTransferPairs`- `insertManualInventoryAdjustment` — adjustments with tracked entity handling; wraps the `post-inventory-adjustment` edge function, which also maintains cost layers and posts GL journals (5310 vs RM/FG) in one transaction when accounting is enabled- `correctStockMovement` — wraps the `correct-stock-movement` edge function: fixes a posted `itemLedger` row by booking ONE opposite (delta) movement linked via `correctionOfItemLedgerId`, dated with the original's `postingDate` and posted into the original's accounting period (fails if Locked/Closed). The delta is derived against the movement's current effective quantity (original + prior corrections), so repeat corrections converge- `getStorageUnit(s)` / `getStorageUnitTree` / `getStorageUnitsTreeForLocation` — storage hierarchydiff --git a/apps/erp/app/modules/inventory/inventory.service.ts b/apps/erp/app/modules/inventory/inventory.service.tsindex b8415269af..942c56009f 100644--- a/apps/erp/app/modules/inventory/inventory.service.ts+++ b/apps/erp/app/modules/inventory/inventory.service.ts@@ -294,6 +294,31 @@ export async function getItemLedgerActivity(return { data: rows, hasMore: (data?.length ?? 0) === pageSize, error };}+/**+ * On-hand quantity of an item at a location right after ledger entry+ * `entryNumber` (omit it for on-hand now), on the same definition as the+ * inventory table's On Hand column. The Activity panel fetches this once for+ * its newest loaded entry and derives every other row's balance from the+ * contiguous pages — see `withRunningBalance`.+ * @mcp read+ */+export async function getItemLedgerBalance(+ client: SupabaseClient<Database>,+ args: {+ itemId: string;+ companyId: string;+ locationId: string;+ entryNumber?: number;+ }+) {+ return client.rpc("get_item_ledger_balance", {+ company_id: args.companyId,+ location_id: args.locationId,+ item_id: args.itemId,+ entry_number: args.entryNumber+ });+}+/** @mcp read */export async function getBatchProperties(client: SupabaseClient<Database>,diff --git a/apps/erp/app/modules/inventory/ui/Inventory/InventoryActivity.tsx b/apps/erp/app/modules/inventory/ui/Inventory/InventoryActivity.tsxindex 0faa1004ae..efdff3d0b5 100644--- a/apps/erp/app/modules/inventory/ui/Inventory/InventoryActivity.tsx+++ b/apps/erp/app/modules/inventory/ui/Inventory/InventoryActivity.tsx@@ -2,8 +2,11 @@// 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 { cn } from "@carbon/react";+import { useLingui } from "@lingui/react/macro";import { memo } from "react";import {+ LuArrowRight,LuArrowRightLeft,LuExternalLink,LuMoveDown,@@ -11,65 +14,10 @@ import {} from "react-icons/lu";import { Link } from "react-router";import Activity from "~/components/Activity";+import { useQuantityFormatter } from "~/hooks";import { path } from "~/utils/path";import type { ItemLedger } from "../../types";--// A Direct Transfer writes two ledger rows in one transaction — the negative-// out of the source bin and the positive into the destination — so the feed-// renders the same move twice. Collapse each pair into the inbound row and hang-// the source bin off it.-//-// The pair is identified by document + item + tracked entity + `createdAt`:-// Postgres NOW() is transaction time, so both rows share it exactly. Keying on-// the timestamp keeps repeat picks of the same line as separate entries, and-// makes the merge idempotent, so it's safe to re-run over the accumulated list-// as infinite scroll appends pages.-export type CollapsedItemLedger = ItemLedger & {- transferFromStorageUnitName?: string | null;-};--export function collapseTransferPairs(- rows: ItemLedger[]-): CollapsedItemLedger[] {- // Batch Split rows are internal net-zero bookkeeping — the Transfer/- // Consumption rows tell the real story, so they never reach the feed.- rows = rows.filter((row) => row.documentType !== "Batch Split");-- const pairKey = (row: ItemLedger) =>- [row.documentId, row.itemId, row.trackedEntityId ?? "", row.createdAt].join(- "|"- );-- const outboundByKey = new Map<string, ItemLedger>();- for (const row of rows) {- if (row.documentType !== "Direct Transfer" || row.quantity >= 0) continue;- outboundByKey.set(pairKey(row), row);- }-- return rows.reduce<CollapsedItemLedger[]>((acc, row) => {- if (row.documentType !== "Direct Transfer") return [...acc, row];- const outbound = outboundByKey.get(pairKey(row));- // Drop the outbound half only when its inbound partner is present to- // absorb it — otherwise (destination page not loaded yet) keep it, so a- // transfer never vanishes from the feed.- if (row.quantity < 0) {- const hasInbound = rows.some(- (r) =>- r.documentType === "Direct Transfer" &&- r.quantity > 0 &&- pairKey(r) === pairKey(row)- );- return hasInbound ? acc : [...acc, row];- }- return [- ...acc,- {- ...row,- transferFromStorageUnitName: outbound?.storageUnit?.name ?? null- }- ];- }, []);-}+import type { CollapsedItemLedger } from "./ledgerFeed";const getActivityText = (ledgerRecord: CollapsedItemLedger,@@ -328,6 +276,44 @@ const getActivityIcon = (ledgerRecord: ItemLedger) => {}};+// On hand before → after the entry, like the On Hand column of the item's+// supply and demand list. Red once the balance is negative.+function OnHandChange({+ balanceBefore,+ balanceAfter+}: {+ balanceBefore: number;+ balanceAfter: number;+}) {+ const { t } = useLingui();+ const formatQuantity = useQuantityFormatter();+ const before = formatQuantity(balanceBefore);+ const after = formatQuantity(balanceAfter);++ return (+ <span title={t`On hand`}>+ <span className="sr-only">{t`On hand ${before} to ${after}`}</span>+ <span+ aria-hidden+ className="flex items-center gap-1.5 text-sm tabular-nums"+ >+ <span+ className={cn(+ "text-muted-foreground",+ balanceBefore < 0 && "text-red-500"+ )}+ >+ {before}+ </span>+ <LuArrowRight className="size-3 text-muted-foreground" />+ <span className={cn("font-medium", balanceAfter < 0 && "text-red-500")}>+ {after}+ </span>+ </span>+ </span>+ );+}+type InventoryActivityProps = {item: CollapsedItemLedger;highlightId?: string;@@ -347,7 +333,19 @@ const InventoryActivity = memo(employeeId={item.createdBy}activityMessage={getActivityText(item, trackingNoun)}activityTime={item.createdAt}- activityIcon={getActivityIcon(item)}+ activityIcon={+ item.balanceBefore != null && item.balanceAfter != null ? (+ <div className="flex items-center gap-3">+ <OnHandChange+ balanceBefore={item.balanceBefore}+ balanceAfter={item.balanceAfter}+ />+ {getActivityIcon(item)}+ </div>+ ) : (+ getActivityIcon(item)+ )+ }comment={item.comment}highlighted={highlightId === item.id}/>diff --git a/apps/erp/app/modules/inventory/ui/Inventory/index.ts b/apps/erp/app/modules/inventory/ui/Inventory/index.tsindex f5e6304fb8..f68370c6a2 100644--- a/apps/erp/app/modules/inventory/ui/Inventory/index.ts+++ b/apps/erp/app/modules/inventory/ui/Inventory/index.ts@@ -6,5 +6,13 @@ import InventoryActivity from "./InventoryActivity";import InventoryDetails from "./InventoryDetails";export { InventoryActivity, InventoryDetails };-export type { CollapsedItemLedger } from "./InventoryActivity";-export { collapseTransferPairs } from "./InventoryActivity";+export type {+ BalanceAnchor,+ CollapsedItemLedger,+ RunningBalance+} from "./ledgerFeed";+export {+ collapseTransferPairs,+ onHandDelta,+ withRunningBalance+} from "./ledgerFeed";diff --git a/apps/erp/app/modules/inventory/ui/Inventory/ledgerFeed.test.ts b/apps/erp/app/modules/inventory/ui/Inventory/ledgerFeed.test.tsnew file mode 100644index 0000000000..dca4554ca4--- /dev/null+++ b/apps/erp/app/modules/inventory/ui/Inventory/ledgerFeed.test.ts@@ -0,0 +1,143 @@+// 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 { describe, expect, it } from "vitest";+import type { ItemLedger } from "../../types";+import { collapseTransferPairs, withRunningBalance } from "./ledgerFeed";++const row = (+ entryNumber: number,+ quantity: number,+ trackedEntityStatus: string | null = null+) => ({ entryNumber, quantity, trackedEntityStatus });++const balances = (rows: ReturnType<typeof withRunningBalance>) =>+ rows.map((r) => [r.balanceBefore, r.balanceAfter]);++describe("withRunningBalance", () => {+ // newest → oldest, as the feed holds them: +50, −2, +60, −10 → on hand 98+ const rows = [row(4, -10), row(3, 60), row(2, -2), row(1, 50)];++ it("walks older rows down from an anchor on the newest", () => {+ expect(+ balances(withRunningBalance(rows, { entryNumber: 4, balanceAfter: 98 }))+ ).toEqual([+ [108, 98],+ [48, 108],+ [50, 48],+ [0, 50]+ ]);+ });++ it("walks newer rows up from an anchor in the middle", () => {+ // A highlight navigation anchors on an older entry; "Load newer" then+ // prepends rows above it.+ expect(+ balances(withRunningBalance(rows, { entryNumber: 2, balanceAfter: 48 }))+ ).toEqual([+ [108, 98],+ [48, 108],+ [50, 48],+ [0, 50]+ ]);+ });++ it("counts a Rejected tracked entity's row as no change", () => {+ const withRejected = [row(3, 5), row(2, 7, "Rejected"), row(1, 10)];+ expect(+ balances(+ withRunningBalance(withRejected, { entryNumber: 3, balanceAfter: 15 })+ )+ ).toEqual([+ [10, 15],+ [10, 10],+ [0, 10]+ ]);+ });++ it("does not leak float noise into the balance", () => {+ const fractional = [row(3, 0.1), row(2, 0.2), row(1, 0.3)];+ const [, , oldest] = withRunningBalance(fractional, {+ entryNumber: 3,+ balanceAfter: 0.6+ });+ expect(oldest.balanceBefore).toBe(0);+ });++ it("leaves rows unpriced without an anchor, or when it is not loaded", () => {+ expect(balances(withRunningBalance(rows, null))).toEqual(+ rows.map(() => [null, null])+ );+ expect(+ balances(withRunningBalance(rows, { entryNumber: 99, balanceAfter: 1 }))+ ).toEqual(rows.map(() => [null, null]));+ });+});++describe("collapseTransferPairs with a running balance", () => {+ const ledger = (+ entryNumber: number,+ quantity: number,+ overrides: Partial<ItemLedger> = {}+ ) =>+ ({+ id: `il${entryNumber}`,+ entryNumber,+ quantity,+ itemId: "item",+ documentId: "doc",+ documentType: null,+ trackedEntityId: null,+ trackedEntityStatus: null,+ createdAt: `2026-10-02T00:00:0${entryNumber}Z`,+ storageUnit: { name: `Bin ${entryNumber}` },+ ...overrides+ }) as unknown as ItemLedger;++ it("spans both halves of a bin-to-bin transfer, so it reads as no change", () => {+ const transfer = {+ documentType: "Direct Transfer",+ createdAt: "2026-10-02T00:00:00Z"+ } as Partial<ItemLedger>;+ const raw = [+ ledger(3, 4, transfer), // inbound to Bin 3+ ledger(2, -4, transfer), // outbound from Bin 2+ ledger(1, 10)+ ];++ const collapsed = collapseTransferPairs(+ withRunningBalance(raw, { entryNumber: 3, balanceAfter: 10 })+ );++ expect(collapsed).toHaveLength(2);+ expect(collapsed[0]).toMatchObject({+ quantity: 4,+ transferFromStorageUnitName: "Bin 2",+ balanceBefore: 10,+ balanceAfter: 10+ });+ expect(collapsed[1]).toMatchObject({ balanceBefore: 0, balanceAfter: 10 });+ });++ it("prices around a hidden Batch Split", () => {+ const split = { documentType: "Batch Split" } as Partial<ItemLedger>;+ const raw = [+ ledger(4, -3),+ ledger(3, 5, split),+ ledger(2, -5, split),+ ledger(1, 10)+ ];++ const collapsed = collapseTransferPairs(+ withRunningBalance(raw, { entryNumber: 4, balanceAfter: 7 })+ );++ expect(+ collapsed.map((r) => [r.entryNumber, r.balanceBefore, r.balanceAfter])+ ).toEqual([+ [4, 10, 7],+ [1, 0, 10]+ ]);+ });+});diff --git a/apps/erp/app/modules/inventory/ui/Inventory/ledgerFeed.ts b/apps/erp/app/modules/inventory/ui/Inventory/ledgerFeed.tsnew file mode 100644index 0000000000..8efdb811e2--- /dev/null+++ b/apps/erp/app/modules/inventory/ui/Inventory/ledgerFeed.ts@@ -0,0 +1,147 @@+// 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 { round } from "@carbon/utils";+import type { ItemLedger } from "../../types";++export type RunningBalance = {+ /** On-hand before this entry; null when the feed has no anchor for it. */+ balanceBefore: number | null;+ /** On-hand after this entry; null when the feed has no anchor for it. */+ balanceAfter: number | null;+};++export type BalanceAnchor = {+ /** The entry the balance was measured right after. */+ entryNumber: number;+ balanceAfter: number;+};++type LedgerRow = {+ entryNumber: number;+ quantity: number;+ trackedEntityStatus?: string | null;+};++/**+ * What a ledger row moves the On Hand column by. A row whose tracked entity is+ * Rejected counts as zero, as it does in get_inventory_quantities.+ */+export function onHandDelta(row: LedgerRow) {+ return row.trackedEntityStatus === "Rejected" ? 0 : row.quantity;+}++/**+ * Stamp every row with the on-hand before and after it.+ *+ * `rows` is the feed's accumulated list — newest→oldest and contiguous by+ * `entryNumber`, which the keyset paging guarantees — and `anchor` is the one+ * balance the server measured (get_item_ledger_balance). Walking out from the+ * anchor in both directions prices every loaded page, so paging older or newer+ * never needs another query.+ *+ * Run this on the RAW rows, before collapsing transfer pairs or dropping Batch+ * Split rows: those hidden rows still move the balance one at a time.+ */+export function withRunningBalance<T extends LedgerRow>(+ rows: T[],+ anchor: BalanceAnchor | null+): (T & RunningBalance)[] {+ const anchorIndex = anchor+ ? rows.findIndex((row) => row.entryNumber === anchor.entryNumber)+ : -1;++ if (!anchor || anchorIndex === -1) {+ return rows.map((row) => ({+ ...row,+ balanceBefore: null,+ balanceAfter: null+ }));+ }++ const after = new Array<number>(rows.length);+ after[anchorIndex] = anchor.balanceAfter;+ // Older rows sit below: each one ends where the newer row above it began.+ for (let i = anchorIndex + 1; i < rows.length; i++) {+ after[i] = round(after[i - 1] - onHandDelta(rows[i - 1]));+ }+ // Newer rows sit above: each one ends its own quantity past the row below.+ for (let i = anchorIndex - 1; i >= 0; i--) {+ after[i] = round(after[i + 1] + onHandDelta(rows[i]));+ }++ return rows.map((row, i) => ({+ ...row,+ balanceBefore: round(after[i] - onHandDelta(row)),+ balanceAfter: after[i]+ }));+}++// A Direct Transfer writes two ledger rows in one transaction — the negative+// out of the source bin and the positive into the destination — so the feed+// renders the same move twice. Collapse each pair into the inbound row and hang+// the source bin off it.+//+// The pair is identified by document + item + tracked entity + `createdAt`:+// Postgres NOW() is transaction time, so both rows share it exactly. Keying on+// the timestamp keeps repeat picks of the same line as separate entries, and+// makes the merge idempotent, so it's safe to re-run over the accumulated list+// as infinite scroll appends pages.+//+// Rows carrying a running balance keep it across the merge: the collapsed entry+// spans both halves, from the older half's balance before to the newer half's+// balance after — so a move between two bins of one location reads as no change.+export type CollapsedItemLedger = ItemLedger &+ Partial<RunningBalance> & {+ transferFromStorageUnitName?: string | null;+ };++export function collapseTransferPairs<+ T extends ItemLedger & Partial<RunningBalance>+>(rows: T[]): (T & CollapsedItemLedger)[] {+ // Batch Split rows are internal net-zero bookkeeping — the Transfer/+ // Consumption rows tell the real story, so they never reach the feed.+ rows = rows.filter((row) => row.documentType !== "Batch Split");++ const pairKey = (row: ItemLedger) =>+ [row.documentId, row.itemId, row.trackedEntityId ?? "", row.createdAt].join(+ "|"+ );++ const outboundByKey = new Map<string, T>();+ for (const row of rows) {+ if (row.documentType !== "Direct Transfer" || row.quantity >= 0) continue;+ outboundByKey.set(pairKey(row), row);+ }++ return rows.reduce<(T & CollapsedItemLedger)[]>((acc, row) => {+ if (row.documentType !== "Direct Transfer") return [...acc, row];+ const outbound = outboundByKey.get(pairKey(row));+ // Drop the outbound half only when its inbound partner is present to+ // absorb it — otherwise (destination page not loaded yet) keep it, so a+ // transfer never vanishes from the feed.+ if (row.quantity < 0) {+ const hasInbound = rows.some(+ (r) =>+ r.documentType === "Direct Transfer" &&+ r.quantity > 0 &&+ pairKey(r) === pairKey(row)+ );+ return hasInbound ? acc : [...acc, row];+ }+ const [older, newer] =+ outbound && outbound.entryNumber > row.entryNumber+ ? [row, outbound]+ : [outbound ?? row, row];+ return [+ ...acc,+ {+ ...row,+ transferFromStorageUnitName: outbound?.storageUnit?.name ?? null,+ balanceBefore: older.balanceBefore,+ balanceAfter: newer.balanceAfter+ }+ ];+ }, []);+}diff --git a/apps/erp/app/modules/settings/settings.models.ts b/apps/erp/app/modules/settings/settings.models.tsindex fb816babe6..f54b07bf52 100644--- a/apps/erp/app/modules/settings/settings.models.ts+++ b/apps/erp/app/modules/settings/settings.models.ts@@ -615,6 +615,16 @@ export const postingSyncSettingsValidator = z.object({lockDate: zfd.text(z.string().optional())});+/**+ * Turns an accounting integration's sync on or off (the switch in the+ * integration drawer header). The action refuses "on" while any required+ * account is unmapped.+ */+export const syncEnabledValidator = z.object({+ intent: z.literal("update-sync-enabled"),+ syncEnabled: z.enum(["true", "false"]).transform((value) => value === "true")+});+/*** Saves the dimension-slot configuration (Dimensions tab): which Carbon* dimensions ride along on pushed journals and which provider analyticsdiff --git a/apps/erp/app/modules/settings/settings.server.ts b/apps/erp/app/modules/settings/settings.server.tsindex 4585145810..dfe97be441 100644--- a/apps/erp/app/modules/settings/settings.server.ts+++ b/apps/erp/app/modules/settings/settings.server.ts@@ -7,10 +7,12 @@ import { getCarbonServiceRole } from "@carbon/auth/client.server";import type { Database, Json } from "@carbon/database";import {getIntegrationConfigById,+ getIntegrationIdsByRole,type IntegrationID,resolveIntegrationSecrets,splitSecrets} from "@carbon/ee";+import { isAccountingSyncEnabled } from "@carbon/ee/accounting";import { getIntegrationServerHooks } from "@carbon/ee/hooks.server";import { patchRampSettings } from "@carbon/ee/ramp.server";import { redis } from "@carbon/kv";@@ -469,9 +471,38 @@ export async function updateCustomFieldsSortOrder(}}+export type IntegrationHealthStatus =+ | "healthy"+ | "unhealthy"+ | "inactive"+ | "sync-off";++/**+ * Connection health, plus `sync-off` for an accounting integration whose+ * connection works but whose sync switch is off (a new connection still being+ * set up, or one switched off since). A broken connection still reads+ * `unhealthy` — that is the more urgent thing to show.+ */export async function getIntegrationHealth(companyId: string,integration: Integration+): Promise<Integration & { health: IntegrationHealthStatus }> {+ const result = await getConnectionHealth(companyId, integration);+ if (+ result.health === "healthy" &&+ (getIntegrationIdsByRole("accounting") as string[]).includes(+ integration.id ?? ""+ ) &&+ !isAccountingSyncEnabled(integration.metadata)+ ) {+ return { ...result, health: "sync-off" };+ }+ return result;+}++async function getConnectionHealth(+ companyId: string,+ integration: Integration): Promise<Integration & { health: "healthy" | "unhealthy" | "inactive" }> {if (!integration.active) {return {diff --git a/apps/erp/app/modules/settings/ui/Integrations/AccountingSyncControl.tsx b/apps/erp/app/modules/settings/ui/Integrations/AccountingSyncControl.tsxnew file mode 100644index 0000000000..1d94c66646--- /dev/null+++ b/apps/erp/app/modules/settings/ui/Integrations/AccountingSyncControl.tsx@@ -0,0 +1,110 @@+// 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 { Badge, Button, Switch } from "@carbon/react";+import { Plural, Trans, useLingui } from "@lingui/react/macro";+import { useFetcher, useSearchParams } from "react-router";+import { usePermissions } from "~/hooks";++type AccountingSyncControlProps = {+ enabled: boolean;+ /** Required accounts with no provider account yet; sync stays off while > 0. */+ unmappedRequiredCount: number;+};++/**+ * The on/off switch for an accounting integration's sync, shown in the+ * integration drawer header. A new connection starts off so accounts can be+ * mapped first; the switch only turns on once every required account is mapped+ * (the action enforces the same rule).+ */+export function AccountingSyncControl({+ enabled,+ unmappedRequiredCount+}: AccountingSyncControlProps) {+ const { t } = useLingui();+ const permissions = usePermissions();+ const fetcher = useFetcher();+ const [, setSearchParams] = useSearchParams();++ const isSubmitting = fetcher.state !== "idle";+ const checked = fetcher.formData+ ? fetcher.formData.get("syncEnabled") === "true"+ : enabled;+ const isBlocked = !checked && unmappedRequiredCount > 0;++ return (+ <div className="flex items-start justify-between gap-4 rounded-md border border-border bg-muted/40 px-3 py-2">+ <div className="flex min-w-0 flex-col gap-1">+ <div className="flex items-center gap-2">+ <span className="text-sm font-medium">+ <Trans>Sync</Trans>+ </span>+ {checked ? (+ <Badge variant="green">+ <Trans>On</Trans>+ </Badge>+ ) : (+ <Badge variant="secondary">+ <Trans>Off</Trans>+ </Badge>+ )}+ </div>+ <p className="text-xs text-muted-foreground">+ {checked ? (+ <Trans>+ Records and posted journals are being sent to and received from+ this provider.+ </Trans>+ ) : isBlocked ? (+ <>+ <Trans>Nothing is synced until you turn sync on.</Trans>{" "}+ <Plural+ value={unmappedRequiredCount}+ one="Map the # remaining required account first."+ other="Map the # remaining required accounts first."+ />+ </>+ ) : (+ <Trans>+ Nothing is synced until you turn sync on. Every required account+ is mapped.+ </Trans>+ )}+ </p>+ {isBlocked && (+ <Button+ variant="link"+ size="sm"+ className="self-start px-0"+ onClick={() =>+ setSearchParams(+ (params) => {+ params.set("tab", "account-mapping");+ return params;+ },+ { replace: true }+ )+ }+ >+ <Trans>Open Account Mapping</Trans>+ </Button>+ )}+ </div>+ <Switch+ checked={checked}+ disabled={+ !permissions.can("update", "settings") || isSubmitting || isBlocked+ }+ aria-label={t`Sync`}+ onCheckedChange={(next) =>+ fetcher.submit(+ { intent: "update-sync-enabled", syncEnabled: String(next) },+ { method: "post" }+ )+ }+ />+ </div>+ );+}diff --git a/apps/erp/app/modules/settings/ui/Integrations/IntegrationCard.tsx b/apps/erp/app/modules/settings/ui/Integrations/IntegrationCard.tsxindex 7e1fd5bc94..30cc684df4 100644--- a/apps/erp/app/modules/settings/ui/Integrations/IntegrationCard.tsx+++ b/apps/erp/app/modules/settings/ui/Integrations/IntegrationCard.tsx@@ -15,7 +15,7 @@ import {cn,useRouteData} from "@carbon/react";-import { Trans } from "@lingui/react/macro";+import { Trans, useLingui } from "@lingui/react/macro";import { useState } from "react";import { LuLock } from "react-icons/lu";import { Link, useFetcher, useNavigate } from "react-router";@@ -23,10 +23,17 @@ import { usePlanGate } from "~/hooks/usePlanGate";import { path } from "~/utils/path";import { InstallModeDialog } from "./InstallModeDialog";+/** Mirrors `IntegrationHealthStatus` in settings.server (not importable here). */+type IntegrationHealthStatus =+ | "healthy"+ | "unhealthy"+ | "inactive"+ | "sync-off";+export type IntegrationHealth = {id: string;active: boolean;- health: "healthy" | "unhealthy" | "inactive";+ health: IntegrationHealthStatus;/*** Which install mode this one is in, resolved SERVER-side.*@@ -245,21 +252,30 @@ export function IntegrationCard({);}-const StatusBadge = ({- status-}: {- status: "healthy" | "unhealthy" | "inactive";-}) => {+const StatusBadge = ({ status }: { status: IntegrationHealthStatus }) => {+ const { t } = useLingui();+const colors = {healthy: "bg-green-500",unhealthy: "bg-red-500",- inactive: "bg-gray-400"+ inactive: "bg-gray-400",+ "sync-off": "bg-orange-500"} as const;const badgeVariants = {healthy: "green",unhealthy: "red",- inactive: "gray"+ inactive: "gray",+ "sync-off": "orange"+ } as const;++ const labels = {+ healthy: t`healthy`,+ unhealthy: t`unhealthy`,+ inactive: t`inactive`,+ // Connected, but the accounting sync switch is off — a new connection+ // still being set up, or one switched off since.+ "sync-off": t`sync off`} as const;const ping = colors[status] || "text-gray-400";@@ -269,17 +285,20 @@ const StatusBadge = ({className="flex items-center mr-auto gap-x-2 py-0.5"><span className="relative flex size-2">- <span- className={cn(- "absolute inline-flex h-full w-full animate-ping rounded-full opacity-75",- ping- )}- />+ {/* Nothing is moving while sync is off, so the dot holds still. */}+ {status !== "sync-off" && (+ <span+ className={cn(+ "absolute inline-flex h-full w-full animate-ping rounded-full opacity-75",+ ping+ )}+ />+ )}<spanclassName={cn("relative inline-flex size-2 rounded-full", ping)}/></span>- {status}+ {labels[status]}</Badge>);};diff --git a/apps/erp/app/modules/settings/ui/Integrations/IntegrationForm.tsx b/apps/erp/app/modules/settings/ui/Integrations/IntegrationForm.tsxindex a97881240a..fda39502e6 100644--- a/apps/erp/app/modules/settings/ui/Integrations/IntegrationForm.tsx+++ b/apps/erp/app/modules/settings/ui/Integrations/IntegrationForm.tsx@@ -586,6 +586,9 @@ interface IntegrationFormProps {tabs?: IntegrationFormTab[];/** Initially-selected tab value (defaults to the Settings tab). */defaultTab?: string;+ /** Rendered in the header under the connection details of an installed+ * integration (e.g. an accounting integration's sync switch). */+ headerExtra?: ReactNode;}export function IntegrationForm({@@ -596,7 +599,8 @@ export function IntegrationForm({onClose,dynamicOptions = {},tabs = [],- defaultTab+ defaultTab,+ headerExtra}: IntegrationFormProps) {const { t } = useLingui();const permissions = usePermissions();@@ -928,6 +932,7 @@ export function IntegrationForm({</p></div>)}+ {installed && headerExtra}</div>);diff --git a/apps/erp/app/modules/settings/ui/Integrations/SyncActivity.tsx b/apps/erp/app/modules/settings/ui/Integrations/SyncActivity.tsxindex 854b0ff48b..0b9b6f3f2c 100644--- a/apps/erp/app/modules/settings/ui/Integrations/SyncActivity.tsx+++ b/apps/erp/app/modules/settings/ui/Integrations/SyncActivity.tsx@@ -36,6 +36,7 @@ import {LuChevronLeft,LuChevronRight,LuCircleSlash,+ LuDownload,LuRefreshCw,LuRotateCw,LuScale,@@ -116,6 +117,8 @@ export type SyncReconciliationReport = {type SyncActivityProps = {/** Shared tab bar, rendered at the top of this tab's body card. */tabs?: ReactNode;+ /** The integration whose activity this is — scopes the CSV export. */+ integrationId: string;operations: SyncActivityOperation[];/*** `entityType:entityId` -> the document number a human reads@@ -213,7 +216,7 @@ const ENTITY_PATHS: Record<string, (id: string) => string> = {reimbursement: path.to.reimbursement};-function getEntityLabel(entityType: string): string {+export function getEntityLabel(entityType: string): string {return ENTITY_LABELS[entityType] ?? entityType;}@@ -241,7 +244,7 @@ function getEntityReference(};}-function formatTrigger(trigger: string): string {+export function formatTrigger(trigger: string): string {return trigger.charAt(0).toUpperCase() + trigger.slice(1);}@@ -267,6 +270,7 @@ function getAvailableTransitions(status: SyncOperationStatus): {export function SyncActivity({tabs,+ integrationId,operations,readableIds,count,@@ -387,6 +391,24 @@ export function SyncActivity({<Trans>Retry all</Trans></Button>)}+ {count > 0 && (+ <Button+ size="sm"+ variant="secondary"+ leftIcon={<LuDownload />}+ asChild+ >+ <a+ href={path.to.api.integrationSyncActivityCsv(+ integrationId,+ status+ )}+ download+ >+ <Trans>Export CSV</Trans>+ </a>+ </Button>+ )}<Tooltip><TooltipTrigger asChild><IconButtondiff --git a/apps/erp/app/routes/api+/integrations.$id.sync-activity[.]csv.ts b/apps/erp/app/routes/api+/integrations.$id.sync-activity[.]csv.tsnew file mode 100644index 0000000000..4c077fc6af--- /dev/null+++ b/apps/erp/app/routes/api+/integrations.$id.sync-activity[.]csv.ts@@ -0,0 +1,192 @@+// 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 { requirePermissions } from "@carbon/auth/auth.server";+import type { Database } from "@carbon/database";+import { integrations as availableIntegrations } from "@carbon/ee";+import {+ getSyncOperationsExportPage,+ type SyncOperationCursor,+ type SyncOperationExportRow,+ SyncOperationStatusSchema+} from "@carbon/ee/accounting";+import { CSV_CONTENT_TYPE, encodeCsv } from "@carbon/files/csv";+import { getLogger } from "@carbon/logger";+import { chunkArray } from "@carbon/utils";+import type { SupabaseClient } from "@supabase/supabase-js";+import type { LoaderFunctionArgs } from "react-router";+import { getSyncOperationReadableIds } from "~/modules/settings/settings.server";+import {+ formatTrigger,+ getEntityLabel+} from "~/modules/settings/ui/Integrations/SyncActivity";++const logger = getLogger("erp", "integrations-sync-activity-csv");++/**+ * Rows read, resolved, encoded and written per step. Memory is bounded by one+ * page however long the integration's history is.+ */+const PAGE_SIZE = 1000;++/**+ * Operations per readable-id lookup: each batch becomes one `.in("id", …)`+ * per entity type, and a few hundred ids keeps that query string well under+ * PostgREST's URL limit.+ */+const READABLE_ID_BATCH_SIZE = 200;++const FIELDS = [+ "Created",+ "Status",+ "Entity",+ "Reference",+ "Entity ID",+ "Direction",+ "Trigger",+ "Attempts",+ "Last Attempt",+ "Completed",+ "External ID",+ "Error Code",+ "Error",+ "Operation ID"+];++/**+ * GET — the integration's Sync Activity as CSV. Every operation under the+ * tab's current status filter (`?status=`), not just the page on screen.+ * Gated like the tab itself, which lives on the settings-update drawer.+ *+ * Streamed one page at a time: the stream pulls the next page only when the+ * client has taken the last one, so a slow download pauses the reads instead+ * of buffering the history, and a cancelled download stops them.+ */+export async function loader({ request, params }: LoaderFunctionArgs) {+ const { client, companyId } = await requirePermissions(request, {+ update: "settings"+ });++ const integration = availableIntegrations.find(+ (candidate) => candidate.id === params.id+ );+ if (!integration) {+ throw new Response("Integration not found", { status: 404 });+ }++ const status = SyncOperationStatusSchema.safeParse(+ new URL(request.url).searchParams.get("status")+ );++ const readPage = async (after?: SyncOperationCursor) => {+ const page = await getSyncOperationsExportPage(client, {+ companyId,+ integration: integration.id,+ status: status.success ? status.data : undefined,+ after,+ limit: PAGE_SIZE+ });+ if (page.error) {+ logger.error("Failed to load sync operations for export", {+ companyId,+ integration: integration.id,+ after,+ error: page.error+ });+ }+ return page;+ };++ // The first page is read before the response starts, so a failure here is+ // still a real 500 rather than a truncated 200.+ const firstPage = await readPage();+ if (firstPage.error) {+ throw new Response("Failed to export sync activity", { status: 500 });+ }++ const encoder = new TextEncoder();+ let pending: SyncOperationExportRow[] | null = firstPage.data;+ let isFirstPage = true;++ const body = new ReadableStream<Uint8Array>({+ async pull(controller) {+ if (pending === null) {+ controller.close();+ return;+ }++ const rows = pending;+ const csv = await encodePage(client, companyId, rows, isFirstPage);+ if (csv) {+ controller.enqueue(encoder.encode(isFirstPage ? csv : `\r\n${csv}`));+ }+ isFirstPage = false;++ const last = rows.at(-1);+ if (rows.length < PAGE_SIZE || !last) {+ pending = null;+ return;+ }++ // Headers are already sent: a failure past page one can only end the+ // download, which the browser reports as a failed file.+ const next = await readPage({ createdAt: last.createdAt, id: last.id });+ if (next.error) {+ controller.error(new Error("Failed to export sync activity"));+ return;+ }+ pending = next.data.length > 0 ? next.data : null;+ }+ });++ const suffix = status.success+ ? `-${status.data.toLowerCase().replace(/\s+/g, "-")}`+ : "";++ return new Response(body, {+ headers: {+ "Content-Type": CSV_CONTENT_TYPE,+ "Content-Disposition": `attachment; filename="${integration.id}-sync-activity${suffix}.csv"`+ }+ });+}++/** One page of operations → CSV text, resolving their document numbers. */+async function encodePage(+ client: SupabaseClient<Database>,+ companyId: string,+ operations: SyncOperationExportRow[],+ header: boolean+): Promise<string> {+ const readableIds: Awaited<ReturnType<typeof getSyncOperationReadableIds>> =+ {};+ for (const batch of chunkArray(operations, READABLE_ID_BATCH_SIZE)) {+ Object.assign(+ readableIds,+ await getSyncOperationReadableIds(client, companyId, batch)+ );+ }++ return encodeCsv(+ operations.map((operation) => ({+ Created: operation.createdAt,+ Status: operation.status,+ Entity: getEntityLabel(operation.entityType),+ Reference:+ readableIds[`${operation.entityType}:${operation.entityId}`]?.label ??+ operation.entityId,+ "Entity ID": operation.entityId,+ Direction: operation.direction === "push-to-accounting" ? "Push" : "Pull",+ Trigger: formatTrigger(operation.trigger),+ Attempts: operation.attemptCount,+ "Last Attempt": operation.lastAttemptAt,+ Completed: operation.completedAt,+ "External ID": operation.externalId,+ "Error Code": operation.errorCode,+ Error: operation.errorMessage,+ "Operation ID": operation.id+ })),+ { fields: FIELDS, header }+ );+}diff --git a/apps/erp/app/routes/api+/integrations.journal-backfill.ts b/apps/erp/app/routes/api+/integrations.journal-backfill.tsindex a97721accd..4571aec4b1 100644--- a/apps/erp/app/routes/api+/integrations.journal-backfill.ts+++ b/apps/erp/app/routes/api+/integrations.journal-backfill.ts@@ -4,7 +4,7 @@import { assertIsPost } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";-import { ProviderID } from "@carbon/ee/accounting";+import { isAccountingSyncEnabled, ProviderID } from "@carbon/ee/accounting";import { trigger } from "@carbon/jobs";import { getLogger } from "@carbon/logger";import type { ActionFunctionArgs } from "react-router";@@ -47,7 +47,7 @@ export async function action({ request }: ActionFunctionArgs) {const integration = await client.from("companyIntegration")- .select("active")+ .select("active, metadata").eq("companyId", companyId).eq("id", provider).single();@@ -59,6 +59,13 @@ export async function action({ request }: ActionFunctionArgs) {);}+ if (!isAccountingSyncEnabled(integration.data.metadata)) {+ return data(+ { error: "Turn on sync for this integration first" },+ { status: 400 }+ );+ }+try {await trigger("accounting-journal-backfill", { companyId, provider });return data({ success: true, message: "Journal backfill started" });diff --git a/apps/erp/app/routes/api+/integrations.master-sync.ts b/apps/erp/app/routes/api+/integrations.master-sync.tsindex c7df8baf3e..d86a409567 100644--- a/apps/erp/app/routes/api+/integrations.master-sync.ts+++ b/apps/erp/app/routes/api+/integrations.master-sync.ts@@ -4,7 +4,7 @@import { assertIsPost } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";-import { ProviderID } from "@carbon/ee/accounting";+import { isAccountingSyncEnabled, ProviderID } from "@carbon/ee/accounting";import { trigger } from "@carbon/jobs";import { getLogger } from "@carbon/logger";import type { ActionFunctionArgs } from "react-router";@@ -79,6 +79,18 @@ export async function action({ request }: ActionFunctionArgs) {);}+ // Importing only writes into Carbon, and is part of setting an integration+ // up; pushing sends records to the provider, so it waits for sync.+ if (+ direction === "push-to-accounting" &&+ !isAccountingSyncEnabled(integration.data.metadata)+ ) {+ return data(+ { error: "Turn on sync for this integration first" },+ { status: 400 }+ );+ }+const settings = EntitySettingsSchema.parse(integration.data.metadata ?? {});// An explicit `entities` list wins: the import action names customers anddiff --git a/apps/erp/app/routes/api+/integrations.quickbooks.oauth.ts b/apps/erp/app/routes/api+/integrations.quickbooks.oauth.tsindex 4626a902ed..6931b7d522 100644--- a/apps/erp/app/routes/api+/integrations.quickbooks.oauth.ts+++ b/apps/erp/app/routes/api+/integrations.quickbooks.oauth.ts@@ -13,13 +13,15 @@ import { QuickBooks } from "@carbon/ee";import {DEFAULT_SYNC_CONFIG,getProviderIntegration,- ProviderID+ ProviderID,+ syncEnabledOnConnect} from "@carbon/ee/accounting";import { quickbooksOnInstall } from "@carbon/ee/quickbooks/hooks.server";import { getLogger } from "@carbon/logger";import type { LoaderFunctionArgs } from "react-router";import { data, redirect } from "react-router";import { upsertCompanyIntegration } from "~/modules/settings/settings.server";+import { getIntegration } from "~/modules/settings/settings.service";import { oAuthCallbackSchema } from "~/modules/shared";import { path } from "~/utils/path";@@ -104,6 +106,11 @@ export async function loader({ request }: LoaderFunctionArgs) {);}+ // Sync starts off on a new connection so accounts can be mapped first; a+ // reconnect to the same organization keeps the switch where it was.+ const existing = await getIntegration(client, QuickBooks.id, companyId);+ const syncEnabled = syncEnabledOnConnect(existing.data?.metadata, realmId);+const createdQuickBooksIntegration = await upsertCompanyIntegration(client,{@@ -112,6 +119,7 @@ export async function loader({ request }: LoaderFunctionArgs) {// @ts-ignoremetadata: {syncConfig: DEFAULT_SYNC_CONFIG,+ settings: { syncEnabled },// Provider-specific fields live under providerMetadata (new// credential shape) — legacy rows are upgraded on readcredentials: {diff --git a/apps/erp/app/routes/api+/integrations.xero.oauth.ts b/apps/erp/app/routes/api+/integrations.xero.oauth.tsindex b6498399b6..190904de13 100644--- a/apps/erp/app/routes/api+/integrations.xero.oauth.ts+++ b/apps/erp/app/routes/api+/integrations.xero.oauth.ts@@ -9,13 +9,15 @@ import { Xero } from "@carbon/ee";import {DEFAULT_SYNC_CONFIG,getProviderIntegration,- ProviderID+ ProviderID,+ syncEnabledOnConnect} from "@carbon/ee/accounting";import { xeroOnInstall } from "@carbon/ee/xero/hooks.server";import { getLogger } from "@carbon/logger";import type { LoaderFunctionArgs } from "react-router";import { data, redirect } from "react-router";import { upsertCompanyIntegration } from "~/modules/settings/settings.server";+import { getIntegration } from "~/modules/settings/settings.service";import { oAuthCallbackSchema } from "~/modules/shared";import { path } from "~/utils/path";@@ -193,12 +195,18 @@ export async function loader({ request }: LoaderFunctionArgs) {);}+ // Sync starts off on a new connection so accounts can be mapped first; a+ // reconnect to the same organization keeps the switch where it was.+ const existing = await getIntegration(client, Xero.id, companyId);+ const syncEnabled = syncEnabledOnConnect(existing.data?.metadata, tenantId);+const createdXeroIntegration = await upsertCompanyIntegration(client, {id: Xero.id,active: true,// @ts-ignoremetadata: {syncConfig: DEFAULT_SYNC_CONFIG,+ settings: { syncEnabled },// Provider-specific fields live under providerMetadata (new// credential shape) — legacy rows are upgraded on readcredentials: {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 81181e4455..aca524a4a6 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@@ -1,5 +1,5 @@{- "totalTools": 1482,+ "totalTools": 1483,"modules": 15,"tools": [{"name":"account_deleteUserAttributeValue","classification":"DESTRUCTIVE","paramCount":2,"schema":"0d38e12233b4","response":"bcde375ebd4c","injectAuth":"companyId+userId","permission":"none","paginates":false},@@ -186,6 +186,7 @@{"name":"inventory_getInventoryValuation","classification":"READ","paramCount":2,"schema":"288f0d29701b","response":"4005e935f8f1","injectAuth":"companyId","permission":"inventory:view","paginates":false},{"name":"inventory_getInventoryValuationTieOut","classification":"READ","paramCount":1,"schema":"cb789596bf56","response":"20aee38c95a3","injectAuth":"companyId","permission":"inventory:view","paginates":false},{"name":"inventory_getItemLedgerActivity","classification":"READ","paramCount":5,"schema":"b898b72c5939","response":"8d500cb0a03f","injectAuth":"companyId","permission":"inventory:view","paginates":false},+ {"name":"inventory_getItemLedgerBalance","classification":"READ","paramCount":3,"schema":"33e76470e057","response":"cddf8275afa1","injectAuth":"companyId","permission":"inventory:view","paginates":false},{"name":"inventory_getItemLedgerPage","classification":"READ","paramCount":4,"schema":"7ef5489d0abf","response":"8d500cb0a03f","injectAuth":"companyId","permission":"inventory:view","paginates":true},{"name":"inventory_getKanban","classification":"READ","paramCount":1,"schema":"369f807bc840","response":"c5aa7a081ed4","injectAuth":"companyId","permission":"inventory:view","paginates":false},{"name":"inventory_getKanbans","classification":"READ","paramCount":2,"schema":"68cb4a73d5a9","response":"fa96e94d8dda","injectAuth":"companyId","permission":"inventory:view","paginates":true},diff --git a/apps/erp/app/routes/api+/webhook.quickbooks.$companyId.test.ts b/apps/erp/app/routes/api+/webhook.quickbooks.$companyId.test.tsindex 50149fc7d9..4688da85e5 100644--- a/apps/erp/app/routes/api+/webhook.quickbooks.$companyId.test.ts+++ b/apps/erp/app/routes/api+/webhook.quickbooks.$companyId.test.ts@@ -22,6 +22,9 @@ vi.mock("@carbon/ee/accounting", () => ({getProviderIntegration(...args),parseStoredCredentials: (raw: unknown) => raw,ProviderID: { QUICKBOOKS: "quickbooks" },+ isAccountingSyncEnabled: (metadata: unknown) =>+ (metadata as { settings?: { syncEnabled?: unknown } } | null)?.settings+ ?.syncEnabled !== false,// Faithful minimal version of the real helper: first LinkedTxn of the// family's TxnType → canonical composite.buildQboPaymentSyncChange: (@@ -161,6 +164,26 @@ describe("webhook.quickbooks payment accelerator", () => {]);});+ it("acks and ignores a signed delivery while sync is turned off", async () => {+ getAccountingIntegration.mockResolvedValue({+ companyId: "company-1",+ active: true,+ metadata: {+ settings: { syncEnabled: false },+ credentials: {+ type: "oauth2",+ providerMetadata: { webhookVerifierToken: TOKEN, realmId: "realm-1" }+ }+ }+ });++ const result = await run(makeRequest(billPaymentEvent));++ expect(result).toEqual({ success: true, ignored: true });+ expect(trigger).not.toHaveBeenCalled();+ expect(getProviderIntegration).not.toHaveBeenCalled();+ });+it("enqueues the prefix-less AR composite for a Payment", async () => {await run(makeRequest({diff --git a/apps/erp/app/routes/api+/webhook.quickbooks.$companyId.ts b/apps/erp/app/routes/api+/webhook.quickbooks.$companyId.tsindex 67d5e484b0..65969bed64 100644--- a/apps/erp/app/routes/api+/webhook.quickbooks.$companyId.ts+++ b/apps/erp/app/routes/api+/webhook.quickbooks.$companyId.ts@@ -8,6 +8,7 @@ import {buildQboPaymentSyncChange,getAccountingIntegration,getProviderIntegration,+ isAccountingSyncEnabled,ProviderID,parseStoredCredentials} from "@carbon/ee/accounting";@@ -192,6 +193,12 @@ export async function action({ request, params }: ActionFunctionArgs) {return data({ success: false }, { status: 401 });}+ // Sync is turned off while the integration is being set up: acknowledge so+ // Intuit does not retry, and do nothing.+ if (!isAccountingSyncEnabled(integration.metadata)) {+ return { success: true, ignored: true };+ }+let parsed: z.infer<typeof webhookValidator>;try {parsed = webhookValidator.parse(JSON.parse(body));diff --git a/apps/erp/app/routes/api+/webhook.rillet.$companyId.ts b/apps/erp/app/routes/api+/webhook.rillet.$companyId.tsindex 0f7f9fdeae..589c9e42b1 100644--- a/apps/erp/app/routes/api+/webhook.rillet.$companyId.ts+++ b/apps/erp/app/routes/api+/webhook.rillet.$companyId.ts@@ -5,6 +5,7 @@import { getCarbonServiceRole } from "@carbon/auth/client.server";import {getRilletPaymentSyncEntityId,+ isAccountingSyncEnabled,ProviderID,parseStoredCredentials,verifyRilletWebhookSignature@@ -106,6 +107,12 @@ export async function action({ request, params }: ActionFunctionArgs) {return data({ success: false }, { status: 401 });}+ // Sync is turned off while the integration is being set up: acknowledge so+ // Rillet does not retry, and do nothing.+ if (!isAccountingSyncEnabled(integration.data.metadata)) {+ return { success: true, ignored: true };+ }+// VERIFY(Phase 1.3): AP bill payments are POLL-ONLY. Rillet documents only// `bill-created`/`bill-updated`/`bill-deleted` webhook events — no// bill-payment (or bill-updated-on-payment) event is confirmed — so thisdiff --git a/apps/erp/app/routes/api+/webhook.xero.test.ts b/apps/erp/app/routes/api+/webhook.xero.test.tsindex fd7db041f9..c5322b1d77 100644--- a/apps/erp/app/routes/api+/webhook.xero.test.ts+++ b/apps/erp/app/routes/api+/webhook.xero.test.ts@@ -28,6 +28,9 @@ vi.mock("@carbon/ee/accounting", () => ({getProviderIntegration: (...args: unknown[]) =>getProviderIntegration(...args),ProviderID: { XERO: "xero" },+ isAccountingSyncEnabled: (metadata: unknown) =>+ (metadata as { settings?: { syncEnabled?: unknown } } | null)?.settings+ ?.syncEnabled !== false,parseStoredCredentials: (raw: unknown) => raw,// Real composite-id shape (the syncer's contract): ACCREC prefix-less AR,// ACCPAY `bill:`-prefixed AP.diff --git a/apps/erp/app/routes/api+/webhook.xero.ts b/apps/erp/app/routes/api+/webhook.xero.tsindex 4b35ec6a67..466956096a 100644--- a/apps/erp/app/routes/api+/webhook.xero.ts+++ b/apps/erp/app/routes/api+/webhook.xero.ts@@ -35,6 +35,7 @@ import {getProviderIntegration,getXeroBillPaymentSyncEntityId,getXeroPaymentSyncEntityId,+ isAccountingSyncEnabled,ProviderID,parseStoredCredentials} from "@carbon/ee/accounting";@@ -223,6 +224,15 @@ export async function action({ request }: ActionFunctionArgs) {const companyId = integration.companyId;+ // Sync is turned off while the integration is being set up: skip this+ // tenant before any provider call.+ if (!isAccountingSyncEnabled(integration.metadata)) {+ logger.info("Xero sync is turned off; ignoring webhook events", {+ companyId+ });+ continue;+ }+const provider = getProviderIntegration(serviceRole,companyId,diff --git a/apps/erp/app/routes/x+/inventory+/quantities+/$itemId.activity.tsx b/apps/erp/app/routes/x+/inventory+/quantities+/$itemId.activity.tsxindex 54c36448a4..a981420cf3 100644--- a/apps/erp/app/routes/x+/inventory+/quantities+/$itemId.activity.tsx+++ b/apps/erp/app/routes/x+/inventory+/quantities+/$itemId.activity.tsx@@ -12,11 +12,17 @@ import { LuChevronUp } from "react-icons/lu";import type { LoaderFunctionArgs } from "react-router";import { redirect, useLoaderData } from "react-router";import InfiniteScroll from "~/components/InfiniteScroll";-import type { CollapsedItemLedger, ItemLedger } from "~/modules/inventory";+import type {+ BalanceAnchor,+ CollapsedItemLedger,+ ItemLedger+} from "~/modules/inventory";import {collapseTransferPairs,getItemLedgerActivity,- InventoryActivity+ getItemLedgerBalance,+ InventoryActivity,+ withRunningBalance} from "~/modules/inventory";import { getItem } from "~/modules/items";import { getLocationsList } from "~/modules/resources";@@ -81,8 +87,10 @@ export async function loader({ request, params }: LoaderFunctionArgs) {// The activity page and the "is there anything newer than the anchor?"// existence check both depend only on `anchorEntryNumber`, not on each other —- // run them in parallel to save a roundtrip on highlight navigations.- const [itemLedgerRecords, newer, item] = await Promise.all([+ // run them in parallel to save a roundtrip on highlight navigations. So does+ // the on-hand balance when the page is anchored, since the anchor entry is+ // then the page's newest row.+ const [itemLedgerRecords, newer, item, anchoredBalance] = await Promise.all([getItemLedgerActivity(client, {itemId,companyId,@@ -101,7 +109,15 @@ export async function loader({ request, params }: LoaderFunctionArgs) {.gt("entryNumber", anchorEntryNumber).limit(1): Promise.resolve({ data: [] as { id: string }[] }),- getItem(client, itemId)+ getItem(client, itemId),+ anchorEntryNumber !== null+ ? getItemLedgerBalance(client, {+ itemId,+ companyId,+ locationId,+ entryNumber: anchorEntryNumber+ })+ : null]);if (itemLedgerRecords.error) {throw redirect(@@ -116,6 +132,27 @@ export async function loader({ request, params }: LoaderFunctionArgs) {// Only offer "Load newer" when entries actually exist above the anchor.const hasNewer = (newer.data?.length ?? 0) > 0;+ // One balance prices the whole feed: the on-hand right after the newest row+ // loaded. The client walks every page out from it. Unanchored, the newest+ // row is only known now — measuring "on hand now" in parallel instead would+ // misprice the feed whenever an entry landed between the two queries.+ const newestEntryNumber = itemLedgerRecords.data[0]?.entryNumber;+ const balance =+ newestEntryNumber === undefined+ ? null+ : (anchoredBalance ??+ (await getItemLedgerBalance(client, {+ itemId,+ companyId,+ locationId,+ entryNumber: newestEntryNumber+ })));+ // A failed balance read costs only the before → after column, not the feed.+ const balanceAnchor: BalanceAnchor | null =+ newestEntryNumber !== undefined && balance && !balance.error+ ? { entryNumber: newestEntryNumber, balanceAfter: Number(balance.data) }+ : null;+return {initialItemLedgers: itemLedgerRecords.data,itemId,@@ -124,6 +161,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {highlightId,hasOlder: itemLedgerRecords.hasMore,hasNewer,+ balanceAnchor,itemTrackingType: item.data?.itemTrackingType ?? null};}@@ -137,6 +175,7 @@ export default function ItemInventoryActivityRoute() {highlightId,hasOlder: initialHasOlder,hasNewer: initialHasNewer,+ balanceAnchor: initialBalanceAnchor,itemTrackingType} = useLoaderData<typeof loader>();@@ -144,11 +183,14 @@ export default function ItemInventoryActivityRoute() {const [itemLedgers, setItemLedgers] =useState<ItemLedger[]>(initialItemLedgers);- // A stock transfer writes an outbound and an inbound ledger row; collapse- // each pair so one move reads as one activity entry.+ // Held alongside the rows it was measured against, so the two never drift.+ const [balanceAnchor] = useState(initialBalanceAnchor);+ // Price every row from the one anchored balance BEFORE collapsing: a stock+ // transfer writes an outbound and an inbound ledger row, and collapsing each+ // pair (so one move reads as one entry) must not lose either half's quantity.const activityItems = useMemo(- () => collapseTransferPairs(itemLedgers),- [itemLedgers]+ () => collapseTransferPairs(withRunningBalance(itemLedgers, balanceAnchor)),+ [itemLedgers, balanceAnchor]);// InfiniteScroll only forwards { item, highlightId } — close over the item's// tracking type so rows label their tracked entity from the item, not adiff --git a/apps/erp/app/routes/x+/settings+/integrations.$id.tsx b/apps/erp/app/routes/x+/settings+/integrations.$id.tsxindex a236971d90..313bc24706 100644--- a/apps/erp/app/routes/x+/settings+/integrations.$id.tsx+++ b/apps/erp/app/routes/x+/settings+/integrations.$id.tsx@@ -25,7 +25,9 @@ import {getProviderIntegration,getSyncOperations,getUnmappedPostingAccounts,+ getUnmappedRequiredAccounts,getUnmappedSlottedDimensionValues,+ isAccountingSyncEnabled,JOURNAL_ENTRY_SOURCE_TYPES,loadAccountDefaultAccountIds,matchAccountsByCode,@@ -43,6 +45,8 @@ import {type SyncOperation,type SyncOperationStatus,SyncOperationStatusSchema,+ selectRequiredMappingAccountIds,+ selectUnmappedRequiredAccounts,suggestAccountMatchesWithAI,transitionOperation,upsertAccountMapping,@@ -114,13 +118,15 @@ import {dimensionSlotsUpdateValidator,dimensionValueMappingBulkUpsertValidator,dimensionValueMappingUpsertValidator,- postingSyncSettingsValidator+ postingSyncSettingsValidator,+ syncEnabledValidator} from "~/modules/settings/settings.models";import {getSyncOperationReadableIds,invalidateIntegrationHealthCache,upsertCompanyIntegration} from "~/modules/settings/settings.server";+import { AccountingSyncControl } from "~/modules/settings/ui/Integrations/AccountingSyncControl";import { AccountMapping } from "~/modules/settings/ui/Integrations/AccountMapping";import { DimensionMapping } from "~/modules/settings/ui/Integrations/DimensionMapping";import type { IntegrationFormTab } from "~/modules/settings/ui/Integrations/IntegrationForm";@@ -309,18 +315,23 @@ async function getAccountMappingTabData(}// The tab spans the FULL chart of accounts (getAccountMappings is unscoped and- // the syncers already see every mapping). The "required" set — badged and- // surfaced as needing mapping — is the accountDefault posting accounts PLUS- // every Expense account: any Expense account can be charged directly on a PO- // G/L-account line, so it should be mapped up front rather than parking a- // journal later.+ // the syncers already see every mapping). The "required" set — badged, and+ // what must be mapped before sync can be turned on — is the accountDefault+ // posting accounts PLUS every Expense account.const fullChart = allAccounts.data ?? [];- const expenseAccountIds = fullChart- .filter((account) => account.class === "Expense")- .map((account) => account.id);- const requiredAccountIds = [- ...new Set([...accountDefaultIds, ...expenseAccountIds])- ];+ const requiredAccountIds = selectRequiredMappingAccountIds(+ accountDefaultIds,+ fullChart+ );+ const unmappedRequiredCount = selectUnmappedRequiredAccounts({+ accountDefaultIds,+ chart: fullChart,+ mappedAccountIds: new Set(+ (mappings.data ?? [])+ .filter((mapping) => mapping.externalId)+ .map((mapping) => mapping.accountId)+ )+ }).length;return {mappings: mappings.data ?? [],@@ -328,6 +339,7 @@ async function getAccountMappingTabData(chart,proposals: proposals.data ?? [],requiredAccountIds,+ unmappedRequiredCount,allAccounts: fullChart,blocking: blocking.data ?? []};@@ -671,6 +683,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {dynamicOptions,syncActivity: null,accountMapping: null,+ accountingSync: null,postingSync: null,dimensionSync: null};@@ -1116,12 +1129,22 @@ export async function loader({ request, params }: LoaderFunctionArgs) {}): null;+ // The header's sync switch: off on a new connection, and only switchable on+ // once every required account is mapped.+ const accountingSync = accountMapping+ ? {+ enabled: isAccountingSyncEnabled(metadata),+ unmappedRequiredCount: accountMapping.unmappedRequiredCount+ }+ : null;+return {installed: integrationData.data.active,metadata: flattenedMetadata,dynamicOptions,syncActivity,accountMapping,+ accountingSync,postingSync,dimensionSync};@@ -1530,6 +1553,99 @@ export async function action({ request, params }: ActionFunctionArgs) {);}+ // Turn an accounting integration's sync on or off (drawer header switch).+ // A new connection starts off; turning it on is refused until every+ // required account is mapped, so the first push cannot park a wall of+ // UNMAPPED_ACCOUNTS warnings. Stays on the page.+ if (formData.get("intent") === "update-sync-enabled") {+ const validation = await validator(syncEnabledValidator).validate(formData);++ if (validation.error) {+ return validationError(validation.error);+ }++ const { syncEnabled } = validation.data;++ const existing = await getIntegration(client, integrationId, companyId);+ if (existing.error || !existing.data?.active) {+ return data(+ {},+ await flash(+ request,+ error(existing.error, "Failed to load integration settings")+ )+ );+ }++ if (syncEnabled) {+ const unmapped = await getUnmappedRequiredAccounts(getDatabaseClient(), {+ companyId,+ integration: integrationId+ });+ if (unmapped.error || !unmapped.data) {+ logger.error("Failed to load unmapped accounts", {+ companyId,+ integrationId,+ error: unmapped.error+ });+ return data(+ {},+ await flash(+ request,+ error(unmapped.error, "Failed to check the account mapping")+ )+ );+ }+ if (unmapped.data.length > 0) {+ return data(+ {},+ await flash(+ request,+ error(+ null,+ `Map the remaining ${unmapped.data.length} required account${+ unmapped.data.length === 1 ? "" : "s"+ } before turning on sync`+ )+ )+ );+ }+ }++ const existingMetadata =+ (existing.data.metadata as Record<string, unknown>) ?? {};+ const existingSettings =+ (existingMetadata.settings as Record<string, unknown> | undefined) ?? {};++ const update = await upsertCompanyIntegration(client, {+ id: integrationId,+ active: existing.data.active,+ metadata: {+ ...existingMetadata,+ settings: { ...existingSettings, syncEnabled }+ } as Json,+ companyId,+ updatedBy: userId+ });++ if (update.error) {+ return data(+ {},+ await flash(request, error(update.error, "Failed to update sync"))+ );+ }++ await invalidateIntegrationHealthCache(integrationId, companyId);++ return data(+ {},+ await flash(+ request,+ success(syncEnabled ? "Turned on sync" : "Turned off sync")+ )+ );+ }+// Persist posting-sync settings (Posting tab): read-modify-write the// companyIntegration metadata JSONB, deep-merging the postingSync// fragment under metadata.settings so credentials and other settings@@ -1768,6 +1884,20 @@ export async function action({ request, params }: ActionFunctionArgs) {const wasInstalled = existing.data?.active === true;+ // An accounting integration installed from this form (Rillet) starts with+ // sync off, so accounts can be mapped before anything reaches the provider.+ // OAuth providers make the same decision in their callbacks.+ if (+ !wasInstalled &&+ (integration as { providerRole?: "accounting" | "spend" }).providerRole ===+ "accounting"+ ) {+ metadata.settings = {+ ...((metadata.settings as Record<string, unknown> | undefined) ?? {}),+ syncEnabled: false+ };+ }+// Install-time secret presence. The config schemas now let an empty secret// field mean "keep the existing vaulted value" (it loads masked, never sent to// the browser). A FRESH install with no secret at all would leave the@@ -2016,6 +2146,7 @@ export default function IntegrationRoute() {dynamicOptions,syncActivity,accountMapping,+ accountingSync,postingSync,dimensionSync} = useLoaderData<typeof loader>();@@ -2085,7 +2216,7 @@ export default function IntegrationRoute() {)});}- if (syncActivity) {+ if (syncActivity && integrationId) {tabs.push({value: "sync-activity",label:@@ -2100,6 +2231,7 @@ export default function IntegrationRoute() {content: (tabBar) => (<SyncActivitytabs={tabBar}+ integrationId={integrationId}operations={syncActivity.operations}count={syncActivity.count}status={syncActivity.status}@@ -2129,6 +2261,14 @@ export default function IntegrationRoute() {dynamicOptions={dynamicOptions}tabs={tabs.length > 0 ? tabs : undefined}defaultTab={defaultTab}+ headerExtra={+ accountingSync ? (+ <AccountingSyncControl+ enabled={accountingSync.enabled}+ unmappedRequiredCount={accountingSync.unmappedRequiredCount}+ />+ ) : undefined+ }onClose={() => navigate(path.to.integrations)}/>);diff --git a/apps/erp/app/utils/path.ts b/apps/erp/app/utils/path.tsindex a563fa497e..eb82dfa62b 100644--- a/apps/erp/app/utils/path.ts+++ b/apps/erp/app/utils/path.ts@@ -143,6 +143,10 @@ export const path = {),inspectionDocuments: (itemId: string) =>generatePath(`${api}/quality/inspection-documents/${itemId}`),+ integrationSyncActivityCsv: (id: string, status?: string | null) =>+ `${generatePath(`${api}/integrations/${id}/sync-activity.csv`)}${+ status ? `?${new URLSearchParams({ status })}` : ""+ }`,issueTypes: `${api}/quality/issue-types`,item: (type: string) => generatePath(`${api}/item/${type}`),itemConfigurable: `${api}/items/configurable`,diff --git a/docs/content/docs/integrations/accounting.mdx b/docs/content/docs/integrations/accounting.mdxindex cbb1a3a9bf..ca1f7d6a98 100644--- a/docs/content/docs/integrations/accounting.mdx+++ b/docs/content/docs/integrations/accounting.mdx@@ -9,10 +9,10 @@ Carbon synchronizes accounting data with **Xero**, **QuickBooks Online**, or **R<PlanBadge plan="Business" className="my-[8px]" />-After connection, Carbon sends **customers**, **vendors**, **items**, **sales invoices**, **bills**, and automated **GL journals** to the provider. **Carbon is the source of truth**: Carbon changes take precedence, and stable record mappings prevent duplicates. Provider payments synchronize back to Carbon and settle the matching invoice or bill.+Once **Sync** is on, Carbon sends **customers**, **vendors**, **items**, **sales invoices**, **bills**, and automated **GL journals** to the provider. **Carbon is the source of truth**: Carbon changes take precedence, and stable record mappings prevent duplicates. Provider payments synchronize back to Carbon and settle the matching invoice or bill.-<Callout type="note" title="Journal mirroring is automatic, and always on">-Carbon mirrors every automated GL posting to the connected provider. This behavior cannot be disabled. Journals with a `Manual` source do not synchronize.+<Callout type="note" title="Journal mirroring is automatic while sync is on">+While **Sync** is on, Carbon mirrors every automated GL posting to the connected provider. Journals with a `Manual` source do not synchronize.</Callout>A provider payment creates a Carbon payment and <Term id="invoice-settlement">invoice settlement</Term>, then posts to Carbon's <Term id="general-ledger">general ledger</Term>. Rillet also accepts outbound Carbon payments. Xero and QuickBooks support inbound payment synchronization only.@@ -30,7 +30,17 @@ Xero and QuickBooks Online use **OAuth**. Rillet uses a per-company **API key**.<Step>### Configure the sync- Set the account mapping, dimensions, and posting-sync options (below) before the first push.+ A new connection starts with **Sync** off, so nothing reaches the ledger while you set it up. Set the+ account mapping, dimensions, and posting-sync options (below). If the ledger already has customers and+ vendors, run **Import customers & vendors** now — it works while sync is off, and links them so the first+ sync updates them instead of creating duplicates.+ </Step>+ <Step>+ ### Turn on sync++ Turn on the **Sync** switch at the top of the integration. It stays locked until every account marked+ **Required** on the Account Mapping tab is mapped. Turning it off later pauses the sync again; a reconnect+ to the same organization keeps it where it was.</Step><Step>### Run the initial sync@@ -73,7 +83,7 @@ The **Posting Sync** tab controls three things:## Watch it run-The **Sync Activity** tab lists each operation's **Status**, **Entity**, **Direction**, **Trigger**, **Attempts**, **Last Attempt**, and **Error**. Filter by status, **Retry** or **Skip** a failed operation, **Re-send** a completed operation, or **Retry all**. Carbon creates an in-app notification when failures remain after an outbound run.+The **Sync Activity** tab lists each operation's **Status**, **Entity**, **Direction**, **Trigger**, **Attempts**, **Last Attempt**, and **Error**. Filter by status, **Retry** or **Skip** a failed operation, **Re-send** a completed operation, or **Retry all**. **Export CSV** downloads every operation under the current status filter, with the document number, provider ID, and full error. Carbon creates an in-app notification when failures remain after an outbound run.Weekly reconciliation writes the **Sync Tie-Out** report under **Accounting → Reports → Sync Tie-Out**. Each row compares **Posted**, **Synced**, and **Provider** balances for one accounting period, account, and integration. The report flags **Internal** and **External Delta** values.diff --git a/packages/database/src/swagger-docs-schema.ts b/packages/database/src/swagger-docs-schema.tsindex a54835312d..c7d78c3c1e 100644--- a/packages/database/src/swagger-docs-schema.ts+++ b/packages/database/src/swagger-docs-schema.ts@@ -103672,6 +103672,96 @@ export default {tags: ["(rpc) sync_insert_company_related_records"]}},+ "/rpc/get_item_ledger_balance": {+ get: {+ parameters: [+ {+ format: "text",+ in: "query",+ name: "company_id",+ required: true,+ type: "string"+ },+ {+ format: "text",+ in: "query",+ name: "location_id",+ required: true,+ type: "string"+ },+ {+ format: "text",+ in: "query",+ name: "item_id",+ required: true,+ type: "string"+ },+ {+ format: "integer",+ in: "query",+ name: "entry_number",+ required: false,+ type: "integer"+ }+ ],+ produces: [+ "application/json",+ "application/vnd.pgrst.object+json;nulls=stripped",+ "application/vnd.pgrst.object+json"+ ],+ responses: {+ "200": {+ description: "OK"+ }+ },+ tags: ["(rpc) get_item_ledger_balance"]+ },+ post: {+ parameters: [+ {+ in: "body",+ name: "args",+ required: true,+ schema: {+ properties: {+ company_id: {+ format: "text",+ type: "string"+ },+ entry_number: {+ format: "integer",+ type: "integer"+ },+ item_id: {+ format: "text",+ type: "string"+ },+ location_id: {+ format: "text",+ type: "string"+ }+ },+ required: ["company_id", "location_id", "item_id"],+ type: "object"+ }+ },+ {+ $ref: "#/parameters/preferParams"+ }+ ],+ produces: [+ "application/json",+ "application/vnd.pgrst.object+json;nulls=stripped",+ "application/vnd.pgrst.object+json"+ ],+ responses: {+ "200": {+ description: "OK"+ }+ },+ tags: ["(rpc) get_item_ledger_balance"]+ }+ },"/rpc/sync_add_employee_to_type_group": {post: {parameters: [diff --git a/packages/database/src/types.ts b/packages/database/src/types.tsindex 207e7814c0..78f000e2f5 100644--- a/packages/database/src/types.ts+++ b/packages/database/src/types.ts@@ -83604,6 +83604,15 @@ export type Database = {unitOfMeasureCode: string}[]}+ get_item_ledger_balance: {+ Args: {+ company_id: string+ entry_number?: number+ item_id: string+ location_id: string+ }+ Returns: number+ }get_item_quantities_by_tracking_id: {Args: { company_id: string; item_id: string; location_id: string }Returns: {diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.tsindex 207e7814c0..78f000e2f5 100644--- a/packages/database/supabase/functions/lib/types.ts+++ b/packages/database/supabase/functions/lib/types.ts@@ -83604,6 +83604,15 @@ export type Database = {unitOfMeasureCode: string}[]}+ get_item_ledger_balance: {+ Args: {+ company_id: string+ entry_number?: number+ item_id: string+ location_id: string+ }+ Returns: number+ }get_item_quantities_by_tracking_id: {Args: { company_id: string; item_id: string; location_id: string }Returns: {diff --git a/packages/database/supabase/migrations/20261002153931_item-ledger-running-balance.sql b/packages/database/supabase/migrations/20261002153931_item-ledger-running-balance.sqlnew file mode 100644index 0000000000..2ac17aaf00--- /dev/null+++ b/packages/database/supabase/migrations/20261002153931_item-ledger-running-balance.sql@@ -0,0 +1,97 @@+-- Running on-hand balance for the inventory activity feed.+--+-- The feed (Inventory → Quantities → item → Activity) pages itemLedger rows+-- newest→oldest by "entryNumber", 20 at a time. To show "before → after" on+-- every row it needs ONE number per session: the on-hand right after the+-- newest row it loaded. Every other balance is derived client-side by walking+-- the contiguous pages and adding/subtracting each row's quantity, so paging+-- costs no extra queries.+--+-- get_item_ledger_balance returns that number, on the same definition as+-- get_inventory_quantities."quantityOnHand" so the top of the feed matches the+-- On Hand column:+--+-- balance after entry N = on-hand now − Σ rows with entryNumber > N+--+-- "On-hand now" comes from the itemLedgerSnapshot + live delta (cheap however+-- long the item's history is), and the suffix is usually empty or a handful of+-- rows — the feed anchors on the newest entry unless it was opened on a+-- highlighted older one. Both halves count a row through+-- item_ledger_on_hand_contribution, so a Rejected tracked entity's rows add+-- zero, exactly as quantityOnHand does.++-- The feed orders one item's rows at one location by entryNumber. The existing+-- ("companyId", "locationId", "itemId") index found the rows but left a sort of+-- the item's whole history behind every 20-row page; with entryNumber appended+-- both the page and the suffix sum below are a bounded index range scan.+CREATE INDEX IF NOT EXISTS "itemLedger_companyId_locationId_itemId_entryNumber_idx"+ ON "itemLedger" ("companyId", "locationId", "itemId", "entryNumber");++CREATE OR REPLACE FUNCTION get_item_ledger_balance(+ company_id TEXT,+ location_id TEXT,+ item_id TEXT,+ entry_number INTEGER DEFAULT NULL+)+RETURNS NUMERIC+LANGUAGE plpgsql+STABLE+SECURITY DEFINER+SET search_path = public+AS $$+DECLARE+ v_cutoff TIMESTAMPTZ;+ v_on_hand NUMERIC;+ v_after NUMERIC := 0;+BEGIN+ PERFORM assert_company_access(company_id);++ SELECT MAX("snapshotCutoff") INTO v_cutoff+ FROM "itemLedgerSnapshot"+ WHERE "companyId" = company_id;++ -- Same three arms as get_inventory_quantities: snapshotted untracked rows,+ -- live tracked rows (their status is rewritten in place, so never+ -- snapshotted), and untracked rows newer than the snapshot cutoff.+ SELECT COALESCE(SUM(combined."quantity"), 0) INTO v_on_hand+ FROM (+ SELECT s."quantity"+ FROM "itemLedgerSnapshot" s+ WHERE s."companyId" = company_id+ AND s."locationId" = location_id+ AND s."itemId" = item_id++ UNION ALL++ SELECT item_ledger_on_hand_contribution(il."quantity", il."trackedEntityStatus")+ FROM "itemLedger" il+ WHERE il."companyId" = company_id+ AND il."locationId" = location_id+ AND il."itemId" = item_id+ AND il."trackedEntityId" IS NOT NULL++ UNION ALL++ SELECT il."quantity"+ FROM "itemLedger" il+ WHERE il."companyId" = company_id+ AND il."locationId" = location_id+ AND il."itemId" = item_id+ AND il."trackedEntityId" IS NULL+ AND (v_cutoff IS NULL OR il."createdAt" >= v_cutoff)+ ) combined;++ IF entry_number IS NOT NULL THEN+ SELECT COALESCE(SUM(+ item_ledger_on_hand_contribution(il."quantity", il."trackedEntityStatus")+ ), 0) INTO v_after+ FROM "itemLedger" il+ WHERE il."companyId" = company_id+ AND il."locationId" = location_id+ AND il."itemId" = item_id+ AND il."entryNumber" > entry_number;+ END IF;++ RETURN v_on_hand - v_after;+END;+$$;diff --git a/packages/database/supabase/migrations/20261002164721_sync-operation-export-index.sql b/packages/database/supabase/migrations/20261002164721_sync-operation-export-index.sqlnew file mode 100644index 0000000000..ff18a863fb--- /dev/null+++ b/packages/database/supabase/migrations/20261002164721_sync-operation-export-index.sql@@ -0,0 +1,5 @@+-- The Sync Activity CSV export pages an integration's whole history newest+-- first with a (createdAt, id) keyset. Without this index every page sorts+-- the tenant's entire history; with it each page is an index range scan.+CREATE INDEX IF NOT EXISTS "accountingSyncOperation_createdAt_idx"+ ON "accountingSyncOperation" ("companyId", "integration", "createdAt" DESC, "id");diff --git a/packages/ee/src/accounting/core/account-mapping.ts b/packages/ee/src/accounting/core/account-mapping.tsindex 63a14ecddd..7f10ee089f 100644--- a/packages/ee/src/accounting/core/account-mapping.ts+++ b/packages/ee/src/accounting/core/account-mapping.ts@@ -497,6 +497,80 @@ export async function getFullChartMappableAccounts(}}+/**+ * The accounts a company must map before an accounting integration may sync:+ * every accountDefault posting account plus every Expense account (any+ * Expense account can be charged directly on a PO G/L-account line). The+ * Account Mapping tab badges exactly this set as Required.+ */+export function selectRequiredMappingAccountIds(+ accountDefaultIds: string[],+ chart: Pick<MappableChartAccount, "id" | "class">[]+): string[] {+ return [+ ...new Set([+ ...accountDefaultIds,+ ...chart+ .filter((account) => account.class === "Expense")+ .map((account) => account.id)+ ])+ ];+}++/**+ * Required accounts (selectRequiredMappingAccountIds) in the active chart that+ * have no provider account yet. Turning sync on is refused while any remain.+ */+export function selectUnmappedRequiredAccounts(args: {+ accountDefaultIds: string[];+ chart: MappableChartAccount[];+ mappedAccountIds: Set<string>;+}): UnmappedPostingAccount[] {+ const required = new Set(+ selectRequiredMappingAccountIds(args.accountDefaultIds, args.chart)+ );+ return args.chart+ .filter(+ (account) =>+ required.has(account.id) && !args.mappedAccountIds.has(account.id)+ )+ .map(({ id, number, name }) => ({ id, number, name }));+}++export async function getUnmappedRequiredAccounts(+ db: Db,+ args: { companyId: string; integration: string }+): Promise<{ data: UnmappedPostingAccount[] | null; error: string | null }> {+ try {+ const [accountDefaultIds, chart, mappedRows] = await Promise.all([+ loadAccountDefaultAccountIds(db, args.companyId),+ getFullChartMappableAccounts(db, { companyId: args.companyId }),+ db+ .selectFrom("externalIntegrationMapping")+ .select("entityId")+ .where("entityType", "=", ACCOUNT_MAPPING_ENTITY_TYPE)+ .where("integration", "=", args.integration)+ .where("companyId", "=", args.companyId)+ .where("externalId", "is not", null)+ .execute()+ ]);+ if (chart.error || !chart.data) {+ return { data: null, error: chart.error ?? "Failed to load accounts" };+ }++ return {+ data: selectUnmappedRequiredAccounts({+ accountDefaultIds,+ chart: chart.data,+ mappedAccountIds: new Set(mappedRows.map((row) => row.entityId))+ }),+ error: null+ };+ } catch (err) {+ return { data: null, error: toErrorMessage(err) };+ }+}+/*** Propose (not write) exact matches between Carbon account numbers and the* provider's chart-of-accounts codes across the FULL chart of accounts — everydiff --git a/packages/ee/src/accounting/core/models.ts b/packages/ee/src/accounting/core/models.tsindex 7539749437..f5de9c4931 100644--- a/packages/ee/src/accounting/core/models.ts+++ b/packages/ee/src/accounting/core/models.ts@@ -957,6 +957,52 @@ export const ProviderIntegrationMetadataSchema = z.object({defaultPurchaseAccountCode: z.string().optional()});+/**+ * Whether an accounting integration may move data. A new connection starts+ * OFF so the customer can map accounts and choose posting settings before+ * anything reaches the provider; it is turned on from the integration drawer,+ * and only once every required account is mapped. Stored at+ * `metadata.settings.syncEnabled`. A row with no flag predates the switch and+ * was already syncing, so absent reads as on — every connect path writes an+ * explicit value.+ */+export function isAccountingSyncEnabled(metadata: unknown): boolean {+ const settings =+ metadata && typeof metadata === "object"+ ? (metadata as { settings?: unknown }).settings+ : undefined;+ if (!settings || typeof settings !== "object") return true;+ return (settings as Record<string, unknown>).syncEnabled !== false;+}++/**+ * The sync switch for an OAuth (re)connection. A reconnect to the SAME+ * provider organization (a Xero tenant, a QuickBooks realm) keeps the switch+ * where it was — an expired grant must not pause an integration that was+ * live. A first connection, or one to a different organization, starts off.+ */+export function syncEnabledOnConnect(+ existingMetadata: unknown,+ organizationId: string+): boolean {+ if (!existingMetadata || typeof existingMetadata !== "object") return false;+ const credentials = (existingMetadata as { credentials?: unknown })+ .credentials as Record<string, unknown> | undefined;+ const providerMetadata = credentials?.providerMetadata as+ | Record<string, unknown>+ | undefined;+ // Legacy rows kept the organization id directly on credentials.+ const previousOrganizationId =+ providerMetadata?.tenantId ??+ providerMetadata?.realmId ??+ credentials?.tenantId ??+ credentials?.realmId;+ return (+ previousOrganizationId === organizationId &&+ isAccountingSyncEnabled(existingMetadata)+ );+}+// /********************************************************\// * Sync Operation Schemas *// \********************************************************/diff --git a/packages/ee/src/accounting/core/operations.ts b/packages/ee/src/accounting/core/operations.tsindex 5319903a43..bf7783fbfb 100644--- a/packages/ee/src/accounting/core/operations.ts+++ b/packages/ee/src/accounting/core/operations.ts@@ -405,6 +405,9 @@ export async function clearResolvedSyncOperations(* `entityTypes` is the include-only counterpart (the consolidation cron* claims ONLY journalEntry operations). Mutually exclusive with* `excludeEntityTypes` — see getClaimEntityTypeFilterError.+ *+ * `direction` claims only operations going that way (a master-data import+ * claims only its own pulls).*/export async function claimPendingOperations(client: SupabaseClient<Database>,@@ -423,6 +426,7 @@ export async function claimPendingOperations(* transitional consolidation flag.*/holdDailySummaryJournalEntries?: boolean;+ direction?: SyncOperationDirection;}): Promise<{ data: SyncOperation[]; error: string | null }> {const filterError = getClaimEntityTypeFilterError(args);@@ -454,6 +458,9 @@ export async function claimPendingOperations(if (args.holdDailySummaryJournalEntries) {pendingQuery = pendingQuery.or(dailySummaryHold);}+ if (args.direction) {+ pendingQuery = pendingQuery.eq("direction", args.direction);+ }const pending = await pendingQuery.order("createdAt", { ascending: true })@@ -476,6 +483,9 @@ export async function claimPendingOperations(if (args.holdDailySummaryJournalEntries) {staleQuery = staleQuery.or(dailySummaryHold);}+ if (args.direction) {+ staleQuery = staleQuery.eq("direction", args.direction);+ }const stale = await staleQuery.order("createdAt", { ascending: true })@@ -833,3 +843,76 @@ export async function getSyncOperations(error: null};}++/** The columns the Sync Activity CSV export reads, and nothing heavier. */+const SYNC_OPERATION_EXPORT_COLUMNS =+ "id, integration, entityType, entityId, direction, trigger, status, attemptCount, lastAttemptAt, completedAt, errorCode, errorMessage, externalId, createdAt";++export type SyncOperationExportRow = Pick<+ SyncOperation,+ | "id"+ | "integration"+ | "entityType"+ | "entityId"+ | "direction"+ | "trigger"+ | "status"+ | "attemptCount"+ | "lastAttemptAt"+ | "completedAt"+ | "errorCode"+ | "errorMessage"+ | "externalId"+ | "createdAt"+>;++/** Where the previous page ended: its last row's sort key. */+export type SyncOperationCursor = Pick<SyncOperation, "createdAt" | "id">;++/**+ * One page of sync operations for the Sync Activity CSV export, newest first,+ * under the same filters as `getSyncOperations`. Keyset-paged on+ * (createdAt DESC, id) — served by `accountingSyncOperation_createdAt_idx` —+ * so the caller can stream an unbounded history one page at a time instead+ * of holding it in memory, and page N costs the same as page 1. Pass the+ * previous page's last row as `after`; a page shorter than `limit` is the+ * last one.+ */+export async function getSyncOperationsExportPage(+ client: SupabaseClient<Database>,+ args: {+ companyId: string;+ integration: string;+ status?: SyncOperationStatus | SyncOperationStatus[];+ after?: SyncOperationCursor;+ limit: number;+ }+): Promise<{ data: SyncOperationExportRow[]; error: string | null }> {+ let query = syncOperationTable(client)+ .select(SYNC_OPERATION_EXPORT_COLUMNS)+ .eq("companyId", args.companyId)+ .eq("integration", args.integration);++ if (args.status) {+ query = Array.isArray(args.status)+ ? query.in("status", args.status)+ : query.eq("status", args.status);+ }++ if (args.after) {+ // Quoted: a timestamp carries `.`, `:` and `+`, all reserved in an+ // or-filter. `id` ascending breaks createdAt ties, matching the index.+ const { createdAt, id } = args.after;+ query = query.or(+ `createdAt.lt."${createdAt}",and(createdAt.eq."${createdAt}",id.gt."${id}")`+ );+ }++ const result = await query+ .order("createdAt", { ascending: false })+ .order("id", { ascending: true })+ .limit(args.limit);++ if (result.error) return { data: [], error: result.error.message };+ return { data: (result.data ?? []) as SyncOperationExportRow[], error: null };+}diff --git a/packages/ee/src/accounting/core/sync-switch.test.ts b/packages/ee/src/accounting/core/sync-switch.test.tsnew file mode 100644index 0000000000..044a0d0565--- /dev/null+++ b/packages/ee/src/accounting/core/sync-switch.test.ts@@ -0,0 +1,150 @@+// 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 {+ type MappableChartAccount,+ selectRequiredMappingAccountIds,+ selectUnmappedRequiredAccounts+} from "./account-mapping";+import { isAccountingSyncEnabled, syncEnabledOnConnect } from "./models";++describe("isAccountingSyncEnabled", () => {+ it("is off only when the flag is explicitly false", () => {+ expect(isAccountingSyncEnabled({ settings: { syncEnabled: false } })).toBe(+ false+ );+ expect(isAccountingSyncEnabled({ settings: { syncEnabled: true } })).toBe(+ true+ );+ });++ it("treats a row that predates the switch as on", () => {+ expect(isAccountingSyncEnabled({ settings: { postingSync: {} } })).toBe(+ true+ );+ expect(isAccountingSyncEnabled({ credentials: {} })).toBe(true);+ expect(isAccountingSyncEnabled(null)).toBe(true);+ });+});++describe("syncEnabledOnConnect", () => {+ const live = (organization: Record<string, string>) => ({+ settings: { syncEnabled: true },+ credentials: { type: "oauth2", providerMetadata: organization }+ });++ it("starts a first connection off", () => {+ expect(syncEnabledOnConnect(null, "tenant-1")).toBe(false);+ expect(syncEnabledOnConnect(undefined, "realm-1")).toBe(false);+ });++ it("keeps a live integration on when it reconnects to the same organization", () => {+ expect(+ syncEnabledOnConnect(live({ tenantId: "tenant-1" }), "tenant-1")+ ).toBe(true);+ expect(syncEnabledOnConnect(live({ realmId: "realm-1" }), "realm-1")).toBe(+ true+ );+ });++ it("keeps a legacy row (no flag, id on credentials) on for the same organization", () => {+ expect(+ syncEnabledOnConnect(+ { credentials: { tenantId: "tenant-1" } },+ "tenant-1"+ )+ ).toBe(true);+ });++ it("starts off when the organization changes", () => {+ expect(+ syncEnabledOnConnect(live({ tenantId: "tenant-1" }), "tenant-2")+ ).toBe(false);+ });++ it("keeps a switched-off integration off on reconnect", () => {+ expect(+ syncEnabledOnConnect(+ {+ settings: { syncEnabled: false },+ credentials: { providerMetadata: { tenantId: "tenant-1" } }+ },+ "tenant-1"+ )+ ).toBe(false);+ });+});++describe("required account mapping", () => {+ const chart: MappableChartAccount[] = [+ {+ id: "sales",+ number: "4000",+ name: "Sales",+ class: "Revenue",+ accountType: null+ },+ {+ id: "rent",+ number: "6100",+ name: "Rent",+ class: "Expense",+ accountType: null+ },+ {+ id: "travel",+ number: "6200",+ name: "Travel",+ class: "Expense",+ accountType: null+ },+ {+ id: "cash",+ number: "1000",+ name: "Cash",+ class: "Asset",+ accountType: null+ }+ ];++ it("requires every posting-default account plus every Expense account", () => {+ expect(+ selectRequiredMappingAccountIds(["sales", "rent"], chart).sort()+ ).toEqual(["rent", "sales", "travel"]);+ });++ it("lists required accounts that are not mapped, ignoring optional ones", () => {+ expect(+ selectUnmappedRequiredAccounts({+ accountDefaultIds: ["sales"],+ chart,+ mappedAccountIds: new Set(["rent", "cash"])+ })+ ).toEqual([+ { id: "sales", number: "4000", name: "Sales" },+ { id: "travel", number: "6200", name: "Travel" }+ ]);+ });++ it("is empty once every required account is mapped", () => {+ expect(+ selectUnmappedRequiredAccounts({+ accountDefaultIds: ["sales"],+ chart,+ mappedAccountIds: new Set(["sales", "rent", "travel"])+ })+ ).toEqual([]);+ });++ it("ignores a posting default that is not an active leaf account", () => {+ expect(+ selectUnmappedRequiredAccounts({+ accountDefaultIds: ["inactive-account"],+ chart: [],+ mappedAccountIds: new Set()+ })+ ).toEqual([]);+ });+});diff --git a/packages/ee/src/accounting/providers/xero/entities/__tests__/purchase-order.test.ts b/packages/ee/src/accounting/providers/xero/entities/__tests__/purchase-order.test.tsnew file mode 100644index 0000000000..e339ef62a7--- /dev/null+++ b/packages/ee/src/accounting/providers/xero/entities/__tests__/purchase-order.test.ts@@ -0,0 +1,114 @@+// 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 type { Accounting } from "../../../../core/types";+import type { Xero } from "../../models";+import { xeroItemCode } from "../item";+import { PurchaseOrderSyncer } from "../purchase-order";++/**+ * A PO line names its item by `ItemCode`, which Xero resolves against the+ * items it holds. The item syncer pushes a revised item as+ * `readableIdWithRevision` (`PRT-001374.A`), so a line sending the bare+ * `readableId` is refused with "Item code 'PRT-001374' is not valid".+ */++describe("xeroItemCode", () => {+ it("uses the revisioned id when the item has one", () => {+ expect(+ xeroItemCode({+ readableId: "PRT-001374",+ readableIdWithRevision: "PRT-001374.A"+ })+ ).toBe("PRT-001374.A");+ });++ it("falls back to the readable id", () => {+ expect(+ xeroItemCode({ readableId: "PRT-001374", readableIdWithRevision: null })+ ).toBe("PRT-001374");+ });+});++function makePurchaseOrderSyncer(itemRow: {+ readableId: string;+ readableIdWithRevision: string | null;+}) {+ const query = {+ selectFrom: () => query,+ select: () => query,+ where: () => query,+ executeTakeFirst: async () => itemRow+ };+ const syncer = new PurchaseOrderSyncer({+ database: query as never,+ companyId: "company-1",+ provider: { id: "xero" } as never,+ config: { enabled: true, direction: "push-to-accounting", owner: "carbon" },+ entityType: "purchaseOrder"+ });+ const internals = syncer as unknown as Record<string, unknown>;+ internals.getRemoteId = async () => null;+ internals.ensureDependencySynced = async () => "xero-item-1";+ return syncer as unknown as {+ mapToRemote(local: Accounting.PurchaseOrder): Promise<Xero.PurchaseOrder>;+ };+}++const purchaseOrder = (+ line: Partial<Accounting.PurchaseOrder["lines"][number]>+): Accounting.PurchaseOrder =>+ ({+ id: "po-1",+ companyId: "company-1",+ purchaseOrderId: "PO000709",+ supplierId: "supplier-1",+ supplierExternalId: "xero-contact-1",+ status: "To Receive",+ orderDate: "2026-09-30",+ currencyCode: "GBP",+ exchangeRate: 1,+ subtotal: 10,+ totalTax: 0,+ totalAmount: 10,+ supplierReference: null,+ lines: [+ {+ id: "line-1",+ description: "Bracket",+ quantity: 1,+ unitPrice: 10,+ itemId: "item-1",+ itemCode: null,+ accountNumber: null,+ taxPercent: null,+ taxAmount: null,+ totalAmount: 10,+ quantityReceived: null,+ quantityInvoiced: null,+ ...line+ }+ ]+ }) as unknown as Accounting.PurchaseOrder;++describe("Xero PurchaseOrderSyncer.mapToRemote (line ItemCode)", () => {+ it("sends the code the item was pushed under, revision included", async () => {+ const payload = await makePurchaseOrderSyncer({+ readableId: "PRT-001374",+ readableIdWithRevision: "PRT-001374.A"+ }).mapToRemote(purchaseOrder({}));++ expect(payload.LineItems?.[0]?.ItemCode).toBe("PRT-001374.A");+ });++ it("sends no ItemCode on a line without an item", async () => {+ const payload = await makePurchaseOrderSyncer({+ readableId: "unused",+ readableIdWithRevision: null+ }).mapToRemote(purchaseOrder({ itemId: null }));++ expect(payload.LineItems?.[0]?.ItemCode).toBeUndefined();+ });+});diff --git a/packages/ee/src/accounting/providers/xero/entities/item.ts b/packages/ee/src/accounting/providers/xero/entities/item.tsindex 26ec95157f..c668439672 100644--- a/packages/ee/src/accounting/providers/xero/entities/item.ts+++ b/packages/ee/src/accounting/providers/xero/entities/item.ts@@ -25,6 +25,19 @@ type ItemRow = {unitSalePrice: number | null;};+/**+ * The `Code` an item is pushed to Xero under. Any document line that names+ * the item by `ItemCode` must use this too — Xero rejects a code it has no+ * item for ("Item code 'X' is not valid"), so a revised item pushed as+ * `PRT-1.A` cannot be referenced as `PRT-1`.+ */+export function xeroItemCode(item: {+ readableId: string;+ readableIdWithRevision: string | null;+}): string {+ return item.readableIdWithRevision ?? item.readableId;+}+export class ItemSyncer extends BaseEntitySyncer<Accounting.Item,Xero.Item,@@ -105,7 +118,7 @@ export class ItemSyncer extends BaseEntitySyncer<result.set(row.id, {id: row.id,- code: row.readableIdWithRevision ?? row.readableId,+ code: xeroItemCode(row),name: row.name,description: row.description,companyId: row.companyId!,diff --git a/packages/ee/src/accounting/providers/xero/entities/purchase-order.ts b/packages/ee/src/accounting/providers/xero/entities/purchase-order.tsindex 1a3e81bb16..ee3fbf8a36 100644--- a/packages/ee/src/accounting/providers/xero/entities/purchase-order.ts+++ b/packages/ee/src/accounting/providers/xero/entities/purchase-order.ts@@ -12,6 +12,7 @@ import {import { throwXeroApiError } from "../../../core/utils";import { parseDotnetDate, type Xero } from "../models";import type { XeroProvider } from "../provider";+import { xeroItemCode } from "./item";// Note: This syncer uses the default ID mapping from BaseEntitySyncer// which uses the externalIntegrationMapping table with entityType "purchaseOrder"@@ -54,7 +55,8 @@ type PurchaseOrderLineRow = {extendedPrice: number | null;quantityReceived: number | null;quantityInvoiced: number | null;- itemCode: string | null;+ itemReadableId: string | null;+ itemReadableIdWithRevision: string | null;};// Status mapping between Carbon and Xero@@ -168,7 +170,8 @@ export class PurchaseOrderSyncer extends BaseEntitySyncer<"purchaseOrderLine.extendedPrice","purchaseOrderLine.quantityReceived","purchaseOrderLine.quantityInvoiced",- "item.readableId as itemCode",+ "item.readableId as itemReadableId",+ "item.readableIdWithRevision as itemReadableIdWithRevision","account.number as accountNumber"]).where("purchaseOrderLine.purchaseOrderId", "in", orderIds)@@ -236,7 +239,12 @@ export class PurchaseOrderSyncer extends BaseEntitySyncer<quantity: Number(line.purchaseQuantity) || 0,unitPrice: Number(line.unitPrice) || 0,itemId: line.itemId,- itemCode: line.itemCode,+ itemCode: line.itemReadableId+ ? xeroItemCode({+ readableId: line.itemReadableId,+ readableIdWithRevision: line.itemReadableIdWithRevision+ })+ : null,accountNumber: line.accountNumber,taxPercent: line.taxPercent != null ? Number(line.taxPercent) : null,taxAmount: line.taxAmount != null ? Number(line.taxAmount) : null,@@ -330,10 +338,10 @@ export class PurchaseOrderSyncer extends BaseEntitySyncer<if (!itemCode) {const item = await this.database.selectFrom("item")- .select("readableId")+ .select(["readableId", "readableIdWithRevision"]).where("id", "=", line.itemId).executeTakeFirst();- itemCode = item?.readableId ?? null;+ itemCode = item ? xeroItemCode(item) : null;}}diff --git a/packages/files/AGENTS.md b/packages/files/AGENTS.mdindex 8a1a26a9e2..0895653ca2 100644--- a/packages/files/AGENTS.md+++ b/packages/files/AGENTS.md@@ -7,7 +7,7 @@ in the codebase, shared by the browser, Node, and the Supabase edge runtime.| Subpath | Provides ||---------|----------|| `.` (root) | Cross-type helpers: `MEDIA_CONTENT_TYPES` + `getContentType` (the one extension→MIME map every file-serving route uses), `getFileExtension` / `effectiveExtension` (`.zst` unwrap), `getDocumentType` / `documentTypes` / `isPreviewableDocumentType` (file classification for the Documents UI), `convertKbToString`, and `downloadBlob` / `downloadText` — THE browser "save this as a file" sequence (object URL → anchor click → revoke); never hand-roll it. **`storage(client)`** — the Carbon storage client, supabase-shaped: `.from(bucket)` is plain supabase for `public` / `temp-staging`; `.company(companyId)` is that company's private bucket (bucket id = companyId, THROWS on an empty id). Writes go to the company bucket only; reads (`download`, `info`, `exists`, `createSignedUrl`) fall back to the legacy shared `private` bucket, `move` retries as a move OUT of it, `list` unions both and `remove` deletes from both. The fallback stays until nothing writes to `private` any more: the one-off copy (`scripts/one-off/migrate-private-buckets.ts`) ran, but files have landed there since. `list(folder)` takes no options: it reads the cursor-paged `listV2` endpoint to the end in both buckets and returns every entry directly inside the folder, sorted by name, in the old `list` shape (`name` is the entry's own name; a sub-folder has a null `id`), the company copy winning a tie. Every key must sit under `${companyId}/` and pass `isUnsafeStoragePath`; anything else gets `{ data: null, error }` without touching storage. **`isUnsafeStoragePath(path)`** is THE storage-key traversal guard (dot segments, `\`, `?`, `#`, control characters, checked as given and after every decode so `%2e%2e` / `%252e%252e` are caught; malformed escapes refused) — every route that takes a key from a URL or form calls it rather than a local copy; **`safeStorageFileName(name)`** turns a caller-supplied file name into a safe last key segment (basename, no `%`) or null. This is the contract for document keys (`${companyId}/parts/…`, `/job/…`, `/tmp/…`, everything `getPrivateUrl` serves); the backup and audit-archive layouts (`exports/…`, `audit/…`) share the bucket under their own keys and keep using plain `client.storage.from(companyId)`. `getCompanyPrivateBucket` / `LEGACY_PRIVATE_BUCKET` / `hasCompanyPrivateObjectPathPrefix` are exported for the few places that need the bucket *name* (MediaUploader staging, route authorization, the assembler's bucket resolver) |-| `./csv` | `encodeCsv` (object rows) / `encodeCsvTable` (header + cells) — the ONE CSV encoder, injection-safe by construction (`stripCsvFormulaPrefix` on every string cell); `parseCsv` (text) / `parseCsvFile` (browser File, streamed); `downloadCsv`; `CSV_CONTENT_TYPE`. papaparse underneath, in every runtime. The Table export button, report exports, import templates, import-error re-exports and the sales CSV import all go through here — before this there were two libraries (`json-2-csv` + papaparse) and two hand-rolled encoders, and only ONE of the five export sites protected against formula injection |+| `./csv` | `encodeCsv` (object rows; `header: false` encodes a later page of a streamed file — pages join with `\r\n`, see the Sync Activity export) / `encodeCsvTable` (header + cells) — the ONE CSV encoder, injection-safe by construction (`stripCsvFormulaPrefix` on every string cell); `parseCsv` (text) / `parseCsvFile` (browser File, streamed); `downloadCsv`; `CSV_CONTENT_TYPE`. papaparse underneath, in every runtime. The Table export button, report exports, import templates, import-error re-exports and the sales CSV import all go through here — before this there were two libraries (`json-2-csv` + papaparse) and two hand-rolled encoders, and only ONE of the five export sites protected against formula injection || `./media` | Images. **`MediaUploader`** — the configured client (constructor takes the storage client + HEIC staging location once, files-sdk style): `prepareForUpload(files)` (HEIC → JPEG sequentially + duplicate-name refusal, throws `DuplicateFileNameError`), `convertHeic(file)`, `prepareImage(file, shape)`. Underneath: `processImage` (the pipeline), `prepareImageUpload` (pipeline → native-decode fallback → imgproxy fallback), `convertHeicToJpeg` / `convertHeicFiles` / `findDuplicateFileName`, `transformImageViaStorage` (imgproxy round-trip), `isHeic`, `IMAGE_UPLOAD_MIME_TYPES`, plus the storage-path helpers `getPrivateUrl` / `getRawModelUrl` / `parseJobFilePath` || `./media/node` | `initNodeImageCodecs()` — Node-only wasm pre-instantiation; call once before the pipeline in Node (jobs, paperless, vitest). The wasm comes from the BUNDLER (`?inline` data URIs), never off disk — so this module is consumable only from a Vite pipeline, and that pipeline needs `assetsInclude: ["**/*.wasm"]` (already set in `apps/erp/vite.config.ts` and `@carbon/config/vitest`). Never import from client code || `./cad` | CAD/model formats: `supportedModelTypes`, `optimizableModelFormat`, `modelPathOptimizeFormat`, `isModelRawDownloadable` |diff --git a/packages/files/src/csv/csv.test.ts b/packages/files/src/csv/csv.test.tsindex 6be3357d4a..6a3ab614ed 100644--- a/packages/files/src/csv/csv.test.ts+++ b/packages/files/src/csv/csv.test.ts@@ -24,6 +24,19 @@ describe("encodeCsv", () => {});expect(csv).toBe("a,b,c\r\n2,1,-");});+ it("joins header-less pages into the same file as one encode", () => {+ const fields = ["a", "b"];+ const rows = [+ { a: 1, b: "x" },+ { a: 2, b: "y, z" },+ { a: 3, b: '"q"' }+ ];+ const paged = [+ encodeCsv(rows.slice(0, 2), { fields }),+ encodeCsv(rows.slice(2), { fields, header: false })+ ].join("\r\n");+ expect(paged).toBe(encodeCsv(rows, { fields }));+ });});describe("encodeCsvTable / parseCsv round trip", () => {diff --git a/packages/files/src/csv/csv.ts b/packages/files/src/csv/csv.tsindex 3611acb04e..319bbc53fb 100644--- a/packages/files/src/csv/csv.ts+++ b/packages/files/src/csv/csv.ts@@ -35,6 +35,11 @@ export type EncodeCsvOptions = {fields?: string[];/** Value emitted for null/undefined cells. Default "". */emptyFieldValue?: string;+ /**+ * Emit the header row. Default true. Pass false for every page after the+ * first when streaming one file in pages; the pages join with "\r\n".+ */+ header?: boolean;};/**@@ -57,7 +62,10 @@ export function encodeCsv(}));// Headers are cells too — import-error re-exports echo uploaded headers.- return Papa.unparse({ fields: fields.map(stripCsvFormulaPrefix), data });+ return Papa.unparse(+ { fields: fields.map(stripCsvFormulaPrefix), data },+ { header: options.header ?? true }+ );}/** Header row + tabular cells → CSV text (for templates and error re-exports). */diff --git a/packages/jobs/src/inngest/functions/events/sync.ts b/packages/jobs/src/inngest/functions/events/sync.tsindex 3960ff20f4..8a25fc5bf7 100644--- a/packages/jobs/src/inngest/functions/events/sync.ts+++ b/packages/jobs/src/inngest/functions/events/sync.ts@@ -4,7 +4,11 @@import { getCarbonServiceRole } from "@carbon/auth/client.server";import { EventSchema } from "@carbon/database/event";-import { ProviderID, SpendProviderID } from "@carbon/ee/accounting";+import {+ isAccountingSyncEnabled,+ ProviderID,+ SpendProviderID+} from "@carbon/ee/accounting";import { groupBy } from "@carbon/utils";import { z } from "zod";/**@@ -146,6 +150,17 @@ export const syncFunction = inngest.createFunction(}return stepSummary;}+ // Sync is still off on this integration (it is being set up):+ // record nothing, so turning it on starts from a clean ledger.+ if (!isAccountingSyncEnabled(resolved.metadata)) {+ for (const r of records) {+ stepSummary.skipped.push({+ recordId: r.event.recordId,+ reason: `Sync is turned off for '${provider}'`+ });+ }+ return stepSummary;+ }const seen = new Set<string>();const refs: ReconcileRef[] = [];diff --git a/packages/jobs/src/inngest/functions/integrations/accounting-consolidation.ts b/packages/jobs/src/inngest/functions/integrations/accounting-consolidation.tsindex a18fb3f26e..47b40226a7 100644--- a/packages/jobs/src/inngest/functions/integrations/accounting-consolidation.ts+++ b/packages/jobs/src/inngest/functions/integrations/accounting-consolidation.ts@@ -14,6 +14,7 @@ import {getPostingSyncSourceTypeSkipReason,getProviderIntegration,getSyncOperations,+ isAccountingSyncEnabled,JournalEntrySyncError,type JournalEntrySyncer,mapJournalEntryToManualJournal,@@ -734,6 +735,7 @@ export const accountingConsolidationFunction = inngest.createFunction(return (integrations.data ?? []).filter((row) => {+ if (!isAccountingSyncEnabled(row.metadata)) return false;const settings = resolvePostingSyncSettings(row.metadata);return (settings.consolidation === "daily" ||diff --git a/packages/jobs/src/inngest/functions/integrations/accounting-journal-backfill.ts b/packages/jobs/src/inngest/functions/integrations/accounting-journal-backfill.tsindex c85a1a2efa..44a1f8fda4 100644--- a/packages/jobs/src/inngest/functions/integrations/accounting-journal-backfill.ts+++ b/packages/jobs/src/inngest/functions/integrations/accounting-journal-backfill.ts@@ -22,6 +22,7 @@import { getCarbonServiceRole } from "@carbon/auth/client.server";import {getAccountingIntegration,+ isAccountingSyncEnabled,ProviderID,resolvePostingSyncSettings} from "@carbon/ee/accounting";@@ -85,6 +86,11 @@ export const accountingJournalBackfillFunction = inngest.createFunction(skippedReason: null as string | null};+ if (!isAccountingSyncEnabled(phaseIntegration.metadata)) {+ summary.skippedReason = "sync is turned off for this integration";+ return summary;+ }+if (!isJournalEntryPostingEnabled(phaseIntegration.metadata)) {summary.skippedReason = "posting sync (journalEntry) disabled";return summary;diff --git a/packages/jobs/src/inngest/functions/integrations/accounting-master-sync.ts b/packages/jobs/src/inngest/functions/integrations/accounting-master-sync.tsindex 94fd39a7ad..db41e47898 100644--- a/packages/jobs/src/inngest/functions/integrations/accounting-master-sync.ts+++ b/packages/jobs/src/inngest/functions/integrations/accounting-master-sync.ts@@ -8,6 +8,7 @@ import {createMappingService,getAccountingIntegration,getProviderIntegration,+ isAccountingSyncEnabled,ProviderID,providerSupportsMasterDataImport,type SyncContext,@@ -162,6 +163,23 @@ export const accountingMasterSyncFunction = inngest.createFunction() as AccountingProvider;const database = getJobDatabaseClient();+ // A push while sync is off is refused by the API route; this covers an+ // event sent some other way, or sync turned off after the route accepted+ // it. An import (pull) runs either way — it only writes into Carbon, and+ // the links it creates are what keep the first push after sync is turned+ // on from duplicating customers and vendors in the ledger.+ if (+ payload.direction === "push-to-accounting" &&+ !isAccountingSyncEnabled(integration.metadata)+ ) {+ return {+ provider: payload.provider,+ direction: payload.direction,+ entities: {},+ skippedReason: "sync is turned off for this integration"+ };+ }+const createdBy = getSyncOperationActor(integration);const result: Record<string, EntityCounts> = {};@@ -342,13 +360,23 @@ async function syncBatch(args: {companyId: args.companyId,integration: args.integrationId,provider: args.provider,- integrationMetadata: args.integrationMetadata+ integrationMetadata: args.integrationMetadata,+ // An import drains only its own pulls — which is also what lets it run+ // while sync is off without flushing anything else that is waiting.+ ...(args.direction === "pull-from-accounting"+ ? {+ only: {+ entityTypes: [args.entityType],+ direction: args.direction+ }+ }+ : {})});counts.claimed = drained.claimed;- // A drain processes every claimable operation for the company, not just this- // batch's. Attributing its result to THIS batch is correct only because+ // A push drain processes every claimable operation for the company, not just+ // this batch's (an import's is scoped to its own pulls, above). Attributing its result to THIS batch is correct only because// `concurrency: { limit: 1 }` plus the sequential batch loop mean earlier// batches are already Completed (never re-claimed) and later ones are not// enqueued yet — so the only ops in flight for this (direction, entityType)diff --git a/packages/jobs/src/inngest/functions/integrations/accounting-outbound-sweep.ts b/packages/jobs/src/inngest/functions/integrations/accounting-outbound-sweep.tsindex e6f7be8b68..e638be6cc2 100644--- a/packages/jobs/src/inngest/functions/integrations/accounting-outbound-sweep.ts+++ b/packages/jobs/src/inngest/functions/integrations/accounting-outbound-sweep.ts@@ -8,6 +8,7 @@ import {ensureProviderSubscriptions,getAccountingIntegration,getProviderIntegration,+ isAccountingSyncEnabled,PAYMENT_PUSH_PROVIDERS,ProviderID,resolvePostingSyncSettings,@@ -663,7 +664,7 @@ export const accountingOutboundSweepFunction = inngest.createFunction(const targets = await step.run("find-outbound-sweep-targets", async () => {const integrations = await client.from("companyIntegration")- .select("id, companyId, updatedBy")+ .select("id, companyId, metadata, updatedBy").in("id", Object.values(ProviderID)).eq("active", true);@@ -673,11 +674,14 @@ export const accountingOutboundSweepFunction = inngest.createFunction();}- return (integrations.data ?? []).map((row) => ({- companyId: row.companyId,- providerId: row.id as ProviderID,- updatedBy: row.updatedBy- }));+ // An integration with sync turned off is still being set up.+ return (integrations.data ?? [])+ .filter((row) => isAccountingSyncEnabled(row.metadata))+ .map((row) => ({+ companyId: row.companyId,+ providerId: row.id as ProviderID,+ updatedBy: row.updatedBy+ }));});if (targets.length === 0) {diff --git a/packages/jobs/src/inngest/functions/integrations/accounting-pull-sweep.ts b/packages/jobs/src/inngest/functions/integrations/accounting-pull-sweep.tsindex bebb850946..ba521e91ed 100644--- a/packages/jobs/src/inngest/functions/integrations/accounting-pull-sweep.ts+++ b/packages/jobs/src/inngest/functions/integrations/accounting-pull-sweep.ts@@ -9,6 +9,7 @@ import {findPaymentCompositesByRemoteId,getAccountingIntegration,getProviderIntegration,+ isAccountingSyncEnabled,type ProviderChange,ProviderID,providerSupportsIncrementalPull,@@ -421,7 +422,7 @@ export const accountingPullSweepFunction = inngest.createFunction(const targets = await step.run("find-pull-sweep-targets", async () => {const integrations = await client.from("companyIntegration")- .select("id, companyId, updatedBy")+ .select("id, companyId, metadata, updatedBy").in("id", Object.values(ProviderID)).eq("active", true);@@ -431,11 +432,14 @@ export const accountingPullSweepFunction = inngest.createFunction();}- return (integrations.data ?? []).map((row) => ({- companyId: row.companyId,- providerId: row.id as ProviderID,- updatedBy: row.updatedBy- }));+ // An integration with sync turned off is still being set up.+ return (integrations.data ?? [])+ .filter((row) => isAccountingSyncEnabled(row.metadata))+ .map((row) => ({+ companyId: row.companyId,+ providerId: row.id as ProviderID,+ updatedBy: row.updatedBy+ }));});if (targets.length === 0) {diff --git a/packages/jobs/src/inngest/functions/integrations/accounting-reconciliation.ts b/packages/jobs/src/inngest/functions/integrations/accounting-reconciliation.tsindex b3dd32a7f7..7a5fc4c3f1 100644--- a/packages/jobs/src/inngest/functions/integrations/accounting-reconciliation.ts+++ b/packages/jobs/src/inngest/functions/integrations/accounting-reconciliation.ts@@ -9,6 +9,7 @@ import {getJournalEntrySyncEntityId,getProviderIntegration,getSyncOperations,+ isAccountingSyncEnabled,ProviderID,parseJournalEntrySyncEntityId,RatelimitError,@@ -993,7 +994,11 @@ export const accountingReconciliationFunction = inngest.createFunction(}return (integrations.data ?? [])- .filter((row) => resolvePostingSyncSettings(row.metadata).enabled)+ .filter(+ (row) =>+ isAccountingSyncEnabled(row.metadata) &&+ resolvePostingSyncSettings(row.metadata).enabled+ ).map((row) => ({companyId: row.companyId,providerId: row.id,diff --git a/packages/jobs/src/inngest/functions/integrations/accounting-sync-operations.test.ts b/packages/jobs/src/inngest/functions/integrations/accounting-sync-operations.test.tsindex a2ec981c25..6241c43d93 100644--- a/packages/jobs/src/inngest/functions/integrations/accounting-sync-operations.test.ts+++ b/packages/jobs/src/inngest/functions/integrations/accounting-sync-operations.test.ts@@ -12,6 +12,7 @@ import type { SupabaseClient } from "@supabase/supabase-js";import { describe, expect, it } from "vitest";import {compareMonthlyTotals,+ drainSyncOperations,getAdvancedPullCursor,getDailyConsolidationBatchKey,getJournalPostingDecision,@@ -1805,3 +1806,89 @@ describe("loadChargePolicyInputs", () => {expect(queries).toEqual([]);});});++describe("drainSyncOperations while sync is turned off", () => {+ // Records every query-builder call; every query resolves to no rows, so a+ // drain that claims stops after one empty claim.+ function recordingClient() {+ const calls: Array<[string, unknown[]]> = [];+ const builder: Record<string, unknown> = {};+ const proxy: unknown = new Proxy(builder, {+ get(_target, prop) {+ if (prop === "then") {+ return (resolve: (value: unknown) => void) =>+ resolve({ data: [], error: null });+ }+ return (...args: unknown[]) => {+ calls.push([String(prop), args]);+ return proxy;+ };+ }+ });+ const client = {+ from: (table: string) => {+ calls.push(["from", [table]]);+ return proxy;+ }+ };+ return {+ calls,+ client: client as unknown as SupabaseClient<Database>+ };+ }++ const drainArgs = (client: SupabaseClient<Database>) => ({+ client,+ database: {} as never,+ companyId: "company-1",+ integration: "xero",+ provider: {} as never,+ integrationMetadata: { settings: { syncEnabled: false } }+ });++ it("claims nothing", async () => {+ const { client, calls } = recordingClient();++ const summary = await drainSyncOperations(drainArgs(client));++ expect(summary.claimed).toBe(0);+ expect(calls).toEqual([]);+ });++ it("lets a customer/vendor import drain only its own pulls", async () => {+ const { client, calls } = recordingClient();++ await drainSyncOperations({+ ...drainArgs(client),+ only: { entityTypes: ["customer"], direction: "pull-from-accounting" }+ });++ // Both claim queries (Pending + stale In Flight) are scoped.+ const directionFilters = calls.filter(+ ([method, args]) => method === "eq" && args[0] === "direction"+ );+ expect(directionFilters).toEqual([+ ["eq", ["direction", "pull-from-accounting"]],+ ["eq", ["direction", "pull-from-accounting"]]+ ]);+ expect(+ calls.filter(+ ([method, args]) => method === "in" && args[0] === "entityType"+ )+ ).toEqual([+ ["in", ["entityType", ["customer"]]],+ ["in", ["entityType", ["customer"]]]+ ]);+ });++ it("does not let a scoped push through", async () => {+ const { client, calls } = recordingClient();++ await drainSyncOperations({+ ...drainArgs(client),+ only: { entityTypes: ["customer"], direction: "push-to-accounting" }+ });++ expect(calls).toEqual([]);+ });+});diff --git a/packages/jobs/src/inngest/functions/integrations/accounting-sync-operations.ts b/packages/jobs/src/inngest/functions/integrations/accounting-sync-operations.tsindex b12622959c..17a82fb02d 100644--- a/packages/jobs/src/inngest/functions/integrations/accounting-sync-operations.ts+++ b/packages/jobs/src/inngest/functions/integrations/accounting-sync-operations.ts@@ -44,6 +44,7 @@ import {getJournalEntrySyncEntityId,getJournalPostingPolicyDecision,insertTerminalSyncOperation,+ isAccountingSyncEnabled,isJournalEntrySyncFailure,netJournalLinesPerAccount,type PostingSyncSettings,@@ -949,6 +950,15 @@ export async function drainSyncOperations(args: {* silently push daily-consolidation journal operations individually.*/integrationMetadata: unknown;+ /**+ * Claim only these operations. A master-data import passes its own entity+ * type and the pull direction, so it drains what it enqueued and nothing+ * else that is waiting.+ */+ only?: {+ entityTypes: AccountingEntityType[];+ direction: SyncOperationDirection;+ };}): Promise<DrainSummary> {const summary: DrainSummary = {claimed: 0,@@ -958,6 +968,19 @@ export async function drainSyncOperations(args: {groups: []};+ // Sync is turned off (an accounting integration still being set up): leave+ // every row Pending. The entry points already skip enqueueing; this is the+ // backstop for a Retry clicked in Sync Activity, which the first drain after+ // sync is turned on then picks up. The one exception is a scoped PULL — a+ // customer/vendor import only writes into Carbon, and the links it creates+ // are what stop the first push after sync is on from duplicating records.+ if (+ !isAccountingSyncEnabled(args.integrationMetadata) &&+ args.only?.direction !== "pull-from-accounting"+ ) {+ return summary;+ }+const postingSyncSettings = resolvePostingSyncSettings(args.integrationMetadata);@@ -975,9 +998,14 @@ export async function drainSyncOperations(args: {const claimed = await claimPendingOperations(args.client, {companyId: args.companyId,integration: args.integration,- ...(excludeEntityTypes- ? { excludeEntityTypes }- : { holdDailySummaryJournalEntries: true })+ ...(args.only+ ? {+ entityTypes: args.only.entityTypes,+ direction: args.only.direction+ }+ : excludeEntityTypes+ ? { excludeEntityTypes }+ : { holdDailySummaryJournalEntries: true })});if (claimed.error) {diff --git a/packages/jobs/src/inngest/functions/integrations/sync-external-accounting.ts b/packages/jobs/src/inngest/functions/integrations/sync-external-accounting.tsindex eb1989d993..364cf71429 100644--- a/packages/jobs/src/inngest/functions/integrations/sync-external-accounting.ts+++ b/packages/jobs/src/inngest/functions/integrations/sync-external-accounting.ts@@ -9,6 +9,7 @@ import {createMappingService,getAccountingIntegration,getProviderIntegration,+ isAccountingSyncEnabled,type SyncOperationTrigger} from "@carbon/ee/accounting";import { getLogger } from "@carbon/logger";@@ -93,6 +94,18 @@ export const syncExternalAccountingFunction = inngest.createFunction(payload.provider);+ // Sync is turned off (the integration is still being set up): a+ // webhook must not queue work that runs the moment it is turned on.+ if (!isAccountingSyncEnabled(integration.metadata)) {+ log.info("Sync is turned off for this integration, skipping");+ return {+ enqueued: 0,+ cooldownSkipped: 0,+ disabled: [...new Set(payload.entities.map((e) => e.entityType))],+ errors: []+ } satisfies EnqueueStepSummary;+ }+const provider = getProviderIntegration(client,payload.companyId,diff --git a/packages/locale/locales/de/erp.po b/packages/locale/locales/de/erp.poindex 6ba0c1ba2e..7284931859 100644--- a/packages/locale/locales/de/erp.po+++ b/packages/locale/locales/de/erp.po@@ -433,6 +433,9 @@ msgstr "{unbatchedBatchableOperations} Los-fähige Arbeitsgänge sind nicht in emsgid "{uncounted, plural, one {# uncounted line} other {# uncounted lines}}"msgstr "{uncounted, plural, one {# nicht gezählte Zeile} other {# nicht gezählte Zeilen}}"+msgid "{unmappedRequiredCount, plural, one {Map the # remaining required account first.} other {Map the # remaining required accounts first.}}"+msgstr ""+msgid "{unschedulableCount} can't be scheduled"msgstr "{unschedulableCount} können nicht eingeplant werden"@@ -8805,6 +8808,9 @@ msgstr "Hat Arbeitsgänge, die nicht eingeplant werden können"msgid "Headers"msgstr "Header"+msgid "healthy"+msgstr ""+msgid "Help"msgstr "Hilfe"@@ -9238,6 +9244,9 @@ msgstr "In-App-Benachrichtigungen werden immer zugestellt. Wählen Sie, welche Tmsgid "In-app notifications are always delivered. Choose which topics also reach you by email."msgstr "In-App-Benachrichtigungen werden immer zugestellt. Wählen Sie, welche Themen Sie auch per E-Mail erreichen."+msgid "inactive"+msgstr ""+msgid "Inactive"msgstr "Inaktiv"@@ -12353,6 +12362,12 @@ msgstr "Nichts hier entspricht Ihrer Suche und Ihren Filtern."msgid "Nothing in the archive"msgstr "Nichts im Archiv"+msgid "Nothing is synced until you turn sync on."+msgstr ""++msgid "Nothing is synced until you turn sync on. Every required account is mapped."+msgstr ""+msgid "Nothing scheduled — add a station below."msgstr "Nichts geplant — fügen Sie unten eine Station hinzu."@@ -12414,6 +12429,9 @@ msgstr "von"msgid "of {0}h"msgstr "von {0}h"+msgid "Off"+msgstr ""+msgid "Off — handled outside the sync"msgstr "Aus — außerhalb der Synchronisierung behandelt"@@ -12429,6 +12447,9 @@ msgstr "OK"msgid "Oldest first"msgstr "Älteste zuerst"+msgid "On"+msgstr ""+msgid "On cutover day, work the checklist below in order. Acceptance tests come from your in-scope requirements. Support details are at the bottom."msgstr "Am Umstellungstag arbeiten Sie die Checkliste unten der Reihe nach ab. Akzeptanztests stammen aus Ihren im Umfang enthaltenen Anforderungen. Supportdetails finden Sie unten."@@ -12447,6 +12468,9 @@ msgstr "Verfügbar"msgid "On Hand"msgstr "Verfügbar"+msgid "On hand {before} to {after}"+msgstr "Verfügbar: {before} auf {after}"+msgid "On Hold"msgstr "Angehalten"@@ -12602,6 +12626,9 @@ msgstr "Öffnen"msgid "Open a change notice"msgstr "Öffnen Sie eine Änderungsmitteilung"+msgid "Open Account Mapping"+msgstr ""+msgid "Open Actions"msgstr "Offene Maßnahmen"@@ -14703,6 +14730,9 @@ msgstr "Erfasst, dass das Prüfmittel während dieser Kalibrierung angepasst wurmsgid "Records"msgstr "Aufzeichnungen"+msgid "Records and posted journals are being sent to and received from this provider."+msgstr ""+msgid "Recovery Period"msgstr "Registrieren"@@ -17804,6 +17834,9 @@ msgstr "Synchronisieren"msgid "Sync Activity"msgstr "Synchronisierungsaktivität"+msgid "sync off"+msgstr ""+msgid "Sync operation"msgstr "Synchronisierungsoperation"@@ -19774,6 +19807,9 @@ msgstr "Rückgängig machen"msgid "Ungroup"msgstr ""+msgid "unhealthy"+msgstr ""+msgid "Uninstall"msgstr "Deinstallieren"diff --git a/packages/locale/locales/en/erp.po b/packages/locale/locales/en/erp.poindex 013a78f4eb..e71340a97b 100644--- a/packages/locale/locales/en/erp.po+++ b/packages/locale/locales/en/erp.po@@ -433,6 +433,9 @@ msgstr "{unbatchedBatchableOperations} batchable operations are not in a batchmsgid "{uncounted, plural, one {# uncounted line} other {# uncounted lines}}"msgstr "{uncounted, plural, one {# uncounted line} other {# uncounted lines}}"+msgid "{unmappedRequiredCount, plural, one {Map the # remaining required account first.} other {Map the # remaining required accounts first.}}"+msgstr "{unmappedRequiredCount, plural, one {Map the # remaining required account first.} other {Map the # remaining required accounts first.}}"+msgid "{unschedulableCount} can't be scheduled"msgstr "{unschedulableCount} can't be scheduled"@@ -8805,6 +8808,9 @@ msgstr "Has operations that can't be scheduled"msgid "Headers"msgstr "Headers"+msgid "healthy"+msgstr "healthy"+msgid "Help"msgstr "Help"@@ -9238,6 +9244,9 @@ msgstr "In-app notifications are always delivered. Choose which topics also reacmsgid "In-app notifications are always delivered. Choose which topics also reach you by email."msgstr "In-app notifications are always delivered. Choose which topics also reach you by email."+msgid "inactive"+msgstr "inactive"+msgid "Inactive"msgstr "Inactive"@@ -12353,6 +12362,12 @@ msgstr "Nothing here matches your search and filters."msgid "Nothing in the archive"msgstr "Nothing in the archive"+msgid "Nothing is synced until you turn sync on."+msgstr "Nothing is synced until you turn sync on."++msgid "Nothing is synced until you turn sync on. Every required account is mapped."+msgstr "Nothing is synced until you turn sync on. Every required account is mapped."+msgid "Nothing scheduled — add a station below."msgstr "Nothing scheduled — add a station below."@@ -12414,6 +12429,9 @@ msgstr "of"msgid "of {0}h"msgstr "of {0}h"+msgid "Off"+msgstr "Off"+msgid "Off — handled outside the sync"msgstr "Off — handled outside the sync"@@ -12429,6 +12447,9 @@ msgstr "OK"msgid "Oldest first"msgstr "Oldest first"+msgid "On"+msgstr "On"+msgid "On cutover day, work the checklist below in order. Acceptance tests come from your in-scope requirements. Support details are at the bottom."msgstr "On cutover day, work the checklist below in order. Acceptance tests come from your in-scope requirements. Support details are at the bottom."@@ -12447,6 +12468,9 @@ msgstr "On hand"msgid "On Hand"msgstr "On Hand"+msgid "On hand {before} to {after}"+msgstr "On hand {before} to {after}"+msgid "On Hold"msgstr "On Hold"@@ -12602,6 +12626,9 @@ msgstr "Open"msgid "Open a change notice"msgstr "Open a change notice"+msgid "Open Account Mapping"+msgstr "Open Account Mapping"+msgid "Open Actions"msgstr "Open Actions"@@ -14703,6 +14730,9 @@ msgstr "Recorded that the gauge was adjusted during this calibration; affects homsgid "Records"msgstr "Records"+msgid "Records and posted journals are being sent to and received from this provider."+msgstr "Records and posted journals are being sent to and received from this provider."+msgid "Recovery Period"msgstr "Recovery Period"@@ -17804,6 +17834,9 @@ msgstr "Sync"msgid "Sync Activity"msgstr "Sync Activity"+msgid "sync off"+msgstr "sync off"+msgid "Sync operation"msgstr "Sync operation"@@ -19774,6 +19807,9 @@ msgstr "Undo"msgid "Ungroup"msgstr "Ungroup"+msgid "unhealthy"+msgstr "unhealthy"+msgid "Uninstall"msgstr "Uninstall"diff --git a/packages/locale/locales/es/erp.po b/packages/locale/locales/es/erp.poindex 770cd2b448..355e72f7de 100644--- a/packages/locale/locales/es/erp.po+++ b/packages/locale/locales/es/erp.po@@ -433,6 +433,9 @@ msgstr "{unbatchedBatchableOperations} operaciones agrupables no están en un lomsgid "{uncounted, plural, one {# uncounted line} other {# uncounted lines}}"msgstr "{uncounted, plural, one {# línea sin contar} other {# líneas sin contar}}"+msgid "{unmappedRequiredCount, plural, one {Map the # remaining required account first.} other {Map the # remaining required accounts first.}}"+msgstr ""+msgid "{unschedulableCount} can't be scheduled"msgstr "{unschedulableCount} no puede ser programado"@@ -8805,6 +8808,9 @@ msgstr "Tiene operaciones que no pueden ser programadas"msgid "Headers"msgstr "Encabezados"+msgid "healthy"+msgstr ""+msgid "Help"msgstr "Ayuda"@@ -9238,6 +9244,9 @@ msgstr "Las notificaciones en la aplicación siempre se entregan. Elija qué temmsgid "In-app notifications are always delivered. Choose which topics also reach you by email."msgstr "Las notificaciones en la aplicación siempre se entregan. Elija qué temas también le llegan por correo electrónico."+msgid "inactive"+msgstr ""+msgid "Inactive"msgstr "Inactivo"@@ -12353,6 +12362,12 @@ msgstr "Nada aquí coincide con tu búsqueda y filtros."msgid "Nothing in the archive"msgstr "Nada en el archivo"+msgid "Nothing is synced until you turn sync on."+msgstr ""++msgid "Nothing is synced until you turn sync on. Every required account is mapped."+msgstr ""+msgid "Nothing scheduled — add a station below."msgstr "Nada programado — agrega una estación a continuación."@@ -12414,6 +12429,9 @@ msgstr "de"msgid "of {0}h"msgstr "de {0}h"+msgid "Off"+msgstr ""+msgid "Off — handled outside the sync"msgstr "Off — manejado fuera de la sincronización"@@ -12429,6 +12447,9 @@ msgstr "Aceptar"msgid "Oldest first"msgstr "Más antiguo primero"+msgid "On"+msgstr ""+msgid "On cutover day, work the checklist below in order. Acceptance tests come from your in-scope requirements. Support details are at the bottom."msgstr "En el día de la migración, trabaja la lista de verificación a continuación en orden. Las pruebas de aceptación provienen de tus requisitos dentro del alcance. Los detalles de soporte están en la parte inferior."@@ -12447,6 +12468,9 @@ msgstr "En existencia"msgid "On Hand"msgstr "En Stock"+msgid "On hand {before} to {after}"+msgstr "En existencia: de {before} a {after}"+msgid "On Hold"msgstr "Suspendido"@@ -12602,6 +12626,9 @@ msgstr "Abrir"msgid "Open a change notice"msgstr "Abrir un aviso de cambio"+msgid "Open Account Mapping"+msgstr ""+msgid "Open Actions"msgstr "Acciones Abiertas"@@ -14703,6 +14730,9 @@ msgstr "Registrado que el instrumento de medición fue ajustado durante esta calmsgid "Records"msgstr "Registros"+msgid "Records and posted journals are being sent to and received from this provider."+msgstr ""+msgid "Recovery Period"msgstr "Registrar"@@ -17804,6 +17834,9 @@ msgstr "Sincronizar"msgid "Sync Activity"msgstr "Actividad de sincronización"+msgid "sync off"+msgstr ""+msgid "Sync operation"msgstr "Operación de sincronización"@@ -19774,6 +19807,9 @@ msgstr "Deshacer"msgid "Ungroup"msgstr ""+msgid "unhealthy"+msgstr ""+msgid "Uninstall"msgstr "Desinstalar"diff --git a/packages/locale/locales/fr/erp.po b/packages/locale/locales/fr/erp.poindex 8363e84502..6e68c79ce4 100644--- a/packages/locale/locales/fr/erp.po+++ b/packages/locale/locales/fr/erp.po@@ -433,6 +433,9 @@ msgstr "{unbatchedBatchableOperations} opérations pouvant être mises en lot nemsgid "{uncounted, plural, one {# uncounted line} other {# uncounted lines}}"msgstr "{uncounted, plural, one {# ligne non comptabilisée} other {# lignes non comptabilisées}}"+msgid "{unmappedRequiredCount, plural, one {Map the # remaining required account first.} other {Map the # remaining required accounts first.}}"+msgstr ""+msgid "{unschedulableCount} can't be scheduled"msgstr "{unschedulableCount} ne peuvent pas être planifiés"@@ -8805,6 +8808,9 @@ msgstr "Contient des opérations qui ne peuvent pas être planifiées"msgid "Headers"msgstr "En-têtes"+msgid "healthy"+msgstr ""+msgid "Help"msgstr "Aide"@@ -9238,6 +9244,9 @@ msgstr "Les notifications dans l'application sont toujours livrées. Choisissezmsgid "In-app notifications are always delivered. Choose which topics also reach you by email."msgstr "Les notifications dans l'application sont toujours livrées. Choisissez les sujets qui vous parviennent également par e-mail."+msgid "inactive"+msgstr ""+msgid "Inactive"msgstr "Inactif"@@ -12353,6 +12362,12 @@ msgstr "Rien ici ne correspond à votre recherche et vos filtres."msgid "Nothing in the archive"msgstr "Rien dans l'archive"+msgid "Nothing is synced until you turn sync on."+msgstr ""++msgid "Nothing is synced until you turn sync on. Every required account is mapped."+msgstr ""+msgid "Nothing scheduled — add a station below."msgstr "Rien de programmé — ajoutez une station ci-dessous."@@ -12414,6 +12429,9 @@ msgstr "de"msgid "of {0}h"msgstr "de {0}h"+msgid "Off"+msgstr ""+msgid "Off — handled outside the sync"msgstr "Off — géré en dehors de la synchronisation"@@ -12429,6 +12447,9 @@ msgstr "OK"msgid "Oldest first"msgstr "Le plus ancien en premier"+msgid "On"+msgstr ""+msgid "On cutover day, work the checklist below in order. Acceptance tests come from your in-scope requirements. Support details are at the bottom."msgstr "Le jour du basculement, travaillez la liste de contrôle ci-dessous dans l'ordre. Les tests d'acceptation proviennent de vos exigences dans le périmètre. Les détails du support se trouvent en bas."@@ -12447,6 +12468,9 @@ msgstr "En stock"msgid "On Hand"msgstr "En stock"+msgid "On hand {before} to {after}"+msgstr "En stock : de {before} à {after}"+msgid "On Hold"msgstr "Suspendu"@@ -12602,6 +12626,9 @@ msgstr "Ouvrir"msgid "Open a change notice"msgstr "Ouvrir un avis de modification"+msgid "Open Account Mapping"+msgstr ""+msgid "Open Actions"msgstr "Actions ouvertes"@@ -14703,6 +14730,9 @@ msgstr "Enregistré que l'instrument de mesure a été ajusté lors de cet étalmsgid "Records"msgstr "Enregistrements"+msgid "Records and posted journals are being sent to and received from this provider."+msgstr ""+msgid "Recovery Period"msgstr "Enregistrer"@@ -17804,6 +17834,9 @@ msgstr "Synchroniser"msgid "Sync Activity"msgstr "Activité de synchronisation"+msgid "sync off"+msgstr ""+msgid "Sync operation"msgstr "Opération de synchronisation"@@ -19774,6 +19807,9 @@ msgstr "Annuler"msgid "Ungroup"msgstr ""+msgid "unhealthy"+msgstr ""+msgid "Uninstall"msgstr "Désinstaller"diff --git a/packages/locale/locales/hi/erp.po b/packages/locale/locales/hi/erp.poindex bf3173e61a..6e13824c94 100644--- a/packages/locale/locales/hi/erp.po+++ b/packages/locale/locales/hi/erp.po@@ -433,6 +433,9 @@ msgstr "{unbatchedBatchableOperations} बैचेबल ऑपरेशन बmsgid "{uncounted, plural, one {# uncounted line} other {# uncounted lines}}"msgstr "{uncounted, plural, one {# अनगिनती लाइन} other {# अनगिनती लाइनें}}"+msgid "{unmappedRequiredCount, plural, one {Map the # remaining required account first.} other {Map the # remaining required accounts first.}}"+msgstr ""+msgid "{unschedulableCount} can't be scheduled"msgstr "{unschedulableCount} को शेड्यूल नहीं किया जा सकता"@@ -8805,6 +8808,9 @@ msgstr "ऐसे ऑपरेशन हैं जिन्हें शेडmsgid "Headers"msgstr "हेडर"+msgid "healthy"+msgstr ""+msgid "Help"msgstr "मदद"@@ -9238,6 +9244,9 @@ msgstr "इन-ऐप सूचनाएं हमेशा दी जातीmsgid "In-app notifications are always delivered. Choose which topics also reach you by email."msgstr "इन-ऐप सूचनाएं हमेशा दी जाती हैं। चुनें कि कौन से विषय आपको ईमेल द्वारा भी पहुंचें।"+msgid "inactive"+msgstr ""+msgid "Inactive"msgstr "निष्क्रिय"@@ -12353,6 +12362,12 @@ msgstr "यहां कुछ भी आपकी खोज और फ़िलmsgid "Nothing in the archive"msgstr "आर्काइव में कुछ नहीं है"+msgid "Nothing is synced until you turn sync on."+msgstr ""++msgid "Nothing is synced until you turn sync on. Every required account is mapped."+msgstr ""+msgid "Nothing scheduled — add a station below."msgstr "कुछ भी शेड्यूल नहीं किया गया — नीचे एक स्टेशन जोड़ें।"@@ -12414,6 +12429,9 @@ msgstr "का"msgid "of {0}h"msgstr "का {0}h"+msgid "Off"+msgstr ""+msgid "Off — handled outside the sync"msgstr "बंद — सिंक के बाहर संभाला गया"@@ -12429,6 +12447,9 @@ msgstr "ठीक है"msgid "Oldest first"msgstr "सबसे पुराना पहले"+msgid "On"+msgstr ""+msgid "On cutover day, work the checklist below in order. Acceptance tests come from your in-scope requirements. Support details are at the bottom."msgstr "कटओवर दिन पर, नीचे दी गई चेकलिस्ट को क्रम में काम करें। स्वीकृति परीक्षण आपकी स्कोप में शामिल आवश्यकताओं से आते हैं। समर्थन विवरण नीचे हैं।"@@ -12447,6 +12468,9 @@ msgstr "हाथ में"msgid "On Hand"msgstr "हाथ में"+msgid "On hand {before} to {after}"+msgstr "हाथ में: {before} से {after}"+msgid "On Hold"msgstr "होल्ड पर"@@ -12602,6 +12626,9 @@ msgstr "खोलें"msgid "Open a change notice"msgstr "एक परिवर्तन सूचना खोलें"+msgid "Open Account Mapping"+msgstr ""+msgid "Open Actions"msgstr "खुली कार्रवाइयाँ"@@ -14703,6 +14730,9 @@ msgstr "दर्ज किया गया कि इस अंशांकनmsgid "Records"msgstr "रिकॉर्ड"+msgid "Records and posted journals are being sent to and received from this provider."+msgstr ""+msgid "Recovery Period"msgstr "पंजीकृत करें"@@ -17804,6 +17834,9 @@ msgstr "सिंक करें"msgid "Sync Activity"msgstr "सिंक गतिविधि"+msgid "sync off"+msgstr ""+msgid "Sync operation"msgstr "सिंक संचालन"@@ -19774,6 +19807,9 @@ msgstr "पूर्ववत करें"msgid "Ungroup"msgstr ""+msgid "unhealthy"+msgstr ""+msgid "Uninstall"msgstr "अनइंस्टॉल करें"diff --git a/packages/locale/locales/it/erp.po b/packages/locale/locales/it/erp.poindex 7eac4c346b..0a329c1087 100644--- a/packages/locale/locales/it/erp.po+++ b/packages/locale/locales/it/erp.po@@ -433,6 +433,9 @@ msgstr "{unbatchedBatchableOperations} operazioni raggruppabili non sono in un lmsgid "{uncounted, plural, one {# uncounted line} other {# uncounted lines}}"msgstr "{uncounted, plural, one {# riga non conteggiata} other {# righe non conteggiate}}"+msgid "{unmappedRequiredCount, plural, one {Map the # remaining required account first.} other {Map the # remaining required accounts first.}}"+msgstr ""+msgid "{unschedulableCount} can't be scheduled"msgstr "{unschedulableCount} non può essere programmato"@@ -8805,6 +8808,9 @@ msgstr "Ha operazioni che non possono essere programmate"msgid "Headers"msgstr "Intestazioni"+msgid "healthy"+msgstr ""+msgid "Help"msgstr "Aiuto"@@ -9238,6 +9244,9 @@ msgstr "Le notifiche in-app vengono sempre consegnate. Scegli quali argomenti vumsgid "In-app notifications are always delivered. Choose which topics also reach you by email."msgstr "Le notifiche in-app vengono sempre consegnate. Scegli quali argomenti vuoi ricevere anche per e-mail."+msgid "inactive"+msgstr ""+msgid "Inactive"msgstr "Inattivo"@@ -12353,6 +12362,12 @@ msgstr "Niente qui corrisponde alla tua ricerca e ai tuoi filtri."msgid "Nothing in the archive"msgstr "Niente nell'archivio"+msgid "Nothing is synced until you turn sync on."+msgstr ""++msgid "Nothing is synced until you turn sync on. Every required account is mapped."+msgstr ""+msgid "Nothing scheduled — add a station below."msgstr "Niente programmato — aggiungi una stazione di seguito."@@ -12414,6 +12429,9 @@ msgstr "di"msgid "of {0}h"msgstr "di {0}h"+msgid "Off"+msgstr ""+msgid "Off — handled outside the sync"msgstr "Disattivato — gestito al di fuori della sincronizzazione"@@ -12429,6 +12447,9 @@ msgstr "OK"msgid "Oldest first"msgstr "Più vecchio prima"+msgid "On"+msgstr ""+msgid "On cutover day, work the checklist below in order. Acceptance tests come from your in-scope requirements. Support details are at the bottom."msgstr "Nel giorno del cutover, esegui la checklist sottostante in ordine. I test di accettazione provengono dai tuoi requisiti in ambito. I dettagli di supporto sono in fondo."@@ -12447,6 +12468,9 @@ msgstr "A portata di mano"msgid "On Hand"msgstr "In Magazzino"+msgid "On hand {before} to {after}"+msgstr "Giacenza: da {before} a {after}"+msgid "On Hold"msgstr "In Sospeso"@@ -12602,6 +12626,9 @@ msgstr "Apri"msgid "Open a change notice"msgstr "Apri un avviso di modifica"+msgid "Open Account Mapping"+msgstr ""+msgid "Open Actions"msgstr "Azioni Aperte"@@ -14703,6 +14730,9 @@ msgstr "Registrato che lo strumento di misura è stato regolato durante questa tmsgid "Records"msgstr "Registri"+msgid "Records and posted journals are being sent to and received from this provider."+msgstr ""+msgid "Recovery Period"msgstr "Registrare"@@ -17804,6 +17834,9 @@ msgstr "Sincronizza"msgid "Sync Activity"msgstr "Attività di sincronizzazione"+msgid "sync off"+msgstr ""+msgid "Sync operation"msgstr "Operazione di sincronizzazione"@@ -19774,6 +19807,9 @@ msgstr "Annulla"msgid "Ungroup"msgstr ""+msgid "unhealthy"+msgstr ""+msgid "Uninstall"msgstr "Disinstalla"diff --git a/packages/locale/locales/ja/erp.po b/packages/locale/locales/ja/erp.poindex bbada8cc97..ef09302147 100644--- a/packages/locale/locales/ja/erp.po+++ b/packages/locale/locales/ja/erp.po@@ -433,6 +433,9 @@ msgstr "{unbatchedBatchableOperations} バッチ対象の工程はバッチにmsgid "{uncounted, plural, one {# uncounted line} other {# uncounted lines}}"msgstr "{uncounted, plural, one {# 未計数行} other {# 未計数行}}"+msgid "{unmappedRequiredCount, plural, one {Map the # remaining required account first.} other {Map the # remaining required accounts first.}}"+msgstr ""+msgid "{unschedulableCount} can't be scheduled"msgstr "{unschedulableCount}はスケジュール化できません"@@ -8805,6 +8808,9 @@ msgstr "スケジュール化できない工程があります"msgid "Headers"msgstr "ヘッダー"+msgid "healthy"+msgstr ""+msgid "Help"msgstr "ヘルプ"@@ -9238,6 +9244,9 @@ msgstr "アプリ内通知は常に配信されます。どのトピックがメmsgid "In-app notifications are always delivered. Choose which topics also reach you by email."msgstr "アプリ内通知は常に配信されます。どのトピックがメールでも届くかを選択してください。"+msgid "inactive"+msgstr ""+msgid "Inactive"msgstr "無効"@@ -12353,6 +12362,12 @@ msgstr "検索と絞り込み条件に一致するものがありません"msgid "Nothing in the archive"msgstr "アーカイブに何もありません"+msgid "Nothing is synced until you turn sync on."+msgstr ""++msgid "Nothing is synced until you turn sync on. Every required account is mapped."+msgstr ""+msgid "Nothing scheduled — add a station below."msgstr "スケジュールがありません。以下にステーションを追加してください。"@@ -12414,6 +12429,9 @@ msgstr "の"msgid "of {0}h"msgstr "{0}h中"+msgid "Off"+msgstr ""+msgid "Off — handled outside the sync"msgstr "オフ — 同期外で処理"@@ -12429,6 +12447,9 @@ msgstr "OK"msgid "Oldest first"msgstr "最も古いものから"+msgid "On"+msgstr ""+msgid "On cutover day, work the checklist below in order. Acceptance tests come from your in-scope requirements. Support details are at the bottom."msgstr "カットオーバー日に、下のチェックリストを順番に作業してください。受け入れテストはあなたの対象要求事項から取得されます。サポートの詳細は下部にあります。"@@ -12447,6 +12468,9 @@ msgstr "手持在庫"msgid "On Hand"msgstr "手持在庫"+msgid "On hand {before} to {after}"+msgstr "手持在庫: {before} から {after}"+msgid "On Hold"msgstr "保留中"@@ -12602,6 +12626,9 @@ msgstr "開く"msgid "Open a change notice"msgstr "変更通知を開く"+msgid "Open Account Mapping"+msgstr ""+msgid "Open Actions"msgstr "オープンアクション"@@ -14703,6 +14730,9 @@ msgstr "この校正中に測定器が調整されたことを記録した。校msgid "Records"msgstr "記録"+msgid "Records and posted journals are being sent to and received from this provider."+msgstr ""+msgid "Recovery Period"msgstr "登録"@@ -17804,6 +17834,9 @@ msgstr "同期"msgid "Sync Activity"msgstr "同期アクティビティ"+msgid "sync off"+msgstr ""+msgid "Sync operation"msgstr "同期操作"@@ -19774,6 +19807,9 @@ msgstr "元に戻す"msgid "Ungroup"msgstr ""+msgid "unhealthy"+msgstr ""+msgid "Uninstall"msgstr "アンインストール"diff --git a/packages/locale/locales/ko/erp.po b/packages/locale/locales/ko/erp.poindex 6cd540d194..1fa37d909b 100644--- a/packages/locale/locales/ko/erp.po+++ b/packages/locale/locales/ko/erp.po@@ -433,6 +433,9 @@ msgstr "{unbatchedBatchableOperations}개 배치 가능한 공정은 배치에msgid "{uncounted, plural, one {# uncounted line} other {# uncounted lines}}"msgstr "미실사 라인 {uncounted}개"+msgid "{unmappedRequiredCount, plural, one {Map the # remaining required account first.} other {Map the # remaining required accounts first.}}"+msgstr ""+msgid "{unschedulableCount} can't be scheduled"msgstr "{unschedulableCount}개는 일정을 짤 수 없습니다"@@ -8805,6 +8808,9 @@ msgstr "일정을 짤 수 없는 공정이 있습니다"msgid "Headers"msgstr "헤더"+msgid "healthy"+msgstr ""+msgid "Help"msgstr "도움말"@@ -9238,6 +9244,9 @@ msgstr "인앱 알림은 항상 전달됩니다. 이메일 또는 Slack으로도msgid "In-app notifications are always delivered. Choose which topics also reach you by email."msgstr "인앱 알림은 항상 전달됩니다. 이메일로도 전달받을 주제를 선택하세요."+msgid "inactive"+msgstr ""+msgid "Inactive"msgstr "비활성"@@ -12353,6 +12362,12 @@ msgstr "검색 및 필터와 일치하는 항목이 없습니다."msgid "Nothing in the archive"msgstr "보관함이 비어 있습니다"+msgid "Nothing is synced until you turn sync on."+msgstr ""++msgid "Nothing is synced until you turn sync on. Every required account is mapped."+msgstr ""+msgid "Nothing scheduled — add a station below."msgstr "일정이 없습니다 — 아래에서 스테이션을 추가하세요."@@ -12414,6 +12429,9 @@ msgstr "중"msgid "of {0}h"msgstr "{0}h 중"+msgid "Off"+msgstr ""+msgid "Off — handled outside the sync"msgstr "끔 — 동기화 외부에서 처리됨"@@ -12429,6 +12447,9 @@ msgstr "확인"msgid "Oldest first"msgstr "오래된순"+msgid "On"+msgstr ""+msgid "On cutover day, work the checklist below in order. Acceptance tests come from your in-scope requirements. Support details are at the bottom."msgstr "전환일 당일에는 아래 체크리스트를 순서대로 진행하세요. 승인 테스트는 범위 내 요구사항을 기준으로 하며, 지원 관련 세부 정보는 하단에 있습니다."@@ -12447,6 +12468,9 @@ msgstr "보유수량"msgid "On Hand"msgstr "보유수량"+msgid "On hand {before} to {after}"+msgstr "보유수량: {before}에서 {after}(으)로"+msgid "On Hold"msgstr "보류"@@ -12602,6 +12626,9 @@ msgstr "열림"msgid "Open a change notice"msgstr "변경 통지 열기"+msgid "Open Account Mapping"+msgstr ""+msgid "Open Actions"msgstr "미결 조치"@@ -14703,6 +14730,9 @@ msgstr "이 교정 중에 계측기가 조정되었다고 기록되었습니다.msgid "Records"msgstr "레코드"+msgid "Records and posted journals are being sent to and received from this provider."+msgstr ""+msgid "Recovery Period"msgstr "회수 기간"@@ -17804,6 +17834,9 @@ msgstr "동기화"msgid "Sync Activity"msgstr "동기화 활동"+msgid "sync off"+msgstr ""+msgid "Sync operation"msgstr "동기화 작업"@@ -19774,6 +19807,9 @@ msgstr "실행 취소"msgid "Ungroup"msgstr ""+msgid "unhealthy"+msgstr ""+msgid "Uninstall"msgstr "제거"diff --git a/packages/locale/locales/pl/erp.po b/packages/locale/locales/pl/erp.poindex 8e37f30028..60eb88f45c 100644--- a/packages/locale/locales/pl/erp.po+++ b/packages/locale/locales/pl/erp.po@@ -433,6 +433,9 @@ msgstr "{unbatchedBatchableOperations} operacji możliwych do tworzenia partii nmsgid "{uncounted, plural, one {# uncounted line} other {# uncounted lines}}"msgstr "{uncounted, plural, one {# niepoliczony wiersz} other {# niepoliczone wiersze}}"+msgid "{unmappedRequiredCount, plural, one {Map the # remaining required account first.} other {Map the # remaining required accounts first.}}"+msgstr ""+msgid "{unschedulableCount} can't be scheduled"msgstr "Nie można zaplanować {unschedulableCount}"@@ -8805,6 +8808,9 @@ msgstr "Ma operacje, które nie można zaplanować"msgid "Headers"msgstr "Nagłówki"+msgid "healthy"+msgstr ""+msgid "Help"msgstr "Pomoc"@@ -9238,6 +9244,9 @@ msgstr "Powiadomienia w aplikacji są zawsze dostarczane. Wybierz, które tematymsgid "In-app notifications are always delivered. Choose which topics also reach you by email."msgstr "Powiadomienia w aplikacji są zawsze dostarczane. Wybierz, które tematy mają do Ciebie dotrzeć również pocztą e-mail."+msgid "inactive"+msgstr ""+msgid "Inactive"msgstr "Nieaktywny"@@ -12353,6 +12362,12 @@ msgstr "Nic tutaj nie odpowiada Twojemu wyszukiwaniu i filtrom."msgid "Nothing in the archive"msgstr "Nic w archiwum"+msgid "Nothing is synced until you turn sync on."+msgstr ""++msgid "Nothing is synced until you turn sync on. Every required account is mapped."+msgstr ""+msgid "Nothing scheduled — add a station below."msgstr "Nic nie zaplanowano — dodaj stanowisko poniżej."@@ -12414,6 +12429,9 @@ msgstr "z"msgid "of {0}h"msgstr "z {0}h"+msgid "Off"+msgstr ""+msgid "Off — handled outside the sync"msgstr "Wyłączone — obsługiwane poza synchronizacją"@@ -12429,6 +12447,9 @@ msgstr "OK"msgid "Oldest first"msgstr "Najstarsze najpierw"+msgid "On"+msgstr ""+msgid "On cutover day, work the checklist below in order. Acceptance tests come from your in-scope requirements. Support details are at the bottom."msgstr "W dniu przejścia pracuj nad listą kontrolną poniżej w kolejności. Testy akceptacyjne pochodzą z Twoich wymagań objętych zakresem. Szczegóły dotyczące wsparcia znajdują się na dole."@@ -12447,6 +12468,9 @@ msgstr "W magazynie"msgid "On Hand"msgstr "W magazynie"+msgid "On hand {before} to {after}"+msgstr "W magazynie: z {before} na {after}"+msgid "On Hold"msgstr "Wstrzymane"@@ -12602,6 +12626,9 @@ msgstr "Otwórz"msgid "Open a change notice"msgstr "Otwórz zawiadomienie o zmianie"+msgid "Open Account Mapping"+msgstr ""+msgid "Open Actions"msgstr "Otwarte Działania"@@ -14703,6 +14730,9 @@ msgstr "Zanotowano, że przyrząd pomiarowy został dostrojony podczas tego wzormsgid "Records"msgstr "Rekordy"+msgid "Records and posted journals are being sent to and received from this provider."+msgstr ""+msgid "Recovery Period"msgstr "Zarejestruj"@@ -17804,6 +17834,9 @@ msgstr "Synchronizuj"msgid "Sync Activity"msgstr "Działalność synchronizacji"+msgid "sync off"+msgstr ""+msgid "Sync operation"msgstr "Operacja synchronizacji"@@ -19774,6 +19807,9 @@ msgstr "Cofnij"msgid "Ungroup"msgstr ""+msgid "unhealthy"+msgstr ""+msgid "Uninstall"msgstr "Odinstaluj"diff --git a/packages/locale/locales/pt/erp.po b/packages/locale/locales/pt/erp.poindex 6c824510bc..e9989f946f 100644--- a/packages/locale/locales/pt/erp.po+++ b/packages/locale/locales/pt/erp.po@@ -433,6 +433,9 @@ msgstr "{unbatchedBatchableOperations} operações agrupáveis não estão em ummsgid "{uncounted, plural, one {# uncounted line} other {# uncounted lines}}"msgstr "{uncounted, plural, one {# linha não contada} other {# linhas não contadas}}"+msgid "{unmappedRequiredCount, plural, one {Map the # remaining required account first.} other {Map the # remaining required accounts first.}}"+msgstr ""+msgid "{unschedulableCount} can't be scheduled"msgstr "{unschedulableCount} não podem ser programadas"@@ -8805,6 +8808,9 @@ msgstr "Tem operações que não podem ser programadas"msgid "Headers"msgstr "Cabeçalhos"+msgid "healthy"+msgstr ""+msgid "Help"msgstr "Ajuda"@@ -9238,6 +9244,9 @@ msgstr "As notificações no aplicativo são sempre entregues. Escolha quais tómsgid "In-app notifications are always delivered. Choose which topics also reach you by email."msgstr "As notificações no aplicativo são sempre entregues. Escolha quais tópicos também chegarão a você por email."+msgid "inactive"+msgstr ""+msgid "Inactive"msgstr "Inativo"@@ -12353,6 +12362,12 @@ msgstr "Nada aqui corresponde à sua pesquisa e filtros."msgid "Nothing in the archive"msgstr "Nada no arquivo"+msgid "Nothing is synced until you turn sync on."+msgstr ""++msgid "Nothing is synced until you turn sync on. Every required account is mapped."+msgstr ""+msgid "Nothing scheduled — add a station below."msgstr "Nada agendado — adicione uma estação abaixo."@@ -12414,6 +12429,9 @@ msgstr "de"msgid "of {0}h"msgstr "de {0}h"+msgid "Off"+msgstr ""+msgid "Off — handled outside the sync"msgstr "Desativado — tratado fora da sincronização"@@ -12429,6 +12447,9 @@ msgstr "OK"msgid "Oldest first"msgstr "Mais antigos primeiro"+msgid "On"+msgstr ""+msgid "On cutover day, work the checklist below in order. Acceptance tests come from your in-scope requirements. Support details are at the bottom."msgstr "No dia de cutover, trabalhe a lista de verificação abaixo em ordem. Os testes de aceitação vêm dos seus requisitos no escopo. Os detalhes de suporte estão na parte inferior."@@ -12447,6 +12468,9 @@ msgstr "Em mão"msgid "On Hand"msgstr "Em Mãos"+msgid "On hand {before} to {after}"+msgstr "Em mão: de {before} para {after}"+msgid "On Hold"msgstr "Suspenso"@@ -12602,6 +12626,9 @@ msgstr "Abrir"msgid "Open a change notice"msgstr "Abrir um aviso de alteração"+msgid "Open Account Mapping"+msgstr ""+msgid "Open Actions"msgstr "Ações Abertas"@@ -14703,6 +14730,9 @@ msgstr "Registrado que o instrumento de medição foi ajustado durante esta calimsgid "Records"msgstr "Registros"+msgid "Records and posted journals are being sent to and received from this provider."+msgstr ""+msgid "Recovery Period"msgstr "Registrar"@@ -17804,6 +17834,9 @@ msgstr "Sincronizar"msgid "Sync Activity"msgstr "Atividade de sincronização"+msgid "sync off"+msgstr ""+msgid "Sync operation"msgstr "Operação de sincronização"@@ -19774,6 +19807,9 @@ msgstr "Desfazer"msgid "Ungroup"msgstr ""+msgid "unhealthy"+msgstr ""+msgid "Uninstall"msgstr "Desinstalar"diff --git a/packages/locale/locales/ru/erp.po b/packages/locale/locales/ru/erp.poindex b42efe9a84..9e16b3eaac 100644--- a/packages/locale/locales/ru/erp.po+++ b/packages/locale/locales/ru/erp.po@@ -433,6 +433,9 @@ msgstr "{unbatchedBatchableOperations} группируемые операцииmsgid "{uncounted, plural, one {# uncounted line} other {# uncounted lines}}"msgstr "{uncounted, plural, one {# непосчитанная строка} other {# непосчитанные строки}}"+msgid "{unmappedRequiredCount, plural, one {Map the # remaining required account first.} other {Map the # remaining required accounts first.}}"+msgstr ""+msgid "{unschedulableCount} can't be scheduled"msgstr "{unschedulableCount} не может быть спланировано"@@ -8805,6 +8808,9 @@ msgstr "Имеет операции, которые не могут быть сmsgid "Headers"msgstr "Заголовки"+msgid "healthy"+msgstr ""+msgid "Help"msgstr "Справка"@@ -9238,6 +9244,9 @@ msgstr "Уведомления в приложении всегда доставmsgid "In-app notifications are always delivered. Choose which topics also reach you by email."msgstr "Уведомления в приложении всегда доставляются. Выберите, какие темы также будут доходить до вас по электронной почте."+msgid "inactive"+msgstr ""+msgid "Inactive"msgstr "Неактивно"@@ -12353,6 +12362,12 @@ msgstr "Здесь нет ничего, соответствующего вашmsgid "Nothing in the archive"msgstr "Ничего в архиве"+msgid "Nothing is synced until you turn sync on."+msgstr ""++msgid "Nothing is synced until you turn sync on. Every required account is mapped."+msgstr ""+msgid "Nothing scheduled — add a station below."msgstr "Ничего не запланировано — добавьте рабочее место ниже."@@ -12414,6 +12429,9 @@ msgstr "из"msgid "of {0}h"msgstr "из {0}ч"+msgid "Off"+msgstr ""+msgid "Off — handled outside the sync"msgstr "Отключено — обработано вне синхронизации"@@ -12429,6 +12447,9 @@ msgstr "ОК"msgid "Oldest first"msgstr "Сначала самые старые"+msgid "On"+msgstr ""+msgid "On cutover day, work the checklist below in order. Acceptance tests come from your in-scope requirements. Support details are at the bottom."msgstr "В день переключения выполняйте контрольный список ниже по порядку. Тесты приемки основаны на ваших требованиях в области действия. Детали поддержки находятся внизу."@@ -12447,6 +12468,9 @@ msgstr "На складе"msgid "On Hand"msgstr "На складе"+msgid "On hand {before} to {after}"+msgstr "На складе: с {before} до {after}"+msgid "On Hold"msgstr "Приостановлено"@@ -12602,6 +12626,9 @@ msgstr "Открыть"msgid "Open a change notice"msgstr "Открыть Извещение об изменении"+msgid "Open Account Mapping"+msgstr ""+msgid "Open Actions"msgstr "Открытые действия"@@ -14703,6 +14730,9 @@ msgstr "Зафиксировано, что средство измеренияmsgid "Records"msgstr "Записи"+msgid "Records and posted journals are being sent to and received from this provider."+msgstr ""+msgid "Recovery Period"msgstr "Зарегистрировать"@@ -17804,6 +17834,9 @@ msgstr "Синхронизация"msgid "Sync Activity"msgstr "Активность синхронизации"+msgid "sync off"+msgstr ""+msgid "Sync operation"msgstr "Операция синхронизации"@@ -19774,6 +19807,9 @@ msgstr "Отменить"msgid "Ungroup"msgstr ""+msgid "unhealthy"+msgstr ""+msgid "Uninstall"msgstr "Удалить"diff --git a/packages/locale/locales/tr/erp.po b/packages/locale/locales/tr/erp.poindex 9b82f7eaa2..af42b1fd9c 100644--- a/packages/locale/locales/tr/erp.po+++ b/packages/locale/locales/tr/erp.po@@ -433,6 +433,9 @@ msgstr "{unbatchedBatchableOperations} partiye alınabilir operasyon partide demsgid "{uncounted, plural, one {# uncounted line} other {# uncounted lines}}"msgstr "{uncounted, plural, one {# sayılmamış satır} other {# sayılmamış satırlar}}"+msgid "{unmappedRequiredCount, plural, one {Map the # remaining required account first.} other {Map the # remaining required accounts first.}}"+msgstr ""+msgid "{unschedulableCount} can't be scheduled"msgstr "{unschedulableCount} planlanmıyor"@@ -8805,6 +8808,9 @@ msgstr "Planlanmayan operasyonları var"msgid "Headers"msgstr "Başlıklar"+msgid "healthy"+msgstr ""+msgid "Help"msgstr "Yardım"@@ -9238,6 +9244,9 @@ msgstr "Uygulama içi bildirimler her zaman iletilir. Hangi konuların e-posta vmsgid "In-app notifications are always delivered. Choose which topics also reach you by email."msgstr "Uygulama içi bildirimler her zaman iletilir. Hangi konuların e-posta aracılığıyla sizi ulaştıracağını seçin."+msgid "inactive"+msgstr ""+msgid "Inactive"msgstr "Pasif"@@ -12353,6 +12362,12 @@ msgstr "Burada arama ve filtrelerinizle eşleşen hiçbir şey yok."msgid "Nothing in the archive"msgstr "Arşivde hiçbir şey yok"+msgid "Nothing is synced until you turn sync on."+msgstr ""++msgid "Nothing is synced until you turn sync on. Every required account is mapped."+msgstr ""+msgid "Nothing scheduled — add a station below."msgstr "Hiçbir şey zamanlanmadı — aşağıya bir istasyon ekleyin."@@ -12414,6 +12429,9 @@ msgstr "adet"msgid "of {0}h"msgstr "başında {0}s"+msgid "Off"+msgstr ""+msgid "Off — handled outside the sync"msgstr "Kapalı — senkronizasyon dışında işlenir"@@ -12429,6 +12447,9 @@ msgstr "Tamam"msgid "Oldest first"msgstr "En eski önce"+msgid "On"+msgstr ""+msgid "On cutover day, work the checklist below in order. Acceptance tests come from your in-scope requirements. Support details are at the bottom."msgstr "Geçiş gününde, aşağıdaki kontrol listesini sırayla çalışın. Kabul testleri kapsam içi gerekliliklerinizden gelir. Destek ayrıntıları altta yer alır."@@ -12447,6 +12468,9 @@ msgstr "Eldeki"msgid "On Hand"msgstr "Stokta"+msgid "On hand {before} to {after}"+msgstr "Eldeki: {before} değerinden {after} değerine"+msgid "On Hold"msgstr "Askıda"@@ -12602,6 +12626,9 @@ msgstr "Aç"msgid "Open a change notice"msgstr "Bir değişiklik bildirisi aç"+msgid "Open Account Mapping"+msgstr ""+msgid "Open Actions"msgstr "Açık Aksiyonlar"@@ -14703,6 +14730,9 @@ msgstr "Bu kalibrasyon sırasında ölçüm aletinin ayarlandığı kaydedildi;msgid "Records"msgstr "Kayıtlar"+msgid "Records and posted journals are being sent to and received from this provider."+msgstr ""+msgid "Recovery Period"msgstr "Kayıt Yap"@@ -17804,6 +17834,9 @@ msgstr "Senkronize Et"msgid "Sync Activity"msgstr "Senkronizasyon Etkinliği"+msgid "sync off"+msgstr ""+msgid "Sync operation"msgstr "Senkronizasyon işlemi"@@ -19774,6 +19807,9 @@ msgstr "Geri Al"msgid "Ungroup"msgstr ""+msgid "unhealthy"+msgstr ""+msgid "Uninstall"msgstr "Kaldır"diff --git a/packages/locale/locales/zh/erp.po b/packages/locale/locales/zh/erp.poindex 5b5c3e4314..5d69bcd49f 100644--- a/packages/locale/locales/zh/erp.po+++ b/packages/locale/locales/zh/erp.po@@ -433,6 +433,9 @@ msgstr "{unbatchedBatchableOperations} 个可分组的工序不在生产批次msgid "{uncounted, plural, one {# uncounted line} other {# uncounted lines}}"msgstr "{uncounted, plural, one {# 未计数行} other {# 未计数行}}"+msgid "{unmappedRequiredCount, plural, one {Map the # remaining required account first.} other {Map the # remaining required accounts first.}}"+msgstr ""+msgid "{unschedulableCount} can't be scheduled"msgstr "{unschedulableCount}无法排程"@@ -8805,6 +8808,9 @@ msgstr "有无法排程的工序"msgid "Headers"msgstr "标头"+msgid "healthy"+msgstr ""+msgid "Help"msgstr "帮助"@@ -9238,6 +9244,9 @@ msgstr "应用内通知始终会被传递。选择哪些主题也通过电子邮msgid "In-app notifications are always delivered. Choose which topics also reach you by email."msgstr "应用内通知始终会被传递。选择哪些主题也通过电子邮件发送给您。"+msgid "inactive"+msgstr ""+msgid "Inactive"msgstr "已停用"@@ -12353,6 +12362,12 @@ msgstr "没有与您的搜索和过滤条件匹配的内容。"msgid "Nothing in the archive"msgstr "存档中没有任何内容"+msgid "Nothing is synced until you turn sync on."+msgstr ""++msgid "Nothing is synced until you turn sync on. Every required account is mapped."+msgstr ""+msgid "Nothing scheduled — add a station below."msgstr "未安排任何事项——在下方添加工位。"@@ -12414,6 +12429,9 @@ msgstr "的"msgid "of {0}h"msgstr "共 {0}h"+msgid "Off"+msgstr ""+msgid "Off — handled outside the sync"msgstr "关闭 — 在同步外处理"@@ -12429,6 +12447,9 @@ msgstr "确定"msgid "Oldest first"msgstr "最早优先"+msgid "On"+msgstr ""+msgid "On cutover day, work the checklist below in order. Acceptance tests come from your in-scope requirements. Support details are at the bottom."msgstr "在转换日,按顺序完成下列检查清单。验收测试来自您范围内的要求。支持详情见下方。"@@ -12447,6 +12468,9 @@ msgstr "现有"msgid "On Hand"msgstr "现有"+msgid "On hand {before} to {after}"+msgstr "现有:从 {before} 到 {after}"+msgid "On Hold"msgstr "搁置"@@ -12602,6 +12626,9 @@ msgstr "未结"msgid "Open a change notice"msgstr "打开变更通知"+msgid "Open Account Mapping"+msgstr ""+msgid "Open Actions"msgstr "未结操作"@@ -14703,6 +14730,9 @@ msgstr "记录在此校准期间调整了量具;影响校准周期的重新计msgid "Records"msgstr "记录"+msgid "Records and posted journals are being sent to and received from this provider."+msgstr ""+msgid "Recovery Period"msgstr "注册"@@ -17804,6 +17834,9 @@ msgstr "同步"msgid "Sync Activity"msgstr "同步活动"+msgid "sync off"+msgstr ""+msgid "Sync operation"msgstr "同步操作"@@ -19774,6 +19807,9 @@ msgstr "撤销"msgid "Ungroup"msgstr ""+msgid "unhealthy"+msgstr ""+msgid "Uninstall"msgstr "卸载"