Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
feat(accounting): opening balances tool on chart of accounts (#1559)
Brad Barbin3fd09186b381
diff --git a/.ai/plans/2026-09-01-opening-balances.md b/.ai/plans/2026-09-01-opening-balances.mdnew file mode 100644index 0000000000..ee3386ef96--- /dev/null+++ b/.ai/plans/2026-09-01-opening-balances.md@@ -0,0 +1,590 @@+# Opening Balances tool — implementation plan++**Spec:** none — design confirmed with user in-conversation (2026-09-01); captured here.+**Run record:** .ai/runs/2026-09-01-opening-balances.md+**Branch:** mbabane++## Design summary++> **Implementation note (superseded entry point):** the standalone+> `/x/accounting/opening-balances` screen below was the original design. It was+> replaced during implementation by an **inline mode on the Chart of Accounts+> page** — the `charts.tsx` loader/action, a toolbar button that toggles+> `openingBalanceMode` in `ChartOfAccountsTree`, and `OpeningBalancePostModal`+> for the as-of date. The authoritative route/action/guard contract is the one+> described in `apps/erp/app/modules/accounting/AGENTS.md`. The service layer+> (`createOpeningBalanceJournal` / `getExistingOpeningBalanceEntry`) is unchanged+> from this plan; only the UI entry point moved.++New screen at **Accounting → General Ledger → Opening Balances**+(`/x/accounting/opening-balances`). The user sets the initial GL balance for each+posting (leaf) account as of a cutover posting date. On save, the tool posts **one+balanced journal entry** with a new `journalEntrySourceType` value `'Opening+Balance'`, auto-plugging the net difference to the company's **Retained Earnings**+default account so total debits = total credits.++Reuses the existing posting stack — no new edge function:+`getNextSequence("journalEntry")` → `createJournalEntry({ sourceType: 'Opening+Balance' })` → `saveJournalEntryWithLines({ lines })` → `postJournalEntry`.+`saveJournalEntryWithLines` already looks up each account's `class` and encodes the+stored amount via `toStoredAmount(debit, credit, class)`; `postJournalEntry`+already validates debit=credit and resolves the accounting period via+`getOrCreateAccountingPeriod`. So the service layer only has to compute the+Retained-Earnings plug and drive those three calls.++**Guard:** if a *posted, not-yet-reversed* `'Opening Balance'` entry already+exists for the company, the screen shows a banner linking to it and refuses a new+one (opening balances are entered once; changing them means reversing the existing+entry first). The form is pre-filled from that entry when it exists so the user can+see what was entered.++**Currency:** base currency only (matches the journal editor).++## Progress+- [x] Task 1: Migration — add `'Opening Balance'` to `journalEntrySourceType` (20260901165008; enum verified in DB)+- [x] Task 2: Regenerate DB types (2 hits in types.ts)+- [x] Task 3: Models — source-type array + `openingBalanceValidator`+- [x] Task 4: Service — `createOpeningBalanceJournal` + `getExistingOpeningBalanceEntry`+- [x] Task 5: `path.ts` + nav entry (LuWallet under General Ledger)+- [x] Task 6: Route loader/action `opening-balances.tsx`+- [x] Task 7: UI `OpeningBalancesForm.tsx` (+ ui barrel index)+- [x] Task 8: i18n extract + scoped typecheck (erp+ee) + lint — all green+- [ ] Task 9: Browser verification via /test (runs after /ui polish)++## Forced change (not in original task list)+- `packages/ee/src/accounting/core/models.ts` POSTING_POLICY is an exhaustive+ `Record<journalEntrySourceType, ...>`; adding the enum value forced an entry.+ Added `'Opening Balance'` mirroring `Manual` (`syncable: false`) — opening+ balances are a setup artifact the external ledger owns; syncing would+ double-count. Correct + type-forced, so applied in place.++## Dependencies+- Task 2 needs Task 1. Task 3 needs Task 2 (generated enum type). Task 4 needs Task 3.+ Task 6 needs Tasks 4–5. Task 7 needs Task 6. Tasks 5 is independent of 3–4 (can run+ alongside). Task 8 after 3–7. Task 9 last.++---++## Task 1: Migration — add `'Opening Balance'` to `journalEntrySourceType`++**Depends on:** none+**Files:**+- Create: `packages/database/supabase/migrations/{generated}_opening-balance-source-type.sql`+- Copy from (precedent): `packages/database/supabase/migrations/20260726013204_add_nonconformance_journal_doctypes.sql`++**Steps:**+1. Create the file with `pnpm db:migrate:new opening-balance-source-type` (it+ picks the timestamp — do NOT hand-write it, never `000000` HHMMSS).+2. Body — a single idempotent enum addition:+ ```sql+ -- Opening Balances tool posts a manual-style GL entry tagged with this source+ -- type. ADD VALUE only; no column/usage change. Idempotent for the retrying+ -- deploy runner. Postgres disallows ALTER TYPE ... ADD VALUE inside a txn with+ -- later use of the value, but this migration only adds it, so it is fine.+ ALTER TYPE "journalEntrySourceType" ADD VALUE IF NOT EXISTS 'Opening Balance';+ ```+3. Apply it: `pnpm db:migrate`.++**Verify:**+```bash+grep -c "ADD VALUE IF NOT EXISTS 'Opening Balance'" packages/database/supabase/migrations/*_opening-balance-source-type.sql+# Expected: 1 (match the exact ALTER TYPE statement — a bare "Opening Balance"+# substring also matches the descriptive comment and would report 2).+```+Also confirm the enum applied:+```bash+# after pnpm db:migrate — no error output means success+echo "migration applied"+```++**Out of scope:** Do not touch the base enum definition in+`20260402000000_journal-entries.sql` (never edit an applied migration). Do not add+any new table or column.++---++## Task 2: Regenerate DB types++**Depends on:** Task 1+**Files:**+- Modify (generated): `packages/database/src/types.ts` (and any re-exported enum types)++**Steps:**+1. Run `pnpm run generate:types`. This must run against the migrated local DB, so+ `pnpm db:migrate` (Task 1 step 3) must have succeeded first.+2. Do not hand-edit the output.++**Verify:**+```bash+grep -c "Opening Balance" packages/database/src/types.ts+# Expected: >= 1 (the enum union now includes it)+```+If the count is 0, STOP — the migration didn't apply to the DB the generator reads.++**Out of scope:** manual edits to generated types.++---++## Task 3: Models — source-type array + `openingBalanceValidator`++**Depends on:** Task 2+**Files:**+- Modify: `apps/erp/app/modules/accounting/accounting.models.ts` — add enum-array value + new validator+- Copy from (precedent): the existing `journalEntryValidator` (same file, ~line 330 region) and `journalEntrySourceTypes` array (~line 681)++**Steps:**+1. In the `journalEntrySourceTypes` array (starts ~line 681), add `"Opening+ Balance"` as a new entry. Place it after `"Manual"` (keep it near the top; the+ array is not alphabetized). This array is the UI-facing source-type list.+2. Add a new validator near the other journal validators:+ ```typescript+ export const openingBalanceValidator = z.object({+ postingDate: z.string().min(1, { message: "Posting date is required" }),+ // JSON-encoded array of { accountId, amount } produced by the form's hidden+ // input. amount is the signed base-currency figure the user typed against the+ // account, positive = the account's natural balance side (debit for+ // Asset/Expense, credit for Liability/Equity/Revenue). The service converts+ // amount → {debit, credit} per class before posting.+ lines: z+ .string()+ .min(1, { message: "At least one balance is required" })+ .transform((val, ctx) => {+ try {+ const parsed = JSON.parse(val) as Array<{+ accountId: string;+ amount: number;+ }>;+ return parsed.filter(+ (l) => l.accountId && typeof l.amount === "number" && l.amount !== 0+ );+ } catch {+ ctx.addIssue({ code: z.ZodIssueCode.custom, message: "Invalid lines" });+ return z.NEVER;+ }+ })+ });+ ```+ Note: the form sends one signed `amount` per account (natural-balance sign), NOT+ separate debit/credit columns — the debit/credit split is derived from account+ class in the service. Zero-amount rows are dropped.++**Verify:**+```bash+pnpm exec turbo run typecheck --filter=@carbon/erp 2>&1 | tail -20+# Expected: no type errors referencing accounting.models.ts+```++**Out of scope:** do not change `journalEntryValidator`.++---++## Task 4: Service — `createOpeningBalanceJournal` + `getExistingOpeningBalanceEntry`++**Depends on:** Task 3+**Files:**+- Modify: `apps/erp/app/modules/accounting/accounting.ee.service.ts` — two new exported functions+- Copy from (precedent): `createJournalEntry` (~4795), `saveJournalEntryWithLines`+ (~4904), `postJournalEntry` (~5015), `getDefaultAccounts` (~3538) in the same file++**Steps:**+1. Confirm imports already present at top of file: `getNextSequence` (from+ `~/modules/settings`, already imported ~line 20), `toStoredAmount`,+ `toDisplayDebit`, `toDisplayCredit` (from `@carbon/utils`). Add whichever of the+ `toDisplay*` are missing to the existing `@carbon/utils` import.+2. Add `getExistingOpeningBalanceEntry`:+ ```typescript+ // Returns the company's current posted Opening Balance journal entry (with its+ // lines decoded to per-account debit/credit) or null. "Reversed" entries do NOT+ // count — after a reversal the user may enter a fresh set. Only status='Posted'+ // with sourceType='Opening Balance' blocks a new one.+ export async function getExistingOpeningBalanceEntry(+ client: SupabaseClient<Database>,+ companyId: string+ ) {+ const entry = await client+ .from("journal")+ .select(+ "id, journalEntryId, postingDate, status, journalLine(accountId, amount, account(id, class, number, name))"+ )+ .eq("companyId", companyId)+ .eq("sourceType", "Opening Balance")+ .eq("status", "Posted")+ .order("createdAt", { ascending: false })+ .limit(1)+ .maybeSingle();++ if (entry.error) return { data: null, error: entry.error };+ if (!entry.data) return { data: null, error: null };++ const lines = (entry.data.journalLine ?? [])+ .filter((l) => l.account) // skip the retained-earnings plug? no — keep all+ .map((l) => {+ const cls = (l.account as { class: AccountClass }).class;+ return {+ accountId: l.accountId as string,+ debit: toDisplayDebit(l.amount as number, cls),+ credit: toDisplayCredit(l.amount as number, cls)+ };+ });++ return {+ data: {+ id: entry.data.id,+ journalEntryId: entry.data.journalEntryId,+ postingDate: entry.data.postingDate,+ lines+ },+ error: null+ };+ }+ ```+ Use the `AccountClass` type already used in the file (or+ `Database["public"]["Enums"]["glAccountClass"]`). If the embed shape fights the+ generated types, cast the row locally rather than changing the query shape.+3. Add `createOpeningBalanceJournal`:+ ```typescript+ export async function createOpeningBalanceJournal(+ client: SupabaseClient<Database>,+ args: {+ companyId: string;+ companyGroupId: string;+ userId: string;+ postingDate: string;+ // one signed natural-balance amount per account (from the form)+ balances: Array<{ accountId: string; amount: number }>;+ }+ ) {+ const { companyId, companyGroupId, userId, postingDate, balances } = args;++ const entered = balances.filter((b) => b.amount !== 0);+ if (entered.length === 0) {+ return { data: null, error: { message: "No opening balances entered" } };+ }++ // Resolve Retained Earnings (the balancing plug).+ const defaults = await getDefaultAccounts(client, companyId);+ if (defaults.error) return { data: null, error: defaults.error };+ const retainedEarningsAccount = defaults.data?.retainedEarningsAccount;+ if (!retainedEarningsAccount) {+ return {+ data: null,+ error: {+ message:+ "No Retained Earnings account is configured in Default Accounts"+ }+ };+ }++ // Look up account classes so we can split the natural-balance amount into+ // debit/credit. (saveJournalEntryWithLines re-derives the stored amount from+ // debit/credit, so we must hand it debit/credit, not the signed amount.)+ const accountIds = [...new Set(entered.map((b) => b.accountId))];+ const accounts = await client+ .from("account")+ .select("id, class")+ .in("id", accountIds);+ if (accounts.error) return { data: null, error: accounts.error };+ const classById = new Map(+ accounts.data.map((a) => [a.id, a.class as AccountClass])+ );++ // Build debit/credit lines. A positive natural-balance amount posts to the+ // account's natural side: debit for Asset/Expense, credit for+ // Liability/Equity/Revenue. Negative flips it.+ const naturalDebit = (cls: AccountClass) =>+ cls === "Asset" || cls === "Expense";+ let netDebitMinusCredit = 0; // in signed "debit positive" space+ const lines: Array<{ accountId: string; debit: number; credit: number }> = [];+ for (const b of entered) {+ const cls = classById.get(b.accountId);+ if (!cls) {+ return {+ data: null,+ error: { message: `Account not found: ${b.accountId}` }+ };+ }+ const isDebit = naturalDebit(cls) ? b.amount >= 0 : b.amount < 0;+ const magnitude = Math.abs(b.amount);+ const debit = isDebit ? magnitude : 0;+ const credit = isDebit ? 0 : magnitude;+ netDebitMinusCredit += debit - credit;+ lines.push({ accountId: b.accountId, debit, credit });+ }++ // Balancing plug to Retained Earnings. If entered lines net to more debit,+ // the plug is a credit, and vice-versa. Use equals() tolerance so a zero plug+ // is dropped.+ if (!equals(netDebitMinusCredit, 0)) {+ const plug = netDebitMinusCredit; // debit-positive+ lines.push({+ accountId: retainedEarningsAccount,+ debit: plug < 0 ? -plug : 0,+ credit: plug > 0 ? plug : 0+ });+ }++ // Allocate readable id + create the Draft header with the new source type.+ const journalEntryId = await getNextSequence(client, "journalEntry", companyId);+ if (journalEntryId.error || !journalEntryId.data) {+ return {+ data: null,+ error: journalEntryId.error ?? { message: "Failed to allocate sequence" }+ };+ }++ const created = await createJournalEntry(client, {+ journalEntryId: journalEntryId.data as string,+ sourceType: "Opening Balance",+ companyId,+ createdBy: userId,+ postingDate,+ description: "Opening balances"+ });+ if (created.error || !created.data) {+ return { data: null, error: created.error ?? { message: "Create failed" } };+ }+ const id = created.data.id;++ const saved = await saveJournalEntryWithLines(client, {+ journalEntryId: id,+ postingDate,+ description: "Opening balances",+ updatedBy: userId,+ lines,+ companyId,+ companyGroupId+ });+ if (saved.error) return { data: null, error: saved.error };++ const posted = await postJournalEntry(client, id, userId);+ if (posted.error) return { data: null, error: posted.error };++ return { data: { id }, error: null };+ }+ ```+4. Import `equals` from `@carbon/utils` if not already imported (it's the float+ tolerance helper from precision). If `equals` is not exported there, use+ `Math.abs(netDebitMinusCredit) > EPSILON` with `EPSILON` from `@carbon/utils`,+ or a local `1e-6`. Prefer the shared helper — check the import first.+ If neither `equals` nor `EPSILON` is exported from `@carbon/utils`, STOP and+ report rather than inventing a literal (numeric-precision rule bans stray+ scale/tolerance literals).++**Verify:**+```bash+pnpm exec turbo run typecheck --filter=@carbon/erp 2>&1 | tail -20+# Expected: no type errors in accounting.ee.service.ts+```++**Out of scope:** do not modify `createJournalEntry`, `saveJournalEntryWithLines`,+or `postJournalEntry`. Do not add a Kysely client (service files are browser-bundled+— use only the passed `client`).++---++## Task 5: `path.ts` + nav entry++**Depends on:** none+**Files:**+- Modify: `apps/erp/app/utils/path.ts` — add `accountingOpeningBalances`+- Modify: `apps/erp/app/modules/accounting/ui/useAccountingSubmodules.tsx` — nav item+- Copy from (precedent): the `accountingJournals` path entry (~line 28) and the+ "Journal Entries" nav route (~line 60)++**Steps:**+1. In `path.ts`, next to `accountingJournals: \`${x}/accounting/journals\`,` add:+ ```typescript+ accountingOpeningBalances: `${x}/accounting/opening-balances`,+ ```+2. In `useAccountingSubmodules.tsx`, add a route object inside the **General+ Ledger** group's `routes` array (after "Journal Entries"):+ ```tsx+ {+ name: t`Opening Balances`,+ to: path.to.accountingOpeningBalances,+ role: "employee",+ icon: <LuWallet />+ }+ ```+ Add `LuWallet` to the `react-icons/lu` import at the top of the file (keep the+ import list alphabetized as it currently is).++**Verify:**+```bash+grep -n "accountingOpeningBalances" apps/erp/app/utils/path.ts+grep -n "Opening Balances" apps/erp/app/modules/accounting/ui/useAccountingSubmodules.tsx+# Expected: one hit each+```++**Out of scope:** do not reorder other nav groups.++---++## Task 6: Route loader/action `opening-balances.tsx`++**Depends on:** Tasks 4, 5+**Files:**+- Create: `apps/erp/app/routes/x+/accounting+/opening-balances.tsx`+- Copy from (precedent): `apps/erp/app/routes/x+/accounting+/journals.new.tsx`+ (action shape, service-role invoke pattern) and any accounting list route with a+ loader that reads `getChartOfAccounts` (e.g. `charts.tsx`) for the loader shape,+ and `payment-terms.$paymentTermId.tsx` for the validate→service→flash pattern++**Steps:**+1. **Loader** — `requirePermissions(request, { view: "accounting" })` →+ `{ client, companyId, companyGroupId }`. Also read the base currency+ (`getCompany`/user company base currency — use the same source the journal editor+ uses: `useUser().company.baseCurrencyCode` is client-side; for the loader, read+ the company's `baseCurrencyCode` however neighboring accounting loaders do — if+ unclear, pass nothing and let the form read `useUser()`).+ - `getChartOfAccounts(client, companyGroupId, { incomeBalance: null, startDate:+ null, endDate: null })`, then filter to **posting leaf accounts**: `a.isGroup+ === false && a.class` present. Sort by `number`.+ - `getExistingOpeningBalanceEntry(client, companyId)`.+ - Return a plain object `{ accounts, existingEntry }` (NO `Response.json` /+ `json()` — return the object directly).+2. **Action** — `assertIsPost(request)`; `requirePermissions(request, { create:+ "accounting" })` → `{ client, companyId, companyGroupId, userId }`.+ - `validator(openingBalanceValidator).validate(formData)`; on error+ `return validationError(validation.error)`.+ - Re-check the guard server-side: `getExistingOpeningBalanceEntry`; if one+ exists, `return data({}, await flash(request, error(null, "An opening balance+ entry already exists — reverse it before entering new balances")))`.+ - Map validated `lines` (`{accountId, amount}[]`) →+ `createOpeningBalanceJournal(client, { companyId, companyGroupId, userId,+ postingDate, balances: lines })`.+ - On error → `return data({}, await flash(request, error(result.error, "Failed+ to post opening balances")))`.+ - On success → `throw redirect(path.to.journalEntry(result.data.id), await+ flash(request, success("Opening balances posted")))`.+3. **Default export** — render `<OpeningBalancesForm accounts={accounts}+ existingEntry={existingEntry} />` from loader data via `useLoaderData`.++**Verify:**+```bash+pnpm exec turbo run typecheck --filter=@carbon/erp 2>&1 | tail -20+# Expected: no type errors in opening-balances.tsx+```+If the base-currency source in the loader is unclear after checking neighbors,+default to reading it in the form via `useUser().company.baseCurrencyCode` and pass+nothing from the loader — do NOT guess a service function name.++**Out of scope:** no `clientAction` (this posts a JE, it is not a cached list+entity). No CSV export.++---++## Task 7: UI `OpeningBalancesForm.tsx`++**Depends on:** Task 6+**Files:**+- Create: `apps/erp/app/modules/accounting/ui/OpeningBalances/OpeningBalancesForm.tsx`+- Copy from (precedent): `apps/erp/app/modules/accounting/ui/JournalEntries/JournalEntryForm.tsx`+ (Card + ValidatedForm + line-table + totals footer + hidden JSON `lines` field)++**Steps:**+1. Props:+ ```typescript+ type OpeningBalancesFormProps = {+ accounts: Array<{+ id: string;+ number: string | null;+ name: string;+ class: "Asset" | "Liability" | "Equity" | "Revenue" | "Expense";+ }>;+ existingEntry: {+ id: string;+ journalEntryId: string;+ postingDate: string;+ lines: Array<{ accountId: string; debit: number; credit: number }>;+ } | null;+ };+ ```+2. If `existingEntry` is non-null, render an informational banner (use+ `@carbon/react` `Alert`/`Status` or the Card empty-state pattern) that says an+ opening-balance entry already exists, with a `<Link to={path.to.journalEntry(+ existingEntry.id)}>` button showing `existingEntry.journalEntryId`, and text:+ "Reverse it from the journal entry screen before entering new balances." Show the+ entered balances read-only underneath (map `existingEntry.lines` to account+ names). Do NOT render the editable form in this state.+3. Otherwise render the editable form:+ - `ValidatedForm method="post" validator={openingBalanceValidator}`.+ - `DatePicker name="postingDate"` — default via `useCompanyToday()` from+ `~/hooks` (business date; never `new Date()`).+ - A table: one row per account showing `number` + `name` (stacked, like the+ journal line account cell) and a single amount `Number` input in state. Header+ columns: "Account", "Amount" (right-aligned). Keep amounts in a+ `Record<accountId, number>` state map.+ - Use `Number`/`NumberControlled` from `~/components/Form` with+ `formatOptions={INPUT_FORMAT.money(baseCurrencyCode, decimalPlaces)}` — read+ `baseCurrencyCode` from `useUser().company.baseCurrencyCode` and decimals from+ the currency (use `useCurrencyFormatter`/`useCurrencyMinDecimals` as the+ journal editor does). Do NOT pass inline `minimumFractionDigits`.+ - Hidden field: `<input type="hidden" name="lines" value={linesJson} />` where+ `linesJson = JSON.stringify(Object.entries(amounts).filter(([,v]) => v).map(+ ([accountId, amount]) => ({ accountId, amount })))`.+ - Footer: compute per-account debit/credit exactly as the service does+ (natural-debit = Asset/Expense) to show live **Total Debits**, **Total+ Credits**, and **"Balancing to Retained Earnings: {formatted plug}"** (the+ signed difference). Format money via `useCurrencyFormatter`.+ - A single **Post Opening Balances** submit button, disabled unless+ `permissions.can("create", "accounting")` and at least one non-zero amount.+ - All user-visible strings use `useLingui().t\`\`` or `<Trans>`.+4. Export from the module barrel if the module `index.ts` re-exports `ui/*`+ (check `apps/erp/app/modules/accounting/index.ts`; if it barrels UI, add the+ export — otherwise import directly in the route).++**Verify:**+```bash+pnpm exec turbo run typecheck --filter=@carbon/erp 2>&1 | tail -20+# Expected: no type errors in OpeningBalancesForm.tsx+```++**Out of scope:** no per-account debit/credit two-column entry (single amount+column only). No dimension pickers. This first pass is functional; the /ui phase+handles visual polish (Vercel aesthetic).++---++## Task 8: i18n extract + scoped typecheck + lint++**Depends on:** Tasks 3–7+**Files:**+- Modify (generated `.po`): `packages/locale/locales/*/erp.po`++**Steps:**+1. `pnpm lingui:extract` to register the new `<Trans>` / `t\`\`` strings.+2. Scoped typecheck and lint.++**Verify:**+```bash+pnpm exec turbo run typecheck --filter=@carbon/erp 2>&1 | tail -20+pnpm run lint 2>&1 | tail -20+# Expected: both clean (no errors in the new files)+```++**Out of scope:** do not run whole-repo `tsc` (OOMs). Do not translate other+locales here (the /translate step can fill them later if desired).++---++## Task 9: Browser verification via /test++**Depends on:** Tasks 1–8 (+ the /ui polish phase, which runs before this)+**Files:** none (verification only)++**Steps:**+1. Boot the stack (`crbn up`), `/auth` to log in.+2. Enable accounting locally if needed (`/x/settings/accounting`), and confirm a+ Retained Earnings default is set (`/x/accounting/defaults`).+3. Navigate to Accounting → General Ledger → **Opening Balances**.+4. Enter a debit balance on a Cash/Asset account and confirm the footer shows the+ plug flowing to Retained Earnings and the entry balancing.+5. Post; confirm redirect to the created journal entry, source type **Opening+ Balance**, status **Posted**, debits = credits.+6. Return to Opening Balances; confirm the guard banner now appears linking to that+ entry. Reverse the entry from the JE screen; confirm the form is editable again.++**Verify:** the pass/fail table from `/test`; every step above passes.++**Out of scope:** load testing, multi-company consolidation.diff --git a/.ai/playbooks/opening-balances.md b/.ai/playbooks/opening-balances.mdnew file mode 100644index 0000000000..89719d38c2--- /dev/null+++ b/.ai/playbooks/opening-balances.md@@ -0,0 +1,30 @@+# Opening Balances (inline on Chart of Accounts)++Last tested: 2026-09-01+Route: /x/accounting/charts (no standalone page — the earlier /x/accounting/opening-balances screen was removed)++## Prerequisites+- Accounting enabled (/x/settings/accounting) — the balance column and the "Opening Balances" button only show when enabled.+- A Retained Earnings default account set at /x/accounting/defaults (seed demo has `3100 Retained Earnings`).+- No un-reversed posted `Opening Balance` journal entry — otherwise the "Opening Balances" button is hidden (reverse the JE to re-enable).++## Steps+### 1. Navigate — /x/accounting/charts+Expect the Chart of Accounts tree + a primary "Opening Balances" button in the toolbar (next to New Group / New Account).+### 2. Enter mode — click "Opening Balances"+Add Group / Add Account disappear; Cancel + Post appear; the balance column header becomes "Opening Balance"; each **leaf** account row's balance cell becomes a right-aligned numeric input (group rows show no input); the per-row actions menu is hidden.+### 3. Fill — type an amount into an account's input, then BLUR (click another input) so react-aria commits. Positive = the account's natural side (Asset/Expense → debit; Liability/Equity/Revenue → credit). Post enables once at least one non-zero amount exists.+### 4. Post — click "Post" → a centered modal "Post opening balances" opens with an "As of date" DatePicker (defaults to company today). `requestSubmit` the modal's form (button text "Post", NOT a click).+### 5. Verify — redirects to /x/journal-entry/{id}/details: Source "Opening Balance", status POSTED, your line(s) + an auto Retained Earnings plug line, Totals BALANCED.+### 6. Guard — back on /x/accounting/charts the "Opening Balances" button is now hidden (a posted entry exists). Reverse the JE (JE detail → ⋮ More options → Reverse Entry → confirm) to make it appear again.+### 7. Cancel — clicking Cancel in opening-balance mode discards entered amounts and returns to the normal tree (inputs gone, Add buttons back).++## Selector Notes+- Leaf-account inputs render as `textbox` refs showing `$0.00`; the first is the first leaf account in the tree.+- Toolbar buttons: "Opening Balances" (enter), then "Cancel" / "Post" once in mode.+- Modal Post button: `button[type=submit]` text "Post" inside the modal's form. Use `f.requestSubmit(b)`.++## Common Failures+- "Opening Balances" button missing: accounting disabled, no create-accounting permission, or an un-reversed posted Opening Balance entry already exists.+- Post modal submit does nothing: clicked instead of `requestSubmit`, or the number input's onChange never fired (fill + blur).+- Vite "Cannot find module": after adding/removing route or ui files, `touch` the changed file or reload so Vite re-resolves.diff --git a/.ai/runs/2026-09-01-opening-balances.md b/.ai/runs/2026-09-01-opening-balances.mdnew file mode 100644index 0000000000..c8e2f0fd8f--- /dev/null+++ b/.ai/runs/2026-09-01-opening-balances.md@@ -0,0 +1,30 @@+# Feature run: Opening Balances tool (accounting)++- Date: 2026-09-01+- Mode: fully-autonomous+- Request: Add a tool for adding opening balances to Carbon accounts. New screen under Accounting → General Ledger → Opening Balances; set initial GL balance per posting (leaf) account as of a cutover date; on save post one balanced journal entry with a new `'Opening Balance'` journalEntrySourceType, auto-plugging the difference to Retained Earnings (`accountDefault.retainedEarningsAccount`). Reuse getNextSequence → createJournalEntry → saveJournalEntryWithLines → postJournalEntry. Sign conventions via toStoredAmount/toDisplayDebit/toDisplayCredit. Detect existing posted Opening Balance entry and require reversal first (pre-fill from existing). Base currency only. Then use /ui for a Vercel aesthetic.+- Phase plan: research [skip — well-understood accounting concept; design already grounded against code + confirmed with user this turn] · spec [skip — design confirmed with user, captured in plan] · plan [run] · execute [run] · ui-polish [run — user explicitly requested /ui with Vercel aesthetic] · test [run — user-facing posting flow] · self-review [run]++## Decisions+- Balancing account: Retained Earnings (accountDefault.retainedEarningsAccount) — confirmed with user; matches fixed-asset mid-life registration precedent — 2026-09-01+- Re-run guard: detect existing posted 'Opening Balance' JE, require reversal first, pre-fill form from it — confirmed with user — 2026-09-01+- Currency: base currency only (matches journal editor) — confirmed with user — 2026-09-01++## Decisions (cont.)+- 🛑 Plan-approval gate (autonomous): auto-approved plan .ai/plans/2026-09-01-opening-balances.md — 9 tasks, grounded against verified service signatures (createJournalEntry/saveJournalEntryWithLines/postJournalEntry, getNextSequence "journalEntry", getDefaultAccounts.retainedEarningsAccount). Rationale: design pre-confirmed with user; plan only mechanizes it — 2026-09-01++## Phase log+- plan: done — .ai/plans/2026-09-01-opening-balances.md+- execute: Tasks 1–8 done. Booted mbabane stack via `crbn up` (crbn migrate's postgres-only stack fails on storage.buckets — env limitation). Migration applied + enum verified in DB. Forced POSTING_POLICY entry in @carbon/ee (mirrors Manual, syncable:false). Gates green: typecheck erp+ee, biome lint (7 files), lingui:extract.+- DEVIATION: not auto-committing per task — standing user preference "never auto-commit unless explicitly asked" (memory feedback_no_auto_commit) overrides the execute/feature skills' per-task commit. Work left uncommitted for user review.+- ui-polish: done — /ui skill (uidotsh design guidelines: tables/surfaces/typography/colors/shadows). Rewrote OpeningBalancesForm with class-grouped sections (Assets/Liabilities/Equity/Revenue/Expenses), heading-group header w/ inline As-of date + Post, hover rows, Dr/Cr status pills, and a 3-cell divider stat strip (Total debits / Total credits / Retained Earnings plug) with Balanced status. tabular-nums throughout, /60-/40 opacity dividers, rounded-xl bordered surfaces, no shadow+border. Behavior preserved (hidden lines JSON, totals/plug memo, existing-entry branch). Gates green: typecheck erp, biome lint, lingui:extract.+- test: PASS 9/9 (/test skill, agent-browser on erp.mbabane.dev, company "Carbon Development"). Login → preconditions (accounting on, RE default 3100) → nav entry present → empty state renders (class sections + summary strip) → entered $10,000 debit on Bank-Cash (Dr pill, plug $10,000 credit, "Balancing to Retained Earnings") → Post → redirected to JE-2026-09-000001, source "Opening Balance", POSTED, Bank-Cash Dr $10,000 + auto Retained Earnings Cr $10,000, BALANCED → guard banner on re-entry (no editable form) → reversed JE re-enables the form. Screenshots in .ai/scratch/e2e/. Playbook cached at .ai/playbooks/opening-balances.md. Also fixed a copy nit (Plural: "1 account with a balance"); re-verified typecheck+lint+extract green.+- self-review: done. Must-fix caught + fixed: `.po` catalogs had 12.7k-line origin-ref churn (extract didn't run lingui:clean) → ran `pnpm lingui:clean`, now 961 insertions (new strings only, erp-only). Verified sync-policy enforcement (posting.ts:193 `syncable===false`, models.ts:625, defaultEnabled:false) — Opening Balance never syncs, correct. Sign/plug logic in service matches form preview. Guard is Posted-only + re-checked in action. Docs updated: accounting AGENTS.md (Key Service Functions) + accounting-sync-handlers.md rule. Residual low-sev risks noted (non-atomic create→save→post can orphan a Draft on post failure; plug carries raw float within tolerance) — not blocking, mirror existing manual-JE behavior.++## UX pivot (2026-09-01, user feedback: standalone page "really ugly")+- Removed the standalone /x/accounting/opening-balances page, its ui/OpeningBalances/ dir, the path.ts entry, and the nav item (path.ts + useAccountingSubmodules reverted to original — no longer in the diff).+- Reimplemented INLINE on the Chart of Accounts page: a primary "Opening Balances" button (ChartOfAccountsTableFilters) toggles `openingBalanceMode` (state lifted into charts.tsx). In mode: each leaf account's balance cell becomes a numeric input (ChartOfAccountsTree), group rows show none; Add Group/Add Account + per-row menus hidden; Cancel + Post shown. Post opens OpeningBalancePostModal (centered ModalDrawer type=modal) collecting the as-of date, submitting to the charts.tsx action. Service/validator/migration/POSTING_POLICY unchanged. Guard: charts loader hides the button when a posted entry exists; action re-checks.+- Re-verified in browser: enter mode → 80 inputs, Add buttons gone, Cancel+Post present → entered $25,000 on Bank-Cash → Post modal (date default today) → posted JE (Opening Balance, POSTED, BALANCED) → guard hides button → reversal re-enables → Cancel exits cleanly. Screenshots: .ai/scratch/e2e/coa-*.png. Playbook updated to the inline flow. Docs (AGENTS.md) updated. Copy plural fixed. Gates green: typecheck erp, biome lint, lingui extract+clean.++## Outcome+- COMPLETE (uncommitted, per user's no-auto-commit preference). Final surface = inline on Chart of Accounts (no standalone page). All gates green. Ready for the user to review + commit.diff --git a/.claude/rules/accounting-sync-handlers.md b/.claude/rules/accounting-sync-handlers.mdindex baa2651f4a..f12ebb6709 100644--- a/.claude/rules/accounting-sync-handlers.md+++ b/.claude/rules/accounting-sync-handlers.md@@ -10,7 +10,7 @@ paths:Syncs Carbon entities <-> external accounting providers. **Three live providers**: Xero (`ProviderID.XERO`), QuickBooks Online (`ProviderID.QBO`), and Rillet (`ProviderID.RILLET`). (QuickBooks *Desktop* shipped then was removed 2026-08-01; Sage was never built.) `SyncFactory` is a **provider-keyed registry** (`registries[providerId][entityType]`) — each provider's `index.ts` barrel calls `SyncFactory.register(...)`. Runs on **Inngest** (the old trigger.dev `from-/to-accounting-sync` task design is gone — do not look for `UPSERT_MAP`/`DELETE_MAP` or a `trigger/` dir; neither exists).-Design specs: `.ai/specs/2026-08-12-accounting-sync-reconciler-unification.md` (v5 — ONE state-shaped decision core; events are hints; the authoritative design of record) and `.ai/specs/implemented/2026-08-05-accounting-document-representation.md` (AR/AP documents replay their posting journal; provider items non-tracked). The superseded v2/v3/v4 specs (engine + ledger + pull sweep + Phase F/G payment sync-back; journal policy/dimensions/tie-out; delivery robustness — converged subscriptions, truthful ledger, outbound sweep, tie-out enforcement) were removed 2026-08-13 — their shipped behavior is documented in THIS rule; their history is in git. **Always-on (implemented 2026-08-13, plan `.ai/plans/2026-08-13-accounting-sync-automated-postings-only.md` Tasks 1–6+8):** posting sync mirrors Carbon's automated GL postings whenever an accounting integration is connected — no master `postingSync.enabled` toggle, no per-source-type on/off, no `journalEntry` entity gate (defaulted on in `DEFAULT_SYNC_CONFIG` and forced on in every `build*SyncConfig`). `Manual` journals NEVER sync (`POSTING_POLICY.Manual.syncable: false` → permanent `MANUAL_DISABLED`). Legacy `enabled` fields stay in the stored schema for parse-compat but are never read; per-type granularity (individual vs daily-summary) remains the only per-type setting. Plan Tasks 7 (reversal/void propagation audit) and 9 (lock AR/AP families to documents) remain open.+Design specs: `.ai/specs/2026-08-12-accounting-sync-reconciler-unification.md` (v5 — ONE state-shaped decision core; events are hints; the authoritative design of record) and `.ai/specs/implemented/2026-08-05-accounting-document-representation.md` (AR/AP documents replay their posting journal; provider items non-tracked). The superseded v2/v3/v4 specs (engine + ledger + pull sweep + Phase F/G payment sync-back; journal policy/dimensions/tie-out; delivery robustness — converged subscriptions, truthful ledger, outbound sweep, tie-out enforcement) were removed 2026-08-13 — their shipped behavior is documented in THIS rule; their history is in git. **Always-on (implemented 2026-08-13, plan `.ai/plans/2026-08-13-accounting-sync-automated-postings-only.md` Tasks 1–6+8):** posting sync mirrors Carbon's automated GL postings whenever an accounting integration is connected — no master `postingSync.enabled` toggle, no per-source-type on/off, no `journalEntry` entity gate (defaulted on in `DEFAULT_SYNC_CONFIG` and forced on in every `build*SyncConfig`). `Manual` and `Opening Balance` journals NEVER sync (`POSTING_POLICY[...].syncable: false` → the `MANUAL_DISABLED` exclude at `posting.ts`; the external ledger owns manual journals and its own opening balances). Note the exclude `reason`/`message` are still worded "Manual" for both — the gate is `syncable === false`, not a name check. Legacy `enabled` fields stay in the stored schema for parse-compat but are never read; per-type granularity (individual vs daily-summary) remains the only per-type setting. Plan Tasks 7 (reversal/void propagation audit) and 9 (lock AR/AP families to documents) remain open.## Architecture: class-per-entity syncers, not a handler mapdiff --git a/apps/erp/app/components/Icons.tsx b/apps/erp/app/components/Icons.tsxindex 62d4425199..ab5e48bee8 100644--- a/apps/erp/app/components/Icons.tsx+++ b/apps/erp/app/components/Icons.tsx@@ -15,6 +15,7 @@ import type { ReactNode } from "react";import { AiOutlinePartition } from "react-icons/ai";import { FaCodePullRequest } from "react-icons/fa6";import {+ LuArrowDownToDot,LuArrowLeftRight,LuAtom,LuBanknote,@@ -599,6 +600,8 @@ export const JournalEntrySourceTypeIcon = ({switch (sourceType) {case "Manual":return <LuBookOpen className={className} />;+ case "Opening Balance":+ return <LuArrowDownToDot className={className} />;case "Purchase Receipt":return <LuHandCoins className={className} />;case "Purchase Invoice":diff --git a/apps/erp/app/modules/accounting/AGENTS.md b/apps/erp/app/modules/accounting/AGENTS.mdindex cd2aa59e84..9d08381121 100644--- a/apps/erp/app/modules/accounting/AGENTS.md+++ b/apps/erp/app/modules/accounting/AGENTS.md@@ -80,6 +80,7 @@ pnpm --filter @carbon/erp test -- --testPathPattern=accounting- `getAccountPeriodSeries` — thin wrapper for the `accountTreeBalancePeriodSeries` RPC (period ends must come from `computeReportPeriodBuckets`)- `getReportPins` / `upsertReportPin` — per-user pin overrides for the reports hub- `createJournalEntry` / `saveJournalEntryWithLines` / `postJournalEntry` / `reverseJournalEntry` — journal lifecycle+- `createOpeningBalanceJournal` / `getExistingOpeningBalanceEntry` — Opening Balances, an **inline mode on the Chart of Accounts page** (`charts.tsx` action; the "Opening Balances" primary button toggles `openingBalanceMode` in `ChartOfAccountsTree`, replacing each leaf account's balance cell with a numeric input and hiding Add Group/Add Account; Post opens `OpeningBalancePostModal` to collect the as-of date). Posts ONE balanced journal (`journalEntrySourceType` `'Opening Balance'`) from per-account natural-balance amounts, auto-plugging the net difference to `accountDefault.retainedEarningsAccount`; reuses `getNextSequence`→`createJournalEntry`→`saveJournalEntryWithLines`→`postJournalEntry`. `getExistingOpeningBalanceEntry` returns the current **Posted** opening-balance entry (Reversed does not count), which gates re-entry: the charts loader hides the button when one exists, and the charts action re-checks server-side. `'Opening Balance'` is `syncable:false` in `@carbon/ee` POSTING_POLICY — like `Manual`, it never syncs (the external ledger owns opening balances).- `getOrCreateAccountingPeriod` / `getCurrentAccountingPeriod` — period management (lazy create on posting)- `createFiscalYearPeriods` — generate the 12 monthly periods for a fiscal year (idempotent; from `fiscalYearSettings.startMonth`)- `lockAccountingPeriod` / `unlockAccountingPeriod` / `closeAccountingPeriod` / `reopenAccountingPeriod` — Open↔Locked↔Closed transitions (sequential close/reopen)diff --git a/apps/erp/app/modules/accounting/accounting.ee.service.ts b/apps/erp/app/modules/accounting/accounting.ee.service.tsindex 108c337db1..3d174cbe0d 100644--- a/apps/erp/app/modules/accounting/accounting.ee.service.ts+++ b/apps/erp/app/modules/accounting/accounting.ee.service.ts@@ -5099,6 +5099,199 @@ export async function postJournalEntry(.single();}+// Returns `{ id }` of the company's current posted Opening Balance journal+// entry, or null. Callers only need existence — this is the re-entry gate. Only+// status='Posted' blocks a new set; a Reversed entry lets the user enter a fresh+// one.+export async function getExistingOpeningBalanceEntry(+ client: SupabaseClient<Database>,+ companyId: string+) {+ const entry = await client+ .from("journal")+ .select("id")+ .eq("companyId", companyId)+ .eq("sourceType", "Opening Balance")+ .eq("status", "Posted")+ .order("createdAt", { ascending: false })+ .limit(1)+ .maybeSingle();++ if (entry.error) return { data: null, error: entry.error };+ return { data: entry.data ? { id: entry.data.id } : null, error: null };+}++// Posts the company's opening balances as a single balanced journal entry+// (sourceType 'Opening Balance'). Each `balances` row carries one signed+// natural-balance amount for a posting account; the net difference is plugged to+// the Retained Earnings default account so debits equal credits. Reuses the+// manual-JE stack: createJournalEntry (Draft) → saveJournalEntryWithLines →+// postJournalEntry (which validates the balance and resolves the period).+export async function createOpeningBalanceJournal(+ client: SupabaseClient<Database>,+ args: {+ companyId: string;+ companyGroupId: string;+ userId: string;+ postingDate: string;+ balances: Array<{ accountId: string; amount: number }>;+ }+) {+ const { companyId, companyGroupId, userId, postingDate, balances } = args;++ const entered = balances.filter((b) => b.amount !== 0);+ if (entered.length === 0) {+ return { data: null, error: { message: "No opening balances entered" } };+ }++ // Guard here — not only in the route — so every caller (the route action AND+ // the MCP-exposed tool) is protected. Opening balances are entered once; an+ // un-reversed posted entry must be reversed before a new set is posted.+ const existing = await getExistingOpeningBalanceEntry(client, companyId);+ if (existing.error) return { data: null, error: existing.error };+ if (existing.data) {+ return {+ data: null,+ error: {+ message:+ "An opening balance entry already exists — reverse it before entering new balances"+ }+ };+ }++ // Retained Earnings is the balancing plug.+ const defaults = await getDefaultAccounts(client, companyId);+ if (defaults.error) return { data: null, error: defaults.error };+ const retainedEarningsAccount = defaults.data?.retainedEarningsAccount;+ if (!retainedEarningsAccount) {+ return {+ data: null,+ error: {+ message:+ "No Retained Earnings account is configured in Default Accounts"+ }+ };+ }++ // Account classes turn each signed natural-balance amount into debit/credit+ // (saveJournalEntryWithLines re-derives the stored amount from debit/credit).+ const accountIds = [...new Set(entered.map((b) => b.accountId))];+ const accounts = await client+ .from("account")+ .select("id, class")+ .in("id", accountIds)+ // Scope to the caller's chart of accounts (company-group). A foreign id then+ // resolves to no class and aborts below with "Account not found", so a+ // crafted payload can't post against another tenant's accounts.+ .eq("companyGroupId", companyGroupId);+ if (accounts.error) return { data: null, error: accounts.error };+ const classById = new Map(+ accounts.data.map((a) => [+ a.id,+ a.class as Database["public"]["Enums"]["glAccountClass"]+ ])+ );++ const isNaturalDebit = (cls: Database["public"]["Enums"]["glAccountClass"]) =>+ cls === "Asset" || cls === "Expense";++ // Sum in "debit positive" space so the plug's sign is unambiguous.+ let netDebitMinusCredit = 0;+ const lines: Array<{ accountId: string; debit: number; credit: number }> = [];+ for (const b of entered) {+ const cls = classById.get(b.accountId);+ if (!cls) {+ return {+ data: null,+ error: { message: `Account not found: ${b.accountId}` }+ };+ }+ const isDebit = isNaturalDebit(cls) ? b.amount >= 0 : b.amount < 0;+ const magnitude = Math.abs(b.amount);+ const debit = isDebit ? magnitude : 0;+ const credit = isDebit ? 0 : magnitude;+ netDebitMinusCredit += debit - credit;+ lines.push({ accountId: b.accountId, debit, credit });+ }++ // Plug to Retained Earnings unless the entered lines already balance (shared+ // tolerance, no literal). More debit ⇒ the plug is a credit, and vice-versa.+ if (!isBalanced(netDebitMinusCredit, 0, JOURNAL_BALANCE_TOLERANCE)) {+ lines.push({+ accountId: retainedEarningsAccount,+ debit: netDebitMinusCredit < 0 ? -netDebitMinusCredit : 0,+ credit: netDebitMinusCredit > 0 ? netDebitMinusCredit : 0+ });+ }++ const journalEntryId = await getNextSequence(+ client,+ "journalEntry",+ companyId+ );+ if (journalEntryId.error || !journalEntryId.data) {+ return {+ data: null,+ error: journalEntryId.error ?? {+ message: "Failed to allocate journal entry number"+ }+ };+ }++ const created = await createJournalEntry(client, {+ journalEntryId: journalEntryId.data as string,+ sourceType: "Opening Balance",+ companyId,+ createdBy: userId,+ postingDate,+ description: "Opening balances"+ });+ if (created.error || !created.data) {+ return {+ data: null,+ error: created.error ?? { message: "Failed to create journal entry" }+ };+ }+ const id = created.data.id;++ // No transaction spans create → save → post (these reuse the supabase-client+ // JE helpers), so on any failure roll back the Draft header we just created —+ // journalLine cascades (ON DELETE CASCADE). Otherwise an orphan 'Opening+ // Balance' Draft lingers that the Posted-only re-entry gate can't see, and the+ // user would accumulate one per retry (e.g. an as-of date in a Closed period).+ const rollbackDraft = () =>+ client.from("journal").delete().eq("id", id).eq("status", "Draft");++ const saved = await saveJournalEntryWithLines(client, {+ journalEntryId: id,+ postingDate,+ description: "Opening balances",+ updatedBy: userId,+ lines,+ companyId,+ companyGroupId+ });+ if (saved.error) {+ await rollbackDraft();+ return { data: null, error: saved.error };+ }++ const posted = await postJournalEntry(client, id, userId);+ if (posted.error) {+ await rollbackDraft();+ // A unique violation on journal_one_posted_opening_balance_per_company means+ // a concurrent request already posted the company's opening balances — the+ // atomic backstop for the check-then-post race.+ const message =+ (posted.error as { code?: string }).code === "23505"+ ? "An opening balance entry already exists — reverse it before entering new balances"+ : posted.error.message;+ return { data: null, error: { message } };+ }++ return { data: { id }, error: null };+}+export async function reverseJournalEntry(client: SupabaseClient<Database>,id: string,diff --git a/apps/erp/app/modules/accounting/accounting.models.ts b/apps/erp/app/modules/accounting/accounting.models.tsindex 0ebf300b5d..340aa1f588 100644--- a/apps/erp/app/modules/accounting/accounting.models.ts+++ b/apps/erp/app/modules/accounting/accounting.models.ts@@ -678,8 +678,63 @@ export const intercompanyTransactionValidator = z});+export const openingBalanceValidator = z.object({+ postingDate: z.string().min(1, { message: "Posting date is required" }),+ // JSON-encoded array of { accountId, amount } produced by the form's hidden+ // input. `amount` is the signed base-currency figure the user typed against+ // the account, positive = the account's natural balance side (debit for+ // Asset/Expense, credit for Liability/Equity/Revenue). The service converts+ // each amount → {debit, credit} per class and appends the Retained Earnings+ // plug before posting. Zero-amount rows are dropped.+ lines: z+ .string()+ .min(1, { message: "At least one balance is required" })+ .transform((val, ctx) => {+ let parsed: unknown;+ try {+ parsed = JSON.parse(val);+ } catch {+ ctx.addIssue({ code: z.ZodIssueCode.custom, message: "Invalid lines" });+ return z.NEVER;+ }+ if (!Array.isArray(parsed)) {+ ctx.addIssue({ code: z.ZodIssueCode.custom, message: "Invalid lines" });+ return z.NEVER;+ }++ // Reject structurally-invalid rows rather than silently dropping them, so+ // a malformed payload fails loudly instead of posting a partial entry. A+ // zero amount is a legitimately-empty input and is the only thing skipped.+ const result: Array<{ accountId: string; amount: number }> = [];+ for (const row of parsed) {+ const accountId = (row as { accountId?: unknown }).accountId;+ const amount = (row as { amount?: unknown }).amount;+ if (typeof accountId !== "string" || accountId.length === 0) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ message: "An opening balance row is missing its account"+ });+ return z.NEVER;+ }+ if (typeof amount !== "number" || !Number.isFinite(amount)) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ message: "An opening balance row has an invalid amount"+ });+ return z.NEVER;+ }+ if (amount !== 0) result.push({ accountId, amount });+ }+ return result;+ })+ .refine((lines) => lines.length > 0, {+ message: "At least one balance is required"+ })+});+export const journalEntrySourceTypes = ["Manual",+ "Opening Balance","Purchase Receipt","Purchase Invoice","Purchase Return",diff --git a/apps/erp/app/modules/accounting/ui/ChartOfAccounts/ChartOfAccountsTableFilters.tsx b/apps/erp/app/modules/accounting/ui/ChartOfAccounts/ChartOfAccountsTableFilters.tsxindex 62809c6643..68e7c65a23 100644--- a/apps/erp/app/modules/accounting/ui/ChartOfAccounts/ChartOfAccountsTableFilters.tsx+++ b/apps/erp/app/modules/accounting/ui/ChartOfAccounts/ChartOfAccountsTableFilters.tsx@@ -6,7 +6,7 @@ import {InputLeftElement} from "@carbon/react";import { Trans, useLingui } from "@lingui/react/macro";-import { LuSearch, LuX } from "react-icons/lu";+import { LuCheckCheck, LuSearch, LuWallet, LuX } from "react-icons/lu";import { New, PeriodSelector } from "~/components";import { usePermissions, useUrlParams } from "~/hooks";@@ -14,12 +14,24 @@ type ChartOfAccountsTableFiltersProps = {fiscalStartMonth?: number;search: string;onSearchChange: (value: string) => void;+ openingBalanceMode: boolean;+ canEnterOpeningBalances: boolean;+ hasOpeningBalanceEntries: boolean;+ onEnterOpeningBalances: () => void;+ onCancelOpeningBalances: () => void;+ onPostOpeningBalances: () => void;};const ChartOfAccountsTableFilters = ({fiscalStartMonth,search,- onSearchChange+ onSearchChange,+ openingBalanceMode,+ canEnterOpeningBalances,+ hasOpeningBalanceEntries,+ onEnterOpeningBalances,+ onCancelOpeningBalances,+ onPostOpeningBalances}: ChartOfAccountsTableFiltersProps) => {const { t } = useLingui();const [params, setParams] = useUrlParams();@@ -55,10 +67,39 @@ const ChartOfAccountsTableFilters = ({)}</HStack><HStack>- {permissions.can("create", "accounting") && (+ {openingBalanceMode ? (+ // Entering opening balances: Add Group / Add Account are hidden; only+ // Cancel + Post remain.<>- <New label={t`Group`} to={`new-group?${params.toString()}`} />- <New label={t`Account`} to={`new?${params.toString()}`} />+ <Button variant="secondary" onClick={onCancelOpeningBalances}>+ <Trans>Cancel</Trans>+ </Button>+ <Button+ variant="primary"+ leftIcon={<LuCheckCheck />}+ isDisabled={!hasOpeningBalanceEntries}+ onClick={onPostOpeningBalances}+ >+ <Trans>Post</Trans>+ </Button>+ </>+ ) : (+ <>+ {permissions.can("create", "accounting") && (+ <>+ <New label={t`Group`} to={`new-group?${params.toString()}`} />+ <New label={t`Account`} to={`new?${params.toString()}`} />+ </>+ )}+ {canEnterOpeningBalances && (+ <Button+ variant="secondary"+ leftIcon={<LuWallet />}+ onClick={onEnterOpeningBalances}+ >+ <Trans>Opening Balances</Trans>+ </Button>+ )}</>)}</HStack>diff --git a/apps/erp/app/modules/accounting/ui/ChartOfAccounts/ChartOfAccountsTree.tsx b/apps/erp/app/modules/accounting/ui/ChartOfAccounts/ChartOfAccountsTree.tsxindex 73ad7189e2..a61f4a9cc2 100644--- a/apps/erp/app/modules/accounting/ui/ChartOfAccounts/ChartOfAccountsTree.tsx+++ b/apps/erp/app/modules/accounting/ui/ChartOfAccounts/ChartOfAccountsTree.tsx@@ -4,8 +4,11 @@ import {DropdownMenuContent,DropdownMenuItem,DropdownMenuTrigger,+ NumberField,+ NumberInput,ScrollArea} from "@carbon/react";+import { INPUT_FORMAT } from "@carbon/utils";import { Trans, useLingui } from "@lingui/react/macro";import { memo, useMemo, useRef } from "react";import {@@ -22,13 +25,22 @@ import {import { useNavigate } from "react-router";import type { FlatTree, FlatTreeItem } from "~/components/TreeView";import { LevelLine, TreeView, useTree } from "~/components/TreeView";-import { useRealtime, useSettings, useUrlParams } from "~/hooks";+import {+ useCurrencyDecimals,+ useRealtime,+ useSettings,+ useUrlParams,+ useUser+} from "~/hooks";import { path } from "~/utils/path";import type { Chart } from "../../types";type ChartOfAccountsTreeProps = {data: Chart[];search: string;+ openingBalanceMode?: boolean;+ amounts?: Record<string, number>;+ onAmountChange?: (accountId: string, value: number) => void;};function accountsToFlatTree(accounts: Chart[]): FlatTree<Chart> {@@ -101,7 +113,13 @@ function formatCurrency(value: number): string {}const ChartOfAccountsTree = memo(- ({ data, search }: ChartOfAccountsTreeProps) => {+ ({+ data,+ search,+ openingBalanceMode = false,+ amounts = {},+ onAmountChange+ }: ChartOfAccountsTreeProps) => {const { t } = useLingui();useRealtime("journal");const settings = useSettings();@@ -109,6 +127,9 @@ const ChartOfAccountsTree = memo(const parentRef = useRef<HTMLDivElement>(null);const navigate = useNavigate();const [params] = useUrlParams();+ const { company } = useUser();+ const currencyCode = company.baseCurrencyCode;+ const currencyDecimals = useCurrencyDecimals(currencyCode);const openLedger = (accountId: string) => {const nextParams = new URLSearchParams(params);@@ -156,10 +177,16 @@ const ChartOfAccountsTree = memo(<div className="flex-1 px-4"><Trans>Account</Trans></div>- {accountingEnabled && (- <span className="w-32 text-right px-4">- {params.get("startDate") ? t`Net Change` : t`Balance`}+ {openingBalanceMode ? (+ <span className="w-44 text-right px-4">+ <Trans>Opening Balance</Trans></span>+ ) : (+ accountingEnabled && (+ <span className="w-32 text-right px-4">+ {params.get("startDate") ? t`Net Change` : t`Balance`}+ </span>+ ))}</div><TreeView<Chart>@@ -196,7 +223,9 @@ const ChartOfAccountsTree = memo(selectNode(node.id, false);if (isGroup) {toggleExpandNode(node.id);- } else {+ } else if (!openingBalanceMode) {+ // In opening-balance mode a leaf row hosts an input; don't+ // navigate away and lose the entered amounts.openLedger(account.id as string);}}}@@ -250,8 +279,39 @@ const ChartOfAccountsTree = memo(<span className="truncate">{account.name}</span></div>- {/* Balance */}- {accountingEnabled &&+ {/* Balance / opening-balance input */}+ {openingBalanceMode ? (+ isGroup ? (+ // Groups are rollups — no balance can be posted to them.+ <span className="w-44 shrink-0" />+ ) : (+ <div+ className="w-44 shrink-0 pl-2"+ onClick={(e) => e.stopPropagation()}+ >+ <NumberField+ aria-label={t`Opening balance for ${account.name}`}+ value={amounts[account.id as string] ?? 0}+ onChange={(value) =>+ onAmountChange?.(+ account.id as string,+ isNaN(value) ? 0 : value+ )+ }+ formatOptions={INPUT_FORMAT.rate(+ currencyCode,+ currencyDecimals+ )}+ >+ <NumberInput+ size="sm"+ className="h-7 text-right font-mono tabular-nums"+ />+ </NumberField>+ </div>+ )+ ) : (+ accountingEnabled &&(isGroup ? (<span className="w-32 text-right tabular-nums shrink-0 text-muted-foreground">{formatCurrency(balance)}@@ -267,22 +327,71 @@ const ChartOfAccountsTree = memo(>{formatCurrency(balance)}</button>- ))}+ ))+ )}- {/* Actions menu */}- <DropdownMenu>- <DropdownMenuTrigger asChild>- <button- className="ml-1 shrink-0 rounded-md p-1 opacity-0 transition-opacity hover:bg-accent group-hover/row:opacity-100"- onClick={(e) => e.stopPropagation()}- >- <LuEllipsisVertical className="h-3.5 w-3.5 text-muted-foreground" />- </button>- </DropdownMenuTrigger>- <DropdownMenuContent align="end">- {isGroup ? (- <>- {!account.isSystem && (+ {/* Actions menu — hidden while entering opening balances */}+ {!openingBalanceMode && (+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <button+ className="ml-1 shrink-0 rounded-md p-1 opacity-0 transition-opacity hover:bg-accent group-hover/row:opacity-100"+ onClick={(e) => e.stopPropagation()}+ >+ <LuEllipsisVertical className="h-3.5 w-3.5 text-muted-foreground" />+ </button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end">+ {isGroup ? (+ <>+ {!account.isSystem && (+ <DropdownMenuItem+ onClick={() =>+ runMenuAction(() =>+ navigate(account.id as string)+ )+ }+ >+ <LuPencil className="mr-2 h-4 w-4" />+ <Trans>Edit Group</Trans>+ </DropdownMenuItem>+ )}+ <DropdownMenuItem+ onClick={() =>+ runMenuAction(() =>+ navigate(`new-group?parentId=${account.id}`)+ )+ }+ >+ <LuFolderPlus className="mr-2 h-4 w-4" />+ <Trans>Add Group</Trans>+ </DropdownMenuItem>+ <DropdownMenuItem+ onClick={() =>+ runMenuAction(() =>+ navigate(`new?parentId=${account.id}`)+ )+ }+ >+ <LuFilePlus className="mr-2 h-4 w-4" />+ <Trans>Add Account</Trans>+ </DropdownMenuItem>+ {!account.isSystem && (+ <DropdownMenuItem+ className="text-destructive"+ onClick={() =>+ runMenuAction(() =>+ navigate(`delete/${account.id}`)+ )+ }+ >+ <LuTrash2 className="mr-2 h-4 w-4" />+ <Trans>Delete</Trans>+ </DropdownMenuItem>+ )}+ </>+ ) : (+ <><DropdownMenuItemonClick={() =>runMenuAction(() =>@@ -291,30 +400,8 @@ const ChartOfAccountsTree = memo(}><LuPencil className="mr-2 h-4 w-4" />- <Trans>Edit Group</Trans>+ <Trans>Edit</Trans></DropdownMenuItem>- )}- <DropdownMenuItem- onClick={() =>- runMenuAction(() =>- navigate(`new-group?parentId=${account.id}`)- )- }- >- <LuFolderPlus className="mr-2 h-4 w-4" />- <Trans>Add Group</Trans>- </DropdownMenuItem>- <DropdownMenuItem- onClick={() =>- runMenuAction(() =>- navigate(`new?parentId=${account.id}`)- )- }- >- <LuFilePlus className="mr-2 h-4 w-4" />- <Trans>Add Account</Trans>- </DropdownMenuItem>- {!account.isSystem && (<DropdownMenuItemclassName="text-destructive"onClick={() =>@@ -326,33 +413,11 @@ const ChartOfAccountsTree = memo(<LuTrash2 className="mr-2 h-4 w-4" /><Trans>Delete</Trans></DropdownMenuItem>- )}- </>- ) : (- <>- <DropdownMenuItem- onClick={() =>- runMenuAction(() => navigate(account.id as string))- }- >- <LuPencil className="mr-2 h-4 w-4" />- <Trans>Edit</Trans>- </DropdownMenuItem>- <DropdownMenuItem- className="text-destructive"- onClick={() =>- runMenuAction(() =>- navigate(`delete/${account.id}`)- )- }- >- <LuTrash2 className="mr-2 h-4 w-4" />- <Trans>Delete</Trans>- </DropdownMenuItem>- </>- )}- </DropdownMenuContent>- </DropdownMenu>+ </>+ )}+ </DropdownMenuContent>+ </DropdownMenu>+ )}</div>);}}diff --git a/apps/erp/app/modules/accounting/ui/ChartOfAccounts/OpeningBalancePostModal.tsx b/apps/erp/app/modules/accounting/ui/ChartOfAccounts/OpeningBalancePostModal.tsxnew file mode 100644index 0000000000..5437119542--- /dev/null+++ b/apps/erp/app/modules/accounting/ui/ChartOfAccounts/OpeningBalancePostModal.tsx@@ -0,0 +1,96 @@+import { ValidatedForm } from "@carbon/form";+import {+ Button,+ HStack,+ ModalDrawer,+ ModalDrawerBody,+ ModalDrawerContent,+ ModalDrawerFooter,+ ModalDrawerHeader,+ ModalDrawerProvider,+ ModalDrawerTitle,+ VStack+} from "@carbon/react";+import { Plural, Trans, useLingui } from "@lingui/react/macro";+import { LuCheckCheck } from "react-icons/lu";+import { DatePicker, Submit } from "~/components/Form";+import { useCompanyToday } from "~/hooks";+import { path } from "~/utils/path";+import { openingBalanceValidator } from "../../accounting.models";++type OpeningBalancePostModalProps = {+ /** JSON array of { accountId, amount } for the non-zero rows. */+ linesJson: string;+ /** How many accounts carry a balance — shown for confirmation. */+ count: number;+ open: boolean;+ onClose: () => void;+};++const OpeningBalancePostModal = ({+ linesJson,+ count,+ open,+ onClose+}: OpeningBalancePostModalProps) => {+ const { t } = useLingui();+ const today = useCompanyToday();++ return (+ <ModalDrawerProvider type="modal">+ <ModalDrawer+ open={open}+ onOpenChange={(o) => {+ if (!o) onClose();+ }}+ >+ <ModalDrawerContent>+ <ValidatedForm+ method="post"+ action={path.to.chartOfAccounts}+ validator={openingBalanceValidator}+ defaultValues={{ postingDate: today, lines: [] }}+ className="flex flex-col h-full"+ >+ <ModalDrawerHeader>+ <ModalDrawerTitle>+ <Trans>Post opening balances</Trans>+ </ModalDrawerTitle>+ </ModalDrawerHeader>+ <ModalDrawerBody>+ <input type="hidden" name="lines" value={linesJson} />+ <VStack spacing={4}>+ <p className="text-sm text-muted-foreground">+ <Trans>+ A single balanced journal entry will be posted as of the+ date below, with the difference offset to Retained Earnings.+ </Trans>+ </p>+ <DatePicker name="postingDate" label={t`As of date`} />+ <p className="text-xs text-muted-foreground">+ <Plural+ value={count}+ one="# account with a balance"+ other="# accounts with a balance"+ />+ </p>+ </VStack>+ </ModalDrawerBody>+ <ModalDrawerFooter>+ <HStack>+ <Submit leftIcon={<LuCheckCheck />}>+ <Trans>Post</Trans>+ </Submit>+ <Button size="md" variant="solid" onClick={onClose}>+ <Trans>Cancel</Trans>+ </Button>+ </HStack>+ </ModalDrawerFooter>+ </ValidatedForm>+ </ModalDrawerContent>+ </ModalDrawer>+ </ModalDrawerProvider>+ );+};++export default OpeningBalancePostModal;diff --git a/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json b/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.jsonindex ab4bc07d94..e1c5887ec7 100644--- a/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json+++ b/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json@@ -1,6 +1,6 @@{- "generated": "2026-09-02T18:59:20.006Z",- "totalTools": 1488,+ "generated": "2026-09-03T02:17:05.898Z",+ "totalTools": 1490,"modules": 15,"tools": [{@@ -3613,6 +3613,53 @@]}},+ {+ "name": "accounting_getExistingOpeningBalanceEntry",+ "module": "accounting",+ "classification": "READ",+ "description": "get existing opening balance entry",+ "paramCount": 0,+ "serviceParams": [+ "client",+ "companyId"+ ],+ "injectAuth": [+ "companyId"+ ],+ "schema": {+ "type": "object",+ "properties": {}+ }+ },+ {+ "name": "accounting_createOpeningBalanceJournal",+ "module": "accounting",+ "classification": "DESTRUCTIVE",+ "description": "create opening balance journal",+ "paramCount": 2,+ "serviceParams": [+ "client",+ "args"+ ],+ "injectAuth": [+ "companyId",+ "createdBy",+ "updatedBy"+ ],+ "schema": {+ "type": "object",+ "properties": {+ "postingDate": {+ "type": "string"+ },+ "balances": {}+ },+ "required": [+ "postingDate",+ "balances"+ ]+ }+ },{"name": "accounting_reverseJournalEntry","module": "accounting",diff --git a/apps/erp/app/routes/x+/accounting+/charts.tsx b/apps/erp/app/routes/x+/accounting+/charts.tsxindex ba81fa9db2..b804f1f514 100644--- a/apps/erp/app/routes/x+/accounting+/charts.tsx+++ b/apps/erp/app/routes/x+/accounting+/charts.tsx@@ -1,18 +1,24 @@-import { error } from "@carbon/auth";+import { assertIsPost, error, success } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";+import { validationError, validator } from "@carbon/form";import { VStack } from "@carbon/react";import { msg } from "@lingui/core/macro";-import { useState } from "react";-import type { LoaderFunctionArgs } from "react-router";-import { Outlet, redirect, useLoaderData } from "react-router";+import { useMemo, useState } from "react";+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";+import { data, Outlet, redirect, useLoaderData } from "react-router";+import { usePermissions, useSettings } from "~/hooks";import type { Chart } from "~/modules/accounting";import {+ createOpeningBalanceJournal,getChartOfAccounts,- getFiscalYearSettings+ getExistingOpeningBalanceEntry,+ getFiscalYearSettings,+ openingBalanceValidator} from "~/modules/accounting";import { ChartOfAccountsTree } from "~/modules/accounting/ui/ChartOfAccounts";import ChartOfAccountsTableFilters from "~/modules/accounting/ui/ChartOfAccounts/ChartOfAccountsTableFilters";+import OpeningBalancePostModal from "~/modules/accounting/ui/ChartOfAccounts/OpeningBalancePostModal";import { months } from "~/modules/shared";import type { Handle } from "~/utils/handle";import { path } from "~/utils/path";@@ -41,14 +47,16 @@ export async function loader({ request }: LoaderFunctionArgs) {const startDate = searchParams.get("startDate") || null;const endDate = searchParams.get("endDate") || null;- const [chartOfAccounts, fiscalYearSettings] = await Promise.all([- getChartOfAccounts(client, companyGroupId, {- incomeBalance: null,- startDate,- endDate- }),- getFiscalYearSettings(client, companyId)- ]);+ const [chartOfAccounts, fiscalYearSettings, existingOpeningBalance] =+ await Promise.all([+ getChartOfAccounts(client, companyGroupId, {+ incomeBalance: null,+ startDate,+ endDate+ }),+ getFiscalYearSettings(client, companyId),+ getExistingOpeningBalanceEntry(client, companyId)+ ]);if (chartOfAccounts.error) {throw redirect(@@ -63,13 +71,92 @@ export async function loader({ request }: LoaderFunctionArgs) {return {chartOfAccounts: (chartOfAccounts.data ?? []) as Chart[],fiscalStartMonth:- months.indexOf(fiscalYearSettings.data?.startMonth ?? "January") + 1+ months.indexOf(fiscalYearSettings.data?.startMonth ?? "January") + 1,+ hasOpeningBalance: existingOpeningBalance.data !== null};}+export async function action({ request }: ActionFunctionArgs) {+ assertIsPost(request);+ const { client, companyId, companyGroupId, userId } =+ await requirePermissions(request, {+ create: "accounting"+ });++ const formData = await request.formData();+ const validation = await validator(openingBalanceValidator).validate(+ formData+ );++ if (validation.error) {+ return validationError(validation.error);+ }++ // The re-entry guard (and the "already posted" message) lives in+ // createOpeningBalanceJournal so every caller is protected; the loader hides+ // the entry button when one exists, so this is just the backstop.+ const result = await createOpeningBalanceJournal(client, {+ companyId,+ companyGroupId,+ userId,+ postingDate: validation.data.postingDate,+ balances: validation.data.lines+ });++ if (result.error || !result.data) {+ return data(+ {},+ await flash(+ request,+ error(result.error, "Failed to post opening balances")+ )+ );+ }++ throw redirect(+ path.to.journalEntry(result.data.id),+ await flash(request, success("Opening balances posted"))+ );+}+export default function ChartOfAccountsRoute() {- const { chartOfAccounts, fiscalStartMonth } = useLoaderData<typeof loader>();+ const { chartOfAccounts, fiscalStartMonth, hasOpeningBalance } =+ useLoaderData<typeof loader>();+ const permissions = usePermissions();+ const settings = useSettings();+ const accountingEnabled = (settings as { accountingEnabled?: boolean })+ .accountingEnabled;+const [search, setSearch] = useState("");+ const [openingBalanceMode, setOpeningBalanceMode] = useState(false);+ const [amounts, setAmounts] = useState<Record<string, number>>({});+ const [postModalOpen, setPostModalOpen] = useState(false);++ const canEnterOpeningBalances =+ Boolean(accountingEnabled) &&+ permissions.can("create", "accounting") &&+ !hasOpeningBalance;++ const enteredCount = useMemo(+ () => Object.values(amounts).filter((amount) => amount).length,+ [amounts]+ );++ const linesJson = useMemo(+ () =>+ JSON.stringify(+ Object.entries(amounts)+ .filter(([, amount]) => amount)+ .map(([accountId, amount]) => ({ accountId, amount }))+ ),+ [amounts]+ );++ const exitOpeningBalanceMode = () => {+ setOpeningBalanceMode(false);+ setAmounts({});+ setPostModalOpen(false);+ };return (<VStack spacing={0} className="h-full">@@ -77,9 +164,29 @@ export default function ChartOfAccountsRoute() {fiscalStartMonth={fiscalStartMonth}search={search}onSearchChange={setSearch}+ openingBalanceMode={openingBalanceMode}+ canEnterOpeningBalances={canEnterOpeningBalances}+ hasOpeningBalanceEntries={enteredCount > 0}+ onEnterOpeningBalances={() => setOpeningBalanceMode(true)}+ onCancelOpeningBalances={exitOpeningBalanceMode}+ onPostOpeningBalances={() => setPostModalOpen(true)}+ />+ <ChartOfAccountsTree+ data={chartOfAccounts}+ search={search}+ openingBalanceMode={openingBalanceMode}+ amounts={amounts}+ onAmountChange={(accountId, value) =>+ setAmounts((prev) => ({ ...prev, [accountId]: value }))+ }/>- <ChartOfAccountsTree data={chartOfAccounts} search={search} /><Outlet />+ <OpeningBalancePostModal+ open={postModalOpen}+ onClose={() => setPostModalOpen(false)}+ linesJson={linesJson}+ count={enteredCount}+ /></VStack>);}diff --git a/apps/erp/app/routes/x+/templates+/_layout.tsx b/apps/erp/app/routes/x+/templates+/_layout.tsxindex 9304d335e9..aae919bbde 100644--- a/apps/erp/app/routes/x+/templates+/_layout.tsx+++ b/apps/erp/app/routes/x+/templates+/_layout.tsx@@ -16,7 +16,7 @@ export const handle: Handle = {export default function TemplatesRoute() {return (- <div className="h-full w-full bg-background">+ <div className="h-full w-full bg-card"><Outlet /></div>);diff --git a/packages/database/src/swagger-docs-schema.ts b/packages/database/src/swagger-docs-schema.tsindex 65f0b1cb89..257a5984e3 100644--- a/packages/database/src/swagger-docs-schema.ts+++ b/packages/database/src/swagger-docs-schema.ts@@ -104493,7 +104493,8 @@ export default {"Credit Memo","Debit Memo","Non-Conformance",- "Inbound Inspection"+ "Inbound Inspection",+ "Opening Balance"],format: 'public."journalEntrySourceType"',type: "string"@@ -106285,7 +106286,7 @@ export default {properties: {id: {description:- "Note:\nThis is a Primary Key.<pk/>\nThis is a Foreign Key to `supplierLocation.id`.<fk table='supplierLocation' column='id'/>",+ "Note:\nThis is a Foreign Key to `supplierLocation.id`.<fk table='supplierLocation' column='id'/>",format: "text",type: "string"},@@ -106334,7 +106335,7 @@ export default {},supplierLocationId: {description:- "Note:\nThis is a Foreign Key to `supplierLocation.id`.<fk table='supplierLocation' column='id'/>",+ "Note:\nThis is a Primary Key.<pk/>\nThis is a Foreign Key to `supplierLocation.id`.<fk table='supplierLocation' column='id'/>",format: "text",type: "string"},@@ -116085,7 +116086,8 @@ export default {"Credit Memo","Debit Memo","Non-Conformance",- "Inbound Inspection"+ "Inbound Inspection",+ "Opening Balance"],format: 'public."journalEntrySourceType"',type: "string"@@ -128653,7 +128655,8 @@ export default {"Credit Memo","Debit Memo","Non-Conformance",- "Inbound Inspection"+ "Inbound Inspection",+ "Opening Balance"],format: 'public."journalEntrySourceType"',type: "string"diff --git a/packages/database/src/types.ts b/packages/database/src/types.tsindex 3694122401..74e28b91b0 100644--- a/packages/database/src/types.ts+++ b/packages/database/src/types.ts@@ -68308,14 +68308,14 @@ export type Database = {},{foreignKeyName: "partner_id_fkey"- columns: ["supplierLocationId"]+ columns: ["id"]isOneToOne: falsereferencedRelation: "supplierLocation"referencedColumns: ["id"]},{foreignKeyName: "partner_id_fkey"- columns: ["id"]+ columns: ["supplierLocationId"]isOneToOne: falsereferencedRelation: "supplierLocation"referencedColumns: ["id"]@@ -73397,21 +73397,21 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey"- columns: ["invoiceCountryCode"]+ columns: ["customerCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["customerCountryCode"]+ columns: ["shipmentCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["shipmentCountryCode"]+ columns: ["invoiceCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]@@ -80329,6 +80329,7 @@ export type Database = {| "Debit Memo"| "Non-Conformance"| "Inbound Inspection"+ | "Opening Balance"journalEntryStatus: "Draft" | "Posted" | "Reversed"journalLineDocumentType:| "Receipt"@@ -81733,6 +81734,7 @@ export const Constants = {"Debit Memo","Non-Conformance","Inbound Inspection",+ "Opening Balance",],journalEntryStatus: ["Draft", "Posted", "Reversed"],journalLineDocumentType: [diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.tsindex 3694122401..74e28b91b0 100644--- a/packages/database/supabase/functions/lib/types.ts+++ b/packages/database/supabase/functions/lib/types.ts@@ -68308,14 +68308,14 @@ export type Database = {},{foreignKeyName: "partner_id_fkey"- columns: ["supplierLocationId"]+ columns: ["id"]isOneToOne: falsereferencedRelation: "supplierLocation"referencedColumns: ["id"]},{foreignKeyName: "partner_id_fkey"- columns: ["id"]+ columns: ["supplierLocationId"]isOneToOne: falsereferencedRelation: "supplierLocation"referencedColumns: ["id"]@@ -73397,21 +73397,21 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey"- columns: ["invoiceCountryCode"]+ columns: ["customerCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["customerCountryCode"]+ columns: ["shipmentCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["shipmentCountryCode"]+ columns: ["invoiceCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]@@ -80329,6 +80329,7 @@ export type Database = {| "Debit Memo"| "Non-Conformance"| "Inbound Inspection"+ | "Opening Balance"journalEntryStatus: "Draft" | "Posted" | "Reversed"journalLineDocumentType:| "Receipt"@@ -81733,6 +81734,7 @@ export const Constants = {"Debit Memo","Non-Conformance","Inbound Inspection",+ "Opening Balance",],journalEntryStatus: ["Draft", "Posted", "Reversed"],journalLineDocumentType: [diff --git a/packages/database/supabase/migrations/20260901165008_opening-balance-source-type.sql b/packages/database/supabase/migrations/20260901165008_opening-balance-source-type.sqlnew file mode 100644index 0000000000..19c743e749--- /dev/null+++ b/packages/database/supabase/migrations/20260901165008_opening-balance-source-type.sql@@ -0,0 +1,5 @@+-- Opening Balances tool posts a manual-style GL entry tagged with this source+-- type. ADD VALUE only; no column/usage change. Idempotent for the retrying+-- deploy runner. Postgres disallows using a newly-added enum value later in the+-- same transaction, but this migration only adds it, so it is fine.+ALTER TYPE "journalEntrySourceType" ADD VALUE IF NOT EXISTS 'Opening Balance';diff --git a/packages/database/supabase/migrations/20260903021115_opening-balance-unique-posted.sql b/packages/database/supabase/migrations/20260903021115_opening-balance-unique-posted.sqlnew file mode 100644index 0000000000..d254ea9bdf--- /dev/null+++ b/packages/database/supabase/migrations/20260903021115_opening-balance-unique-posted.sql@@ -0,0 +1,13 @@+-- At most one Posted 'Opening Balance' journal per company, enforced atomically.+-- This closes the check-then-post race: the app guards by reading for an existing+-- Posted entry before posting, but concurrent browser/MCP requests could both+-- pass that check. The partial unique index makes the second flip-to-Posted fail+-- with a unique violation instead (the service rolls its Draft back and surfaces+-- the "already exists" message).+--+-- A reversed opening-balance entry has status='Reversed' (its reversing entry is+-- sourceType='Manual'), so it drops out of this partial index — a fresh set can+-- be posted after a reversal, which is the intended re-entry flow.+CREATE UNIQUE INDEX IF NOT EXISTS "journal_one_posted_opening_balance_per_company"+ ON "journal" ("companyId")+ WHERE "sourceType" = 'Opening Balance' AND "status" = 'Posted';diff --git a/packages/ee/src/accounting/core/models.ts b/packages/ee/src/accounting/core/models.tsindex 33a4d2fa64..2b820d1500 100644--- a/packages/ee/src/accounting/core/models.ts+++ b/packages/ee/src/accounting/core/models.ts@@ -308,6 +308,16 @@ export const POSTING_POLICY: Record<defaultEnabled: false,defaultGranularity: "individual"},+ // Opening balances are a one-time setup artifact that touches arbitrary+ // accounts; the external ledger owns its own opening balances (connecting a+ // provider brings theirs), so Carbon's opening-balance journal NEVER syncs —+ // same policy as Manual, to avoid double-counting.+ "Opening Balance": {+ representation: "journal",+ syncable: false,+ defaultEnabled: false,+ defaultGranularity: "individual"+ },"Purchase Receipt": {representation: "journal",defaultEnabled: true,diff --git a/packages/locale/locales/de/erp.po b/packages/locale/locales/de/erp.poindex d1d71214e4..21a3dd9186 100644--- a/packages/locale/locales/de/erp.po+++ b/packages/locale/locales/de/erp.po@@ -201,6 +201,9 @@ msgstr "{chainLabel}. Erwägen Sie, diesen Teil direkt auf den endgültigen Nachmsgid "{conflictCount} conflicts"msgstr "{conflictCount} Konflikte"+msgid "{count, plural, one {# account with a balance} other {# accounts with a balance}}"+msgstr "{count, plural, one {# Konto mit einem Saldo} other {# Konten mit Salden}}"+msgid "{count, plural, one {# course} other {# courses}}"msgstr "{count, plural, one {# Kurs} other {# Kurse}}"@@ -830,6 +833,9 @@ msgstr "Der Status einer Lieferung ändert sich"msgid "A shipment's tracking number changes"msgstr "Die Verfolgungsnummer einer Lieferung ändert sich"+msgid "A single balanced journal entry will be posted as of the date below, with the difference offset to Retained Earnings."+msgstr "Ein einzelner ausgeglichener Buchungssatz wird zum unten angegebenen Datum gebucht, wobei die Differenz auf den Gewinnvortrag verrechnet wird."+msgid "A step needs a name."msgstr "Ein Schritt benötigt einen Namen."@@ -2288,6 +2294,9 @@ msgstr "Zum Stand von"msgid "As of {0}"msgstr "Zum Stand von {0}"+msgid "As of date"+msgstr "Zum Datum"+msgid "As of:"msgstr "Zum Stand von:"@@ -11119,9 +11128,19 @@ msgstr "Eröffnung"msgid "Opening an operation starts its timer, so time is tracked from the moment work begins."msgstr "Das Öffnen einer Operation startet seinen Timer, sodass die Zeit vom Moment des Arbeitsbeginn verfolgt wird."+msgid "Opening Balance"+msgstr "Eröffnungssaldo"++#. placeholder {0}: account.name+msgid "Opening balance for {0}"+msgstr "Eröffnungssaldo für {0}"+msgid "Opening balance of depreciation already booked before this asset was added to Carbon (use 0 for new acquisitions)."msgstr "Eröffnungssaldo der bereits vor dem Hinzufügen dieses Vermögenswerts zu Carbon gebuchten Abschreibung (für neue Akquisitionen 0 verwenden)."+msgid "Opening Balances"+msgstr "Eröffnungssalden"+msgid "Operating Expenses"msgstr "Betriebsaufwendungen"@@ -11873,6 +11892,9 @@ msgstr "Rechnung buchen"msgid "Post journal entries with proper account and description codes"msgstr "Buchen Sie Buchungssätze mit korrekten Konto- und Beschreibungscodes."+msgid "Post opening balances"+msgstr "Eröffnungssalden buchen"+msgid "Post Receipt"msgstr "Beleg buchen"diff --git a/packages/locale/locales/en/erp.po b/packages/locale/locales/en/erp.poindex 51809f174b..fd64fdb523 100644--- a/packages/locale/locales/en/erp.po+++ b/packages/locale/locales/en/erp.po@@ -201,6 +201,9 @@ msgstr "{chainLabel}. Consider pointing this part directly at the final successomsgid "{conflictCount} conflicts"msgstr "{conflictCount} conflicts"+msgid "{count, plural, one {# account with a balance} other {# accounts with a balance}}"+msgstr "{count, plural, one {# account with a balance} other {# accounts with a balance}}"+msgid "{count, plural, one {# course} other {# courses}}"msgstr "{count, plural, one {# course} other {# courses}}"@@ -830,6 +833,9 @@ msgstr "A shipment's status changes"msgid "A shipment's tracking number changes"msgstr "A shipment's tracking number changes"+msgid "A single balanced journal entry will be posted as of the date below, with the difference offset to Retained Earnings."+msgstr "A single balanced journal entry will be posted as of the date below, with the difference offset to Retained Earnings."+msgid "A step needs a name."msgstr "A step needs a name."@@ -2288,6 +2294,9 @@ msgstr "As of"msgid "As of {0}"msgstr "As of {0}"+msgid "As of date"+msgstr "As of date"+msgid "As of:"msgstr "As of:"@@ -11119,9 +11128,19 @@ msgstr "Opening"msgid "Opening an operation starts its timer, so time is tracked from the moment work begins."msgstr "Opening an operation starts its timer, so time is tracked from the moment work begins."+msgid "Opening Balance"+msgstr "Opening Balance"++#. placeholder {0}: account.name+msgid "Opening balance for {0}"+msgstr "Opening balance for {0}"+msgid "Opening balance of depreciation already booked before this asset was added to Carbon (use 0 for new acquisitions)."msgstr "Opening balance of depreciation already booked before this asset was added to Carbon (use 0 for new acquisitions)."+msgid "Opening Balances"+msgstr "Opening Balances"+msgid "Operating Expenses"msgstr "Operating Expenses"@@ -11873,6 +11892,9 @@ msgstr "Post Invoice"msgid "Post journal entries with proper account and description codes"msgstr "Post journal entries with proper account and description codes"+msgid "Post opening balances"+msgstr "Post opening balances"+msgid "Post Receipt"msgstr "Post Receipt"diff --git a/packages/locale/locales/es/erp.po b/packages/locale/locales/es/erp.poindex be1c1495f9..3594ebe374 100644--- a/packages/locale/locales/es/erp.po+++ b/packages/locale/locales/es/erp.po@@ -201,6 +201,9 @@ msgstr "{chainLabel}. Considere apuntar esta pieza directamente al sucesor finalmsgid "{conflictCount} conflicts"msgstr "{conflictCount} conflictos"+msgid "{count, plural, one {# account with a balance} other {# accounts with a balance}}"+msgstr "{count, plural, one {# cuenta con saldo} other {# cuentas con saldo}}"+msgid "{count, plural, one {# course} other {# courses}}"msgstr "{count, plural, one {# curso} other {# cursos}}"@@ -830,6 +833,9 @@ msgstr "El estado de un envío cambia"msgid "A shipment's tracking number changes"msgstr "El número de seguimiento de un envío cambia"+msgid "A single balanced journal entry will be posted as of the date below, with the difference offset to Retained Earnings."+msgstr "Se contabilizará un apunte equilibrado a la fecha indicada, con la diferencia compensada en Resultados acumulados."+msgid "A step needs a name."msgstr "Un paso necesita un nombre."@@ -2288,6 +2294,9 @@ msgstr "A partir de"msgid "As of {0}"msgstr "A partir de {0}"+msgid "As of date"+msgstr "A la fecha"+msgid "As of:"msgstr "A partir de:"@@ -11119,9 +11128,19 @@ msgstr "Apertura"msgid "Opening an operation starts its timer, so time is tracked from the moment work begins."msgstr "Abrir una operación inicia su cronómetro, por lo que el tiempo se registra desde el momento en que comienza el trabajo."+msgid "Opening Balance"+msgstr "Saldo de apertura"++#. placeholder {0}: account.name+msgid "Opening balance for {0}"+msgstr "Saldo de apertura de {0}"+msgid "Opening balance of depreciation already booked before this asset was added to Carbon (use 0 for new acquisitions)."msgstr "Saldo de apertura de la depreciación ya contabilizada antes de que este activo se agregara a Carbon (use 0 para nuevas adquisiciones)."+msgid "Opening Balances"+msgstr "Saldos de apertura"+msgid "Operating Expenses"msgstr "Gastos Operativos"@@ -11873,6 +11892,9 @@ msgstr "Registrar Factura"msgid "Post journal entries with proper account and description codes"msgstr "Registrar asientos de diario con códigos de cuenta y descripción adecuados"+msgid "Post opening balances"+msgstr "Contabilizar saldos de apertura"+msgid "Post Receipt"msgstr "Registrar Recepción"diff --git a/packages/locale/locales/fr/erp.po b/packages/locale/locales/fr/erp.poindex e04a087486..3fcf35e20b 100644--- a/packages/locale/locales/fr/erp.po+++ b/packages/locale/locales/fr/erp.po@@ -201,6 +201,9 @@ msgstr "{chainLabel}. Envisagez de pointer cette pièce directement vers le succmsgid "{conflictCount} conflicts"msgstr "{conflictCount} conflits"+msgid "{count, plural, one {# account with a balance} other {# accounts with a balance}}"+msgstr "{count, plural, one {# compte avec un solde} other {# comptes avec un solde}}"+msgid "{count, plural, one {# course} other {# courses}}"msgstr "{count, plural, one {# cours} other {# cours}}"@@ -830,6 +833,9 @@ msgstr "Le statut d'une expédition change"msgid "A shipment's tracking number changes"msgstr "Le numéro de suivi d'une expédition change"+msgid "A single balanced journal entry will be posted as of the date below, with the difference offset to Retained Earnings."+msgstr "Une seule ligne d'écriture équilibrée sera comptabilisée à la date indiquée ci-dessous, la différence étant imputée au Report à nouveau."+msgid "A step needs a name."msgstr "Une étape doit avoir un nom."@@ -2288,6 +2294,9 @@ msgstr "Au"msgid "As of {0}"msgstr "Au {0}"+msgid "As of date"+msgstr "Date de référence"+msgid "As of:"msgstr "Au :"@@ -11119,9 +11128,19 @@ msgstr "Ouverture"msgid "Opening an operation starts its timer, so time is tracked from the moment work begins."msgstr "Ouvrir une opération démarre son chronomètre, donc le temps est suivi à partir du moment où le travail commence."+msgid "Opening Balance"+msgstr "Solde d'ouverture"++#. placeholder {0}: account.name+msgid "Opening balance for {0}"+msgstr "Solde d'ouverture pour {0}"+msgid "Opening balance of depreciation already booked before this asset was added to Carbon (use 0 for new acquisitions)."msgstr "Solde d'ouverture de l'amortissement déjà comptabilisé avant l'ajout de cet actif à Carbon (utilisez 0 pour les nouvelles acquisitions)."+msgid "Opening Balances"+msgstr "Soldes d'ouverture"+msgid "Operating Expenses"msgstr "Charges d'exploitation"@@ -11873,6 +11892,9 @@ msgstr "Valider la facture"msgid "Post journal entries with proper account and description codes"msgstr "Enregistrer les écritures de journal avec les codes de compte et de description appropriés"+msgid "Post opening balances"+msgstr "Comptabiliser les soldes d'ouverture"+msgid "Post Receipt"msgstr "Valider le reçu"diff --git a/packages/locale/locales/hi/erp.po b/packages/locale/locales/hi/erp.poindex d0821b94f5..8c293f0f3e 100644--- a/packages/locale/locales/hi/erp.po+++ b/packages/locale/locales/hi/erp.po@@ -201,6 +201,9 @@ msgstr "{chainLabel}. इस भाग को सीधे अंतिम उmsgid "{conflictCount} conflicts"msgstr "{conflictCount} विरोध"+msgid "{count, plural, one {# account with a balance} other {# accounts with a balance}}"+msgstr "{count, plural, one {# शेष राशि वाला खाता} other {# शेष राशि वाले खाते}}"+msgid "{count, plural, one {# course} other {# courses}}"msgstr "{count, plural, one {# कोर्स} other {# कोर्स}}"@@ -830,6 +833,9 @@ msgstr "किसी शिपमेंट की स्थिति मेंmsgid "A shipment's tracking number changes"msgstr "एक शिपमेंट का ट्रैकिंग नंबर बदल जाता है"+msgid "A single balanced journal entry will be posted as of the date below, with the difference offset to Retained Earnings."+msgstr "एक संतुलित जर्नल प्रविष्टि नीचे दी गई तारीख के अनुसार पोस्ट की जाएगी, अंतर को प्रतिधारित आय में समायोजित करते हुए।"+msgid "A step needs a name."msgstr "एक चरण को एक नाम की आवश्यकता है।"@@ -2288,6 +2294,9 @@ msgstr "के अनुसार"msgid "As of {0}"msgstr "{0} के अनुसार"+msgid "As of date"+msgstr "तारीख के अनुसार"+msgid "As of:"msgstr "इसके अनुसार:"@@ -11119,9 +11128,19 @@ msgstr "शुरुआती"msgid "Opening an operation starts its timer, so time is tracked from the moment work begins."msgstr "किसी ऑपरेशन को खोलने से इसका टाइमर शुरू हो जाता है, इसलिए काम शुरू होने के समय से समय ट्रैक किया जाता है।"+msgid "Opening Balance"+msgstr "प्रारंभिक शेष राशि"++#. placeholder {0}: account.name+msgid "Opening balance for {0}"+msgstr "{0} की प्रारंभिक शेष राशि"+msgid "Opening balance of depreciation already booked before this asset was added to Carbon (use 0 for new acquisitions)."msgstr "इस संपत्ति को Carbon में जोड़े जाने से पहले दर्ज मूल्यह्रास का प्रारंभिक शेष (नई खरीद के लिए 0 का उपयोग करें)।"+msgid "Opening Balances"+msgstr "प्रारंभिक शेष राशि"+msgid "Operating Expenses"msgstr "परिचालन व्यय"@@ -11873,6 +11892,9 @@ msgstr "चालान पोस्ट करें"msgid "Post journal entries with proper account and description codes"msgstr "उचित खाता और विवरण कोड के साथ जर्नल प्रविष्टियां पोस्ट करें"+msgid "Post opening balances"+msgstr "प्रारंभिक शेष राशि पोस्ट करें"+msgid "Post Receipt"msgstr "रसीद पोस्ट करें"diff --git a/packages/locale/locales/it/erp.po b/packages/locale/locales/it/erp.poindex e2b3601561..23e89da6f6 100644--- a/packages/locale/locales/it/erp.po+++ b/packages/locale/locales/it/erp.po@@ -201,6 +201,9 @@ msgstr "{chainLabel}. Considera di indirizzare direttamente questa parte al succmsgid "{conflictCount} conflicts"msgstr "{conflictCount} conflitti"+msgid "{count, plural, one {# account with a balance} other {# accounts with a balance}}"+msgstr "{count, plural, one {# conto con saldo} other {# conti con saldo}}"+msgid "{count, plural, one {# course} other {# courses}}"msgstr "{count, plural, one {# corso} other {# corsi}}"@@ -830,6 +833,9 @@ msgstr "Lo stato della spedizione cambia"msgid "A shipment's tracking number changes"msgstr "Il numero di tracciamento di una spedizione cambia"+msgid "A single balanced journal entry will be posted as of the date below, with the difference offset to Retained Earnings."+msgstr "Una singola riga di registrazione bilanciata sarà registrata alla data indicata di seguito, con la differenza compensata agli Utili non distribuiti."+msgid "A step needs a name."msgstr "Un passaggio ha bisogno di un nome."@@ -2288,6 +2294,9 @@ msgstr "Al"msgid "As of {0}"msgstr "Al {0}"+msgid "As of date"+msgstr "Data al"+msgid "As of:"msgstr "A partire da:"@@ -11119,9 +11128,19 @@ msgstr "Apertura"msgid "Opening an operation starts its timer, so time is tracked from the moment work begins."msgstr "L'apertura di un'operazione avvia il suo timer, quindi il tempo viene tracciato dal momento in cui inizia il lavoro."+msgid "Opening Balance"+msgstr "Saldo iniziale"++#. placeholder {0}: account.name+msgid "Opening balance for {0}"+msgstr "Saldo iniziale per {0}"+msgid "Opening balance of depreciation already booked before this asset was added to Carbon (use 0 for new acquisitions)."msgstr "Saldo di apertura dell'ammortamento già contabilizzato prima dell'aggiunta di questo asset a Carbon (utilizzare 0 per le nuove acquisizioni)."+msgid "Opening Balances"+msgstr "Saldi iniziali"+msgid "Operating Expenses"msgstr "Spese Operative"@@ -11873,6 +11892,9 @@ msgstr "Registra Fattura"msgid "Post journal entries with proper account and description codes"msgstr "Registra inserimenti della prima nota con codici di conto e descrizione appropriati"+msgid "Post opening balances"+msgstr "Registra saldi iniziali"+msgid "Post Receipt"msgstr "Registra Ricevuta"diff --git a/packages/locale/locales/ja/erp.po b/packages/locale/locales/ja/erp.poindex 790f616756..3ba507cdb7 100644--- a/packages/locale/locales/ja/erp.po+++ b/packages/locale/locales/ja/erp.po@@ -201,6 +201,9 @@ msgstr "{chainLabel}。この部品を最終的な後継品目に直接ポインmsgid "{conflictCount} conflicts"msgstr "{conflictCount} 個の競合"+msgid "{count, plural, one {# account with a balance} other {# accounts with a balance}}"+msgstr "{count, plural, one {# 件の残高のある勘定} other {# 件の残高のある勘定}}"+msgid "{count, plural, one {# course} other {# courses}}"msgstr "{count, plural, one {# コース} other {# コース}}"@@ -830,6 +833,9 @@ msgstr "出荷のステータスが変更される"msgid "A shipment's tracking number changes"msgstr "出荷の追跡番号が変更される"+msgid "A single balanced journal entry will be posted as of the date below, with the difference offset to Retained Earnings."+msgstr "1 つの仕訳行が以下の日付で転記され、差分が利益剰余金にオフセットされます。"+msgid "A step needs a name."msgstr "ステップには名前が必要です。"@@ -2288,6 +2294,9 @@ msgstr "現在時点で"msgid "As of {0}"msgstr "{0}時点で"+msgid "As of date"+msgstr "対象日付"+msgid "As of:"msgstr "以下の日付時点:"@@ -11119,9 +11128,19 @@ msgstr "開始残高"msgid "Opening an operation starts its timer, so time is tracked from the moment work begins."msgstr "操作を開くとそのタイマーが開始され、作業開始時点から時間が追跡されます。"+msgid "Opening Balance"+msgstr "初期残高"++#. placeholder {0}: account.name+msgid "Opening balance for {0}"+msgstr "{0}の初期残高"+msgid "Opening balance of depreciation already booked before this asset was added to Carbon (use 0 for new acquisitions)."msgstr "このアセットがCarbonに追加される前に既に予約されていた減価償却の期首残高(新規取得の場合は0を使用してください)。"+msgid "Opening Balances"+msgstr "初期残高"+msgid "Operating Expenses"msgstr "営業費用"@@ -11873,6 +11892,9 @@ msgstr "請求書を転記"msgid "Post journal entries with proper account and description codes"msgstr "適切なアカウントと説明コードを使用して仕訳を転記する"+msgid "Post opening balances"+msgstr "初期残高を転記"+msgid "Post Receipt"msgstr "領収書を転記"diff --git a/packages/locale/locales/ko/erp.po b/packages/locale/locales/ko/erp.poindex 3681971e74..8b78860b64 100644--- a/packages/locale/locales/ko/erp.po+++ b/packages/locale/locales/ko/erp.po@@ -201,6 +201,9 @@ msgstr "{chainLabel}. 이 품목을 최종 후속 품목으로 직접 연결하msgid "{conflictCount} conflicts"msgstr "{conflictCount}개 충돌"+msgid "{count, plural, one {# account with a balance} other {# accounts with a balance}}"+msgstr "{count, plural, one {# 잔액이 있는 계정} other {# 잔액이 있는 계정}}"+msgid "{count, plural, one {# course} other {# courses}}"msgstr "교육과정 {count}개"@@ -830,6 +833,9 @@ msgstr "출하의 상태가 변경됨"msgid "A shipment's tracking number changes"msgstr "출하의 추적 번호가 변경됨"+msgid "A single balanced journal entry will be posted as of the date below, with the difference offset to Retained Earnings."+msgstr "하나의 균형잡힌 분개가 아래의 날짜로 전기되며, 차액은 이익잉여금으로 상계됩니다."+msgid "A step needs a name."msgstr "단계에 이름이 필요합니다."@@ -2288,6 +2294,9 @@ msgstr "기준"msgid "As of {0}"msgstr "{0} 기준"+msgid "As of date"+msgstr "기준일"+msgid "As of:"msgstr "기준:"@@ -11119,9 +11128,19 @@ msgstr "기초"msgid "Opening an operation starts its timer, so time is tracked from the moment work begins."msgstr "작업을 열면 타이머가 시작되므로 작업이 시작되는 순간부터 시간이 추적됩니다."+msgid "Opening Balance"+msgstr "개시잔액"++#. placeholder {0}: account.name+msgid "Opening balance for {0}"+msgstr "{0}의 개시잔액"+msgid "Opening balance of depreciation already booked before this asset was added to Carbon (use 0 for new acquisitions)."msgstr "이 자산이 Carbon에 등록되기 전에 이미 계상된 감가상각의 기초 잔액입니다(신규 취득 자산은 0을 사용하세요)."+msgid "Opening Balances"+msgstr "개시잔액"+msgid "Operating Expenses"msgstr "영업비용"@@ -11873,6 +11892,9 @@ msgstr "송장 전기"msgid "Post journal entries with proper account and description codes"msgstr "올바른 계정 및 설명 코드로 전표를 전기"+msgid "Post opening balances"+msgstr "개시잔액 전기"+msgid "Post Receipt"msgstr "입고 전기"diff --git a/packages/locale/locales/pl/erp.po b/packages/locale/locales/pl/erp.poindex af500148ce..1bd8b2f1a8 100644--- a/packages/locale/locales/pl/erp.po+++ b/packages/locale/locales/pl/erp.po@@ -201,6 +201,9 @@ msgstr "{chainLabel}. Rozważ wskazanie tej części bezpośrednio na ostatecznemsgid "{conflictCount} conflicts"msgstr "{conflictCount} konflikty"+msgid "{count, plural, one {# account with a balance} other {# accounts with a balance}}"+msgstr "{count, plural, one {# konto z saldem} other {# konta z saldem}}"+msgid "{count, plural, one {# course} other {# courses}}"msgstr "{count, plural, one {# kurs} other {# kursy}}"@@ -830,6 +833,9 @@ msgstr "Status wysyłki zmienia się"msgid "A shipment's tracking number changes"msgstr "Zmiana numeru śledzenia wysyłki"+msgid "A single balanced journal entry will be posted as of the date below, with the difference offset to Retained Earnings."+msgstr "Jeden zbilansowany zapis księgowy będzie zaksięgowany na dzień poniżej, z różnicą przeniesioną do Zysków zatrzymanych."+msgid "A step needs a name."msgstr "Krok wymaga nazwy."@@ -2288,6 +2294,9 @@ msgstr "Na dzień"msgid "As of {0}"msgstr "Od {0}"+msgid "As of date"+msgstr "Na dzień"+msgid "As of:"msgstr "Na dzień:"@@ -11119,9 +11128,19 @@ msgstr "Otwarcie"msgid "Opening an operation starts its timer, so time is tracked from the moment work begins."msgstr "Otwarcie operacji uruchamia jej timer, więc czas jest liczony od momentu, gdy praca się zaczyna."+msgid "Opening Balance"+msgstr "Saldo Otwarcia"++#. placeholder {0}: account.name+msgid "Opening balance for {0}"+msgstr "Saldo Otwarcia dla {0}"+msgid "Opening balance of depreciation already booked before this asset was added to Carbon (use 0 for new acquisitions)."msgstr "Saldo otwarcia amortyzacji już zaksięgowanej przed dodaniem tego zasobu do Carbon (użyj 0 dla nowych przejęć)."+msgid "Opening Balances"+msgstr "Salda Otwarcia"+msgid "Operating Expenses"msgstr "Koszty operacyjne"@@ -11873,6 +11892,9 @@ msgstr "Zaksięguj fakturę"msgid "Post journal entries with proper account and description codes"msgstr "Zaksięguj wpisy dowodu księgowego z odpowiednimi kodami konta i opisu"+msgid "Post opening balances"+msgstr "Zaksięguj salda otwarcia"+msgid "Post Receipt"msgstr "Zaksięguj Paragon"diff --git a/packages/locale/locales/pt/erp.po b/packages/locale/locales/pt/erp.poindex bd2aa7aed2..3c0fc2b03b 100644--- a/packages/locale/locales/pt/erp.po+++ b/packages/locale/locales/pt/erp.po@@ -201,6 +201,9 @@ msgstr "{chainLabel}. Considere apontar esta peça diretamente para o sucessor fmsgid "{conflictCount} conflicts"msgstr "{conflictCount} conflitos"+msgid "{count, plural, one {# account with a balance} other {# accounts with a balance}}"+msgstr "{count, plural, one {# conta com saldo} other {# contas com saldo}}"+msgid "{count, plural, one {# course} other {# courses}}"msgstr "{count, plural, one {# curso} other {# cursos}}"@@ -830,6 +833,9 @@ msgstr "O status da remessa muda"msgid "A shipment's tracking number changes"msgstr "O número de rastreamento de uma remessa muda"+msgid "A single balanced journal entry will be posted as of the date below, with the difference offset to Retained Earnings."+msgstr "Um único lançamento equilibrado será contabilizado na data abaixo, com a diferença compensada em Lucros acumulados."+msgid "A step needs a name."msgstr "Uma etapa precisa de um nome."@@ -2288,6 +2294,9 @@ msgstr "A partir de"msgid "As of {0}"msgstr "A partir de {0}"+msgid "As of date"+msgstr "Na data de"+msgid "As of:"msgstr "A partir de:"@@ -11119,9 +11128,19 @@ msgstr "Abertura"msgid "Opening an operation starts its timer, so time is tracked from the moment work begins."msgstr "Abrir uma operação inicia seu temporizador, portanto o tempo é rastreado a partir do momento em que o trabalho começa."+msgid "Opening Balance"+msgstr "Saldo Inicial"++#. placeholder {0}: account.name+msgid "Opening balance for {0}"+msgstr "Saldo inicial para {0}"+msgid "Opening balance of depreciation already booked before this asset was added to Carbon (use 0 for new acquisitions)."msgstr "Saldo de abertura da depreciação já contabilizada antes de este ativo ser adicionado ao Carbon (use 0 para novas aquisições)."+msgid "Opening Balances"+msgstr "Saldos Iniciais"+msgid "Operating Expenses"msgstr "Despesas Operacionais"@@ -11873,6 +11892,9 @@ msgstr "Lançar Fatura"msgid "Post journal entries with proper account and description codes"msgstr "Registar entradas de diário com códigos de conta e descrição apropriados"+msgid "Post opening balances"+msgstr "Contabilizar saldos iniciais"+msgid "Post Receipt"msgstr "Lançar Recebimento"diff --git a/packages/locale/locales/ru/erp.po b/packages/locale/locales/ru/erp.poindex b831ef4b0e..a389adb367 100644--- a/packages/locale/locales/ru/erp.po+++ b/packages/locale/locales/ru/erp.po@@ -201,6 +201,9 @@ msgstr "{chainLabel}. Рассмотрите возможность указанmsgid "{conflictCount} conflicts"msgstr "{conflictCount} конфликтов"+msgid "{count, plural, one {# account with a balance} other {# accounts with a balance}}"+msgstr "{count, plural, one {# счет с остатком} other {# счетов с остатком}}"+msgid "{count, plural, one {# course} other {# courses}}"msgstr "{count, plural, one {# курс} other {# курсов}}"@@ -830,6 +833,9 @@ msgstr "Статус отгрузки изменился"msgid "A shipment's tracking number changes"msgstr "Номер отслеживания отгрузки изменился"+msgid "A single balanced journal entry will be posted as of the date below, with the difference offset to Retained Earnings."+msgstr "Одна сбалансированная проводка будет проведена на дату, указанную ниже, с разницей, отнесенной на счет нераспределенной прибыли."+msgid "A step needs a name."msgstr "Шаг должен иметь имя."@@ -2288,6 +2294,9 @@ msgstr "На дату"msgid "As of {0}"msgstr "По состоянию на {0}"+msgid "As of date"+msgstr "На дату"+msgid "As of:"msgstr "По состоянию на:"@@ -11119,9 +11128,19 @@ msgstr "Открытие"msgid "Opening an operation starts its timer, so time is tracked from the moment work begins."msgstr "Открытие операции запускает её таймер, поэтому время отсчитывается с момента начала работы."+msgid "Opening Balance"+msgstr "Начальный остаток"++#. placeholder {0}: account.name+msgid "Opening balance for {0}"+msgstr "Начальный остаток для {0}"+msgid "Opening balance of depreciation already booked before this asset was added to Carbon (use 0 for new acquisitions)."msgstr "Начальный остаток амортизации, уже учтенный до добавления этого актива в Carbon (используйте 0 для новых приобретений)."+msgid "Opening Balances"+msgstr "Начальные остатки"+msgid "Operating Expenses"msgstr "Операционные расходы"@@ -11873,6 +11892,9 @@ msgstr "Провести счет-фактуру"msgid "Post journal entries with proper account and description codes"msgstr "Проводите операции журнала с правильными кодами счетов и описания"+msgid "Post opening balances"+msgstr "Провести начальные остатки"+msgid "Post Receipt"msgstr "Отправить квитанцию"diff --git a/packages/locale/locales/tr/erp.po b/packages/locale/locales/tr/erp.poindex fc94cfc462..bfec4aca5e 100644--- a/packages/locale/locales/tr/erp.po+++ b/packages/locale/locales/tr/erp.po@@ -201,6 +201,9 @@ msgstr "{chainLabel}. Bu parçayı doğrudan nihai ardıla yönlendirmeyi düşmsgid "{conflictCount} conflicts"msgstr "{conflictCount} çakışma"+msgid "{count, plural, one {# account with a balance} other {# accounts with a balance}}"+msgstr "{count, plural, one {# bakiyesi olan hesap} other {# bakiyesi olan hesaplar}}"+msgid "{count, plural, one {# course} other {# courses}}"msgstr "{count, plural, one {# kurs} other {# kurs}}"@@ -830,6 +833,9 @@ msgstr "Sevkiyatın durumu değişti"msgid "A shipment's tracking number changes"msgstr "Bir sevkiyatın takip numarası değişti"+msgid "A single balanced journal entry will be posted as of the date below, with the difference offset to Retained Earnings."+msgstr "Aşağıdaki tarih itibarıyla tek bir dengeli yevmiye kaydı muhasebeleştirilecek; fark Dağıtılmamış kârlara kaydedilecektir."+msgid "A step needs a name."msgstr "Bir adım bir ada ihtiyaç duyuyor."@@ -2288,6 +2294,9 @@ msgstr "Itibaren"msgid "As of {0}"msgstr "{0} itibariyle"+msgid "As of date"+msgstr "Tarihi itibarıyla"+msgid "As of:"msgstr "Şu tarih itibariyle:"@@ -11119,9 +11128,19 @@ msgstr "Açılış"msgid "Opening an operation starts its timer, so time is tracked from the moment work begins."msgstr "Bir operasyonu açmak zamanlayıcısını başlatır, böylece zaman çalışma başladığı andan itibaren izlenir."+msgid "Opening Balance"+msgstr "Açılış Bakiyesi"++#. placeholder {0}: account.name+msgid "Opening balance for {0}"+msgstr "{0} için Açılış Bakiyesi"+msgid "Opening balance of depreciation already booked before this asset was added to Carbon (use 0 for new acquisitions)."msgstr "Bu varlık Carbon'a eklenmeden önce zaten deftere geçirilmiş amortismanın açılış bakiyesi (yeni satın almalar için 0 kullanın)."+msgid "Opening Balances"+msgstr "Açılış Bakiyeleri"+msgid "Operating Expenses"msgstr "İşletme Giderleri"@@ -11873,6 +11892,9 @@ msgstr "Faturayı Kaydet"msgid "Post journal entries with proper account and description codes"msgstr "Uygun hesap ve açıklama kodları ile muhasebe fişlerini muhasebeleştirin"+msgid "Post opening balances"+msgstr "Açılış Bakiyelerini Muhasebeleştir"+msgid "Post Receipt"msgstr "Makbuzu Kaydet"diff --git a/packages/locale/locales/zh/erp.po b/packages/locale/locales/zh/erp.poindex cd7dc632d5..00595e81bb 100644--- a/packages/locale/locales/zh/erp.po+++ b/packages/locale/locales/zh/erp.po@@ -201,6 +201,9 @@ msgstr "{chainLabel}。考虑直接将此零件指向最终后继物料。"msgid "{conflictCount} conflicts"msgstr "{conflictCount} 个冲突"+msgid "{count, plural, one {# account with a balance} other {# accounts with a balance}}"+msgstr "{count, plural, one {# 个有余额的账户} other {# 个有余额的账户}}"+msgid "{count, plural, one {# course} other {# courses}}"msgstr "{count, plural, one {# 门课程} other {# 门课程}}"@@ -830,6 +833,9 @@ msgstr "发货单的状态已更改"msgid "A shipment's tracking number changes"msgstr "发货的跟踪号变更"+msgid "A single balanced journal entry will be posted as of the date below, with the difference offset to Retained Earnings."+msgstr "一条平衡的分录将以下面的日期过账,差额冲至未分配利润。"+msgid "A step needs a name."msgstr "步骤需要一个名称。"@@ -2288,6 +2294,9 @@ msgstr "截至"msgid "As of {0}"msgstr "截至 {0}"+msgid "As of date"+msgstr "截至日期"+msgid "As of:"msgstr "截至:"@@ -11119,9 +11128,19 @@ msgstr "期初"msgid "Opening an operation starts its timer, so time is tracked from the moment work begins."msgstr "打开一个操作会启动其计时器,因此从工作开始时起就跟踪时间。"+msgid "Opening Balance"+msgstr "期初余额"++#. placeholder {0}: account.name+msgid "Opening balance for {0}"+msgstr "{0}的期初余额"+msgid "Opening balance of depreciation already booked before this asset was added to Carbon (use 0 for new acquisitions)."msgstr "在将此资产添加到Carbon之前已入账的折旧的期初余额(新购置的情况下使用0)。"+msgid "Opening Balances"+msgstr "期初余额"+msgid "Operating Expenses"msgstr "运营费用"@@ -11873,6 +11892,9 @@ msgstr "过账发票"msgid "Post journal entries with proper account and description codes"msgstr "使用正确的科目和描述代码过账凭证。"+msgid "Post opening balances"+msgstr "过账期初余额"+msgid "Post Receipt"msgstr "过账收据"