Skip to content

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

feat(accounting): financial reports module + accounting beta access gate (#1360)

Brad Barbinbece7da2bf5e
diff --git a/.ai/plans/2026-08-09-dimensional-pivot-reporting.md b/.ai/plans/2026-08-09-dimensional-pivot-reporting.md
new file mode 100644
index 0000000000..5439874799
--- /dev/null
+++ b/.ai/plans/2026-08-09-dimensional-pivot-reporting.md
@@ -0,0 +1,1022 @@
+# Dimensional Pivot Reporting — implementation plan
+
+**Spec:** .ai/specs/2026-08-09-dimensional-pivot-reporting.md
+**Research:** .ai/research/dimensional-pivot-reporting.md
+**Branch:** financial-reports-module
+
+## Progress
+- [x] Task 1: Write the migration (reportView + indexes + 2 RPCs + reportPin key migration)
+- [x] Task 2: Validate the migration in a rolled-back transaction with fixtures
+- [x] Task 3: Apply migration and regenerate DB types
+- [x] Task 4: Add the analytics registry + pivot validators to accounting.models.ts
+- [x] Task 5: Add pivot + reportView service functions to accounting.service.ts
+- [x] Task 6: Build pivotTree.ts (pure pivot assembly) + unit tests
+- [x] Task 7: Build PivotControlBar + SaveViewModal components
+- [x] Task 8: Build PivotTree component + PivotLinesDrawer
+- [x] Task 9: Add analytics routes + path helpers
+- [x] Task 10: Redirect old reports, update hub cards, remove dead code
+- [x] Task 11: i18n extract + lint + scoped typecheck gate (hi/tr/ko translations deferred per Brad)
+- [ ] Task 12: Browser verification via /test (Brad is handling this)
+
+## Dependencies
+- Task 2 needs Task 1; Task 3 needs Task 2.
+- Task 4 needs Task 3 (generated types for enums used in validators).
+- Tasks 5 and 6 both need Task 4 and are independent of each other (parallelizable).
+- Task 7 needs Task 4; Task 8 needs Tasks 4+6. Tasks 7 and 8 are independent of each other.
+- Task 9 needs Tasks 5, 7, 8. Task 10 needs Task 9. Task 11 needs Task 10. Task 12 last.
+
+## Context every executor must read first
+
+- Spec: `.ai/specs/2026-08-09-dimensional-pivot-reporting.md` (design + acceptance criteria)
+- `.claude/rules/workflow-database-migration.md`, `.claude/rules/conventions-database.md` (Task 1)
+- `.claude/rules/conventions-services.md` (Task 5), `.claude/rules/conventions-forms.md` (Task 7)
+- `apps/erp/app/modules/accounting/AGENTS.md`
+- Key facts:
+ - `journalLine.amount` is stored **natural-signed**: positive moves the account
+ toward its natural balance (positive on a Revenue account = more revenue).
+ See `.ai/lessons.md` "Journal debit/credit is derived from account class".
+ - Dimensions: `dimension` (per `companyGroupId`, has `entityType`), tags in
+ `journalLineDimension(journalLineId, dimensionId, valueId, companyId)`.
+ - `journalLines` view = `journalLine` ⨝ `journal` (adds `postingDate`,
+ `journalEntryId`, `status`) and already excludes Draft; RPCs below join the
+ base tables directly like `accountTreeBalancePeriodSeries` does.
+ - Period buckets come only from `computeReportPeriodBuckets` in `@carbon/utils`.
+
+---
+
+## Task 1: Write the migration
+
+**Depends on:** none
+**Files:**
+- Create: `packages/database/supabase/migrations/{timestamp}_dimensional-pivot-reporting.sql` (via `pnpm db:migrate:new dimensional-pivot-reporting` — never hand-pick the timestamp)
+- Copy from (precedent): `packages/database/supabase/migrations/20260809151458_balance-rpc-period-series.sql` (RPC style/header), `packages/database/supabase/migrations/20260809161618_report-pins.sql` (report-table RLS style)
+
+**Steps:**
+
+1. Run `pnpm db:migrate:new dimensional-pivot-reporting`. Put all SQL below in
+ the generated file. Every statement must be idempotent (guards shown).
+
+2. Enum + `reportView` table + RLS:
+
+```sql
+DO $$ BEGIN
+ IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'reportViewVisibility') THEN
+ CREATE TYPE "reportViewVisibility" AS ENUM ('Private', 'Company');
+ END IF;
+END $$;
+
+CREATE TABLE IF NOT EXISTS "reportView" (
+ "id" TEXT NOT NULL DEFAULT id('rv'),
+ "companyId" TEXT NOT NULL,
+ "reportKey" TEXT NOT NULL,
+ "name" TEXT NOT NULL,
+ "config" JSONB NOT NULL,
+ "visibility" "reportViewVisibility" NOT NULL DEFAULT 'Private',
+ "createdBy" TEXT NOT NULL REFERENCES "user"("id"),
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "updatedBy" TEXT REFERENCES "user"("id"),
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+ CONSTRAINT "reportView_pkey" PRIMARY KEY ("id", "companyId"),
+ CONSTRAINT "reportView_companyId_fkey" FOREIGN KEY ("companyId")
+ REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT "reportView_name_unique" UNIQUE ("companyId", "reportKey", "name")
+);
+
+CREATE INDEX IF NOT EXISTS "reportView_companyId_idx" ON "reportView" ("companyId");
+CREATE INDEX IF NOT EXISTS "reportView_createdBy_idx" ON "reportView" ("createdBy");
+
+ALTER TABLE "reportView" ENABLE ROW LEVEL SECURITY;
+
+DROP POLICY IF EXISTS "SELECT" ON "reportView";
+CREATE POLICY "SELECT" ON "reportView" FOR SELECT USING (
+ "companyId" = ANY ((SELECT get_companies_with_employee_role())::text[])
+ AND ("visibility" = 'Company' OR "createdBy" = (SELECT auth.uid())::text)
+);
+DROP POLICY IF EXISTS "INSERT" ON "reportView";
+CREATE POLICY "INSERT" ON "reportView" FOR INSERT WITH CHECK (
+ "companyId" = ANY ((SELECT get_companies_with_employee_role())::text[])
+ AND "createdBy" = (SELECT auth.uid())::text
+);
+DROP POLICY IF EXISTS "UPDATE" ON "reportView";
+CREATE POLICY "UPDATE" ON "reportView" FOR UPDATE USING (
+ "companyId" = ANY ((SELECT get_companies_with_employee_role())::text[])
+ AND "createdBy" = (SELECT auth.uid())::text
+);
+DROP POLICY IF EXISTS "DELETE" ON "reportView";
+CREATE POLICY "DELETE" ON "reportView" FOR DELETE USING (
+ "companyId" = ANY ((SELECT get_companies_with_employee_role())::text[])
+ AND "createdBy" = (SELECT auth.uid())::text
+);
+```
+
+3. Aggregation indexes on `journalLineDimension`. First grep existing indexes
+ (`grep -rn 'journalLineDimension' packages/database/supabase/migrations/ | grep -i 'index'`);
+ add only what's missing:
+
+```sql
+CREATE INDEX IF NOT EXISTS "journalLineDimension_line_dimension_idx"
+ ON "journalLineDimension" ("journalLineId", "dimensionId");
+CREATE INDEX IF NOT EXISTS "journalLineDimension_company_dimension_value_idx"
+ ON "journalLineDimension" ("companyId", "dimensionId", "valueId", "journalLineId");
+```
+
+4. The pivot RPC. plpgsql (never `LANGUAGE sql` — planner inlining drops
+ ordering; see `.ai/lessons.md`), SECURITY INVOKER, mirroring the sibling
+ RPC's header-comment style. Contract notes to include in the SQL comment:
+ p_period_ends comes from `computeReportPeriodBuckets` (sorted ascending,
+ distinct, max == p_end); exactly one account-scope param is non-null;
+ p_column_dimension and p_period_ends are mutually exclusive; NULL
+ rowValue/columnKey means Unassigned; app re-sorts (never trust RPC order).
+
+```sql
+DROP FUNCTION IF EXISTS "journalDimensionPivot";
+CREATE OR REPLACE FUNCTION "journalDimensionPivot" (
+ p_company_group_id TEXT,
+ p_company_id TEXT,
+ p_start DATE,
+ p_end DATE,
+ p_account_classes TEXT[] DEFAULT NULL,
+ p_account_types TEXT[] DEFAULT NULL,
+ p_account_ids TEXT[] DEFAULT NULL,
+ p_row_dimension_1 TEXT DEFAULT NULL,
+ p_row_dimension_2 TEXT DEFAULT NULL,
+ p_column_dimension TEXT DEFAULT NULL,
+ p_period_ends DATE[] DEFAULT NULL,
+ p_filters JSONB DEFAULT NULL,
+ p_group_limit INT DEFAULT 1000
+)
+RETURNS TABLE (
+ "rowValue1Id" TEXT,
+ "rowValue2Id" TEXT,
+ "columnKey" TEXT,
+ "amount" NUMERIC,
+ "quantity" NUMERIC,
+ "lineCount" BIGINT,
+ "hasMore" BOOLEAN
+) LANGUAGE "plpgsql" SECURITY INVOKER SET search_path = public
+AS $$
+BEGIN
+ IF p_company_id IS NULL THEN
+ RAISE EXCEPTION 'journalDimensionPivot requires p_company_id';
+ END IF;
+ IF p_account_classes IS NULL AND p_account_types IS NULL AND p_account_ids IS NULL THEN
+ RAISE EXCEPTION 'journalDimensionPivot requires an account scope';
+ END IF;
+ IF p_column_dimension IS NOT NULL AND p_period_ends IS NOT NULL THEN
+ RAISE EXCEPTION 'journalDimensionPivot: column axis is a dimension OR period ends, not both';
+ END IF;
+
+ RETURN QUERY
+ WITH "scopedLines" AS (
+ SELECT jl."id" AS "lineId", jl."amount" AS "lineAmount",
+ COALESCE(jl."quantity", 0) AS "lineQuantity", j."postingDate"
+ FROM "journal" j
+ INNER JOIN "journalLine" jl ON jl."journalId" = j."id"
+ INNER JOIN "account" a
+ ON a."id" = jl."accountId" AND a."companyGroupId" = p_company_group_id
+ WHERE j."companyId" = p_company_id
+ AND jl."companyId" = p_company_id
+ AND j."status" <> 'Draft'
+ AND j."postingDate" >= p_start
+ AND j."postingDate" <= p_end
+ AND (
+ (p_account_ids IS NOT NULL AND jl."accountId" = ANY(p_account_ids))
+ OR (p_account_types IS NOT NULL AND a."accountType"::TEXT = ANY(p_account_types))
+ OR (p_account_classes IS NOT NULL AND a."class"::TEXT = ANY(p_account_classes))
+ )
+ AND NOT EXISTS (
+ SELECT 1
+ FROM jsonb_array_elements(COALESCE(p_filters, '[]'::jsonb)) AS f
+ WHERE NOT EXISTS (
+ SELECT 1 FROM "journalLineDimension" fd
+ WHERE fd."journalLineId" = jl."id"
+ AND fd."companyId" = p_company_id
+ AND fd."dimensionId" = f->>'dimensionId'
+ AND fd."valueId" IN (SELECT jsonb_array_elements_text(f->'valueIds'))
+ )
+ )
+ ),
+ "taggedLines" AS (
+ SELECT
+ sl."lineId", sl."lineAmount", sl."lineQuantity",
+ d1."valueId" AS "r1",
+ d2."valueId" AS "r2",
+ CASE
+ WHEN p_column_dimension IS NOT NULL THEN dc."valueId"
+ WHEN p_period_ends IS NOT NULL THEN (
+ SELECT MIN(pe)::TEXT FROM unnest(p_period_ends) pe
+ WHERE pe >= sl."postingDate"
+ )
+ ELSE 'total'
+ END AS "colKey"
+ FROM "scopedLines" sl
+ LEFT JOIN "journalLineDimension" d1
+ ON p_row_dimension_1 IS NOT NULL
+ AND d1."journalLineId" = sl."lineId"
+ AND d1."companyId" = p_company_id
+ AND d1."dimensionId" = p_row_dimension_1
+ LEFT JOIN "journalLineDimension" d2
+ ON p_row_dimension_2 IS NOT NULL
+ AND d2."journalLineId" = sl."lineId"
+ AND d2."companyId" = p_company_id
+ AND d2."dimensionId" = p_row_dimension_2
+ LEFT JOIN "journalLineDimension" dc
+ ON p_column_dimension IS NOT NULL
+ AND dc."journalLineId" = sl."lineId"
+ AND dc."companyId" = p_company_id
+ AND dc."dimensionId" = p_column_dimension
+ ),
+ "rowGroups" AS (
+ SELECT tl."r1", tl."r2",
+ ROW_NUMBER() OVER (ORDER BY ABS(SUM(tl."lineAmount")) DESC NULLS LAST) AS rn,
+ COUNT(*) OVER () AS "totalGroups"
+ FROM "taggedLines" tl
+ GROUP BY tl."r1", tl."r2"
+ ),
+ "keptGroups" AS (
+ SELECT rg."r1", rg."r2", rg."totalGroups"
+ FROM "rowGroups" rg
+ WHERE rg.rn <= p_group_limit
+ )
+ SELECT
+ tl."r1" AS "rowValue1Id",
+ tl."r2" AS "rowValue2Id",
+ tl."colKey" AS "columnKey",
+ SUM(tl."lineAmount") AS "amount",
+ SUM(tl."lineQuantity") AS "quantity",
+ COUNT(*)::BIGINT AS "lineCount",
+ (SELECT COALESCE(MAX(kg2."totalGroups"), 0) FROM "keptGroups" kg2) > p_group_limit AS "hasMore"
+ FROM "taggedLines" tl
+ INNER JOIN "keptGroups" kg
+ ON kg."r1" IS NOT DISTINCT FROM tl."r1"
+ AND kg."r2" IS NOT DISTINCT FROM tl."r2"
+ GROUP BY tl."r1", tl."r2", tl."colKey";
+END;
+$$;
+```
+
+5. The drill-through RPC. Match semantics: a row/column dimension param that is
+ NULL = no constraint; dimension set + value NULL = the Unassigned bucket
+ (line has NO tag for that dimension); dimension set + value set = tag equals
+ value. A period column narrows `postingDate` instead. **Before writing the
+ RETURNS clause, check the column types of `journal."journalEntryId"`,
+ `journalLine."documentType"`, `account."number"` in
+ `packages/database/src/types.ts` and match them exactly. If any differs from
+ the sketch, adjust the sketch — do not cast blindly.**
+
+```sql
+DROP FUNCTION IF EXISTS "journalDimensionPivotLines";
+CREATE OR REPLACE FUNCTION "journalDimensionPivotLines" (
+ p_company_group_id TEXT,
+ p_company_id TEXT,
+ p_start DATE,
+ p_end DATE,
+ p_account_classes TEXT[] DEFAULT NULL,
+ p_account_types TEXT[] DEFAULT NULL,
+ p_account_ids TEXT[] DEFAULT NULL,
+ p_filters JSONB DEFAULT NULL,
+ p_row_dimension_1 TEXT DEFAULT NULL,
+ p_row_value_1 TEXT DEFAULT NULL,
+ p_row_dimension_2 TEXT DEFAULT NULL,
+ p_row_value_2 TEXT DEFAULT NULL,
+ p_column_dimension TEXT DEFAULT NULL,
+ p_column_value TEXT DEFAULT NULL,
+ p_column_period_start DATE DEFAULT NULL,
+ p_column_period_end DATE DEFAULT NULL,
+ p_line_limit INT DEFAULT 500
+)
+RETURNS TABLE (
+ "id" TEXT,
+ "postingDate" DATE,
+ "journalEntryId" TEXT,
+ "accountId" TEXT,
+ "accountName" TEXT,
+ "accountNumber" TEXT,
+ "description" TEXT,
+ "documentType" TEXT,
+ "documentId" TEXT,
+ "amount" NUMERIC,
+ "quantity" NUMERIC
+) LANGUAGE "plpgsql" SECURITY INVOKER SET search_path = public
+AS $$
+BEGIN
+ RETURN QUERY
+ SELECT
+ jl."id",
+ j."postingDate",
+ j."journalEntryId"::TEXT,
+ jl."accountId",
+ a."name" AS "accountName",
+ a."number" AS "accountNumber",
+ jl."description",
+ jl."documentType"::TEXT,
+ jl."documentId",
+ jl."amount",
+ COALESCE(jl."quantity", 0) AS "quantity"
+ FROM "journal" j
+ INNER JOIN "journalLine" jl ON jl."journalId" = j."id"
+ INNER JOIN "account" a
+ ON a."id" = jl."accountId" AND a."companyGroupId" = p_company_group_id
+ WHERE j."companyId" = p_company_id
+ AND jl."companyId" = p_company_id
+ AND j."status" <> 'Draft'
+ AND j."postingDate" >= COALESCE(p_column_period_start, p_start)
+ AND j."postingDate" <= COALESCE(p_column_period_end, p_end)
+ AND (
+ (p_account_ids IS NOT NULL AND jl."accountId" = ANY(p_account_ids))
+ OR (p_account_types IS NOT NULL AND a."accountType"::TEXT = ANY(p_account_types))
+ OR (p_account_classes IS NOT NULL AND a."class"::TEXT = ANY(p_account_classes))
+ )
+ AND NOT EXISTS (
+ SELECT 1
+ FROM jsonb_array_elements(COALESCE(p_filters, '[]'::jsonb)) AS f
+ WHERE NOT EXISTS (
+ SELECT 1 FROM "journalLineDimension" fd
+ WHERE fd."journalLineId" = jl."id"
+ AND fd."companyId" = p_company_id
+ AND fd."dimensionId" = f->>'dimensionId'
+ AND fd."valueId" IN (SELECT jsonb_array_elements_text(f->'valueIds'))
+ )
+ )
+ AND (
+ p_row_dimension_1 IS NULL
+ OR (p_row_value_1 IS NULL AND NOT EXISTS (
+ SELECT 1 FROM "journalLineDimension" d
+ WHERE d."journalLineId" = jl."id" AND d."companyId" = p_company_id
+ AND d."dimensionId" = p_row_dimension_1))
+ OR (p_row_value_1 IS NOT NULL AND EXISTS (
+ SELECT 1 FROM "journalLineDimension" d
+ WHERE d."journalLineId" = jl."id" AND d."companyId" = p_company_id
+ AND d."dimensionId" = p_row_dimension_1 AND d."valueId" = p_row_value_1))
+ )
+ AND (
+ p_row_dimension_2 IS NULL
+ OR (p_row_value_2 IS NULL AND NOT EXISTS (
+ SELECT 1 FROM "journalLineDimension" d
+ WHERE d."journalLineId" = jl."id" AND d."companyId" = p_company_id
+ AND d."dimensionId" = p_row_dimension_2))
+ OR (p_row_value_2 IS NOT NULL AND EXISTS (
+ SELECT 1 FROM "journalLineDimension" d
+ WHERE d."journalLineId" = jl."id" AND d."companyId" = p_company_id
+ AND d."dimensionId" = p_row_dimension_2 AND d."valueId" = p_row_value_2))
+ )
+ AND (
+ p_column_dimension IS NULL
+ OR (p_column_value IS NULL AND NOT EXISTS (
+ SELECT 1 FROM "journalLineDimension" d
+ WHERE d."journalLineId" = jl."id" AND d."companyId" = p_company_id
+ AND d."dimensionId" = p_column_dimension))
+ OR (p_column_value IS NOT NULL AND EXISTS (
+ SELECT 1 FROM "journalLineDimension" d
+ WHERE d."journalLineId" = jl."id" AND d."companyId" = p_company_id
+ AND d."dimensionId" = p_column_dimension AND d."valueId" = p_column_value))
+ )
+ ORDER BY j."postingDate", jl."id"
+ LIMIT p_line_limit;
+END;
+$$;
+```
+
+6. `reportPin` key migration (old analytics cards → new generic-report keys),
+ dedupe-safe and idempotent:
+
+```sql
+UPDATE "reportPin" rp SET "reportKey" = 'revenue'
+WHERE rp."reportKey" = 'revenue-by-customer'
+ AND NOT EXISTS (
+ SELECT 1 FROM "reportPin" x
+ WHERE x."reportKey" = 'revenue'
+ AND x."userId" = rp."userId" AND x."companyId" = rp."companyId");
+
+UPDATE "reportPin" rp SET "reportKey" = 'expenses'
+WHERE rp."reportKey" = 'expenses-by-supplier'
+ AND NOT EXISTS (
+ SELECT 1 FROM "reportPin" x
+ WHERE x."reportKey" = 'expenses'
+ AND x."userId" = rp."userId" AND x."companyId" = rp."companyId");
+
+DELETE FROM "reportPin"
+WHERE "reportKey" IN ('revenue-by-customer', 'expenses-by-supplier');
+```
+
+**Verify:**
+```bash
+ls packages/database/supabase/migrations/ | tail -3
+# Expected: the new *_dimensional-pivot-reporting.sql is the newest file (timestamp
+# greater than every existing migration; HHMMSS not 000000)
+```
+
+**Out of scope:** Do not touch `journalLine`, `journalLineDimension` columns,
+any posting function, or existing balance RPCs.
+
+---
+
+## Task 2: Validate the migration in a rolled-back transaction with fixtures
+
+**Depends on:** Task 1
+**Files:**
+- Create: `.ai/scratch/pivot-migration-validate.sql` (gitignored scratch, fine for throwaway validation)
+
+**Steps:**
+
+1. The local stack must be running (`crbn up`, plain portless mode). Get the DB
+ URL from `.env.local` (`SUPABASE_DB_URL`). If the stack cannot boot, STOP
+ and report — do not skip validation.
+2. Write a validation script that runs entirely inside one transaction as
+ `supabase_admin` (pattern: memory/lessons "migration validation via
+ rolled-back psql txn"):
+ - `BEGIN;`
+ - `\i` the new migration file.
+ - Insert fixtures (any existing `companyId`/`companyGroupId` from the local
+ `company` table; disable nothing — journals inserted as `status =
+ 'Posted'` with natural-signed amounts per the lesson):
+ - 1 journal, postingDate in-range, 3 `journalLine` rows on a Revenue-class
+ account: +100 tagged CustomerType A, +200 tagged CustomerType B, +50
+ with no tag. Tag via `journalLineDimension` rows using the seeded
+ CustomerType dimension (`SELECT id FROM dimension WHERE "entityType" =
+ 'CustomerType' AND "companyGroupId" = ...`).
+ - 1 additional journal with `status = 'Draft'`, same account, +999 tagged
+ CustomerType A — must NOT appear in any result (Draft exclusion).
+ - Assertions (each a `SELECT ... ; -- expect:` block, eyeball or `\gset` +
+ `DO` asserts):
+ a. `journalDimensionPivot(companyGroupId, companyId, start, end,
+ p_account_classes => ARRAY['Revenue'], p_row_dimension_1 =>
+ <customerTypeDimId>)` returns 3 rows: (A, 100), (B, 200), (NULL, 50) —
+ NULL row = Unassigned; amounts positive (natural sign).
+ b. Same call with `p_period_ends => ARRAY[end]` returns the same sums
+ with `columnKey = end::text`.
+ c. `p_filters => '[{"dimensionId":"<dim>","valueIds":["<A>"]}]'` returns
+ only the A row.
+ d. `p_group_limit => 1` returns only the B row (largest ABS) with
+ `hasMore = true`.
+ e. `journalDimensionPivotLines(..., p_row_dimension_1 => <dim>,
+ p_row_value_1 => NULL)` returns exactly the untagged +50 line.
+ f. `journalDimensionPivotLines(..., p_row_value_1 => <A>)` sums to 100.
+ - `ROLLBACK;`
+3. Run it: `psql "$SUPABASE_DB_URL" -v ON_ERROR_STOP=1 -f .ai/scratch/pivot-migration-validate.sql`
+4. If assertion (a) shows negative revenue amounts, the natural-sign
+ assumption is wrong — STOP and report; the service layer would need a sign
+ multiplier and the spec's sign section must be revisited. Do not improvise.
+
+**Verify:**
+```bash
+psql "$SUPABASE_DB_URL" -v ON_ERROR_STOP=1 -f .ai/scratch/pivot-migration-validate.sql
+# Expected: script completes with ROLLBACK; all DO-block asserts pass (no exception);
+# no rows left behind (SELECT count(*) FROM "reportView" unchanged after rollback)
+```
+
+**Out of scope:** Do not commit fixtures; do not leave the transaction open; do
+not disable triggers.
+
+---
+
+## Task 3: Apply migration and regenerate DB types
+
+**Depends on:** Task 2
+**Files:**
+- Modify: `packages/database/src/types.ts` — regenerated, never hand-edited
+- Modify: `packages/database/supabase/functions/lib/types.ts` — regenerated
+
+**Steps:**
+1. `pnpm db:migrate` (applies pending migrations to the local dev DB).
+2. `pnpm run generate:types`.
+
+**Verify:**
+```bash
+grep -c 'reportView\|journalDimensionPivot' packages/database/src/types.ts
+# Expected: > 0 (table type + both RPC Function entries present)
+pnpm exec turbo run typecheck --filter=@carbon/database
+# Expected: exit 0
+```
+
+**Out of scope:** No hand edits to generated files.
+
+---
+
+## Task 4: Add the analytics registry + pivot validators to accounting.models.ts
+
+**Depends on:** Task 3
+**Files:**
+- Modify: `apps/erp/app/modules/accounting/accounting.models.ts` — append near the existing report validators (`financialReportColumns` ~L71, `financialReportParamsValidator` ~L82, `dimensionEntityTypes` ~L608)
+
+**Steps:**
+
+1. Add (exact shapes; adjust only if a name collides — then STOP and pick a
+ prefixed name, don't restructure existing exports):
+
+```ts
+export const analyticsReportKeys = [
+ "revenue",
+ "expenses",
+ "cogs",
+ "inventory-change",
+ "scrap",
+] as const;
+export type AnalyticsReportKey = (typeof analyticsReportKeys)[number];
+
+// Account scope: exactly one selector. "scrapAccounts" resolves at runtime to
+// accountDefault.scrapAccount (see getScrapAccountIds in accounting.service.ts).
+export type AnalyticsAccountScope =
+ | { classes: Database["public"]["Enums"]["glAccountClass"][] }
+ | { types: Database["public"]["Enums"]["accountType"][] }
+ | { source: "scrapAccounts" };
+
+export type AnalyticsReportDefinition = {
+ key: AnalyticsReportKey;
+ accountScope: AnalyticsAccountScope;
+ // default pivot state applied when the URL has no pivot params.
+ // rows entries use the "et:<entityType>" alias resolved by the loader.
+ defaultRows: string[];
+};
+
+export const analyticsReports: Record<AnalyticsReportKey, AnalyticsReportDefinition> = {
+ revenue: { key: "revenue", accountScope: { classes: ["Revenue"] }, defaultRows: ["et:CustomerType"] },
+ expenses: { key: "expenses", accountScope: { classes: ["Expense"] }, defaultRows: ["et:SupplierType"] },
+ cogs: { key: "cogs", accountScope: { types: ["Cost of Goods Sold"] }, defaultRows: ["et:ItemPostingGroup"] },
+ "inventory-change": { key: "inventory-change", accountScope: { types: ["Inventory"] }, defaultRows: ["et:ItemPostingGroup"] },
+ scrap: { key: "scrap", accountScope: { source: "scrapAccounts" }, defaultRows: ["et:ScrapReason"] },
+};
+
+export const pivotMeasures = ["amount", "quantity", "count"] as const;
+
+export const pivotColumnAxisValidator = z.discriminatedUnion("type", [
+ z.object({ type: z.literal("period"), bucket: z.enum(financialReportColumns) }),
+ z.object({ type: z.literal("dimension"), dimensionId: z.string().min(1) }),
+]);
+
+export const pivotStateValidator = z.object({
+ rows: z.array(z.string().min(1)).max(2).default([]),
+ columnAxis: pivotColumnAxisValidator.default({ type: "period", bucket: "month" }),
+ measure: z.enum(pivotMeasures).default("amount"),
+ percentOfTotal: z.boolean().default(false),
+ filters: z
+ .array(z.object({ dimensionId: z.string().min(1), valueIds: z.array(z.string()).min(1) }))
+ .default([]),
+});
+export type PivotState = z.infer<typeof pivotStateValidator>;
+
+export const reportViewValidator = z.object({
+ id: zfd.text(z.string().optional()),
+ reportKey: z.enum(analyticsReportKeys),
+ name: z.string().min(1, { message: "Name is required" }).max(100),
+ visibility: z.enum(["Private", "Company"]),
+ // JSON-encoded PivotState; parsed with pivotStateValidator in the action
+ config: z.string().min(2),
+});
+```
+
+ Display names for report keys/measures live in the UI with Lingui (Task 7),
+ not in the models file (msg descriptors don't belong in models).
+
+2. **URL param contract** (document as a comment above `pivotStateValidator`;
+ the loader in Task 9 and the control bar in Task 7 both implement it):
+ - `rows` = comma-separated list, each item a `dimension.id` or `et:<entityType>` alias
+ - `col` = `period:month|quarter|year` or `dim:<dimensionId>`
+ - `measure` = `amount|quantity|count`; `pct` = `1` when percentOfTotal
+ - `filters` = JSON-encoded `[{dimensionId, valueIds}]` (URL-encoded)
+ - `startDate`/`endDate` — same params the existing `ReportFilters` writes
+
+3. Export any new types from the module barrel if not already covered by
+ `export *` (check `apps/erp/app/modules/accounting/index.ts`).
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=erp
+# Expected: exit 0
+```
+
+**Out of scope:** Do not modify existing validators or `financialReportParamsValidator`.
+
+---
+
+## Task 5: Add pivot + reportView service functions to accounting.service.ts
+
+**Depends on:** Task 4 (parallel with Task 6)
+**Files:**
+- Modify: `apps/erp/app/modules/accounting/accounting.service.ts` — add functions near the existing report functions (`getAccountPeriodSeries` ~L347) and reportPin functions (`getReportPins` ~L832)
+- Modify: `apps/erp/app/modules/accounting/types.ts` — derived types
+- Copy from (precedent): `getAccountPeriodSeries` (RPC call + period buckets), `getReportPins`/`upsertReportPin` (simple table CRUD), `getEntityDimensionValues` ~L2982 (entityType → source-table mapping)
+
+**Steps:**
+
+1. `getScrapAccountIds(client, companyId)`: `SELECT scrapAccount FROM
+ accountDefault WHERE companyId = ...`; returns `{ data: string[], error }`
+ (empty array if null). (Grep confirmed `scrapAccount` exists only on
+ `accountDefault` — no posting-group override.)
+
+2. `getDimensionPivot(client, args)` with:
+
+```ts
+args: {
+ companyId: string;
+ companyGroupId: string;
+ report: AnalyticsReportDefinition;
+ scrapAccountIds?: string[]; // required when accountScope.source === "scrapAccounts"
+ startDate: string; // YYYY-MM-DD
+ endDate: string;
+ periodEnds?: string[]; // from computeReportPeriodBuckets, when columnAxis is period
+ state: PivotState; // rows already resolved to dimension ids (loader does et: resolution)
+}
+```
+
+ - Calls `client.rpc("journalDimensionPivot", {...})` mapping: scope →
+ `p_account_classes`/`p_account_types`/`p_account_ids` (scrap →
+ scrapAccountIds; if scrapAccountIds is empty, return
+ `{ data: { groups: [], columnKeys: [], hasMore: false, valueNames: {} }, error: null }`
+ without calling the RPC), rows → `p_row_dimension_1/2`, columnAxis →
+ `p_column_dimension` or `p_period_ends`, filters → `p_filters`.
+ - Collects distinct non-null `rowValue1Id`/`rowValue2Id`/`columnKey`
+ (columnKey only when the column axis is a dimension) and resolves display
+ names per the tagged dimension's `entityType`.
+ - **Name resolution:** read `getEntityDimensionValues` (~L2982) first. Factor
+ its entityType→(table, id column, name column) mapping into a reusable
+ helper `resolveDimensionValueNames(client, companyId, companyGroupId,
+ requests: { entityType, valueIds }[])` → `Record<string, string>`. Reuse
+ the mapping — do NOT invent table names. Only query the ids actually
+ returned (≤1,000 groups), batched per entityType with `.in("id", ids)`.
+ If the existing mapping can't be factored without changing
+ `getEntityDimensionValues` behavior, duplicate the mapping table into the
+ helper and leave the original untouched.
+ - Returns `{ data: { groups, columnKeys, hasMore, valueNames }, error }`,
+ `groups` sorted descending by `ABS(amount)` **in TypeScript** (never trust
+ RPC ordering — lesson).
+
+3. `getDimensionPivotLines(client, args)` — same scope/filter args plus
+ `{ rowDimension1?, rowValue1?, rowDimension2?, rowValue2?, columnDimension?,
+ columnValue?, columnPeriodStart?, columnPeriodEnd? }`; calls
+ `journalDimensionPivotLines`; re-sorts by postingDate in TS.
+
+4. `getReportViews(client, { companyId, reportKey? })` — `.from("reportView")
+ .select("*").eq("companyId", companyId)` (+ `.eq("reportKey", reportKey)`),
+ RLS handles visibility. `upsertReportView(client, view)` — insert or update
+ (id present → update with `updatedBy`/`updatedAt`; absent → insert with
+ `createdBy`); returns the row. `deleteReportView(client, id, companyId)`.
+ All follow `{ data, error }` — never throw (conventions-services).
+
+5. In `types.ts`, add `export type DimensionPivot = NonNullable<Awaited<ReturnType<typeof getDimensionPivot>>["data"]>;`
+ and the same for `DimensionPivotLine`, `ReportView` (follow the file's
+ existing `Awaited<ReturnType<...>>` style).
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=erp
+# Expected: exit 0
+```
+
+**Out of scope:** No changes to `getEntityDimensionValues` behavior, no changes
+to existing report service functions, no new service files.
+
+---
+
+## Task 6: Build pivotTree.ts (pure pivot assembly) + unit tests
+
+**Depends on:** Task 4 (parallel with Task 5)
+**Files:**
+- Create: `apps/erp/app/modules/accounting/ui/Reports/pivotTree.ts`
+- Create: `apps/erp/app/modules/accounting/ui/Reports/pivotTree.test.ts`
+- Copy from (precedent): `apps/erp/app/modules/accounting/ui/Reports/reportTree.ts` (flat-tree builder style + its test if one exists), `apps/erp/app/components/TreeView/` (the `FlatTreeItem` shape: `id, parentId, children, hasChildren, level, data`)
+
+**Steps:**
+
+1. Pure functions (no React, no client):
+
+```ts
+export type PivotCellValue = { amount: number; quantity: number; lineCount: number };
+export type PivotRowNode = {
+ key: string; // "<r1 ?? '∅'>|<r2 ?? '∅'>" composite
+ rowValue1Id: string | null; // null = Unassigned
+ rowValue2Id: string | null;
+ label: string; // resolved name or "Unassigned"
+ cells: Record<string, PivotCellValue>; // by columnKey
+ total: PivotCellValue;
+};
+
+export function buildPivotTree(args: {
+ groups: /* RPC rows from getDimensionPivot */;
+ valueNames: Record<string, string>;
+ columnKeys: string[]; // ordered: period ends ascending, or dimension values sorted by grand total desc
+ rowCount: 0 | 1 | 2;
+ maxColumns?: number; // default 50
+}): {
+ flatTree: FlatTreeItem<PivotRowNode>[]; // level-1 groups with nested level-2 children, subtotals on parents
+ columnKeys: string[]; // possibly truncated (see columnsTruncated)
+ columnTotals: Record<string, PivotCellValue>;
+ grandTotal: PivotCellValue;
+ columnsTruncated: boolean; // true when > maxColumns distinct columns — UI must show a banner
+}
+```
+
+ Rules: parent rows (dimension 1) aggregate their children's cells; Unassigned
+ sorts last; everything else sorted by `ABS(total[measure])` descending; when
+ `columnsTruncated`, keep the top `maxColumns` columns by grand total and DROP
+ the rest from `columnKeys` (the banner states truncation — no silent cap).
+2. `applyPercentOfTotal(cells, columnTotals)` helper returning percentages per
+ column (0 when the column total is 0 — no division by zero).
+3. `pivotToCsvRows(tree, columnKeys, measure)` returning `string[][]` for the
+ export (header row + data rows exactly as rendered).
+4. Tests (vitest, colocated `pivotTree.test.ts`; run like the existing erp unit
+ tests — check how `reportTree` or `executivePnl` tests are invoked first).
+ Cases: (a) 1-dim rows with Unassigned sorting last and correct totals;
+ (b) 2-dim nesting with parent subtotals = sum of children; (c) column totals
+ + grand total consistency; (d) percentOfTotal sums to 100 per column
+ (within float tolerance) and 0-total column yields 0s; (e) column truncation
+ sets `columnsTruncated` and keeps top-N by grand total; (f) CSV rows match
+ the tree. Use optional chaining on indexed access (`arr[0]?.prop`) —
+ `noUncheckedIndexedAccess` is on.
+
+**Verify:**
+```bash
+pnpm --filter erp test -- pivotTree
+# Expected: all pivotTree tests pass
+pnpm exec turbo run typecheck --filter=erp
+# Expected: exit 0
+```
+
+**Out of scope:** No React components here; no data fetching.
+
+---
+
+## Task 7: Build PivotControlBar + SaveViewModal components
+
+**Depends on:** Task 4 (parallel with Task 8)
+**Files:**
+- Create: `apps/erp/app/modules/accounting/ui/Reports/PivotControlBar.tsx`
+- Create: `apps/erp/app/modules/accounting/ui/Reports/SaveViewModal.tsx`
+- Modify: `apps/erp/app/modules/accounting/ui/Reports/index.ts` — export both
+- Copy from (precedent): `apps/erp/app/modules/accounting/ui/Reports/ReportFilters.tsx` (filter-bar layout, URL-param writing, download button), `apps/erp/app/components/PeriodSelector.tsx` (range variant), `apps/erp/app/modules/accounting/ui/JournalEntries/DimensionSelector.tsx` (dimension value picker incl. lazy high-cardinality entities)
+
+**Steps:**
+
+1. `PivotControlBar` props: `reportKey`, `dimensions` (from
+ `getActiveDimensionsWithValues` loader data), `state: PivotState`,
+ `savedViews`, `accountScopeLabel`. It renders, in ReportFilters' visual
+ style (same HStack/spacing/size conventions — ERP `size="md"`):
+ - Rows: two dimension selects (second enabled only when first set; can't
+ pick the same dimension twice)
+ - Columns: a segmented/select control: Month / Quarter / Year / By dimension
+ (+ dimension select when "By dimension")
+ - Values: measure select (Amount/Quantity/Count) + "% of total" toggle
+ - Filters: add-filter popover → dimension → multi-select values (lazy-load
+ values for Customer/Supplier/Item via the same mechanism
+ DimensionSelector uses — read it first)
+ - `PeriodSelector` (range variant) + account-scope chip (read-only Badge) +
+ saved-view select (grouped Private/Company) + Save view button + CSV
+ download + reset
+ - All state changes write URL search params per the Task 4 contract
+ (`setSearchParams`, replace, like ReportFilters does). No local state
+ that isn't in the URL.
+2. `SaveViewModal`: `ValidatedForm` + `reportViewValidator` posting to the
+ route action (Task 9). Fields: Name (Input), Visibility (Select:
+ Private/Company), hidden `reportKey` + `config` (JSON.stringify of current
+ PivotState). Follow `.claude/rules/conventions-forms.md`; Modal from
+ `@carbon/react`. Editing an existing view pre-fills + passes `id`.
+ Delete button (owner only — compare `createdBy` to `useUser()` id) submits
+ intent=delete.
+3. All user-facing strings via Lingui (`useLingui().t` / `<Trans>`); counts
+ shown plainly (never parenthesized).
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=erp
+# Expected: exit 0
+```
+
+**Out of scope:** No route/loader code; no pivot rendering.
+
+---
+
+## Task 8: Build PivotTree component + PivotLinesDrawer
+
+**Depends on:** Tasks 4+6 (parallel with Task 7)
+**Files:**
+- Create: `apps/erp/app/modules/accounting/ui/Reports/PivotTree.tsx`
+- Create: `apps/erp/app/modules/accounting/ui/Reports/PivotLinesDrawer.tsx`
+- Modify: `apps/erp/app/modules/accounting/ui/Reports/index.ts` — export both
+- Copy from (precedent): `apps/erp/app/modules/accounting/ui/Reports/MultiPeriodStatementTree.tsx` (TreeView-based multi-column report tree — the closest existing screen; clone its structure), `apps/erp/app/modules/accounting/ui/Reports/AccountLedgerDrawer.tsx` (drill-through drawer)
+
+**Steps:**
+
+1. `PivotTree`: renders `buildPivotTree` output with `TreeView`/`useTree`
+ exactly the way MultiPeriodStatementTree renders its tree: expandable
+ level-1/level-2 rows, one numeric column per `columnKey` (period label via
+ `getPeriodColumnLabel` from `exportReport.ts` when the axis is period;
+ `valueNames` otherwise), plus a Total column; column-totals footer row and
+ grand total; measure formatting — amount via the report's currency
+ formatting used in MultiPeriodStatementTree, quantity/count as plain
+ numbers, percentages with one decimal when `percentOfTotal`. Unassigned
+ label italic/muted. `columnsTruncated` or `hasMore` → an explicit banner
+ line above the tree ("Showing top 1,000 groups by amount" / "Showing top 50
+ columns"). Tabular numbers (`make-interfaces-feel-better`: use the same
+ number-cell classes as the precedent).
+2. Cell + row-total click opens `PivotLinesDrawer` (also double-click):
+ Drawer (overlay, per detail-view convention) fetching
+ `analyticsReportLines` (Task 9) via `useFetcher` with the cell coordinates
+ (rowValue ids, columnKey → dimension value or period start/end resolved from
+ the bucket). Shows a simple table: Posting Date (`formatDate` from
+ `@carbon/utils` — never `new Date`), Journal (link to the journal entry
+ using the same link target AccountLedgerDrawer uses), Account, Description,
+ Document, Amount, Quantity; footer sums; the 500-line cap surfaced as a
+ banner when `lines.length === 500`.
+3. Empty state when no groups: icon + "No journal lines in scope for this
+ period" (Lingui), matching the empty-state pattern in the precedent tree.
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=erp
+# Expected: exit 0
+```
+
+**Out of scope:** No loader/action code; no changes to TreeView itself.
+
+---
+
+## Task 9: Add analytics routes + path helpers
+
+**Depends on:** Tasks 5, 7, 8
+**Files:**
+- Create: `apps/erp/app/routes/x+/reports+/analytics.$reportKey.tsx`
+- Create: `apps/erp/app/routes/x+/reports+/analytics.$reportKey.lines.tsx`
+- Modify: `apps/erp/app/utils/path.ts` — add `analyticsReport: (key: string) => ...` and `analyticsReportLines: (key: string) => ...` in alphabetical position
+- Copy from (precedent): `apps/erp/app/routes/x+/reports+/income-statement.tsx` (loader shape: params → `computeReportPeriodBuckets` → service → tree component), `apps/erp/app/routes/x+/reports+/revenue-by-customer.tsx` (timezone-aware `defaultReportRange` handling)
+
+**Steps:**
+
+1. `analytics.$reportKey.tsx`:
+ - `handle.breadcrumb`: msg-descriptor per key (switch over
+ `analyticsReportKeys`; unknown key → 404 via `data(null, { status: 404 })`
+ — check how sibling routes 404 first and copy that).
+ - Loader: `requirePermissions(request, { view: "accounting", role:
+ "employee" })` destructuring `{ client, companyId, companyGroupId }`.
+ Parse URL params per the Task 4 contract into `PivotState`
+ (`pivotStateValidator.safeParse` on the assembled object; invalid → fall
+ back to the report default + keep going). Resolve `et:<entityType>` row
+ aliases to dimension ids via `getDimensions` filtered to active — if no
+ dimension exists for the alias, drop that row selection. Dates default
+ via `defaultReportRange` + `getCompanyTimeZone` exactly like
+ revenue-by-customer.tsx does today. When columnAxis is period, compute
+ `periodEnds` with `computeReportPeriodBuckets(startDate, endDate, bucket,
+ fiscalStartMonth)` (see income-statement.tsx for the fiscal month
+ lookup). Load in parallel (`Promise.all`): `getDimensionPivot`,
+ `getActiveDimensionsWithValues`, `getReportViews(client, { companyId,
+ reportKey })`, and `getScrapAccountIds` when the report is scrap.
+ - Action: `assertIsPost`; parse `intent` — `save` validates
+ `reportViewValidator` via `validator(...).validate(formData)`, parses
+ `config` with `pivotStateValidator` (invalid → flash error), calls
+ `upsertReportView`; `delete` calls `deleteReportView` (RLS enforces
+ ownership; surface the error via flash if it fails). Return plain objects
+ + `flash` per route conventions — success stays on the page with a
+ success flash (no redirect needed; the view list refreshes via loader
+ revalidation).
+ - Component: `PivotControlBar` + `PivotTree` wired to loader data; CSV
+ download uses `pivotToCsvRows` + the exact download mechanism
+ `ReportFilters`/`exportReport.ts` uses today.
+2. `analytics.$reportKey.lines.tsx`: loader-only fetcher route (same
+ permissions) parsing the same scope params + cell coordinates
+ (`r1`,`r2`,`col` params; `r1=∅` sentinel for Unassigned must be
+ distinguished from absent — use `r1null=1`-style flags, mirroring the RPC's
+ NULL semantics) and returning `getDimensionPivotLines` data. If a
+ `.lines.tsx` sibling route nests awkwardly under `$reportKey` (flat-routes
+ dot-nesting makes it a child of the report route — that is fine for a
+ fetcher), verify with `pnpm --filter erp exec react-router routes` if
+ unsure; if it renders as a nested Outlet instead of a resource route, move
+ it to `apps/erp/app/routes/api+/accounting.analytics-lines.tsx` and update
+ `path.ts` accordingly.
+3. `path.ts`: `analyticsReport: (key: string) => \`${x}/reports/analytics/${key}\``
+ (+ lines helper matching wherever the fetcher route landed).
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=erp
+# Expected: exit 0
+```
+
+**Out of scope:** Hub cards and redirects (Task 10); no new permissions scopes.
+
+---
+
+## Task 10: Redirect old reports, update hub cards, remove dead code
+
+**Depends on:** Task 9
+**Files:**
+- Modify: `apps/erp/app/routes/x+/reports+/revenue-by-customer.tsx` — replace with a redirect loader
+- Modify: `apps/erp/app/routes/x+/reports+/expenses-by-supplier.tsx` — replace with a redirect loader
+- Modify: `apps/erp/app/routes/x+/accounting+/reports.tsx` — swap the two Analytics cards for the five generic reports + saved-views list
+- Modify: `apps/erp/app/utils/path.ts` — remove `revenueByCustomer` / `expensesBySupplier` after all references are updated
+- Possibly delete: `SpendByPartyReport` + `getRevenueByCustomer` / `getExpensesBySupplier` (invoicing module) — only if unreferenced
+
+**Steps:**
+
+1. Replace each old route file's contents with only:
+ `export async function loader() { throw redirect(path.to.analyticsReport("revenue") + "?rows=et:Customer"); }`
+ (expenses → `analyticsReport("expenses") + "?rows=et:Supplier"`). Keep the
+ file (URL keeps working); remove the old component/loader imports.
+2. Hub (`x+/accounting+/reports.tsx`): replace the `revenue-by-customer` and
+ `expenses-by-supplier` `ReportDefinition` entries with five entries — keys
+ exactly `revenue`, `expenses`, `cogs`, `inventory-change`, `scrap` (they
+ must match the Task 1 reportPin migration), category `t\`Analytics\``,
+ `defaultPinned: false`, `to: path.to.analyticsReport(key)`, names/
+ descriptions via Lingui (e.g. `t\`Revenue\`` / `t\`Slice revenue by any
+ dimension\``). Add the AR/AP aging cards untouched. Below the Analytics
+ card grid, list saved views: extend the hub loader with
+ `getReportViews(client, { companyId })` and render each view as a small
+ link row (name + report + owner/shared badge) →
+ `path.to.analyticsReport(view.reportKey)` + `?view=<id>`; the analytics
+ loader applies a `view` param by loading that reportView's config (add
+ this handling to Task 9's loader — parse `view` param first, URL params
+ still win when present).
+3. Grep for now-dead code: `grep -rn "SpendByPartyReport\|getRevenueByCustomer\|getExpensesBySupplier" apps/`
+ — if the only references were the two replaced routes, delete the component
+ and service functions and update the invoicing barrel exports
+ (`apps/erp/app/modules/invoicing/index.ts`, `ui/index.ts`,
+ `ui/Reports/index.ts` as applicable). If anything else references them
+ (e.g. ARAPWorkbench), leave them and note it in the run record.
+4. Grep for remaining `path.to.revenueByCustomer` / `path.to.expensesBySupplier`
+ references; the redirect routes themselves should use literal old paths in
+ `handle`/nothing — after all references are gone, delete the two path
+ helpers. If the redirect route files need a path constant, inline the
+ string.
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=erp
+# Expected: exit 0
+grep -rn "revenueByCustomer\|expensesBySupplier" apps/erp/app/utils/path.ts
+# Expected: no matches
+```
+
+**Out of scope:** AR/AP aging reports; inventory-valuation; do not touch `ARAPWorkbench` unless the grep in step 3 says it references deleted code (then STOP and report instead of deleting).
+
+---
+
+## Task 11: i18n extract + lint + scoped typecheck gate
+
+**Depends on:** Task 10
+**Files:**
+- Modify: `packages/locale/locales/*/erp.po` — extracted strings
+
+**Steps:**
+1. `pnpm run lingui:extract` (updates the .po catalogs with the new strings).
+2. Fill missing translations for the new strings via the `/translate` skill
+ (or leave for the check-and-commit gate if executing task-by-task — it runs
+ /translate when locale files changed).
+3. `pnpm run lint` — fix any Biome findings in the new files.
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=erp
+# Expected: exit 0
+pnpm run lint
+# Expected: exit 0 (no errors)
+git diff --stat packages/locale/locales/en/erp.po
+# Expected: new msgids for the pivot UI strings
+```
+
+**Out of scope:** No locale-list changes.
+
+---
+
+## Task 12: Browser verification via /test
+
+**Depends on:** Task 11
+**Files:** none (verification only; playbook may be cached to `.ai/playbooks/`)
+
+**Steps:**
+
+1. Boot the stack with plain `crbn up` (portless). If accounting is disabled
+ locally (fresh reset), enable it at `/x/settings/accounting` first
+ (memory: crbn reset seeds `accountingEnabled=false`).
+2. Ensure there is dimension-tagged data: post at least (a) a sales invoice
+ (tags Customer/CustomerType) and (b) a stock scrap with a scrap reason
+ (tags ScrapReason — flow from #1355). If seeded data already contains
+ posted journals with tags (check via the trial balance + a quick pivot),
+ skip creation.
+3. Run `/test` against the branch diff with this scenario list (maps to the
+ spec's acceptance criteria):
+ - `/x/reports/analytics/scrap` → default rows=ScrapReason; groups per
+ reason; drill-through drawer sums equal the cell.
+ - `/x/reports/analytics/revenue?rows=et:CustomerType` with month columns →
+ positive amounts; switch measure to Quantity and Count; toggle % of
+ total (columns sum to 100%).
+ - Set rows to two dimensions (ScrapReason → Item) → nested tree with
+ parent subtotals.
+ - `/x/reports/analytics/inventory-change?rows=et:ItemPostingGroup` →
+ signed net change per item group (positive when inventory rose, e.g.
+ after a receipt/completion; negative after a scrap/issue).
+ - Column axis = dimension (Location) → per-location columns + totals.
+ - Add a Location filter → all cells restricted consistently.
+ - Save a view (visibility Company) → appears on the reports hub; open via
+ the hub link; URL round-trip (copy URL into a new tab reproduces state).
+ - `/x/reports/revenue-by-customer` → 302 redirect to the analytics preset.
+ - CSV download matches rendered rows.
+ Note: agent-browser + ValidatedForm → submit via `requestSubmit(button)`,
+ blur react-aria fields to commit values (memory: agent-browser RVF forms).
+4. Screenshots of the pivot (1-dim, 2-dim nested, dimension columns, drawer)
+ for the PR per the surface-designs feedback.
+
+**Verify:**
+```bash
+# /test produces a pass/fail table; all scenarios above must pass.
+# Expected: PASS on every scenario; screenshots saved for the PR.
+```
+
+**Out of scope:** No production data; no Xero/sync verification; do not run `crbn reset`.
diff --git a/.ai/research/dimensional-pivot-reporting.md b/.ai/research/dimensional-pivot-reporting.md
new file mode 100644
index 0000000000..c69ef8b6f4
--- /dev/null
+++ b/.ai/research/dimensional-pivot-reporting.md
@@ -0,0 +1,338 @@
+# Dimensional Pivot-Table Reporting Research: Best Practices Survey
+
+## Summary
+
+Surveyed how best-in-class ERPs turn a dimension-tagged general ledger into
+interactive slice-and-dice analytics: **Sage Intacct** (multidimensional GL +
+Interactive Custom Report Writer), **NetSuite** (custom segments + SuiteAnalytics
+Workbook + saved searches), **SAP S/4HANA** (Universal Journal ACDOCA + CO-PA
+Profitability Analysis + statistical key figures), and **QuickBooks Online / Xero**
+(lightweight tracking categories / classes). Plus a cross-tool survey of the
+pivot-builder UX and how accounting systems answer *operational* (non-financial)
+questions.
+
+The dominant industry pattern is a **multidimensional GL**: every posting line is
+tagged with a set of dimension values, and analytics come "for free" by
+**grouping/filtering the ledger by dimension** — no per-breakdown GL accounts, no
+separate data warehouse until scale demands it. The pivot UX has strongly
+converged on a **Rows / Columns / Values / Filters "shelf" model** with per-measure
+aggregation, an expandable row-group hierarchy with subtotals, and double-click
+drill-through to the underlying transactions. Non-financial questions ("biggest
+causes of scrap", "units by reason") are answered either by tagging the relevant
+GL lines with an operational dimension (e.g. ScrapReason) or via **statistical
+accounts** carrying quantities alongside money. Dimension **hierarchies** (item →
+item group, customer → customer type, account → category) are resolved by joining
+to master data at query time, not by denormalizing parents onto every fact row.
+
+**This maps almost perfectly onto Carbon's existing model:** the GL already carries
+rich per-line analytical tags via the `journalLineDimension` join table (12 entity
+types actively populated at posting time), but **every current report aggregates by
+account only** — no dimension is a query parameter anywhere. The feature is the
+missing aggregation-by-dimension path plus a pivot UI on top of data we already
+capture.
+
+## Competitors Surveyed
+
+- **SAP S/4HANA** — enterprise reference. Universal Journal (ACDOCA) puts every
+ dimension as a column on each line; CO-PA is the dedicated profitability
+ slice/dice cube; statistical key figures mix non-financial quantities with money.
+- **Sage Intacct** — the market leader in *multidimensional* mid-market accounting
+ and the feature the user explicitly wants to emulate. Dimensions tag every
+ transaction and propagate to the GL; Interactive Custom Report Writer (ICRW) is
+ the drag-and-drop pivot builder; statistical accounts cover operational metrics.
+- **NetSuite** — custom segments (`cseg…`) extend the native four classifications;
+ SuiteAnalytics Workbook is the modern Rows/Columns/Measures pivot; Saved Searches
+ are the grouping-based analytics workhorse.
+- **QuickBooks Online / Xero** — small-business reference showing the *minimum
+ viable* dimension model (2 lightweight tracking categories / classes + a canned
+ "P&L by <dimension>" report). Useful as the floor, not the target.
+
+## Key Consensus Patterns
+
+### 1. Multidimensional GL — tag the line, pivot the ledger
+- **SAP**: ACDOCA carries profit center, cost center, functional area, segment,
+ WBS, customer, product, and CO-PA market-segment characteristics as native
+ columns on every journal line — one harmonized table, no FI/CO reconciliation.
+- **Intacct**: every transaction is tagged with multiple dimension values
+ (Location, Department, Project, Customer, Vendor, Employee, Item, Class, +
+ user-defined) that **propagate down to the GL entries**, so slicing needs no
+ extra accounts.
+- **NetSuite**: native Subsidiary/Department/Class/Location + custom segments,
+ applied at body and/or line, flagged "GL Impact" so they flow to postings.
+- **Xero/QBO**: the lite version — 2 tracking categories (Xero) / Class + Location
+ (QBO) tagged per line.
+- **Rationale**: a fat segmented account number or a per-breakdown report doesn't
+ scale; tagging the line once and grouping at read time answers unlimited
+ questions from the same books.
+
+### 2. The pivot builder — Rows / Columns / Values / Filters shelves
+- **NetSuite Workbook**: drag fields into Rows, Columns, Measures; each measure has
+ its own summary type (sum/count/avg/min/max); nested row fields form an
+ expand/collapse hierarchy with per-level subtotals; Top-10/Bottom-10 filters;
+ double-click a cell drills to source records.
+- **Intacct ICRW**: canvas drag-and-drop; Define (columns) → Refine (reorder +
+ calculated columns) → Views (pivot + grouping) → Prompts (run-time filters) →
+ drill-to-source.
+- **SAP KE30**: OLAP drill-down report — start aggregated, drill characteristic by
+ characteristic (country → customer → product), dynamically re-pivot.
+- **Power BI / Excel / Metabase**: identical four-well model.
+- **Rationale**: this interaction model is so universal that users already know it;
+ an ERP should copy it rather than invent. **Copyable model**: field list → four
+ droppable shelves → per-Value aggregation dropdown → indented expand/collapse row
+ tree with subtotals + grand total → double-click drills to journal lines.
+
+### 3. Natural sign — present magnitudes, not raw debit/credit
+- Assets/expenses are normal-debit; liabilities/equity/revenue are normal-credit.
+ Every tool applies a **"normal balance by account type" sign rule** so revenue
+ *and* expense both surface as positive magnitudes, with a per-report "reverse
+ sign" escape hatch (NetSuite "Account Format: Reverse Sign"; Intacct derives sign
+ from the account group's normal balance).
+- **Rationale**: raw debit/credit signs read backwards to business users. Carbon
+ already has this: `applyRootSignCorrection` / `rootSignMultiplier(class)` in
+ `accounting.service.ts`.
+
+### 4. Operational (non-financial) analytics — two mechanisms
+- **(a) Dimension-tag the GL line** and pivot the ledger directly (Intacct/BC
+ "default dimensions", SAP CO-PA characteristics). Answers anything expressible in
+ **money** along any tagged dimension ("sales by customer type", "cost by item
+ group"). Fast, always consistent with the books.
+- **(b) Statistical accounts / statistical key figures** carry **quantities** that
+ don't have to balance (units produced, scrap units, headcount) tagged by the same
+ dimensions, rolled in next to money to compute ratios (revenue/employee,
+ cost/unit). This is how Intacct/SAP answer "biggest causes of scrap" purely
+ inside accounting.
+- Modern mid-market ERPs favor **(a) + (b)**, deferring a separate star-schema
+ warehouse **(c)** until volume/BI demand justifies the ETL.
+- **Note for Carbon**: journal lines already carry a `quantity` column *and*
+ dimensions — so pattern (a) works today for money, and (a)-with-quantity gives us
+ most of (b)'s value without a separate statistical ledger. The gap is that some
+ operational dimensions (ScrapReason, Department) aren't yet tagged at posting.
+
+### 5. Dimension hierarchies — resolve parents at query time
+- Store only the **leaf** dimension value on the fact line; keep parent
+ relationships on master data (item → itemGroup, customer → customerType, account
+ → category) and resolve roll-ups with a **join at pivot time** (SQL `GROUP BY
+ ROLLUP` or a hierarchy join). Re-parenting a value reclassifies history
+ automatically — no fact backfill.
+- **Rationale**: matches how Carbon's financial statements already roll accounts up
+ their category tree; keeps the fact table narrow.
+
+### 6. Saved / shared report definitions
+- Every tool lets a user **save ("memorize")** a customized report (its
+ rows/columns/measures/filters), **share** it (public flag + role/group/user
+ grants), **schedule + email/export** (PDF/CSV/Excel), and organize into groups.
+- **Rationale**: a pivot builder is only useful if the good pivots become
+ reusable, shareable saved views. Carbon already has `reportPin` (per-user
+ pinning) as a seed of this.
+
+### 7. Performance — narrow indexed fact + optional pre-aggregation
+- Interactive pivots run **on-the-fly `GROUP BY`** over a well-indexed journal-line
+ table (composite index on `companyId, period, account, <dimension>`); the hot,
+ repetitive reports are backed by **pre-aggregated period-balance summary tables /
+ materialized views** (Oracle `GL_DAILY_BALANCES` pattern — maintain
+ balances-by-account-by-period(-by-dimension) incrementally at post time).
+- **Rationale**: don't re-sum millions of lines per report; but don't build a
+ warehouse before you need it. Carbon already has `accountingPeriodBalance`
+ snapshots + the `accountTreeBalance*` RPCs for the account-only path — the
+ dimensional path can start as on-the-fly `GROUP BY` and add a summary rollup only
+ if volume bites.
+
+## Answers to Research Questions
+
+1. **Dimension data model** — Tag each transaction/journal line with N dimension
+ values that propagate to the GL. Standard set spans Location, Department,
+ Project, Customer, Vendor/Supplier, Employee, Item, Class, Cost Center + custom.
+ Values form parent/child **hierarchies** with roll-up. SAP puts them as columns
+ (ACDOCA); Intacct/NetSuite as tags/segments; Xero/QBO cap at ~2 lightweight ones.
+ **Carbon uses a normalized join table** (`journalLineDimension`) keyed by
+ `entityType` — closer to Intacct's tag model than SAP's column model.
+
+2. **Report-builder UX** — Converged **Rows / Columns / Values / Filters** shelves;
+ drag fields in; per-measure aggregation (sum/count/avg/min/max); nested row
+ groups expand/collapse with per-level subtotals + grand total; double-click a
+ cell drills through to the underlying transaction lines; run-time filter prompts.
+
+3. **Measures** — Sum of **signed GL amount** (with a natural-sign-by-account-type
+ presentation flip), **quantity**, **count**, and calculated/formula measures.
+ Amount must balance per journal; quantity need not — which is what enables
+ operational metrics.
+
+4. **Operational questions** — "biggest causes of scrap" / "sales by customer type"
+ / "what item groups drove inventory": answered by grouping the dimension-tagged
+ ledger (money and/or quantity), optionally supplemented by statistical accounts.
+ Requires the relevant lines to actually be tagged with the operational dimension
+ at posting time.
+
+5. **Saved/shared definitions** — Save a pivot config, share via public flag +
+ role/group/user grants, schedule + email, export PDF/CSV/Excel, organize into
+ groups. Permissions gate who can run/edit.
+
+## Competitor-Specific Details
+
+### Sage Intacct (the primary model to emulate)
+- **Standard dimensions** (module-gated): Location, Department, Vendor, Customer,
+ Employee, Project, Item, Class, + Affiliate, Asset, Contract, Cost type, Task,
+ Warehouse. **User-defined dimensions** via Platform Services (custom objects
+ flagged `userDefinedDimension` / `enabledInGL`).
+- **Dimension groups** (a named member set — manual or rule-based "all members
+ matching criteria" — surfaced as a filter dropdown), **dimension structures** (a
+ group of groups; financial-statement columns/rows with "roll up child amount"),
+ and **dimension relationships** (auto-fill/restrict one dimension from another at
+ entry). The user's `no-matrix-config` preference aligns with groups + relationships,
+ not a classification matrix.
+- **Statistical accounts**: non-financial quantities, don't balance, rolled into
+ account groups to appear beside money; "dimension count rules" can auto-post them.
+- **ICRW** tiers: Financial Report Writer (GAAP statements) → Custom Report Writer
+ → Interactive Custom Report Writer (the pivot) → Interactive Visual Explorer (BI
+ charts).
+
+### NetSuite
+- **Custom segments** (`cseg…`) with GL-Impact flag, body/line placement,
+ parent/child hierarchies, dependent "Filter By" cascades, up to 2 "balancing"
+ segments. **Saved Searches**: Criteria + Results with per-column **Summary Types**
+ (Group / Sum / Count / Avg / Min / Max) → grouped summary rows + drill-down; group
+ by *any* field incl. non-financial (item group, customer category, custom
+ segment). **SuiteAnalytics Workbook**: dataset (joined records) → Rows/Columns/
+ Measures pivot + calculated measures + drill to cell detail.
+
+### SAP S/4HANA
+- **ACDOCA** = every dimension as a column on one line-item table; coding-block
+ (CI_COBL / OXK3) extensibility propagates custom fields into the journal.
+- **CO-PA**: characteristics (dimensions) + value fields or (account-based) GL
+ accounts as measures; **derivation strategies** auto-populate dependent
+ characteristics from master data (customer → region/group); **KE30** drill-down.
+- **Statistical key figures**: non-monetary values (headcount, m², units, scrap
+ qty) as allocation bases and for ratio reporting.
+
+### QuickBooks Online / Xero (the floor)
+- **Xero**: max **2** tracking categories, ~100 options each, tagged per line; "P&L
+ by tracking category" report.
+- **QBO**: **Class** (per line or per transaction) + **Location** (per transaction);
+ Plus caps class+location+sub-items at 40 combined, Advanced unlimited; "P&L by
+ Class / by Location" reports. Reports are Customized → Save-as/memorized → shared
+ → scheduled.
+
+## Recommended Approach for Carbon
+
+Follows the **Sage Intacct multidimensional-GL + interactive pivot** pattern,
+grounded in Carbon's existing `journalLineDimension` model and reporting base.
+
+1. **Reuse the existing dimension tag layer as the analytics substrate.** Carbon's
+ `journalLineDimension(journalLineId, dimensionId, valueId)` is exactly Intacct's
+ "tag propagated to the GL line" pattern. No schema change to *capture* dimensions
+ — the data is already there for 12 entity types.
+
+2. **Build the missing aggregation-by-dimension path.** Every current report
+ aggregates by account only (snapshot-based `accountTreeBalance*` RPCs, no
+ dimension params). Add a new query/RPC that joins
+ `journalLines` → `journalLineDimension`, resolves `valueId` per `entityType`
+ against its source table, filters (period, company, account scope, dimension
+ filters), and groups by 1–2 chosen dimensions — returning **sum(signed amount)**
+ and **sum(quantity)** with the natural-sign correction already in the codebase.
+
+3. **Adopt the Rows/Columns/Values/Filters pivot UX** but scoped to what's
+ achievable: a **Group-By (rows) + optional pivot dimension or period (columns) +
+ measure (amount/quantity/count) + dimension filters** control bar, an
+ expand/collapse row-group tree (reuse `TreeView`/`useTree` + `reportTree.ts`),
+ subtotals + grand total, and **double-click drill-through** to the journal lines
+ behind a cell (reuse the existing `AccountLedgerDrawer` pattern).
+
+4. **Consolidate hardcoded per-dimension reports into generic measure-anchored
+ reports** (per the user's steer): "Revenue", "Expenses", "COGS", "Inventory
+ Change", "Scrap" become generic reports whose Group-By is interactive. The
+ existing `revenue-by-customer` / `expenses-by-supplier` routes become **preset
+ views** (a saved Group-By selection) of the generic reports.
+
+5. **Resolve hierarchies at query time**, not by denormalizing: group by the leaf
+ value and, where a parent exists (item → itemGroup, customer → customerType),
+ offer the parent as its own Group-By option resolved via a master-data join —
+ mirroring the account-category roll-up financial statements already use.
+
+6. **Natural sign + quantity as first-class measures.** Reuse
+ `rootSignMultiplier` / `applyRootSignCorrection` so revenue and expense read
+ positive; expose `quantity` as a measure so operational questions ("scrap units
+ by reason", "units by item group") work from the same pivot.
+
+7. **Close the operational-tagging gap as needed.** "Biggest causes of scrap"
+ requires the ScrapReason dimension to actually be tagged on the relevant journal
+ lines — today `post-inventory-adjustment` writes zero dimensions and `ScrapReason`/
+ `Department` are enum values without writers. Decide in the spec whether v1 ships
+ only the dimensions already populated (Location, Item, ItemPostingGroup,
+ Customer, CustomerType, Supplier, SupplierType, CostCenter, WorkCenter, Process,
+ FixedAssetClass, Employee) and defers scrap/department tagging to a follow-up, or
+ includes the posting-function changes to tag them.
+
+8. **Saved views over a config engine.** Start with saved/shareable pivot
+ definitions (extend the `reportPin` idea into named, shareable report views)
+ rather than a heavyweight report-writer. No classification-matrix config
+ (consistent with the `no-matrix-config` preference).
+
+9. **Performance: on-the-fly `GROUP BY` first.** Index `journalLineDimension` and
+ the `journalLines` view path on `(companyId, dimensionId, valueId)` /
+ `(companyId, accountId, postingDate)`; only add a pre-aggregated per-period,
+ per-dimension summary table (Oracle `GL_DAILY_BALANCES` style) if interactive
+ latency becomes a problem. Don't build a warehouse up front.
+
+## Open Questions to Carry Into the Spec
+
+- **Scrap/Department tagging**: v1 scope — ship only already-populated dimensions,
+ or extend posting functions (esp. `post-inventory-adjustment`) to tag ScrapReason
+ / Department so "biggest causes of scrap" works day one?
+- **Measure set for v1**: amount + quantity + count enough, or do we need
+ calculated/ratio measures (cost per unit)?
+- **Columns/pivot axis**: support a full second (column) pivot dimension in v1, or
+ ship rows-group + period-columns first and add a free column dimension later?
+- **Saved views scope**: per-user pins only (like `reportPin` today), or
+ shareable/company-wide saved pivots with permissions in v1?
+- **Which generic reports to seed**: Revenue, Expenses, COGS, Inventory Change,
+ Scrap — and how existing narrow reports migrate to presets.
+- **Aggregation home**: new Postgres RPC (consistent with `accountTreeBalance*`) vs.
+ a Kysely query in the service layer — and whether it can reuse period-bucket
+ logic (`computeReportPeriodBuckets`).
+
+## Sources
+
+### Sage Intacct
+- https://www.intacct.com/ia/docs/en_US/help_action/Intacct_basics/Dimensions/basics-dimensions-overview.htm
+- https://developer.intacct.com/api/platform-services/dimensions/
+- https://www.intacct.com/ia/docs/en_GB/help_action/Reporting/Get_started/report-types.htm
+- https://www.intacct.com/ia/docs/en_US/help_action/Reporting/Interactive_custom_reports/Intro/interactive-custom-report-writer-overview.htm
+- https://www.intacct.com/ia/docs/en_US/help_action/General_Ledger/Setup/Statistical_accounts_and_journals/track-statistical-data-overview.htm
+- https://www.claconnect.com/en/resources/blogs/sage/sage-intacct-reports-dimension-groups-and-dimension-structures
+- https://planergy.com/blog/sage-intacct-dimensions/
+- https://intellitecsolutions.com/sage-intacct-best-practices-standard-user-defined-dimensions/
+
+### NetSuite
+- https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_4313464596.html
+- https://www.houseblend.io/articles/netsuite-custom-segments-setup-gl-impact
+- https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_N648820.html
+- https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_158042187611.html
+- https://www.salto.io/blog-posts/netsuite-suiteanalytics-workbook-guide
+- https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_3891485192.html
+- https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_0801122218.html
+
+### SAP
+- https://www.cbs-consulting.com/us/sap-universal-journal-acdoca/
+- https://blog.sap-press.com/what-is-saps-universal-journal
+- https://community.sap.com/t5/technology-blog-posts-by-members/the-ultimate-sap-s-4hana-guide-to-profitability-analysis-co-pa/ba-p/14223304
+- https://learning.sap.com/courses/profitability-analysis-in-sap-s-4hana/defining-a-derivation-strategy
+- https://blog.sap-press.com/account-based-co-pa-in-sap-s4hana-how-margin-analysis-works-in-the-universal-journal
+- https://erproof.com/co/sap-co-training/sap-statistical-key-figures/
+- https://www.michaelmanagement.com/blog/sap/a-look-at-statistical-key-figures-and-reporting
+
+### QuickBooks Online / Xero
+- http://elearningresources.blob.core.windows.net/cloudhelp/Desktop/Content/Connect/Xero-tracking.htm
+- https://www.ledgerlogic.ca/blog/xero-tracking-categories-guide
+- https://quickbooks.intuit.com/learn-support/en-us/help-article/class-list/track-transactions-class/L927QQfNV_US_en_US
+- https://fitsmallbusiness.com/using-classes-and-locations-quickbooks-online/
+- https://quickbooks.intuit.com/learn-support/en-us/help-article/memorizing-reports/create-access-modify-memorized-reports/L8TUb2B8j_US_en_US
+
+### Pivot UX / operational analytics / performance
+- https://learn.microsoft.com/en-us/power-bi/paginated-reports/report-builder-tables-matrices-lists
+- https://learn.microsoft.com/en-us/power-bi/guidance/star-schema
+- https://www.sqlbi.com/articles/controlling-drillthrough-in-excel-pivottables-connected-to-power-bi-or-analysis-services/
+- https://blog.prolecto.com/2013/03/14/the-pluses-and-minuses-of-netsuite-financial-statement-polarity/
+- https://businesscentralinsights.com/analyze-data-by-dimensions
+- https://medium.com/learning-sql/olap-hierarchical-aggregation-with-sql-6c45ebc206d7
+- https://blogs.oracle.com/erp-ace/cloud-gls-daily-pl-reporting
+- https://support.boldbi.com/kb/article/15430/summary-tables-vs-materialized-views-a-comparison
diff --git a/.ai/runs/2026-08-09-dimensional-pivot-reporting.md b/.ai/runs/2026-08-09-dimensional-pivot-reporting.md
new file mode 100644
index 0000000000..69570e63dc
--- /dev/null
+++ b/.ai/runs/2026-08-09-dimensional-pivot-reporting.md
@@ -0,0 +1,22 @@
+# Feature run: Dimensional pivot-table analytics reporting
+
+- Date: 2026-08-09
+- Mode: approval-per-phase
+- Request: Add groupable pivot-table analytics reporting that leverages the dimensions layer on journal entry lines — slice/dice across reports to answer questions like biggest causes of scrap, what customer types drive sales, what item groups caused inventory to change. Inspired by Sage Intacct's dimensional reporting. Build via research → spec → plan.
+- Phase plan: research [run — ERP-domain, dimensional analytics/BI; anchor design in industry practice] · spec [run — new data model + reporting surface, crosses accounting/reporting modules, 3+ files] · plan [run] · execute [skip for now — user scoped to "spec and then a plan"] · test [skip — no build yet] · self-review [skip — no build yet]
+
+## Decisions
+- (approval mode — human resolves the two 🛑 gates)
+
+## Design steers (from user, in-flight)
+- **Collapse hardcoded per-dimension reports into generic measure-anchored reports.** Instead of separate "Revenue by Customer" / "Expense by Supplier" routes, have a small set of generic reports ("Revenue", "Expenses", COGS, "Inventory Change", scrap, etc.) where the Group-By dimension is chosen interactively in the pivot UI. "Revenue by customer" and "revenue by customer type" become the same report with a different Group-By selection. Existing narrow reports become preset views of the generic ones. — 2026-08-09
+
+## Phase log
+- research: DONE → .ai/research/dimensional-pivot-reporting.md (5 subagents: codebase map + Intacct + NetSuite + SAP/QBO/Xero + pivot-UX/perf). Key: Carbon already has journalLineDimension tag layer (12 entity types populated); all current reports aggregate by account only; ScrapReason/Department enum values have no posting writers (scrap-tagging gap).
+- spec: DONE → .ai/specs/2026-08-09-dimensional-pivot-reporting.md. Abbreviated interview (4 Qs): Q1=(a) seeded account-class scopes + replace narrow reports with preset redirects; Q2=(b) full shelf model (≤2 row dims + free column axis); Q3=(c) shareable saved views day one; Q4=(b) amount+quantity+count (+% of total toggle). Correction found during design: ScrapReason IS tagged since #1355 (codebase map was stale on this) — no posting changes needed.
+- plan: DONE → .ai/plans/2026-08-09-dimensional-pivot-reporting.md (12 tasks: migration w/ full RPC SQL → rolled-back psql validation w/ fixtures → apply+generate:types → models registry/validators → service fns → pivotTree pure lib+tests → PivotControlBar/SaveViewModal → PivotTree/PivotLinesDrawer → routes+path → redirects+hub+dead-code → i18n/lint → /test browser verification). Spec approved by Brad before planning.
+
+
+## Outcome
+- Plan approved by Brad; /execute ran Tasks 1–11 (9 commits on financial-reports-module, pushed: 5e8f15541..3f6377a30). All gates green: rolled-back SQL validation (all asserts), 13 pivotData unit tests, scoped typecheck, biome, repo test pass (22 tasks). i18n: 225/300 msgstrs filled; hi/tr/ko deferred per Brad (session limit). Deviations: pivotTree.ts renamed pivotData.ts (case-collision with PivotTree.tsx); drill-through drawer shows journalEntryId as text (RPC lacks journal.id — follow-up candidate); tool-metadata.json rode along in Task-5 commit (schema-derived regen).
+- Task 12 (browser verification): Brad is handling manually.
diff --git a/.ai/specs/2026-08-09-dimensional-pivot-reporting.md b/.ai/specs/2026-08-09-dimensional-pivot-reporting.md
new file mode 100644
index 0000000000..6ab61aa569
--- /dev/null
+++ b/.ai/specs/2026-08-09-dimensional-pivot-reporting.md
@@ -0,0 +1,404 @@
+# Dimensional Pivot Reporting (Analytics on the Journal Dimension Layer)
+
+> Status: draft
+> Author: Claude (with Brad Barbin)
+> Date: 2026-08-09
+> Research: `.ai/research/dimensional-pivot-reporting.md`
+> Related: `.ai/specs/2026-07-02-financial-reporting.md` (reporting base),
+> `.ai/specs/2026-07-04-segment-reporting.md` (Segment dimension — complementary;
+> once implemented, Segment becomes one more Group-By option here)
+
+## TLDR
+
+A small set of **generic, measure-anchored analytics reports** — Revenue,
+Expenses, COGS, Inventory Change, Scrap — each defined by a declarative
+**account scope** (class/type/configured-account filter over the GL), rendered
+as an **interactive pivot**: up to 2 nested row Group-By dimensions, a free
+column axis (period buckets *or* a dimension), measures Amount / Quantity /
+Count with a "% of column total" toggle, dimension filters, and double-click
+**drill-through** to the underlying journal lines. The data substrate is the
+existing `journalLineDimension` tag layer (already populated by every posting
+path for 13+ entity types, including ScrapReason since #1355) — no posting
+changes required. One new plpgsql RPC does the `GROUP BY`; one new table
+(`reportView`) stores **named, shareable saved views** (owner + company-wide
+visibility). The hardcoded `revenue-by-customer` and `expenses-by-supplier`
+reports are **replaced** by presets of the generic reports (old routes
+redirect). This is the Sage Intacct multidimensional-GL pattern
+(rows/columns/values/filters shelf UX per NetSuite SuiteAnalytics) built on
+data Carbon already captures.
+
+## Problem Statement
+
+Carbon's GL carries rich per-line analytical tags — `journalLineDimension`
+rows link every posted journal line to dimension values for Location, Item,
+ItemPostingGroup, Customer, CustomerType, Supplier, SupplierType, CostCenter,
+WorkCenter, Process, FixedAssetClass, Employee, and (as of #1355) ScrapReason —
+but **no report can group or filter by any of them**. Every report on the
+`financial-reports-module` branch aggregates by account only, via the
+snapshot-based `accountTreeBalance*` RPCs, which take no dimension parameters.
+
+Concrete questions a user cannot answer today without SQL:
+
+- *What were my biggest causes of scrap last quarter?* (ScrapReason is tagged
+ on scrap journal lines; nothing reads it.)
+- *Which customer types drive revenue?* (CustomerType is tagged by
+ `post-sales-invoice`; the only report is a hardcoded revenue-by-**customer**.)
+- *Which item groups caused inventory to go up?* (ItemPostingGroup + Item are
+ tagged on every inventory posting; inventory reports show accounts only.)
+
+Each new question currently requires a new hardcoded report
+(`revenue-by-customer.tsx`, `expenses-by-supplier.tsx`, …) — an unscalable
+pattern the industry abandoned for the multidimensional-GL + pivot approach
+(see research: Intacct dimensions/ICRW, NetSuite Workbook, SAP CO-PA).
+
+## Proposed Solution
+
+### Concept model
+
+```
+Generic report (code registry, seeded) Pivot state (URL params / saved view)
+┌─────────────────────────────┐ ┌────────────────────────────────┐
+│ key: "revenue" │ │ rows: [CustomerType, Item] │
+│ name: "Revenue" │ + │ columns: period:month | dimId │
+│ accountScope: │ │ measure: amount|quantity|count │
+│ class = 'Revenue' │ │ filters: {dimId: [valueIds]} │
+│ sign: natural (as stored) │ │ period: startDate..endDate │
+└─────────────────────────────┘ └────────────────────────────────┘
+ │ │
+ └──────────────┬───────────────────────┘
+ ▼
+ RPC journalDimensionPivot (plpgsql GROUP BY over
+ journalLines ⨝ journalLineDimension, posted only)
+ ▼
+ Pivot tree: nested row groups + column matrix,
+ subtotals, grand total, Unassigned bucket,
+ double-click cell → drill-through drawer (journal lines)
+```
+
+### Seeded generic reports (v1)
+
+| Key | Name | Account scope | Notes |
+|-----|------|---------------|-------|
+| `revenue` | Revenue | `account.class = 'Revenue'` | replaces revenue-by-customer |
+| `expenses` | Expenses | `account.class = 'Expense'` | replaces expenses-by-supplier; includes COGS/Tax/Other Expense types |
+| `cogs` | COGS | `account.accountType = 'Cost of Goods Sold'` | subset of Expenses |
+| `inventory-change` | Inventory Change | `account.accountType = 'Inventory'` | net change (not balance) over the period |
+| `scrap` | Scrap | accounts designated as scrap accounts: `accountDefault.scrapAccount` + posting-group overrides where present | default rows preset: ScrapReason |
+
+The registry lives in code (`accounting.models.ts`), not in a DB table — no
+config surface, consistent with the no-matrix-config rule. Each report page
+shows its account scope as a read-only chip so users can see what's included.
+User-defined account scopes are explicitly deferred.
+
+### Sign convention
+
+Stored `journalLine.amount` is signed so that **positive moves the account
+toward its natural balance** (lesson: `journalEntries` view derives
+debit/credit from class + sign). Within a single-class account scope,
+`SUM(amount)` therefore already reads naturally: positive revenue = more
+revenue, positive inventory change = inventory up, positive scrap = more scrap
+cost. No `rootSignMultiplier` correction is needed inside one scope (it exists
+for cross-class trees). The plan must include a seeded-data verification of
+this before the RPC is finalized.
+
+### Untagged lines
+
+Lines in scope with no tag for a chosen Group-By dimension group into an
+explicit **Unassigned** bucket (consistent with the segment-reporting spec's
+Unassigned concept). History is never rewritten; pre-dimension lines simply
+report as Unassigned.
+
+### Design Decisions
+
+| Decision | Choice | Rationale |
+|----------|--------|-----------|
+| Report anchoring | Seeded account-class/type scopes in a code registry (**user choice Q1: a**) | Zero config, covers the motivating questions; account-scope builder deferred |
+| Fate of narrow reports | Replace: routes redirect to generic-report preset URLs, hub cards repointed (**user choice Q1**) | One code path; old links keep working |
+| Pivot capability v1 | Full shelf model: ≤2 nested row dims + free column axis (period buckets *or* one dimension) (**user choice Q2: b**) | NetSuite-Workbook parity; period is just another column option |
+| Saved views | New `reportView` table, named views, owner + company-wide visibility from day one (**user choice Q3: c**) | Intacct/NetSuite parity; config is also URL-encoded so copy-paste links work |
+| Measures v1 | Amount + Quantity + Count, plus a presentation-only "% of column total" toggle (**user choice Q4: b**) | `journalLine.quantity` already populated by inventory/scrap postings; ratios/calculated measures deferred |
+| Aggregation home | New **plpgsql** RPC `journalDimensionPivot`, on-the-fly `GROUP BY`, posted (non-Draft) lines only | Consistent with existing report RPCs; plpgsql avoids the `LANGUAGE sql` inlining/ORDER-BY pitfall (lessons); no summary table until latency demands it |
+| Dimension hierarchy | No hierarchy joins in v1 — parent classifications (CustomerType, SupplierType, ItemPostingGroup) are *already separate tagged dimensions* | Grouping by "customer type" needs no customer→type join; matches how posting writes tags today |
+| Company scope | Single company per pivot in v1; multi-company consolidation + currency translation deferred | Translation machinery (`translateCompanyBalances`) is account-series-shaped; dimensions are companyId-scoped tags; cross-company pivot is a clean fast-follow |
+| Row cap | RPC caps distinct row groups at 1,000, returns a `hasMore` flag; UI shows an explicit "showing top 1,000 groups by measure" banner | No silent truncation; protects against group-by-Item on huge datasets |
+| Multi-tenancy (H1) | `reportView` has `companyId`, composite PK `("id","companyId")`, `id('rv')` default | Convention |
+| Service shape (H2) | All new fns in `accounting.service.ts` take `client` first, return `{data, error}` | One service file per module rule |
+| RLS (H3) | `reportView`: SELECT own-or-company-shared; INSERT/UPDATE/DELETE owner only; simple policy names + `::text[]` helper casts | RLS conventions |
+| Permissions (H4) | Routes gate `requirePermissions(request, { view: "accounting", role: "employee" })`, same as sibling report routes | Reports are accounting-view surfaces |
+| Forms (H5) | Save-view modal uses `ValidatedForm` + zod validator + route action | Form conventions |
+| Module layout (H6) | Models/validators in `accounting.models.ts`, service fns in `accounting.service.ts`, UI in `modules/accounting/ui/Reports/`, routes in `x+/reports+/` | Existing reporting-base layout |
+| Backward compat (H7) | Old report URLs 302-redirect with preset params; `reportPin` keys for removed reports migrate to the new report keys | No FROZEN surface touched |
+| Drill-through | Second RPC `journalDimensionPivotLines` returns the journal lines behind a cell; rendered in a drawer (AccountLedgerDrawer pattern) | PostgREST can't express N dimension-tag joins; Drawer per detail-view convention |
+| Value-name resolution | RPC returns `valueId`s; names resolved per entityType via the existing `getEntityDimensionValues` resolution logic, batched in the service | Avoids a 15-table CASE join in SQL; high-cardinality entities stay lazy |
+| Export | CSV via the existing `exportReport.ts` pattern | Parity with sibling reports |
+
+## Data Model Changes
+
+No changes to `journalLine`, `journalLineDimension`, `dimension`, or any
+posting path.
+
+### New table: `reportView`
+
+```sql
+CREATE TYPE "reportViewVisibility" AS ENUM ('Private', 'Company');
+
+CREATE TABLE "reportView" (
+ "id" TEXT NOT NULL DEFAULT id('rv'),
+ "companyId" TEXT NOT NULL,
+ "reportKey" TEXT NOT NULL, -- 'revenue' | 'expenses' | 'cogs' | 'inventory-change' | 'scrap'
+ "name" TEXT NOT NULL,
+ "config" JSONB NOT NULL, -- validated pivot state: rows[], columnAxis, measure, filters, period prefs
+ "visibility" "reportViewVisibility" NOT NULL DEFAULT 'Private',
+
+ "createdBy" TEXT NOT NULL REFERENCES "user"("id"),
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "updatedBy" TEXT REFERENCES "user"("id"),
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+
+ CONSTRAINT "reportView_pkey" PRIMARY KEY ("id", "companyId"),
+ CONSTRAINT "reportView_companyId_fkey" FOREIGN KEY ("companyId")
+ REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT "reportView_name_unique" UNIQUE ("companyId", "reportKey", "name")
+);
+
+CREATE INDEX "reportView_companyId_idx" ON "reportView" ("companyId");
+CREATE INDEX "reportView_createdBy_idx" ON "reportView" ("createdBy");
+
+ALTER TABLE "reportView" ENABLE ROW LEVEL SECURITY;
+
+CREATE POLICY "SELECT" ON "reportView" FOR SELECT USING (
+ "companyId" = ANY ((SELECT get_companies_with_employee_role())::text[])
+ AND ("visibility" = 'Company' OR "createdBy" = (SELECT auth.uid())::text)
+);
+CREATE POLICY "INSERT" ON "reportView" FOR INSERT WITH CHECK (
+ "companyId" = ANY ((SELECT get_companies_with_employee_role())::text[])
+ AND "createdBy" = (SELECT auth.uid())::text
+);
+CREATE POLICY "UPDATE" ON "reportView" FOR UPDATE USING (
+ "companyId" = ANY ((SELECT get_companies_with_employee_role())::text[])
+ AND "createdBy" = (SELECT auth.uid())::text
+);
+CREATE POLICY "DELETE" ON "reportView" FOR DELETE USING (
+ "companyId" = ANY ((SELECT get_companies_with_employee_role())::text[])
+ AND "createdBy" = (SELECT auth.uid())::text
+);
+```
+
+### New RPC: `journalDimensionPivot` (plpgsql)
+
+Signature sketch (exact SQL in the plan; fork period-bucket handling from the
+newest `accountTreeBalancePeriodSeries` definition per the migration lesson):
+
+```
+journalDimensionPivot(
+ p_company_id TEXT,
+ p_start_date DATE,
+ p_end_date DATE,
+ p_account_classes "glAccountClass"[] DEFAULT NULL, -- scope, OR:
+ p_account_types "accountType"[] DEFAULT NULL,
+ p_account_ids TEXT[] DEFAULT NULL, -- (scrap report)
+ p_row_dimension_1 TEXT DEFAULT NULL, -- dimension.id
+ p_row_dimension_2 TEXT DEFAULT NULL,
+ p_column_dimension TEXT DEFAULT NULL, -- mutually exclusive with p_period_ends
+ p_period_ends DATE[] DEFAULT NULL, -- from computeReportPeriodBuckets
+ p_filters JSONB DEFAULT NULL -- [{dimensionId, valueIds[]}]
+) RETURNS TABLE (
+ rowValue1Id TEXT, -- NULL = Unassigned
+ rowValue2Id TEXT,
+ columnKey TEXT, -- valueId or periodEnd::text
+ amount NUMERIC, -- SUM(jl.amount), natural-signed within scope
+ quantity NUMERIC, -- SUM(jl.quantity)
+ lineCount BIGINT
+)
+```
+
+Semantics:
+
+- Reads the `journalLines` view (excludes `status = 'Draft'`), filtered by
+ `companyId`, `postingDate` range, and the account scope (exactly one of
+ classes/types/ids provided by the report registry).
+- One `LEFT JOIN journalLineDimension` per selected dimension (max 3), each
+ constrained to its `dimensionId`; `NULL` valueId groups as Unassigned.
+- Filters are `EXISTS` subqueries per filter dimension.
+- Caps output at 1,000 distinct (row1, row2) groups ordered by
+ `ABS(SUM(amount))` DESC, plus a sentinel row / separate `hasMore` signal.
+- Ordering is re-applied in the app (RPC ordering is not relied upon — lesson).
+
+### New RPC: `journalDimensionPivotLines` (plpgsql)
+
+Same filter params plus the clicked cell's `(rowValue1Id, rowValue2Id,
+columnKey)`; returns the journal lines (id, postingDate, accountId, account
+name/number, description, documentType, documentId, amount, quantity,
+journalEntryId) behind that cell, capped + ordered by postingDate. Feeds the
+drill-through drawer; its two measure sums must equal the cell.
+
+### Indexes
+
+Verify and add as needed (in the same migration):
+
+```sql
+CREATE INDEX IF NOT EXISTS "journalLineDimension_companyId_dimensionId_valueId_idx"
+ ON "journalLineDimension" ("companyId", "dimensionId", "valueId", "journalLineId");
+```
+
+plus confirmation that the `journalLines` path has a usable
+`(companyId, accountId, postingDate)` index (add if absent).
+
+## API / Service Changes
+
+All in `apps/erp/app/modules/accounting/` (one service, one models file).
+
+`accounting.models.ts`:
+
+- `analyticsReportKeys = ["revenue","expenses","cogs","inventory-change","scrap"] as const`
+- `ANALYTICS_REPORTS` registry: key → name, account scope, default pivot state
+ (e.g. scrap → rows `[ScrapReason]`), i18n label ids.
+- `pivotStateValidator` (zod): `rows` (≤2 dimension ids), `columnAxis`
+ (`{type:"period",bucket:"month"|"quarter"|"year"} | {type:"dimension",dimensionId}`),
+ `measure` (`amount|quantity|count`), `percentOfTotal` (bool), `filters`,
+ `startDate`, `endDate`. Used by both the URL-param parser and
+ `reportViewValidator` (name, reportKey, visibility, config).
+
+`accounting.service.ts`:
+
+- `getDimensionPivot(client, params)` — calls `journalDimensionPivot`, resolves
+ value display names per entityType (batched; reuses the
+ `getEntityDimensionValues` resolution approach), re-sorts, returns groups +
+ `hasMore`.
+- `getDimensionPivotLines(client, params)` — drill-through.
+- `getReportViews(client, {companyId, userId, reportKey?})`,
+ `upsertReportView(client, view)`, `deleteReportView(client, id, companyId)`.
+- Types propagate via `Awaited<ReturnType<...>>` in `types.ts` after
+ `pnpm run generate:types`.
+
+## UI Changes
+
+Routes (`apps/erp/app/routes/x+/reports+/`):
+
+- `analytics.$reportKey.tsx` — the pivot page. Loader: validate `reportKey`
+ against the registry, parse pivot state from URL (fall back to the report's
+ default preset), `requirePermissions({ view: "accounting", role: "employee" })`,
+ run `getDimensionPivot`, load active dimensions for the shelf pickers
+ (`getActiveDimensionsWithValues`; Customer/Supplier/Item values lazy).
+ Action: save/update/delete `reportView`.
+- `analytics.$reportKey.lines.tsx` (or fetcher route) — drill-through drawer
+ data via `getDimensionPivotLines`; rendered as a **Drawer overlay** per the
+ detail-view convention.
+- `revenue-by-customer.tsx` / `expenses-by-supplier.tsx` — replaced by
+ redirects to `analytics/revenue?rows=<customerDimId>` /
+ `analytics/expenses?rows=<supplierDimId>`.
+
+Components (`modules/accounting/ui/Reports/`):
+
+- `PivotControlBar.tsx` — the shelves: Rows (up to 2 dimension selects),
+ Columns (period-bucket segmented control ⟷ dimension select), Values
+ (measure select + %-of-total toggle), Filters (dimension multi-selects),
+ plus the shared `PeriodSelector`, account-scope chip, saved-view picker,
+ Save-view button (`ValidatedForm` modal), CSV export, reset. Built from
+ existing `ReportFilters` parts.
+- `PivotTree.tsx` — nested row groups on `TreeView`/`useTree` (virtualized),
+ column matrix with column subtotals + grand-total row/column, Unassigned
+ bucket, top-1,000 banner when `hasMore`, empty states. Cell click opens the
+ drill-through drawer. Rendering patterned on `MultiPeriodStatementTree`.
+- `pivotTree.ts` — pure pivot-tree assembly from RPC rows (unit-testable,
+ `reportTree.ts` style).
+
+Hub (`x+/accounting+/reports.tsx`): the five generic reports as Analytics
+cards (replacing the two hardcoded analytics cards); shared (`Company`) saved
+views listed under their report; `reportPin` keys for the two removed reports
+migrated to the new keys. `path.ts`: `analyticsReport(key)` +
+`analyticsReportLines(key)` helpers; remove the dead helpers.
+
+i18n: all new strings through Lingui; run `/translate` for the .po catalogs.
+
+## Acceptance Criteria
+
+- [ ] With seeded scrap postings across ≥2 scrap reasons, `analytics/scrap`
+ defaults to rows=ScrapReason and shows one group per reason plus
+ Unassigned, with Amount equal to the scrap account's net change for the
+ period and Quantity matching the scrapped units; sorting by Amount ranks
+ the biggest cause first.
+- [ ] `analytics/revenue` grouped by CustomerType (rows) × month (columns)
+ shows per-type monthly revenue as positive numbers; its grand total
+ equals the Income Statement revenue total for the same period and
+ company.
+- [ ] `analytics/revenue` grouped by Customer reproduces the totals of the old
+ revenue-by-customer report for the same period; `/x/reports/revenue-by-customer`
+ redirects (302) to the preset URL.
+- [ ] `analytics/inventory-change` grouped by ItemPostingGroup shows signed
+ net change per group (positive = inventory up), summing to the inventory
+ accounts' net change for the period.
+- [ ] Rows accepts 2 dimensions (e.g. ScrapReason → Item): child groups render
+ nested under parents with subtotals per parent and a grand total.
+- [ ] Column axis switches between month/quarter/year buckets and a dimension
+ (e.g. Location as columns); column subtotals and grand-total column are
+ correct in both modes.
+- [ ] Measure toggles between Amount, Quantity, Count; % of column total
+ renders shares that sum to 100% per column (Unassigned included).
+- [ ] A dimension filter (e.g. Location = one plant) restricts every cell,
+ subtotal, and drill-through consistently.
+- [ ] Double-clicking a cell opens a Drawer whose journal lines sum exactly to
+ the cell's Amount and Quantity.
+- [ ] Draft journals are excluded everywhere (pivot and drill-through).
+- [ ] Saving a view named "Scrap by reason by plant" with visibility Company
+ makes it appear for a *different* employee of the same company; a
+ Private view does not; only the owner can edit/delete; view names are
+ unique per company+report.
+- [ ] Pivot state round-trips through the URL: copy-pasting the address into
+ another session reproduces the exact pivot.
+- [ ] With >1,000 row groups (group by Item on a large dataset), the UI shows
+ the explicit top-1,000-by-measure banner — no silent truncation.
+- [ ] CSV export contains exactly the rendered rows/columns.
+- [ ] `pnpm exec turbo run typecheck --filter=erp` and scoped tests pass;
+ `pnpm run generate:types` committed after the migration.
+
+## Risks
+
+| Risk | Severity | Mitigation |
+|------|----------|------------|
+| Pivot `GROUP BY` too slow on large journals (3 dimension joins) | Med | Composite indexes; ≤3 dimensions per query; 1,000-group cap; fall back to an incrementally-maintained per-period dimension summary table (Oracle GL_DAILY_BALANCES pattern) only if measured latency demands it |
+| Sign convention misread (stored amount vs class-derived debit/credit) | High if wrong | Lesson documents natural-sign storage; plan includes a seeded-data assertion (revenue positive, scrap positive, inventory-up positive) before UI work |
+| Value-name resolution for high-cardinality entities (Item/Customer/Supplier) | Med | Resolve names only for the ≤1,000 returned group ids, batched per entityType; pickers stay lazy as today |
+| Dimension tagging gaps make reports look wrong (e.g. Department never tagged) | Med | Shelf pickers list only *active* dimensions; Unassigned bucket makes gaps visible instead of silently wrong; Department tagging is a known follow-up |
+| RPC ordering dropped by planner | Low | plpgsql + authoritative re-sort in the service (lesson) |
+| `reportView.config` drift as pivot state evolves | Low | `pivotStateValidator` parses configs on read; invalid saved views fall back to the report default with a toast |
+| Redirects break existing pins/bookmarks | Low | 302 redirects + `reportPin` key migration in the same migration |
+
+## Open Questions
+
+> HARD STOP: Do not proceed with implementation until these are answered.
+
+- [x] What anchors a generic report, and what happens to the existing narrow
+ reports? — **Answer (Brad, 2026-08-09): (a)** seeded account-class/type
+ scopes in code, scope shown as a read-only chip, account-scope builder
+ deferred; `revenue-by-customer` / `expenses-by-supplier` replaced by
+ redirects to generic-report presets.
+- [x] How much pivot in v1? — **Answer (Brad, 2026-08-09): (b)** full shelf
+ model: ≤2 nested row dimensions **and** a free column axis (dimension or
+ period buckets), with column subtotals.
+- [x] Saved views scope? — **Answer (Brad, 2026-08-09): (c)** named saved
+ views with sharing from day one — owner + company-wide visibility flag;
+ config also URL-encoded so links work.
+- [x] Measure set? — **Answer (Brad, 2026-08-09): (b)** Amount + Quantity +
+ Count (with the recommended presentation-only "% of column total"
+ toggle); calculated/ratio measures deferred.
+
+Decisions settled from codebase/research during design (recorded in Design
+Decisions above): plpgsql RPC aggregation home; single-company v1; 1,000-group
+cap; Unassigned bucket; no hierarchy joins (parent types are already separate
+dimensions); drill-through via second RPC + Drawer; value-name resolution in
+the service; CSV export parity.
+
+## Deferred (explicitly out of scope for v1)
+
+- Multi-company consolidation + currency translation on pivots
+- User-defined account scopes / report builder
+- Calculated measures (ratios, cost-per-unit)
+- Scheduled delivery / email of saved views
+- Department tagging at posting time (dimension exists, no writer yet)
+- Pre-aggregated dimension summary table (only if latency demands)
+
+## Changelog
+
+- 2026-08-09: Created after abbreviated grill interview (4 questions resolved
+ by Brad) on top of `.ai/research/dimensional-pivot-reporting.md`.
diff --git a/apps/erp/app/components/Layout/Topbar/Suggestion.tsx b/apps/erp/app/components/Layout/Topbar/Suggestion.tsx
index 9f4ed4202c..8a91e2f12b 100644
--- a/apps/erp/app/components/Layout/Topbar/Suggestion.tsx
+++ b/apps/erp/app/components/Layout/Topbar/Suggestion.tsx
@@ -24,12 +24,13 @@ import data from "@emoji-mart/data";
import { Trans, useLingui } from "@lingui/react/macro";
import { nanoid } from "nanoid";
import type { ChangeEvent } from "react";
-import React, { Suspense, useEffect, useRef, useState } from "react";
+import React, { Suspense, useEffect, useState } from "react";
import { LuImage, LuMegaphone } from "react-icons/lu";
import { useFetcher, useLocation } from "react-router";
import { useUser } from "~/hooks";
import { suggestionValidator } from "~/modules/shared";
import type { action } from "~/routes/x+/resources+/suggestions.new";
+import { useUIStore } from "~/stores/ui";
import { path } from "~/utils/path";
const logger = getLogger("erp", "suggestion");
@@ -49,7 +50,7 @@ const Suggestion = () => {
const { t } = useLingui();
const fetcher = useFetcher<typeof action>();
const location = useLocation();
- const popoverTriggerRef = useRef<HTMLButtonElement>(null);
+ const [open, setOpen] = useState(false);
const [suggestion, setSuggestion] = useState("");
const [emoji, setEmoji] = useState(defaultEmoji);
const [emojiPickerOpen, setEmojiPickerOpen] = useState(false);
@@ -64,6 +65,10 @@ const Suggestion = () => {
const { carbon } = useCarbon();
const user = useUser();
const companyId = user.company.id;
+ const suggestionPrefill = useUIStore((state) => state.suggestionPrefill);
+ const clearSuggestionRequest = useUIStore(
+ (state) => state.clearSuggestionRequest
+ );
useEffect(() => {
if (fetcher.data?.success) {
@@ -73,12 +78,23 @@ const Suggestion = () => {
setAttachment(null);
setAnonymous(true);
setSendToCarbon(CARBON_SLACK_ENABLED);
- popoverTriggerRef.current?.click();
+ setOpen(false);
} else if (fetcher.data?.message) {
toast.error(fetcher.data.message);
}
}, [fetcher.data]);
+ useEffect(() => {
+ if (!suggestionPrefill) return;
+ setSuggestion(suggestionPrefill.suggestion);
+ setAnonymous(suggestionPrefill.anonymous);
+ setSendToCarbon(suggestionPrefill.sendToCarbon);
+ setEmoji(defaultEmoji);
+ setAttachment(null);
+ setOpen(true);
+ clearSuggestionRequest();
+ }, [suggestionPrefill, clearSuggestionRequest]);
+
const uploadImage = async (e: ChangeEvent<HTMLInputElement>) => {
if (e.target.files && carbon) {
const file = e.target.files[0];
@@ -119,8 +135,8 @@ const Suggestion = () => {
};
return (
- <Popover>
- <PopoverTrigger ref={popoverTriggerRef} asChild>
+ <Popover open={open} onOpenChange={setOpen}>
+ <PopoverTrigger asChild>
<Button
variant="secondary"
className="hover:scale-100"
@@ -224,7 +240,7 @@ const Suggestion = () => {
setSuggestion("");
setEmoji(defaultEmoji);
setAttachment(null);
- popoverTriggerRef.current?.click();
+ setOpen(false);
}}
>
<Trans>Cancel</Trans>
diff --git a/apps/erp/app/components/PeriodSelector.tsx b/apps/erp/app/components/PeriodSelector.tsx
index 6219da9b76..1ceb0edb48 100644
--- a/apps/erp/app/components/PeriodSelector.tsx
+++ b/apps/erp/app/components/PeriodSelector.tsx
@@ -5,6 +5,7 @@ import {
PopoverContent,
PopoverTrigger
} from "@carbon/react";
+import { defaultReportRange } from "@carbon/utils";
import type { CalendarDate } from "@internationalized/date";
import {
endOfMonth,
@@ -35,6 +36,12 @@ type PeriodSelectorProps = {
variant?: PeriodSelectorVariant;
/** Fiscal year start month (1-12) from fiscalYearSettings; defaults to January */
fiscalStartMonth?: number;
+ /**
+ * Preset id shown as active when no date params are set — mirrors the
+ * report loader's default range so the trigger label isn't misleading
+ * (e.g. "last-6-months" instead of "All Time").
+ */
+ defaultPresetId?: string;
};
function quarterStart(date: CalendarDate): CalendarDate {
@@ -72,7 +79,8 @@ function presetDates(preset: PeriodPreset): string | null {
const PeriodSelector = ({
variant = "range",
- fiscalStartMonth = 1
+ fiscalStartMonth = 1,
+ defaultPresetId
}: PeriodSelectorProps) => {
const { t } = useLingui();
const [params, setParams] = useUrlParams();
@@ -144,6 +152,13 @@ const PeriodSelector = ({
startDate: lastQuarterStart.toString(),
endDate: thisQuarterStart.subtract({ days: 1 }).toString()
},
+ {
+ id: "last-6-months",
+ label: t`Last 6 Months`,
+ // Shares its bounds with the loaders' `defaultReportRange`, so the
+ // default label and the queried window can never drift.
+ ...defaultReportRange(now.toString())
+ },
{
id: "this-year",
label: t`This Fiscal Year`,
@@ -161,19 +176,27 @@ const PeriodSelector = ({
label: t`Fiscal Year to Date`,
startDate: fyStart.toString(),
endDate: now.toString()
- },
- {
- id: "all-time",
- label: t`All Time`
}
];
}, [variant, fiscalStartMonth, t]);
- const activePreset = presets.find((preset) =>
- variant === "asOf"
- ? preset.endDate === endDate
- : preset.startDate === startDate && preset.endDate === endDate
- );
+ // Every range report opens on the trailing six months and every as-of report
+ // on today; the loaders default their data to the matching window. Callers may
+ // override, but the point is that no report has to wire this up one-by-one.
+ const effectiveDefaultPresetId =
+ defaultPresetId ?? (variant === "asOf" ? "today" : "last-6-months");
+
+ // No date params → the loader falls back to its default range; reflect that
+ // default preset as active so the trigger isn't mislabeled "All Time".
+ const hasDateParams =
+ variant === "asOf" ? !!endDate : !!(startDate || endDate);
+ const activePreset = hasDateParams
+ ? presets.find((preset) =>
+ variant === "asOf"
+ ? preset.endDate === endDate
+ : preset.startDate === startDate && preset.endDate === endDate
+ )
+ : presets.find((preset) => preset.id === effectiveDefaultPresetId);
const triggerLabel = activePreset
? activePreset.label
diff --git a/apps/erp/app/components/TreeView/TreeView.tsx b/apps/erp/app/components/TreeView/TreeView.tsx
index c9f1b3a62f..af9d92014b 100644
--- a/apps/erp/app/components/TreeView/TreeView.tsx
+++ b/apps/erp/app/components/TreeView/TreeView.tsx
@@ -24,6 +24,14 @@ export type TreeViewProps<TData> = {
parentRef?: MutableRefObject<HTMLElement | null>;
scrollRef?: MutableRefObject<HTMLElement | null>;
onScroll?: (scrollTop: number) => void;
+ /**
+ * Minimum content width in px for horizontally scrollable trees (rows wider
+ * than the viewport). Without it the inner containers clamp to 100% and the
+ * per-row overflow-clip wrapper clips wide rows, so the tree can never
+ * scroll horizontally. Pair with an `overflow-x-auto` parentClassName;
+ * sticky (pinned) cells inside rows stick to this component's scroller.
+ */
+ contentMinWidth?: number;
} & Pick<UseTreeStateOutput, "getTreeProps" | "getNodeProps">;
export type GetTreePropsFn = UseTreeStateOutput["getTreeProps"];
@@ -40,7 +48,8 @@ export function TreeView<TData>({
virtualizer,
parentRef,
scrollRef,
- onScroll
+ onScroll,
+ contentMinWidth
}: TreeViewProps<TData>) {
useEffect(() => {
if (autoFocus) {
@@ -89,6 +98,7 @@ export function TreeView<TData>({
style={{
height: `${virtualizer.getTotalSize()}px`,
width: "100%",
+ minWidth: contentMinWidth,
position: "relative",
overflowY: "visible"
}}
@@ -100,6 +110,7 @@ export function TreeView<TData>({
top: 0,
left: 0,
width: "100%",
+ minWidth: contentMinWidth,
transform: `translateY(${virtualItems.at(0)?.start ?? 0}px)`
}}
>
diff --git a/apps/erp/app/modules/accounting/AGENTS.md b/apps/erp/app/modules/accounting/AGENTS.md
index a39d47814f..6aeff2d95e 100644
--- a/apps/erp/app/modules/accounting/AGENTS.md
+++ b/apps/erp/app/modules/accounting/AGENTS.md
@@ -2,6 +2,12 @@
Chart of accounts, journal entries, general ledger, fiscal periods, currencies, payment terms, cost centers, dimensions, financial reporting (trial balance, balance sheet, income statement), fixed assets with depreciation, intercompany transactions, and external accounting sync (Xero).
+The reports hub lives inside the accounting module at `/x/accounting/reports` (with the module sidebar; single "Reports" sidebar item), while the report pages themselves are full-screen in their own namespace `apps/erp/app/routes/x+/reports+/` (`/x/reports/{balance-sheet,income-statement,executive-pnl,trial-balance,inventory-valuation}` — bare-outlet layout, no module sidebar; `/x/reports` redirects to the hub). Balance sheet and income statement are multi-period: a Columns filter (Monthly default / Quarterly / Yearly) buckets the selected range fiscal-aware via `computeReportPeriodBuckets` (`@carbon/utils`) and the `accountTreeBalancePeriodSeries` RPC returns per-bucket `balanceAtDate`/`netChange` in one snapshot-bounded journal scan. Trial balance stays single-period (Beginning/Debit/Credit/Ending derived from netChange by account class).
+
+**Inventory Valuation** (`inventory-valuation.tsx`, gated on `view: "accounting"`) is an inventory-subledger report that lives here (not in the inventory module): it renders the `InventoryValuationWorkbench` from `~/modules/inventory` (on-hand value by location/item, as-of date, with a GL tie-out and a **Reconcile** action → `inventory-valuation.reconcile` posting via `createInventoryReconciliationJournal`, gated on `create: "accounting"`). Data/UI live in the inventory module; only the route + hub registration are here.
+
+The **Executive P&L** (`executive-pnl.tsx`) shares the income statement's loader (same period series, consolidation, and translation) but renders a condensed summary instead of the account tree: `computeExecutivePnl` (`ui/Reports/executivePnl.ts`) rolls income-statement leaves up by `accountType` into Revenue / Cost of Sales / Operating Expenses / Other Income / Other Expense / Tax, then derives Gross Profit, Operating Income, and Net Income with margin-of-revenue percentages. A class-based catch-all keeps Net Income tied out to the income-statement root; `ExecutivePnlSummary` renders the fixed lines (no search, no drill-down).
+
## Key Domain Concepts
- **Chart of Accounts** — hierarchical account tree. Accounts have `class` (Asset/Liability/Equity/Revenue/Expense), `incomeBalance` (Balance Sheet/Income Statement), and `accountType`. Group accounts contain children; leaf accounts post transactions. Scoped by `companyGroupId`.
@@ -49,7 +55,7 @@ pnpm --filter @carbon/erp test -- --testPathPattern=accounting
| `journal` / `journalLine` | Double-entry transactions; lines carry dimension assignments |
| `journalLineDimension` | Dimension values assigned to journal lines |
| `accountingPeriod` | Fiscal periods. `closeStatus` (`periodCloseStatus`: Open→Locked→Closed lifecycle), `fiscalYear`/`periodNumber` (identity from the fiscal start month), `lockedAt`/`lockedBy`. Legacy `status` (Active/Inactive) is deprecated. |
-| `accountingPeriodBalance` | Cumulative per-account GL balance snapshots. `closeAccountingPeriod` calls `snapshotAccountingPeriodBalances` inside its close transaction (after the flip to Closed) to write them; `reopenAccountingPeriod` deletes them (`endingBalanceDate` ≥ period `endDate`) before flipping back to Open. Read by `accountTreeBalancesByCompany` (snapshot + delta; full-scan fallback when empty). Balance RPCs exclude Draft journals. |
+| `accountingPeriodBalance` | Cumulative per-account GL balance snapshots. `closeAccountingPeriod` calls `snapshotAccountingPeriodBalances` inside its close transaction (after the flip to Closed) to write them; `reopenAccountingPeriod` deletes them (`endingBalanceDate` ≥ period `endDate`) before flipping back to Open. Read by `accountTreeBalancesByCompany` (snapshot + delta; full-scan fallback when empty) and `accountTreeBalancePeriodSeries` (multi-period: base snapshot before the range start + one bounded scan bucketed by period ends; single uniform branch). Balance RPCs exclude Draft journals. |
| `periodCloseTaskDefinition` / `periodCloseTask` | NetSuite-style close checklist: company-level task templates + per-period instances (seeded via `seed-company`) |
| `accountDefault` | Default GL account mappings (AR, AP, inventory, etc.) |
| `currency` / `currencyCode` / `exchangeRateHistory` | Multi-currency with historical rates |
@@ -61,13 +67,18 @@ pnpm --filter @carbon/erp test -- --testPathPattern=accounting
| `fixedAssetDisposal` / `fixedAssetUsageLog` | Asset disposal and usage tracking |
| `intercompanyTransaction` | Cross-company transaction matching |
| `fiscalYearSettings` | Fiscal and tax year configuration |
+| `reportPin` | Per-user pin overrides for the reports hub — explicit `pinned` boolean per `(reportKey, userId, companyId)`; absent row = the report's default (core statements default pinned) |
## Key Service Functions
- `getChartOfAccounts` / `getAccounts` / `upsertAccount` — account management
- `getTrialBalance` — trial balance via `trialBalance` RPC
-- `getFinancialStatementBalances` — balance sheet / income statement with Net Income computation
-- `getConsolidatedBalances` — multi-company consolidation with currency translation
+- `getFinancialStatementBalances` — single-period statement balances with Net Income computation (trial balance report)
+- `getFinancialStatementPeriodSeries` — multi-period balance sheet / income statement columns via the `accountTreeBalancePeriodSeries` RPC; per-bucket Net Income injection and optional per-bucket translation (`translate` arg)
+- `getConsolidatedBalances` / `getConsolidatedPeriodSeries` — multi-company consolidation with currency translation (single-period / per-bucket)
+- `translateCompanyPeriodSeries` — per-bucket currency translation (wraps `translateCompanyBalances` once per bucket)
+- `getAccountPeriodSeries` — thin wrapper for the `accountTreeBalancePeriodSeries` RPC (period ends must come from `computeReportPeriodBuckets`)
+- `getReportPins` / `upsertReportPin` — per-user pin overrides for the reports hub
- `createJournalEntry` / `saveJournalEntryWithLines` / `postJournalEntry` / `reverseJournalEntry` — journal lifecycle
- `getOrCreateAccountingPeriod` / `getCurrentAccountingPeriod` — period management (lazy create on posting)
- `createFiscalYearPeriods` — generate the 12 monthly periods for a fiscal year (idempotent; from `fiscalYearSettings.startMonth`)
diff --git a/apps/erp/app/modules/accounting/accounting.models.ts b/apps/erp/app/modules/accounting/accounting.models.ts
index 1e6eeac0b2..ec072ff298 100644
--- a/apps/erp/app/modules/accounting/accounting.models.ts
+++ b/apps/erp/app/modules/accounting/accounting.models.ts
@@ -68,6 +68,212 @@ export const accountClassTypes = [
"Expense"
] as const;
+export const financialReportColumns = ["month", "quarter", "year"] as const;
+
+// Pin/unpin toggle on the reports hub (/x/accounting/reports)
+export const reportPinValidator = z.object({
+ reportKey: z.string().min(1),
+ pinned: z.enum(["true", "false"])
+});
+
+// URL search params for the /x/reports financial statements. Parsed with
+// safeParse in the loaders — invalid params fall back to defaults rather than
+// failing the report.
+export const financialReportParamsValidator = z.object({
+ companies: z.string().optional(),
+ startDate: z
+ .string()
+ .regex(/^\d{4}-\d{2}-\d{2}$/)
+ .optional(),
+ endDate: z
+ .string()
+ .regex(/^\d{4}-\d{2}-\d{2}$/)
+ .optional(),
+ columns: z.enum(financialReportColumns).catch("month").default("month"),
+ showTranslated: z
+ .string()
+ .optional()
+ .transform((v) => v === "true")
+});
+
+// -- Dimensional analytics (pivot) reports --
+// Spec: .ai/specs/2026-08-09-dimensional-pivot-reporting.md
+
+export const analyticsReportKeys = [
+ "revenue",
+ "expenses",
+ "assets",
+ "inventory-change",
+ "scrap"
+] as const;
+export type AnalyticsReportKey = (typeof analyticsReportKeys)[number];
+
+// Account scope: exactly one selector. "scrapAccounts" resolves at runtime to
+// accountDefault.scrapAccount (getScrapAccountIds in accounting.service.ts).
+export type AnalyticsAccountScope =
+ | { classes: (typeof accountClassTypes)[number][] }
+ | { types: (typeof accountTypes)[number][] }
+ | { source: "scrapAccounts" };
+
+export type AnalyticsReportDefinition = {
+ key: AnalyticsReportKey;
+ accountScope: AnalyticsAccountScope;
+ // Row selections applied when the URL has no pivot params. Entries use the
+ // "et:<entityType>" alias the analytics loader resolves to a dimension id.
+ defaultRows: string[];
+};
+
+export const analyticsReports: Record<
+ AnalyticsReportKey,
+ AnalyticsReportDefinition
+> = {
+ revenue: {
+ key: "revenue",
+ accountScope: { classes: ["Revenue"] },
+ defaultRows: ["et:Customer"]
+ },
+ expenses: {
+ key: "expenses",
+ accountScope: { classes: ["Expense"] },
+ defaultRows: ["et:Location"]
+ },
+ assets: {
+ key: "assets",
+ accountScope: { classes: ["Asset"] },
+ defaultRows: ["et:Location"]
+ },
+ "inventory-change": {
+ key: "inventory-change",
+ accountScope: { types: ["Inventory"] },
+ defaultRows: ["et:Location"]
+ },
+ scrap: {
+ key: "scrap",
+ accountScope: { source: "scrapAccounts" },
+ defaultRows: ["et:ScrapReason"]
+ }
+};
+
+export const pivotMeasures = ["amount", "quantity", "count"] as const;
+export type PivotMeasure = (typeof pivotMeasures)[number];
+
+// Purchases report — grouping fields (columns on the purchase invoice line /
+// its header), NOT journal dimensions. The purchases pivot RPC resolves each
+// to a value id; the report reuses the shared PivotState (rows/columnAxis hold
+// these field keys).
+export const purchaseGroupingFields = [
+ "supplier",
+ "supplierType",
+ "item",
+ "itemPostingGroup",
+ "costCenter"
+] as const;
+export type PurchaseGroupingField = (typeof purchaseGroupingFields)[number];
+
+export const pivotColumnAxisValidator = z.discriminatedUnion("type", [
+ z.object({
+ type: z.literal("period"),
+ bucket: z.enum(financialReportColumns)
+ }),
+ z.object({ type: z.literal("dimension"), dimensionId: z.string().min(1) })
+]);
+export type PivotColumnAxis = z.infer<typeof pivotColumnAxisValidator>;
+
+// Pivot state, encoded in the URL as:
+// rows = comma-separated dimension ids (or "et:<entityType>" aliases), max 2
+// col = "period:month|quarter|year" or "dim:<dimensionId>"
+// measure = amount|quantity|count; pct=1 for percent-of-column-total
+// filters = URL-encoded JSON [{dimensionId, valueIds}]
+// accounts = comma-separated account ids narrowing the report's account scope
+// sort = "<columnKey|__total__|__label__>:asc|desc" (row sort; omit for the
+// default ABS(measure) descending)
+// startDate/endDate — same params ReportFilters writes
+export const pivotStateValidator = z.object({
+ rows: z.array(z.string().min(1)).max(2).default([]),
+ columnAxis: pivotColumnAxisValidator.default({
+ type: "period",
+ bucket: "month"
+ }),
+ measure: z.enum(pivotMeasures).default("amount"),
+ percentOfTotal: z.boolean().default(false),
+ // Row sort. null (the default) means ABS(measure) descending, Unassigned last.
+ sort: z
+ .object({
+ key: z.string().min(1),
+ direction: z.enum(["asc", "desc"])
+ })
+ .nullable()
+ .default(null),
+ filters: z
+ .array(
+ z.object({
+ dimensionId: z.string().min(1),
+ valueIds: z.array(z.string()).min(1)
+ })
+ )
+ .default([]),
+ // Optional narrowing to specific accounts WITHIN the report's account scope
+ // (base classes/types define the universe; these intersect it).
+ accountIds: z.array(z.string().min(1)).default([])
+});
+export type PivotState = z.infer<typeof pivotStateValidator>;
+
+/**
+ * Overlay the client-only display params (`measure` / `pct` / `sort`) from the
+ * URL onto a loader-derived PivotState. The analytics report loaders skip
+ * revalidation when only these change (see `revalidateIgnoringPivotDisplay`), so
+ * the route component re-derives them here to stay in sync without a refetch.
+ * A server-affecting change always re-runs the loader, so the passed `state` is
+ * the correct base (saved view / default) for any display param absent from the
+ * URL — including after the user clears a sort.
+ */
+export function applyPivotDisplayParams(
+ state: PivotState,
+ searchParams: URLSearchParams
+): PivotState {
+ const measureParam = searchParams.get("measure");
+ const measure = (pivotMeasures as readonly string[]).includes(
+ measureParam ?? ""
+ )
+ ? (measureParam as PivotMeasure)
+ : state.measure;
+
+ const pctParam = searchParams.get("pct");
+ const percentOfTotal =
+ pctParam !== null ? pctParam === "1" : state.percentOfTotal;
+
+ const sortParam = searchParams.get("sort");
+ let sort = state.sort;
+ if (sortParam !== null) {
+ const separator = sortParam.lastIndexOf(":");
+ const key = separator > 0 ? sortParam.slice(0, separator) : "";
+ const direction = separator > 0 ? sortParam.slice(separator + 1) : "";
+ sort =
+ key && (direction === "asc" || direction === "desc")
+ ? { key, direction }
+ : state.sort;
+ }
+
+ return { ...state, measure, percentOfTotal, sort };
+}
+
+export const reportViewVisibilities = ["Private", "Company"] as const;
+
+// Save-view modal on the analytics reports; config is a JSON-encoded
+// PivotState re-parsed with pivotStateValidator in the route action.
+export const reportViewValidator = z.object({
+ id: zfd.text(z.string().optional()),
+ reportKey: z.enum(analyticsReportKeys),
+ name: z
+ .string()
+ .min(1, { message: "Name is required" })
+ .max(100, { message: "Name must be 100 characters or fewer" }),
+ visibility: z.enum(reportViewVisibilities, {
+ errorMap: () => ({ message: "Visibility is required" })
+ }),
+ config: z.string().min(2, { message: "Config is required" })
+});
+
export const groupAccountValidator = z
.object({
id: zfd.text(z.string().optional()),
diff --git a/apps/erp/app/modules/accounting/accounting.service.ts b/apps/erp/app/modules/accounting/accounting.service.ts
index bd220522f8..73a2282faa 100644
--- a/apps/erp/app/modules/accounting/accounting.service.ts
+++ b/apps/erp/app/modules/accounting/accounting.service.ts
@@ -1,7 +1,7 @@
import type { Database, Json } from "@carbon/database";
import { getCompanyTimeZone } from "@carbon/database";
import type { Kysely, KyselyDatabase } from "@carbon/database/client";
-import type { PeriodPostingSource } from "@carbon/utils";
+import type { PeriodPostingSource, ReportPeriodBucket } from "@carbon/utils";
import {
datetime,
fiscalYearAndPeriodFor,
@@ -20,6 +20,8 @@ import type { GenericQueryFilters } from "~/utils/query";
import { setGenericQueryFilters } from "~/utils/query";
import { sanitize } from "~/utils/supabase";
import type {
+ AnalyticsAccountScope,
+ AnalyticsReportDefinition,
accountValidator,
costCenterValidator,
currencyValidator,
@@ -33,6 +35,7 @@ import type {
journalEntryValidator,
macrsConventions,
macrsPropertyClasses,
+ PivotState,
paymentTermValidator,
periodCloseStatuses,
periodCloseTaskDefinitionValidator,
@@ -43,6 +46,8 @@ import type {
} from "./accounting.models";
import type {
AccountLedgerLine,
+ ChartPeriodSeries,
+ PeriodCell,
Transaction,
TranslatedBalance
} from "./types";
@@ -342,6 +347,1142 @@ export async function getFinancialStatementBalances(
};
}
+export async function getAccountPeriodSeries(
+ client: SupabaseClient<Database>,
+ companyGroupId: string,
+ companyId: string,
+ args: { start: string; periodEnds: string[] }
+) {
+ // Defined in migration 20260809151458_balance-rpc-period-series.sql.
+ // The contract on p_period_ends (sorted ascending, distinct, >= p_start) is
+ // enforced by computeReportPeriodBuckets — the only producer of this arg.
+ return client.rpc("accountTreeBalancePeriodSeries", {
+ p_company_group_id: companyGroupId,
+ p_company_id: companyId,
+ p_start: args.start,
+ p_period_ends: args.periodEnds
+ });
+}
+
+/**
+ * Recalculates every period cell for system (root) accounts using the same
+ * sign-aware aggregation as applyRootSignCorrection.
+ *
+ * KEEP IN SYNC with applyRootSignCorrection above — identical root/child walk,
+ * applied per period bucket instead of to the single-measure columns.
+ */
+function applyRootSignCorrectionToSeries<
+ T extends {
+ id: string;
+ parentId: string | null;
+ isSystem?: boolean | null;
+ class: string | null;
+ periods: Record<string, PeriodCell>;
+ }
+>(accounts: T[], bucketKeys: string[]): T[] {
+ const roots = accounts.filter((a) => a.isSystem ?? a.parentId === null);
+ if (roots.length === 0) return accounts;
+
+ const rootIds = new Set(roots.map((r) => r.id));
+ const childrenByRoot = new Map<string, T[]>();
+
+ for (const account of accounts) {
+ if (account.parentId && rootIds.has(account.parentId)) {
+ const list = childrenByRoot.get(account.parentId) ?? [];
+ list.push(account);
+ childrenByRoot.set(account.parentId, list);
+ }
+ }
+
+ return accounts.map((account) => {
+ if (!rootIds.has(account.id)) return account;
+
+ const children = childrenByRoot.get(account.id) ?? [];
+ const periods: Record<string, PeriodCell> = {};
+
+ for (const key of bucketKeys) {
+ let netChange = 0;
+ let balanceAtDate = 0;
+ let translatedBalance = 0;
+ let translatedNetChange = 0;
+ let hasTranslated = false;
+
+ for (const child of children) {
+ const sign = rootSignMultiplier(child.class);
+ const cell = child.periods[key];
+ netChange += sign * (cell?.netChange ?? 0);
+ balanceAtDate += sign * (cell?.balanceAtDate ?? 0);
+ if (typeof cell?.translatedBalance === "number") {
+ hasTranslated = true;
+ translatedBalance += sign * cell.translatedBalance;
+ }
+ if (typeof cell?.translatedNetChange === "number") {
+ hasTranslated = true;
+ translatedNetChange += sign * cell.translatedNetChange;
+ }
+ }
+
+ periods[key] = {
+ netChange,
+ balanceAtDate,
+ ...(hasTranslated ? { translatedBalance, translatedNetChange } : {})
+ };
+ }
+
+ return { ...account, periods };
+ });
+}
+
+// Overlay per-bucket translated leaf balances onto the series rows.
+function overlayTranslationOnSeries<
+ T extends { id: string; periods: Record<string, PeriodCell> }
+>(
+ rows: T[],
+ byBucket: Record<string, { balances: TranslatedBalance[]; cta: number }>
+): T[] {
+ const maps = new Map<string, Map<string, TranslatedBalance>>();
+ for (const [key, bucket] of Object.entries(byBucket)) {
+ maps.set(key, new Map(bucket.balances.map((b) => [b.accountId, b])));
+ }
+
+ return rows.map((row) => {
+ let changed = false;
+ const periods = { ...row.periods };
+ for (const [key, map] of maps) {
+ const translation = map.get(row.id);
+ if (!translation) continue;
+ changed = true;
+ const existing = periods[key] ?? { netChange: 0, balanceAtDate: 0 };
+ const exchangeRate = Number(translation.exchangeRate);
+ periods[key] = {
+ ...existing,
+ translatedBalance: Number(translation.translatedBalance),
+ // Translated period delta: apply the same per-account rate to netChange
+ // so flow reads (income statement / executive P&L) get a translated
+ // activity figure rather than the translated cumulative balance.
+ translatedNetChange:
+ Math.round(existing.netChange * exchangeRate * 10000) / 10000,
+ exchangeRate
+ };
+ }
+ return changed ? { ...row, periods } : row;
+ });
+}
+
+/**
+ * Per-bucket currency translation for a period series. Calls the existing
+ * translateCompanyBalances once per bucket (bucket end = closing rate date,
+ * bucket start = average-rate window start) on synthetic single-measure rows
+ * built from that bucket's balanceAtDate.
+ */
+export async function translateCompanyPeriodSeries(
+ client: SupabaseClient<Database>,
+ companyGroupId: string,
+ companyId: string,
+ targetCurrency: string,
+ buckets: ReportPeriodBucket[],
+ series: Array<{
+ id: string;
+ consolidatedRate: string | null;
+ isGroup: boolean | null;
+ class: string | null;
+ periods: Record<string, PeriodCell>;
+ }>
+): Promise<{
+ byBucket: Record<string, { balances: TranslatedBalance[]; cta: number }>;
+ error: string | null;
+}> {
+ const results = await Promise.all(
+ buckets.map(async (bucket) => {
+ const synthetic = series.map((row) => ({
+ id: row.id,
+ balanceAtDate: row.periods[bucket.key]?.balanceAtDate ?? 0,
+ consolidatedRate: row.consolidatedRate,
+ isGroup: row.isGroup,
+ class: row.class
+ }));
+ const translation = await translateCompanyBalances(
+ client,
+ companyGroupId,
+ companyId,
+ targetCurrency,
+ bucket.end,
+ bucket.start,
+ synthetic
+ );
+ return { key: bucket.key, translation };
+ })
+ );
+
+ const byBucket: Record<
+ string,
+ { balances: TranslatedBalance[]; cta: number }
+ > = {};
+ for (const { key, translation } of results) {
+ if (translation.error) {
+ return { byBucket: {}, error: translation.error };
+ }
+ byBucket[key] = { balances: translation.data ?? [], cta: translation.cta };
+ }
+
+ return { byBucket, error: null };
+}
+
+/**
+ * Multi-period financial statement balances: one column per bucket, powered by
+ * the accountTreeBalancePeriodSeries RPC (snapshot-based, single journal scan).
+ * The multi-period sibling of getFinancialStatementBalances — same accounts
+ * view, same Net Income injection (per bucket), same root sign correction.
+ */
+export async function getFinancialStatementPeriodSeries(
+ client: SupabaseClient<Database>,
+ companyGroupId: string,
+ companyId: string,
+ args: {
+ buckets: ReportPeriodBucket[];
+ // Balance sheet only: append a computed "Net Income" equity line per bucket.
+ includeCurrentYearEarnings?: boolean;
+ // When set, per-bucket translated balances are overlaid before the root
+ // sign correction so root rows carry translated values too.
+ translate?: { targetCurrency: string };
+ }
+): Promise<{
+ data: ChartPeriodSeries[] | null;
+ ctaByBucket: Record<string, number>;
+ error: { message: string } | null;
+}> {
+ if (args.buckets.length === 0) {
+ return { data: [], ctaByBucket: {}, error: null };
+ }
+
+ const bucketKeys = args.buckets.map((b) => b.key);
+ const keyByEnd = new Map(args.buckets.map((b) => [b.end, b.key]));
+
+ const accountsQuery = client
+ .from("accounts")
+ .select("*")
+ .eq("companyGroupId", companyGroupId)
+ .eq("active", true)
+ .order("number", { ascending: true });
+
+ // The buckets helper may truncate a very wide range, so the series start is
+ // the FIRST bucket's start — not whatever the caller had before bucketing.
+ const seriesQuery = getAccountPeriodSeries(
+ client,
+ companyGroupId,
+ companyId,
+ {
+ start: args.buckets[0]!.start,
+ periodEnds: args.buckets.map((b) => b.end)
+ }
+ );
+
+ const [accountsResponse, seriesResponse] = await Promise.all([
+ accountsQuery,
+ seriesQuery
+ ]);
+
+ if (accountsResponse.error) {
+ return {
+ data: null,
+ ctaByBucket: {},
+ error: accountsResponse.error
+ };
+ }
+ if (seriesResponse.error) {
+ return { data: null, ctaByBucket: {}, error: seriesResponse.error };
+ }
+
+ const periodsByAccountId = new Map<string, Record<string, PeriodCell>>();
+ for (const row of seriesResponse.data ?? []) {
+ const key = keyByEnd.get(row.periodEnd);
+ if (!key) continue;
+ let record = periodsByAccountId.get(row.accountId);
+ if (!record) {
+ record = {};
+ periodsByAccountId.set(row.accountId, record);
+ }
+ record[key] = {
+ netChange: Number(row.netChange ?? 0),
+ balanceAtDate: Number(row.balanceAtDate ?? 0)
+ };
+ }
+
+ const emptyPeriods = (): Record<string, PeriodCell> =>
+ Object.fromEntries(
+ bucketKeys.map((key) => [key, { netChange: 0, balanceAtDate: 0 }])
+ );
+
+ let mapped = (accountsResponse.data ?? [])
+ .filter((a): a is typeof a & { id: string } => a.id !== null)
+ .map((account) => ({
+ ...account,
+ periods: {
+ ...emptyPeriods(),
+ ...(periodsByAccountId.get(account.id) ?? {})
+ }
+ }));
+
+ // Same Net Income equity line as getFinancialStatementBalances, computed per
+ // bucket: cumulative (balanceAtDate) and per-bucket (netChange) sums over
+ // income-statement LEAF accounts, rolled into the Equity group subtotal.
+ if (args.includeCurrentYearEarnings) {
+ const balanceSheetRoot = mapped.find(
+ (a) =>
+ a.incomeBalance === "Balance Sheet" &&
+ (a.isSystem ?? a.parentId === null)
+ );
+ const equityGroup = mapped.find(
+ (a) =>
+ a.class === "Equity" && a.isGroup && a.parentId === balanceSheetRoot?.id
+ );
+ if (balanceSheetRoot && equityGroup) {
+ const netIncomePeriods: Record<string, PeriodCell> = {};
+ for (const key of bucketKeys) {
+ let balanceAtDate = 0;
+ let netChange = 0;
+ for (const a of mapped) {
+ if (a.incomeBalance !== "Income Statement" || a.isGroup) continue;
+ const sign = rootSignMultiplier(a.class);
+ const cell = a.periods[key];
+ balanceAtDate += sign * (cell?.balanceAtDate ?? 0);
+ netChange += sign * (cell?.netChange ?? 0);
+ }
+ const equityCell = equityGroup.periods[key] ?? {
+ netChange: 0,
+ balanceAtDate: 0
+ };
+ equityGroup.periods[key] = {
+ ...equityCell,
+ netChange: equityCell.netChange + netChange,
+ balanceAtDate: equityCell.balanceAtDate + balanceAtDate
+ };
+ netIncomePeriods[key] = { netChange, balanceAtDate };
+ }
+ // Clone the Equity group to inherit every account column the report
+ // needs. Must NOT be isSystem — a system row is treated as a root by
+ // applyRootSignCorrectionToSeries and recomputed to zero.
+ mapped.push({
+ ...equityGroup,
+ id: NET_INCOME_ACCOUNT_ID,
+ name: "Net Income",
+ isGroup: false,
+ isSystem: false,
+ parentId: equityGroup.id,
+ periods: netIncomePeriods
+ });
+ }
+ }
+
+ let ctaByBucket: Record<string, number> = {};
+
+ if (args.translate) {
+ const translation = await translateCompanyPeriodSeries(
+ client,
+ companyGroupId,
+ companyId,
+ args.translate.targetCurrency,
+ args.buckets,
+ mapped
+ );
+ if (translation.error) {
+ return {
+ data: null,
+ ctaByBucket: {},
+ error: { message: translation.error }
+ };
+ }
+ mapped = overlayTranslationOnSeries(mapped, translation.byBucket);
+ for (const [key, bucket] of Object.entries(translation.byBucket)) {
+ ctaByBucket[key] = bucket.cta;
+ }
+ }
+
+ return {
+ data: applyRootSignCorrectionToSeries(
+ mapped,
+ bucketKeys
+ ) as unknown as ChartPeriodSeries[],
+ ctaByBucket,
+ error: null
+ };
+}
+
+/**
+ * Multi-company, multi-period consolidation — the period-series sibling of
+ * getConsolidatedBalances: per-company series (including auto-resolved
+ * elimination entities) summed per account and bucket, with per-bucket
+ * currency translation and CTA.
+ */
+export async function getConsolidatedPeriodSeries(
+ client: SupabaseClient<Database>,
+ companyGroupId: string,
+ companyIds: string[],
+ targetCurrency: string,
+ args: { buckets: ReportPeriodBucket[] }
+): Promise<{
+ data: ChartPeriodSeries[];
+ ctaByBucket: Record<string, number>;
+}> {
+ const bucketKeys = args.buckets.map((b) => b.key);
+ const allIds = await resolveConsolidationCompanyIds(
+ client,
+ companyGroupId,
+ companyIds
+ );
+
+ const results = await Promise.all(
+ allIds.map(async (id) => {
+ const series = await getFinancialStatementPeriodSeries(
+ client,
+ companyGroupId,
+ id,
+ { buckets: args.buckets }
+ );
+
+ const translation =
+ series.error || !series.data
+ ? {
+ byBucket: {} as Record<
+ string,
+ { balances: TranslatedBalance[]; cta: number }
+ >,
+ error: series.error?.message ?? "Failed to load balances"
+ }
+ : await translateCompanyPeriodSeries(
+ client,
+ companyGroupId,
+ id,
+ targetCurrency,
+ args.buckets,
+ series.data
+ );
+
+ return { series, translation };
+ })
+ );
+
+ // Sum raw cells per (account, bucket) across companies
+ const summedByAccount = new Map<string, Record<string, PeriodCell>>();
+ for (const { series } of results) {
+ if (series.error || !series.data) continue;
+ for (const row of series.data) {
+ let record = summedByAccount.get(row.id);
+ if (!record) {
+ record = {};
+ summedByAccount.set(row.id, record);
+ }
+ for (const key of bucketKeys) {
+ const cell = row.periods[key];
+ if (!cell) continue;
+ const agg = record[key] ?? { netChange: 0, balanceAtDate: 0 };
+ record[key] = {
+ netChange: agg.netChange + cell.netChange,
+ balanceAtDate: agg.balanceAtDate + cell.balanceAtDate
+ };
+ }
+ }
+ }
+
+ // Sum translated leaf balances per (account, bucket) and CTA per bucket
+ const translatedByAccount = new Map<
+ string,
+ Record<string, { translatedBalance: number; exchangeRate: number }>
+ >();
+ const ctaByBucket: Record<string, number> = Object.fromEntries(
+ bucketKeys.map((key) => [key, 0])
+ );
+
+ for (const { translation } of results) {
+ if (translation.error) continue;
+ for (const [key, bucket] of Object.entries(translation.byBucket)) {
+ ctaByBucket[key] = (ctaByBucket[key] ?? 0) + bucket.cta;
+ for (const row of bucket.balances) {
+ let record = translatedByAccount.get(row.accountId);
+ if (!record) {
+ record = {};
+ translatedByAccount.set(row.accountId, record);
+ }
+ const existing = record[key];
+ record[key] = existing
+ ? {
+ translatedBalance:
+ existing.translatedBalance + Number(row.translatedBalance),
+ exchangeRate: existing.exchangeRate
+ }
+ : {
+ translatedBalance: Number(row.translatedBalance),
+ exchangeRate: Number(row.exchangeRate)
+ };
+ }
+ }
+ }
+
+ // Use the first company's account structure as the base (shared chart)
+ const baseAccounts = results.find((r) => r.series.data)?.series.data ?? [];
+
+ const consolidated = baseAccounts.map((account) => {
+ const summed = summedByAccount.get(account.id);
+ const translated = translatedByAccount.get(account.id);
+ const periods: Record<string, PeriodCell> = {};
+ for (const key of bucketKeys) {
+ periods[key] = {
+ netChange: 0,
+ balanceAtDate: 0,
+ ...(summed?.[key] ?? {}),
+ ...(translated?.[key] ?? {})
+ };
+ }
+ return { ...account, periods };
+ });
+
+ return {
+ data: applyRootSignCorrectionToSeries(consolidated, bucketKeys),
+ ctaByBucket
+ };
+}
+
+// Per-user pin overrides for the reports hub. Absent row = the report's
+// default pin state (the core financial statements default to pinned).
+export async function getReportPins(
+ client: SupabaseClient<Database>,
+ userId: string,
+ companyId: string
+) {
+ return client
+ .from("reportPin")
+ .select("reportKey, pinned")
+ .eq("userId", userId)
+ .eq("companyId", companyId);
+}
+
+export async function upsertReportPin(
+ client: SupabaseClient<Database>,
+ args: {
+ reportKey: string;
+ pinned: boolean;
+ userId: string;
+ companyId: string;
+ }
+) {
+ return client.from("reportPin").upsert(
+ {
+ reportKey: args.reportKey,
+ pinned: args.pinned,
+ userId: args.userId,
+ companyId: args.companyId,
+ createdBy: args.userId,
+ updatedBy: args.userId,
+ updatedAt: datetime.timestamp()
+ },
+ { onConflict: "reportKey,userId,companyId" }
+ );
+}
+
+// -- Dimensional analytics (pivot) reports --
+// Spec: .ai/specs/2026-08-09-dimensional-pivot-reporting.md
+// RPCs defined in migration 20260809184714_dimensional-pivot-reporting.sql.
+
+// In `columnKeys` the null column (lines with no tag for the column
+// dimension — the Unassigned bucket) is represented by this string sentinel.
+// Group rows keep their `columnKey` as returned by the RPC (null stays null).
+export const UNASSIGNED_COLUMN_KEY = "__unassigned__";
+
+type DimensionPivotGroup = {
+ rowValue1Id: string | null;
+ rowValue2Id: string | null;
+ columnKey: string | null;
+ amount: number;
+ quantity: number;
+ lineCount: number;
+};
+
+type DimensionPivotData = {
+ groups: DimensionPivotGroup[];
+ columnKeys: string[];
+ hasMore: boolean;
+ valueNames: Record<string, string>;
+};
+
+/**
+ * Maps an AnalyticsAccountScope onto the pivot RPCs' account-scope params.
+ * Exactly one selector is set (the RPCs raise without one); the scrap scope
+ * resolves to the accountDefault.scrapAccount ids the loader fetched via
+ * getScrapAccountIds.
+ */
+function pivotAccountScopeParams(
+ scope: AnalyticsAccountScope,
+ scrapAccountIds: string[] | undefined
+):
+ | { p_account_classes: string[] }
+ | { p_account_types: string[] }
+ | { p_account_ids: string[] } {
+ if ("classes" in scope) return { p_account_classes: [...scope.classes] };
+ if ("types" in scope) return { p_account_types: [...scope.types] };
+ return { p_account_ids: scrapAccountIds ?? [] };
+}
+
+/**
+ * The leaf accounts inside a report's account scope — the universe the
+ * per-report account multi-select filters within. Mirrors the scope selectors
+ * pivotAccountScopeParams uses: class-scoped and type-scoped reports resolve to
+ * the matching active, non-group accounts; the scrap scope resolves to the
+ * scrapAccount ids the loader already fetched. Returns the raw supabase
+ * response so callers keep the `{ data, error }` convention.
+ */
+export async function getAccountsInScope(
+ client: SupabaseClient<Database>,
+ companyGroupId: string,
+ scope: AnalyticsAccountScope,
+ scrapAccountIds?: string[]
+) {
+ let query = client
+ .from("account")
+ .select("id, number, name")
+ .eq("companyGroupId", companyGroupId)
+ .eq("active", true)
+ .eq("isGroup", false);
+
+ if ("classes" in scope) {
+ query = query.in("class", scope.classes);
+ } else if ("types" in scope) {
+ query = query.in("accountType", scope.types);
+ } else {
+ query = query.in("id", scrapAccountIds ?? []);
+ }
+
+ return query.order("number", { ascending: true });
+}
+
+export async function getDimensionPivot(
+ client: SupabaseClient<Database>,
+ args: {
+ companyId: string;
+ companyGroupId: string;
+ report: AnalyticsReportDefinition;
+ // Required when report.accountScope.source === "scrapAccounts"
+ scrapAccountIds?: string[];
+ startDate: string; // YYYY-MM-DD
+ endDate: string;
+ // From computeReportPeriodBuckets, when state.columnAxis is period
+ periodEnds?: string[];
+ // rows are already-resolved dimension ids (the loader resolves et: aliases)
+ state: PivotState;
+ }
+): Promise<{
+ data: DimensionPivotData | null;
+ error: PostgrestError | null;
+}> {
+ const { report, state } = args;
+
+ // Scrap report with no configured scrap account: nothing can match, and the
+ // RPC raises without an account scope — short-circuit to an empty pivot.
+ if (
+ "source" in report.accountScope &&
+ (args.scrapAccountIds ?? []).length === 0
+ ) {
+ return {
+ data: { groups: [], columnKeys: [], hasMore: false, valueNames: {} },
+ error: null
+ };
+ }
+
+ const columnDimensionId =
+ state.columnAxis.type === "dimension"
+ ? state.columnAxis.dimensionId
+ : undefined;
+
+ const result = await client.rpc("journalDimensionPivot", {
+ p_company_group_id: args.companyGroupId,
+ p_company_id: args.companyId,
+ p_start: args.startDate,
+ p_end: args.endDate,
+ ...pivotAccountScopeParams(report.accountScope, args.scrapAccountIds),
+ ...(state.rows[0] ? { p_row_dimension_1: state.rows[0] } : {}),
+ ...(state.rows[1] ? { p_row_dimension_2: state.rows[1] } : {}),
+ ...(columnDimensionId ? { p_column_dimension: columnDimensionId } : {}),
+ ...(state.columnAxis.type === "period" && args.periodEnds
+ ? { p_period_ends: args.periodEnds }
+ : {}),
+ ...(state.filters.length > 0 ? { p_filters: state.filters } : {}),
+ ...(state.accountIds.length > 0
+ ? { p_filter_account_ids: state.accountIds }
+ : {})
+ });
+
+ if (result.error) return { data: null, error: result.error };
+
+ // The generated Returns can't express nullability: NULL rowValue/columnKey
+ // is the Unassigned bucket (line carries no tag for that dimension).
+ const rows = (result.data ?? []) as Array<{
+ rowValue1Id: string | null;
+ rowValue2Id: string | null;
+ columnKey: string | null;
+ amount: number | string;
+ quantity: number | string;
+ lineCount: number | string;
+ hasMore: boolean;
+ }>;
+
+ const hasMore = rows.some((r) => r.hasMore);
+
+ // Sorted descending by ABS(amount) in TS — never trust RPC ordering.
+ const groups: DimensionPivotGroup[] = rows
+ .map((r) => ({
+ rowValue1Id: r.rowValue1Id,
+ rowValue2Id: r.rowValue2Id,
+ columnKey: r.columnKey,
+ amount: Number(r.amount),
+ quantity: Number(r.quantity),
+ lineCount: Number(r.lineCount)
+ }))
+ .sort((a, b) => Math.abs(b.amount) - Math.abs(a.amount));
+
+ // Ordered distinct column keys: period axis follows the periodEnds order;
+ // dimension axis orders by descending ABS(column total). The Unassigned
+ // (null) column always sorts last, as the UNASSIGNED_COLUMN_KEY sentinel.
+ const hasUnassignedColumn = groups.some((g) => g.columnKey === null);
+ let columnKeys: string[];
+ if (state.columnAxis.type === "period") {
+ // Every bucket in the selected range renders as a column, including
+ // buckets with no journal lines — a 6-month range always shows 6 columns.
+ columnKeys = [...(args.periodEnds ?? [])];
+ // Defensive: keep any keys the periodEnds contract didn't cover (e.g. the
+ // literal 'total' when no period ends were provided).
+ for (const g of groups) {
+ if (g.columnKey !== null && !columnKeys.includes(g.columnKey)) {
+ columnKeys.push(g.columnKey);
+ }
+ }
+ } else {
+ const totalsByColumn = new Map<string, number>();
+ for (const g of groups) {
+ if (g.columnKey === null) continue;
+ totalsByColumn.set(
+ g.columnKey,
+ (totalsByColumn.get(g.columnKey) ?? 0) + g.amount
+ );
+ }
+ columnKeys = [...totalsByColumn.keys()].sort(
+ (a, b) =>
+ Math.abs(totalsByColumn.get(b) ?? 0) -
+ Math.abs(totalsByColumn.get(a) ?? 0)
+ );
+ }
+ if (hasUnassignedColumn) columnKeys.push(UNASSIGNED_COLUMN_KEY);
+
+ // Resolve display names for the value ids actually present, batched by the
+ // owning dimension's entityType.
+ const valueIdsByDimension = new Map<string, Set<string>>();
+ const collect = (dimensionId: string | undefined, valueId: string | null) => {
+ if (!dimensionId || !valueId) return;
+ const set = valueIdsByDimension.get(dimensionId) ?? new Set<string>();
+ set.add(valueId);
+ valueIdsByDimension.set(dimensionId, set);
+ };
+ for (const g of groups) {
+ collect(state.rows[0], g.rowValue1Id);
+ collect(state.rows[1], g.rowValue2Id);
+ collect(columnDimensionId, g.columnKey);
+ }
+
+ let valueNames: Record<string, string> = {};
+ if (valueIdsByDimension.size > 0) {
+ const dimensions = await client
+ .from("dimension")
+ .select("id, entityType")
+ .in("id", [...valueIdsByDimension.keys()]);
+
+ if (dimensions.error) return { data: null, error: dimensions.error };
+
+ valueNames = await resolveDimensionValueNames(
+ client,
+ (dimensions.data ?? []).map((d) => ({
+ entityType: d.entityType,
+ valueIds: [...(valueIdsByDimension.get(d.id) ?? [])]
+ }))
+ );
+ }
+
+ return {
+ data: { groups, columnKeys, hasMore, valueNames },
+ error: null
+ };
+}
+
+type DimensionPivotLineRow =
+ Database["public"]["Functions"]["journalDimensionPivotLines"]["Returns"][number];
+
+/**
+ * Drill-through: the journal lines behind one pivot cell.
+ *
+ * NULL semantics per axis (row 1 / row 2 / column): passing the dimension
+ * param with NO value param means Unassigned (the RPC matches lines with no
+ * tag for that dimension) — so `rowValue1IsNull` maps to "send
+ * p_row_dimension_1, omit p_row_value_1". A period column narrows postingDate
+ * via p_column_period_start/end instead of a dimension match.
+ */
+export async function getDimensionPivotLines(
+ client: SupabaseClient<Database>,
+ args: {
+ companyId: string;
+ companyGroupId: string;
+ report: AnalyticsReportDefinition;
+ scrapAccountIds?: string[];
+ startDate: string;
+ endDate: string;
+ filters: PivotState["filters"];
+ rowDimension1?: string;
+ rowValue1?: string;
+ rowValue1IsNull?: boolean;
+ rowDimension2?: string;
+ rowValue2?: string;
+ rowValue2IsNull?: boolean;
+ columnDimension?: string;
+ columnValue?: string;
+ columnValueIsNull?: boolean;
+ columnPeriodStart?: string;
+ columnPeriodEnd?: string;
+ accountIds?: string[];
+ }
+): Promise<{
+ data: DimensionPivotLineRow[] | null;
+ error: PostgrestError | null;
+}> {
+ // Same short-circuit as getDimensionPivot: no scrap account, no scope.
+ if (
+ "source" in args.report.accountScope &&
+ (args.scrapAccountIds ?? []).length === 0
+ ) {
+ return { data: [], error: null };
+ }
+
+ const result = await client.rpc("journalDimensionPivotLines", {
+ p_company_group_id: args.companyGroupId,
+ p_company_id: args.companyId,
+ p_start: args.startDate,
+ p_end: args.endDate,
+ ...pivotAccountScopeParams(args.report.accountScope, args.scrapAccountIds),
+ ...(args.filters.length > 0 ? { p_filters: args.filters } : {}),
+ ...(args.rowDimension1 ? { p_row_dimension_1: args.rowDimension1 } : {}),
+ ...(args.rowValue1 ? { p_row_value_1: args.rowValue1 } : {}),
+ ...(args.rowDimension2 ? { p_row_dimension_2: args.rowDimension2 } : {}),
+ ...(args.rowValue2 ? { p_row_value_2: args.rowValue2 } : {}),
+ ...(args.columnDimension
+ ? { p_column_dimension: args.columnDimension }
+ : {}),
+ ...(args.columnValue ? { p_column_value: args.columnValue } : {}),
+ ...(args.columnPeriodStart
+ ? { p_column_period_start: args.columnPeriodStart }
+ : {}),
+ ...(args.columnPeriodEnd
+ ? { p_column_period_end: args.columnPeriodEnd }
+ : {}),
+ ...((args.accountIds ?? []).length > 0
+ ? { p_filter_account_ids: args.accountIds }
+ : {})
+ });
+
+ if (result.error) return { data: null, error: result.error };
+
+ // Re-sort authoritatively in TS — never trust RPC ordering.
+ const lines = [...(result.data ?? [])].sort((a, b) => {
+ if (a.postingDate !== b.postingDate) {
+ return a.postingDate < b.postingDate ? -1 : 1;
+ }
+ return a.id < b.id ? -1 : a.id > b.id ? 1 : 0;
+ });
+
+ return { data: lines, error: null };
+}
+
+// -- Purchases analytics (purchase invoice subledger) --
+// RPCs in 20260809211324_purchases-pivot-report.sql. Gross invoiced spend
+// from purchaseInvoiceLine — NOT the GL journal (AP nets on payment; item
+// tags don't live on AP lines). Output matches DimensionPivotData so the
+// existing PivotTree renders it unchanged.
+
+// Grouping-field key → the entityType used to resolve value ids to names.
+const PURCHASE_FIELD_ENTITY_TYPE: Record<string, string> = {
+ supplier: "Supplier",
+ supplierType: "SupplierType",
+ item: "Item",
+ itemPostingGroup: "ItemPostingGroup",
+ costCenter: "CostCenter"
+};
+
+export async function getPurchaseLinePivot(
+ client: SupabaseClient<Database>,
+ args: {
+ companyId: string;
+ startDate: string;
+ endDate: string;
+ periodEnds?: string[];
+ state: PivotState;
+ }
+): Promise<{
+ data: DimensionPivotData | null;
+ error: PostgrestError | null;
+}> {
+ const { state } = args;
+ const columnField =
+ state.columnAxis.type === "dimension"
+ ? state.columnAxis.dimensionId
+ : undefined;
+
+ const result = await client.rpc("purchaseLineDimensionPivot", {
+ p_company_id: args.companyId,
+ p_start: args.startDate,
+ p_end: args.endDate,
+ ...(state.rows[0] ? { p_row_field_1: state.rows[0] } : {}),
+ ...(state.rows[1] ? { p_row_field_2: state.rows[1] } : {}),
+ ...(columnField ? { p_column_field: columnField } : {}),
+ ...(state.columnAxis.type === "period" && args.periodEnds
+ ? { p_period_ends: args.periodEnds }
+ : {})
+ });
+
+ if (result.error) return { data: null, error: result.error };
+
+ const rows = (result.data ?? []) as Array<{
+ rowValue1Id: string | null;
+ rowValue2Id: string | null;
+ columnKey: string | null;
+ amount: number | string;
+ quantity: number | string;
+ lineCount: number | string;
+ hasMore: boolean;
+ }>;
+
+ const hasMore = rows.some((r) => r.hasMore);
+
+ const groups: DimensionPivotGroup[] = rows
+ .map((r) => ({
+ rowValue1Id: r.rowValue1Id,
+ rowValue2Id: r.rowValue2Id,
+ columnKey: r.columnKey,
+ amount: Number(r.amount),
+ quantity: Number(r.quantity),
+ lineCount: Number(r.lineCount)
+ }))
+ .sort((a, b) => Math.abs(b.amount) - Math.abs(a.amount));
+
+ const hasUnassignedColumn = groups.some((g) => g.columnKey === null);
+ let columnKeys: string[];
+ if (state.columnAxis.type === "period") {
+ columnKeys = [...(args.periodEnds ?? [])];
+ for (const g of groups) {
+ if (g.columnKey !== null && !columnKeys.includes(g.columnKey)) {
+ columnKeys.push(g.columnKey);
+ }
+ }
+ } else {
+ const totalsByColumn = new Map<string, number>();
+ for (const g of groups) {
+ if (g.columnKey === null) continue;
+ totalsByColumn.set(
+ g.columnKey,
+ (totalsByColumn.get(g.columnKey) ?? 0) + g.amount
+ );
+ }
+ columnKeys = [...totalsByColumn.keys()].sort(
+ (a, b) =>
+ Math.abs(totalsByColumn.get(b) ?? 0) -
+ Math.abs(totalsByColumn.get(a) ?? 0)
+ );
+ }
+ if (hasUnassignedColumn) columnKeys.push(UNASSIGNED_COLUMN_KEY);
+
+ // Resolve value ids to names, batched by each grouping field's entityType.
+ const valueIdsByField = new Map<string, Set<string>>();
+ const collect = (field: string | undefined, valueId: string | null) => {
+ if (!field || !valueId) return;
+ const set = valueIdsByField.get(field) ?? new Set<string>();
+ set.add(valueId);
+ valueIdsByField.set(field, set);
+ };
+ for (const g of groups) {
+ collect(state.rows[0], g.rowValue1Id);
+ collect(state.rows[1], g.rowValue2Id);
+ collect(columnField, g.columnKey);
+ }
+
+ let valueNames: Record<string, string> = {};
+ if (valueIdsByField.size > 0) {
+ valueNames = await resolveDimensionValueNames(
+ client,
+ [...valueIdsByField.entries()]
+ .map(([field, ids]) => ({
+ entityType: PURCHASE_FIELD_ENTITY_TYPE[field] ?? "",
+ valueIds: [...ids]
+ }))
+ .filter((request) => request.entityType)
+ );
+ }
+
+ return {
+ data: { groups, columnKeys, hasMore, valueNames },
+ error: null
+ };
+}
+
+type PurchaseLinePivotRow =
+ Database["public"]["Functions"]["purchaseLinePivotLines"]["Returns"][number];
+
+export async function getPurchaseLinePivotLines(
+ client: SupabaseClient<Database>,
+ args: {
+ companyId: string;
+ startDate: string;
+ endDate: string;
+ // A field is passed ONLY when the cell constrains that axis: with a value
+ // for a normal cell, or without one for the Unassigned bucket (the RPC
+ // then matches rows whose field IS NULL). Omit the field for row totals /
+ // parent cells to leave the axis unconstrained.
+ rowField1?: string;
+ rowValue1?: string;
+ rowField2?: string;
+ rowValue2?: string;
+ columnField?: string;
+ columnValue?: string;
+ columnPeriodStart?: string;
+ columnPeriodEnd?: string;
+ }
+): Promise<{
+ data: PurchaseLinePivotRow[] | null;
+ error: PostgrestError | null;
+}> {
+ const result = await client.rpc("purchaseLinePivotLines", {
+ p_company_id: args.companyId,
+ p_start: args.startDate,
+ p_end: args.endDate,
+ ...(args.rowField1 ? { p_row_field_1: args.rowField1 } : {}),
+ ...(args.rowValue1 ? { p_row_value_1: args.rowValue1 } : {}),
+ ...(args.rowField2 ? { p_row_field_2: args.rowField2 } : {}),
+ ...(args.rowValue2 ? { p_row_value_2: args.rowValue2 } : {}),
+ ...(args.columnField ? { p_column_field: args.columnField } : {}),
+ ...(args.columnValue ? { p_column_value: args.columnValue } : {}),
+ ...(args.columnPeriodStart
+ ? { p_column_period_start: args.columnPeriodStart }
+ : {}),
+ ...(args.columnPeriodEnd
+ ? { p_column_period_end: args.columnPeriodEnd }
+ : {})
+ });
+
+ if (result.error) return { data: null, error: result.error };
+
+ // Re-sort authoritatively in TS — never trust RPC ordering.
+ const lines = [...(result.data ?? [])].sort((a, b) => {
+ if (a.postingDate !== b.postingDate) {
+ return a.postingDate < b.postingDate ? -1 : 1;
+ }
+ return a.id < b.id ? -1 : a.id > b.id ? 1 : 0;
+ });
+
+ return { data: lines, error: null };
+}
+
+/**
+ * Batch-resolves dimension value ids to display names, grouped by the owning
+ * dimension's entityType. Entity-backed types resolve through the shared
+ * entityType → source-table mapping (getEntityValuesByIds — the same helper
+ * getJournalLineDimensions uses); Custom resolves from dimensionValue.
+ * Lookup failures degrade to missing entries (callers fall back to the id).
+ */
+async function resolveDimensionValueNames(
+ client: SupabaseClient<Database>,
+ requests: { entityType: string; valueIds: string[] }[]
+): Promise<Record<string, string>> {
+ const batches = await Promise.all(
+ requests.map(async ({ entityType, valueIds }) => {
+ if (valueIds.length === 0) return [];
+ if (entityType === "Custom") {
+ const res = await client
+ .from("dimensionValue")
+ .select("id, name")
+ .in("id", valueIds);
+ return res.data ?? [];
+ }
+ const res = await getEntityValuesByIds(client, entityType, valueIds);
+ return res.data ?? [];
+ })
+ );
+
+ const valueNames: Record<string, string> = {};
+ for (const batch of batches) {
+ for (const item of batch as { id: string; name: string }[]) {
+ valueNames[item.id] = item.name;
+ }
+ }
+ return valueNames;
+}
+
+// Named, shareable saved pivot views for the analytics reports. RLS handles
+// visibility (Company rows are readable by every employee; Private rows only
+// by their creator; writes stay owner-only).
+export async function getReportViews(
+ client: SupabaseClient<Database>,
+ args: { companyId: string; reportKey?: string }
+) {
+ let query = client
+ .from("reportView")
+ .select("*")
+ .eq("companyId", args.companyId);
+
+ if (args.reportKey) {
+ query = query.eq("reportKey", args.reportKey);
+ }
+
+ return query.order("name", { ascending: true });
+}
+
+export async function upsertReportView(
+ client: SupabaseClient<Database>,
+ view:
+ | {
+ reportKey: string;
+ name: string;
+ visibility: Database["public"]["Enums"]["reportViewVisibility"];
+ config: Json;
+ companyId: string;
+ createdBy: string;
+ }
+ | {
+ id: string;
+ reportKey: string;
+ name: string;
+ visibility: Database["public"]["Enums"]["reportViewVisibility"];
+ config: Json;
+ companyId: string;
+ updatedBy: string;
+ }
+) {
+ if ("id" in view) {
+ const { id, companyId, ...update } = view;
+ return client
+ .from("reportView")
+ .update({ ...update, updatedAt: datetime.timestamp() })
+ .eq("id", id)
+ .eq("companyId", companyId)
+ .select("*")
+ .single();
+ }
+ return client.from("reportView").insert([view]).select("*").single();
+}
+
+export async function deleteReportView(
+ client: SupabaseClient<Database>,
+ id: string,
+ companyId: string
+) {
+ return client
+ .from("reportView")
+ .delete()
+ .eq("id", id)
+ .eq("companyId", companyId);
+}
+
export async function getCompaniesInGroup(
client: SupabaseClient<Database>,
companyGroupId: string
@@ -1994,6 +3135,30 @@ export async function getDefaultAccounts(
.single();
}
+/**
+ * The GL account ids scrap postings offset to, for the scrap analytics
+ * report's account scope (accountScope.source === "scrapAccounts"). Empty
+ * when no scrap account is configured — getDimensionPivot short-circuits to
+ * an empty pivot in that case.
+ */
+export async function getScrapAccountIds(
+ client: SupabaseClient<Database>,
+ companyId: string
+): Promise<{ data: string[]; error: PostgrestError | null }> {
+ const result = await client
+ .from("accountDefault")
+ .select("scrapAccount")
+ .eq("companyId", companyId)
+ .maybeSingle();
+
+ if (result.error) return { data: [], error: result.error };
+
+ return {
+ data: result.data?.scrapAccount ? [result.data.scrapAccount] : [],
+ error: null
+ };
+}
+
export async function getFiscalYearSettings(
client: SupabaseClient<Database>,
companyId: string
@@ -2791,18 +3956,16 @@ export async function translateCompanyBalances(
return { data: rows, cta, error: null };
}
-export async function getConsolidatedBalances(
+// Find elimination entities that should be included automatically in a
+// consolidation. An elimination entity is included when its parentCompanyId is
+// an ancestor of any selected company (i.e. it sits at or above the selected
+// companies in the hierarchy and captures their intercompany eliminations).
+// Returns the operating company ids plus those elimination entity ids.
+async function resolveConsolidationCompanyIds(
client: SupabaseClient<Database>,
companyGroupId: string,
- companyIds: string[],
- targetCurrency: string,
- periodEnd: string,
- periodStart?: string
-) {
- // Find elimination entities that should be included automatically.
- // An elimination entity is included when its parentCompanyId is an ancestor
- // of any selected company (i.e. it sits at or above the selected companies
- // in the hierarchy and captures their intercompany eliminations).
+ companyIds: string[]
+): Promise<string[]> {
const { data: allGroupCompanies } = await client
.from("company")
.select("id, parentCompanyId, isEliminationEntity")
@@ -2834,8 +3997,23 @@ export async function getConsolidatedBalances(
)
.map((c) => c.id);
+ return [...companyIds, ...eliminationIds];
+}
+
+export async function getConsolidatedBalances(
+ client: SupabaseClient<Database>,
+ companyGroupId: string,
+ companyIds: string[],
+ targetCurrency: string,
+ periodEnd: string,
+ periodStart?: string
+) {
// All companies whose balances we need (operating + elimination entities)
- const allIds = [...companyIds, ...eliminationIds];
+ const allIds = await resolveConsolidationCompanyIds(
+ client,
+ companyGroupId,
+ companyIds
+ );
// Get balances for all companies, then translate the already-computed
// balances to the target currency (one ledger scan per company, not two).
diff --git a/apps/erp/app/modules/accounting/types.ts b/apps/erp/app/modules/accounting/types.ts
index 535048946c..20a8bfa26c 100644
--- a/apps/erp/app/modules/accounting/types.ts
+++ b/apps/erp/app/modules/accounting/types.ts
@@ -8,11 +8,15 @@ import type {
getCostCentersTree,
getCurrencies,
getDimension,
+ getDimensionPivot,
+ getDimensionPivotLines,
getDimensions,
getJournalEntries,
getJournalEntry,
getPaymentTerms,
- getPeriodCloseReadiness
+ getPeriodCloseReadiness,
+ getPurchaseLinePivotLines,
+ getReportViews
} from "./accounting.service";
export type Account = NonNullable<
@@ -60,6 +64,24 @@ export type DimensionDetail = NonNullable<
Awaited<ReturnType<typeof getDimension>>["data"]
>;
+// -- Dimensional analytics (pivot) report types --
+
+export type DimensionPivot = NonNullable<
+ Awaited<ReturnType<typeof getDimensionPivot>>["data"]
+>;
+
+export type DimensionPivotLine = NonNullable<
+ Awaited<ReturnType<typeof getDimensionPivotLines>>["data"]
+>[number];
+
+export type PurchaseLinePivotLine = NonNullable<
+ Awaited<ReturnType<typeof getPurchaseLinePivotLines>>["data"]
+>[number];
+
+export type ReportView = NonNullable<
+ Awaited<ReturnType<typeof getReportViews>>["data"]
+>[number];
+
export const currencyCodes = [
"AFN",
"AFA",
@@ -397,6 +419,26 @@ export type TranslatedTransaction = Transaction & {
exchangeRate?: number;
};
+// One report column's values for one account, keyed by ReportPeriodBucket.key.
+// `translatedBalance` is the translated cumulative balance (balanceAtDate × rate,
+// for balance-sheet/stock reads); `translatedNetChange` is the translated period
+// delta (netChange × rate, for income-statement/flow reads).
+export type PeriodCell = {
+ netChange: number;
+ balanceAtDate: number;
+ translatedBalance?: number;
+ translatedNetChange?: number;
+ exchangeRate?: number;
+};
+
+// A chart row with multi-period values for the /x/reports statements. Reads
+// come from the "accounts" view merged with the accountTreeBalancePeriodSeries
+// RPC — only the hierarchy columns and per-period cells, no single-measure
+// balance columns.
+export type ChartPeriodSeries = Account & {
+ periods: Record<string, PeriodCell>;
+};
+
export type JournalEntry = NonNullable<
Awaited<ReturnType<typeof getJournalEntry>>["data"]
>;
diff --git a/apps/erp/app/modules/accounting/ui/AccountingBetaGate.tsx b/apps/erp/app/modules/accounting/ui/AccountingBetaGate.tsx
new file mode 100644
index 0000000000..be836451f4
--- /dev/null
+++ b/apps/erp/app/modules/accounting/ui/AccountingBetaGate.tsx
@@ -0,0 +1,76 @@
+import { Button } from "@carbon/react";
+import { Trans } from "@lingui/react/macro";
+import { LuLock } from "react-icons/lu";
+import { useLocation } from "react-router";
+import {
+ UpgradeOverlayActions,
+ UpgradeOverlayCard,
+ UpgradeOverlayContent,
+ UpgradeOverlayDescription,
+ UpgradeOverlayIcon,
+ UpgradeOverlayTitle
+} from "~/components/UpgradeOverlay";
+import { useSettings } from "~/hooks";
+import { useUIStore } from "~/stores/ui";
+import { path } from "~/utils/path";
+
+const gatedRoutes = [
+ path.to.reports,
+ path.to.intercompany,
+ path.to.accountingJournals,
+ path.to.accountingPeriods,
+ path.to.fixedAssets,
+ path.to.depreciationRuns
+];
+
+const REQUEST_ACCESS_MESSAGE =
+ "I would like to request access to the accounting beta";
+
+export default function AccountingBetaGate() {
+ const settings = useSettings();
+ const location = useLocation();
+ const requestSuggestion = useUIStore((state) => state.requestSuggestion);
+
+ const accountingEnabled = (settings as any).accountingEnabled ?? false;
+ if (accountingEnabled) return null;
+
+ const isGated = gatedRoutes.some((route) =>
+ location.pathname.startsWith(route)
+ );
+ if (!isGated) return null;
+
+ return (
+ <div className="absolute inset-0 z-10 bg-background/60 backdrop-blur-sm">
+ <UpgradeOverlayCard>
+ <UpgradeOverlayIcon>
+ <LuLock className="size-6 text-muted-foreground" />
+ </UpgradeOverlayIcon>
+ <UpgradeOverlayContent>
+ <UpgradeOverlayTitle>
+ <Trans>Accounting is disabled for this company.</Trans>
+ </UpgradeOverlayTitle>
+ <UpgradeOverlayDescription>
+ <Trans>
+ Accounting is currently in beta. Request access to enable
+ reporting, journal entries, accounting periods, fixed assets, and
+ more.
+ </Trans>
+ </UpgradeOverlayDescription>
+ </UpgradeOverlayContent>
+ <UpgradeOverlayActions>
+ <Button
+ onClick={() =>
+ requestSuggestion({
+ suggestion: REQUEST_ACCESS_MESSAGE,
+ anonymous: false,
+ sendToCarbon: true
+ })
+ }
+ >
+ <Trans>Request access</Trans>
+ </Button>
+ </UpgradeOverlayActions>
+ </UpgradeOverlayCard>
+ </div>
+ );
+}
diff --git a/apps/erp/app/modules/accounting/ui/Reports/ExecutivePnlSummary.tsx b/apps/erp/app/modules/accounting/ui/Reports/ExecutivePnlSummary.tsx
new file mode 100644
index 0000000000..93809df91b
--- /dev/null
+++ b/apps/erp/app/modules/accounting/ui/Reports/ExecutivePnlSummary.tsx
@@ -0,0 +1,198 @@
+import { cn } from "@carbon/react";
+import type {
+ ReportColumnGranularity,
+ ReportPeriodBucket
+} from "@carbon/utils";
+import { Trans, useLingui } from "@lingui/react/macro";
+import { useLocale } from "@react-aria/i18n";
+import { memo, useEffect, useMemo, useRef } from "react";
+import { useRealtime } from "~/hooks";
+import type { ChartPeriodSeries } from "../../types";
+import { computeExecutivePnl, type ExecutivePnlRowKey } from "./executivePnl";
+import { getPeriodColumnLabel } from "./MultiPeriodStatementTree";
+
+const ACCOUNT_COLUMN_WIDTH = 360;
+const PERIOD_COLUMN_WIDTH = 128;
+
+type ExecutivePnlSummaryProps = {
+ /** Income-statement accounts (filtered to incomeBalance "Income Statement"). */
+ data: ChartPeriodSeries[];
+ periods: ReportPeriodBucket[];
+ columns: ReportColumnGranularity;
+ showTranslated?: boolean;
+ parentCurrency?: string | null;
+};
+
+function formatCurrency(value: number | null | undefined): string {
+ if (value == null) return "-";
+ return value.toLocaleString(undefined, {
+ minimumFractionDigits: 2,
+ maximumFractionDigits: 2
+ });
+}
+
+const ExecutivePnlSummary = memo(
+ ({
+ data,
+ periods,
+ columns,
+ showTranslated = false,
+ parentCurrency
+ }: ExecutivePnlSummaryProps) => {
+ const { t } = useLingui();
+ const { locale } = useLocale();
+ useRealtime("journal");
+ const scrollRef = useRef<HTMLDivElement>(null);
+ const headerRef = useRef<HTMLDivElement>(null);
+
+ // Mirror the body's horizontal scroll onto the header so columns track.
+ useEffect(() => {
+ const element = scrollRef.current;
+ if (!element) return;
+ const sync = () => {
+ if (headerRef.current)
+ headerRef.current.scrollLeft = element.scrollLeft;
+ };
+ element.addEventListener("scroll", sync, { passive: true });
+ return () => element.removeEventListener("scroll", sync);
+ }, []);
+
+ const rows = useMemo(
+ () =>
+ computeExecutivePnl(
+ data,
+ periods.map((bucket) => bucket.key),
+ { showTranslated }
+ ),
+ [data, periods, showTranslated]
+ );
+
+ const labels: Record<ExecutivePnlRowKey, string> = {
+ revenue: t`Revenue`,
+ cogs: t`Cost of Sales`,
+ grossProfit: t`Gross Profit`,
+ operatingExpenses: t`Operating Expenses`,
+ operatingIncome: t`Operating Income`,
+ otherIncome: t`Other Income`,
+ otherExpense: t`Other Expense`,
+ tax: t`Income Tax`,
+ netIncome: t`Net Income`
+ };
+
+ const percentFormatter = useMemo(
+ () =>
+ new Intl.NumberFormat(locale, {
+ style: "percent",
+ minimumFractionDigits: 1,
+ maximumFractionDigits: 1
+ }),
+ [locale]
+ );
+
+ const rowWidth =
+ ACCOUNT_COLUMN_WIDTH + periods.length * PERIOD_COLUMN_WIDTH + 16;
+
+ return (
+ <div className="flex h-[calc(100dvh-var(--header-height)-61px)] w-full flex-col">
+ {/* Header viewport — scrollLeft is mirrored from the body below */}
+ <div ref={headerRef} className="shrink-0 overflow-x-hidden">
+ <div
+ className="flex h-12 items-center border-b border-border bg-card pr-4 text-sm font-medium text-foreground/80"
+ style={{ minWidth: rowWidth }}
+ >
+ <div
+ className="sticky left-0 z-[2] flex h-full shrink-0 items-center bg-card px-4"
+ style={{ width: ACCOUNT_COLUMN_WIDTH }}
+ >
+ <Trans>Executive P&amp;L</Trans>
+ </div>
+ {periods.map((bucket) => (
+ <div
+ key={bucket.key}
+ className="flex shrink-0 flex-col items-end justify-center px-2 text-right"
+ style={{ width: PERIOD_COLUMN_WIDTH }}
+ >
+ <span className="whitespace-nowrap">
+ {getPeriodColumnLabel(bucket, columns, locale)}
+ </span>
+ {bucket.isPartial && (
+ <span className="text-xs font-normal text-muted-foreground">
+ {t`To Date`}
+ </span>
+ )}
+ </div>
+ ))}
+ </div>
+ </div>
+
+ <div ref={scrollRef} className="flex-1 overflow-auto">
+ <div style={{ minWidth: rowWidth }}>
+ {rows.map((row) => (
+ <div
+ key={row.key}
+ className={cn(
+ "flex h-9 items-center pr-4 text-sm",
+ row.isSubtotal && "font-semibold",
+ row.isSubtotal &&
+ !row.isBottomLine &&
+ "border-t border-border",
+ row.isBottomLine &&
+ "border-y-2 border-border bg-muted/40 font-semibold"
+ )}
+ style={{ minWidth: rowWidth }}
+ >
+ {/* Sticky label cell */}
+ <div
+ className={cn(
+ "sticky left-0 z-[1] flex h-full shrink-0 items-center px-4",
+ row.isBottomLine ? "bg-muted/40" : "bg-card"
+ )}
+ style={{ width: ACCOUNT_COLUMN_WIDTH }}
+ >
+ <span className="truncate">{labels[row.key]}</span>
+ </div>
+
+ {/* One cell per period bucket */}
+ {periods.map((bucket) => {
+ const value = row.values[bucket.key] ?? 0;
+ const margin = row.margins?.[bucket.key];
+ return (
+ <div
+ key={bucket.key}
+ className="flex shrink-0 flex-col items-end justify-center px-2 text-right tabular-nums"
+ style={{ width: PERIOD_COLUMN_WIDTH }}
+ >
+ <span
+ className={cn(
+ !row.isSubtotal && "text-muted-foreground"
+ )}
+ >
+ {formatCurrency(value)}
+ </span>
+ {row.margins != null && (
+ <span className="text-xs font-normal text-muted-foreground">
+ {margin == null
+ ? "-"
+ : percentFormatter.format(margin)}
+ </span>
+ )}
+ </div>
+ );
+ })}
+ </div>
+ ))}
+ </div>
+ </div>
+
+ {showTranslated && parentCurrency && (
+ <div className="shrink-0 border-t border-border bg-card px-4 py-1.5 text-xs text-muted-foreground">
+ <Trans>Showing in {parentCurrency}</Trans>
+ </div>
+ )}
+ </div>
+ );
+ }
+);
+
+ExecutivePnlSummary.displayName = "ExecutivePnlSummary";
+export default ExecutivePnlSummary;
diff --git a/apps/erp/app/modules/accounting/ui/Reports/FinancialStatementTree.tsx b/apps/erp/app/modules/accounting/ui/Reports/FinancialStatementTree.tsx
deleted file mode 100644
index a40ad9b4c4..0000000000
--- a/apps/erp/app/modules/accounting/ui/Reports/FinancialStatementTree.tsx
+++ /dev/null
@@ -1,289 +0,0 @@
-import { cn, ScrollArea } from "@carbon/react";
-import { Trans, useLingui } from "@lingui/react/macro";
-import { memo, useMemo, useRef } from "react";
-import {
- LuCalculator,
- LuChevronDown,
- LuChevronRight,
- LuFolder,
- LuFolderOpen
-} from "react-icons/lu";
-import { useNavigate } from "react-router";
-import type { FlatTree, FlatTreeItem } from "~/components/TreeView";
-import { LevelLine, TreeView, useTree } from "~/components/TreeView";
-import { useRealtime, useUrlParams } from "~/hooks";
-import type { Chart } from "../../types";
-import { NET_INCOME_ACCOUNT_ID } from "../../types";
-
-type TranslatedChart = Chart & {
- translatedBalance?: number;
- exchangeRate?: number;
-};
-
-type FinancialStatementTreeProps = {
- data: TranslatedChart[];
- /**
- * Which RPC measure the amount column shows. The Balance Sheet reads
- * "balanceAtDate" (closing balance as of endDate = the ledger drawer's
- * Closing); the Income Statement reads "netChange" (activity within the
- * startDate–endDate range = the drawer's Net Change). Never the RPC's
- * all-time "balance".
- */
- measure: "balanceAtDate" | "netChange";
- showTranslated?: boolean;
- parentCurrency?: string | null;
- search: string;
- /** When provided, clicking a leaf account opens its ledger drill-down */
- ledgerPath?: (accountId: string) => string;
-};
-
-function accountsToFlatTree(
- accounts: TranslatedChart[]
-): FlatTree<TranslatedChart> {
- const byParent = new Map<string, TranslatedChart[]>();
- for (const a of accounts) {
- const key = a.parentId ?? "__root__";
- if (!byParent.has(key)) byParent.set(key, []);
- byParent.get(key)!.push(a);
- }
-
- const result: FlatTreeItem<TranslatedChart>[] = [];
-
- function walk(parentId: string | null, level: number) {
- const children = (byParent.get(parentId ?? "__root__") ?? []).sort(
- (a, b) => {
- const aIsGroup = a.isGroup ? 1 : 0;
- const bIsGroup = b.isGroup ? 1 : 0;
- if (aIsGroup !== bIsGroup) return aIsGroup - bIsGroup;
- // The computed Net Income line always sorts to the end of its group.
- if (a.id === NET_INCOME_ACCOUNT_ID) return 1;
- if (b.id === NET_INCOME_ACCOUNT_ID) return -1;
- return (a.name ?? "").localeCompare(b.name ?? "");
- }
- );
- for (const account of children) {
- const childAccounts = byParent.get(account.id) ?? [];
- const childIds = childAccounts.map((c) => c.id);
- result.push({
- id: account.id,
- parentId: parentId ?? undefined,
- children: childIds,
- hasChildren: childIds.length > 0,
- level,
- data: account
- });
- walk(account.id, level + 1);
- }
- }
-
- walk(null, 0);
- return result;
-}
-
-function filterAccounts(
- accounts: TranslatedChart[],
- search: string
-): TranslatedChart[] {
- if (!search.trim()) return accounts;
- const lower = search.toLowerCase();
-
- const byId = new Map(accounts.map((a) => [a.id, a]));
- const matched = new Set<string>();
-
- for (const a of accounts) {
- const nameMatch = a.name?.toLowerCase().includes(lower);
- const numberMatch = a.number?.toLowerCase().includes(lower);
- if (nameMatch || numberMatch) {
- matched.add(a.id as string);
- let parentId = a.parentId;
- while (parentId) {
- matched.add(parentId);
- const parent = byId.get(parentId);
- parentId = parent?.parentId ?? null;
- }
- }
- }
-
- return accounts.filter((a) => matched.has(a.id as string));
-}
-
-function formatCurrency(value: number): string {
- return value.toLocaleString(undefined, {
- minimumFractionDigits: 2,
- maximumFractionDigits: 2
- });
-}
-
-const FinancialStatementTree = memo(
- ({
- data,
- measure,
- showTranslated = false,
- parentCurrency,
- search,
- ledgerPath
- }: FinancialStatementTreeProps) => {
- const { t } = useLingui();
- const measureLabel = measure === "netChange" ? t`Net Change` : t`Balance`;
- useRealtime("journal");
- const navigate = useNavigate();
- const [params] = useUrlParams();
- const parentRef = useRef<HTMLDivElement>(null);
-
- const openLedger = (accountId: string) => {
- if (!ledgerPath) return;
- const nextParams = new URLSearchParams(params);
- nextParams.delete("offset");
- const qs = nextParams.toString();
- navigate(qs ? `${ledgerPath(accountId)}?${qs}` : ledgerPath(accountId));
- };
-
- const filtered = useMemo(
- () => filterAccounts(data, search),
- [data, search]
- );
- const tree = useMemo(() => accountsToFlatTree(filtered), [filtered]);
-
- const {
- nodes,
- getTreeProps,
- getNodeProps,
- selectNode,
- toggleExpandNode,
- virtualizer
- } = useTree<TranslatedChart, undefined>({
- tree,
- parentRef,
- estimatedRowHeight: () => 36,
- isEager: true
- });
-
- return (
- <ScrollArea className="h-[calc(100dvh-var(--header-height)-61px)] w-full">
- <div className="sticky top-0 z-10 flex h-11 items-center pr-4 text-sm font-medium text-foreground/80 border-b border-border bg-card">
- <div className="flex-1 px-4">
- <Trans>Account</Trans>
- </div>
- <span className="w-32 text-right px-4">
- {showTranslated ? t`Local` : measureLabel}
- </span>
- {showTranslated && (
- <span className="w-32 text-right px-4">
- {parentCurrency ?? "Translated"}
- </span>
- )}
- </div>
- <TreeView<TranslatedChart>
- tree={tree}
- nodes={nodes}
- getTreeProps={getTreeProps}
- getNodeProps={getNodeProps}
- virtualizer={virtualizer}
- parentRef={parentRef}
- parentClassName="h-full"
- renderNode={({ node, state }) => {
- const account = node.data;
- const isGroup = account.isGroup;
- const isExpanded = state.expanded;
- const isDrillable =
- !isGroup && !!ledgerPath && account.id !== NET_INCOME_ACCOUNT_ID;
-
- return (
- <div
- className={cn(
- "flex h-8 cursor-pointer items-center overflow-hidden pr-4 text-sm group/row",
- state.selected
- ? "bg-muted hover:bg-accent"
- : "bg-transparent hover:bg-accent",
- isGroup && "font-semibold"
- )}
- onClick={() => {
- selectNode(node.id, false);
- if (isGroup) {
- toggleExpandNode(node.id);
- } else if (isDrillable) {
- openLedger(account.id);
- }
- }}
- >
- {/* Indentation lines */}
- <div className="flex h-9 items-center">
- {Array.from({ length: node.level }).map((_, index) => (
- <LevelLine key={index} isSelected={state.selected} />
- ))}
-
- <div
- className={cn(
- "flex h-9 w-5 items-center justify-center",
- node.hasChildren && "hover:bg-accent"
- )}
- onClick={(e) => {
- e.stopPropagation();
- toggleExpandNode(node.id);
- }}
- >
- {node.hasChildren ? (
- isExpanded ? (
- <LuChevronDown className="h-4 w-4 text-muted-foreground flex-shrink-0" />
- ) : (
- <LuChevronRight className="h-4 w-4 text-muted-foreground flex-shrink-0" />
- )
- ) : (
- <div className="h-9 w-5" />
- )}
- </div>
- </div>
-
- {/* Folder icon */}
- <div className="w-5 h-5 flex items-center justify-center mr-2 shrink-0">
- {isGroup &&
- (isExpanded ? (
- <LuFolderOpen className="h-4 w-4 text-muted-foreground" />
- ) : (
- <LuFolder className="h-4 w-4 text-muted-foreground" />
- ))}
- </div>
-
- {/* Account number + name */}
- <div className="flex flex-1 items-center gap-2 overflow-hidden">
- {!isGroup && account.number && (
- <span className="text-muted-foreground shrink-0">
- {account.number}
- </span>
- )}
- <span className="truncate">{account.name}</span>
- {account.id === NET_INCOME_ACCOUNT_ID && (
- <LuCalculator className="h-3.5 w-3.5 text-muted-foreground shrink-0" />
- )}
- </div>
-
- {/* Balance (as of endDate) or Net Change (within range) */}
- <span
- className={cn(
- "w-32 text-right tabular-nums shrink-0 text-muted-foreground",
- isDrillable &&
- "group-hover/row:text-foreground group-hover/row:underline underline-offset-2 decoration-border"
- )}
- >
- {formatCurrency(account[measure] ?? 0)}
- </span>
-
- {/* Translated Balance */}
- {showTranslated && (
- <span className="w-32 text-right tabular-nums shrink-0 text-muted-foreground">
- {account.translatedBalance != null
- ? formatCurrency(account.translatedBalance)
- : "-"}
- </span>
- )}
- </div>
- );
- }}
- />
- </ScrollArea>
- );
- }
-);
-
-FinancialStatementTree.displayName = "FinancialStatementTree";
-export default FinancialStatementTree;
diff --git a/apps/erp/app/modules/accounting/ui/Reports/MultiPeriodStatementTree.tsx b/apps/erp/app/modules/accounting/ui/Reports/MultiPeriodStatementTree.tsx
new file mode 100644
index 0000000000..22c56e9a6c
--- /dev/null
+++ b/apps/erp/app/modules/accounting/ui/Reports/MultiPeriodStatementTree.tsx
@@ -0,0 +1,308 @@
+import { cn } from "@carbon/react";
+import type {
+ ReportColumnGranularity,
+ ReportPeriodBucket
+} from "@carbon/utils";
+import { formatDate } from "@carbon/utils";
+import { Trans, useLingui } from "@lingui/react/macro";
+import { useLocale } from "@react-aria/i18n";
+import { memo, useEffect, useMemo, useRef } from "react";
+import {
+ LuCalculator,
+ LuChevronDown,
+ LuChevronRight,
+ LuFolder,
+ LuFolderOpen
+} from "react-icons/lu";
+import { useNavigate } from "react-router";
+import { LevelLine, TreeView, useTree } from "~/components/TreeView";
+import { useRealtime, useUrlParams } from "~/hooks";
+import type { ChartPeriodSeries } from "../../types";
+import { NET_INCOME_ACCOUNT_ID } from "../../types";
+import { accountsToFlatTree, filterAccounts } from "./reportTree";
+
+const ACCOUNT_COLUMN_WIDTH = 360;
+const PERIOD_COLUMN_WIDTH = 128;
+
+type MultiPeriodStatementTreeProps = {
+ data: ChartPeriodSeries[];
+ /** Ordered buckets from computeReportPeriodBuckets — one column each */
+ periods: ReportPeriodBucket[];
+ columns: ReportColumnGranularity;
+ /**
+ * Which measure the period cells show. The Balance Sheet reads
+ * "balanceAtDate" (closing balance as of each bucket end); the Income
+ * Statement reads "netChange" (activity within each bucket).
+ */
+ measure: "balanceAtDate" | "netChange";
+ /** When true, cells show the bucket's translated balance instead */
+ showTranslated?: boolean;
+ parentCurrency?: string | null;
+ search: string;
+ /** When provided, clicking a leaf account opens its ledger drill-down */
+ ledgerPath?: (accountId: string) => string;
+};
+
+function formatCurrency(value: number | null | undefined): string {
+ if (value == null) return "-";
+ return value.toLocaleString(undefined, {
+ minimumFractionDigits: 2,
+ maximumFractionDigits: 2
+ });
+}
+
+export function getPeriodColumnLabel(
+ bucket: ReportPeriodBucket,
+ columns: ReportColumnGranularity,
+ locale?: string
+): string {
+ switch (columns) {
+ case "month":
+ return formatDate(
+ bucket.start,
+ { month: "short", year: "numeric" },
+ locale
+ );
+ case "quarter":
+ return `Q${bucket.quarter} FY${bucket.fiscalYear}`;
+ case "year":
+ return `FY${bucket.fiscalYear}`;
+ }
+}
+
+const MultiPeriodStatementTree = memo(
+ ({
+ data,
+ periods,
+ columns,
+ measure,
+ showTranslated = false,
+ parentCurrency,
+ search,
+ ledgerPath
+ }: MultiPeriodStatementTreeProps) => {
+ const { t } = useLingui();
+ const { locale } = useLocale();
+ useRealtime("journal");
+ const navigate = useNavigate();
+ const [params] = useUrlParams();
+ const parentRef = useRef<HTMLDivElement>(null);
+ const scrollRef = useRef<HTMLElement | null>(null);
+ const headerRef = useRef<HTMLDivElement>(null);
+
+ // The tree's own element scrolls both axes; mirror its horizontal offset
+ // onto the header viewport so the column headers track the columns.
+ useEffect(() => {
+ const element = scrollRef.current;
+ if (!element) return;
+ const sync = () => {
+ if (headerRef.current) {
+ headerRef.current.scrollLeft = element.scrollLeft;
+ }
+ };
+ element.addEventListener("scroll", sync, { passive: true });
+ return () => element.removeEventListener("scroll", sync);
+ }, []);
+
+ const openLedger = (accountId: string) => {
+ if (!ledgerPath) return;
+ const nextParams = new URLSearchParams(params);
+ nextParams.delete("offset");
+ const qs = nextParams.toString();
+ navigate(qs ? `${ledgerPath(accountId)}?${qs}` : ledgerPath(accountId));
+ };
+
+ const filtered = useMemo(
+ () => filterAccounts(data, search),
+ [data, search]
+ );
+ const tree = useMemo(() => accountsToFlatTree(filtered), [filtered]);
+
+ const {
+ nodes,
+ getTreeProps,
+ getNodeProps,
+ selectNode,
+ toggleExpandNode,
+ virtualizer
+ } = useTree<ChartPeriodSeries, undefined>({
+ tree,
+ parentRef,
+ estimatedRowHeight: () => 36,
+ isEager: true
+ });
+
+ const rowWidth =
+ ACCOUNT_COLUMN_WIDTH + periods.length * PERIOD_COLUMN_WIDTH + 16;
+
+ return (
+ <div className="flex h-[calc(100dvh-var(--header-height)-61px)] w-full flex-col">
+ {/* Header viewport — scrollLeft is mirrored from the tree below */}
+ <div ref={headerRef} className="shrink-0 overflow-x-hidden">
+ <div
+ className="flex h-12 items-center border-b border-border bg-card pr-4 text-sm font-medium text-foreground/80"
+ style={{ minWidth: rowWidth }}
+ >
+ <div
+ className="sticky left-0 z-[2] flex h-full shrink-0 items-center bg-card px-4"
+ style={{ width: ACCOUNT_COLUMN_WIDTH }}
+ >
+ <Trans>Account</Trans>
+ </div>
+ {periods.map((bucket) => (
+ <div
+ key={bucket.key}
+ className="flex shrink-0 flex-col items-end justify-center px-2 text-right"
+ style={{ width: PERIOD_COLUMN_WIDTH }}
+ >
+ <span className="whitespace-nowrap">
+ {getPeriodColumnLabel(bucket, columns, locale)}
+ </span>
+ {bucket.isPartial && (
+ <span className="text-xs font-normal text-muted-foreground">
+ {t`To Date`}
+ </span>
+ )}
+ </div>
+ ))}
+ </div>
+ </div>
+ <TreeView<ChartPeriodSeries>
+ tree={tree}
+ nodes={nodes}
+ getTreeProps={getTreeProps}
+ getNodeProps={getNodeProps}
+ virtualizer={virtualizer}
+ parentRef={parentRef}
+ scrollRef={scrollRef}
+ parentClassName="flex-1 overflow-x-auto"
+ contentMinWidth={rowWidth}
+ renderNode={({ node, state }) => {
+ const account = node.data;
+ const isGroup = account.isGroup;
+ const isExpanded = state.expanded;
+ const isDrillable =
+ !isGroup && !!ledgerPath && account.id !== NET_INCOME_ACCOUNT_ID;
+
+ return (
+ <div
+ className={cn(
+ "flex h-8 cursor-pointer items-center pr-4 text-sm group/row",
+ state.selected
+ ? "bg-muted hover:bg-accent"
+ : "bg-transparent hover:bg-accent",
+ isGroup && "font-semibold"
+ )}
+ style={{ minWidth: rowWidth }}
+ onClick={() => {
+ selectNode(node.id, false);
+ if (isGroup) {
+ toggleExpandNode(node.id);
+ } else if (isDrillable) {
+ openLedger(account.id);
+ }
+ }}
+ >
+ {/* Pinned account cell: indentation + folder + number + name */}
+ <div
+ className={cn(
+ "sticky left-0 z-[1] flex h-full shrink-0 items-center overflow-hidden",
+ state.selected
+ ? "bg-muted group-hover/row:bg-accent"
+ : "bg-card group-hover/row:bg-accent"
+ )}
+ style={{ width: ACCOUNT_COLUMN_WIDTH }}
+ >
+ {/* Indentation lines */}
+ <div className="flex h-9 items-center">
+ {Array.from({ length: node.level }).map((_, index) => (
+ <LevelLine key={index} isSelected={state.selected} />
+ ))}
+
+ <div
+ className={cn(
+ "flex h-9 w-5 items-center justify-center",
+ node.hasChildren && "hover:bg-accent"
+ )}
+ onClick={(e) => {
+ e.stopPropagation();
+ toggleExpandNode(node.id);
+ }}
+ >
+ {node.hasChildren ? (
+ isExpanded ? (
+ <LuChevronDown className="h-4 w-4 text-muted-foreground flex-shrink-0" />
+ ) : (
+ <LuChevronRight className="h-4 w-4 text-muted-foreground flex-shrink-0" />
+ )
+ ) : (
+ <div className="h-9 w-5" />
+ )}
+ </div>
+ </div>
+
+ {/* Folder icon */}
+ <div className="w-5 h-5 flex items-center justify-center mr-2 shrink-0">
+ {isGroup &&
+ (isExpanded ? (
+ <LuFolderOpen className="h-4 w-4 text-muted-foreground" />
+ ) : (
+ <LuFolder className="h-4 w-4 text-muted-foreground" />
+ ))}
+ </div>
+
+ {/* Account number + name */}
+ <div className="flex flex-1 items-center gap-2 overflow-hidden pr-2">
+ {!isGroup && account.number && (
+ <span className="text-muted-foreground shrink-0">
+ {account.number}
+ </span>
+ )}
+ <span className="truncate">{account.name}</span>
+ {account.id === NET_INCOME_ACCOUNT_ID && (
+ <LuCalculator className="h-3.5 w-3.5 text-muted-foreground shrink-0" />
+ )}
+ </div>
+ </div>
+
+ {/* One cell per period bucket */}
+ {periods.map((bucket) => {
+ const cell = account.periods?.[bucket.key];
+ // Translated: the Income Statement (netChange) must read the
+ // translated period delta; the Balance Sheet (balanceAtDate)
+ // reads the translated cumulative balance.
+ const value = showTranslated
+ ? measure === "netChange"
+ ? cell?.translatedNetChange
+ : cell?.translatedBalance
+ : (cell?.[measure] ?? 0);
+ return (
+ <span
+ key={bucket.key}
+ className={cn(
+ "shrink-0 px-2 text-right tabular-nums text-muted-foreground",
+ isDrillable &&
+ "group-hover/row:text-foreground group-hover/row:underline underline-offset-2 decoration-border"
+ )}
+ style={{ width: PERIOD_COLUMN_WIDTH }}
+ >
+ {formatCurrency(value)}
+ </span>
+ );
+ })}
+ </div>
+ );
+ }}
+ />
+ {showTranslated && parentCurrency && (
+ <div className="shrink-0 border-t border-border bg-card px-4 py-1.5 text-xs text-muted-foreground">
+ <Trans>Showing in {parentCurrency}</Trans>
+ </div>
+ )}
+ </div>
+ );
+ }
+);
+
+MultiPeriodStatementTree.displayName = "MultiPeriodStatementTree";
+export default MultiPeriodStatementTree;
diff --git a/apps/erp/app/modules/accounting/ui/Reports/PivotControlBar.tsx b/apps/erp/app/modules/accounting/ui/Reports/PivotControlBar.tsx
new file mode 100644
index 0000000000..e0735435b4
--- /dev/null
+++ b/apps/erp/app/modules/accounting/ui/Reports/PivotControlBar.tsx
@@ -0,0 +1,523 @@
+import {
+ ActionMenu,
+ Button,
+ DropdownMenu,
+ DropdownMenuCheckboxItem,
+ DropdownMenuContent,
+ DropdownMenuIcon,
+ DropdownMenuItem,
+ DropdownMenuLabel,
+ DropdownMenuRadioGroup,
+ DropdownMenuRadioItem,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+ HStack,
+ Switch
+} from "@carbon/react";
+import { Trans, useLingui } from "@lingui/react/macro";
+import { useMemo, useState } from "react";
+import {
+ LuBookmarkPlus,
+ LuColumns3,
+ LuCornerDownRight,
+ LuDownload,
+ LuListFilter,
+ LuRows3,
+ LuSigma,
+ LuTrash2,
+ LuX
+} from "react-icons/lu";
+import { PeriodSelector } from "~/components";
+import { DimensionEntityTypeIcon } from "~/components/Icons";
+import ConfirmDelete from "~/components/Modals/ConfirmDelete";
+import { useUrlParams } from "~/hooks";
+import { path } from "~/utils/path";
+import type {
+ AnalyticsReportKey,
+ PivotMeasure,
+ PivotState
+} from "../../accounting.models";
+import { financialReportColumns, pivotMeasures } from "../../accounting.models";
+import type { getActiveDimensionsWithValues } from "../../accounting.service";
+import type { ReportView } from "../../types";
+import SaveViewModal from "./SaveViewModal";
+
+export type PivotDimension = NonNullable<
+ Awaited<ReturnType<typeof getActiveDimensionsWithValues>>["data"]
+>[number];
+
+export type PivotAccount = {
+ id: string;
+ number: string | null;
+ name: string;
+};
+
+type PivotControlBarProps = {
+ reportKey: AnalyticsReportKey;
+ dimensions: PivotDimension[];
+ state: PivotState;
+ savedViews: ReportView[];
+ activeViewId?: string;
+ currentUserId: string;
+ accounts: PivotAccount[];
+ onDownload: () => void;
+};
+
+const PivotControlBar = ({
+ reportKey,
+ dimensions,
+ state,
+ savedViews,
+ activeViewId,
+ currentUserId,
+ accounts,
+ onDownload
+}: PivotControlBarProps) => {
+ const { t } = useLingui();
+ const [params, setParams] = useUrlParams();
+
+ // Transient interaction state only (like modal open/close) — all report
+ // state lives in the URL per the pivot param contract.
+ const [saveModalOpen, setSaveModalOpen] = useState(false);
+ const [deleteModalOpen, setDeleteModalOpen] = useState(false);
+
+ const dimensionById = useMemo(
+ () => new Map(dimensions.map((d) => [d.dimensionId, d])),
+ [dimensions]
+ );
+
+ const columnLabels: Record<(typeof financialReportColumns)[number], string> =
+ {
+ month: t`Monthly`,
+ quarter: t`Quarterly`,
+ year: t`Yearly`
+ };
+
+ const measureLabels: Record<PivotMeasure, string> = {
+ amount: t`Amount`,
+ quantity: t`Quantity`,
+ count: t`Count`
+ };
+
+ // -- Rows --
+
+ const row1 = state.rows[0];
+ const row2 = state.rows[1];
+
+ const setRows = (rows: string[]) => {
+ setParams({ rows: rows.length > 0 ? rows.join(",") : undefined });
+ };
+
+ const onRow1Change = (dimensionId: string) => {
+ if (!dimensionId) {
+ // Clearing the first level promotes the second, if any
+ setRows(row2 ? [row2] : []);
+ return;
+ }
+ setRows([dimensionId, ...(row2 && row2 !== dimensionId ? [row2] : [])]);
+ };
+
+ const onRow2Change = (dimensionId: string) => {
+ if (!row1) return;
+ setRows(dimensionId ? [row1, dimensionId] : [row1]);
+ };
+
+ // -- Columns --
+
+ const columnAxisValue =
+ state.columnAxis.type === "period" ? state.columnAxis.bucket : "dimension";
+
+ const columnDimensionId =
+ state.columnAxis.type === "dimension"
+ ? state.columnAxis.dimensionId
+ : undefined;
+
+ const columnDimensionCandidates = dimensions.filter(
+ (d) => !state.rows.includes(d.dimensionId)
+ );
+
+ const columnLabel =
+ state.columnAxis.type === "period"
+ ? columnLabels[state.columnAxis.bucket]
+ : (dimensionById.get(state.columnAxis.dimensionId)?.dimensionName ??
+ t`By dimension`);
+
+ const onColumnAxisChange = (value: string) => {
+ if (value === "dimension") {
+ const fallback = columnDimensionCandidates[0];
+ if (!fallback) return;
+ setParams({ col: `dim:${fallback.dimensionId}` });
+ return;
+ }
+ // period:month is the default — omit it from the URL like ReportFilters
+ setParams({ col: value === "month" ? undefined : `period:${value}` });
+ };
+
+ // -- Accounts --
+ // A subset of the report's account scope. Empty = the full scope (all
+ // accounts); a non-empty set narrows the report to those accounts.
+
+ const accountById = useMemo(
+ () => new Map(accounts.map((a) => [a.id, a])),
+ [accounts]
+ );
+ const selectedAccountIds = state.accountIds.filter((id) =>
+ accountById.has(id)
+ );
+
+ const setAccounts = (ids: string[]) => {
+ setParams({ accounts: ids.length > 0 ? ids.join(",") : undefined });
+ };
+
+ const toggleAccount = (id: string) => {
+ setAccounts(
+ selectedAccountIds.includes(id)
+ ? selectedAccountIds.filter((a) => a !== id)
+ : [...selectedAccountIds, id]
+ );
+ };
+
+ const accountsLabel =
+ selectedAccountIds.length === 0
+ ? t`All accounts`
+ : selectedAccountIds.length === 1
+ ? (accountById.get(selectedAccountIds[0])?.name ??
+ selectedAccountIds[0])
+ : t`${selectedAccountIds.length} accounts`;
+
+ // -- Saved views --
+
+ const privateViews = savedViews.filter((v) => v.visibility === "Private");
+ const companyViews = savedViews.filter((v) => v.visibility === "Company");
+ const activeView = savedViews.find((v) => v.id === activeViewId);
+
+ const onSelectView = (id: string) => {
+ if (!id) return;
+ // The view's config supplies the pivot state, so drop any explicit pivot
+ // params (which would otherwise win over the view in the loader). Dates
+ // are unrelated to the saved config and are preserved.
+ setParams({
+ view: id,
+ rows: undefined,
+ col: undefined,
+ measure: undefined,
+ pct: undefined,
+ filters: undefined,
+ accounts: undefined,
+ sort: undefined
+ });
+ };
+
+ const onReset = () => {
+ setParams({
+ rows: undefined,
+ col: undefined,
+ measure: undefined,
+ pct: undefined,
+ filters: undefined,
+ accounts: undefined,
+ sort: undefined,
+ view: undefined,
+ startDate: undefined,
+ endDate: undefined
+ });
+ };
+
+ return (
+ <div className="flex flex-wrap px-4 py-3 items-center gap-2 justify-between bg-card border-b border-border w-full">
+ <HStack className="flex-wrap gap-y-2">
+ <PeriodSelector variant="range" />
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button variant="secondary" leftIcon={<LuRows3 />}>
+ {row1
+ ? (dimensionById.get(row1)?.dimensionName ?? row1)
+ : t`Group by`}
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="start">
+ <DropdownMenuRadioGroup
+ value={row1 ?? ""}
+ onValueChange={onRow1Change}
+ >
+ <DropdownMenuRadioItem value="">
+ <Trans>None</Trans>
+ </DropdownMenuRadioItem>
+ {dimensions.map((dim) => (
+ <DropdownMenuRadioItem
+ key={dim.dimensionId}
+ value={dim.dimensionId}
+ >
+ <DropdownMenuIcon
+ icon={
+ <DimensionEntityTypeIcon
+ entityType={dim.entityType as any}
+ />
+ }
+ />
+ {dim.dimensionName}
+ </DropdownMenuRadioItem>
+ ))}
+ </DropdownMenuRadioGroup>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button
+ variant="secondary"
+ leftIcon={<LuCornerDownRight />}
+ isDisabled={!row1}
+ >
+ {row2
+ ? (dimensionById.get(row2)?.dimensionName ?? row2)
+ : t`Then by`}
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="start">
+ <DropdownMenuRadioGroup
+ value={row2 ?? ""}
+ onValueChange={onRow2Change}
+ >
+ <DropdownMenuRadioItem value="">
+ <Trans>None</Trans>
+ </DropdownMenuRadioItem>
+ {dimensions
+ .filter((dim) => dim.dimensionId !== row1)
+ .map((dim) => (
+ <DropdownMenuRadioItem
+ key={dim.dimensionId}
+ value={dim.dimensionId}
+ >
+ <DropdownMenuIcon
+ icon={
+ <DimensionEntityTypeIcon
+ entityType={dim.entityType as any}
+ />
+ }
+ />
+ {dim.dimensionName}
+ </DropdownMenuRadioItem>
+ ))}
+ </DropdownMenuRadioGroup>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button variant="secondary" leftIcon={<LuColumns3 />}>
+ {columnLabel}
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="start">
+ <DropdownMenuRadioGroup
+ value={columnAxisValue}
+ onValueChange={onColumnAxisChange}
+ >
+ {financialReportColumns.map((granularity) => (
+ <DropdownMenuRadioItem key={granularity} value={granularity}>
+ {columnLabels[granularity]}
+ </DropdownMenuRadioItem>
+ ))}
+ <DropdownMenuSeparator />
+ <DropdownMenuRadioItem
+ value="dimension"
+ disabled={columnDimensionCandidates.length === 0}
+ >
+ <Trans>By dimension</Trans>
+ </DropdownMenuRadioItem>
+ </DropdownMenuRadioGroup>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ {state.columnAxis.type === "dimension" && (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button variant="secondary">
+ {columnDimensionId
+ ? (dimensionById.get(columnDimensionId)?.dimensionName ??
+ columnDimensionId)
+ : t`Column dimension`}
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="start">
+ <DropdownMenuRadioGroup
+ value={columnDimensionId ?? ""}
+ onValueChange={(value) => {
+ if (value) setParams({ col: `dim:${value}` });
+ }}
+ >
+ {columnDimensionCandidates.map((dim) => (
+ <DropdownMenuRadioItem
+ key={dim.dimensionId}
+ value={dim.dimensionId}
+ >
+ <DropdownMenuIcon
+ icon={
+ <DimensionEntityTypeIcon
+ entityType={dim.entityType as any}
+ />
+ }
+ />
+ {dim.dimensionName}
+ </DropdownMenuRadioItem>
+ ))}
+ </DropdownMenuRadioGroup>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ )}
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button variant="secondary" leftIcon={<LuSigma />}>
+ {measureLabels[state.measure]}
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="start">
+ <DropdownMenuRadioGroup
+ value={state.measure}
+ onValueChange={(value) =>
+ setParams({ measure: value === "amount" ? undefined : value })
+ }
+ >
+ {pivotMeasures.map((measure) => (
+ <DropdownMenuRadioItem key={measure} value={measure}>
+ {measureLabels[measure]}
+ </DropdownMenuRadioItem>
+ ))}
+ </DropdownMenuRadioGroup>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ {accounts.length > 0 && (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button variant="secondary" leftIcon={<LuListFilter />}>
+ {accountsLabel}
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent
+ align="start"
+ className="max-h-80 overflow-y-auto"
+ >
+ <DropdownMenuLabel>
+ <Trans>Accounts</Trans>
+ </DropdownMenuLabel>
+ {selectedAccountIds.length > 0 && (
+ <>
+ <DropdownMenuItem onClick={() => setAccounts([])}>
+ <DropdownMenuIcon icon={<LuX />} />
+ <Trans>Clear selection</Trans>
+ </DropdownMenuItem>
+ <DropdownMenuSeparator />
+ </>
+ )}
+ {accounts.map((account) => (
+ <DropdownMenuCheckboxItem
+ key={account.id}
+ checked={selectedAccountIds.includes(account.id)}
+ onSelect={(event) => {
+ // Keep the menu open so several accounts can be toggled.
+ event.preventDefault();
+ toggleAccount(account.id);
+ }}
+ >
+ {account.number ? `${account.number} · ` : ""}
+ {account.name}
+ </DropdownMenuCheckboxItem>
+ ))}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ )}
+ <Switch
+ variant="small"
+ checked={state.percentOfTotal}
+ onCheckedChange={(checked) =>
+ setParams({ pct: checked ? "1" : undefined })
+ }
+ label={t`% of total`}
+ />
+ {[...params.entries()].length > 0 && (
+ <Button variant="secondary" rightIcon={<LuX />} onClick={onReset}>
+ {t`Reset`}
+ </Button>
+ )}
+ </HStack>
+ <HStack className="gap-2">
+ <Button
+ variant="secondary"
+ leftIcon={<LuDownload />}
+ onClick={onDownload}
+ >
+ {t`Download`}
+ </Button>
+ <ActionMenu>
+ <DropdownMenuItem onClick={() => setSaveModalOpen(true)}>
+ <DropdownMenuIcon icon={<LuBookmarkPlus />} />
+ <Trans>Save view</Trans>
+ </DropdownMenuItem>
+ {activeView && activeView.createdBy === currentUserId && (
+ <DropdownMenuItem
+ destructive
+ onClick={() => setDeleteModalOpen(true)}
+ >
+ <DropdownMenuIcon icon={<LuTrash2 />} />
+ <Trans>Delete view</Trans>
+ </DropdownMenuItem>
+ )}
+ {savedViews.length > 0 && (
+ <>
+ <DropdownMenuSeparator />
+ <DropdownMenuRadioGroup
+ value={activeViewId ?? ""}
+ onValueChange={onSelectView}
+ >
+ {privateViews.length > 0 && (
+ <>
+ <DropdownMenuLabel>
+ <Trans>Private</Trans>
+ </DropdownMenuLabel>
+ {privateViews.map((view) => (
+ <DropdownMenuRadioItem key={view.id} value={view.id}>
+ {view.name}
+ </DropdownMenuRadioItem>
+ ))}
+ </>
+ )}
+ {privateViews.length > 0 && companyViews.length > 0 && (
+ <DropdownMenuSeparator />
+ )}
+ {companyViews.length > 0 && (
+ <>
+ <DropdownMenuLabel>
+ <Trans>Company</Trans>
+ </DropdownMenuLabel>
+ {companyViews.map((view) => (
+ <DropdownMenuRadioItem key={view.id} value={view.id}>
+ {view.name}
+ </DropdownMenuRadioItem>
+ ))}
+ </>
+ )}
+ </DropdownMenuRadioGroup>
+ </>
+ )}
+ </ActionMenu>
+ </HStack>
+ {saveModalOpen && (
+ <SaveViewModal
+ reportKey={reportKey}
+ state={state}
+ view={activeView}
+ onClose={() => setSaveModalOpen(false)}
+ />
+ )}
+ {deleteModalOpen && activeView && (
+ <ConfirmDelete
+ action={path.to.deleteReportView(activeView.id)}
+ name={activeView.name}
+ text={t`Are you sure you want to delete the "${activeView.name}" view? This cannot be undone.`}
+ onCancel={() => setDeleteModalOpen(false)}
+ onSubmit={() => setDeleteModalOpen(false)}
+ />
+ )}
+ </div>
+ );
+};
+
+export default PivotControlBar;
diff --git a/apps/erp/app/modules/accounting/ui/Reports/PivotLinesDrawer.tsx b/apps/erp/app/modules/accounting/ui/Reports/PivotLinesDrawer.tsx
new file mode 100644
index 0000000000..b89200c30e
--- /dev/null
+++ b/apps/erp/app/modules/accounting/ui/Reports/PivotLinesDrawer.tsx
@@ -0,0 +1,191 @@
+import {
+ Drawer,
+ DrawerBody,
+ DrawerContent,
+ DrawerHeader,
+ DrawerTitle,
+ Spinner,
+ Table,
+ Tbody,
+ Td,
+ Tfoot,
+ Th,
+ Thead,
+ Tr
+} from "@carbon/react";
+import { formatDate } from "@carbon/utils";
+import { Trans, useLingui } from "@lingui/react/macro";
+import { useLocale } from "@react-aria/i18n";
+import { useMemo } from "react";
+import type { DimensionPivotLine } from "../../types";
+
+// The drill-through RPC caps results at 500 lines; surface the cap when hit.
+const LINE_LIMIT = 500;
+
+type PivotLinesDrawerProps = {
+ open: boolean;
+ onClose: () => void;
+ title: string;
+ lines: DimensionPivotLine[] | null;
+ isLoading: boolean;
+};
+
+// Same money formatting as AccountLedgerDrawer.formatAmount.
+function formatAmount(value: number): string {
+ return value.toLocaleString(undefined, {
+ minimumFractionDigits: 2,
+ maximumFractionDigits: 2
+ });
+}
+
+function formatQuantity(value: number): string {
+ return value.toLocaleString(undefined, { maximumFractionDigits: 2 });
+}
+
+/**
+ * Presentational drill-through drawer for one pivot cell. The route owns the
+ * fetcher: it fetches the lines for the clicked cell coordinates and passes
+ * them here (matching AccountLedgerDrawer, which also receives its lines as
+ * props from the route).
+ */
+const PivotLinesDrawer = ({
+ open,
+ onClose,
+ title,
+ lines,
+ isLoading
+}: PivotLinesDrawerProps) => {
+ const { t } = useLingui();
+ const { locale } = useLocale();
+
+ const totals = useMemo(
+ () =>
+ (lines ?? []).reduce(
+ (acc, line) => {
+ acc.amount += line.amount;
+ acc.quantity += line.quantity;
+ return acc;
+ },
+ { amount: 0, quantity: 0 }
+ ),
+ [lines]
+ );
+
+ return (
+ <Drawer
+ open={open}
+ onOpenChange={(isOpen) => {
+ if (!isOpen) onClose();
+ }}
+ >
+ <DrawerContent size="lg">
+ <DrawerHeader>
+ <DrawerTitle>{title}</DrawerTitle>
+ </DrawerHeader>
+ <DrawerBody className="p-0">
+ {isLoading ? (
+ <div className="flex w-full items-center justify-center py-16">
+ <Spinner size={24} />
+ </div>
+ ) : !lines || lines.length === 0 ? (
+ <div className="flex w-full items-center justify-center py-16 text-sm text-muted-foreground">
+ <Trans>No transactions in this period</Trans>
+ </div>
+ ) : (
+ <>
+ {lines.length === LINE_LIMIT && (
+ <div className="border-b border-border px-4 py-1.5 text-xs text-muted-foreground">
+ {t`Showing the first 500 lines`}
+ </div>
+ )}
+ <Table>
+ <Thead>
+ <Tr>
+ <Th className="px-4">
+ <Trans>Date</Trans>
+ </Th>
+ <Th className="px-4">
+ <Trans>Journal</Trans>
+ </Th>
+ <Th className="px-4">
+ <Trans>Account</Trans>
+ </Th>
+ <Th className="px-4 w-full">
+ <Trans>Description</Trans>
+ </Th>
+ <Th className="px-4">
+ <Trans>Document</Trans>
+ </Th>
+ <Th className="px-4 text-right">
+ <Trans>Amount</Trans>
+ </Th>
+ <Th className="px-4 text-right">
+ <Trans>Quantity</Trans>
+ </Th>
+ </Tr>
+ </Thead>
+ <Tbody>
+ {lines.map((line) => (
+ <Tr key={line.id} className="hover:bg-muted/50">
+ <Td className="px-4 whitespace-nowrap text-muted-foreground">
+ {formatDate(line.postingDate, undefined, locale)}
+ </Td>
+ <Td className="px-4 whitespace-nowrap font-mono text-xs">
+ {line.journalEntryId}
+ </Td>
+ <Td className="px-4 whitespace-nowrap">
+ <div className="flex items-center gap-2">
+ {line.accountNumber && (
+ <span className="text-muted-foreground shrink-0">
+ {line.accountNumber}
+ </span>
+ )}
+ <span className="line-clamp-1">
+ {line.accountName}
+ </span>
+ </div>
+ </Td>
+ <Td className="px-4">
+ <p className="line-clamp-1">
+ {line.description || "–"}
+ </p>
+ </Td>
+ <Td className="px-4 whitespace-nowrap text-xs text-muted-foreground">
+ {line.documentType || line.documentId
+ ? [line.documentType, line.documentId]
+ .filter(Boolean)
+ .join(" ")
+ : "–"}
+ </Td>
+ <Td className="px-4 text-right tabular-nums">
+ {formatAmount(line.amount)}
+ </Td>
+ <Td className="px-4 text-right tabular-nums">
+ {formatQuantity(line.quantity)}
+ </Td>
+ </Tr>
+ ))}
+ </Tbody>
+ <Tfoot>
+ <Tr className="font-medium">
+ <Td className="px-4" colSpan={5}>
+ <Trans>Total</Trans>
+ </Td>
+ <Td className="px-4 text-right tabular-nums">
+ {formatAmount(totals.amount)}
+ </Td>
+ <Td className="px-4 text-right tabular-nums">
+ {formatQuantity(totals.quantity)}
+ </Td>
+ </Tr>
+ </Tfoot>
+ </Table>
+ </>
+ )}
+ </DrawerBody>
+ </DrawerContent>
+ </Drawer>
+ );
+};
+
+export default PivotLinesDrawer;
diff --git a/apps/erp/app/modules/accounting/ui/Reports/PivotTree.tsx b/apps/erp/app/modules/accounting/ui/Reports/PivotTree.tsx
new file mode 100644
index 0000000000..927ea1ebc0
--- /dev/null
+++ b/apps/erp/app/modules/accounting/ui/Reports/PivotTree.tsx
@@ -0,0 +1,502 @@
+import { cn } from "@carbon/react";
+import { Trans, useLingui } from "@lingui/react/macro";
+import { useLocale } from "@react-aria/i18n";
+import { useVirtualizer } from "@tanstack/react-virtual";
+import { memo, useEffect, useMemo, useRef } from "react";
+import {
+ LuChartNoAxesColumnIncreasing,
+ LuChevronDown,
+ LuChevronRight,
+ LuChevronsUpDown,
+ LuChevronUp
+} from "react-icons/lu";
+import { LevelLine, TreeView, useTree } from "~/components/TreeView";
+import { useRealtime, useUrlParams } from "~/hooks";
+import type { PivotMeasure, PivotState } from "../../accounting.models";
+import type { DimensionPivot } from "../../types";
+import type { PivotCellValue, PivotRowNode } from "./pivotData";
+import {
+ applyPercentOfTotal,
+ buildPivotTree,
+ getPivotMeasureValue,
+ LABEL_SORT_KEY,
+ TOTAL_SORT_KEY,
+ UNASSIGNED_COLUMN_KEY
+} from "./pivotData";
+
+const ROW_COLUMN_WIDTH = 360;
+const VALUE_COLUMN_WIDTH = 128;
+
+/**
+ * Cell coordinates handed back on drill-through. NULL semantics mirror
+ * getDimensionPivotLines: `rowValueNIsNull: true` means the Unassigned bucket
+ * (constrain to lines with no tag for that dimension); `rowValueNId: null`
+ * with `rowValueNIsNull: false` means no constraint on that axis (e.g. a
+ * level-1 parent cell leaves the second row dimension unconstrained).
+ * `columnKey` is the real column key (period end date or dimension value id);
+ * it is null for the Unassigned column and for row-total cells — use
+ * `isRowTotal` to tell those apart.
+ */
+export type PivotCellCoordinates = {
+ rowValue1Id: string | null;
+ rowValue1IsNull: boolean;
+ rowValue2Id: string | null;
+ rowValue2IsNull: boolean;
+ columnKey: string | null;
+ isRowTotal: boolean;
+};
+
+type PivotTreeProps = {
+ pivot: DimensionPivot;
+ state: PivotState;
+ /**
+ * columnKey → header label. The route computes period labels via
+ * getPeriodColumnLabel and dimension labels via pivot.valueNames; the
+ * Unassigned column label is supplied here (localized).
+ */
+ columnLabels: Record<string, string>;
+ onCellClick: (coordinates: PivotCellCoordinates) => void;
+};
+
+// Same money formatting as MultiPeriodStatementTree.formatCurrency.
+function formatAmount(value: number | null | undefined): string {
+ if (value == null) return "-";
+ return value.toLocaleString(undefined, {
+ minimumFractionDigits: 2,
+ maximumFractionDigits: 2
+ });
+}
+
+function formatMeasureValue(value: number, measure: PivotMeasure): string {
+ if (measure === "amount") return formatAmount(value);
+ if (measure === "quantity") {
+ return value.toLocaleString(undefined, { maximumFractionDigits: 2 });
+ }
+ return value.toLocaleString(undefined, { maximumFractionDigits: 0 });
+}
+
+const PivotTree = memo(
+ ({ pivot, state, columnLabels, onCellClick }: PivotTreeProps) => {
+ const { t } = useLingui();
+ const { locale } = useLocale();
+ const [, setParams] = useUrlParams();
+ useRealtime("journal");
+ const parentRef = useRef<HTMLDivElement>(null);
+ const scrollRef = useRef<HTMLElement | null>(null);
+ const headerRef = useRef<HTMLDivElement>(null);
+ const footerRef = useRef<HTMLDivElement>(null);
+
+ // The tree's own element scrolls both axes; mirror its horizontal offset
+ // onto the header and footer viewports so the columns stay aligned.
+ useEffect(() => {
+ const element = scrollRef.current;
+ if (!element) return;
+ const sync = () => {
+ if (headerRef.current) {
+ headerRef.current.scrollLeft = element.scrollLeft;
+ }
+ if (footerRef.current) {
+ footerRef.current.scrollLeft = element.scrollLeft;
+ }
+ };
+ element.addEventListener("scroll", sync, { passive: true });
+ return () => element.removeEventListener("scroll", sync);
+ }, []);
+
+ const rowCount = Math.min(state.rows.length, 2) as 0 | 1 | 2;
+
+ const pivotTree = useMemo(
+ () =>
+ buildPivotTree({
+ groups: pivot.groups,
+ valueNames: pivot.valueNames,
+ columnKeys: pivot.columnKeys,
+ rowCount,
+ measure: state.measure,
+ unassignedLabel: t`Unassigned`,
+ totalLabel: t`Total`,
+ sort: state.sort
+ }),
+ [pivot, rowCount, state.measure, state.sort, t]
+ );
+
+ const { flatTree, columnKeys, columnTotals, grandTotal } = pivotTree;
+
+ const percentFormatter = useMemo(
+ () =>
+ new Intl.NumberFormat(locale, {
+ style: "percent",
+ minimumFractionDigits: 1,
+ maximumFractionDigits: 1
+ }),
+ [locale]
+ );
+
+ const grandTotalValue = getPivotMeasureValue(grandTotal, state.measure);
+
+ const formatCell = (
+ cell: PivotCellValue | undefined,
+ percent: number | undefined
+ ): string => {
+ if (state.percentOfTotal) {
+ return percentFormatter.format((percent ?? 0) / 100);
+ }
+ return formatMeasureValue(
+ getPivotMeasureValue(cell, state.measure),
+ state.measure
+ );
+ };
+
+ const formatRowTotal = (total: PivotCellValue): string => {
+ const value = getPivotMeasureValue(total, state.measure);
+ if (state.percentOfTotal) {
+ const percent = grandTotalValue === 0 ? 0 : value / grandTotalValue;
+ return percentFormatter.format(percent);
+ }
+ return formatMeasureValue(value, state.measure);
+ };
+
+ const cellCoordinates = (
+ data: PivotRowNode,
+ level: number,
+ columnKey: string | null,
+ isRowTotal: boolean
+ ): PivotCellCoordinates => ({
+ rowValue1Id: data.rowValue1Id,
+ rowValue1IsNull: rowCount >= 1 && data.rowValue1Id === null,
+ rowValue2Id: data.rowValue2Id,
+ rowValue2IsNull:
+ rowCount === 2 && level === 1 && data.rowValue2Id === null,
+ columnKey:
+ isRowTotal || columnKey === UNASSIGNED_COLUMN_KEY ? null : columnKey,
+ isRowTotal
+ });
+
+ const {
+ nodes,
+ getTreeProps,
+ getNodeProps,
+ selectNode,
+ toggleExpandNode,
+ virtualizer
+ } = useTree<PivotRowNode, undefined>({
+ tree: flatTree,
+ parentRef,
+ estimatedRowHeight: () => 36,
+ isEager: true
+ });
+
+ const totalColumnsWidth = columnKeys.length * VALUE_COLUMN_WIDTH;
+ const rowWidth =
+ ROW_COLUMN_WIDTH + totalColumnsWidth + VALUE_COLUMN_WIDTH + 16;
+
+ // Horizontal virtualizer over the value columns — thousands of columns stay
+ // cheap because only the visible window renders in every row + header +
+ // footer. It reads the tree's own horizontal scroller (scrollRef), the same
+ // element the header/footer mirror their scrollLeft from.
+ const columnVirtualizer = useVirtualizer({
+ horizontal: true,
+ count: columnKeys.length,
+ getScrollElement: () => scrollRef.current,
+ estimateSize: () => VALUE_COLUMN_WIDTH,
+ overscan: 6
+ });
+ const virtualColumns = columnVirtualizer.getVirtualItems();
+
+ // Column-header sort: unsorted → firstDirection → opposite → unsorted.
+ const cycleSort = (key: string, firstDirection: "asc" | "desc") => {
+ const current = state.sort;
+ let next: PivotState["sort"];
+ if (!current || current.key !== key) {
+ next = { key, direction: firstDirection };
+ } else if (current.direction === firstDirection) {
+ next = { key, direction: firstDirection === "asc" ? "desc" : "asc" };
+ } else {
+ next = null;
+ }
+ setParams({ sort: next ? `${next.key}:${next.direction}` : undefined });
+ };
+
+ const renderSortIndicator = (key: string) => {
+ if (state.sort?.key === key) {
+ return state.sort.direction === "asc" ? (
+ <LuChevronUp className="h-3.5 w-3.5 shrink-0" />
+ ) : (
+ <LuChevronDown className="h-3.5 w-3.5 shrink-0" />
+ );
+ }
+ return (
+ <LuChevronsUpDown className="h-3.5 w-3.5 shrink-0 text-muted-foreground opacity-0 transition-opacity group-hover/header:opacity-60" />
+ );
+ };
+
+ if (pivot.groups.length === 0) {
+ return (
+ <div className="flex h-[calc(100dvh-var(--header-height)-61px)] w-full flex-col items-center justify-center gap-2 text-muted-foreground">
+ <LuChartNoAxesColumnIncreasing className="h-8 w-8" />
+ <p className="text-sm">
+ <Trans>No journal lines in scope for this period</Trans>
+ </p>
+ </div>
+ );
+ }
+
+ return (
+ <div className="flex h-[calc(100dvh-var(--header-height)-61px)] w-full flex-col">
+ {pivot.hasMore && (
+ <div className="shrink-0 border-b border-border bg-card px-4 py-1.5 text-xs text-muted-foreground">
+ <p>{t`Showing the top 1,000 groups by amount`}</p>
+ </div>
+ )}
+ {/* Header viewport — scrollLeft is mirrored from the tree below */}
+ <div ref={headerRef} className="shrink-0 overflow-x-hidden">
+ <div
+ className="relative flex h-12 items-center border-b border-border bg-card text-sm font-medium text-foreground/80"
+ style={{ minWidth: rowWidth }}
+ >
+ {/* Row-label header — sorts rows alphabetically by label */}
+ <button
+ type="button"
+ className={cn(
+ "group/header sticky left-0 z-[2] flex h-full shrink-0 items-center gap-1 bg-card px-4 text-muted-foreground hover:text-foreground",
+ state.sort?.key === LABEL_SORT_KEY && "text-foreground"
+ )}
+ style={{ width: ROW_COLUMN_WIDTH }}
+ onClick={() => cycleSort(LABEL_SORT_KEY, "asc")}
+ >
+ {renderSortIndicator(LABEL_SORT_KEY)}
+ </button>
+ {virtualColumns.map((virtualColumn) => {
+ const columnKey = columnKeys[virtualColumn.index];
+ if (columnKey === undefined) return null;
+ return (
+ <button
+ type="button"
+ key={columnKey}
+ className={cn(
+ "group/header absolute top-0 flex h-full items-center justify-end gap-1 px-2 text-right hover:text-foreground",
+ columnKey === UNASSIGNED_COLUMN_KEY &&
+ "italic text-muted-foreground",
+ state.sort?.key === columnKey && "text-foreground"
+ )}
+ style={{
+ left: ROW_COLUMN_WIDTH + virtualColumn.start,
+ width: VALUE_COLUMN_WIDTH
+ }}
+ onClick={() => cycleSort(columnKey, "desc")}
+ >
+ <span className="truncate">
+ {columnKey === UNASSIGNED_COLUMN_KEY
+ ? t`Unassigned`
+ : (columnLabels[columnKey] ?? columnKey)}
+ </span>
+ {renderSortIndicator(columnKey)}
+ </button>
+ );
+ })}
+ {/* Total header — sorts rows by their total */}
+ <button
+ type="button"
+ className={cn(
+ "group/header absolute top-0 flex h-full items-center justify-end gap-1 px-2 text-right hover:text-foreground",
+ state.sort?.key === TOTAL_SORT_KEY && "text-foreground"
+ )}
+ style={{
+ left: ROW_COLUMN_WIDTH + totalColumnsWidth,
+ width: VALUE_COLUMN_WIDTH
+ }}
+ onClick={() => cycleSort(TOTAL_SORT_KEY, "desc")}
+ >
+ <Trans>Total</Trans>
+ {renderSortIndicator(TOTAL_SORT_KEY)}
+ </button>
+ </div>
+ </div>
+ <TreeView<PivotRowNode>
+ tree={flatTree}
+ nodes={nodes}
+ getTreeProps={getTreeProps}
+ getNodeProps={getNodeProps}
+ virtualizer={virtualizer}
+ parentRef={parentRef}
+ scrollRef={scrollRef}
+ parentClassName="flex-1 overflow-x-auto"
+ contentMinWidth={rowWidth}
+ renderNode={({ node, state: nodeState }) => {
+ const row = node.data;
+ const percents = state.percentOfTotal
+ ? applyPercentOfTotal(row.cells, columnTotals, state.measure)
+ : undefined;
+
+ return (
+ <div
+ className={cn(
+ "relative flex h-8 cursor-pointer items-center text-sm group/row",
+ nodeState.selected
+ ? "bg-muted hover:bg-accent"
+ : "bg-transparent hover:bg-accent",
+ node.hasChildren && "font-semibold"
+ )}
+ style={{ minWidth: rowWidth }}
+ onClick={() => {
+ selectNode(node.id, false);
+ if (node.hasChildren) {
+ toggleExpandNode(node.id);
+ }
+ }}
+ >
+ {/* Pinned row cell: indentation + chevron + label */}
+ <div
+ className={cn(
+ "sticky left-0 z-[1] flex h-full shrink-0 items-center overflow-hidden",
+ nodeState.selected
+ ? "bg-muted group-hover/row:bg-accent"
+ : "bg-card group-hover/row:bg-accent"
+ )}
+ style={{ width: ROW_COLUMN_WIDTH }}
+ >
+ {/* Indentation lines */}
+ <div className="flex h-9 items-center">
+ {Array.from({ length: node.level }).map((_, index) => (
+ <LevelLine key={index} isSelected={nodeState.selected} />
+ ))}
+
+ <div
+ className={cn(
+ "flex h-9 w-5 items-center justify-center",
+ node.hasChildren && "hover:bg-accent"
+ )}
+ onClick={(e) => {
+ e.stopPropagation();
+ toggleExpandNode(node.id);
+ }}
+ >
+ {node.hasChildren ? (
+ nodeState.expanded ? (
+ <LuChevronDown className="h-4 w-4 text-muted-foreground flex-shrink-0" />
+ ) : (
+ <LuChevronRight className="h-4 w-4 text-muted-foreground flex-shrink-0" />
+ )
+ ) : (
+ <div className="h-9 w-5" />
+ )}
+ </div>
+ </div>
+
+ <div className="flex flex-1 items-center gap-2 overflow-hidden pl-2 pr-2">
+ <span
+ className={cn(
+ "truncate",
+ row.isUnassigned && "italic text-muted-foreground"
+ )}
+ >
+ {row.label}
+ </span>
+ </div>
+ </div>
+
+ {/* Virtualized value cells — only the visible column window */}
+ {virtualColumns.map((virtualColumn) => {
+ const columnKey = columnKeys[virtualColumn.index];
+ if (columnKey === undefined) return null;
+ return (
+ <span
+ key={columnKey}
+ className="absolute top-0 flex h-full cursor-pointer items-center justify-end px-2 text-right tabular-nums text-muted-foreground hover:text-foreground hover:underline underline-offset-2 decoration-border"
+ style={{
+ left: ROW_COLUMN_WIDTH + virtualColumn.start,
+ width: VALUE_COLUMN_WIDTH
+ }}
+ onClick={(e) => {
+ e.stopPropagation();
+ onCellClick(
+ cellCoordinates(row, node.level, columnKey, false)
+ );
+ }}
+ >
+ {formatCell(row.cells[columnKey], percents?.[columnKey])}
+ </span>
+ );
+ })}
+
+ {/* Row total */}
+ <span
+ className="absolute top-0 flex h-full cursor-pointer items-center justify-end px-2 text-right font-medium tabular-nums text-muted-foreground hover:text-foreground hover:underline underline-offset-2 decoration-border"
+ style={{
+ left: ROW_COLUMN_WIDTH + totalColumnsWidth,
+ width: VALUE_COLUMN_WIDTH
+ }}
+ onClick={(e) => {
+ e.stopPropagation();
+ onCellClick(cellCoordinates(row, node.level, null, true));
+ }}
+ >
+ {formatRowTotal(row.total)}
+ </span>
+ </div>
+ );
+ }}
+ />
+ {/* Column totals footer — scrollLeft mirrored from the tree above */}
+ <div ref={footerRef} className="shrink-0 overflow-x-hidden">
+ <div
+ className="relative flex h-9 items-center border-t border-border bg-card text-sm font-semibold"
+ style={{ minWidth: rowWidth }}
+ >
+ <div
+ className="sticky left-0 z-[2] flex h-full shrink-0 items-center bg-card px-4"
+ style={{ width: ROW_COLUMN_WIDTH }}
+ >
+ <Trans>Total</Trans>
+ </div>
+ {virtualColumns.map((virtualColumn) => {
+ const columnKey = columnKeys[virtualColumn.index];
+ if (columnKey === undefined) return null;
+ return (
+ <span
+ key={columnKey}
+ className="absolute top-0 flex h-full items-center justify-end px-2 text-right tabular-nums"
+ style={{
+ left: ROW_COLUMN_WIDTH + virtualColumn.start,
+ width: VALUE_COLUMN_WIDTH
+ }}
+ >
+ {state.percentOfTotal
+ ? percentFormatter.format(
+ getPivotMeasureValue(
+ columnTotals[columnKey],
+ state.measure
+ ) === 0
+ ? 0
+ : 1
+ )
+ : formatMeasureValue(
+ getPivotMeasureValue(
+ columnTotals[columnKey],
+ state.measure
+ ),
+ state.measure
+ )}
+ </span>
+ );
+ })}
+ <span
+ className="absolute top-0 flex h-full items-center justify-end px-2 text-right tabular-nums"
+ style={{
+ left: ROW_COLUMN_WIDTH + totalColumnsWidth,
+ width: VALUE_COLUMN_WIDTH
+ }}
+ >
+ {state.percentOfTotal
+ ? percentFormatter.format(grandTotalValue === 0 ? 0 : 1)
+ : formatMeasureValue(grandTotalValue, state.measure)}
+ </span>
+ </div>
+ </div>
+ </div>
+ );
+ }
+);
+
+PivotTree.displayName = "PivotTree";
+export default PivotTree;
diff --git a/apps/erp/app/modules/accounting/ui/Reports/PurchaseLinesDrawer.tsx b/apps/erp/app/modules/accounting/ui/Reports/PurchaseLinesDrawer.tsx
new file mode 100644
index 0000000000..9cb7468d57
--- /dev/null
+++ b/apps/erp/app/modules/accounting/ui/Reports/PurchaseLinesDrawer.tsx
@@ -0,0 +1,178 @@
+import {
+ Drawer,
+ DrawerBody,
+ DrawerContent,
+ DrawerHeader,
+ DrawerTitle,
+ Spinner,
+ Table,
+ Tbody,
+ Td,
+ Tfoot,
+ Th,
+ Thead,
+ Tr
+} from "@carbon/react";
+import { formatDate } from "@carbon/utils";
+import { Trans, useLingui } from "@lingui/react/macro";
+import { useLocale } from "@react-aria/i18n";
+import { useMemo } from "react";
+import type { PurchaseLinePivotLine } from "../../types";
+
+// The drill-through RPC caps results at 500 lines; surface the cap when hit.
+const LINE_LIMIT = 500;
+
+type PurchaseLinesDrawerProps = {
+ open: boolean;
+ onClose: () => void;
+ title: string;
+ lines: PurchaseLinePivotLine[] | null;
+ isLoading: boolean;
+};
+
+function formatAmount(value: number): string {
+ return value.toLocaleString(undefined, {
+ minimumFractionDigits: 2,
+ maximumFractionDigits: 2
+ });
+}
+
+function formatQuantity(value: number): string {
+ return value.toLocaleString(undefined, { maximumFractionDigits: 2 });
+}
+
+/**
+ * Presentational drill-through drawer for one Purchases pivot cell — mirrors
+ * PivotLinesDrawer but with purchase-invoice columns (invoice / supplier /
+ * item) instead of the journal columns. The route owns the fetcher.
+ */
+const PurchaseLinesDrawer = ({
+ open,
+ onClose,
+ title,
+ lines,
+ isLoading
+}: PurchaseLinesDrawerProps) => {
+ const { t } = useLingui();
+ const { locale } = useLocale();
+
+ const totals = useMemo(
+ () =>
+ (lines ?? []).reduce(
+ (acc, line) => {
+ acc.amount += line.amount;
+ acc.quantity += line.quantity;
+ return acc;
+ },
+ { amount: 0, quantity: 0 }
+ ),
+ [lines]
+ );
+
+ return (
+ <Drawer
+ open={open}
+ onOpenChange={(isOpen) => {
+ if (!isOpen) onClose();
+ }}
+ >
+ <DrawerContent size="lg">
+ <DrawerHeader>
+ <DrawerTitle>{title}</DrawerTitle>
+ </DrawerHeader>
+ <DrawerBody className="p-0">
+ {isLoading ? (
+ <div className="flex w-full items-center justify-center py-16">
+ <Spinner size={24} />
+ </div>
+ ) : !lines || lines.length === 0 ? (
+ <div className="flex w-full items-center justify-center py-16 text-sm text-muted-foreground">
+ <Trans>No purchases in this period</Trans>
+ </div>
+ ) : (
+ <>
+ {lines.length === LINE_LIMIT && (
+ <div className="border-b border-border px-4 py-1.5 text-xs text-muted-foreground">
+ {t`Showing the first 500 lines`}
+ </div>
+ )}
+ <Table>
+ <Thead>
+ <Tr>
+ <Th className="px-4">
+ <Trans>Date</Trans>
+ </Th>
+ <Th className="px-4">
+ <Trans>Invoice</Trans>
+ </Th>
+ <Th className="px-4">
+ <Trans>Supplier</Trans>
+ </Th>
+ <Th className="px-4">
+ <Trans>Item</Trans>
+ </Th>
+ <Th className="px-4 w-full">
+ <Trans>Description</Trans>
+ </Th>
+ <Th className="px-4 text-right">
+ <Trans>Amount</Trans>
+ </Th>
+ <Th className="px-4 text-right">
+ <Trans>Quantity</Trans>
+ </Th>
+ </Tr>
+ </Thead>
+ <Tbody>
+ {lines.map((line) => (
+ <Tr key={line.id} className="hover:bg-muted/50">
+ <Td className="px-4 whitespace-nowrap text-muted-foreground">
+ {formatDate(line.postingDate, undefined, locale)}
+ </Td>
+ <Td className="px-4 whitespace-nowrap font-mono text-xs">
+ {line.invoiceReadableId}
+ </Td>
+ <Td className="px-4 whitespace-nowrap">
+ <span className="line-clamp-1">
+ {line.supplierName || "–"}
+ </span>
+ </Td>
+ <Td className="px-4 whitespace-nowrap font-mono text-xs">
+ {line.itemReadableId || "–"}
+ </Td>
+ <Td className="px-4">
+ <p className="line-clamp-1">
+ {line.description || "–"}
+ </p>
+ </Td>
+ <Td className="px-4 text-right tabular-nums">
+ {formatAmount(line.amount)}
+ </Td>
+ <Td className="px-4 text-right tabular-nums">
+ {formatQuantity(line.quantity)}
+ </Td>
+ </Tr>
+ ))}
+ </Tbody>
+ <Tfoot>
+ <Tr className="font-medium">
+ <Td className="px-4" colSpan={5}>
+ <Trans>Total</Trans>
+ </Td>
+ <Td className="px-4 text-right tabular-nums">
+ {formatAmount(totals.amount)}
+ </Td>
+ <Td className="px-4 text-right tabular-nums">
+ {formatQuantity(totals.quantity)}
+ </Td>
+ </Tr>
+ </Tfoot>
+ </Table>
+ </>
+ )}
+ </DrawerBody>
+ </DrawerContent>
+ </Drawer>
+ );
+};
+
+export default PurchaseLinesDrawer;
diff --git a/apps/erp/app/modules/accounting/ui/Reports/PurchasesControlBar.tsx b/apps/erp/app/modules/accounting/ui/Reports/PurchasesControlBar.tsx
new file mode 100644
index 0000000000..e830a6e781
--- /dev/null
+++ b/apps/erp/app/modules/accounting/ui/Reports/PurchasesControlBar.tsx
@@ -0,0 +1,330 @@
+import {
+ Button,
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuIcon,
+ DropdownMenuRadioGroup,
+ DropdownMenuRadioItem,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+ HStack,
+ Switch
+} from "@carbon/react";
+import { Trans, useLingui } from "@lingui/react/macro";
+import { useMemo } from "react";
+import {
+ LuColumns3,
+ LuCornerDownRight,
+ LuDownload,
+ LuRows3,
+ LuSigma,
+ LuX
+} from "react-icons/lu";
+import { PeriodSelector } from "~/components";
+import { DimensionEntityTypeIcon } from "~/components/Icons";
+import { useUrlParams } from "~/hooks";
+import type { PivotMeasure, PivotState } from "../../accounting.models";
+import {
+ financialReportColumns,
+ pivotMeasures,
+ purchaseGroupingFields
+} from "../../accounting.models";
+
+type PurchasesControlBarProps = {
+ state: PivotState;
+ onDownload: () => void;
+};
+
+const PurchasesControlBar = ({
+ state,
+ onDownload
+}: PurchasesControlBarProps) => {
+ const { t } = useLingui();
+ const [params, setParams] = useUrlParams();
+
+ // Grouping fields (purchase invoice line / header columns), with a label and
+ // the entityType used for the row/column icons.
+ const fieldOptions: {
+ field: string;
+ label: string;
+ entityType: string;
+ }[] = useMemo(() => {
+ const labels: Record<(typeof purchaseGroupingFields)[number], string> = {
+ supplier: t`Supplier`,
+ supplierType: t`Supplier Type`,
+ item: t`Item`,
+ itemPostingGroup: t`Item Group`,
+ costCenter: t`Cost Center`
+ };
+ const entityTypes: Record<(typeof purchaseGroupingFields)[number], string> =
+ {
+ supplier: "Supplier",
+ supplierType: "SupplierType",
+ item: "Item",
+ itemPostingGroup: "ItemPostingGroup",
+ costCenter: "CostCenter"
+ };
+ return purchaseGroupingFields.map((field) => ({
+ field,
+ label: labels[field],
+ entityType: entityTypes[field]
+ }));
+ }, [t]);
+
+ const fieldById = useMemo(
+ () => new Map(fieldOptions.map((o) => [o.field, o])),
+ [fieldOptions]
+ );
+
+ const columnLabels: Record<(typeof financialReportColumns)[number], string> =
+ {
+ month: t`Monthly`,
+ quarter: t`Quarterly`,
+ year: t`Yearly`
+ };
+
+ const measureLabels: Record<PivotMeasure, string> = {
+ amount: t`Amount`,
+ quantity: t`Quantity`,
+ count: t`Count`
+ };
+
+ // -- Rows --
+ const row1 = state.rows[0];
+ const row2 = state.rows[1];
+
+ const setRows = (rows: string[]) => {
+ setParams({ rows: rows.length > 0 ? rows.join(",") : undefined });
+ };
+
+ const onRow1Change = (field: string) => {
+ if (!field) {
+ setRows(row2 ? [row2] : []);
+ return;
+ }
+ setRows([field, ...(row2 && row2 !== field ? [row2] : [])]);
+ };
+
+ const onRow2Change = (field: string) => {
+ if (!row1) return;
+ setRows(field ? [row1, field] : [row1]);
+ };
+
+ // -- Columns --
+ const columnAxisValue =
+ state.columnAxis.type === "period" ? state.columnAxis.bucket : "dimension";
+
+ const columnFieldId =
+ state.columnAxis.type === "dimension"
+ ? state.columnAxis.dimensionId
+ : undefined;
+
+ const columnCandidates = fieldOptions.filter(
+ (o) => !state.rows.includes(o.field)
+ );
+
+ const columnLabel =
+ state.columnAxis.type === "period"
+ ? columnLabels[state.columnAxis.bucket]
+ : (fieldById.get(state.columnAxis.dimensionId)?.label ?? t`By field`);
+
+ const onColumnAxisChange = (value: string) => {
+ if (value === "dimension") {
+ const fallback = columnCandidates[0];
+ if (!fallback) return;
+ setParams({ col: `dim:${fallback.field}` });
+ return;
+ }
+ setParams({ col: value === "month" ? undefined : `period:${value}` });
+ };
+
+ const onReset = () => {
+ setParams({
+ rows: undefined,
+ col: undefined,
+ measure: undefined,
+ pct: undefined,
+ startDate: undefined,
+ endDate: undefined
+ });
+ };
+
+ return (
+ <div className="flex flex-wrap px-4 py-3 items-center gap-2 justify-between bg-card border-b border-border w-full">
+ <HStack className="flex-wrap gap-y-2">
+ <PeriodSelector variant="range" />
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button variant="secondary" leftIcon={<LuRows3 />}>
+ {row1 ? (fieldById.get(row1)?.label ?? row1) : t`Group by`}
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="start">
+ <DropdownMenuRadioGroup
+ value={row1 ?? ""}
+ onValueChange={onRow1Change}
+ >
+ <DropdownMenuRadioItem value="">
+ <Trans>None</Trans>
+ </DropdownMenuRadioItem>
+ {fieldOptions.map((option) => (
+ <DropdownMenuRadioItem key={option.field} value={option.field}>
+ <DropdownMenuIcon
+ icon={
+ <DimensionEntityTypeIcon
+ entityType={option.entityType as any}
+ />
+ }
+ />
+ {option.label}
+ </DropdownMenuRadioItem>
+ ))}
+ </DropdownMenuRadioGroup>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button
+ variant="secondary"
+ leftIcon={<LuCornerDownRight />}
+ isDisabled={!row1}
+ >
+ {row2 ? (fieldById.get(row2)?.label ?? row2) : t`Then by`}
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="start">
+ <DropdownMenuRadioGroup
+ value={row2 ?? ""}
+ onValueChange={onRow2Change}
+ >
+ <DropdownMenuRadioItem value="">
+ <Trans>None</Trans>
+ </DropdownMenuRadioItem>
+ {fieldOptions
+ .filter((option) => option.field !== row1)
+ .map((option) => (
+ <DropdownMenuRadioItem
+ key={option.field}
+ value={option.field}
+ >
+ <DropdownMenuIcon
+ icon={
+ <DimensionEntityTypeIcon
+ entityType={option.entityType as any}
+ />
+ }
+ />
+ {option.label}
+ </DropdownMenuRadioItem>
+ ))}
+ </DropdownMenuRadioGroup>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button variant="secondary" leftIcon={<LuColumns3 />}>
+ {columnLabel}
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="start">
+ <DropdownMenuRadioGroup
+ value={columnAxisValue}
+ onValueChange={onColumnAxisChange}
+ >
+ {financialReportColumns.map((granularity) => (
+ <DropdownMenuRadioItem key={granularity} value={granularity}>
+ {columnLabels[granularity]}
+ </DropdownMenuRadioItem>
+ ))}
+ <DropdownMenuSeparator />
+ <DropdownMenuRadioItem
+ value="dimension"
+ disabled={columnCandidates.length === 0}
+ >
+ <Trans>By field</Trans>
+ </DropdownMenuRadioItem>
+ </DropdownMenuRadioGroup>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ {state.columnAxis.type === "dimension" && (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button variant="secondary">
+ {columnFieldId
+ ? (fieldById.get(columnFieldId)?.label ?? columnFieldId)
+ : t`Column field`}
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="start">
+ <DropdownMenuRadioGroup
+ value={columnFieldId ?? ""}
+ onValueChange={(value) => {
+ if (value) setParams({ col: `dim:${value}` });
+ }}
+ >
+ {columnCandidates.map((option) => (
+ <DropdownMenuRadioItem
+ key={option.field}
+ value={option.field}
+ >
+ <DropdownMenuIcon
+ icon={
+ <DimensionEntityTypeIcon
+ entityType={option.entityType as any}
+ />
+ }
+ />
+ {option.label}
+ </DropdownMenuRadioItem>
+ ))}
+ </DropdownMenuRadioGroup>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ )}
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button variant="secondary" leftIcon={<LuSigma />}>
+ {measureLabels[state.measure]}
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="start">
+ <DropdownMenuRadioGroup
+ value={state.measure}
+ onValueChange={(value) =>
+ setParams({ measure: value === "amount" ? undefined : value })
+ }
+ >
+ {pivotMeasures.map((measure) => (
+ <DropdownMenuRadioItem key={measure} value={measure}>
+ {measureLabels[measure]}
+ </DropdownMenuRadioItem>
+ ))}
+ </DropdownMenuRadioGroup>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ <Switch
+ variant="small"
+ checked={state.percentOfTotal}
+ onCheckedChange={(checked) =>
+ setParams({ pct: checked ? "1" : undefined })
+ }
+ label={t`% of total`}
+ />
+ {[...params.entries()].length > 0 && (
+ <Button variant="secondary" rightIcon={<LuX />} onClick={onReset}>
+ {t`Reset`}
+ </Button>
+ )}
+ </HStack>
+ <Button
+ variant="secondary"
+ leftIcon={<LuDownload />}
+ onClick={onDownload}
+ >
+ {t`Download`}
+ </Button>
+ </div>
+ );
+};
+
+export default PurchasesControlBar;
diff --git a/apps/erp/app/modules/accounting/ui/Reports/ReportFilters.tsx b/apps/erp/app/modules/accounting/ui/Reports/ReportFilters.tsx
index 8fd660383a..4f4dbcbc80 100644
--- a/apps/erp/app/modules/accounting/ui/Reports/ReportFilters.tsx
+++ b/apps/erp/app/modules/accounting/ui/Reports/ReportFilters.tsx
@@ -1,14 +1,27 @@
import {
Button,
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuRadioGroup,
+ DropdownMenuRadioItem,
+ DropdownMenuTrigger,
HStack,
Input,
InputGroup,
InputLeftElement
} from "@carbon/react";
+import type { ReportColumnGranularity } from "@carbon/utils";
import { useLingui } from "@lingui/react/macro";
-import { LuLanguages, LuSearch, LuX } from "react-icons/lu";
+import {
+ LuColumns3,
+ LuDownload,
+ LuLanguages,
+ LuSearch,
+ LuX
+} from "react-icons/lu";
import { PeriodSelector } from "~/components";
import { useUrlParams } from "~/hooks";
+import { financialReportColumns } from "../../accounting.models";
import CompanySelector from "./CompanySelector";
type Company = {
@@ -24,8 +37,17 @@ type ReportFiltersProps = {
parentCurrency?: string | null;
periodVariant?: "range" | "asOf";
fiscalStartMonth?: number;
- search: string;
- onSearchChange: (value: string) => void;
+ /** Preset shown as active in the period selector when no date params are set */
+ defaultPeriodId?: string;
+ /** Renders the Columns granularity select (BS & IS only) */
+ showColumns?: boolean;
+ /** Renders the account search box (hidden for fixed summary reports) */
+ showSearch?: boolean;
+ /** Renders a Download (CSV) button on the right */
+ onDownload?: () => void;
+ /** Omitted for fixed summary reports that render no search box */
+ search?: string;
+ onSearchChange?: (value: string) => void;
};
const ReportFilters = ({
@@ -36,27 +58,45 @@ const ReportFilters = ({
parentCurrency,
periodVariant = "range",
fiscalStartMonth,
- search,
+ defaultPeriodId,
+ showColumns = false,
+ showSearch = true,
+ onDownload,
+ search = "",
onSearchChange
}: ReportFiltersProps) => {
const { t } = useLingui();
const [params, setParams] = useUrlParams();
const showTranslated = params.get("showTranslated") === "true";
+ const columnsParam = params.get("columns");
+ const columns: ReportColumnGranularity = financialReportColumns.includes(
+ columnsParam as ReportColumnGranularity
+ )
+ ? (columnsParam as ReportColumnGranularity)
+ : "month";
+
+ const columnLabels: Record<ReportColumnGranularity, string> = {
+ month: t`Monthly`,
+ quarter: t`Quarterly`,
+ year: t`Yearly`
+ };
return (
<div className="flex px-4 py-3 items-center space-x-4 justify-between bg-card border-b border-border w-full">
<HStack>
- <InputGroup size="sm" className="w-64">
- <InputLeftElement>
- <LuSearch className="h-4 w-4 text-muted-foreground" />
- </InputLeftElement>
- <Input
- placeholder={t`Search accounts...`}
- value={search}
- onChange={(e) => onSearchChange(e.target.value)}
- />
- </InputGroup>
+ {showSearch && (
+ <InputGroup size="sm" className="w-64">
+ <InputLeftElement>
+ <LuSearch className="h-4 w-4 text-muted-foreground" />
+ </InputLeftElement>
+ <Input
+ placeholder={t`Search accounts...`}
+ value={search}
+ onChange={(e) => onSearchChange?.(e.target.value)}
+ />
+ </InputGroup>
+ )}
<CompanySelector
companies={companies}
selectedCompanyIds={selectedCompanyIds}
@@ -64,7 +104,33 @@ const ReportFilters = ({
<PeriodSelector
variant={periodVariant}
fiscalStartMonth={fiscalStartMonth}
+ defaultPresetId={defaultPeriodId}
/>
+ {showColumns && (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button variant="secondary" leftIcon={<LuColumns3 />}>
+ {columnLabels[columns]}
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="start">
+ <DropdownMenuRadioGroup
+ value={columns}
+ onValueChange={(value) =>
+ setParams({
+ columns: value === "month" ? undefined : value
+ })
+ }
+ >
+ {financialReportColumns.map((granularity) => (
+ <DropdownMenuRadioItem key={granularity} value={granularity}>
+ {columnLabels[granularity]}
+ </DropdownMenuRadioItem>
+ ))}
+ </DropdownMenuRadioGroup>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ )}
{!isMultiCompany && isForeignCurrency && parentCurrency && (
<Button
variant={showTranslated ? "primary" : "secondary"}
@@ -92,6 +158,7 @@ const ReportFilters = ({
companies: undefined,
startDate: undefined,
endDate: undefined,
+ columns: undefined,
showTranslated: undefined
})
}
@@ -100,6 +167,15 @@ const ReportFilters = ({
</Button>
)}
</HStack>
+ {onDownload && (
+ <Button
+ variant="secondary"
+ leftIcon={<LuDownload />}
+ onClick={onDownload}
+ >
+ {t`Download`}
+ </Button>
+ )}
</div>
);
};
diff --git a/apps/erp/app/modules/accounting/ui/Reports/SaveViewModal.tsx b/apps/erp/app/modules/accounting/ui/Reports/SaveViewModal.tsx
new file mode 100644
index 0000000000..f7d896c77d
--- /dev/null
+++ b/apps/erp/app/modules/accounting/ui/Reports/SaveViewModal.tsx
@@ -0,0 +1,140 @@
+import { ValidatedForm } from "@carbon/form";
+import {
+ Button,
+ HStack,
+ Modal,
+ ModalBody,
+ ModalContent,
+ ModalFooter,
+ ModalHeader,
+ ModalTitle,
+ VStack
+} from "@carbon/react";
+import { Trans, useLingui } from "@lingui/react/macro";
+import { useEffect } from "react";
+import { useFetcher } from "react-router";
+import { Hidden, Input, Select, Submit } from "~/components/Form";
+import { useUser } from "~/hooks";
+import type { AnalyticsReportKey, PivotState } from "../../accounting.models";
+import {
+ reportViewValidator,
+ reportViewVisibilities
+} from "../../accounting.models";
+import type { ReportView } from "../../types";
+
+type SaveViewModalProps = {
+ reportKey: AnalyticsReportKey;
+ /** The current pivot state — saved as the view's config */
+ state: PivotState;
+ /** The active saved view, if any. Editable only when owned by the current user. */
+ view?: ReportView;
+ onClose: () => void;
+};
+
+const SaveViewModal = ({
+ reportKey,
+ state,
+ view,
+ onClose
+}: SaveViewModalProps) => {
+ const { t } = useLingui();
+ const { id: userId } = useUser();
+ const fetcher = useFetcher<{ fieldErrors?: Record<string, string> }>();
+
+ // Only the owner edits (RLS enforces this server-side too); a shared view
+ // someone else created is saved as a new view instead.
+ const isEditing = !!view && view.createdBy === userId;
+
+ useEffect(() => {
+ if (
+ fetcher.state === "loading" &&
+ fetcher.data != null &&
+ !fetcher.data.fieldErrors
+ ) {
+ onClose();
+ }
+ }, [fetcher.state, fetcher.data, onClose]);
+
+ const visibilityOptions = reportViewVisibilities.map((visibility) => ({
+ value: visibility,
+ label: visibility === "Private" ? t`Private` : t`Company`
+ }));
+
+ const onDelete = () => {
+ if (!isEditing || !view) return;
+ fetcher.submit({ intent: "delete-view", id: view.id }, { method: "post" });
+ };
+
+ return (
+ <Modal
+ open
+ onOpenChange={(open) => {
+ if (!open) onClose();
+ }}
+ >
+ <ModalContent>
+ <ValidatedForm
+ validator={reportViewValidator}
+ method="post"
+ defaultValues={{
+ id: isEditing ? view.id : undefined,
+ reportKey,
+ name: isEditing ? view.name : "",
+ visibility: isEditing ? view.visibility : "Private",
+ config: JSON.stringify(state)
+ }}
+ fetcher={fetcher}
+ className="flex flex-col h-full"
+ >
+ <ModalHeader>
+ <ModalTitle>
+ {isEditing ? <Trans>Edit View</Trans> : <Trans>Save View</Trans>}
+ </ModalTitle>
+ </ModalHeader>
+ <ModalBody>
+ {isEditing && <Hidden name="id" />}
+ <Hidden name="intent" value="save-view" />
+ <Hidden name="reportKey" value={reportKey} />
+ <Hidden name="config" value={JSON.stringify(state)} />
+ <VStack spacing={4}>
+ <Input name="name" label={t`Name`} />
+ <Select
+ name="visibility"
+ label={t`Visibility`}
+ options={visibilityOptions}
+ />
+ </VStack>
+ </ModalBody>
+ <ModalFooter>
+ <HStack className="w-full justify-between">
+ <div>
+ {isEditing && (
+ <Button
+ variant="destructive"
+ isLoading={
+ fetcher.state !== "idle" &&
+ fetcher.formData?.get("intent") === "delete-view"
+ }
+ onClick={onDelete}
+ >
+ <Trans>Delete</Trans>
+ </Button>
+ )}
+ </div>
+ <HStack>
+ <Submit>
+ <Trans>Save</Trans>
+ </Submit>
+ <Button size="md" variant="solid" onClick={() => onClose()}>
+ <Trans>Cancel</Trans>
+ </Button>
+ </HStack>
+ </HStack>
+ </ModalFooter>
+ </ValidatedForm>
+ </ModalContent>
+ </Modal>
+ );
+};
+
+export default SaveViewModal;
diff --git a/apps/erp/app/modules/accounting/ui/Reports/TrialBalanceTree.tsx b/apps/erp/app/modules/accounting/ui/Reports/TrialBalanceTree.tsx
index 10f3bb470b..e81506dbf6 100644
--- a/apps/erp/app/modules/accounting/ui/Reports/TrialBalanceTree.tsx
+++ b/apps/erp/app/modules/accounting/ui/Reports/TrialBalanceTree.tsx
@@ -8,10 +8,14 @@ import {
LuFolderOpen
} from "react-icons/lu";
import { useNavigate } from "react-router";
-import type { FlatTree, FlatTreeItem } from "~/components/TreeView";
import { LevelLine, TreeView, useTree } from "~/components/TreeView";
import { useRealtime, useUrlParams } from "~/hooks";
import type { Chart } from "../../types";
+import {
+ accountsToFlatTree,
+ filterAccounts,
+ getDebitCredit
+} from "./reportTree";
type TrialBalanceChart = Chart & {
translatedBalance?: number;
@@ -27,73 +31,6 @@ type TrialBalanceTreeProps = {
ledgerPath?: (accountId: string) => string;
};
-function accountsToFlatTree(
- accounts: TrialBalanceChart[]
-): FlatTree<TrialBalanceChart> {
- const byParent = new Map<string, TrialBalanceChart[]>();
- for (const a of accounts) {
- const key = a.parentId ?? "__root__";
- if (!byParent.has(key)) byParent.set(key, []);
- byParent.get(key)!.push(a);
- }
-
- const result: FlatTreeItem<TrialBalanceChart>[] = [];
-
- function walk(parentId: string | null, level: number) {
- const children = (byParent.get(parentId ?? "__root__") ?? []).sort(
- (a, b) => {
- const aIsGroup = a.isGroup ? 1 : 0;
- const bIsGroup = b.isGroup ? 1 : 0;
- if (aIsGroup !== bIsGroup) return aIsGroup - bIsGroup;
- return (a.name ?? "").localeCompare(b.name ?? "");
- }
- );
- for (const account of children) {
- const childAccounts = byParent.get(account.id) ?? [];
- const childIds = childAccounts.map((c) => c.id);
- result.push({
- id: account.id,
- parentId: parentId ?? undefined,
- children: childIds,
- hasChildren: childIds.length > 0,
- level,
- data: account
- });
- walk(account.id, level + 1);
- }
- }
-
- walk(null, 0);
- return result;
-}
-
-function filterAccounts(
- accounts: TrialBalanceChart[],
- search: string
-): TrialBalanceChart[] {
- if (!search.trim()) return accounts;
- const lower = search.toLowerCase();
-
- const byId = new Map(accounts.map((a) => [a.id, a]));
- const matched = new Set<string>();
-
- for (const a of accounts) {
- const nameMatch = a.name?.toLowerCase().includes(lower);
- const numberMatch = a.number?.toLowerCase().includes(lower);
- if (nameMatch || numberMatch) {
- matched.add(a.id as string);
- let parentId = a.parentId;
- while (parentId) {
- matched.add(parentId);
- const parent = byId.get(parentId);
- parentId = parent?.parentId ?? null;
- }
- }
- }
-
- return accounts.filter((a) => matched.has(a.id as string));
-}
-
function formatCurrency(value: number): string {
if (value === 0) return "-";
return value.toLocaleString(undefined, {
@@ -110,33 +47,6 @@ function formatPercent(value: number): string {
})}%`;
}
-/** Normal-debit accounts: positive balance = debit */
-function isNormalDebit(accountClass: string | null | undefined): boolean {
- return accountClass === "Asset" || accountClass === "Expense";
-}
-
-/**
- * Split net change into debit and credit based on account class.
- * Normal-debit accounts (Asset, Expense): positive netChange = debit
- * Normal-credit accounts (Liability, Equity, Revenue): positive netChange = credit
- */
-function getDebitCredit(
- netChange: number,
- accountClass: string | null | undefined
-): { debit: number; credit: number } {
- if (netChange === 0) return { debit: 0, credit: 0 };
-
- if (isNormalDebit(accountClass)) {
- return netChange > 0
- ? { debit: netChange, credit: 0 }
- : { debit: 0, credit: Math.abs(netChange) };
- }
- // Normal credit accounts
- return netChange > 0
- ? { debit: 0, credit: netChange }
- : { debit: Math.abs(netChange), credit: 0 };
-}
-
const TrialBalanceTree = memo(
({
data,
diff --git a/apps/erp/app/modules/accounting/ui/Reports/executivePnl.test.ts b/apps/erp/app/modules/accounting/ui/Reports/executivePnl.test.ts
new file mode 100644
index 0000000000..6d1f9646ca
--- /dev/null
+++ b/apps/erp/app/modules/accounting/ui/Reports/executivePnl.test.ts
@@ -0,0 +1,255 @@
+import { describe, expect, it } from "vitest";
+import type { ChartPeriodSeries } from "../../types";
+import { computeExecutivePnl, type ExecutivePnlRowKey } from "./executivePnl";
+
+// Minimal leaf-account factory — only the fields computeExecutivePnl reads.
+function leaf(
+ partial: Partial<ChartPeriodSeries> & {
+ accountType: ChartPeriodSeries["accountType"];
+ class: ChartPeriodSeries["class"];
+ periods: ChartPeriodSeries["periods"];
+ }
+): ChartPeriodSeries {
+ return {
+ id: partial.id ?? Math.random().toString(36).slice(2),
+ isGroup: false,
+ ...partial
+ } as ChartPeriodSeries;
+}
+
+const BUCKETS = ["2026-01"];
+
+function valuesByKey(accounts: ChartPeriodSeries[]) {
+ const rows = computeExecutivePnl(accounts, BUCKETS);
+ const map = {} as Record<ExecutivePnlRowKey, number>;
+ for (const row of rows) map[row.key] = row.values["2026-01"]!;
+ return { rows, map };
+}
+
+describe("computeExecutivePnl", () => {
+ it("rolls leaves into categories and derives the subtotals", () => {
+ const accounts = [
+ leaf({
+ accountType: "Income",
+ class: "Revenue",
+ periods: { "2026-01": { netChange: 1000, balanceAtDate: 1000 } }
+ }),
+ leaf({
+ accountType: "Cost of Goods Sold",
+ class: "Expense",
+ periods: { "2026-01": { netChange: 400, balanceAtDate: 400 } }
+ }),
+ leaf({
+ accountType: "Expense",
+ class: "Expense",
+ periods: { "2026-01": { netChange: 200, balanceAtDate: 200 } }
+ }),
+ leaf({
+ accountType: "Other Income",
+ class: "Revenue",
+ periods: { "2026-01": { netChange: 50, balanceAtDate: 50 } }
+ }),
+ leaf({
+ accountType: "Other Expense",
+ class: "Expense",
+ periods: { "2026-01": { netChange: 30, balanceAtDate: 30 } }
+ }),
+ leaf({
+ accountType: "Tax",
+ class: "Expense",
+ periods: { "2026-01": { netChange: 100, balanceAtDate: 100 } }
+ })
+ ];
+
+ const { map } = valuesByKey(accounts);
+
+ expect(map.revenue).toBe(1000);
+ expect(map.cogs).toBe(400);
+ expect(map.grossProfit).toBe(600); // 1000 − 400
+ expect(map.operatingExpenses).toBe(200);
+ expect(map.operatingIncome).toBe(400); // 600 − 200
+ expect(map.otherIncome).toBe(50);
+ expect(map.otherExpense).toBe(30);
+ expect(map.tax).toBe(100);
+ expect(map.netIncome).toBe(320); // 400 + 50 − 30 − 100
+ });
+
+ it("translated: uses the translated period delta, not the cumulative balance", () => {
+ // balanceAtDate is fiscal-YTD cumulative and differs from the period's
+ // netChange; translatedBalance (cumulative × rate) must NOT leak into the P&L.
+ const accounts = [
+ leaf({
+ accountType: "Income",
+ class: "Revenue",
+ periods: {
+ "2026-01": {
+ netChange: 1000,
+ balanceAtDate: 3000,
+ translatedNetChange: 1500, // 1000 × 1.5
+ translatedBalance: 4500 // 3000 × 1.5
+ }
+ }
+ }),
+ leaf({
+ accountType: "Cost of Goods Sold",
+ class: "Expense",
+ periods: {
+ "2026-01": {
+ netChange: 400,
+ balanceAtDate: 1200,
+ translatedNetChange: 600, // 400 × 1.5
+ translatedBalance: 1800
+ }
+ }
+ })
+ ];
+
+ const rows = computeExecutivePnl(accounts, BUCKETS, {
+ showTranslated: true
+ });
+ const map = {} as Record<ExecutivePnlRowKey, number>;
+ for (const row of rows) map[row.key] = row.values["2026-01"]!;
+
+ expect(map.revenue).toBe(1500); // translatedNetChange, not 4500 (balance)
+ expect(map.cogs).toBe(600);
+ expect(map.grossProfit).toBe(900); // 1500 − 600
+ });
+
+ it("translated: falls back to untranslated netChange when no translated delta", () => {
+ const accounts = [
+ leaf({
+ accountType: "Income",
+ class: "Revenue",
+ // showTranslated requested but the cell carries no translatedNetChange.
+ periods: { "2026-01": { netChange: 800, balanceAtDate: 2400 } }
+ })
+ ];
+
+ const rows = computeExecutivePnl(accounts, BUCKETS, {
+ showTranslated: true
+ });
+ expect(rows.find((r) => r.key === "revenue")?.values["2026-01"]).toBe(800);
+ });
+
+ it("ties Net Income out to the class-based root (rootSignMultiplier)", () => {
+ const accounts = [
+ leaf({
+ accountType: "Income",
+ class: "Revenue",
+ periods: { "2026-01": { netChange: 1200, balanceAtDate: 1200 } }
+ }),
+ leaf({
+ accountType: "Cost of Goods Sold",
+ class: "Expense",
+ periods: { "2026-01": { netChange: 500, balanceAtDate: 500 } }
+ }),
+ leaf({
+ accountType: "Expense",
+ class: "Expense",
+ periods: { "2026-01": { netChange: 150, balanceAtDate: 150 } }
+ }),
+ leaf({
+ accountType: "Other Income",
+ class: "Revenue",
+ periods: { "2026-01": { netChange: 75, balanceAtDate: 75 } }
+ }),
+ leaf({
+ accountType: "Tax",
+ class: "Expense",
+ periods: { "2026-01": { netChange: 60, balanceAtDate: 60 } }
+ })
+ ];
+
+ const { map } = valuesByKey(accounts);
+
+ // rootSignMultiplier: Revenue +1, Expense −1
+ const rootNet = 1200 + 75 - (500 + 150 + 60); // = 565
+ expect(map.netIncome).toBe(rootNet);
+ });
+
+ it("folds uncategorized income-statement leaves into a bucket by class", () => {
+ const accounts = [
+ leaf({
+ accountType: "Income",
+ class: "Revenue",
+ periods: { "2026-01": { netChange: 800, balanceAtDate: 800 } }
+ }),
+ // An income-statement expense leaf with no P&L-specific accountType.
+ leaf({
+ accountType: null,
+ class: "Expense",
+ periods: { "2026-01": { netChange: 90, balanceAtDate: 90 } }
+ }),
+ // A revenue-class leaf with no P&L-specific accountType.
+ leaf({
+ accountType: null,
+ class: "Revenue",
+ periods: { "2026-01": { netChange: 40, balanceAtDate: 40 } }
+ })
+ ];
+
+ const { map } = valuesByKey(accounts);
+
+ expect(map.revenue).toBe(840); // 800 + 40 (class fallback)
+ expect(map.operatingExpenses).toBe(90); // class fallback
+ expect(map.netIncome).toBe(750); // 840 − 90
+ });
+
+ it("skips group rows and the synthetic Net Income line", () => {
+ const accounts = [
+ leaf({
+ id: "grp",
+ isGroup: true,
+ accountType: "Income",
+ class: "Revenue",
+ periods: { "2026-01": { netChange: 9999, balanceAtDate: 9999 } }
+ }),
+ leaf({
+ id: "net-income",
+ accountType: null,
+ class: "Equity",
+ periods: { "2026-01": { netChange: 5555, balanceAtDate: 5555 } }
+ }),
+ leaf({
+ accountType: "Income",
+ class: "Revenue",
+ periods: { "2026-01": { netChange: 100, balanceAtDate: 100 } }
+ })
+ ];
+
+ const { map } = valuesByKey(accounts);
+ expect(map.revenue).toBe(100);
+ });
+
+ it("marks margins null when revenue is zero", () => {
+ const accounts = [
+ leaf({
+ accountType: "Expense",
+ class: "Expense",
+ periods: { "2026-01": { netChange: 200, balanceAtDate: 200 } }
+ })
+ ];
+ const rows = computeExecutivePnl(accounts, BUCKETS);
+ const netIncome = rows.find((r) => r.key === "netIncome")!;
+ expect(netIncome.margins?.["2026-01"]).toBeNull();
+ expect(netIncome.values["2026-01"]).toBe(-200);
+ });
+
+ it("computes margins as a fraction of revenue", () => {
+ const accounts = [
+ leaf({
+ accountType: "Income",
+ class: "Revenue",
+ periods: { "2026-01": { netChange: 1000, balanceAtDate: 1000 } }
+ }),
+ leaf({
+ accountType: "Cost of Goods Sold",
+ class: "Expense",
+ periods: { "2026-01": { netChange: 250, balanceAtDate: 250 } }
+ })
+ ];
+ const rows = computeExecutivePnl(accounts, BUCKETS);
+ const grossProfit = rows.find((r) => r.key === "grossProfit")!;
+ expect(grossProfit.margins?.["2026-01"]).toBeCloseTo(0.75); // 750 / 1000
+ });
+});
diff --git a/apps/erp/app/modules/accounting/ui/Reports/executivePnl.ts b/apps/erp/app/modules/accounting/ui/Reports/executivePnl.ts
new file mode 100644
index 0000000000..32cde02a62
--- /dev/null
+++ b/apps/erp/app/modules/accounting/ui/Reports/executivePnl.ts
@@ -0,0 +1,197 @@
+import type { ChartPeriodSeries, PeriodCell } from "../../types";
+import { NET_INCOME_ACCOUNT_ID } from "../../types";
+
+// The condensed lines an executive P&L rolls the income-statement account tree
+// up into. Base categories are summed directly from leaf accounts; the three
+// subtotals are derived from them.
+export type ExecutivePnlRowKey =
+ | "revenue"
+ | "cogs"
+ | "grossProfit"
+ | "operatingExpenses"
+ | "operatingIncome"
+ | "otherIncome"
+ | "otherExpense"
+ | "tax"
+ | "netIncome";
+
+export type ExecutivePnlRow = {
+ key: ExecutivePnlRowKey;
+ /** Subtotals (Gross Profit / Operating Income / Net Income) render emphasized. */
+ isSubtotal: boolean;
+ /** Net Income is the bottom line — rendered with the strongest emphasis. */
+ isBottomLine: boolean;
+ /** Amount per bucket, keyed by ReportPeriodBucket.key. */
+ values: Record<string, number>;
+ /**
+ * Margin as a fraction of revenue per bucket (subtotals only; `null` when
+ * revenue is zero so the UI can hide it). Undefined for non-subtotal rows.
+ */
+ margins?: Record<string, number | null>;
+};
+
+type BaseCategory =
+ | "revenue"
+ | "cogs"
+ | "operatingExpenses"
+ | "otherIncome"
+ | "otherExpense"
+ | "tax";
+
+// Map a leaf income-statement account to one of the executive P&L buckets.
+// Primary split is by accountType; the class-based fallback guarantees every
+// leaf lands somewhere so Net Income ties out to the income-statement root.
+function categoryOf(account: ChartPeriodSeries): BaseCategory | null {
+ if (account.isGroup) return null;
+ if (account.id === NET_INCOME_ACCOUNT_ID) return null;
+
+ switch (account.accountType) {
+ case "Income":
+ return "revenue";
+ case "Other Income":
+ return "otherIncome";
+ case "Cost of Goods Sold":
+ return "cogs";
+ case "Expense":
+ return "operatingExpenses";
+ case "Other Expense":
+ return "otherExpense";
+ case "Tax":
+ return "tax";
+ default:
+ // Uncategorized income-statement leaf — fold into the closest bucket by
+ // class rather than drop it (keeps the bottom line correct).
+ if (account.class === "Revenue") return "revenue";
+ if (account.class === "Expense") return "operatingExpenses";
+ return null;
+ }
+}
+
+function cellValue(
+ cell: PeriodCell | undefined,
+ showTranslated: boolean
+): number {
+ if (!cell) return 0;
+ // Income-statement lines are period activity, so the translated value must be
+ // the translated netChange (period delta), NOT translatedBalance (the
+ // translated cumulative balance). Fall back to the untranslated netChange.
+ if (showTranslated && typeof cell.translatedNetChange === "number") {
+ return cell.translatedNetChange;
+ }
+ return cell.netChange ?? 0;
+}
+
+/**
+ * Roll an income-statement account series (already filtered to
+ * `incomeBalance === "Income Statement"`) up into the executive P&L summary
+ * lines, one value per period bucket.
+ *
+ * netChange for income-statement leaves is natural-positive (revenue positive
+ * when earned, costs positive when incurred), so categories sum directly and
+ * the subtotals are simple differences:
+ * Gross Profit = Revenue − COGS
+ * Operating Income = Gross Profit − Operating Expenses
+ * Net Income = Operating Income + Other Income − Other Expense − Tax
+ */
+export function computeExecutivePnl(
+ accounts: ChartPeriodSeries[],
+ bucketKeys: string[],
+ options: { showTranslated?: boolean } = {}
+): ExecutivePnlRow[] {
+ const showTranslated = options.showTranslated ?? false;
+
+ const zero = (): Record<string, number> =>
+ Object.fromEntries(bucketKeys.map((key) => [key, 0]));
+
+ const sums: Record<BaseCategory, Record<string, number>> = {
+ revenue: zero(),
+ cogs: zero(),
+ operatingExpenses: zero(),
+ otherIncome: zero(),
+ otherExpense: zero(),
+ tax: zero()
+ };
+
+ for (const account of accounts) {
+ const category = categoryOf(account);
+ if (!category) continue;
+ for (const key of bucketKeys) {
+ sums[category][key] += cellValue(account.periods?.[key], showTranslated);
+ }
+ }
+
+ const derive = (fn: (key: string) => number): Record<string, number> =>
+ Object.fromEntries(bucketKeys.map((key) => [key, fn(key)]));
+
+ const grossProfit = derive((k) => sums.revenue[k]! - sums.cogs[k]!);
+ const operatingIncome = derive(
+ (k) => grossProfit[k]! - sums.operatingExpenses[k]!
+ );
+ const netIncome = derive(
+ (k) =>
+ operatingIncome[k]! +
+ sums.otherIncome[k]! -
+ sums.otherExpense[k]! -
+ sums.tax[k]!
+ );
+
+ const marginsOf = (
+ values: Record<string, number>
+ ): Record<string, number | null> =>
+ Object.fromEntries(
+ bucketKeys.map((k) => {
+ const revenue = sums.revenue[k]!;
+ return [k, revenue === 0 ? null : values[k]! / revenue];
+ })
+ );
+
+ return [
+ {
+ key: "revenue",
+ isSubtotal: false,
+ isBottomLine: false,
+ values: sums.revenue
+ },
+ { key: "cogs", isSubtotal: false, isBottomLine: false, values: sums.cogs },
+ {
+ key: "grossProfit",
+ isSubtotal: true,
+ isBottomLine: false,
+ values: grossProfit,
+ margins: marginsOf(grossProfit)
+ },
+ {
+ key: "operatingExpenses",
+ isSubtotal: false,
+ isBottomLine: false,
+ values: sums.operatingExpenses
+ },
+ {
+ key: "operatingIncome",
+ isSubtotal: true,
+ isBottomLine: false,
+ values: operatingIncome,
+ margins: marginsOf(operatingIncome)
+ },
+ {
+ key: "otherIncome",
+ isSubtotal: false,
+ isBottomLine: false,
+ values: sums.otherIncome
+ },
+ {
+ key: "otherExpense",
+ isSubtotal: false,
+ isBottomLine: false,
+ values: sums.otherExpense
+ },
+ { key: "tax", isSubtotal: false, isBottomLine: false, values: sums.tax },
+ {
+ key: "netIncome",
+ isSubtotal: true,
+ isBottomLine: true,
+ values: netIncome,
+ margins: marginsOf(netIncome)
+ }
+ ];
+}
diff --git a/apps/erp/app/modules/accounting/ui/Reports/exportReport.ts b/apps/erp/app/modules/accounting/ui/Reports/exportReport.ts
new file mode 100644
index 0000000000..afcad2aa46
--- /dev/null
+++ b/apps/erp/app/modules/accounting/ui/Reports/exportReport.ts
@@ -0,0 +1,112 @@
+import type { ReportPeriodBucket } from "@carbon/utils";
+import { json2csv } from "json-2-csv";
+import type { Chart, ChartPeriodSeries } from "../../types";
+import { computeExecutivePnl, type ExecutivePnlRowKey } from "./executivePnl";
+import {
+ accountsToFlatTree,
+ filterAccounts,
+ getDebitCredit
+} from "./reportTree";
+
+// Standalone CSV download (ExchangeRateForm pattern) — the report trees are
+// not built on the shared Table component, so they get no free export button.
+function downloadCsv(rows: Record<string, unknown>[], filename: string) {
+ if (rows.length === 0) return;
+ const csvData = json2csv(rows, { emptyFieldValue: "" });
+ const blob = new Blob([csvData], { type: "text/csv" });
+ const url = window.URL.createObjectURL(blob);
+ const a = document.createElement("a");
+ a.href = url;
+ a.download = filename;
+ document.body.appendChild(a);
+ a.click();
+ window.URL.revokeObjectURL(url);
+ document.body.removeChild(a);
+}
+
+// Export the multi-period statement in flat-tree display order (the FULL tree,
+// honoring the current search filter — never the virtualizer's window).
+export function exportPeriodReport(args: {
+ accounts: ChartPeriodSeries[];
+ periods: Array<ReportPeriodBucket & { label: string }>;
+ measure: "balanceAtDate" | "netChange";
+ showTranslated?: boolean;
+ search: string;
+ filename: string;
+}) {
+ const tree = accountsToFlatTree(filterAccounts(args.accounts, args.search));
+ const rows = tree.map(({ data: account }) => {
+ const row: Record<string, unknown> = {
+ Number: account.isGroup ? "" : (account.number ?? ""),
+ Account: account.name ?? ""
+ };
+ for (const bucket of args.periods) {
+ const cell = account.periods?.[bucket.key];
+ row[bucket.label] = args.showTranslated
+ ? (cell?.translatedBalance ?? "")
+ : (cell?.[args.measure] ?? 0);
+ }
+ return row;
+ });
+ downloadCsv(rows, args.filename);
+}
+
+// Export the executive P&L summary rows (condensed subtotals with margins),
+// one column per period bucket — mirrors what ExecutivePnlSummary renders.
+export function exportExecutivePnl(args: {
+ accounts: ChartPeriodSeries[];
+ periods: Array<ReportPeriodBucket & { label: string }>;
+ labels: Record<ExecutivePnlRowKey, string>;
+ showTranslated?: boolean;
+ filename: string;
+}) {
+ const rows = computeExecutivePnl(
+ args.accounts,
+ args.periods.map((bucket) => bucket.key),
+ { showTranslated: args.showTranslated }
+ );
+
+ const csvRows = rows.map((row) => {
+ const csvRow: Record<string, unknown> = { Line: args.labels[row.key] };
+ for (const bucket of args.periods) {
+ csvRow[bucket.label] = row.values[bucket.key] ?? 0;
+ if (row.margins != null) {
+ const margin = row.margins[bucket.key];
+ csvRow[`${bucket.label} %`] = margin == null ? "" : margin;
+ }
+ }
+ return csvRow;
+ });
+ downloadCsv(csvRows, args.filename);
+}
+
+// Export the single-period trial balance with the same Beginning/Debit/Credit/
+// Ending derivation the tree renders.
+export function exportTrialBalance(args: {
+ accounts: (Chart & { translatedBalance?: number })[];
+ showTranslated?: boolean;
+ parentCurrency?: string | null;
+ search: string;
+ filename: string;
+}) {
+ const tree = accountsToFlatTree(filterAccounts(args.accounts, args.search));
+ const rows = tree.map(({ data: account }) => {
+ const endingBalance = account.balanceAtDate ?? 0;
+ const netChange = account.netChange ?? 0;
+ const { debit, credit } = getDebitCredit(netChange, account.class);
+ const row: Record<string, unknown> = {
+ Number: account.isGroup ? "" : (account.number ?? ""),
+ Account: account.name ?? "",
+ Beginning: endingBalance - netChange,
+ Debits: debit,
+ Credits: credit,
+ Ending: endingBalance
+ };
+ if (args.showTranslated) {
+ row[`Ending (${args.parentCurrency ?? "Translated"})`] =
+ account.translatedBalance ?? "";
+ }
+ return row;
+ });
+ downloadCsv(rows, args.filename);
+}
diff --git a/apps/erp/app/modules/accounting/ui/Reports/index.ts b/apps/erp/app/modules/accounting/ui/Reports/index.ts
index 2bec9c50a8..33c50bf41b 100644
--- a/apps/erp/app/modules/accounting/ui/Reports/index.ts
+++ b/apps/erp/app/modules/accounting/ui/Reports/index.ts
@@ -1,6 +1,25 @@
export { default as AccountLedgerDrawer } from "./AccountLedgerDrawer";
export { default as CompanySelector } from "./CompanySelector";
-export { default as FinancialStatementTree } from "./FinancialStatementTree";
+export { default as ExecutivePnlSummary } from "./ExecutivePnlSummary";
+export type { ExecutivePnlRow, ExecutivePnlRowKey } from "./executivePnl";
+export { computeExecutivePnl } from "./executivePnl";
+export {
+ exportExecutivePnl,
+ exportPeriodReport,
+ exportTrialBalance
+} from "./exportReport";
+export {
+ default as MultiPeriodStatementTree,
+ getPeriodColumnLabel
+} from "./MultiPeriodStatementTree";
+export type { PivotDimension } from "./PivotControlBar";
+export { default as PivotControlBar } from "./PivotControlBar";
+export { default as PivotLinesDrawer } from "./PivotLinesDrawer";
+export type { PivotCellCoordinates } from "./PivotTree";
+export { default as PivotTree } from "./PivotTree";
+export { default as PurchaseLinesDrawer } from "./PurchaseLinesDrawer";
+export { default as PurchasesControlBar } from "./PurchasesControlBar";
export { default as ReportFilters } from "./ReportFilters";
+export { default as SaveViewModal } from "./SaveViewModal";
export { default as TrialBalanceTable } from "./TrialBalanceTable";
export { default as TrialBalanceTree } from "./TrialBalanceTree";
diff --git a/apps/erp/app/modules/accounting/ui/Reports/pivotData.test.ts b/apps/erp/app/modules/accounting/ui/Reports/pivotData.test.ts
new file mode 100644
index 0000000000..8487c7b0c5
--- /dev/null
+++ b/apps/erp/app/modules/accounting/ui/Reports/pivotData.test.ts
@@ -0,0 +1,562 @@
+import { describe, expect, it } from "vitest";
+import type { PivotGroupRow } from "./pivotData";
+import {
+ applyPercentOfTotal,
+ buildPivotTree,
+ getPivotMeasureValue,
+ LABEL_SORT_KEY,
+ pivotToCsvRows,
+ TOTAL_SORT_KEY,
+ UNASSIGNED_COLUMN_KEY
+} from "./pivotData";
+
+function group(
+ rowValue1Id: string | null,
+ rowValue2Id: string | null,
+ columnKey: string | null,
+ amount: number,
+ quantity = 0,
+ lineCount = 1
+): PivotGroupRow {
+ return { rowValue1Id, rowValue2Id, columnKey, amount, quantity, lineCount };
+}
+
+const VALUE_NAMES: Record<string, string> = {
+ a: "Alpha",
+ b: "Beta",
+ x: "X-Ray",
+ y: "Yankee"
+};
+
+describe("buildPivotTree", () => {
+ it("1-dim rows: sorts by ABS(measure) desc, Unassigned last, totals correct", () => {
+ const groups = [
+ group("a", null, "c1", 100, 5, 2),
+ group("a", null, "c2", 50, 1, 1),
+ group("b", null, "c1", -400, 2, 3),
+ group("b", null, "c2", 100, 0, 1),
+ // Unassigned row has the biggest ABS total but must still sort last.
+ group(null, null, "c1", 900, 9, 4)
+ ];
+
+ const result = buildPivotTree({
+ groups,
+ valueNames: VALUE_NAMES,
+ columnKeys: ["c1", "c2"],
+ rowCount: 1,
+ measure: "amount"
+ });
+
+ expect(result.flatTree).toHaveLength(3);
+ expect(result.flatTree.map((n) => n.data.label)).toEqual([
+ "Beta", // ABS(-300) > ABS(150)
+ "Alpha",
+ "Unassigned"
+ ]);
+ expect(result.columnsTruncated).toBe(false);
+ expect(result.columnKeys).toEqual(["c1", "c2"]);
+
+ const beta = result.flatTree[0];
+ expect(beta?.id).toBe("b");
+ expect(beta?.parentId).toBeUndefined();
+ expect(beta?.level).toBe(0);
+ expect(beta?.hasChildren).toBe(false);
+ expect(beta?.children).toEqual([]);
+ expect(beta?.data.rowValue1Id).toBe("b");
+ expect(beta?.data.rowValue2Id).toBeNull();
+ expect(beta?.data.isUnassigned).toBe(false);
+ expect(beta?.data.total).toEqual({
+ amount: -300,
+ quantity: 2,
+ lineCount: 4
+ });
+ expect(beta?.data.cells["c1"]).toEqual({
+ amount: -400,
+ quantity: 2,
+ lineCount: 3
+ });
+ expect(beta?.data.cells["c2"]).toEqual({
+ amount: 100,
+ quantity: 0,
+ lineCount: 1
+ });
+
+ const unassigned = result.flatTree[2];
+ expect(unassigned?.data.isUnassigned).toBe(true);
+ expect(unassigned?.data.rowValue1Id).toBeNull();
+ expect(unassigned?.data.total.amount).toBe(900);
+ });
+
+ it("falls back to the raw id when a valueNames entry is missing", () => {
+ const result = buildPivotTree({
+ groups: [group("mystery", null, "c1", 10)],
+ valueNames: {},
+ columnKeys: ["c1"],
+ rowCount: 1,
+ measure: "amount"
+ });
+ expect(result.flatTree[0]?.data.label).toBe("mystery");
+ });
+
+ it("2-dim nesting: parent subtotals equal sum of children; levels and parentId wired", () => {
+ const groups = [
+ group("a", "x", "c1", 100, 2, 1),
+ group("a", "x", "c2", 50, 1, 1),
+ group("a", "y", "c1", 300, 3, 2),
+ group("a", null, "c1", 25, 0, 1), // Unassigned child under Alpha
+ group("b", "x", "c1", 10, 1, 1)
+ ];
+
+ const result = buildPivotTree({
+ groups,
+ valueNames: VALUE_NAMES,
+ columnKeys: ["c1", "c2"],
+ rowCount: 2,
+ measure: "amount"
+ });
+
+ // Alpha (475) before Beta (10); Alpha's children: Yankee (300), X-Ray (150),
+ // Unassigned (25, last regardless of size).
+ expect(result.flatTree.map((n) => n.id)).toEqual([
+ "a",
+ "a|y",
+ "a|x",
+ "a|__unassigned__",
+ "b",
+ "b|x"
+ ]);
+
+ const alpha = result.flatTree[0];
+ expect(alpha?.level).toBe(0);
+ expect(alpha?.parentId).toBeUndefined();
+ expect(alpha?.hasChildren).toBe(true);
+ expect(alpha?.children).toEqual(["a|y", "a|x", "a|__unassigned__"]);
+ expect(alpha?.data.rowValue1Id).toBe("a");
+ expect(alpha?.data.rowValue2Id).toBeNull();
+
+ const alphaChildren = result.flatTree.filter((n) => n.parentId === "a");
+ expect(alphaChildren).toHaveLength(3);
+ for (const child of alphaChildren) {
+ expect(child.level).toBe(1);
+ expect(child.hasChildren).toBe(false);
+ expect(child.data.rowValue1Id).toBe("a");
+ }
+
+ // Parent totals aggregate children.
+ const childTotalSum = alphaChildren.reduce(
+ (sum, child) => sum + child.data.total.amount,
+ 0
+ );
+ expect(alpha?.data.total.amount).toBe(childTotalSum);
+ expect(alpha?.data.total).toEqual({
+ amount: 475,
+ quantity: 6,
+ lineCount: 5
+ });
+
+ // Parent cells aggregate children's cells per column.
+ const childC1Sum = alphaChildren.reduce(
+ (sum, child) => sum + (child.data.cells["c1"]?.amount ?? 0),
+ 0
+ );
+ expect(alpha?.data.cells["c1"]?.amount).toBe(childC1Sum);
+ expect(alpha?.data.cells["c1"]?.amount).toBe(425);
+ expect(alpha?.data.cells["c2"]?.amount).toBe(50);
+
+ // Unassigned leaf: rowValue2Id null, flagged.
+ const unassignedLeaf = result.flatTree.find(
+ (n) => n.id === "a|__unassigned__"
+ );
+ expect(unassignedLeaf?.data.rowValue2Id).toBeNull();
+ expect(unassignedLeaf?.data.isUnassigned).toBe(true);
+ });
+
+ it("column totals and grand total are consistent with the input", () => {
+ const groups = [
+ group("a", null, "c1", 100, 2, 1),
+ group("b", null, "c1", -40, 1, 2),
+ group("a", null, "c2", 60, 3, 1),
+ group(null, null, null, 5, 1, 1) // null columnKey → UNASSIGNED_COLUMN_KEY
+ ];
+
+ const result = buildPivotTree({
+ groups,
+ valueNames: VALUE_NAMES,
+ columnKeys: ["c1", "c2", UNASSIGNED_COLUMN_KEY],
+ rowCount: 1,
+ measure: "amount"
+ });
+
+ expect(result.columnTotals["c1"]).toEqual({
+ amount: 60,
+ quantity: 3,
+ lineCount: 3
+ });
+ expect(result.columnTotals["c2"]).toEqual({
+ amount: 60,
+ quantity: 3,
+ lineCount: 1
+ });
+ expect(result.columnTotals[UNASSIGNED_COLUMN_KEY]).toEqual({
+ amount: 5,
+ quantity: 1,
+ lineCount: 1
+ });
+ expect(result.grandTotal).toEqual({
+ amount: 125,
+ quantity: 7,
+ lineCount: 5
+ });
+
+ // Grand total equals the sum of all column totals (nothing hidden here).
+ const columnSum = Object.values(result.columnTotals).reduce(
+ (sum, cell) => sum + cell.amount,
+ 0
+ );
+ expect(columnSum).toBe(result.grandTotal.amount);
+ });
+
+ it("rowCount 0: a single total row spanning all data", () => {
+ const groups = [
+ group("a", null, "c1", 100, 2, 1),
+ group("b", null, "c2", 50, 1, 1)
+ ];
+
+ const result = buildPivotTree({
+ groups,
+ valueNames: VALUE_NAMES,
+ columnKeys: ["c1", "c2"],
+ rowCount: 0,
+ measure: "amount"
+ });
+
+ expect(result.flatTree).toHaveLength(1);
+ const totalNode = result.flatTree[0];
+ expect(totalNode?.id).toBe("total");
+ expect(totalNode?.data.key).toBe("total");
+ expect(totalNode?.data.label).toBe("Total");
+ expect(totalNode?.level).toBe(0);
+ expect(totalNode?.parentId).toBeUndefined();
+ expect(totalNode?.hasChildren).toBe(false);
+ expect(totalNode?.data.isUnassigned).toBe(false);
+ expect(totalNode?.data.total).toEqual({
+ amount: 150,
+ quantity: 3,
+ lineCount: 2
+ });
+ expect(totalNode?.data.cells["c1"]?.amount).toBe(100);
+ expect(totalNode?.data.cells["c2"]?.amount).toBe(50);
+
+ // Localized total label is honored.
+ const localized = buildPivotTree({
+ groups,
+ valueNames: VALUE_NAMES,
+ columnKeys: ["c1", "c2"],
+ rowCount: 0,
+ measure: "amount",
+ totalLabel: "Gesamt"
+ });
+ expect(localized.flatTree[0]?.data.label).toBe("Gesamt");
+ });
+
+ it("honors a localized unassignedLabel", () => {
+ const result = buildPivotTree({
+ groups: [group(null, null, "c1", 10)],
+ valueNames: {},
+ columnKeys: ["c1"],
+ rowCount: 1,
+ measure: "amount",
+ unassignedLabel: "Nicht zugewiesen"
+ });
+ expect(result.flatTree[0]?.data.label).toBe("Nicht zugewiesen");
+ expect(result.flatTree[0]?.data.isUnassigned).toBe(true);
+ });
+
+ it("truncates columns to top-N by ABS(measure), always keeping Unassigned; totals stay truthful", () => {
+ const groups = [
+ group("a", null, "c1", 1000, 1, 1),
+ group("a", null, "c2", 10, 1, 1),
+ group("a", null, "c3", -500, 1, 1),
+ group("a", null, null, 1, 1, 1) // Unassigned column, tiny total
+ ];
+
+ const result = buildPivotTree({
+ groups,
+ valueNames: VALUE_NAMES,
+ columnKeys: ["c1", "c2", "c3", UNASSIGNED_COLUMN_KEY],
+ rowCount: 1,
+ measure: "amount",
+ maxColumns: 2
+ });
+
+ expect(result.columnsTruncated).toBe(true);
+ // Top non-unassigned column by ABS is c1 (1000 > 500 > 10); Unassigned is
+ // always kept even though its total is the smallest.
+ expect(result.columnKeys).toEqual(["c1", UNASSIGNED_COLUMN_KEY]);
+
+ const alpha = result.flatTree[0];
+ // Hidden columns are excluded from visible cells...
+ expect(alpha?.data.cells["c2"]).toBeUndefined();
+ expect(alpha?.data.cells["c3"]).toBeUndefined();
+ expect(alpha?.data.cells["c1"]?.amount).toBe(1000);
+ expect(alpha?.data.cells[UNASSIGNED_COLUMN_KEY]?.amount).toBe(1);
+ // ...but row totals, column totals, and the grand total include ALL data.
+ expect(alpha?.data.total.amount).toBe(511);
+ expect(result.grandTotal.amount).toBe(511);
+ expect(result.columnTotals["c2"]?.amount).toBe(10);
+ expect(result.columnTotals["c3"]?.amount).toBe(-500);
+ });
+
+ it("truncates by the chosen measure, not always amount", () => {
+ const groups = [
+ group("a", null, "c1", 1000, 1, 1), // big amount, small quantity
+ group("a", null, "c2", 10, 900, 1) // small amount, big quantity
+ ];
+
+ const result = buildPivotTree({
+ groups,
+ valueNames: VALUE_NAMES,
+ columnKeys: ["c1", "c2"],
+ rowCount: 1,
+ measure: "quantity",
+ maxColumns: 1
+ });
+
+ expect(result.columnsTruncated).toBe(true);
+ expect(result.columnKeys).toEqual(["c2"]);
+ });
+
+ it("does not cap columns when maxColumns is omitted", () => {
+ const columnKeys = Array.from({ length: 120 }, (_, i) => `c${i}`);
+ const groups = columnKeys.map((key, i) => group("a", null, key, i + 1));
+
+ const result = buildPivotTree({
+ groups,
+ valueNames: VALUE_NAMES,
+ columnKeys,
+ rowCount: 1,
+ measure: "amount"
+ });
+
+ expect(result.columnsTruncated).toBe(false);
+ expect(result.columnKeys).toEqual(columnKeys);
+ });
+
+ it("sorts rows by a specific column, ascending and descending (signed)", () => {
+ const groups = [
+ group("a", null, "c1", 100),
+ group("b", null, "c1", -300),
+ group("c", null, "c1", 200)
+ ];
+
+ const desc = buildPivotTree({
+ groups,
+ valueNames: VALUE_NAMES,
+ columnKeys: ["c1"],
+ rowCount: 1,
+ measure: "amount",
+ sort: { key: "c1", direction: "desc" }
+ });
+ // Signed, not ABS: 200 > 100 > -300.
+ expect(desc.flatTree.map((n) => n.data.rowValue1Id)).toEqual([
+ "c",
+ "a",
+ "b"
+ ]);
+
+ const asc = buildPivotTree({
+ groups,
+ valueNames: VALUE_NAMES,
+ columnKeys: ["c1"],
+ rowCount: 1,
+ measure: "amount",
+ sort: { key: "c1", direction: "asc" }
+ });
+ expect(asc.flatTree.map((n) => n.data.rowValue1Id)).toEqual([
+ "b",
+ "a",
+ "c"
+ ]);
+ });
+
+ it("sorts by total and keeps Unassigned last even under an explicit sort", () => {
+ const groups = [
+ group("a", null, "c1", 100),
+ group("b", null, "c1", 300),
+ group(null, null, "c1", 999) // Unassigned biggest, must still sort last
+ ];
+
+ const result = buildPivotTree({
+ groups,
+ valueNames: VALUE_NAMES,
+ columnKeys: ["c1"],
+ rowCount: 1,
+ measure: "amount",
+ sort: { key: TOTAL_SORT_KEY, direction: "asc" }
+ });
+
+ expect(result.flatTree.map((n) => n.data.label)).toEqual([
+ "Alpha",
+ "Beta",
+ "Unassigned"
+ ]);
+ });
+
+ it("sorts by row label alphabetically", () => {
+ const groups = [group("b", null, "c1", 100), group("a", null, "c1", 100)];
+
+ const asc = buildPivotTree({
+ groups,
+ valueNames: VALUE_NAMES,
+ columnKeys: ["c1"],
+ rowCount: 1,
+ measure: "amount",
+ sort: { key: LABEL_SORT_KEY, direction: "asc" }
+ });
+ expect(asc.flatTree.map((n) => n.data.label)).toEqual(["Alpha", "Beta"]);
+
+ const desc = buildPivotTree({
+ groups,
+ valueNames: VALUE_NAMES,
+ columnKeys: ["c1"],
+ rowCount: 1,
+ measure: "amount",
+ sort: { key: LABEL_SORT_KEY, direction: "desc" }
+ });
+ expect(desc.flatTree.map((n) => n.data.label)).toEqual(["Beta", "Alpha"]);
+ });
+
+ it("applies the column sort within a nested level too", () => {
+ const groups = [
+ group("a", "x", "c1", 100),
+ group("a", "y", "c1", 300),
+ group("a", "z", "c1", 200)
+ ];
+
+ const result = buildPivotTree({
+ groups,
+ valueNames: { ...VALUE_NAMES, z: "Zulu" },
+ columnKeys: ["c1"],
+ rowCount: 2,
+ measure: "amount",
+ sort: { key: "c1", direction: "asc" }
+ });
+
+ // Children of Alpha ordered by c1 ascending: x(100), z(200), y(300).
+ expect(
+ result.flatTree
+ .filter((n) => n.parentId === "a")
+ .map((n) => n.data.rowValue2Id)
+ ).toEqual(["x", "z", "y"]);
+ });
+});
+
+describe("applyPercentOfTotal", () => {
+ it("sums to ~100 per column and yields 0s for a zero-total column", () => {
+ const groups = [
+ group("a", null, "c1", 25, 0, 1),
+ group("b", null, "c1", 75, 0, 1),
+ // c0 nets to zero: both rows must read 0%.
+ group("a", null, "c0", 100, 0, 1),
+ group("b", null, "c0", -100, 0, 1)
+ ];
+
+ const result = buildPivotTree({
+ groups,
+ valueNames: VALUE_NAMES,
+ columnKeys: ["c1", "c0"],
+ rowCount: 1,
+ measure: "amount"
+ });
+
+ let c1Sum = 0;
+ for (const node of result.flatTree) {
+ const percents = applyPercentOfTotal(
+ node.data.cells,
+ result.columnTotals,
+ "amount"
+ );
+ c1Sum += percents["c1"] ?? 0;
+ expect(percents["c0"]).toBe(0);
+ }
+ expect(Math.abs(c1Sum - 100)).toBeLessThan(1e-6);
+ });
+
+ it("uses the chosen measure (count maps to lineCount)", () => {
+ const cells = { c1: { amount: 0, quantity: 0, lineCount: 3 } };
+ const columnTotals = { c1: { amount: 0, quantity: 0, lineCount: 12 } };
+ const percents = applyPercentOfTotal(cells, columnTotals, "count");
+ expect(percents["c1"]).toBe(25);
+ });
+});
+
+describe("getPivotMeasureValue", () => {
+ it("maps each measure and treats a missing cell as 0", () => {
+ const cell = { amount: 1, quantity: 2, lineCount: 3 };
+ expect(getPivotMeasureValue(cell, "amount")).toBe(1);
+ expect(getPivotMeasureValue(cell, "quantity")).toBe(2);
+ expect(getPivotMeasureValue(cell, "count")).toBe(3);
+ expect(getPivotMeasureValue(undefined, "amount")).toBe(0);
+ });
+});
+
+describe("pivotToCsvRows", () => {
+ it("matches the rendered tree: header, indentation, and totals row", () => {
+ const groups = [
+ group("a", "x", "c1", 100, 0, 1),
+ group("a", "y", "c1", 300, 0, 1),
+ group("a", "x", "c2", 50, 0, 1),
+ group(null, null, "c1", 5, 0, 1)
+ ];
+
+ const built = buildPivotTree({
+ groups,
+ valueNames: VALUE_NAMES,
+ columnKeys: ["c1", "c2"],
+ rowCount: 2,
+ measure: "amount"
+ });
+
+ const csv = pivotToCsvRows({
+ flatTree: built.flatTree,
+ columnKeys: built.columnKeys,
+ columnTotals: built.columnTotals,
+ grandTotal: built.grandTotal,
+ measure: "amount",
+ columnLabels: { c1: "Jan 2026", c2: "Feb 2026" }
+ });
+
+ // header + 5 tree nodes (Alpha, 2 children, Unassigned parent + child) + totals
+ expect(csv).toEqual([
+ ["", "Jan 2026", "Feb 2026", "Total"],
+ ["Alpha", "400", "50", "450"],
+ [" Yankee", "300", "0", "300"],
+ [" X-Ray", "100", "50", "150"],
+ ["Unassigned", "5", "0", "5"],
+ [" Unassigned", "5", "0", "5"],
+ ["Total", "405", "50", "455"]
+ ]);
+ });
+
+ it("falls back to the raw column key when a label is missing", () => {
+ const built = buildPivotTree({
+ groups: [group("a", null, "c1", 10, 0, 1)],
+ valueNames: VALUE_NAMES,
+ columnKeys: ["c1"],
+ rowCount: 1,
+ measure: "amount"
+ });
+
+ const csv = pivotToCsvRows({
+ flatTree: built.flatTree,
+ columnKeys: built.columnKeys,
+ columnTotals: built.columnTotals,
+ grandTotal: built.grandTotal,
+ measure: "amount",
+ columnLabels: {}
+ });
+
+ expect(csv[0]).toEqual(["", "c1", "Total"]);
+ expect(csv[csv.length - 1]).toEqual(["Total", "10", "10"]);
+ });
+});
diff --git a/apps/erp/app/modules/accounting/ui/Reports/pivotData.ts b/apps/erp/app/modules/accounting/ui/Reports/pivotData.ts
new file mode 100644
index 0000000000..496a719bdc
--- /dev/null
+++ b/apps/erp/app/modules/accounting/ui/Reports/pivotData.ts
@@ -0,0 +1,358 @@
+import type { FlatTreeItem } from "~/components/TreeView";
+import type { PivotMeasure } from "../../accounting.models";
+
+// Pure pivot assembly for the dimensional analytics reports — no React, no
+// data fetching. Spec: .ai/specs/2026-08-09-dimensional-pivot-reporting.md.
+
+export type PivotCellValue = {
+ amount: number;
+ quantity: number;
+ lineCount: number;
+};
+
+// Input shape (mirrors getDimensionPivot groups).
+export type PivotGroupRow = {
+ rowValue1Id: string | null;
+ rowValue2Id: string | null;
+ columnKey: string | null; // null = Unassigned column (dimension axis)
+ amount: number;
+ quantity: number;
+ lineCount: number;
+};
+
+export type PivotRowNode = {
+ key: string;
+ rowValue1Id: string | null; // null = Unassigned
+ rowValue2Id: string | null; // null on level-1 parents and on Unassigned leaves
+ label: string; // resolved name or the unassigned label
+ isUnassigned: boolean;
+ cells: Record<string, PivotCellValue>; // by columnKey; null columnKey stored under UNASSIGNED_COLUMN_KEY
+ total: PivotCellValue;
+};
+
+export const UNASSIGNED_COLUMN_KEY = "__unassigned__";
+
+// Sentinel sort keys for the non-value columns. Any other sort key is a real
+// columnKey. See buildPivotTree's `sort` arg.
+export const TOTAL_SORT_KEY = "__total__";
+export const LABEL_SORT_KEY = "__label__";
+
+export type PivotSort = { key: string; direction: "asc" | "desc" };
+
+function zeroCell(): PivotCellValue {
+ return { amount: 0, quantity: 0, lineCount: 0 };
+}
+
+function addTo(
+ target: PivotCellValue,
+ source: { amount: number; quantity: number; lineCount: number }
+): void {
+ target.amount += source.amount;
+ target.quantity += source.quantity;
+ target.lineCount += source.lineCount;
+}
+
+/** Read the measure's numeric value off a cell; a missing cell reads as 0. */
+export function getPivotMeasureValue(
+ cell: PivotCellValue | undefined,
+ measure: PivotMeasure
+): number {
+ if (!cell) return 0;
+ if (measure === "quantity") return cell.quantity;
+ if (measure === "count") return cell.lineCount;
+ return cell.amount;
+}
+
+// Internal aggregation node — cells only accumulate visible columns; totals
+// accumulate everything (totals stay truthful when columns are truncated).
+type RowAgg = {
+ cells: Record<string, PivotCellValue>;
+ total: PivotCellValue;
+ children: Map<string | null, RowAgg>;
+};
+
+function newAgg(): RowAgg {
+ return { cells: {}, total: zeroCell(), children: new Map() };
+}
+
+function getOrCreate(
+ map: Map<string | null, RowAgg>,
+ key: string | null
+): RowAgg {
+ let agg = map.get(key);
+ if (!agg) {
+ agg = newAgg();
+ map.set(key, agg);
+ }
+ return agg;
+}
+
+export function buildPivotTree(args: {
+ groups: PivotGroupRow[];
+ valueNames: Record<string, string>;
+ columnKeys: string[]; // ordered, may contain UNASSIGNED_COLUMN_KEY
+ rowCount: 0 | 1 | 2; // how many row dimensions are selected
+ measure: PivotMeasure; // used for sorting by ABS(total[measure])
+ unassignedLabel?: string; // default "Unassigned" — caller passes the localized string
+ totalLabel?: string; // default "Total" — label of the single row when rowCount is 0
+ maxColumns?: number; // optional; omit for no cap. Keeps the top-N by ABS(measure).
+ sort?: PivotSort | null; // row sort; omit/null for the default ABS(measure) desc
+}): {
+ flatTree: FlatTreeItem<PivotRowNode>[];
+ columnKeys: string[];
+ columnTotals: Record<string, PivotCellValue>;
+ grandTotal: PivotCellValue;
+ columnsTruncated: boolean;
+} {
+ const { groups, valueNames, rowCount, measure } = args;
+ const unassignedLabel = args.unassignedLabel ?? "Unassigned";
+ const totalLabel = args.totalLabel ?? "Total";
+ const maxColumns = args.maxColumns;
+ const sort = args.sort ?? null;
+
+ // Column totals + grand total over ALL data (hidden columns included).
+ const columnTotals: Record<string, PivotCellValue> = {};
+ const grandTotal = zeroCell();
+ for (const group of groups) {
+ const columnKey = group.columnKey ?? UNASSIGNED_COLUMN_KEY;
+ const columnTotal = (columnTotals[columnKey] ??= zeroCell());
+ addTo(columnTotal, group);
+ addTo(grandTotal, group);
+ }
+ for (const key of args.columnKeys) {
+ columnTotals[key] ??= zeroCell();
+ }
+
+ // Column truncation: keep the top maxColumns by ABS(column total of the
+ // chosen measure) — but always keep the Unassigned column when present.
+ let visibleColumnKeys = args.columnKeys;
+ let columnsTruncated = false;
+ if (maxColumns !== undefined && args.columnKeys.length > maxColumns) {
+ columnsTruncated = true;
+ const hasUnassigned = args.columnKeys.includes(UNASSIGNED_COLUMN_KEY);
+ const ranked = args.columnKeys
+ .filter((key) => key !== UNASSIGNED_COLUMN_KEY)
+ .sort(
+ (a, b) =>
+ Math.abs(getPivotMeasureValue(columnTotals[b], measure)) -
+ Math.abs(getPivotMeasureValue(columnTotals[a], measure))
+ );
+ const keepCount = hasUnassigned ? Math.max(maxColumns - 1, 0) : maxColumns;
+ const kept = new Set(ranked.slice(0, keepCount));
+ if (hasUnassigned) kept.add(UNASSIGNED_COLUMN_KEY);
+ // Preserve the caller's column order.
+ visibleColumnKeys = args.columnKeys.filter((key) => kept.has(key));
+ }
+ const visibleColumnSet = new Set(visibleColumnKeys);
+
+ const accumulate = (agg: RowAgg, columnKey: string, group: PivotGroupRow) => {
+ addTo(agg.total, group);
+ // Dropped columns are excluded from visible cells; row totals keep them.
+ if (visibleColumnSet.has(columnKey)) {
+ const cell = (agg.cells[columnKey] ??= zeroCell());
+ addTo(cell, group);
+ }
+ };
+
+ const labelFor = (id: string | null): string =>
+ id === null ? unassignedLabel : (valueNames[id] ?? id);
+
+ // Value read for the active column sort (signed, unlike the ABS default).
+ const sortValue = (agg: RowAgg): number =>
+ sort && sort.key === TOTAL_SORT_KEY
+ ? getPivotMeasureValue(agg.total, measure)
+ : getPivotMeasureValue(agg.cells[sort?.key ?? ""], measure);
+
+ // Sort: Unassigned always last at its level. With no explicit sort, order by
+ // ABS(total[measure]) descending, then label ascending for determinism. With
+ // an explicit sort, order by the chosen column/total (signed) or label in the
+ // requested direction, tie-broken by label ascending.
+ const sortRowEntries = (
+ entries: [string | null, RowAgg][]
+ ): [string | null, RowAgg][] =>
+ entries.sort((a, b) => {
+ const [aId, aAgg] = a;
+ const [bId, bAgg] = b;
+ if ((aId === null) !== (bId === null)) return aId === null ? 1 : -1;
+
+ if (!sort) {
+ const diff =
+ Math.abs(getPivotMeasureValue(bAgg.total, measure)) -
+ Math.abs(getPivotMeasureValue(aAgg.total, measure));
+ if (diff !== 0) return diff;
+ return labelFor(aId).localeCompare(labelFor(bId));
+ }
+
+ const direction = sort.direction === "asc" ? 1 : -1;
+
+ if (sort.key === LABEL_SORT_KEY) {
+ return direction * labelFor(aId).localeCompare(labelFor(bId));
+ }
+
+ const diff = sortValue(aAgg) - sortValue(bAgg);
+ if (diff !== 0) return direction * diff;
+ return labelFor(aId).localeCompare(labelFor(bId));
+ });
+
+ const flatTree: FlatTreeItem<PivotRowNode>[] = [];
+
+ if (rowCount === 0) {
+ // No row grouping: a single level-1 node holding every group.
+ const totalAgg = newAgg();
+ for (const group of groups) {
+ accumulate(totalAgg, group.columnKey ?? UNASSIGNED_COLUMN_KEY, group);
+ }
+ flatTree.push({
+ id: "total",
+ parentId: undefined,
+ children: [],
+ hasChildren: false,
+ level: 0,
+ data: {
+ key: "total",
+ rowValue1Id: null,
+ rowValue2Id: null,
+ label: totalLabel,
+ isUnassigned: false,
+ cells: totalAgg.cells,
+ total: totalAgg.total
+ }
+ });
+ } else {
+ const level1 = new Map<string | null, RowAgg>();
+ for (const group of groups) {
+ const columnKey = group.columnKey ?? UNASSIGNED_COLUMN_KEY;
+ const parentAgg = getOrCreate(level1, group.rowValue1Id);
+ accumulate(parentAgg, columnKey, group);
+ if (rowCount === 2) {
+ const childAgg = getOrCreate(parentAgg.children, group.rowValue2Id);
+ accumulate(childAgg, columnKey, group);
+ }
+ }
+
+ const rowKeyPart = (id: string | null): string => id ?? "__unassigned__";
+
+ for (const [rowValue1Id, parentAgg] of sortRowEntries([...level1])) {
+ const parentKey = rowKeyPart(rowValue1Id);
+ const childEntries =
+ rowCount === 2 ? sortRowEntries([...parentAgg.children]) : [];
+ const childIds = childEntries.map(
+ ([rowValue2Id]) => `${parentKey}|${rowKeyPart(rowValue2Id)}`
+ );
+
+ flatTree.push({
+ id: parentKey,
+ parentId: undefined,
+ children: childIds,
+ hasChildren: childIds.length > 0,
+ level: 0,
+ data: {
+ key: parentKey,
+ rowValue1Id,
+ rowValue2Id: null,
+ label: labelFor(rowValue1Id),
+ isUnassigned: rowValue1Id === null,
+ cells: parentAgg.cells,
+ total: parentAgg.total
+ }
+ });
+
+ for (const [rowValue2Id, childAgg] of childEntries) {
+ const childKey = `${parentKey}|${rowKeyPart(rowValue2Id)}`;
+ flatTree.push({
+ id: childKey,
+ parentId: parentKey,
+ children: [],
+ hasChildren: false,
+ level: 1,
+ data: {
+ key: childKey,
+ rowValue1Id,
+ rowValue2Id,
+ label: labelFor(rowValue2Id),
+ isUnassigned: rowValue2Id === null,
+ cells: childAgg.cells,
+ total: childAgg.total
+ }
+ });
+ }
+ }
+ }
+
+ return {
+ flatTree,
+ columnKeys: visibleColumnKeys,
+ columnTotals,
+ grandTotal,
+ columnsTruncated
+ };
+}
+
+/**
+ * Per-column percentage of the column total for the chosen measure.
+ * A zero column total yields 0 (no division by zero).
+ */
+export function applyPercentOfTotal(
+ cells: Record<string, PivotCellValue>,
+ columnTotals: Record<string, PivotCellValue>,
+ measure: PivotMeasure
+): Record<string, number> {
+ const result: Record<string, number> = {};
+ for (const [key, cell] of Object.entries(cells)) {
+ const total = getPivotMeasureValue(columnTotals[key], measure);
+ result[key] =
+ total === 0 ? 0 : (getPivotMeasureValue(cell, measure) / total) * 100;
+ }
+ return result;
+}
+
+/**
+ * CSV rows exactly as rendered: header row ("", column labels, "Total"), one
+ * row per flat-tree node (level-2 labels indented two spaces), and a final
+ * totals row.
+ */
+export function pivotToCsvRows(args: {
+ flatTree: FlatTreeItem<PivotRowNode>[];
+ columnKeys: string[];
+ columnTotals: Record<string, PivotCellValue>;
+ grandTotal: PivotCellValue;
+ measure: PivotMeasure;
+ columnLabels: Record<string, string>;
+}): string[][] {
+ const {
+ flatTree,
+ columnKeys,
+ columnTotals,
+ grandTotal,
+ measure,
+ columnLabels
+ } = args;
+
+ const rows: string[][] = [];
+ rows.push([
+ "",
+ ...columnKeys.map((key) => columnLabels[key] ?? key),
+ "Total"
+ ]);
+
+ for (const node of flatTree) {
+ const indent = " ".repeat(node.level);
+ rows.push([
+ `${indent}${node.data.label}`,
+ ...columnKeys.map((key) =>
+ String(getPivotMeasureValue(node.data.cells[key], measure))
+ ),
+ String(getPivotMeasureValue(node.data.total, measure))
+ ]);
+ }
+
+ rows.push([
+ "Total",
+ ...columnKeys.map((key) =>
+ String(getPivotMeasureValue(columnTotals[key], measure))
+ ),
+ String(getPivotMeasureValue(grandTotal, measure))
+ ]);
+
+ return rows;
+}
diff --git a/apps/erp/app/modules/accounting/ui/Reports/reportTree.ts b/apps/erp/app/modules/accounting/ui/Reports/reportTree.ts
new file mode 100644
index 0000000000..de9ab39b67
--- /dev/null
+++ b/apps/erp/app/modules/accounting/ui/Reports/reportTree.ts
@@ -0,0 +1,114 @@
+import type { FlatTree, FlatTreeItem } from "~/components/TreeView";
+import { NET_INCOME_ACCOUNT_ID } from "../../types";
+
+// The minimal account shape the report trees need to build/filter a hierarchy.
+export type ReportAccountNode = {
+ id: string;
+ parentId: string | null;
+ name: string | null;
+ number: string | null;
+ isGroup: boolean | null;
+};
+
+// Shared by TrialBalanceTree and MultiPeriodStatementTree: build the flat tree
+// in display order — groups sort before leaves, the computed Net Income line
+// always sorts to the end of its group, everything else alphabetically.
+export function accountsToFlatTree<T extends ReportAccountNode>(
+ accounts: T[]
+): FlatTree<T> {
+ const byParent = new Map<string, T[]>();
+ for (const a of accounts) {
+ const key = a.parentId ?? "__root__";
+ if (!byParent.has(key)) byParent.set(key, []);
+ byParent.get(key)!.push(a);
+ }
+
+ const result: FlatTreeItem<T>[] = [];
+
+ function walk(parentId: string | null, level: number) {
+ const children = (byParent.get(parentId ?? "__root__") ?? []).sort(
+ (a, b) => {
+ const aIsGroup = a.isGroup ? 1 : 0;
+ const bIsGroup = b.isGroup ? 1 : 0;
+ if (aIsGroup !== bIsGroup) return aIsGroup - bIsGroup;
+ if (a.id === NET_INCOME_ACCOUNT_ID) return 1;
+ if (b.id === NET_INCOME_ACCOUNT_ID) return -1;
+ return (a.name ?? "").localeCompare(b.name ?? "");
+ }
+ );
+ for (const account of children) {
+ const childAccounts = byParent.get(account.id) ?? [];
+ const childIds = childAccounts.map((c) => c.id);
+ result.push({
+ id: account.id,
+ parentId: parentId ?? undefined,
+ children: childIds,
+ hasChildren: childIds.length > 0,
+ level,
+ data: account
+ });
+ walk(account.id, level + 1);
+ }
+ }
+
+ walk(null, 0);
+ return result;
+}
+
+// Search filter: keep matched accounts plus all their ancestors so the tree
+// path to a match stays visible.
+export function filterAccounts<T extends ReportAccountNode>(
+ accounts: T[],
+ search: string
+): T[] {
+ if (!search.trim()) return accounts;
+ const lower = search.toLowerCase();
+
+ const byId = new Map(accounts.map((a) => [a.id, a]));
+ const matched = new Set<string>();
+
+ for (const a of accounts) {
+ const nameMatch = a.name?.toLowerCase().includes(lower);
+ const numberMatch = a.number?.toLowerCase().includes(lower);
+ if (nameMatch || numberMatch) {
+ matched.add(a.id);
+ let parentId = a.parentId;
+ while (parentId) {
+ matched.add(parentId);
+ const parent = byId.get(parentId);
+ parentId = parent?.parentId ?? null;
+ }
+ }
+ }
+
+ return accounts.filter((a) => matched.has(a.id));
+}
+
+/** Normal-debit accounts: positive balance = debit */
+export function isNormalDebit(
+ accountClass: string | null | undefined
+): boolean {
+ return accountClass === "Asset" || accountClass === "Expense";
+}
+
+/**
+ * Split net change into debit and credit based on account class.
+ * Normal-debit accounts (Asset, Expense): positive netChange = debit
+ * Normal-credit accounts (Liability, Equity, Revenue): positive netChange = credit
+ */
+export function getDebitCredit(
+ netChange: number,
+ accountClass: string | null | undefined
+): { debit: number; credit: number } {
+ if (netChange === 0) return { debit: 0, credit: 0 };
+
+ if (isNormalDebit(accountClass)) {
+ return netChange > 0
+ ? { debit: netChange, credit: 0 }
+ : { debit: 0, credit: Math.abs(netChange) };
+ }
+ // Normal credit accounts
+ return netChange > 0
+ ? { debit: 0, credit: netChange }
+ : { debit: Math.abs(netChange), credit: 0 };
+}
diff --git a/apps/erp/app/modules/accounting/ui/useAccountingSubmodules.tsx b/apps/erp/app/modules/accounting/ui/useAccountingSubmodules.tsx
index 4cae985182..2f45e83118 100644
--- a/apps/erp/app/modules/accounting/ui/useAccountingSubmodules.tsx
+++ b/apps/erp/app/modules/accounting/ui/useAccountingSubmodules.tsx
@@ -14,25 +14,13 @@ import {
LuFileSpreadsheet,
LuHandCoins,
LuLayers,
- LuScale,
- LuSheet,
- LuTrendingUp
+ LuSheet
} from "react-icons/lu";
-import { usePermissions, useRouteData, useSettings } from "~/hooks";
+import { usePermissions, useRouteData } from "~/hooks";
import type { AuthenticatedRouteGroup, Role } from "~/types";
import { path } from "~/utils/path";
const multiCompanyRoutes = new Set<string>([path.to.intercompany]);
-const accountingOnlyRoutes = new Set<string>([
- path.to.balanceSheet,
- path.to.incomeStatement,
- path.to.trialBalance,
- path.to.intercompany,
- path.to.accountingJournals,
- path.to.accountingPeriods,
- path.to.fixedAssets,
- path.to.depreciationRuns
-]);
export default function useAccountingSubmodules() {
const { t } = useLingui();
@@ -42,20 +30,8 @@ export default function useAccountingSubmodules() {
name: t`Reports`,
routes: [
{
- name: t`Balance Sheet`,
- to: path.to.balanceSheet,
- role: "employee",
- icon: <LuScale />
- },
- {
- name: t`Income Statement`,
- to: path.to.incomeStatement,
- role: "employee",
- icon: <LuTrendingUp />
- },
- {
- name: t`Trial Balance`,
- to: path.to.trialBalance,
+ name: t`Reporting`,
+ to: path.to.reports,
role: "employee",
icon: <LuFileSpreadsheet />
}
@@ -159,8 +135,6 @@ export default function useAccountingSubmodules() {
[t]
);
- const settings = useSettings();
- const accountingEnabled = (settings as any).accountingEnabled ?? false;
const permissions = usePermissions();
const routeData = useRouteData<{ hasMultipleCompanies: boolean }>(
path.to.accounting
@@ -170,7 +144,6 @@ export default function useAccountingSubmodules() {
const isRouteVisible = (route: { to: string; role?: string }) => {
if (route.role && !permissions.is(route.role as Role)) return false;
if (!hasMultipleCompanies && multiCompanyRoutes.has(route.to)) return false;
- if (!accountingEnabled && accountingOnlyRoutes.has(route.to)) return false;
return true;
};
diff --git a/apps/erp/app/modules/inventory/ui/useInventorySubmodules.tsx b/apps/erp/app/modules/inventory/ui/useInventorySubmodules.tsx
index 61fe6e5813..7d45f2862a 100644
--- a/apps/erp/app/modules/inventory/ui/useInventorySubmodules.tsx
+++ b/apps/erp/app/modules/inventory/ui/useInventorySubmodules.tsx
@@ -2,7 +2,6 @@ import { useLingui } from "@lingui/react/macro";
import {
LuArrowDownUp,
LuArrowRightLeft,
- LuChartBar,
LuClipboardCheck,
LuClipboardList,
LuHandCoins,
@@ -101,19 +100,7 @@ export default function useInventorySubmodules() {
to: path.to.traceability,
role: "employee",
icon: <LuNetwork />
- },
- // Valuation exposes unit costs and GL balances — gated on accounting
- // view, not just the employee role (spec: grill Q6).
- ...(permissions.can("view", "accounting")
- ? [
- {
- name: t`Valuation`,
- to: path.to.inventoryValuation,
- role: "employee" as const,
- icon: <LuChartBar />
- }
- ]
- : [])
+ }
]
},
{
diff --git a/apps/erp/app/modules/invoicing/index.ts b/apps/erp/app/modules/invoicing/index.ts
index 21ecd36e6f..50f5d7a9a2 100644
--- a/apps/erp/app/modules/invoicing/index.ts
+++ b/apps/erp/app/modules/invoicing/index.ts
@@ -1,4 +1,5 @@
export * from "./invoicing.models";
+export * from "./invoicing.reports";
export * from "./invoicing.service";
export * from "./types";
export * from "./ui";
diff --git a/apps/erp/app/modules/invoicing/invoicing.reports.test.ts b/apps/erp/app/modules/invoicing/invoicing.reports.test.ts
new file mode 100644
index 0000000000..07e56fc1ea
--- /dev/null
+++ b/apps/erp/app/modules/invoicing/invoicing.reports.test.ts
@@ -0,0 +1,90 @@
+import { parseDate } from "@internationalized/date";
+import { describe, expect, it } from "vitest";
+import { aggregateSpend, previousPeriod } from "./invoicing.reports";
+
+describe("previousPeriod", () => {
+ it("returns the equal-length window immediately before the range", () => {
+ // Jan 1–31 (31 days) → the 31 days before it: Dec 1–31.
+ expect(previousPeriod("2026-01-01", "2026-01-31")).toEqual({
+ previousStart: "2025-12-01",
+ previousEnd: "2025-12-31"
+ });
+ });
+
+ it("handles a single-day range", () => {
+ expect(previousPeriod("2026-03-15", "2026-03-15")).toEqual({
+ previousStart: "2026-03-14",
+ previousEnd: "2026-03-14"
+ });
+ });
+
+ it("spans month/year boundaries: previous window ends the day before, same length", () => {
+ const start = "2026-02-01";
+ const end = "2026-07-31";
+ const { previousStart, previousEnd } = previousPeriod(start, end);
+ // Ends the day before the range starts...
+ expect(previousEnd).toBe("2026-01-31");
+ // ...and is exactly as long as the selected range.
+ expect(parseDate(previousEnd).compare(parseDate(previousStart))).toBe(
+ parseDate(end).compare(parseDate(start))
+ );
+ });
+});
+
+describe("aggregateSpend", () => {
+ const start = "2026-01-01";
+ const end = "2026-01-31";
+ const prevStart = "2025-12-01";
+ const prevEnd = "2025-12-31";
+
+ const run = (
+ rows: { partyId: string | null; totalAmount: number | null; date: string }[]
+ ) => aggregateSpend(rows, start, end, prevStart, prevEnd);
+
+ it("buckets amounts into the current and previous windows", () => {
+ const result = run([
+ { partyId: "c1", totalAmount: 100, date: "2026-01-10" },
+ { partyId: "c1", totalAmount: 50, date: "2026-01-20" },
+ { partyId: "c1", totalAmount: 120, date: "2025-12-15" }
+ ]);
+ expect(result).toEqual([
+ { partyId: "c1", total: 150, previousTotal: 120, variance: 25 }
+ ]);
+ });
+
+ it("marks a party with no prior basis as null variance (new)", () => {
+ const result = run([
+ { partyId: "c1", totalAmount: 200, date: "2026-01-05" }
+ ]);
+ expect(result[0]?.variance).toBeNull();
+ });
+
+ it("computes a negative variance when spend drops", () => {
+ const result = run([
+ { partyId: "c1", totalAmount: 40, date: "2026-01-05" },
+ { partyId: "c1", totalAmount: 80, date: "2025-12-05" }
+ ]);
+ expect(result[0]?.variance).toBe(-50);
+ });
+
+ it("sorts by current-period total descending", () => {
+ const result = run([
+ { partyId: "small", totalAmount: 10, date: "2026-01-02" },
+ { partyId: "big", totalAmount: 900, date: "2026-01-02" },
+ { partyId: "mid", totalAmount: 100, date: "2026-01-02" }
+ ]);
+ expect(result.map((r) => r.partyId)).toEqual(["big", "mid", "small"]);
+ });
+
+ it("drops rows with no party or zero amount, and dates outside both windows", () => {
+ const result = run([
+ { partyId: null, totalAmount: 500, date: "2026-01-10" },
+ { partyId: "c1", totalAmount: 0, date: "2026-01-10" },
+ { partyId: "c2", totalAmount: 75, date: "2026-01-10" },
+ { partyId: "c2", totalAmount: 999, date: "2025-06-01" } // outside both windows
+ ]);
+ expect(result).toEqual([
+ { partyId: "c2", total: 75, previousTotal: 0, variance: null }
+ ]);
+ });
+});
diff --git a/apps/erp/app/modules/invoicing/invoicing.reports.ts b/apps/erp/app/modules/invoicing/invoicing.reports.ts
new file mode 100644
index 0000000000..6ab00a5892
--- /dev/null
+++ b/apps/erp/app/modules/invoicing/invoicing.reports.ts
@@ -0,0 +1,79 @@
+import { parseDate } from "@internationalized/date";
+
+// Pure aggregation for the spend-by-party reports (Revenue by Customer /
+// Expenses by Supplier). Kept dependency-light (only calendar math) so it can be
+// unit-tested without pulling in the whole service graph — mirrors the
+// accounting module's `executivePnl.ts`.
+
+export type SpendByPartyRow = {
+ /** Customer or supplier id (null-party invoices are dropped upstream). */
+ partyId: string;
+ /** Total for the selected period, in the invoice document currency. */
+ total: number;
+ /** Total for the immediately-preceding equal-length period. */
+ previousTotal: number;
+ /**
+ * Percentage change vs. the previous period, or null when there is no prior
+ * basis (the party had no invoices last period).
+ */
+ variance: number | null;
+};
+
+/**
+ * The equal-length period immediately preceding [startDate, endDate]. Both are
+ * inclusive `YYYY-MM-DD` calendar dates, so the previous window is the same span
+ * of days ending the day before startDate.
+ */
+export function previousPeriod(startDate: string, endDate: string) {
+ const start = parseDate(startDate);
+ const end = parseDate(endDate);
+ // Inclusive day span between the two ends (CalendarDate.compare = day diff).
+ const spanDays = end.compare(start);
+ const previousEnd = start.subtract({ days: 1 });
+ const previousStart = previousEnd.subtract({ days: spanDays });
+ return {
+ previousStart: previousStart.toString(),
+ previousEnd: previousEnd.toString()
+ };
+}
+
+/**
+ * Fold invoice rows into one row per party, splitting amounts between the
+ * selected window and the previous window, and deriving a period-over-period
+ * variance. Rows are `YYYY-MM-DD`-keyed, so plain string comparison bounds the
+ * windows. Sorted by current-period total, descending.
+ */
+export function aggregateSpend(
+ rows: { partyId: string | null; totalAmount: number | null; date: string }[],
+ startDate: string,
+ endDate: string,
+ previousStart: string,
+ previousEnd: string
+): SpendByPartyRow[] {
+ const byParty = new Map<string, { total: number; previousTotal: number }>();
+ for (const row of rows) {
+ if (!row.partyId) continue;
+ const amount = Number(row.totalAmount ?? 0);
+ if (!amount) continue;
+ const entry = byParty.get(row.partyId) ?? { total: 0, previousTotal: 0 };
+ if (row.date >= startDate && row.date <= endDate) {
+ entry.total += amount;
+ } else if (row.date >= previousStart && row.date <= previousEnd) {
+ entry.previousTotal += amount;
+ }
+ byParty.set(row.partyId, entry);
+ }
+
+ return [...byParty.entries()]
+ .map(([partyId, { total, previousTotal }]) => ({
+ partyId,
+ total,
+ previousTotal,
+ variance:
+ previousTotal === 0
+ ? null
+ : ((total - previousTotal) / Math.abs(previousTotal)) * 100
+ }))
+ .filter((row) => row.total !== 0 || row.previousTotal !== 0)
+ .sort((a, b) => b.total - a.total);
+}
diff --git a/apps/erp/app/modules/invoicing/ui/Workbench/ARAPWorkbench.tsx b/apps/erp/app/modules/invoicing/ui/Workbench/ARAPWorkbench.tsx
index c6c2b2a80e..c137c85090 100644
--- a/apps/erp/app/modules/invoicing/ui/Workbench/ARAPWorkbench.tsx
+++ b/apps/erp/app/modules/invoicing/ui/Workbench/ARAPWorkbench.tsx
@@ -78,6 +78,9 @@ type ARAPWorkbenchProps = {
asOfDate: string;
agingMethod: "dueDate" | "documentDate";
bucketDays: [number, number, number];
+ // Overrides the table title. Defaults to Receivables/Payables (the invoicing
+ // workbench); the aging reports pass "AR Aging" / "AP Aging".
+ title?: string;
};
// A counterparty (root) row carries the aging buckets; an invoice (child) row
@@ -101,7 +104,8 @@ export function ARAPWorkbench({
open,
asOfDate,
agingMethod,
- bucketDays
+ bucketDays,
+ title
}: ARAPWorkbenchProps) {
const { t } = useLingui();
const [, setParams] = useUrlParams();
@@ -546,7 +550,7 @@ export function ARAPWorkbench({
data={displayRows}
columns={columns}
count={displayRows.length}
- title={side === "ar" ? t`Receivables` : t`Payables`}
+ title={title ?? (side === "ar" ? t`Receivables` : t`Payables`)}
primaryAction={filters}
defaultColumnPinning={{ left: ["Select", "counterparty"] }}
/>
diff --git a/apps/erp/app/routes/api+/accounting.analytics-lines.ts b/apps/erp/app/routes/api+/accounting.analytics-lines.ts
new file mode 100644
index 0000000000..edfc7b8a5a
--- /dev/null
+++ b/apps/erp/app/routes/api+/accounting.analytics-lines.ts
@@ -0,0 +1,100 @@
+import { requirePermissions } from "@carbon/auth/auth.server";
+import type { LoaderFunctionArgs } from "react-router";
+import type { PivotState } from "~/modules/accounting";
+import {
+ analyticsReportKeys,
+ analyticsReports,
+ getDimensionPivotLines,
+ getScrapAccountIds,
+ pivotStateValidator
+} from "~/modules/accounting";
+
+/**
+ * Fetcher endpoint for the analytics pivot drill-through drawer
+ * (analytics.$reportKey.tsx). Returns the journal lines behind one pivot cell.
+ *
+ * Query params (written by the analytics report route via
+ * path.to.api.analyticsReportLines):
+ * - reportKey — one of analyticsReportKeys
+ * - startDate / endDate — YYYY-MM-DD report range (required)
+ * - filters — JSON-encoded [{ dimensionId, valueIds }] (optional)
+ * - accounts — comma-separated account ids narrowing the scope (optional)
+ * - r1d / r1 / r1null=1 — row dimension 1 id + value id; r1null (with no r1)
+ * means the Unassigned bucket — the dimension is sent
+ * to the RPC without a value. Omitting r1d leaves the
+ * axis unconstrained (row totals, parent cells).
+ * - r2d / r2 / r2null=1 — same for row dimension 2
+ * - cold / colv / colvnull=1 — column dimension id + value (dimension axis)
+ * - colstart / colend — period column bounds (period axis)
+ */
+export async function loader({ request }: LoaderFunctionArgs) {
+ const { client, companyId, companyGroupId } = await requirePermissions(
+ request,
+ {
+ view: "accounting",
+ role: "employee"
+ }
+ );
+
+ const url = new URL(request.url);
+ const searchParams = url.searchParams;
+
+ const reportKey = analyticsReportKeys.find(
+ (key) => key === searchParams.get("reportKey")
+ );
+ if (!reportKey) {
+ throw new Response("Not found", { status: 404 });
+ }
+ const report = analyticsReports[reportKey];
+
+ const startDate = searchParams.get("startDate");
+ const endDate = searchParams.get("endDate");
+ if (!startDate || !endDate) {
+ throw new Response("Bad request", { status: 400 });
+ }
+
+ let filters: PivotState["filters"] = [];
+ const filtersParam = searchParams.get("filters");
+ if (filtersParam) {
+ try {
+ const parsed = pivotStateValidator.shape.filters.safeParse(
+ JSON.parse(filtersParam)
+ );
+ if (parsed.success) filters = parsed.data;
+ } catch {
+ // Malformed filters param — ignore it rather than 500
+ }
+ }
+
+ let scrapAccountIds: string[] | undefined;
+ if ("source" in report.accountScope) {
+ scrapAccountIds = (await getScrapAccountIds(client, companyId)).data;
+ }
+
+ const optional = (name: string) => searchParams.get(name) ?? undefined;
+
+ const lines = await getDimensionPivotLines(client, {
+ companyId,
+ companyGroupId,
+ report,
+ scrapAccountIds,
+ startDate,
+ endDate,
+ filters,
+ rowDimension1: optional("r1d"),
+ rowValue1: optional("r1"),
+ rowValue1IsNull: searchParams.get("r1null") === "1",
+ rowDimension2: optional("r2d"),
+ rowValue2: optional("r2"),
+ rowValue2IsNull: searchParams.get("r2null") === "1",
+ columnDimension: optional("cold"),
+ columnValue: optional("colv"),
+ columnValueIsNull: searchParams.get("colvnull") === "1",
+ columnPeriodStart: optional("colstart"),
+ columnPeriodEnd: optional("colend"),
+ accountIds: searchParams.get("accounts")?.split(",").filter(Boolean) ?? []
+ });
+
+ // The drawer shows its empty state rather than a route error boundary
+ return { lines: lines.data ?? [] };
+}
diff --git a/apps/erp/app/routes/api+/accounting.purchase-lines.ts b/apps/erp/app/routes/api+/accounting.purchase-lines.ts
new file mode 100644
index 0000000000..015d03afea
--- /dev/null
+++ b/apps/erp/app/routes/api+/accounting.purchase-lines.ts
@@ -0,0 +1,65 @@
+import { requirePermissions } from "@carbon/auth/auth.server";
+import type { LoaderFunctionArgs } from "react-router";
+import { getPurchaseLinePivotLines } from "~/modules/accounting";
+
+/**
+ * Fetcher endpoint for the Purchases pivot drill-through drawer
+ * (purchases.tsx). Returns the purchase invoice lines behind one pivot cell.
+ *
+ * Query params (written by the purchases report route via
+ * path.to.api.purchasesReportLines):
+ * - startDate / endDate — YYYY-MM-DD report range (required)
+ * - r1f / r1 / r1null=1 — row field 1 key + value; r1null (no r1) is the
+ * Unassigned bucket (field IS NULL). Omitting r1f
+ * leaves the axis unconstrained (row totals / parents).
+ * - r2f / r2 / r2null=1 — same for row field 2
+ * - colf / colv / colvnull=1 — column field key + value (field axis)
+ * - colstart / colend — period column bounds (period axis)
+ */
+export async function loader({ request }: LoaderFunctionArgs) {
+ const { client, companyId } = await requirePermissions(request, {
+ view: "accounting",
+ role: "employee"
+ });
+
+ const searchParams = new URL(request.url).searchParams;
+
+ const startDate = searchParams.get("startDate");
+ const endDate = searchParams.get("endDate");
+ if (!startDate || !endDate) {
+ throw new Response("Bad request", { status: 400 });
+ }
+
+ const optional = (name: string) => searchParams.get(name) ?? undefined;
+
+ // A field is sent only when that axis is constrained (a value, or the
+ // Unassigned bucket). r1null without r1 → send the field, omit the value.
+ const rowField1 =
+ searchParams.get("r1null") === "1" || optional("r1")
+ ? optional("r1f")
+ : undefined;
+ const rowField2 =
+ searchParams.get("r2null") === "1" || optional("r2")
+ ? optional("r2f")
+ : undefined;
+ const columnField =
+ searchParams.get("colvnull") === "1" || optional("colv")
+ ? optional("colf")
+ : undefined;
+
+ const lines = await getPurchaseLinePivotLines(client, {
+ companyId,
+ startDate,
+ endDate,
+ rowField1,
+ rowValue1: optional("r1"),
+ rowField2,
+ rowValue2: optional("r2"),
+ columnField,
+ columnValue: optional("colv"),
+ columnPeriodStart: optional("colstart"),
+ columnPeriodEnd: optional("colend")
+ });
+
+ return { lines: lines.data ?? [] };
+}
diff --git a/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json b/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json
index ffc1d3c601..b2b92bd6f1 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-08-09T00:18:51.796Z",
- "totalTools": 1416,
+ "generated": "2026-08-10T02:45:42.644Z",
+ "totalTools": 1431,
"modules": 15,
"tools": [
{
@@ -493,6 +493,533 @@
]
}
},
+ {
+ "name": "accounting_getAccountPeriodSeries",
+ "module": "accounting",
+ "classification": "READ",
+ "description": "get account period series",
+ "paramCount": 2,
+ "serviceParams": [
+ "client",
+ "companyGroupId",
+ "companyId",
+ "args"
+ ],
+ "injectAuth": [
+ "companyId"
+ ],
+ "schema": {
+ "type": "object",
+ "properties": {
+ "start": {
+ "type": "string"
+ },
+ "periodEnds": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ }
+ },
+ "required": [
+ "start",
+ "periodEnds"
+ ]
+ }
+ },
+ {
+ "name": "accounting_translateCompanyPeriodSeries",
+ "module": "accounting",
+ "classification": "WRITE",
+ "description": "translate company period series",
+ "paramCount": 3,
+ "serviceParams": [
+ "client",
+ "companyGroupId",
+ "companyId",
+ "targetCurrency",
+ "buckets",
+ "series"
+ ],
+ "injectAuth": [
+ "companyId"
+ ],
+ "schema": {
+ "type": "object",
+ "properties": {
+ "targetCurrency": {
+ "type": "string"
+ },
+ "buckets": {
+ "type": "array",
+ "items": {}
+ },
+ "series": {}
+ },
+ "required": [
+ "targetCurrency",
+ "buckets",
+ "series"
+ ]
+ }
+ },
+ {
+ "name": "accounting_getFinancialStatementPeriodSeries",
+ "module": "accounting",
+ "classification": "READ",
+ "description": "get financial statement period series",
+ "paramCount": 3,
+ "serviceParams": [
+ "client",
+ "companyGroupId",
+ "companyId",
+ "args"
+ ],
+ "injectAuth": [
+ "companyId"
+ ],
+ "schema": {
+ "type": "object",
+ "properties": {
+ "buckets": {
+ "type": "array",
+ "items": {}
+ },
+ "includeCurrentYearEarnings": {
+ "type": "boolean"
+ },
+ "translate": {
+ "type": "object",
+ "properties": {
+ "targetCurrency": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "targetCurrency"
+ ]
+ }
+ },
+ "required": [
+ "buckets"
+ ]
+ }
+ },
+ {
+ "name": "accounting_getConsolidatedPeriodSeries",
+ "module": "accounting",
+ "classification": "READ",
+ "description": "get consolidated period series",
+ "paramCount": 3,
+ "serviceParams": [
+ "client",
+ "companyGroupId",
+ "companyIds",
+ "targetCurrency",
+ "args"
+ ],
+ "injectAuth": [
+ "companyId"
+ ],
+ "schema": {
+ "type": "object",
+ "properties": {
+ "companyIds": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ },
+ "targetCurrency": {
+ "type": "string"
+ },
+ "args": {
+ "type": "object",
+ "properties": {
+ "buckets": {
+ "type": "array",
+ "items": {}
+ }
+ },
+ "required": [
+ "buckets"
+ ]
+ }
+ },
+ "required": [
+ "companyIds",
+ "targetCurrency",
+ "args"
+ ]
+ }
+ },
+ {
+ "name": "accounting_getReportPins",
+ "module": "accounting",
+ "classification": "READ",
+ "description": "get report pins",
+ "paramCount": 0,
+ "serviceParams": [
+ "client",
+ "userId",
+ "companyId"
+ ],
+ "injectAuth": [
+ "companyId"
+ ],
+ "schema": {
+ "type": "object",
+ "properties": {}
+ }
+ },
+ {
+ "name": "accounting_upsertReportPin",
+ "module": "accounting",
+ "classification": "WRITE",
+ "description": "upsert report pin",
+ "paramCount": 2,
+ "serviceParams": [
+ "client",
+ "args"
+ ],
+ "injectAuth": [
+ "companyId",
+ "createdBy",
+ "updatedBy"
+ ],
+ "schema": {
+ "type": "object",
+ "properties": {
+ "reportKey": {
+ "type": "string"
+ },
+ "pinned": {
+ "type": "boolean"
+ }
+ },
+ "required": [
+ "reportKey",
+ "pinned"
+ ]
+ }
+ },
+ {
+ "name": "accounting_getAccountsInScope",
+ "module": "accounting",
+ "classification": "READ",
+ "description": "get accounts in scope",
+ "paramCount": 2,
+ "serviceParams": [
+ "client",
+ "companyGroupId",
+ "scope",
+ "scrapAccountIds"
+ ],
+ "injectAuth": [
+ "companyId"
+ ],
+ "schema": {
+ "type": "object",
+ "properties": {
+ "scope": {},
+ "scrapAccountIds": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ }
+ },
+ "required": [
+ "scope"
+ ]
+ }
+ },
+ {
+ "name": "accounting_getDimensionPivot",
+ "module": "accounting",
+ "classification": "READ",
+ "description": "get dimension pivot",
+ "paramCount": 6,
+ "serviceParams": [
+ "client",
+ "args"
+ ],
+ "injectAuth": [
+ "companyId"
+ ],
+ "schema": {
+ "type": "object",
+ "properties": {
+ "report": {},
+ "scrapAccountIds": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ },
+ "startDate": {
+ "type": "string"
+ },
+ "endDate": {
+ "type": "string"
+ },
+ "periodEnds": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ },
+ "state": {}
+ },
+ "required": [
+ "report",
+ "startDate",
+ "endDate",
+ "state"
+ ]
+ }
+ },
+ {
+ "name": "accounting_getDimensionPivotLines",
+ "module": "accounting",
+ "classification": "READ",
+ "description": "get dimension pivot lines",
+ "paramCount": 17,
+ "serviceParams": [
+ "client",
+ "args"
+ ],
+ "injectAuth": [
+ "companyId"
+ ],
+ "schema": {
+ "type": "object",
+ "properties": {
+ "report": {},
+ "scrapAccountIds": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ },
+ "startDate": {
+ "type": "string"
+ },
+ "endDate": {
+ "type": "string"
+ },
+ "filters": {},
+ "rowDimension1": {
+ "type": "string"
+ },
+ "rowValue1": {
+ "type": "string"
+ },
+ "rowValue1IsNull": {
+ "type": "boolean"
+ },
+ "rowDimension2": {
+ "type": "string"
+ },
+ "rowValue2": {
+ "type": "string"
+ },
+ "rowValue2IsNull": {
+ "type": "boolean"
+ },
+ "columnDimension": {
+ "type": "string"
+ },
+ "columnValue": {
+ "type": "string"
+ },
+ "columnValueIsNull": {
+ "type": "boolean"
+ },
+ "columnPeriodStart": {
+ "type": "string"
+ },
+ "columnPeriodEnd": {
+ "type": "string"
+ },
+ "accountIds": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ }
+ },
+ "required": [
+ "report",
+ "startDate",
+ "endDate",
+ "filters"
+ ]
+ }
+ },
+ {
+ "name": "accounting_getPurchaseLinePivot",
+ "module": "accounting",
+ "classification": "READ",
+ "description": "get purchase line pivot",
+ "paramCount": 4,
+ "serviceParams": [
+ "client",
+ "args"
+ ],
+ "injectAuth": [
+ "companyId"
+ ],
+ "schema": {
+ "type": "object",
+ "properties": {
+ "startDate": {
+ "type": "string"
+ },
+ "endDate": {
+ "type": "string"
+ },
+ "periodEnds": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ },
+ "state": {}
+ },
+ "required": [
+ "startDate",
+ "endDate",
+ "state"
+ ]
+ }
+ },
+ {
+ "name": "accounting_getPurchaseLinePivotLines",
+ "module": "accounting",
+ "classification": "READ",
+ "description": "get purchase line pivot lines",
+ "paramCount": 10,
+ "serviceParams": [
+ "client",
+ "args"
+ ],
+ "injectAuth": [
+ "companyId"
+ ],
+ "schema": {
+ "type": "object",
+ "properties": {
+ "startDate": {
+ "type": "string"
+ },
+ "endDate": {
+ "type": "string"
+ },
+ "rowField1": {
+ "type": "string"
+ },
+ "rowValue1": {
+ "type": "string"
+ },
+ "rowField2": {
+ "type": "string"
+ },
+ "rowValue2": {
+ "type": "string"
+ },
+ "columnField": {
+ "type": "string"
+ },
+ "columnValue": {
+ "type": "string"
+ },
+ "columnPeriodStart": {
+ "type": "string"
+ },
+ "columnPeriodEnd": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "startDate",
+ "endDate"
+ ]
+ }
+ },
+ {
+ "name": "accounting_getReportViews",
+ "module": "accounting",
+ "classification": "READ",
+ "description": "get report views",
+ "paramCount": 1,
+ "serviceParams": [
+ "client",
+ "args"
+ ],
+ "injectAuth": [
+ "companyId"
+ ],
+ "schema": {
+ "type": "object",
+ "properties": {
+ "reportKey": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ {
+ "name": "accounting_upsertReportView",
+ "module": "accounting",
+ "classification": "WRITE",
+ "description": "upsert report view",
+ "paramCount": 1,
+ "serviceParams": [
+ "client",
+ "view"
+ ],
+ "injectAuth": [
+ "companyId",
+ "createdBy",
+ "updatedBy"
+ ],
+ "schema": {
+ "type": "object",
+ "properties": {
+ "view": {}
+ },
+ "required": [
+ "view"
+ ]
+ }
+ },
+ {
+ "name": "accounting_deleteReportView",
+ "module": "accounting",
+ "classification": "DESTRUCTIVE",
+ "description": "delete report view",
+ "paramCount": 1,
+ "serviceParams": [
+ "client",
+ "id",
+ "companyId"
+ ],
+ "injectAuth": [
+ "companyId"
+ ],
+ "schema": {
+ "type": "object",
+ "properties": {
+ "id": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "id"
+ ]
+ }
+ },
{
"name": "accounting_getCompaniesInGroup",
"module": "accounting",
@@ -1425,6 +1952,24 @@
"properties": {}
}
},
+ {
+ "name": "accounting_getScrapAccountIds",
+ "module": "accounting",
+ "classification": "READ",
+ "description": "get scrap account ids",
+ "paramCount": 0,
+ "serviceParams": [
+ "client",
+ "companyId"
+ ],
+ "injectAuth": [
+ "companyId"
+ ],
+ "schema": {
+ "type": "object",
+ "properties": {}
+ }
+ },
{
"name": "accounting_getFiscalYearSettings",
"module": "accounting",
diff --git a/apps/erp/app/routes/x+/accounting+/_index.tsx b/apps/erp/app/routes/x+/accounting+/_index.tsx
index 33b3df47bc..b49f5f4c50 100644
--- a/apps/erp/app/routes/x+/accounting+/_index.tsx
+++ b/apps/erp/app/routes/x+/accounting+/_index.tsx
@@ -14,7 +14,5 @@ export async function loader({ request }: LoaderFunctionArgs) {
(companySettings.data as { accountingEnabled?: boolean } | null)
?.accountingEnabled ?? false;
- throw redirect(
- accountingEnabled ? path.to.balanceSheet : path.to.chartOfAccounts
- );
+ throw redirect(accountingEnabled ? path.to.reports : path.to.chartOfAccounts);
}
diff --git a/apps/erp/app/routes/x+/accounting+/_layout.tsx b/apps/erp/app/routes/x+/accounting+/_layout.tsx
index d1a735a5e8..c242be0260 100644
--- a/apps/erp/app/routes/x+/accounting+/_layout.tsx
+++ b/apps/erp/app/routes/x+/accounting+/_layout.tsx
@@ -12,6 +12,7 @@ import {
getBaseCurrency,
getCompaniesInGroup
} from "~/modules/accounting";
+import AccountingBetaGate from "~/modules/accounting/ui/AccountingBetaGate";
import useAccountingSubmodules from "~/modules/accounting/ui/useAccountingSubmodules";
import type { Handle } from "~/utils/handle";
import { path } from "~/utils/path";
@@ -66,8 +67,9 @@ export default function AccountingRoute() {
<CollapsibleSidebarProvider>
<div className="grid grid-cols-[auto_1fr] w-full h-full bg-card">
<GroupedContentSidebar groups={groups} />
- <VStack spacing={0} className="h-full">
+ <VStack spacing={0} className="relative h-full">
<Outlet />
+ <AccountingBetaGate />
</VStack>
</div>
</CollapsibleSidebarProvider>
diff --git a/apps/erp/app/routes/x+/accounting+/reports.tsx b/apps/erp/app/routes/x+/accounting+/reports.tsx
new file mode 100644
index 0000000000..17becf8298
--- /dev/null
+++ b/apps/erp/app/routes/x+/accounting+/reports.tsx
@@ -0,0 +1,568 @@
+import { assertIsPost, error } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import { validationError, validator } from "@carbon/form";
+import {
+ Badge,
+ cn,
+ IconButton,
+ Input,
+ InputGroup,
+ InputLeftElement
+} from "@carbon/react";
+import { msg } from "@lingui/core/macro";
+import { Trans, useLingui } from "@lingui/react/macro";
+import type { ReactNode } from "react";
+import { useMemo, useState } from "react";
+import type { IconType } from "react-icons";
+import {
+ LuArrowUpDown,
+ LuBanknote,
+ LuBookmark,
+ LuBoxes,
+ LuBriefcase,
+ LuFileSpreadsheet,
+ LuHandCoins,
+ LuPin,
+ LuRecycle,
+ LuScale,
+ LuSearch,
+ LuTrash2,
+ LuTrendingUp,
+ LuTruck,
+ LuUsers
+} from "react-icons/lu";
+import type {
+ ActionFunctionArgs,
+ LoaderFunctionArgs,
+ MetaFunction
+} from "react-router";
+import { data, Link, useFetcher, useLoaderData } from "react-router";
+import ConfirmDelete from "~/components/Modals/ConfirmDelete";
+import {
+ getReportPins,
+ getReportViews,
+ reportPinValidator,
+ upsertReportPin
+} from "~/modules/accounting";
+import type { Handle } from "~/utils/handle";
+import { path } from "~/utils/path";
+
+export const meta: MetaFunction = () => {
+ return [{ title: "Carbon | Reports" }];
+};
+
+export const handle: Handle = {
+ breadcrumb: msg`Reports`,
+ to: path.to.reports
+};
+
+export async function loader({ request }: LoaderFunctionArgs) {
+ const { client, companyId, userId } = await requirePermissions(request, {
+ view: "accounting",
+ role: "employee"
+ });
+
+ const [pins, savedViews] = await Promise.all([
+ getReportPins(client, userId, companyId),
+ getReportViews(client, { companyId })
+ ]);
+
+ return {
+ currentUserId: userId,
+ pinOverrides: pins.data ?? [],
+ savedViews: savedViews.data ?? []
+ };
+}
+
+export async function action({ request }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, companyId, userId } = await requirePermissions(request, {
+ view: "accounting",
+ role: "employee"
+ });
+
+ const validation = await validator(reportPinValidator).validate(
+ await request.formData()
+ );
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const { reportKey, pinned } = validation.data;
+
+ const result = await upsertReportPin(client, {
+ reportKey,
+ pinned: pinned === "true",
+ userId,
+ companyId
+ });
+
+ if (result.error) {
+ return data(
+ {},
+ await flash(request, error(result.error, "Failed to update pin"))
+ );
+ }
+
+ return {};
+}
+
+type ReportDefinition = {
+ key: string;
+ name: string;
+ description: string;
+ to: string;
+ icon: IconType;
+ category: string;
+ defaultPinned: boolean;
+};
+
+type SavedView = Awaited<ReturnType<typeof loader>>["savedViews"][number];
+
+// Saved views reuse the reportPin table (free-text reportKey) via a namespaced
+// key, so pinning a view needs no separate schema. Views default to unpinned.
+const viewPinKey = (view: SavedView) => `view:${view.id}`;
+
+export default function ReportsIndexRoute() {
+ const { currentUserId, pinOverrides, savedViews } =
+ useLoaderData<typeof loader>();
+ const { t } = useLingui();
+ const [search, setSearch] = useState("");
+ const [viewPendingDelete, setViewPendingDelete] = useState<SavedView | null>(
+ null
+ );
+ const pinFetcher = useFetcher<typeof action>();
+
+ // The core financial statements default to pinned; users can pin/unpin from
+ // the cards and list rows below (persisted per user + company).
+ const reports = useMemo<ReportDefinition[]>(
+ () => [
+ {
+ key: "income-statement",
+ name: t`Income Statement`,
+ description: t`Revenue and expenses over a period`,
+ to: path.to.incomeStatement,
+ icon: LuTrendingUp,
+ category: t`Financial Statements`,
+ defaultPinned: true
+ },
+ {
+ key: "executive-pnl",
+ name: t`Executive P&L`,
+ description: t`Condensed P&L with margins and key subtotals`,
+ to: path.to.executivePnl,
+ icon: LuBriefcase,
+ category: t`Financial Statements`,
+ defaultPinned: false
+ },
+ {
+ key: "balance-sheet",
+ name: t`Balance Sheet`,
+ description: t`Assets, liabilities and equity as of a date`,
+ to: path.to.balanceSheet,
+ icon: LuScale,
+ category: t`Financial Statements`,
+ defaultPinned: true
+ },
+ {
+ key: "trial-balance",
+ name: t`Trial Balance`,
+ description: t`Account balances with debits and credits`,
+ to: path.to.trialBalance,
+ icon: LuFileSpreadsheet,
+ category: t`Close Reports`,
+ defaultPinned: true
+ },
+ {
+ key: "inventory-valuation",
+ name: t`Inventory Valuation`,
+ description: t`On-hand value by location or item, with GL tie-out`,
+ to: path.to.inventoryValuation,
+ icon: LuBoxes,
+ category: t`Close Reports`,
+ defaultPinned: false
+ },
+ {
+ key: "revenue",
+ name: t`Revenue`,
+ description: t`Slice revenue by customer, customer type, or any dimension`,
+ to: path.to.analyticsReport("revenue"),
+ icon: LuUsers,
+ category: t`Analytics`,
+ defaultPinned: false
+ },
+ {
+ key: "expenses",
+ name: t`Expenses`,
+ description: t`Slice expenses by location, cost center, or any dimension`,
+ to: path.to.analyticsReport("expenses"),
+ icon: LuTruck,
+ category: t`Analytics`,
+ defaultPinned: false
+ },
+ {
+ key: "purchases",
+ name: t`Purchases`,
+ description: t`Spend by supplier, item, or category — your biggest cost drivers`,
+ to: path.to.purchasesReport,
+ icon: LuHandCoins,
+ category: t`Analytics`,
+ defaultPinned: false
+ },
+ {
+ key: "assets",
+ name: t`Assets`,
+ description: t`Slice asset activity by location, item, or any dimension`,
+ to: path.to.analyticsReport("assets"),
+ icon: LuBanknote,
+ category: t`Analytics`,
+ defaultPinned: false
+ },
+ {
+ key: "inventory-change",
+ name: t`Inventory`,
+ description: t`What drove inventory up or down, by any dimension`,
+ to: path.to.analyticsReport("inventory-change"),
+ icon: LuArrowUpDown,
+ category: t`Analytics`,
+ defaultPinned: false
+ },
+ {
+ key: "scrap",
+ name: t`Scrap`,
+ description: t`Biggest causes of scrap by reason, item, or work center`,
+ to: path.to.analyticsReport("scrap"),
+ icon: LuRecycle,
+ category: t`Analytics`,
+ defaultPinned: false
+ },
+ {
+ key: "ar-aging",
+ name: t`AR Aging`,
+ description: t`Open receivables by customer and age`,
+ to: path.to.arAging,
+ icon: LuHandCoins,
+ category: t`Aging`,
+ defaultPinned: false
+ },
+ {
+ key: "ap-aging",
+ name: t`AP Aging`,
+ description: t`Open payables by supplier and age`,
+ to: path.to.apAging,
+ icon: LuBanknote,
+ category: t`Aging`,
+ defaultPinned: false
+ }
+ ],
+ [t]
+ );
+
+ // Persisted overrides + optimistic in-flight toggle
+ const isPinned = (report: ReportDefinition): boolean => {
+ if (
+ pinFetcher.formData &&
+ pinFetcher.formData.get("reportKey") === report.key
+ ) {
+ return pinFetcher.formData.get("pinned") === "true";
+ }
+ const override = pinOverrides.find((p) => p.reportKey === report.key);
+ return override?.pinned ?? report.defaultPinned;
+ };
+
+ const togglePin = (report: ReportDefinition, pinned: boolean) => {
+ pinFetcher.submit(
+ { reportKey: report.key, pinned: String(pinned) },
+ { method: "post", action: path.to.reports }
+ );
+ };
+
+ const isViewPinned = (view: SavedView): boolean => {
+ const key = viewPinKey(view);
+ if (pinFetcher.formData && pinFetcher.formData.get("reportKey") === key) {
+ return pinFetcher.formData.get("pinned") === "true";
+ }
+ return pinOverrides.find((p) => p.reportKey === key)?.pinned ?? false;
+ };
+
+ const toggleViewPin = (view: SavedView, pinned: boolean) => {
+ pinFetcher.submit(
+ { reportKey: viewPinKey(view), pinned: String(pinned) },
+ { method: "post", action: path.to.reports }
+ );
+ };
+
+ const filtered = useMemo(() => {
+ const lower = search.trim().toLowerCase();
+ if (!lower) return reports;
+ return reports.filter(
+ (report) =>
+ report.name.toLowerCase().includes(lower) ||
+ report.description.toLowerCase().includes(lower)
+ );
+ }, [reports, search]);
+
+ const categories = useMemo(() => {
+ const result = new Map<string, ReportDefinition[]>();
+ for (const report of filtered) {
+ const list = result.get(report.category) ?? [];
+ list.push(report);
+ result.set(report.category, list);
+ }
+ return [...result.entries()];
+ }, [filtered]);
+
+ const pinnedReports = reports.filter(isPinned);
+ const pinnedViews = savedViews.filter(isViewPinned);
+ const hasPinned = pinnedReports.length > 0 || pinnedViews.length > 0;
+
+ return (
+ <div className="h-[calc(100dvh-var(--header-height))] w-full overflow-y-auto bg-background">
+ <div className="mx-auto flex w-full max-w-6xl flex-col gap-8 p-8">
+ <div className="flex items-center justify-between gap-4">
+ <h1 className="text-2xl font-semibold tracking-tight">
+ <Trans>Reporting</Trans>
+ </h1>
+ <InputGroup size="sm" className="w-64">
+ <InputLeftElement>
+ <LuSearch className="h-4 w-4 text-muted-foreground" />
+ </InputLeftElement>
+ <Input
+ placeholder={t`Search`}
+ value={search}
+ onChange={(e) => setSearch(e.target.value)}
+ />
+ </InputGroup>
+ </div>
+
+ {hasPinned && (
+ <div>
+ <SectionHeading>
+ <LuPin className="h-3 w-3" />
+ <Trans>Pinned</Trans>
+ </SectionHeading>
+ <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 xl:grid-cols-4">
+ {pinnedReports.map((report) => (
+ <PinnedCard
+ key={report.key}
+ to={report.to}
+ icon={report.icon}
+ name={report.name}
+ pinned
+ onToggle={(next) => togglePin(report, next)}
+ pinLabel={t`Pin ${report.name}`}
+ unpinLabel={t`Unpin ${report.name}`}
+ />
+ ))}
+ {pinnedViews.map((view) => (
+ <PinnedCard
+ key={view.id}
+ to={`${path.to.analyticsReport(view.reportKey)}?view=${view.id}`}
+ icon={LuBookmark}
+ name={view.name}
+ pinned
+ onToggle={(next) => toggleViewPin(view, next)}
+ pinLabel={t`Pin ${view.name}`}
+ unpinLabel={t`Unpin ${view.name}`}
+ />
+ ))}
+ </div>
+ </div>
+ )}
+
+ {categories.map(([category, categoryReports]) => {
+ // Saved pivot views belong to a report card (by reportKey); show them
+ // directly beneath the category that hosts that card (Analytics).
+ const categoryViews = savedViews.filter((view) =>
+ categoryReports.some((report) => report.key === view.reportKey)
+ );
+ return (
+ <div key={category} className="flex flex-col gap-8">
+ <div>
+ <SectionHeading>{category}</SectionHeading>
+ <div className="overflow-hidden rounded-lg border border-border">
+ {categoryReports.map((report, index) => (
+ <Link
+ key={report.key}
+ to={report.to}
+ prefetch="intent"
+ className={
+ "flex cursor-pointer items-center gap-3 bg-card/70 px-4 py-2.5 transition-colors hover:bg-accent/40" +
+ (index > 0 ? " border-t border-border" : "")
+ }
+ >
+ <report.icon className="h-4 w-4 shrink-0 text-muted-foreground" />
+ <span className="text-sm font-medium">{report.name}</span>
+ <span className="truncate text-sm text-muted-foreground">
+ {report.description}
+ </span>
+ <span className="ml-auto">
+ <PinToggle
+ pinned={isPinned(report)}
+ onToggle={(next) => togglePin(report, next)}
+ unpinLabel={t`Unpin ${report.name}`}
+ pinLabel={t`Pin ${report.name}`}
+ />
+ </span>
+ </Link>
+ ))}
+ </div>
+ </div>
+ {categoryViews.length > 0 && (
+ <div>
+ <SectionHeading>
+ <LuBookmark className="h-3 w-3" />
+ <Trans>Saved Views</Trans>
+ </SectionHeading>
+ <div className="overflow-hidden rounded-lg border border-border">
+ {categoryViews.map((view, index) => (
+ <Link
+ key={view.id}
+ to={`${path.to.analyticsReport(view.reportKey)}?view=${view.id}`}
+ prefetch="intent"
+ className={
+ "flex cursor-pointer items-center gap-3 bg-card/70 px-4 py-2.5 transition-colors hover:bg-accent/40" +
+ (index > 0 ? " border-t border-border" : "")
+ }
+ >
+ <LuBookmark className="h-4 w-4 shrink-0 text-muted-foreground" />
+ <span className="text-sm font-medium">{view.name}</span>
+ <span className="truncate text-sm text-muted-foreground">
+ {
+ categoryReports.find(
+ (report) => report.key === view.reportKey
+ )?.name
+ }
+ </span>
+ <span className="ml-auto flex items-center gap-1">
+ {view.visibility === "Company" && (
+ <Badge variant="secondary">
+ <Trans>Shared</Trans>
+ </Badge>
+ )}
+ <PinToggle
+ pinned={isViewPinned(view)}
+ onToggle={(next) => toggleViewPin(view, next)}
+ unpinLabel={t`Unpin ${view.name}`}
+ pinLabel={t`Pin ${view.name}`}
+ />
+ {view.createdBy === currentUserId && (
+ <IconButton
+ aria-label={t`Delete ${view.name}`}
+ variant="ghost"
+ size="sm"
+ className="text-muted-foreground/50 hover:text-destructive-foreground"
+ icon={<LuTrash2 />}
+ onClick={(e) => {
+ e.preventDefault();
+ e.stopPropagation();
+ setViewPendingDelete(view);
+ }}
+ />
+ )}
+ </span>
+ </Link>
+ ))}
+ </div>
+ </div>
+ )}
+ </div>
+ );
+ })}
+
+ {filtered.length === 0 && (
+ <p className="text-sm text-muted-foreground">
+ <Trans>No reports match your search.</Trans>
+ </p>
+ )}
+ </div>
+ {viewPendingDelete && (
+ <ConfirmDelete
+ action={path.to.deleteReportView(viewPendingDelete.id)}
+ name={viewPendingDelete.name}
+ text={t`Are you sure you want to delete the "${viewPendingDelete.name}" view? This cannot be undone.`}
+ onCancel={() => setViewPendingDelete(null)}
+ onSubmit={() => setViewPendingDelete(null)}
+ />
+ )}
+ </div>
+ );
+}
+
+// A pinned item (report or saved view) rendered as a card in the Pinned grid.
+const PinnedCard = ({
+ to,
+ icon: Icon,
+ name,
+ pinned,
+ onToggle,
+ pinLabel,
+ unpinLabel
+}: {
+ to: string;
+ icon: IconType;
+ name: string;
+ pinned: boolean;
+ onToggle: (pinned: boolean) => void;
+ pinLabel: string;
+ unpinLabel: string;
+}) => (
+ <Link
+ to={to}
+ prefetch="intent"
+ className="group flex cursor-pointer items-center justify-between gap-4 rounded-lg border border-border bg-card/70 p-4 backdrop-blur-md transition-colors duration-200 hover:border-foreground/20 hover:bg-accent/40"
+ >
+ <span className="flex items-center gap-3 overflow-hidden">
+ <span className="shrink-0 rounded-lg border border-border p-2.5 transition-colors group-hover:border-foreground/20">
+ <Icon className="text-xl" />
+ </span>
+ <span className="truncate text-sm font-medium tracking-tight">
+ {name}
+ </span>
+ </span>
+ <PinToggle
+ pinned={pinned}
+ onToggle={onToggle}
+ pinLabel={pinLabel}
+ unpinLabel={unpinLabel}
+ />
+ </Link>
+);
+
+// Sits inside the card/row Link, so it must not trigger navigation. Pinned
+// shows a solid pin; unpinned shows a muted pin that fills in on hover.
+const PinToggle = ({
+ pinned,
+ onToggle,
+ pinLabel,
+ unpinLabel
+}: {
+ pinned: boolean;
+ onToggle: (pinned: boolean) => void;
+ pinLabel: string;
+ unpinLabel: string;
+}) => (
+ <IconButton
+ aria-label={pinned ? unpinLabel : pinLabel}
+ variant="ghost"
+ size="sm"
+ className={cn(
+ pinned
+ ? "text-foreground"
+ : "text-muted-foreground/50 hover:text-foreground"
+ )}
+ icon={<LuPin />}
+ onClick={(e) => {
+ e.preventDefault();
+ e.stopPropagation();
+ onToggle(!pinned);
+ }}
+ />
+);
+
+const SectionHeading = ({ children }: { children: ReactNode }) => (
+ <div className="mb-3 flex items-center gap-1.5 text-xs font-medium uppercase tracking-wide text-muted-foreground">
+ {children}
+ </div>
+);
diff --git a/apps/erp/app/routes/x+/get-started+/_layout.tsx b/apps/erp/app/routes/x+/get-started+/_layout.tsx
index 6db4a232cd..a6c9b927a7 100644
--- a/apps/erp/app/routes/x+/get-started+/_layout.tsx
+++ b/apps/erp/app/routes/x+/get-started+/_layout.tsx
@@ -249,7 +249,7 @@ export default function GetStartedLayout() {
return (
<CollapsibleSidebarProvider>
- <div className="grid grid-cols-[auto_1fr] grid-rows-[minmax(0,1fr)] w-full h-full overflow-hidden">
+ <div className="bg-card grid grid-cols-[auto_1fr] grid-rows-[minmax(0,1fr)] w-full h-full overflow-hidden">
<GroupedContentSidebar groups={groups} exactMatch />
<div className="relative min-w-0 overflow-hidden">
<div ref={scrollRef} className="relative z-10 h-full overflow-y-auto">
diff --git a/apps/erp/app/routes/x+/reports+/_index.tsx b/apps/erp/app/routes/x+/reports+/_index.tsx
new file mode 100644
index 0000000000..a68a383b97
--- /dev/null
+++ b/apps/erp/app/routes/x+/reports+/_index.tsx
@@ -0,0 +1,14 @@
+import { requirePermissions } from "@carbon/auth/auth.server";
+import type { LoaderFunctionArgs } from "react-router";
+import { redirect } from "react-router";
+import { path } from "~/utils/path";
+
+// The reports hub lives inside the accounting module (with its sidebar);
+// this namespace only hosts the full-screen report pages.
+export async function loader({ request }: LoaderFunctionArgs) {
+ await requirePermissions(request, {
+ view: "accounting",
+ role: "employee"
+ });
+ throw redirect(path.to.reports);
+}
diff --git a/apps/erp/app/routes/x+/reports+/_layout.tsx b/apps/erp/app/routes/x+/reports+/_layout.tsx
new file mode 100644
index 0000000000..4b761611b1
--- /dev/null
+++ b/apps/erp/app/routes/x+/reports+/_layout.tsx
@@ -0,0 +1,29 @@
+import { msg } from "@lingui/core/macro";
+import { Outlet } from "react-router";
+import type { BreadcrumbSegment, Handle } from "~/utils/handle";
+import { path } from "~/utils/path";
+
+export const handle: Handle = {
+ // Report pages live in their own full-screen namespace, not under the
+ // accounting module layout, so surface the full Accounting > Reports trail
+ // here rather than just "Reports".
+ breadcrumb: (): BreadcrumbSegment[] => [
+ { breadcrumb: msg`Accounting`, to: path.to.accounting },
+ { breadcrumb: msg`Reports`, to: path.to.reports }
+ ],
+ to: path.to.reports,
+ module: "accounting"
+};
+
+// Full-screen namespace: no module sidebar — reports render full-width inside
+// the app shell. `h-full` (not `flex-1`) because the parent <main> is a block,
+// not a flex container, so flex-1 collapses to auto height — which zeroes out
+// the virtualized Table body in the aging reports (the tree reports self-size
+// via their own calc height, so they were unaffected either way).
+export default function ReportsRoute() {
+ return (
+ <div className="h-full bg-card">
+ <Outlet />
+ </div>
+ );
+}
diff --git a/apps/erp/app/routes/x+/reports+/analytics.$reportKey.tsx b/apps/erp/app/routes/x+/reports+/analytics.$reportKey.tsx
new file mode 100644
index 0000000000..a5dc9405a3
--- /dev/null
+++ b/apps/erp/app/routes/x+/reports+/analytics.$reportKey.tsx
@@ -0,0 +1,627 @@
+import { assertIsPost, error, success } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import type { Json } from "@carbon/database";
+import { validationError, validator } from "@carbon/form";
+import { VStack } from "@carbon/react";
+import {
+ computeReportPeriodBuckets,
+ datetime,
+ defaultReportRange
+} from "@carbon/utils";
+import type { MessageDescriptor } from "@lingui/core";
+import { msg } from "@lingui/core/macro";
+import { useLingui } from "@lingui/react/macro";
+import { useLocale } from "@react-aria/i18n";
+import { useMemo, useState } from "react";
+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
+import { data, redirect, useFetcher, useLoaderData } from "react-router";
+import { useUrlParams } from "~/hooks";
+import type {
+ AnalyticsReportKey,
+ DimensionPivotLine,
+ PivotState
+} from "~/modules/accounting";
+import {
+ analyticsReportKeys,
+ analyticsReports,
+ applyPivotDisplayParams,
+ deleteReportView,
+ getAccountsInScope,
+ getActiveDimensionsWithValues,
+ getDimensionPivot,
+ getFiscalYearSettings,
+ getReportViews,
+ getScrapAccountIds,
+ pivotStateValidator,
+ reportViewValidator,
+ upsertReportView
+} from "~/modules/accounting";
+import type { PivotCellCoordinates } from "~/modules/accounting/ui/Reports";
+import {
+ getPeriodColumnLabel,
+ PivotControlBar,
+ PivotLinesDrawer,
+ PivotTree
+} from "~/modules/accounting/ui/Reports";
+import {
+ buildPivotTree,
+ pivotToCsvRows,
+ UNASSIGNED_COLUMN_KEY
+} from "~/modules/accounting/ui/Reports/pivotData";
+import { months } from "~/modules/shared";
+import { getCompanyTimeZone } from "~/modules/shared/timezone.server";
+import type { BreadcrumbSegment, Handle } from "~/utils/handle";
+import { path } from "~/utils/path";
+import { revalidateIgnoringPivotDisplay } from "~/utils/revalidate";
+
+const breadcrumbByReportKey: Record<AnalyticsReportKey, MessageDescriptor> = {
+ revenue: msg`Revenue`,
+ expenses: msg`Expenses`,
+ assets: msg`Assets`,
+ "inventory-change": msg`Inventory`,
+ scrap: msg`Scrap`
+};
+
+export const handle: Handle = {
+ // handle is static per route module, so the per-report label comes from the
+ // function form (Breadcrumbs calls it with the route params + loader data).
+ // With a saved view active, the view name becomes the leaf segment and the
+ // report name links back to the bare report (inspection-document pattern).
+ breadcrumb: (
+ params: { reportKey?: string },
+ data:
+ | { savedViews?: { id: string; name: string }[]; activeViewId?: string }
+ | undefined
+ ): BreadcrumbSegment[] => {
+ const report =
+ breadcrumbByReportKey[params.reportKey as AnalyticsReportKey] ??
+ msg`Analytics`;
+ const activeView = data?.activeViewId
+ ? data.savedViews?.find((view) => view.id === data.activeViewId)
+ : undefined;
+ return activeView
+ ? [
+ {
+ breadcrumb: report,
+ to: path.to.analyticsReport(params.reportKey ?? "")
+ },
+ { breadcrumb: activeView.name }
+ ]
+ : [{ breadcrumb: report }];
+ }
+};
+
+/**
+ * Explicit pivot params from the URL, per the contract documented above
+ * pivotStateValidator. Only params that are PRESENT are returned, so they can
+ * override the base state (saved view config or report default) field by
+ * field. Values are validated later by pivotStateValidator on the merged
+ * object — a bad bookmark must not 500.
+ */
+function parsePivotUrlParams(
+ searchParams: URLSearchParams
+): Record<string, unknown> {
+ const partial: Record<string, unknown> = {};
+
+ const rows = searchParams.get("rows");
+ if (rows !== null) {
+ partial.rows = rows.split(",").filter(Boolean).slice(0, 2);
+ }
+
+ const col = searchParams.get("col");
+ if (col?.startsWith("period:")) {
+ partial.columnAxis = {
+ type: "period",
+ bucket: col.slice("period:".length)
+ };
+ } else if (col?.startsWith("dim:")) {
+ partial.columnAxis = {
+ type: "dimension",
+ dimensionId: col.slice("dim:".length)
+ };
+ }
+
+ const measure = searchParams.get("measure");
+ if (measure !== null) {
+ partial.measure = measure;
+ }
+
+ const pct = searchParams.get("pct");
+ if (pct !== null) {
+ partial.percentOfTotal = pct === "1";
+ }
+
+ const filters = searchParams.get("filters");
+ if (filters !== null) {
+ try {
+ partial.filters = JSON.parse(filters);
+ } catch {
+ // Malformed filters param — ignore it
+ }
+ }
+
+ const accounts = searchParams.get("accounts");
+ if (accounts !== null) {
+ partial.accountIds = accounts.split(",").filter(Boolean);
+ }
+
+ const sort = searchParams.get("sort");
+ if (sort !== null) {
+ // Split on the LAST colon: column keys (period ends, value ids) never
+ // contain one, but be defensive so ids that might are handled correctly.
+ const separator = sort.lastIndexOf(":");
+ const key = separator > 0 ? sort.slice(0, separator) : "";
+ const direction = separator > 0 ? sort.slice(separator + 1) : "";
+ if (key && (direction === "asc" || direction === "desc")) {
+ partial.sort = { key, direction };
+ }
+ }
+
+ return partial;
+}
+
+// measure / % of total / sort are applied client-side by buildPivotTree, so a
+// change to only those skips the (expensive) pivot refetch; the component
+// re-derives them from the URL via applyPivotDisplayParams.
+export const shouldRevalidate = revalidateIgnoringPivotDisplay;
+
+export async function loader({ request, params }: LoaderFunctionArgs) {
+ const { client, companyId, companyGroupId, userId } =
+ await requirePermissions(request, {
+ view: "accounting",
+ role: "employee"
+ });
+
+ const reportKey = analyticsReportKeys.find((key) => key === params.reportKey);
+ if (!reportKey) {
+ throw new Response("Not found", { status: 404 });
+ }
+ const report = analyticsReports[reportKey];
+ const isScrap = "source" in report.accountScope;
+
+ const url = new URL(request.url);
+
+ // Default range: the trailing six months (shared with every other range
+ // report via defaultReportRange), in the company's business timezone.
+ const range = defaultReportRange(
+ url.searchParams.get("endDate") ??
+ datetime.today(await getCompanyTimeZone(client, companyId)).toString()
+ );
+ const startDate = url.searchParams.get("startDate") ?? range.startDate;
+ const endDate = range.endDate;
+
+ const [
+ dimensionsResult,
+ savedViewsResult,
+ fiscalYearSettings,
+ scrapAccounts
+ ] = await Promise.all([
+ getActiveDimensionsWithValues(client, companyGroupId, companyId),
+ getReportViews(client, { companyId, reportKey }),
+ getFiscalYearSettings(client, companyId),
+ isScrap
+ ? getScrapAccountIds(client, companyId)
+ : Promise.resolve({ data: [] as string[], error: null })
+ ]);
+
+ const dimensions = dimensionsResult.data ?? [];
+ const savedViews = savedViewsResult.data ?? [];
+
+ // The account universe the per-report account filter narrows within. Scrap
+ // resolves through the ids just fetched; class/type scopes query directly.
+ const scopeAccounts =
+ (
+ await getAccountsInScope(
+ client,
+ companyGroupId,
+ report.accountScope,
+ scrapAccounts.data ?? undefined
+ )
+ ).data ?? [];
+
+ // -- Resolve the pivot state --
+ // Precedence: explicit URL pivot params > the selected saved view's config >
+ // the report default. The view param supplies the BASE state; any explicit
+ // pivot param present in the URL overrides that field.
+ const viewParam = url.searchParams.get("view");
+ const activeView = viewParam
+ ? savedViews.find((view) => view.id === viewParam)
+ : undefined;
+
+ let baseState: PivotState | undefined;
+ if (activeView) {
+ const config = pivotStateValidator.safeParse(activeView.config);
+ if (config.success) {
+ baseState = config.data;
+ }
+ }
+
+ const defaultState = pivotStateValidator.parse({
+ rows: report.defaultRows
+ });
+ const merged = pivotStateValidator.safeParse({
+ ...(baseState ?? defaultState),
+ ...parsePivotUrlParams(url.searchParams)
+ });
+ const rawState = merged.success ? merged.data : (baseState ?? defaultState);
+
+ // Resolve "et:<entityType>" aliases (the report defaults use them) to the
+ // first matching active dimension; unresolvable entries are dropped.
+ const resolveAlias = (entry: string): string | null => {
+ if (!entry.startsWith("et:")) return entry;
+ const entityType = entry.slice("et:".length);
+ return (
+ dimensions.find((dimension) => dimension.entityType === entityType)
+ ?.dimensionId ?? null
+ );
+ };
+
+ const resolvedRows: string[] = [];
+ for (const entry of rawState.rows) {
+ const resolved = resolveAlias(entry);
+ if (resolved && !resolvedRows.includes(resolved)) {
+ resolvedRows.push(resolved);
+ }
+ }
+
+ let columnAxis: PivotState["columnAxis"] = rawState.columnAxis;
+ if (columnAxis.type === "dimension") {
+ const resolved = resolveAlias(columnAxis.dimensionId);
+ columnAxis = resolved
+ ? { type: "dimension", dimensionId: resolved }
+ : { type: "period", bucket: "month" };
+ }
+
+ const state: PivotState = { ...rawState, rows: resolvedRows, columnAxis };
+
+ // January is the fallback only for genuinely-unset settings (PGRST116 = no
+ // row); a failed query must not silently mis-bucket a non-January fiscal year.
+ if (
+ fiscalYearSettings.error &&
+ fiscalYearSettings.error.code !== "PGRST116"
+ ) {
+ throw new Error("Failed to load fiscal year settings");
+ }
+ const fiscalStartMonth =
+ months.indexOf(fiscalYearSettings.data?.startMonth ?? "January") + 1;
+
+ const periods =
+ state.columnAxis.type === "period"
+ ? computeReportPeriodBuckets(
+ startDate,
+ endDate,
+ state.columnAxis.bucket,
+ fiscalStartMonth
+ )
+ : [];
+
+ const pivotResult = await getDimensionPivot(client, {
+ companyId,
+ companyGroupId,
+ report,
+ ...(isScrap ? { scrapAccountIds: scrapAccounts.data } : {}),
+ startDate,
+ endDate,
+ ...(state.columnAxis.type === "period"
+ ? { periodEnds: periods.map((bucket) => bucket.end) }
+ : {}),
+ state
+ });
+
+ if (pivotResult.error || !pivotResult.data) {
+ throw redirect(
+ path.to.accounting,
+ await flash(
+ request,
+ error(pivotResult.error, "Failed to load analytics report")
+ )
+ );
+ }
+
+ return {
+ pivot: pivotResult.data,
+ dimensions,
+ savedViews,
+ state,
+ periods,
+ startDate,
+ endDate,
+ reportKey,
+ activeViewId: activeView?.id,
+ currentUserId: userId,
+ scopeAccounts
+ };
+}
+
+export async function action({ request }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, companyId, userId } = await requirePermissions(request, {
+ view: "accounting",
+ role: "employee"
+ });
+
+ const formData = await request.formData();
+ const intent = formData.get("intent");
+
+ if (intent === "save-view") {
+ const validation = await validator(reportViewValidator).validate(formData);
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const { id, config, ...reportView } = validation.data;
+
+ let parsedConfig: PivotState;
+ try {
+ const result = pivotStateValidator.safeParse(JSON.parse(config));
+ if (!result.success) throw result.error;
+ parsedConfig = result.data;
+ } catch (err) {
+ return data(
+ {},
+ await flash(request, error(err, "Invalid view configuration"))
+ );
+ }
+
+ const upsert = await upsertReportView(
+ client,
+ id
+ ? {
+ id,
+ ...reportView,
+ config: parsedConfig as unknown as Json,
+ companyId,
+ updatedBy: userId
+ }
+ : {
+ ...reportView,
+ config: parsedConfig as unknown as Json,
+ companyId,
+ createdBy: userId
+ }
+ );
+
+ if (upsert.error) {
+ return data(
+ {},
+ await flash(request, error(upsert.error, "Failed to save view"))
+ );
+ }
+
+ return data(
+ { id: upsert.data.id },
+ await flash(request, success("View saved"))
+ );
+ }
+
+ if (intent === "delete-view") {
+ const id = formData.get("id");
+ if (typeof id !== "string" || id.length === 0) {
+ return data(
+ {},
+ await flash(request, error("Missing view id", "Failed to delete view"))
+ );
+ }
+
+ const deletion = await deleteReportView(client, id, companyId);
+ if (deletion.error) {
+ return data(
+ {},
+ await flash(request, error(deletion.error, "Failed to delete view"))
+ );
+ }
+
+ return data({}, await flash(request, success("View deleted")));
+ }
+
+ return data(
+ {},
+ await flash(request, error("Unknown intent", "Invalid request"))
+ );
+}
+
+export default function AnalyticsReportRoute() {
+ const {
+ pivot,
+ dimensions,
+ savedViews,
+ state: loaderState,
+ periods,
+ startDate,
+ endDate,
+ reportKey,
+ activeViewId,
+ currentUserId,
+ scopeAccounts
+ } = useLoaderData<typeof loader>();
+ const { t } = useLingui();
+ const { locale } = useLocale();
+ const [searchParams] = useUrlParams();
+
+ // measure / % of total / sort are applied client-side; when only those change
+ // the loader is skipped (revalidateIgnoringPivotDisplay), so overlay them from
+ // the URL to keep the pivot in sync without a refetch.
+ // biome-ignore lint/correctness/useExhaustiveDependencies: keyed by the URL string, not the unstable URLSearchParams identity
+ const state = useMemo(
+ () => applyPivotDisplayParams(loaderState, searchParams),
+ [loaderState, searchParams.toString()]
+ );
+
+ const linesFetcher = useFetcher<{ lines: DimensionPivotLine[] }>();
+ const [drillTitle, setDrillTitle] = useState<string | null>(null);
+
+ const bucket =
+ state.columnAxis.type === "period" ? state.columnAxis.bucket : undefined;
+
+ const columnLabels = useMemo(() => {
+ const labels: Record<string, string> = {
+ [UNASSIGNED_COLUMN_KEY]: t`Unassigned`
+ };
+ if (bucket) {
+ for (const period of periods) {
+ labels[period.end] = getPeriodColumnLabel(period, bucket, locale);
+ }
+ } else {
+ for (const key of pivot.columnKeys) {
+ if (key === UNASSIGNED_COLUMN_KEY) continue;
+ labels[key] = pivot.valueNames[key] ?? key;
+ }
+ }
+ return labels;
+ }, [bucket, periods, pivot, locale, t]);
+
+ const onCellClick = (cell: PivotCellCoordinates) => {
+ const titleParts: string[] = [];
+ if (cell.rowValue1IsNull) {
+ titleParts.push(t`Unassigned`);
+ } else if (cell.rowValue1Id) {
+ titleParts.push(pivot.valueNames[cell.rowValue1Id] ?? cell.rowValue1Id);
+ }
+ if (cell.rowValue2IsNull) {
+ titleParts.push(t`Unassigned`);
+ } else if (cell.rowValue2Id) {
+ titleParts.push(pivot.valueNames[cell.rowValue2Id] ?? cell.rowValue2Id);
+ }
+ titleParts.push(
+ cell.isRowTotal
+ ? t`Total`
+ : cell.columnKey === null
+ ? t`Unassigned`
+ : (columnLabels[cell.columnKey] ?? cell.columnKey)
+ );
+
+ const searchParams = new URLSearchParams({ startDate, endDate });
+ if (state.filters.length > 0) {
+ searchParams.set("filters", JSON.stringify(state.filters));
+ }
+ if (state.accountIds.length > 0) {
+ searchParams.set("accounts", state.accountIds.join(","));
+ }
+
+ // NULL semantics per getDimensionPivotLines: sending the dimension WITHOUT
+ // a value means the Unassigned bucket; sending neither leaves the axis
+ // unconstrained (e.g. a level-1 parent cell).
+ const rowDimension1 = state.rows[0];
+ if (rowDimension1 && (cell.rowValue1IsNull || cell.rowValue1Id)) {
+ searchParams.set("r1d", rowDimension1);
+ if (cell.rowValue1IsNull) {
+ searchParams.set("r1null", "1");
+ } else if (cell.rowValue1Id) {
+ searchParams.set("r1", cell.rowValue1Id);
+ }
+ }
+
+ const rowDimension2 = state.rows[1];
+ if (rowDimension2 && (cell.rowValue2IsNull || cell.rowValue2Id)) {
+ searchParams.set("r2d", rowDimension2);
+ if (cell.rowValue2IsNull) {
+ searchParams.set("r2null", "1");
+ } else if (cell.rowValue2Id) {
+ searchParams.set("r2", cell.rowValue2Id);
+ }
+ }
+
+ if (!cell.isRowTotal) {
+ if (state.columnAxis.type === "dimension") {
+ searchParams.set("cold", state.columnAxis.dimensionId);
+ if (cell.columnKey === null) {
+ searchParams.set("colvnull", "1");
+ } else {
+ searchParams.set("colv", cell.columnKey);
+ }
+ } else if (cell.columnKey !== null) {
+ // Period column: narrow by the bucket's date bounds
+ const period = periods.find((p) => p.end === cell.columnKey);
+ if (period) {
+ searchParams.set("colstart", period.start);
+ searchParams.set("colend", period.end);
+ }
+ }
+ }
+
+ setDrillTitle(titleParts.join(" · "));
+ linesFetcher.load(
+ `${path.to.api.analyticsReportLines(reportKey)}&${searchParams.toString()}`
+ );
+ };
+
+ const onDownload = () => {
+ const tree = buildPivotTree({
+ groups: pivot.groups,
+ valueNames: pivot.valueNames,
+ columnKeys: pivot.columnKeys,
+ rowCount: Math.min(state.rows.length, 2) as 0 | 1 | 2,
+ measure: state.measure,
+ unassignedLabel: t`Unassigned`,
+ totalLabel: t`Total`,
+ sort: state.sort
+ });
+
+ const rows = pivotToCsvRows({
+ flatTree: tree.flatTree,
+ columnKeys: tree.columnKeys,
+ columnTotals: tree.columnTotals,
+ grandTotal: tree.grandTotal,
+ measure: state.measure,
+ columnLabels
+ });
+ if (rows.length === 0) return;
+
+ // Standalone Blob + anchor download — same mechanism as exportReport.ts.
+ // Label cells (dimension values, saved names) are user-controlled: prefix
+ // formula-trigger characters so spreadsheets treat them as text. Numeric
+ // measure cells (incl. negatives) pass through untouched.
+ const sanitizeCell = (value: string) => {
+ if (value === "" || Number.isFinite(Number(value))) return value;
+ return /^[=+\-@]/.test(value) ? `'${value}` : value;
+ };
+ const csvData = rows
+ .map((row) =>
+ row
+ .map(sanitizeCell)
+ .map((value) =>
+ /[",\n]/.test(value) ? `"${value.replace(/"/g, '""')}"` : value
+ )
+ .join(",")
+ )
+ .join("\n");
+ const blob = new Blob([csvData], { type: "text/csv" });
+ const url = window.URL.createObjectURL(blob);
+ const a = document.createElement("a");
+ a.href = url;
+ a.download = `${reportKey}.csv`;
+ document.body.appendChild(a);
+ a.click();
+ window.URL.revokeObjectURL(url);
+ document.body.removeChild(a);
+ };
+
+ return (
+ <VStack spacing={0} className="h-full">
+ <PivotControlBar
+ reportKey={reportKey}
+ dimensions={dimensions}
+ state={state}
+ savedViews={savedViews}
+ activeViewId={activeViewId}
+ currentUserId={currentUserId}
+ accounts={scopeAccounts}
+ onDownload={onDownload}
+ />
+ <PivotTree
+ pivot={pivot}
+ state={state}
+ columnLabels={columnLabels}
+ onCellClick={onCellClick}
+ />
+ <PivotLinesDrawer
+ open={drillTitle !== null}
+ onClose={() => setDrillTitle(null)}
+ title={drillTitle ?? ""}
+ lines={linesFetcher.data?.lines ?? null}
+ isLoading={linesFetcher.state !== "idle"}
+ />
+ </VStack>
+ );
+}
diff --git a/apps/erp/app/routes/x+/reports+/ap-aging.tsx b/apps/erp/app/routes/x+/reports+/ap-aging.tsx
new file mode 100644
index 0000000000..72a0c63568
--- /dev/null
+++ b/apps/erp/app/routes/x+/reports+/ap-aging.tsx
@@ -0,0 +1,93 @@
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { datetime } from "@carbon/utils";
+import { msg } from "@lingui/core/macro";
+import { useLingui } from "@lingui/react/macro";
+import type { LoaderFunctionArgs } from "react-router";
+import { useLoaderData } from "react-router";
+import {
+ ARAPWorkbench,
+ getApAging,
+ getApOpenBySupplier,
+ getApTieOut
+} from "~/modules/invoicing";
+import { getCompanySettings } from "~/modules/settings";
+import { getCompanyTimeZone } from "~/modules/shared/timezone.server";
+import type { Handle } from "~/utils/handle";
+import { path } from "~/utils/path";
+
+export const handle: Handle = {
+ breadcrumb: msg`AP Aging`,
+ to: path.to.apAging
+};
+
+function parseBuckets(raw: string | null): [number, number, number] {
+ const parts = (raw ?? "").split(",").map((n) => Number.parseInt(n, 10));
+ if (parts.length === 3 && parts.every((n) => Number.isFinite(n) && n > 0)) {
+ return [parts[0], parts[1], parts[2]];
+ }
+ return [30, 60, 90];
+}
+
+export async function loader({ request }: LoaderFunctionArgs) {
+ const { client, companyId } = await requirePermissions(request, {
+ view: "accounting",
+ role: "employee"
+ });
+
+ const url = new URL(request.url);
+ const asOfDate =
+ url.searchParams.get("asOfDate") ??
+ datetime.today(await getCompanyTimeZone(client, companyId)).toString();
+ const agingMethod: "dueDate" | "documentDate" =
+ url.searchParams.get("agingMethod") === "documentDate"
+ ? "documentDate"
+ : "dueDate";
+ const bucketDays = parseBuckets(url.searchParams.get("bucketDays"));
+
+ // GL tie-outs only mean something when journals are being posted — skip
+ // them entirely when accounting is disabled (result: null hides the
+ // tie-out panel and the adjusting-entry form in ARAPWorkbench).
+ const companySettings = await getCompanySettings(client, companyId);
+ const accountingEnabled =
+ (companySettings.data as { accountingEnabled?: boolean } | null)
+ ?.accountingEnabled ?? false;
+
+ const [tieOut, aging, open] = await Promise.all([
+ accountingEnabled
+ ? getApTieOut(client, companyId, asOfDate)
+ : Promise.resolve({ data: null }),
+ getApAging(client, companyId, asOfDate, { agingMethod, bucketDays }),
+ getApOpenBySupplier(client, companyId, asOfDate)
+ ]);
+
+ return {
+ asOfDate,
+ agingMethod,
+ bucketDays,
+ result: tieOut.data ?? null,
+ aging: aging.data ?? [],
+ open: (open.data ?? []).map((r) => ({
+ ...r,
+ invoiceId: r.documentId,
+ invoiceNumber: r.documentNumber
+ }))
+ };
+}
+
+export default function ApAgingRoute() {
+ const { asOfDate, agingMethod, bucketDays, result, aging, open } =
+ useLoaderData<typeof loader>();
+ const { t } = useLingui();
+ return (
+ <ARAPWorkbench
+ side="ap"
+ result={result}
+ aging={aging}
+ open={open}
+ asOfDate={asOfDate}
+ agingMethod={agingMethod}
+ bucketDays={bucketDays}
+ title={t`AP Aging`}
+ />
+ );
+}
diff --git a/apps/erp/app/routes/x+/reports+/ar-aging.tsx b/apps/erp/app/routes/x+/reports+/ar-aging.tsx
new file mode 100644
index 0000000000..531cf3c9f8
--- /dev/null
+++ b/apps/erp/app/routes/x+/reports+/ar-aging.tsx
@@ -0,0 +1,93 @@
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { datetime } from "@carbon/utils";
+import { msg } from "@lingui/core/macro";
+import { useLingui } from "@lingui/react/macro";
+import type { LoaderFunctionArgs } from "react-router";
+import { useLoaderData } from "react-router";
+import {
+ ARAPWorkbench,
+ getArAging,
+ getArOpenByCustomer,
+ getArTieOut
+} from "~/modules/invoicing";
+import { getCompanySettings } from "~/modules/settings";
+import { getCompanyTimeZone } from "~/modules/shared/timezone.server";
+import type { Handle } from "~/utils/handle";
+import { path } from "~/utils/path";
+
+export const handle: Handle = {
+ breadcrumb: msg`AR Aging`,
+ to: path.to.arAging
+};
+
+function parseBuckets(raw: string | null): [number, number, number] {
+ const parts = (raw ?? "").split(",").map((n) => Number.parseInt(n, 10));
+ if (parts.length === 3 && parts.every((n) => Number.isFinite(n) && n > 0)) {
+ return [parts[0], parts[1], parts[2]];
+ }
+ return [30, 60, 90];
+}
+
+export async function loader({ request }: LoaderFunctionArgs) {
+ const { client, companyId } = await requirePermissions(request, {
+ view: "accounting",
+ role: "employee"
+ });
+
+ const url = new URL(request.url);
+ const asOfDate =
+ url.searchParams.get("asOfDate") ??
+ datetime.today(await getCompanyTimeZone(client, companyId)).toString();
+ const agingMethod: "dueDate" | "documentDate" =
+ url.searchParams.get("agingMethod") === "documentDate"
+ ? "documentDate"
+ : "dueDate";
+ const bucketDays = parseBuckets(url.searchParams.get("bucketDays"));
+
+ // GL tie-outs only mean something when journals are being posted — skip
+ // them entirely when accounting is disabled (result: null hides the
+ // tie-out panel and the adjusting-entry form in ARAPWorkbench).
+ const companySettings = await getCompanySettings(client, companyId);
+ const accountingEnabled =
+ (companySettings.data as { accountingEnabled?: boolean } | null)
+ ?.accountingEnabled ?? false;
+
+ const [tieOut, aging, open] = await Promise.all([
+ accountingEnabled
+ ? getArTieOut(client, companyId, asOfDate)
+ : Promise.resolve({ data: null }),
+ getArAging(client, companyId, asOfDate, { agingMethod, bucketDays }),
+ getArOpenByCustomer(client, companyId, asOfDate)
+ ]);
+
+ return {
+ asOfDate,
+ agingMethod,
+ bucketDays,
+ result: tieOut.data ?? null,
+ aging: aging.data ?? [],
+ open: (open.data ?? []).map((r) => ({
+ ...r,
+ invoiceId: r.documentId,
+ invoiceNumber: r.documentNumber
+ }))
+ };
+}
+
+export default function ArAgingRoute() {
+ const { asOfDate, agingMethod, bucketDays, result, aging, open } =
+ useLoaderData<typeof loader>();
+ const { t } = useLingui();
+ return (
+ <ARAPWorkbench
+ side="ar"
+ result={result}
+ aging={aging}
+ open={open}
+ asOfDate={asOfDate}
+ agingMethod={agingMethod}
+ bucketDays={bucketDays}
+ title={t`AR Aging`}
+ />
+ );
+}
diff --git a/apps/erp/app/routes/x+/accounting+/balance-sheet.$accountId.tsx b/apps/erp/app/routes/x+/reports+/balance-sheet.$accountId.tsx
similarity index 100%
rename from apps/erp/app/routes/x+/accounting+/balance-sheet.$accountId.tsx
rename to apps/erp/app/routes/x+/reports+/balance-sheet.$accountId.tsx
diff --git a/apps/erp/app/routes/x+/accounting+/balance-sheet.tsx b/apps/erp/app/routes/x+/reports+/balance-sheet.tsx
similarity index 52%
rename from apps/erp/app/routes/x+/accounting+/balance-sheet.tsx
rename to apps/erp/app/routes/x+/reports+/balance-sheet.tsx
index 7c7ea63104..8aaabcf813 100644
--- a/apps/erp/app/routes/x+/accounting+/balance-sheet.tsx
+++ b/apps/erp/app/routes/x+/reports+/balance-sheet.tsx
@@ -2,21 +2,28 @@ import { error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { VStack } from "@carbon/react";
-import { datetime } from "@carbon/utils";
+import {
+ computeReportPeriodBuckets,
+ datetime,
+ defaultReportRange
+} from "@carbon/utils";
import { msg } from "@lingui/core/macro";
+import { useLocale } from "@react-aria/i18n";
import { useState } from "react";
import type { LoaderFunctionArgs } from "react-router";
import { Outlet, redirect, useLoaderData } from "react-router";
-import type { Chart } from "~/modules/accounting";
+import type { ChartPeriodSeries } from "~/modules/accounting";
import {
+ financialReportParamsValidator,
getCompaniesInGroup,
- getConsolidatedBalances,
- getFinancialStatementBalances,
- getFiscalYearSettings,
- translateCompanyBalances
+ getConsolidatedPeriodSeries,
+ getFinancialStatementPeriodSeries,
+ getFiscalYearSettings
} from "~/modules/accounting";
import {
- FinancialStatementTree,
+ exportPeriodReport,
+ getPeriodColumnLabel,
+ MultiPeriodStatementTree,
ReportFilters
} from "~/modules/accounting/ui/Reports";
import { months } from "~/modules/shared";
@@ -32,6 +39,26 @@ export const handle: Handle = {
export const shouldRevalidate = revalidateIgnoringOffset;
+const CTA_RESERVES_ACCOUNT_NUMBER = "3200";
+
+function applyCtaByBucket(
+ accounts: ChartPeriodSeries[],
+ ctaByBucket: Record<string, number>
+) {
+ const ctaAccount = accounts.find(
+ (a) => a.number === CTA_RESERVES_ACCOUNT_NUMBER
+ );
+ if (!ctaAccount) return;
+ for (const [key, cta] of Object.entries(ctaByBucket)) {
+ const cell = ctaAccount.periods[key];
+ if (!cell) continue;
+ ctaAccount.periods[key] = {
+ ...cell,
+ translatedBalance: (cell.translatedBalance ?? 0) + cta
+ };
+ }
+}
+
export async function loader({ request }: LoaderFunctionArgs) {
const { client, companyId, companyGroupId } = await requirePermissions(
request,
@@ -42,10 +69,21 @@ export async function loader({ request }: LoaderFunctionArgs) {
);
const url = new URL(request.url);
- const searchParams = new URLSearchParams(url.search);
- const companiesParam = searchParams.get("companies");
- const endDate = searchParams.get("endDate") || null;
- const showTranslated = searchParams.get("showTranslated") === "true";
+ // Invalid params fall back to defaults — a bad bookmark must not 500
+ const parsed = financialReportParamsValidator.safeParse(
+ Object.fromEntries(url.searchParams.entries())
+ );
+ const companiesParam = parsed.success
+ ? (parsed.data.companies ?? null)
+ : null;
+ const startDateParam = parsed.success
+ ? (parsed.data.startDate ?? null)
+ : null;
+ const endDateParam = parsed.success ? (parsed.data.endDate ?? null) : null;
+ const columns = parsed.success ? parsed.data.columns : ("month" as const);
+ const showTranslatedParam = parsed.success
+ ? parsed.data.showTranslated
+ : false;
const [companies, fiscalYearSettings] = await Promise.all([
getCompaniesInGroup(client, companyGroupId),
@@ -65,34 +103,40 @@ export async function loader({ request }: LoaderFunctionArgs) {
: [companyId];
const isMultiCompany = selectedCompanyIds.length > 1;
+ // Default range: last 6 months to date (in the company's business timezone) —
+ // the current partial month plus the five preceding whole months.
+ const range = defaultReportRange(
+ endDateParam ??
+ datetime.today(await getCompanyTimeZone(client, companyId)).toString()
+ );
+ const endDate = range.endDate;
+ const startDate = startDateParam ?? range.startDate;
+
+ const buckets = computeReportPeriodBuckets(
+ startDate,
+ endDate,
+ columns,
+ fiscalStartMonth
+ );
+
if (isMultiCompany && parentCurrency) {
- const periodEnd =
- endDate ??
- datetime.today(await getCompanyTimeZone(client, companyId)).toString();
- const consolidated = await getConsolidatedBalances(
+ const consolidated = await getConsolidatedPeriodSeries(
client,
companyGroupId,
selectedCompanyIds,
parentCurrency,
- periodEnd
+ { buckets }
);
- let balanceSheetAccounts = consolidated.data.filter(
+ const balanceSheetAccounts = consolidated.data.filter(
(a) => a.incomeBalance === "Balance Sheet"
);
-
- // Apply CTA to reserves account
- const ctaAccount = balanceSheetAccounts.find((a) => a.number === "3200");
- if (ctaAccount) {
- ctaAccount.translatedBalance =
- (ctaAccount.translatedBalance ?? 0) + consolidated.cta;
- }
+ applyCtaByBucket(balanceSheetAccounts, consolidated.ctaByBucket);
return {
- balanceSheet: balanceSheetAccounts as (Chart & {
- translatedBalance?: number;
- exchangeRate?: number;
- })[],
+ balanceSheet: balanceSheetAccounts,
+ periods: buckets,
+ columns,
companies: companiesList,
selectedCompanyIds,
showTranslated: true,
@@ -104,81 +148,48 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
// Single company
- const selectedCompanyId = selectedCompanyIds[0];
- const balances = await getFinancialStatementBalances(
+ const selectedCompanyId = selectedCompanyIds[0]!;
+ const selectedCompany = companiesList.find((c) => c.id === selectedCompanyId);
+ const isForeignCurrency =
+ !!parentCurrency &&
+ !!selectedCompany?.baseCurrencyCode &&
+ selectedCompany.baseCurrencyCode !== parentCurrency;
+ const showTranslated = showTranslatedParam && isForeignCurrency;
+
+ const series = await getFinancialStatementPeriodSeries(
client,
companyGroupId,
selectedCompanyId,
- { startDate: null, endDate, includeCurrentYearEarnings: true }
+ {
+ buckets,
+ includeCurrentYearEarnings: true,
+ ...(showTranslated && parentCurrency
+ ? { translate: { targetCurrency: parentCurrency } }
+ : {})
+ }
);
- if (balances.error) {
+ if (series.error) {
throw redirect(
path.to.accounting,
- await flash(
- request,
- error(balances.error, "Failed to load balance sheet")
- )
+ await flash(request, error(series.error, "Failed to load balance sheet"))
);
}
- const selectedCompany = companiesList.find((c) => c.id === selectedCompanyId);
- const isForeignCurrency =
- !!parentCurrency &&
- !!selectedCompany?.baseCurrencyCode &&
- selectedCompany.baseCurrencyCode !== parentCurrency;
-
- let balanceSheetAccounts = (balances.data ?? []).filter(
+ const balanceSheetAccounts = (series.data ?? []).filter(
(a) => a.incomeBalance === "Balance Sheet"
- ) as (Chart & { translatedBalance?: number; exchangeRate?: number })[];
-
- let cta = 0;
-
- if (showTranslated && isForeignCurrency && parentCurrency) {
- const periodEnd =
- endDate ??
- datetime.today(await getCompanyTimeZone(client, companyId)).toString();
- const translation = await translateCompanyBalances(
- client,
- companyGroupId,
- selectedCompanyId!,
- parentCurrency,
- periodEnd,
- undefined,
- balances.data ?? []
- );
-
- if (translation.data) {
- const translationMap = new Map(
- translation.data.map((t) => [t.accountId, t])
- );
- cta = translation.cta;
-
- balanceSheetAccounts = balanceSheetAccounts.map((account) => {
- const t = translationMap.get(account.id);
- if (t) {
- return {
- ...account,
- translatedBalance: Number(t.translatedBalance),
- exchangeRate: Number(t.exchangeRate)
- };
- }
- return account;
- });
-
- const ctaAccount = balanceSheetAccounts.find((a) => a.number === "3200");
- if (ctaAccount) {
- ctaAccount.translatedBalance =
- (ctaAccount.translatedBalance ?? 0) + cta;
- }
- }
+ );
+ if (showTranslated) {
+ applyCtaByBucket(balanceSheetAccounts, series.ctaByBucket);
}
return {
balanceSheet: balanceSheetAccounts,
+ periods: buckets,
+ columns,
companies: companiesList,
selectedCompanyIds,
- showTranslated: showTranslated && isForeignCurrency,
+ showTranslated,
isMultiCompany: false,
isForeignCurrency,
parentCurrency,
@@ -189,6 +200,8 @@ export async function loader({ request }: LoaderFunctionArgs) {
export default function BalanceSheetRoute() {
const {
balanceSheet,
+ periods,
+ columns,
companies,
selectedCompanyIds,
showTranslated,
@@ -198,6 +211,7 @@ export default function BalanceSheetRoute() {
fiscalStartMonth
} = useLoaderData<typeof loader>();
const [search, setSearch] = useState("");
+ const { locale } = useLocale();
return (
<VStack spacing={0} className="h-full">
@@ -207,13 +221,31 @@ export default function BalanceSheetRoute() {
isMultiCompany={isMultiCompany}
isForeignCurrency={isForeignCurrency}
parentCurrency={parentCurrency}
- periodVariant="asOf"
+ periodVariant="range"
fiscalStartMonth={fiscalStartMonth}
+ showColumns
+ onDownload={() =>
+ exportPeriodReport({
+ accounts: balanceSheet,
+ periods: periods.map((bucket) => ({
+ ...bucket,
+ label:
+ getPeriodColumnLabel(bucket, columns, locale) +
+ (bucket.isPartial ? " (To Date)" : "")
+ })),
+ measure: "balanceAtDate",
+ showTranslated,
+ search,
+ filename: "balance-sheet.csv"
+ })
+ }
search={search}
onSearchChange={setSearch}
/>
- <FinancialStatementTree
+ <MultiPeriodStatementTree
data={balanceSheet}
+ periods={periods}
+ columns={columns}
measure="balanceAtDate"
showTranslated={showTranslated}
parentCurrency={parentCurrency}
diff --git a/apps/erp/app/routes/x+/reports+/executive-pnl.tsx b/apps/erp/app/routes/x+/reports+/executive-pnl.tsx
new file mode 100644
index 0000000000..c39a7206d1
--- /dev/null
+++ b/apps/erp/app/routes/x+/reports+/executive-pnl.tsx
@@ -0,0 +1,235 @@
+import { error } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import { VStack } from "@carbon/react";
+import {
+ computeReportPeriodBuckets,
+ datetime,
+ defaultReportRange
+} from "@carbon/utils";
+import { msg } from "@lingui/core/macro";
+import { useLingui } from "@lingui/react/macro";
+import { useLocale } from "@react-aria/i18n";
+import type { LoaderFunctionArgs } from "react-router";
+import { redirect, useLoaderData } from "react-router";
+import {
+ financialReportParamsValidator,
+ getCompaniesInGroup,
+ getConsolidatedPeriodSeries,
+ getFinancialStatementPeriodSeries,
+ getFiscalYearSettings
+} from "~/modules/accounting";
+import type { ExecutivePnlRowKey } from "~/modules/accounting/ui/Reports";
+import {
+ ExecutivePnlSummary,
+ exportExecutivePnl,
+ getPeriodColumnLabel,
+ ReportFilters
+} from "~/modules/accounting/ui/Reports";
+import { months } from "~/modules/shared";
+import { getCompanyTimeZone } from "~/modules/shared/timezone.server";
+import type { Handle } from "~/utils/handle";
+import { path } from "~/utils/path";
+import { revalidateIgnoringOffset } from "~/utils/revalidate";
+
+export const handle: Handle = {
+ breadcrumb: msg`Executive P&L`,
+ to: path.to.executivePnl
+};
+
+export const shouldRevalidate = revalidateIgnoringOffset;
+
+export async function loader({ request }: LoaderFunctionArgs) {
+ const { client, companyId, companyGroupId } = await requirePermissions(
+ request,
+ {
+ view: "accounting",
+ role: "employee"
+ }
+ );
+
+ const url = new URL(request.url);
+ // Invalid params fall back to defaults — a bad bookmark must not 500
+ const parsed = financialReportParamsValidator.safeParse(
+ Object.fromEntries(url.searchParams.entries())
+ );
+ const companiesParam = parsed.success
+ ? (parsed.data.companies ?? null)
+ : null;
+ const startDateParam = parsed.success
+ ? (parsed.data.startDate ?? null)
+ : null;
+ const endDateParam = parsed.success ? (parsed.data.endDate ?? null) : null;
+ const columns = parsed.success ? parsed.data.columns : ("month" as const);
+ const showTranslatedParam = parsed.success
+ ? parsed.data.showTranslated
+ : false;
+
+ const [companies, fiscalYearSettings] = await Promise.all([
+ getCompaniesInGroup(client, companyGroupId),
+ getFiscalYearSettings(client, companyId)
+ ]);
+ const fiscalStartMonth =
+ months.indexOf(fiscalYearSettings.data?.startMonth ?? "January") + 1;
+ const companiesList = companies.data ?? [];
+ const parentCompany = companiesList.find((c) => !c.parentCompanyId);
+ const parentCurrency = parentCompany?.baseCurrencyCode ?? null;
+
+ const selectedCompanyIds =
+ companiesParam === "all"
+ ? companiesList.map((c) => c.id)
+ : companiesParam
+ ? [companiesParam]
+ : [companyId];
+ const isMultiCompany = selectedCompanyIds.length > 1;
+
+ // Default range: last 6 months to date (in the company's business timezone) —
+ // the current partial month plus the five preceding whole months.
+ const range = defaultReportRange(
+ endDateParam ??
+ datetime.today(await getCompanyTimeZone(client, companyId)).toString()
+ );
+ const endDate = range.endDate;
+ const startDate = startDateParam ?? range.startDate;
+
+ const buckets = computeReportPeriodBuckets(
+ startDate,
+ endDate,
+ columns,
+ fiscalStartMonth
+ );
+
+ if (isMultiCompany && parentCurrency) {
+ const consolidated = await getConsolidatedPeriodSeries(
+ client,
+ companyGroupId,
+ selectedCompanyIds,
+ parentCurrency,
+ { buckets }
+ );
+
+ return {
+ incomeStatement: consolidated.data.filter(
+ (a) => a.incomeBalance === "Income Statement"
+ ),
+ periods: buckets,
+ columns,
+ companies: companiesList,
+ selectedCompanyIds,
+ showTranslated: true,
+ isMultiCompany: true,
+ isForeignCurrency: false,
+ parentCurrency,
+ fiscalStartMonth
+ };
+ }
+
+ // Single company
+ const selectedCompanyId = selectedCompanyIds[0]!;
+ const selectedCompany = companiesList.find((c) => c.id === selectedCompanyId);
+ const isForeignCurrency =
+ !!parentCurrency &&
+ !!selectedCompany?.baseCurrencyCode &&
+ selectedCompany.baseCurrencyCode !== parentCurrency;
+ const showTranslated = showTranslatedParam && isForeignCurrency;
+
+ const series = await getFinancialStatementPeriodSeries(
+ client,
+ companyGroupId,
+ selectedCompanyId,
+ {
+ buckets,
+ ...(showTranslated && parentCurrency
+ ? { translate: { targetCurrency: parentCurrency } }
+ : {})
+ }
+ );
+
+ if (series.error) {
+ throw redirect(
+ path.to.accounting,
+ await flash(request, error(series.error, "Failed to load executive P&L"))
+ );
+ }
+
+ return {
+ incomeStatement: (series.data ?? []).filter(
+ (a) => a.incomeBalance === "Income Statement"
+ ),
+ periods: buckets,
+ columns,
+ companies: companiesList,
+ selectedCompanyIds,
+ showTranslated,
+ isMultiCompany: false,
+ isForeignCurrency,
+ parentCurrency,
+ fiscalStartMonth
+ };
+}
+
+export default function ExecutivePnlRoute() {
+ const {
+ incomeStatement,
+ periods,
+ columns,
+ companies,
+ selectedCompanyIds,
+ showTranslated,
+ isMultiCompany,
+ isForeignCurrency,
+ parentCurrency,
+ fiscalStartMonth
+ } = useLoaderData<typeof loader>();
+ const { t } = useLingui();
+ const { locale } = useLocale();
+
+ const labels: Record<ExecutivePnlRowKey, string> = {
+ revenue: t`Revenue`,
+ cogs: t`Cost of Sales`,
+ grossProfit: t`Gross Profit`,
+ operatingExpenses: t`Operating Expenses`,
+ operatingIncome: t`Operating Income`,
+ otherIncome: t`Other Income`,
+ otherExpense: t`Other Expense`,
+ tax: t`Income Tax`,
+ netIncome: t`Net Income`
+ };
+
+ return (
+ <VStack spacing={0} className="h-full">
+ <ReportFilters
+ companies={companies}
+ selectedCompanyIds={selectedCompanyIds}
+ isMultiCompany={isMultiCompany}
+ isForeignCurrency={isForeignCurrency}
+ parentCurrency={parentCurrency}
+ periodVariant="range"
+ fiscalStartMonth={fiscalStartMonth}
+ showColumns
+ showSearch={false}
+ onDownload={() =>
+ exportExecutivePnl({
+ accounts: incomeStatement,
+ periods: periods.map((bucket) => ({
+ ...bucket,
+ label:
+ getPeriodColumnLabel(bucket, columns, locale) +
+ (bucket.isPartial ? " (To Date)" : "")
+ })),
+ labels,
+ showTranslated,
+ filename: "executive-pnl.csv"
+ })
+ }
+ />
+ <ExecutivePnlSummary
+ data={incomeStatement}
+ periods={periods}
+ columns={columns}
+ showTranslated={showTranslated}
+ parentCurrency={parentCurrency}
+ />
+ </VStack>
+ );
+}
diff --git a/apps/erp/app/routes/x+/accounting+/income-statement.$accountId.tsx b/apps/erp/app/routes/x+/reports+/income-statement.$accountId.tsx
similarity index 100%
rename from apps/erp/app/routes/x+/accounting+/income-statement.$accountId.tsx
rename to apps/erp/app/routes/x+/reports+/income-statement.$accountId.tsx
diff --git a/apps/erp/app/routes/x+/accounting+/income-statement.tsx b/apps/erp/app/routes/x+/reports+/income-statement.tsx
similarity index 58%
rename from apps/erp/app/routes/x+/accounting+/income-statement.tsx
rename to apps/erp/app/routes/x+/reports+/income-statement.tsx
index 6714c5946f..1280661c6e 100644
--- a/apps/erp/app/routes/x+/accounting+/income-statement.tsx
+++ b/apps/erp/app/routes/x+/reports+/income-statement.tsx
@@ -2,21 +2,27 @@ import { error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { VStack } from "@carbon/react";
-import { datetime } from "@carbon/utils";
+import {
+ computeReportPeriodBuckets,
+ datetime,
+ defaultReportRange
+} from "@carbon/utils";
import { msg } from "@lingui/core/macro";
+import { useLocale } from "@react-aria/i18n";
import { useState } from "react";
import type { LoaderFunctionArgs } from "react-router";
import { Outlet, redirect, useLoaderData } from "react-router";
-import type { Chart } from "~/modules/accounting";
import {
+ financialReportParamsValidator,
getCompaniesInGroup,
- getConsolidatedBalances,
- getFinancialStatementBalances,
- getFiscalYearSettings,
- translateCompanyBalances
+ getConsolidatedPeriodSeries,
+ getFinancialStatementPeriodSeries,
+ getFiscalYearSettings
} from "~/modules/accounting";
import {
- FinancialStatementTree,
+ exportPeriodReport,
+ getPeriodColumnLabel,
+ MultiPeriodStatementTree,
ReportFilters
} from "~/modules/accounting/ui/Reports";
import { months } from "~/modules/shared";
@@ -42,11 +48,21 @@ export async function loader({ request }: LoaderFunctionArgs) {
);
const url = new URL(request.url);
- const searchParams = new URLSearchParams(url.search);
- const companiesParam = searchParams.get("companies");
- const startDate = searchParams.get("startDate") || null;
- const endDate = searchParams.get("endDate") || null;
- const showTranslated = searchParams.get("showTranslated") === "true";
+ // Invalid params fall back to defaults — a bad bookmark must not 500
+ const parsed = financialReportParamsValidator.safeParse(
+ Object.fromEntries(url.searchParams.entries())
+ );
+ const companiesParam = parsed.success
+ ? (parsed.data.companies ?? null)
+ : null;
+ const startDateParam = parsed.success
+ ? (parsed.data.startDate ?? null)
+ : null;
+ const endDateParam = parsed.success ? (parsed.data.endDate ?? null) : null;
+ const columns = parsed.success ? parsed.data.columns : ("month" as const);
+ const showTranslatedParam = parsed.success
+ ? parsed.data.showTranslated
+ : false;
const [companies, fiscalYearSettings] = await Promise.all([
getCompaniesInGroup(client, companyGroupId),
@@ -66,28 +82,37 @@ export async function loader({ request }: LoaderFunctionArgs) {
: [companyId];
const isMultiCompany = selectedCompanyIds.length > 1;
+ // Default range: last 6 months to date (in the company's business timezone) —
+ // the current partial month plus the five preceding whole months.
+ const range = defaultReportRange(
+ endDateParam ??
+ datetime.today(await getCompanyTimeZone(client, companyId)).toString()
+ );
+ const endDate = range.endDate;
+ const startDate = startDateParam ?? range.startDate;
+
+ const buckets = computeReportPeriodBuckets(
+ startDate,
+ endDate,
+ columns,
+ fiscalStartMonth
+ );
+
if (isMultiCompany && parentCurrency) {
- const periodEnd =
- endDate ??
- datetime.today(await getCompanyTimeZone(client, companyId)).toString();
- const consolidated = await getConsolidatedBalances(
+ const consolidated = await getConsolidatedPeriodSeries(
client,
companyGroupId,
selectedCompanyIds,
parentCurrency,
- periodEnd,
- startDate ?? undefined
- );
-
- const incomeStatementAccounts = consolidated.data.filter(
- (a) => a.incomeBalance === "Income Statement"
+ { buckets }
);
return {
- incomeStatement: incomeStatementAccounts as (Chart & {
- translatedBalance?: number;
- exchangeRate?: number;
- })[],
+ incomeStatement: consolidated.data.filter(
+ (a) => a.incomeBalance === "Income Statement"
+ ),
+ periods: buckets,
+ columns,
companies: companiesList,
selectedCompanyIds,
showTranslated: true,
@@ -99,72 +124,45 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
// Single company
- const selectedCompanyId = selectedCompanyIds[0];
- const balances = await getFinancialStatementBalances(
+ const selectedCompanyId = selectedCompanyIds[0]!;
+ const selectedCompany = companiesList.find((c) => c.id === selectedCompanyId);
+ const isForeignCurrency =
+ !!parentCurrency &&
+ !!selectedCompany?.baseCurrencyCode &&
+ selectedCompany.baseCurrencyCode !== parentCurrency;
+ const showTranslated = showTranslatedParam && isForeignCurrency;
+
+ const series = await getFinancialStatementPeriodSeries(
client,
companyGroupId,
selectedCompanyId,
- { startDate, endDate }
+ {
+ buckets,
+ ...(showTranslated && parentCurrency
+ ? { translate: { targetCurrency: parentCurrency } }
+ : {})
+ }
);
- if (balances.error) {
+ if (series.error) {
throw redirect(
path.to.accounting,
await flash(
request,
- error(balances.error, "Failed to load income statement")
+ error(series.error, "Failed to load income statement")
)
);
}
- const selectedCompany = companiesList.find((c) => c.id === selectedCompanyId);
- const isForeignCurrency =
- !!parentCurrency &&
- !!selectedCompany?.baseCurrencyCode &&
- selectedCompany.baseCurrencyCode !== parentCurrency;
-
- let incomeStatementAccounts = (balances.data ?? []).filter(
- (a) => a.incomeBalance === "Income Statement"
- ) as (Chart & { translatedBalance?: number; exchangeRate?: number })[];
-
- if (showTranslated && isForeignCurrency && parentCurrency) {
- const periodEnd =
- endDate ??
- datetime.today(await getCompanyTimeZone(client, companyId)).toString();
- const translation = await translateCompanyBalances(
- client,
- companyGroupId,
- selectedCompanyId!,
- parentCurrency,
- periodEnd,
- startDate ?? undefined,
- balances.data ?? []
- );
-
- if (translation.data) {
- const translationMap = new Map(
- translation.data.map((t) => [t.accountId, t])
- );
-
- incomeStatementAccounts = incomeStatementAccounts.map((account) => {
- const t = translationMap.get(account.id);
- if (t) {
- return {
- ...account,
- translatedBalance: Number(t.translatedBalance),
- exchangeRate: Number(t.exchangeRate)
- };
- }
- return account;
- });
- }
- }
-
return {
- incomeStatement: incomeStatementAccounts,
+ incomeStatement: (series.data ?? []).filter(
+ (a) => a.incomeBalance === "Income Statement"
+ ),
+ periods: buckets,
+ columns,
companies: companiesList,
selectedCompanyIds,
- showTranslated: showTranslated && isForeignCurrency,
+ showTranslated,
isMultiCompany: false,
isForeignCurrency,
parentCurrency,
@@ -175,6 +173,8 @@ export async function loader({ request }: LoaderFunctionArgs) {
export default function IncomeStatementRoute() {
const {
incomeStatement,
+ periods,
+ columns,
companies,
selectedCompanyIds,
showTranslated,
@@ -184,6 +184,7 @@ export default function IncomeStatementRoute() {
fiscalStartMonth
} = useLoaderData<typeof loader>();
const [search, setSearch] = useState("");
+ const { locale } = useLocale();
return (
<VStack spacing={0} className="h-full">
@@ -193,12 +194,31 @@ export default function IncomeStatementRoute() {
isMultiCompany={isMultiCompany}
isForeignCurrency={isForeignCurrency}
parentCurrency={parentCurrency}
+ periodVariant="range"
fiscalStartMonth={fiscalStartMonth}
+ showColumns
+ onDownload={() =>
+ exportPeriodReport({
+ accounts: incomeStatement,
+ periods: periods.map((bucket) => ({
+ ...bucket,
+ label:
+ getPeriodColumnLabel(bucket, columns, locale) +
+ (bucket.isPartial ? " (To Date)" : "")
+ })),
+ measure: "netChange",
+ showTranslated,
+ search,
+ filename: "income-statement.csv"
+ })
+ }
search={search}
onSearchChange={setSearch}
/>
- <FinancialStatementTree
+ <MultiPeriodStatementTree
data={incomeStatement}
+ periods={periods}
+ columns={columns}
measure="netChange"
showTranslated={showTranslated}
parentCurrency={parentCurrency}
diff --git a/apps/erp/app/routes/x+/inventory+/valuation.reconcile.tsx b/apps/erp/app/routes/x+/reports+/inventory-valuation.reconcile.tsx
similarity index 100%
rename from apps/erp/app/routes/x+/inventory+/valuation.reconcile.tsx
rename to apps/erp/app/routes/x+/reports+/inventory-valuation.reconcile.tsx
diff --git a/apps/erp/app/routes/x+/inventory+/valuation.tsx b/apps/erp/app/routes/x+/reports+/inventory-valuation.tsx
similarity index 97%
rename from apps/erp/app/routes/x+/inventory+/valuation.tsx
rename to apps/erp/app/routes/x+/reports+/inventory-valuation.tsx
index f3cc331672..9d8fb33055 100644
--- a/apps/erp/app/routes/x+/inventory+/valuation.tsx
+++ b/apps/erp/app/routes/x+/reports+/inventory-valuation.tsx
@@ -14,9 +14,9 @@ import type { Handle } from "~/utils/handle";
import { path } from "~/utils/path";
export const handle: Handle = {
- breadcrumb: msg`Valuation`,
+ breadcrumb: msg`Inventory Valuation`,
to: path.to.inventoryValuation,
- module: "inventory"
+ module: "accounting"
};
export async function loader({ request }: LoaderFunctionArgs) {
diff --git a/apps/erp/app/routes/x+/reports+/purchases.tsx b/apps/erp/app/routes/x+/reports+/purchases.tsx
new file mode 100644
index 0000000000..2e84419e37
--- /dev/null
+++ b/apps/erp/app/routes/x+/reports+/purchases.tsx
@@ -0,0 +1,346 @@
+import { error } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import { VStack } from "@carbon/react";
+import {
+ computeReportPeriodBuckets,
+ datetime,
+ defaultReportRange
+} from "@carbon/utils";
+import { msg } from "@lingui/core/macro";
+import { useLingui } from "@lingui/react/macro";
+import { useLocale } from "@react-aria/i18n";
+import { useMemo, useState } from "react";
+import type { LoaderFunctionArgs } from "react-router";
+import { redirect, useFetcher, useLoaderData } from "react-router";
+import { useUrlParams } from "~/hooks";
+import type { PivotState, PurchaseLinePivotLine } from "~/modules/accounting";
+import {
+ applyPivotDisplayParams,
+ getFiscalYearSettings,
+ getPurchaseLinePivot,
+ pivotStateValidator,
+ purchaseGroupingFields
+} from "~/modules/accounting";
+import type { PivotCellCoordinates } from "~/modules/accounting/ui/Reports";
+import {
+ getPeriodColumnLabel,
+ PivotTree,
+ PurchaseLinesDrawer,
+ PurchasesControlBar
+} from "~/modules/accounting/ui/Reports";
+import {
+ buildPivotTree,
+ pivotToCsvRows,
+ UNASSIGNED_COLUMN_KEY
+} from "~/modules/accounting/ui/Reports/pivotData";
+import { months } from "~/modules/shared";
+import { getCompanyTimeZone } from "~/modules/shared/timezone.server";
+import type { Handle } from "~/utils/handle";
+import { path } from "~/utils/path";
+import { revalidateIgnoringPivotDisplay } from "~/utils/revalidate";
+
+export const handle: Handle = {
+ breadcrumb: () => msg`Purchases`
+};
+
+const isGroupingField = (value: string): boolean =>
+ (purchaseGroupingFields as readonly string[]).includes(value);
+
+// Explicit pivot params present in the URL override the report default field by
+// field. Rows/column carry grouping-field keys (not journal dimension ids).
+function parsePurchaseUrlParams(
+ searchParams: URLSearchParams
+): Record<string, unknown> {
+ const partial: Record<string, unknown> = {};
+
+ const rows = searchParams.get("rows");
+ if (rows !== null) {
+ partial.rows = rows.split(",").filter(Boolean).slice(0, 2);
+ }
+
+ const col = searchParams.get("col");
+ if (col?.startsWith("period:")) {
+ partial.columnAxis = {
+ type: "period",
+ bucket: col.slice("period:".length)
+ };
+ } else if (col?.startsWith("dim:")) {
+ partial.columnAxis = {
+ type: "dimension",
+ dimensionId: col.slice("dim:".length)
+ };
+ }
+
+ const measure = searchParams.get("measure");
+ if (measure !== null) partial.measure = measure;
+
+ const pct = searchParams.get("pct");
+ if (pct !== null) partial.percentOfTotal = pct === "1";
+
+ const sort = searchParams.get("sort");
+ if (sort !== null) {
+ const separator = sort.lastIndexOf(":");
+ const key = separator > 0 ? sort.slice(0, separator) : "";
+ const direction = separator > 0 ? sort.slice(separator + 1) : "";
+ if (key && (direction === "asc" || direction === "desc")) {
+ partial.sort = { key, direction };
+ }
+ }
+
+ return partial;
+}
+
+// measure / % of total / sort are applied client-side by buildPivotTree, so a
+// change to only those skips the pivot refetch; the component re-derives them
+// from the URL via applyPivotDisplayParams.
+export const shouldRevalidate = revalidateIgnoringPivotDisplay;
+
+export async function loader({ request }: LoaderFunctionArgs) {
+ const { client, companyId } = await requirePermissions(request, {
+ view: "accounting",
+ role: "employee"
+ });
+
+ const url = new URL(request.url);
+
+ const range = defaultReportRange(
+ url.searchParams.get("endDate") ??
+ datetime.today(await getCompanyTimeZone(client, companyId)).toString()
+ );
+ const startDate = url.searchParams.get("startDate") ?? range.startDate;
+ const endDate = range.endDate;
+
+ const fiscalYearSettings = await getFiscalYearSettings(client, companyId);
+ if (
+ fiscalYearSettings.error &&
+ fiscalYearSettings.error.code !== "PGRST116"
+ ) {
+ throw new Error("Failed to load fiscal year settings");
+ }
+ const fiscalStartMonth =
+ months.indexOf(fiscalYearSettings.data?.startMonth ?? "January") + 1;
+
+ // Precedence: explicit URL pivot params over the report default (Supplier).
+ const defaultState = pivotStateValidator.parse({ rows: ["supplier"] });
+ const merged = pivotStateValidator.safeParse({
+ ...defaultState,
+ ...parsePurchaseUrlParams(url.searchParams)
+ });
+ const rawState = merged.success ? merged.data : defaultState;
+
+ // Keep only valid grouping fields; a bad bookmark must not 500.
+ const rows: string[] = [];
+ for (const entry of rawState.rows) {
+ if (isGroupingField(entry) && !rows.includes(entry)) rows.push(entry);
+ }
+
+ let columnAxis: PivotState["columnAxis"] = rawState.columnAxis;
+ if (
+ columnAxis.type === "dimension" &&
+ !isGroupingField(columnAxis.dimensionId)
+ ) {
+ columnAxis = { type: "period", bucket: "month" };
+ }
+
+ const state: PivotState = { ...rawState, rows, columnAxis };
+
+ const periods =
+ state.columnAxis.type === "period"
+ ? computeReportPeriodBuckets(
+ startDate,
+ endDate,
+ state.columnAxis.bucket,
+ fiscalStartMonth
+ )
+ : [];
+
+ const pivotResult = await getPurchaseLinePivot(client, {
+ companyId,
+ startDate,
+ endDate,
+ ...(state.columnAxis.type === "period"
+ ? { periodEnds: periods.map((bucket) => bucket.end) }
+ : {}),
+ state
+ });
+
+ if (pivotResult.error || !pivotResult.data) {
+ throw redirect(
+ path.to.accounting,
+ await flash(
+ request,
+ error(pivotResult.error, "Failed to load purchases report")
+ )
+ );
+ }
+
+ return { pivot: pivotResult.data, state, periods, startDate, endDate };
+}
+
+export default function PurchasesReportRoute() {
+ const {
+ pivot,
+ state: loaderState,
+ periods,
+ startDate,
+ endDate
+ } = useLoaderData<typeof loader>();
+ const { t } = useLingui();
+ const { locale } = useLocale();
+ const [searchParams] = useUrlParams();
+
+ // measure / % of total / sort are applied client-side; when only those change
+ // the loader is skipped (revalidateIgnoringPivotDisplay), so overlay them from
+ // the URL to keep the pivot in sync without a refetch.
+ // biome-ignore lint/correctness/useExhaustiveDependencies: keyed by the URL string, not the unstable URLSearchParams identity
+ const state = useMemo(
+ () => applyPivotDisplayParams(loaderState, searchParams),
+ [loaderState, searchParams.toString()]
+ );
+
+ const linesFetcher = useFetcher<{ lines: PurchaseLinePivotLine[] }>();
+ const [drillTitle, setDrillTitle] = useState<string | null>(null);
+
+ const bucket =
+ state.columnAxis.type === "period" ? state.columnAxis.bucket : undefined;
+
+ const columnLabels = useMemo(() => {
+ const labels: Record<string, string> = {
+ [UNASSIGNED_COLUMN_KEY]: t`Unassigned`
+ };
+ if (bucket) {
+ for (const period of periods) {
+ labels[period.end] = getPeriodColumnLabel(period, bucket, locale);
+ }
+ } else {
+ for (const key of pivot.columnKeys) {
+ if (key === UNASSIGNED_COLUMN_KEY) continue;
+ labels[key] = pivot.valueNames[key] ?? key;
+ }
+ }
+ return labels;
+ }, [bucket, periods, pivot, locale, t]);
+
+ const onCellClick = (cell: PivotCellCoordinates) => {
+ const titleParts: string[] = [];
+ if (cell.rowValue1IsNull) {
+ titleParts.push(t`Unassigned`);
+ } else if (cell.rowValue1Id) {
+ titleParts.push(pivot.valueNames[cell.rowValue1Id] ?? cell.rowValue1Id);
+ }
+ if (cell.rowValue2IsNull) {
+ titleParts.push(t`Unassigned`);
+ } else if (cell.rowValue2Id) {
+ titleParts.push(pivot.valueNames[cell.rowValue2Id] ?? cell.rowValue2Id);
+ }
+ titleParts.push(
+ cell.isRowTotal
+ ? t`Total`
+ : cell.columnKey === null
+ ? t`Unassigned`
+ : (columnLabels[cell.columnKey] ?? cell.columnKey)
+ );
+
+ const searchParams = new URLSearchParams({ startDate, endDate });
+
+ const rowField1 = state.rows[0];
+ if (rowField1 && (cell.rowValue1IsNull || cell.rowValue1Id)) {
+ searchParams.set("r1f", rowField1);
+ if (cell.rowValue1IsNull) searchParams.set("r1null", "1");
+ else if (cell.rowValue1Id) searchParams.set("r1", cell.rowValue1Id);
+ }
+
+ const rowField2 = state.rows[1];
+ if (rowField2 && (cell.rowValue2IsNull || cell.rowValue2Id)) {
+ searchParams.set("r2f", rowField2);
+ if (cell.rowValue2IsNull) searchParams.set("r2null", "1");
+ else if (cell.rowValue2Id) searchParams.set("r2", cell.rowValue2Id);
+ }
+
+ if (!cell.isRowTotal) {
+ if (state.columnAxis.type === "dimension") {
+ searchParams.set("colf", state.columnAxis.dimensionId);
+ if (cell.columnKey === null) searchParams.set("colvnull", "1");
+ else searchParams.set("colv", cell.columnKey);
+ } else if (cell.columnKey !== null) {
+ const period = periods.find((p) => p.end === cell.columnKey);
+ if (period) {
+ searchParams.set("colstart", period.start);
+ searchParams.set("colend", period.end);
+ }
+ }
+ }
+
+ setDrillTitle(titleParts.join(" · "));
+ linesFetcher.load(
+ `${path.to.api.purchasesReportLines}?${searchParams.toString()}`
+ );
+ };
+
+ const onDownload = () => {
+ const tree = buildPivotTree({
+ groups: pivot.groups,
+ valueNames: pivot.valueNames,
+ columnKeys: pivot.columnKeys,
+ rowCount: Math.min(state.rows.length, 2) as 0 | 1 | 2,
+ measure: state.measure,
+ unassignedLabel: t`Unassigned`,
+ totalLabel: t`Total`,
+ sort: state.sort
+ });
+
+ const rows = pivotToCsvRows({
+ flatTree: tree.flatTree,
+ columnKeys: tree.columnKeys,
+ columnTotals: tree.columnTotals,
+ grandTotal: tree.grandTotal,
+ measure: state.measure,
+ columnLabels
+ });
+ if (rows.length === 0) return;
+
+ const sanitizeCell = (value: string) => {
+ if (value === "" || Number.isFinite(Number(value))) return value;
+ return /^[=+\-@]/.test(value) ? `'${value}` : value;
+ };
+ const csvData = rows
+ .map((row) =>
+ row
+ .map(sanitizeCell)
+ .map((value) =>
+ /[",\n]/.test(value) ? `"${value.replace(/"/g, '""')}"` : value
+ )
+ .join(",")
+ )
+ .join("\n");
+ const blob = new Blob([csvData], { type: "text/csv" });
+ const downloadUrl = window.URL.createObjectURL(blob);
+ const anchor = document.createElement("a");
+ anchor.href = downloadUrl;
+ anchor.download = "purchases.csv";
+ document.body.appendChild(anchor);
+ anchor.click();
+ window.URL.revokeObjectURL(downloadUrl);
+ document.body.removeChild(anchor);
+ };
+
+ return (
+ <VStack spacing={0} className="h-full">
+ <PurchasesControlBar state={state} onDownload={onDownload} />
+ <PivotTree
+ pivot={pivot}
+ state={state}
+ columnLabels={columnLabels}
+ onCellClick={onCellClick}
+ />
+ <PurchaseLinesDrawer
+ open={drillTitle !== null}
+ onClose={() => setDrillTitle(null)}
+ title={drillTitle ?? ""}
+ lines={linesFetcher.data?.lines ?? null}
+ isLoading={linesFetcher.state !== "idle"}
+ />
+ </VStack>
+ );
+}
diff --git a/apps/erp/app/routes/x+/accounting+/trial-balance.$accountId.tsx b/apps/erp/app/routes/x+/reports+/trial-balance.$accountId.tsx
similarity index 100%
rename from apps/erp/app/routes/x+/accounting+/trial-balance.$accountId.tsx
rename to apps/erp/app/routes/x+/reports+/trial-balance.$accountId.tsx
diff --git a/apps/erp/app/routes/x+/accounting+/trial-balance.tsx b/apps/erp/app/routes/x+/reports+/trial-balance.tsx
similarity index 78%
rename from apps/erp/app/routes/x+/accounting+/trial-balance.tsx
rename to apps/erp/app/routes/x+/reports+/trial-balance.tsx
index 1c18d7c787..2515502a7d 100644
--- a/apps/erp/app/routes/x+/accounting+/trial-balance.tsx
+++ b/apps/erp/app/routes/x+/reports+/trial-balance.tsx
@@ -2,13 +2,14 @@ import { error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { VStack } from "@carbon/react";
-import { datetime } from "@carbon/utils";
+import { datetime, defaultReportRange } from "@carbon/utils";
import { msg } from "@lingui/core/macro";
import { useState } from "react";
import type { LoaderFunctionArgs } from "react-router";
import { Outlet, redirect, useLoaderData } from "react-router";
import type { Chart } from "~/modules/accounting";
import {
+ financialReportParamsValidator,
getCompaniesInGroup,
getConsolidatedBalances,
getFinancialStatementBalances,
@@ -16,6 +17,7 @@ import {
translateCompanyBalances
} from "~/modules/accounting";
import {
+ exportTrialBalance,
ReportFilters,
TrialBalanceTree
} from "~/modules/accounting/ui/Reports";
@@ -42,11 +44,20 @@ export async function loader({ request }: LoaderFunctionArgs) {
);
const url = new URL(request.url);
- const searchParams = new URLSearchParams(url.search);
- const companiesParam = searchParams.get("companies");
- const startDate = searchParams.get("startDate") || null;
- const endDate = searchParams.get("endDate") || null;
- const showTranslated = searchParams.get("showTranslated") === "true";
+ // Invalid params fall back to defaults — a bad bookmark must not 500
+ const parsed = financialReportParamsValidator.safeParse(
+ Object.fromEntries(url.searchParams.entries())
+ );
+ const companiesParam = parsed.success
+ ? (parsed.data.companies ?? null)
+ : null;
+ const startDateParam = parsed.success
+ ? (parsed.data.startDate ?? null)
+ : null;
+ const endDateParam = parsed.success ? (parsed.data.endDate ?? null) : null;
+ const showTranslatedParam = parsed.success
+ ? parsed.data.showTranslated
+ : false;
const [companies, fiscalYearSettings] = await Promise.all([
getCompaniesInGroup(client, companyGroupId),
@@ -66,17 +77,23 @@ export async function loader({ request }: LoaderFunctionArgs) {
: [companyId];
const isMultiCompany = selectedCompanyIds.length > 1;
+ // Default to the trailing six months, matching every other range report
+ // (previously trial balance alone defaulted to all-time).
+ const range = defaultReportRange(
+ endDateParam ??
+ datetime.today(await getCompanyTimeZone(client, companyId)).toString()
+ );
+ const startDate = startDateParam ?? range.startDate;
+ const endDate = endDateParam ?? range.endDate;
+
if (isMultiCompany && parentCurrency) {
- const periodEnd =
- endDate ??
- datetime.today(await getCompanyTimeZone(client, companyId)).toString();
const consolidated = await getConsolidatedBalances(
client,
companyGroupId,
selectedCompanyIds,
parentCurrency,
- periodEnd,
- startDate ?? undefined
+ endDate,
+ startDate
);
return {
@@ -124,17 +141,14 @@ export async function loader({ request }: LoaderFunctionArgs) {
exchangeRate?: number;
})[];
- if (showTranslated && isForeignCurrency && parentCurrency) {
- const periodEnd =
- endDate ??
- datetime.today(await getCompanyTimeZone(client, companyId)).toString();
+ if (showTranslatedParam && isForeignCurrency && parentCurrency) {
const translation = await translateCompanyBalances(
client,
companyGroupId,
selectedCompanyId!,
parentCurrency,
- periodEnd,
- startDate ?? undefined,
+ endDate,
+ startDate,
balances.data ?? []
);
@@ -161,7 +175,7 @@ export async function loader({ request }: LoaderFunctionArgs) {
trialBalance: accounts,
companies: companiesList,
selectedCompanyIds,
- showTranslated: showTranslated && isForeignCurrency,
+ showTranslated: showTranslatedParam && isForeignCurrency,
isMultiCompany: false,
isForeignCurrency,
parentCurrency,
@@ -191,6 +205,15 @@ export default function TrialBalanceRoute() {
isForeignCurrency={isForeignCurrency}
parentCurrency={parentCurrency}
fiscalStartMonth={fiscalStartMonth}
+ onDownload={() =>
+ exportTrialBalance({
+ accounts: trialBalance,
+ showTranslated,
+ parentCurrency,
+ search,
+ filename: "trial-balance.csv"
+ })
+ }
search={search}
onSearchChange={setSearch}
/>
diff --git a/apps/erp/app/routes/x+/reports+/views.$viewId.delete.tsx b/apps/erp/app/routes/x+/reports+/views.$viewId.delete.tsx
new file mode 100644
index 0000000000..f85faa8f42
--- /dev/null
+++ b/apps/erp/app/routes/x+/reports+/views.$viewId.delete.tsx
@@ -0,0 +1,43 @@
+import { assertIsPost, error, success } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import type { ActionFunctionArgs } from "react-router";
+import { data, redirect } from "react-router";
+import { deleteReportView } from "~/modules/accounting";
+import { path } from "~/utils/path";
+
+// Delete a saved report view. Posted to by the ConfirmDelete modal on both the
+// reports hub (/x/accounting/reports) and the analytics report control bar.
+// On success we redirect back to the referrer with the `view` param stripped, so
+// the analytics page drops the now-dead selection and the hub list refreshes.
+// RLS keeps deletes owner-only.
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, companyId } = await requirePermissions(request, {
+ view: "accounting",
+ role: "employee"
+ });
+
+ const { viewId } = params;
+ if (!viewId) {
+ throw new Error("viewId not found");
+ }
+
+ const deletion = await deleteReportView(client, viewId, companyId);
+ if (deletion.error) {
+ return data(
+ {},
+ await flash(request, error(deletion.error, "Failed to delete view"))
+ );
+ }
+
+ const referer = request.headers.get("referer");
+ let redirectTo: string = path.to.reports;
+ if (referer) {
+ const url = new URL(referer);
+ url.searchParams.delete("view");
+ redirectTo = `${url.pathname}${url.search}`;
+ }
+
+ throw redirect(redirectTo, await flash(request, success("View deleted")));
+}
diff --git a/apps/erp/app/stores/ui.ts b/apps/erp/app/stores/ui.ts
index 9ad318ba10..3ba9ba9b50 100644
--- a/apps/erp/app/stores/ui.ts
+++ b/apps/erp/app/stores/ui.ts
@@ -1,5 +1,11 @@
import { create } from "zustand";
+export type SuggestionPrefill = {
+ suggestion: string;
+ anonymous: boolean;
+ sendToCarbon: boolean;
+};
+
interface UIStore {
isSearchModalOpen: boolean;
openSearchModal: () => void;
@@ -8,6 +14,9 @@ interface UIStore {
isSidebarOpen: boolean;
setSidebarOpen: (open: boolean) => void;
toggleSidebar: () => void;
+ suggestionPrefill: SuggestionPrefill | null;
+ requestSuggestion: (prefill: SuggestionPrefill) => void;
+ clearSuggestionRequest: () => void;
}
export const useUIStore = create<UIStore>()((set) => ({
@@ -18,5 +27,9 @@ export const useUIStore = create<UIStore>()((set) => ({
set((state) => ({ isSearchModalOpen: !state.isSearchModalOpen })),
isSidebarOpen: true,
setSidebarOpen: (open) => set({ isSidebarOpen: open }),
- toggleSidebar: () => set((state) => ({ isSidebarOpen: !state.isSidebarOpen }))
+ toggleSidebar: () =>
+ set((state) => ({ isSidebarOpen: !state.isSidebarOpen })),
+ suggestionPrefill: null,
+ requestSuggestion: (prefill) => set({ suggestionPrefill: prefill }),
+ clearSuggestionRequest: () => set({ suggestionPrefill: null })
}));
diff --git a/apps/erp/app/utils/path.ts b/apps/erp/app/utils/path.ts
index b486ee4611..c0e37b6329 100644
--- a/apps/erp/app/utils/path.ts
+++ b/apps/erp/app/utils/path.ts
@@ -41,6 +41,9 @@ export const path = {
generatePath(`${x}/items/methods/versions/activate/${id}`),
addAndIssueMaintenanceDispatchItem: (dispatchId: string) =>
generatePath(`${x}/maintenance/${dispatchId}/add-and-issue`),
+ analyticsReport: (key: string) =>
+ generatePath(`${x}/reports/analytics/${key}`),
+ apAging: `${x}/reports/ap-aging`,
api: {
abilities: `${api}/resources/abilities`,
accounts: `${api}/accounting/accounts`,
@@ -48,6 +51,8 @@ export const path = {
agentFeedback: `${api}/agent/feedback`,
agentThread: (id: string) => `${api}/agent/thread/${id}`,
agentThreads: `${api}/agent/threads`,
+ analyticsReportLines: (key: string) =>
+ generatePath(`${api}/accounting/analytics-lines?reportKey=${key}`),
assemblyForItem: (itemId: string) =>
generatePath(`${api}/production/assembly-for-item/${itemId}`),
assemblyInstructions: (itemId: string) =>
@@ -189,6 +194,7 @@ export const path = {
generatePath(`${api}/production/kpi/${key}`),
purchaseInvoice: (id: string) =>
generatePath(`${api}/purchase-invoice/${id}`),
+ purchasesReportLines: `${api}/accounting/purchase-lines`,
purchasingKpi: (key: string) =>
generatePath(`${api}/purchasing/kpi/${key}`),
qualityKpi: (key: string) => generatePath(`${api}/quality/kpi/${key}`),
@@ -291,6 +297,7 @@ export const path = {
approvalRule: (id: string) =>
generatePath(`${x}/settings/approval-rules/${id}`),
approvalRules: `${x}/settings/approval-rules`,
+ arAging: `${x}/reports/ar-aging`,
assemblyInstruction: (id: string) => generatePath(`${x}/assembly/${id}`),
assemblyInstructionActivate: (id: string) =>
generatePath(`${x}/assembly/${id}/activate`),
@@ -341,9 +348,9 @@ export const path = {
autoMatchAssemblyComponents: (id: string) =>
generatePath(`${x}/assembly/${id}/component-mappings/auto`),
backups: `${x}/settings/backups`,
- balanceSheet: `${x}/accounting/balance-sheet`,
+ balanceSheet: `${x}/reports/balance-sheet`,
balanceSheetLedger: (id: string) =>
- generatePath(`${x}/accounting/balance-sheet/${id}`),
+ generatePath(`${x}/reports/balance-sheet/${id}`),
batchProperty: (itemId: string) =>
generatePath(`${x}/inventory/batch-property/${itemId}/property`),
batchPropertyOrder: (itemId: string) =>
@@ -765,6 +772,8 @@ export const path = {
deleteQuoteOperationTool: (id: string) =>
generatePath(`${x}/quote/methods/operation/tool/delete/${id}`),
deleteReceipt: (id: string) => generatePath(`${x}/receipt/${id}/delete`),
+ deleteReportView: (id: string) =>
+ generatePath(`${x}/reports/views/${id}/delete`),
deleteRequiredAction: (id: string) =>
generatePath(`${x}/quality/required-actions/delete/${id}`),
deleteRisk: (id: string) => generatePath(`${x}/quality/risks/delete/${id}`),
@@ -875,6 +884,7 @@ export const path = {
exchangeRate: (id: string) =>
generatePath(`${x}/accounting/exchange-rates/${id}`),
exchangeRates: `${x}/accounting/exchange-rates`,
+ executivePnl: `${x}/reports/executive-pnl`,
external: {
mes: MES_URL,
mesJobOperation: (id: string) => `${MES_URL}/x/operation/${id}`,
@@ -1134,9 +1144,9 @@ export const path = {
holiday: (id: string) => generatePath(`${x}/people/holidays/${id}`),
holidays: `${x}/people/holidays`,
import: (tableId: string) => generatePath(`${x}/shared/import/${tableId}`),
- incomeStatement: `${x}/accounting/income-statement`,
+ incomeStatement: `${x}/reports/income-statement`,
incomeStatementLedger: (id: string) =>
- generatePath(`${x}/accounting/income-statement/${id}`),
+ generatePath(`${x}/reports/income-statement/${id}`),
inspection: (id: string) => generatePath(`${x}/inspection/${id}`),
inspectionAccept: (id: string) =>
generatePath(`${x}/inspection/${id}/accept`),
@@ -1180,8 +1190,8 @@ export const path = {
generatePath(`${x}/inventory/quantities/${id}/adjustment`),
inventoryRoot: `${x}/inventory`,
inventorySettings: `${x}/settings/inventory`,
- inventoryValuation: `${x}/inventory/valuation`,
- inventoryValuationReconcile: `${x}/inventory/valuation/reconcile`,
+ inventoryValuation: `${x}/reports/inventory-valuation`,
+ inventoryValuationReconcile: `${x}/reports/inventory-valuation/reconcile`,
investigationType: (id: string) =>
generatePath(`${x}/quality/investigation-types/${id}`),
investigationTypes: `${x}/quality/investigation-types`,
@@ -1738,6 +1748,7 @@ export const path = {
purchaseOrderStatus: (id: string) =>
generatePath(`${x}/purchase-order/${id}/status`),
purchaseOrders: `${x}/purchasing/orders`,
+ purchasesReport: `${x}/reports/purchases`,
purchasing: `${x}/purchasing`,
purchasingPlanning: `${x}/purchasing/planning`,
@@ -1848,6 +1859,7 @@ export const path = {
refreshSession: "/refresh-session",
repeatDepreciationRun: (id: string) =>
generatePath(`${x}/depreciation-run/${id}/repeat`),
+ reports: `${x}/accounting/reports`,
requiredAction: (id: string) =>
generatePath(`${x}/quality/required-actions/${id}`),
requiredActions: `${x}/quality/required-actions`,
@@ -2110,9 +2122,9 @@ export const path = {
trainingQuestionOrder: (id: string) =>
generatePath(`${x}/training/${id}/questions/order`),
trainings: `${x}/resources/training`,
- trialBalance: `${x}/accounting/trial-balance`,
+ trialBalance: `${x}/reports/trial-balance`,
trialBalanceLedger: (id: string) =>
- generatePath(`${x}/accounting/trial-balance/${id}`),
+ generatePath(`${x}/reports/trial-balance/${id}`),
uom: (id: string) => generatePath(`${x}/items/uom/${id}`),
uoms: `${x}/items/uom`,
updateAssemblyUnit: (id: string, unitId: string) =>
diff --git a/apps/erp/app/utils/revalidate.ts b/apps/erp/app/utils/revalidate.ts
index 0b87bae8cf..27e4bc84cc 100644
--- a/apps/erp/app/utils/revalidate.ts
+++ b/apps/erp/app/utils/revalidate.ts
@@ -25,3 +25,42 @@ export const revalidateIgnoringOffset: ShouldRevalidateFunction = ({
return defaultShouldRevalidate;
};
+
+// The pivot report display toggles that buildPivotTree applies in the browser —
+// they never change the loader's (expensive) journal RPC inputs, so a change to
+// only these can skip the refetch. The route component re-derives them from the
+// URL via applyPivotDisplayParams so the view stays in sync without a loader run.
+const PIVOT_DISPLAY_PARAMS = ["measure", "pct", "sort"];
+
+/**
+ * Skips revalidation for the analytics pivot reports when a navigation changes
+ * ONLY the client-only display params (`measure` / `pct` / `sort`). Any
+ * server-affecting param change, a different report, a mutation, and an
+ * unchanged URL (realtime journal revalidation, initial load) all revalidate as
+ * usual — so live updates and saved-view/filter/date changes still refetch.
+ */
+export const revalidateIgnoringPivotDisplay: ShouldRevalidateFunction = ({
+ currentUrl,
+ nextUrl,
+ formMethod,
+ defaultShouldRevalidate
+}) => {
+ if (formMethod && formMethod !== "GET") return defaultShouldRevalidate;
+ if (currentUrl.pathname !== nextUrl.pathname) return defaultShouldRevalidate;
+ // Unchanged URL → an explicit revalidation (e.g. realtime) or initial load.
+ if (currentUrl.search === nextUrl.search) return defaultShouldRevalidate;
+
+ const current = new URLSearchParams(currentUrl.search);
+ const next = new URLSearchParams(nextUrl.search);
+ for (const key of PIVOT_DISPLAY_PARAMS) {
+ current.delete(key);
+ next.delete(key);
+ }
+ current.sort();
+ next.sort();
+
+ // Only display params differ → same loader data; skip. Otherwise refetch.
+ if (current.toString() === next.toString()) return false;
+
+ return defaultShouldRevalidate;
+};
diff --git a/packages/database/src/swagger-docs-schema.ts b/packages/database/src/swagger-docs-schema.ts
index 5e65c7e39f..741116a421 100644
--- a/packages/database/src/swagger-docs-schema.ts
+++ b/packages/database/src/swagger-docs-schema.ts
@@ -41952,6 +41952,168 @@ export default {
tags: ["customerStatus"]
}
},
+ "/reportPin": {
+ get: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.reportPin.reportKey"
+ },
+ {
+ $ref: "#/parameters/rowFilter.reportPin.userId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.reportPin.companyId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.reportPin.pinned"
+ },
+ {
+ $ref: "#/parameters/rowFilter.reportPin.createdBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.reportPin.createdAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.reportPin.updatedBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.reportPin.updatedAt"
+ },
+ {
+ $ref: "#/parameters/select"
+ },
+ {
+ $ref: "#/parameters/order"
+ },
+ {
+ $ref: "#/parameters/range"
+ },
+ {
+ $ref: "#/parameters/rangeUnit"
+ },
+ {
+ $ref: "#/parameters/offset"
+ },
+ {
+ $ref: "#/parameters/limit"
+ },
+ {
+ $ref: "#/parameters/preferCount"
+ }
+ ],
+ responses: {
+ "200": {
+ description: "OK",
+ schema: {
+ items: {
+ $ref: "#/definitions/reportPin"
+ },
+ type: "array"
+ }
+ },
+ "206": {
+ description: "Partial Content"
+ }
+ },
+ tags: ["reportPin"]
+ },
+ post: {
+ parameters: [
+ {
+ $ref: "#/parameters/body.reportPin"
+ },
+ {
+ $ref: "#/parameters/select"
+ },
+ {
+ $ref: "#/parameters/preferPost"
+ }
+ ],
+ responses: {
+ "201": {
+ description: "Created"
+ }
+ },
+ tags: ["reportPin"]
+ },
+ delete: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.reportPin.reportKey"
+ },
+ {
+ $ref: "#/parameters/rowFilter.reportPin.userId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.reportPin.companyId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.reportPin.pinned"
+ },
+ {
+ $ref: "#/parameters/rowFilter.reportPin.createdBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.reportPin.createdAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.reportPin.updatedBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.reportPin.updatedAt"
+ },
+ {
+ $ref: "#/parameters/preferReturn"
+ }
+ ],
+ responses: {
+ "204": {
+ description: "No Content"
+ }
+ },
+ tags: ["reportPin"]
+ },
+ patch: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.reportPin.reportKey"
+ },
+ {
+ $ref: "#/parameters/rowFilter.reportPin.userId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.reportPin.companyId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.reportPin.pinned"
+ },
+ {
+ $ref: "#/parameters/rowFilter.reportPin.createdBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.reportPin.createdAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.reportPin.updatedBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.reportPin.updatedAt"
+ },
+ {
+ $ref: "#/parameters/body.reportPin"
+ },
+ {
+ $ref: "#/parameters/preferReturn"
+ }
+ ],
+ responses: {
+ "204": {
+ description: "No Content"
+ }
+ },
+ tags: ["reportPin"]
+ }
+ },
"/storageUnit": {
get: {
parameters: [
@@ -48870,6 +49032,186 @@ export default {
tags: ["customerItemPriceOverride"]
}
},
+ "/reportView": {
+ get: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.reportView.id"
+ },
+ {
+ $ref: "#/parameters/rowFilter.reportView.companyId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.reportView.reportKey"
+ },
+ {
+ $ref: "#/parameters/rowFilter.reportView.name"
+ },
+ {
+ $ref: "#/parameters/rowFilter.reportView.config"
+ },
+ {
+ $ref: "#/parameters/rowFilter.reportView.visibility"
+ },
+ {
+ $ref: "#/parameters/rowFilter.reportView.createdBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.reportView.createdAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.reportView.updatedBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.reportView.updatedAt"
+ },
+ {
+ $ref: "#/parameters/select"
+ },
+ {
+ $ref: "#/parameters/order"
+ },
+ {
+ $ref: "#/parameters/range"
+ },
+ {
+ $ref: "#/parameters/rangeUnit"
+ },
+ {
+ $ref: "#/parameters/offset"
+ },
+ {
+ $ref: "#/parameters/limit"
+ },
+ {
+ $ref: "#/parameters/preferCount"
+ }
+ ],
+ responses: {
+ "200": {
+ description: "OK",
+ schema: {
+ items: {
+ $ref: "#/definitions/reportView"
+ },
+ type: "array"
+ }
+ },
+ "206": {
+ description: "Partial Content"
+ }
+ },
+ tags: ["reportView"]
+ },
+ post: {
+ parameters: [
+ {
+ $ref: "#/parameters/body.reportView"
+ },
+ {
+ $ref: "#/parameters/select"
+ },
+ {
+ $ref: "#/parameters/preferPost"
+ }
+ ],
+ responses: {
+ "201": {
+ description: "Created"
+ }
+ },
+ tags: ["reportView"]
+ },
+ delete: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.reportView.id"
+ },
+ {
+ $ref: "#/parameters/rowFilter.reportView.companyId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.reportView.reportKey"
+ },
+ {
+ $ref: "#/parameters/rowFilter.reportView.name"
+ },
+ {
+ $ref: "#/parameters/rowFilter.reportView.config"
+ },
+ {
+ $ref: "#/parameters/rowFilter.reportView.visibility"
+ },
+ {
+ $ref: "#/parameters/rowFilter.reportView.createdBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.reportView.createdAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.reportView.updatedBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.reportView.updatedAt"
+ },
+ {
+ $ref: "#/parameters/preferReturn"
+ }
+ ],
+ responses: {
+ "204": {
+ description: "No Content"
+ }
+ },
+ tags: ["reportView"]
+ },
+ patch: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.reportView.id"
+ },
+ {
+ $ref: "#/parameters/rowFilter.reportView.companyId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.reportView.reportKey"
+ },
+ {
+ $ref: "#/parameters/rowFilter.reportView.name"
+ },
+ {
+ $ref: "#/parameters/rowFilter.reportView.config"
+ },
+ {
+ $ref: "#/parameters/rowFilter.reportView.visibility"
+ },
+ {
+ $ref: "#/parameters/rowFilter.reportView.createdBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.reportView.createdAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.reportView.updatedBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.reportView.updatedAt"
+ },
+ {
+ $ref: "#/parameters/body.reportView"
+ },
+ {
+ $ref: "#/parameters/preferReturn"
+ }
+ ],
+ responses: {
+ "204": {
+ description: "No Content"
+ }
+ },
+ tags: ["reportView"]
+ }
+ },
"/companyIntegration": {
get: {
parameters: [
@@ -85400,6 +85742,28 @@ export default {
}
},
"/rpc/get_companies_with_employee_permission": {
+ get: {
+ parameters: [
+ {
+ format: "text",
+ in: "query",
+ name: "permission",
+ required: true,
+ type: "string"
+ }
+ ],
+ produces: [
+ "application/json",
+ "application/vnd.pgrst.object+json;nulls=stripped",
+ "application/vnd.pgrst.object+json"
+ ],
+ responses: {
+ "200": {
+ description: "OK"
+ }
+ },
+ tags: ["(rpc) get_companies_with_employee_permission"]
+ },
post: {
parameters: [
{
@@ -85759,6 +86123,28 @@ export default {
}
},
"/rpc/get_permission_companies": {
+ get: {
+ parameters: [
+ {
+ format: "text",
+ in: "query",
+ name: "claim",
+ required: true,
+ type: "string"
+ }
+ ],
+ produces: [
+ "application/json",
+ "application/vnd.pgrst.object+json;nulls=stripped",
+ "application/vnd.pgrst.object+json"
+ ],
+ responses: {
+ "200": {
+ description: "OK"
+ }
+ },
+ tags: ["(rpc) get_permission_companies"]
+ },
post: {
parameters: [
{
@@ -86536,6 +86922,19 @@ export default {
}
},
"/rpc/get_companies_with_employee_role": {
+ get: {
+ produces: [
+ "application/json",
+ "application/vnd.pgrst.object+json;nulls=stripped",
+ "application/vnd.pgrst.object+json"
+ ],
+ responses: {
+ "200": {
+ description: "OK"
+ }
+ },
+ tags: ["(rpc) get_companies_with_employee_role"]
+ },
post: {
parameters: [
{
@@ -86604,6 +87003,61 @@ export default {
tags: ["(rpc) _xid_machine_id"]
}
},
+ "/rpc/accountTreeBalancePeriodSeries": {
+ post: {
+ parameters: [
+ {
+ in: "body",
+ name: "args",
+ required: true,
+ schema: {
+ properties: {
+ p_company_group_id: {
+ format: "text",
+ type: "string"
+ },
+ p_company_id: {
+ format: "text",
+ type: "string"
+ },
+ p_period_ends: {
+ format: "date[]",
+ items: {
+ type: "string"
+ },
+ type: "array"
+ },
+ p_start: {
+ format: "date",
+ type: "string"
+ }
+ },
+ required: [
+ "p_company_group_id",
+ "p_company_id",
+ "p_start",
+ "p_period_ends"
+ ],
+ type: "object"
+ }
+ },
+ {
+ $ref: "#/parameters/preferParams"
+ }
+ ],
+ produces: [
+ "application/json",
+ "application/vnd.pgrst.object+json;nulls=stripped",
+ "application/vnd.pgrst.object+json"
+ ],
+ responses: {
+ "200": {
+ description: "OK"
+ }
+ },
+ tags: ["(rpc) accountTreeBalancePeriodSeries"]
+ }
+ },
"/rpc/jsonb_to_text_array": {
get: {
parameters: [
@@ -86839,6 +87293,28 @@ export default {
}
},
"/rpc/has_any_company_permission": {
+ get: {
+ parameters: [
+ {
+ format: "text",
+ in: "query",
+ name: "claim",
+ required: true,
+ type: "string"
+ }
+ ],
+ produces: [
+ "application/json",
+ "application/vnd.pgrst.object+json;nulls=stripped",
+ "application/vnd.pgrst.object+json"
+ ],
+ responses: {
+ "200": {
+ description: "OK"
+ }
+ },
+ tags: ["(rpc) has_any_company_permission"]
+ },
post: {
parameters: [
{
@@ -89117,6 +89593,72 @@ export default {
tags: ["(rpc) prevent_posted_sales_invoice_deletion"]
}
},
+ "/rpc/purchaseLineDimensionPivot": {
+ post: {
+ parameters: [
+ {
+ in: "body",
+ name: "args",
+ required: true,
+ schema: {
+ properties: {
+ p_column_field: {
+ format: "text",
+ type: "string"
+ },
+ p_company_id: {
+ format: "text",
+ type: "string"
+ },
+ p_end: {
+ format: "date",
+ type: "string"
+ },
+ p_group_limit: {
+ format: "integer",
+ type: "integer"
+ },
+ p_period_ends: {
+ format: "date[]",
+ items: {
+ type: "string"
+ },
+ type: "array"
+ },
+ p_row_field_1: {
+ format: "text",
+ type: "string"
+ },
+ p_row_field_2: {
+ format: "text",
+ type: "string"
+ },
+ p_start: {
+ format: "date",
+ type: "string"
+ }
+ },
+ required: ["p_company_id", "p_start", "p_end"],
+ type: "object"
+ }
+ },
+ {
+ $ref: "#/parameters/preferParams"
+ }
+ ],
+ produces: [
+ "application/json",
+ "application/vnd.pgrst.object+json;nulls=stripped",
+ "application/vnd.pgrst.object+json"
+ ],
+ responses: {
+ "200": {
+ description: "OK"
+ }
+ },
+ tags: ["(rpc) purchaseLineDimensionPivot"]
+ }
+ },
"/rpc/sync_create_make_method_related_records": {
post: {
parameters: [
@@ -90302,6 +90844,125 @@ export default {
tags: ["(rpc) sync_finish_job_operation"]
}
},
+ "/rpc/journalDimensionPivotLines": {
+ post: {
+ parameters: [
+ {
+ in: "body",
+ name: "args",
+ required: true,
+ schema: {
+ properties: {
+ p_account_classes: {
+ format: "text[]",
+ items: {
+ type: "string"
+ },
+ type: "array"
+ },
+ p_account_ids: {
+ format: "text[]",
+ items: {
+ type: "string"
+ },
+ type: "array"
+ },
+ p_account_types: {
+ format: "text[]",
+ items: {
+ type: "string"
+ },
+ type: "array"
+ },
+ p_column_dimension: {
+ format: "text",
+ type: "string"
+ },
+ p_column_period_end: {
+ format: "date",
+ type: "string"
+ },
+ p_column_period_start: {
+ format: "date",
+ type: "string"
+ },
+ p_column_value: {
+ format: "text",
+ type: "string"
+ },
+ p_company_group_id: {
+ format: "text",
+ type: "string"
+ },
+ p_company_id: {
+ format: "text",
+ type: "string"
+ },
+ p_end: {
+ format: "date",
+ type: "string"
+ },
+ p_filter_account_ids: {
+ format: "text[]",
+ items: {
+ type: "string"
+ },
+ type: "array"
+ },
+ p_filters: {
+ format: "jsonb"
+ },
+ p_line_limit: {
+ format: "integer",
+ type: "integer"
+ },
+ p_row_dimension_1: {
+ format: "text",
+ type: "string"
+ },
+ p_row_dimension_2: {
+ format: "text",
+ type: "string"
+ },
+ p_row_value_1: {
+ format: "text",
+ type: "string"
+ },
+ p_row_value_2: {
+ format: "text",
+ type: "string"
+ },
+ p_start: {
+ format: "date",
+ type: "string"
+ }
+ },
+ required: [
+ "p_company_group_id",
+ "p_company_id",
+ "p_start",
+ "p_end"
+ ],
+ type: "object"
+ }
+ },
+ {
+ $ref: "#/parameters/preferParams"
+ }
+ ],
+ produces: [
+ "application/json",
+ "application/vnd.pgrst.object+json;nulls=stripped",
+ "application/vnd.pgrst.object+json"
+ ],
+ responses: {
+ "200": {
+ description: "OK"
+ }
+ },
+ tags: ["(rpc) journalDimensionPivotLines"]
+ }
+ },
"/rpc/get_ap_tie_out": {
post: {
parameters: [
@@ -91227,6 +91888,35 @@ export default {
}
},
"/rpc/get_company_id_from_foreign_key": {
+ get: {
+ parameters: [
+ {
+ format: "text",
+ in: "query",
+ name: "foreign_key",
+ required: true,
+ type: "string"
+ },
+ {
+ format: "text",
+ in: "query",
+ name: "tbl",
+ required: true,
+ type: "string"
+ }
+ ],
+ produces: [
+ "application/json",
+ "application/vnd.pgrst.object+json;nulls=stripped",
+ "application/vnd.pgrst.object+json"
+ ],
+ responses: {
+ "200": {
+ description: "OK"
+ }
+ },
+ tags: ["(rpc) get_company_id_from_foreign_key"]
+ },
post: {
parameters: [
{
@@ -92829,6 +93519,35 @@ export default {
}
},
"/rpc/has_role": {
+ get: {
+ parameters: [
+ {
+ format: "text",
+ in: "query",
+ name: "required_role",
+ required: true,
+ type: "string"
+ },
+ {
+ format: "text",
+ in: "query",
+ name: "company",
+ required: true,
+ type: "string"
+ }
+ ],
+ produces: [
+ "application/json",
+ "application/vnd.pgrst.object+json;nulls=stripped",
+ "application/vnd.pgrst.object+json"
+ ],
+ responses: {
+ "200": {
+ description: "OK"
+ }
+ },
+ tags: ["(rpc) has_role"]
+ },
post: {
parameters: [
{
@@ -93807,6 +94526,51 @@ export default {
tags: ["(rpc) findLowestCommonParent"]
}
},
+ "/rpc/sync_webhook_subscription": {
+ post: {
+ parameters: [
+ {
+ in: "body",
+ name: "args",
+ required: true,
+ schema: {
+ properties: {
+ p_new: {
+ format: "jsonb"
+ },
+ p_old: {
+ format: "jsonb"
+ },
+ p_operation: {
+ format: "text",
+ type: "string"
+ },
+ p_table: {
+ format: "text",
+ type: "string"
+ }
+ },
+ required: ["p_table", "p_operation", "p_new", "p_old"],
+ type: "object"
+ }
+ },
+ {
+ $ref: "#/parameters/preferParams"
+ }
+ ],
+ produces: [
+ "application/json",
+ "application/vnd.pgrst.object+json;nulls=stripped",
+ "application/vnd.pgrst.object+json"
+ ],
+ responses: {
+ "200": {
+ description: "OK"
+ }
+ },
+ tags: ["(rpc) sync_webhook_subscription"]
+ }
+ },
"/rpc/get_active_job_operations_by_employee": {
post: {
parameters: [
@@ -94234,6 +94998,85 @@ export default {
tags: ["(rpc) sync_update_quote_line_make_method_item_id"]
}
},
+ "/rpc/purchaseLinePivotLines": {
+ post: {
+ parameters: [
+ {
+ in: "body",
+ name: "args",
+ required: true,
+ schema: {
+ properties: {
+ p_column_field: {
+ format: "text",
+ type: "string"
+ },
+ p_column_period_end: {
+ format: "date",
+ type: "string"
+ },
+ p_column_period_start: {
+ format: "date",
+ type: "string"
+ },
+ p_column_value: {
+ format: "text",
+ type: "string"
+ },
+ p_company_id: {
+ format: "text",
+ type: "string"
+ },
+ p_end: {
+ format: "date",
+ type: "string"
+ },
+ p_line_limit: {
+ format: "integer",
+ type: "integer"
+ },
+ p_row_field_1: {
+ format: "text",
+ type: "string"
+ },
+ p_row_field_2: {
+ format: "text",
+ type: "string"
+ },
+ p_row_value_1: {
+ format: "text",
+ type: "string"
+ },
+ p_row_value_2: {
+ format: "text",
+ type: "string"
+ },
+ p_start: {
+ format: "date",
+ type: "string"
+ }
+ },
+ required: ["p_company_id", "p_start", "p_end"],
+ type: "object"
+ }
+ },
+ {
+ $ref: "#/parameters/preferParams"
+ }
+ ],
+ produces: [
+ "application/json",
+ "application/vnd.pgrst.object+json;nulls=stripped",
+ "application/vnd.pgrst.object+json"
+ ],
+ responses: {
+ "200": {
+ description: "OK"
+ }
+ },
+ tags: ["(rpc) purchaseLinePivotLines"]
+ }
+ },
"/rpc/update_receipt_line_batch_tracking": {
post: {
parameters: [
@@ -94803,6 +95646,35 @@ export default {
}
},
"/rpc/get_claims": {
+ get: {
+ parameters: [
+ {
+ format: "text",
+ in: "query",
+ name: "uid",
+ required: true,
+ type: "string"
+ },
+ {
+ format: "text",
+ in: "query",
+ name: "company",
+ required: true,
+ type: "string"
+ }
+ ],
+ produces: [
+ "application/json",
+ "application/vnd.pgrst.object+json;nulls=stripped",
+ "application/vnd.pgrst.object+json"
+ ],
+ responses: {
+ "200": {
+ description: "OK"
+ }
+ },
+ tags: ["(rpc) get_claims"]
+ },
post: {
parameters: [
{
@@ -94876,6 +95748,112 @@ export default {
tags: ["(rpc) get_opportunity_with_related_records"]
}
},
+ "/rpc/journalDimensionPivot": {
+ post: {
+ parameters: [
+ {
+ in: "body",
+ name: "args",
+ required: true,
+ schema: {
+ properties: {
+ p_account_classes: {
+ format: "text[]",
+ items: {
+ type: "string"
+ },
+ type: "array"
+ },
+ p_account_ids: {
+ format: "text[]",
+ items: {
+ type: "string"
+ },
+ type: "array"
+ },
+ p_account_types: {
+ format: "text[]",
+ items: {
+ type: "string"
+ },
+ type: "array"
+ },
+ p_column_dimension: {
+ format: "text",
+ type: "string"
+ },
+ p_company_group_id: {
+ format: "text",
+ type: "string"
+ },
+ p_company_id: {
+ format: "text",
+ type: "string"
+ },
+ p_end: {
+ format: "date",
+ type: "string"
+ },
+ p_filter_account_ids: {
+ format: "text[]",
+ items: {
+ type: "string"
+ },
+ type: "array"
+ },
+ p_filters: {
+ format: "jsonb"
+ },
+ p_group_limit: {
+ format: "integer",
+ type: "integer"
+ },
+ p_period_ends: {
+ format: "date[]",
+ items: {
+ type: "string"
+ },
+ type: "array"
+ },
+ p_row_dimension_1: {
+ format: "text",
+ type: "string"
+ },
+ p_row_dimension_2: {
+ format: "text",
+ type: "string"
+ },
+ p_start: {
+ format: "date",
+ type: "string"
+ }
+ },
+ required: [
+ "p_company_group_id",
+ "p_company_id",
+ "p_start",
+ "p_end"
+ ],
+ type: "object"
+ }
+ },
+ {
+ $ref: "#/parameters/preferParams"
+ }
+ ],
+ produces: [
+ "application/json",
+ "application/vnd.pgrst.object+json;nulls=stripped",
+ "application/vnd.pgrst.object+json"
+ ],
+ responses: {
+ "200": {
+ description: "OK"
+ }
+ },
+ tags: ["(rpc) journalDimensionPivot"]
+ }
+ },
"/rpc/getConsolidationRates": {
post: {
parameters: [
@@ -115028,6 +116006,61 @@ export default {
},
type: "object"
},
+ reportPin: {
+ required: [
+ "reportKey",
+ "userId",
+ "companyId",
+ "pinned",
+ "createdBy",
+ "createdAt"
+ ],
+ properties: {
+ reportKey: {
+ description: "Note:\nThis is a Primary Key.<pk/>",
+ format: "text",
+ type: "string"
+ },
+ userId: {
+ description:
+ "Note:\nThis is a Primary Key.<pk/>\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",
+ format: "text",
+ type: "string"
+ },
+ companyId: {
+ description:
+ "Note:\nThis is a Primary Key.<pk/>\nThis is a Foreign Key to `company.id`.<fk table='company' column='id'/>",
+ format: "text",
+ type: "string"
+ },
+ pinned: {
+ format: "boolean",
+ type: "boolean"
+ },
+ createdBy: {
+ description:
+ "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",
+ format: "text",
+ type: "string"
+ },
+ createdAt: {
+ default: "now()",
+ format: "timestamp with time zone",
+ type: "string"
+ },
+ updatedBy: {
+ description:
+ "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",
+ format: "text",
+ type: "string"
+ },
+ updatedAt: {
+ format: "timestamp with time zone",
+ type: "string"
+ }
+ },
+ type: "object"
+ },
storageUnit: {
required: [
"id",
@@ -118223,6 +119256,71 @@ export default {
},
type: "object"
},
+ reportView: {
+ required: [
+ "id",
+ "companyId",
+ "reportKey",
+ "name",
+ "config",
+ "visibility",
+ "createdBy",
+ "createdAt"
+ ],
+ properties: {
+ id: {
+ default: "public.id('rv'::text)",
+ description: "Note:\nThis is a Primary Key.<pk/>",
+ format: "text",
+ type: "string"
+ },
+ companyId: {
+ description:
+ "Note:\nThis is a Primary Key.<pk/>\nThis is a Foreign Key to `company.id`.<fk table='company' column='id'/>",
+ format: "text",
+ type: "string"
+ },
+ reportKey: {
+ format: "text",
+ type: "string"
+ },
+ name: {
+ format: "text",
+ type: "string"
+ },
+ config: {
+ format: "jsonb"
+ },
+ visibility: {
+ default: "Private",
+ enum: ["Private", "Company"],
+ format: 'public."reportViewVisibility"',
+ type: "string"
+ },
+ createdBy: {
+ description:
+ "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",
+ format: "text",
+ type: "string"
+ },
+ createdAt: {
+ default: "now()",
+ format: "timestamp with time zone",
+ type: "string"
+ },
+ updatedBy: {
+ description:
+ "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",
+ format: "text",
+ type: "string"
+ },
+ updatedAt: {
+ format: "timestamp with time zone",
+ type: "string"
+ }
+ },
+ type: "object"
+ },
companyIntegration: {
required: ["id", "metadata", "companyId", "active", "updatedAt"],
properties: {
@@ -157610,6 +158708,63 @@ export default {
in: "query",
type: "string"
},
+ "body.reportPin": {
+ name: "reportPin",
+ description: "reportPin",
+ required: false,
+ in: "body",
+ schema: {
+ $ref: "#/definitions/reportPin"
+ }
+ },
+ "rowFilter.reportPin.reportKey": {
+ name: "reportKey",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.reportPin.userId": {
+ name: "userId",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.reportPin.companyId": {
+ name: "companyId",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.reportPin.pinned": {
+ name: "pinned",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.reportPin.createdBy": {
+ name: "createdBy",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.reportPin.createdAt": {
+ name: "createdAt",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.reportPin.updatedBy": {
+ name: "updatedBy",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.reportPin.updatedAt": {
+ name: "updatedAt",
+ required: false,
+ in: "query",
+ type: "string"
+ },
"body.storageUnit": {
name: "storageUnit",
description: "storageUnit",
@@ -161267,6 +162422,75 @@ export default {
in: "query",
type: "string"
},
+ "body.reportView": {
+ name: "reportView",
+ description: "reportView",
+ required: false,
+ in: "body",
+ schema: {
+ $ref: "#/definitions/reportView"
+ }
+ },
+ "rowFilter.reportView.id": {
+ name: "id",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.reportView.companyId": {
+ name: "companyId",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.reportView.reportKey": {
+ name: "reportKey",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.reportView.name": {
+ name: "name",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.reportView.config": {
+ name: "config",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.reportView.visibility": {
+ name: "visibility",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.reportView.createdBy": {
+ name: "createdBy",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.reportView.createdAt": {
+ name: "createdAt",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.reportView.updatedBy": {
+ name: "updatedBy",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.reportView.updatedAt": {
+ name: "updatedAt",
+ required: false,
+ in: "query",
+ type: "string"
+ },
"body.companyIntegration": {
name: "companyIntegration",
description: "companyIntegration",
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index 851793b9bb..841133f8ac 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -44395,6 +44395,311 @@ export type Database = {
},
]
}
+ reportPin: {
+ Row: {
+ companyId: string
+ createdAt: string
+ createdBy: string
+ pinned: boolean
+ reportKey: string
+ updatedAt: string | null
+ updatedBy: string | null
+ userId: string
+ }
+ Insert: {
+ companyId: string
+ createdAt?: string
+ createdBy: string
+ pinned: boolean
+ reportKey: string
+ updatedAt?: string | null
+ updatedBy?: string | null
+ userId: string
+ }
+ Update: {
+ companyId?: string
+ createdAt?: string
+ createdBy?: string
+ pinned?: boolean
+ reportKey?: string
+ updatedAt?: string | null
+ updatedBy?: string | null
+ userId?: string
+ }
+ Relationships: [
+ {
+ foreignKeyName: "reportPin_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "companies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "reportPin_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "reportPin_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "reportPin_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "integrations"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "reportPin_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "reportPin_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "reportPin_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "reportPin_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "reportPin_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ {
+ foreignKeyName: "reportPin_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "reportPin_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "reportPin_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "reportPin_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "reportPin_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ {
+ foreignKeyName: "reportPin_userId_fkey"
+ columns: ["userId"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "reportPin_userId_fkey"
+ columns: ["userId"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "reportPin_userId_fkey"
+ columns: ["userId"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "reportPin_userId_fkey"
+ columns: ["userId"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "reportPin_userId_fkey"
+ columns: ["userId"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ ]
+ }
+ reportView: {
+ Row: {
+ companyId: string
+ config: Json
+ createdAt: string
+ createdBy: string
+ id: string
+ name: string
+ reportKey: string
+ updatedAt: string | null
+ updatedBy: string | null
+ visibility: Database["public"]["Enums"]["reportViewVisibility"]
+ }
+ Insert: {
+ companyId: string
+ config: Json
+ createdAt?: string
+ createdBy: string
+ id?: string
+ name: string
+ reportKey: string
+ updatedAt?: string | null
+ updatedBy?: string | null
+ visibility?: Database["public"]["Enums"]["reportViewVisibility"]
+ }
+ Update: {
+ companyId?: string
+ config?: Json
+ createdAt?: string
+ createdBy?: string
+ id?: string
+ name?: string
+ reportKey?: string
+ updatedAt?: string | null
+ updatedBy?: string | null
+ visibility?: Database["public"]["Enums"]["reportViewVisibility"]
+ }
+ Relationships: [
+ {
+ foreignKeyName: "reportView_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "companies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "reportView_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "reportView_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "reportView_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "integrations"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "reportView_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "reportView_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "reportView_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "reportView_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "reportView_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ {
+ foreignKeyName: "reportView_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "reportView_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "reportView_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "reportView_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "reportView_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ ]
+ }
rework: {
Row: {
companyId: string
@@ -70177,14 +70482,14 @@ export type Database = {
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["shipmentCountryCode"]
+ columns: ["invoiceCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["invoiceCountryCode"]
+ columns: ["shipmentCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -74007,6 +74312,20 @@ export type Database = {
}
Functions: {
_xid_machine_id: { Args: never; Returns: number }
+ accountTreeBalancePeriodSeries: {
+ Args: {
+ p_company_group_id: string
+ p_company_id: string
+ p_period_ends: string[]
+ p_start: string
+ }
+ Returns: {
+ accountId: string
+ balanceAtDate: number
+ netChange: number
+ periodEnd: string
+ }[]
+ }
accountTreeBalances: {
Args: {
from_date?: string
@@ -76073,6 +76392,68 @@ export type Database = {
similarity: number
}[]
}
+ journalDimensionPivot: {
+ Args: {
+ p_account_classes?: string[]
+ p_account_ids?: string[]
+ p_account_types?: string[]
+ p_column_dimension?: string
+ p_company_group_id: string
+ p_company_id: string
+ p_end: string
+ p_filter_account_ids?: string[]
+ p_filters?: Json
+ p_group_limit?: number
+ p_period_ends?: string[]
+ p_row_dimension_1?: string
+ p_row_dimension_2?: string
+ p_start: string
+ }
+ Returns: {
+ amount: number
+ columnKey: string
+ hasMore: boolean
+ lineCount: number
+ quantity: number
+ rowValue1Id: string
+ rowValue2Id: string
+ }[]
+ }
+ journalDimensionPivotLines: {
+ Args: {
+ p_account_classes?: string[]
+ p_account_ids?: string[]
+ p_account_types?: string[]
+ p_column_dimension?: string
+ p_column_period_end?: string
+ p_column_period_start?: string
+ p_column_value?: string
+ p_company_group_id: string
+ p_company_id: string
+ p_end: string
+ p_filter_account_ids?: string[]
+ p_filters?: Json
+ p_line_limit?: number
+ p_row_dimension_1?: string
+ p_row_dimension_2?: string
+ p_row_value_1?: string
+ p_row_value_2?: string
+ p_start: string
+ }
+ Returns: {
+ accountId: string
+ accountName: string
+ accountNumber: string
+ amount: number
+ description: string
+ documentId: string
+ documentType: string
+ id: string
+ journalEntryId: string
+ postingDate: string
+ quantity: number
+ }[]
+ }
journalLinesByAccountNumber: {
Args: { from_date?: string; to_date?: string }
Returns: {
@@ -76128,6 +76509,53 @@ export type Database = {
Args: { p_new: Json; p_old: Json; p_operation: string; p_table: string }
Returns: undefined
}
+ purchaseLineDimensionPivot: {
+ Args: {
+ p_column_field?: string
+ p_company_id: string
+ p_end: string
+ p_group_limit?: number
+ p_period_ends?: string[]
+ p_row_field_1?: string
+ p_row_field_2?: string
+ p_start: string
+ }
+ Returns: {
+ amount: number
+ columnKey: string
+ hasMore: boolean
+ lineCount: number
+ quantity: number
+ rowValue1Id: string
+ rowValue2Id: string
+ }[]
+ }
+ purchaseLinePivotLines: {
+ Args: {
+ p_column_field?: string
+ p_column_period_end?: string
+ p_column_period_start?: string
+ p_column_value?: string
+ p_company_id: string
+ p_end: string
+ p_line_limit?: number
+ p_row_field_1?: string
+ p_row_field_2?: string
+ p_row_value_1?: string
+ p_row_value_2?: string
+ p_start: string
+ }
+ Returns: {
+ amount: number
+ description: string
+ id: string
+ invoiceReadableId: string
+ itemReadableId: string
+ postingDate: string
+ quantity: number
+ supplierName: string
+ }[]
+ }
recompute_service_line_fulfillment: {
Args: {
p_company_id: string
@@ -76446,6 +76874,10 @@ export type Database = {
Args: { p_new: Json; p_old: Json; p_operation: string; p_table: string }
Returns: undefined
}
+ sync_webhook_subscription: {
+ Args: { p_new: Json; p_old: Json; p_operation: string; p_table: string }
+ Returns: undefined
+ }
translateTrialBalance: {
Args: {
p_company_group_id: string
@@ -77059,6 +77491,7 @@ export type Database = {
| "Manufacturing Consumption"
| "Manufacturing Output"
receiptStatus: "Draft" | "Pending" | "Posted" | "Voided"
+ reportViewVisibility: "Private" | "Company"
riskRegisterType: "Risk" | "Opportunity"
riskSource:
| "Customer"
@@ -78466,6 +78899,7 @@ export const Constants = {
"Manufacturing Output",
],
receiptStatus: ["Draft", "Pending", "Posted", "Voided"],
+ reportViewVisibility: ["Private", "Company"],
riskRegisterType: ["Risk", "Opportunity"],
riskSource: [
"Customer",
diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.ts
index 851793b9bb..841133f8ac 100644
--- a/packages/database/supabase/functions/lib/types.ts
+++ b/packages/database/supabase/functions/lib/types.ts
@@ -44395,6 +44395,311 @@ export type Database = {
},
]
}
+ reportPin: {
+ Row: {
+ companyId: string
+ createdAt: string
+ createdBy: string
+ pinned: boolean
+ reportKey: string
+ updatedAt: string | null
+ updatedBy: string | null
+ userId: string
+ }
+ Insert: {
+ companyId: string
+ createdAt?: string
+ createdBy: string
+ pinned: boolean
+ reportKey: string
+ updatedAt?: string | null
+ updatedBy?: string | null
+ userId: string
+ }
+ Update: {
+ companyId?: string
+ createdAt?: string
+ createdBy?: string
+ pinned?: boolean
+ reportKey?: string
+ updatedAt?: string | null
+ updatedBy?: string | null
+ userId?: string
+ }
+ Relationships: [
+ {
+ foreignKeyName: "reportPin_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "companies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "reportPin_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "reportPin_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "reportPin_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "integrations"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "reportPin_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "reportPin_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "reportPin_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "reportPin_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "reportPin_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ {
+ foreignKeyName: "reportPin_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "reportPin_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "reportPin_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "reportPin_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "reportPin_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ {
+ foreignKeyName: "reportPin_userId_fkey"
+ columns: ["userId"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "reportPin_userId_fkey"
+ columns: ["userId"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "reportPin_userId_fkey"
+ columns: ["userId"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "reportPin_userId_fkey"
+ columns: ["userId"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "reportPin_userId_fkey"
+ columns: ["userId"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ ]
+ }
+ reportView: {
+ Row: {
+ companyId: string
+ config: Json
+ createdAt: string
+ createdBy: string
+ id: string
+ name: string
+ reportKey: string
+ updatedAt: string | null
+ updatedBy: string | null
+ visibility: Database["public"]["Enums"]["reportViewVisibility"]
+ }
+ Insert: {
+ companyId: string
+ config: Json
+ createdAt?: string
+ createdBy: string
+ id?: string
+ name: string
+ reportKey: string
+ updatedAt?: string | null
+ updatedBy?: string | null
+ visibility?: Database["public"]["Enums"]["reportViewVisibility"]
+ }
+ Update: {
+ companyId?: string
+ config?: Json
+ createdAt?: string
+ createdBy?: string
+ id?: string
+ name?: string
+ reportKey?: string
+ updatedAt?: string | null
+ updatedBy?: string | null
+ visibility?: Database["public"]["Enums"]["reportViewVisibility"]
+ }
+ Relationships: [
+ {
+ foreignKeyName: "reportView_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "companies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "reportView_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "reportView_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "reportView_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "integrations"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "reportView_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "reportView_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "reportView_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "reportView_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "reportView_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ {
+ foreignKeyName: "reportView_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "reportView_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "reportView_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "reportView_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "reportView_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ ]
+ }
rework: {
Row: {
companyId: string
@@ -70177,14 +70482,14 @@ export type Database = {
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["shipmentCountryCode"]
+ columns: ["invoiceCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["invoiceCountryCode"]
+ columns: ["shipmentCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -74007,6 +74312,20 @@ export type Database = {
}
Functions: {
_xid_machine_id: { Args: never; Returns: number }
+ accountTreeBalancePeriodSeries: {
+ Args: {
+ p_company_group_id: string
+ p_company_id: string
+ p_period_ends: string[]
+ p_start: string
+ }
+ Returns: {
+ accountId: string
+ balanceAtDate: number
+ netChange: number
+ periodEnd: string
+ }[]
+ }
accountTreeBalances: {
Args: {
from_date?: string
@@ -76073,6 +76392,68 @@ export type Database = {
similarity: number
}[]
}
+ journalDimensionPivot: {
+ Args: {
+ p_account_classes?: string[]
+ p_account_ids?: string[]
+ p_account_types?: string[]
+ p_column_dimension?: string
+ p_company_group_id: string
+ p_company_id: string
+ p_end: string
+ p_filter_account_ids?: string[]
+ p_filters?: Json
+ p_group_limit?: number
+ p_period_ends?: string[]
+ p_row_dimension_1?: string
+ p_row_dimension_2?: string
+ p_start: string
+ }
+ Returns: {
+ amount: number
+ columnKey: string
+ hasMore: boolean
+ lineCount: number
+ quantity: number
+ rowValue1Id: string
+ rowValue2Id: string
+ }[]
+ }
+ journalDimensionPivotLines: {
+ Args: {
+ p_account_classes?: string[]
+ p_account_ids?: string[]
+ p_account_types?: string[]
+ p_column_dimension?: string
+ p_column_period_end?: string
+ p_column_period_start?: string
+ p_column_value?: string
+ p_company_group_id: string
+ p_company_id: string
+ p_end: string
+ p_filter_account_ids?: string[]
+ p_filters?: Json
+ p_line_limit?: number
+ p_row_dimension_1?: string
+ p_row_dimension_2?: string
+ p_row_value_1?: string
+ p_row_value_2?: string
+ p_start: string
+ }
+ Returns: {
+ accountId: string
+ accountName: string
+ accountNumber: string
+ amount: number
+ description: string
+ documentId: string
+ documentType: string
+ id: string
+ journalEntryId: string
+ postingDate: string
+ quantity: number
+ }[]
+ }
journalLinesByAccountNumber: {
Args: { from_date?: string; to_date?: string }
Returns: {
@@ -76128,6 +76509,53 @@ export type Database = {
Args: { p_new: Json; p_old: Json; p_operation: string; p_table: string }
Returns: undefined
}
+ purchaseLineDimensionPivot: {
+ Args: {
+ p_column_field?: string
+ p_company_id: string
+ p_end: string
+ p_group_limit?: number
+ p_period_ends?: string[]
+ p_row_field_1?: string
+ p_row_field_2?: string
+ p_start: string
+ }
+ Returns: {
+ amount: number
+ columnKey: string
+ hasMore: boolean
+ lineCount: number
+ quantity: number
+ rowValue1Id: string
+ rowValue2Id: string
+ }[]
+ }
+ purchaseLinePivotLines: {
+ Args: {
+ p_column_field?: string
+ p_column_period_end?: string
+ p_column_period_start?: string
+ p_column_value?: string
+ p_company_id: string
+ p_end: string
+ p_line_limit?: number
+ p_row_field_1?: string
+ p_row_field_2?: string
+ p_row_value_1?: string
+ p_row_value_2?: string
+ p_start: string
+ }
+ Returns: {
+ amount: number
+ description: string
+ id: string
+ invoiceReadableId: string
+ itemReadableId: string
+ postingDate: string
+ quantity: number
+ supplierName: string
+ }[]
+ }
recompute_service_line_fulfillment: {
Args: {
p_company_id: string
@@ -76446,6 +76874,10 @@ export type Database = {
Args: { p_new: Json; p_old: Json; p_operation: string; p_table: string }
Returns: undefined
}
+ sync_webhook_subscription: {
+ Args: { p_new: Json; p_old: Json; p_operation: string; p_table: string }
+ Returns: undefined
+ }
translateTrialBalance: {
Args: {
p_company_group_id: string
@@ -77059,6 +77491,7 @@ export type Database = {
| "Manufacturing Consumption"
| "Manufacturing Output"
receiptStatus: "Draft" | "Pending" | "Posted" | "Voided"
+ reportViewVisibility: "Private" | "Company"
riskRegisterType: "Risk" | "Opportunity"
riskSource:
| "Customer"
@@ -78466,6 +78899,7 @@ export const Constants = {
"Manufacturing Output",
],
receiptStatus: ["Draft", "Pending", "Posted", "Voided"],
+ reportViewVisibility: ["Private", "Company"],
riskRegisterType: ["Risk", "Opportunity"],
riskSource: [
"Customer",
diff --git a/packages/database/supabase/migrations/20260809151458_balance-rpc-period-series.sql b/packages/database/supabase/migrations/20260809151458_balance-rpc-period-series.sql
new file mode 100644
index 0000000000..f544ed63f3
--- /dev/null
+++ b/packages/database/supabase/migrations/20260809151458_balance-rpc-period-series.sql
@@ -0,0 +1,167 @@
+-- ============================================================
+-- accountTreeBalancePeriodSeries: multi-period balances in one scan.
+--
+-- Powers the /x/reports balance sheet + income statement comparison
+-- columns (Monthly / Quarterly / Yearly). For each bucket end date it
+-- returns the cumulative balance through that date and the net change
+-- since the previous bucket (the first bucket's baseline is the day
+-- before p_start), rolled up to every account via the same recursive
+-- accountTree CTE as accountTreeBalancesByCompany.
+--
+-- Builds on the accountingPeriodBalance snapshots (20260713232634):
+-- the base is the newest snapshot strictly BEFORE p_start, and the only
+-- journal scan is the bounded window (base, max(p_period_ends)]. Unlike
+-- accountTreeBalancesByCompany there is a single uniform branch — with
+-- no snapshots the base COALESCEs to zero at DATE '0001-01-01' and the
+-- scan degrades to full history, which is exactly the pre-snapshot
+-- behavior. Draft journals are excluded, matching the sibling RPCs.
+--
+-- CONTRACT (enforced by computeReportPeriodBuckets in @carbon/utils,
+-- the only producer of p_period_ends):
+-- * p_period_ends is sorted ascending, distinct, and every element
+-- is >= p_start. Lines are bucketed to the FIRST period end >= their
+-- postingDate, so unsorted/overlapping inputs would misassign.
+-- * p_company_id is required — consolidation callers loop companies.
+--
+-- ⚠ KEEP IN SYNC: the "accountTree" recursive CTE below is copied
+-- verbatim from accountTreeBalancesByCompany
+-- (20260713233919_balance-rpc-snapshot-delta.sql). If account-tree
+-- construction or the root rollup changes there, change it here too.
+--
+-- Perf note: the per-line bucket assignment is a correlated MIN(ord)
+-- against the unnested p_period_ends (≤ 60 elements, capped by the TS
+-- helper); delta lines are snapshot-bounded, so this stays cheap.
+-- ============================================================
+
+CREATE OR REPLACE FUNCTION "accountTreeBalancePeriodSeries" (
+ p_company_group_id TEXT,
+ p_company_id TEXT,
+ p_start DATE,
+ p_period_ends DATE[]
+)
+RETURNS TABLE (
+ "accountId" TEXT,
+ "periodEnd" DATE,
+ "balanceAtDate" NUMERIC,
+ "netChange" NUMERIC
+) LANGUAGE "plpgsql" SECURITY INVOKER SET search_path = public
+AS $$
+DECLARE
+ v_base_date DATE; -- newest snapshot strictly before p_start (NULL => no snapshots)
+ v_last_end DATE;
+BEGIN
+ IF p_company_id IS NULL THEN
+ RAISE EXCEPTION 'accountTreeBalancePeriodSeries requires p_company_id';
+ END IF;
+ IF p_period_ends IS NULL OR array_length(p_period_ends, 1) IS NULL THEN
+ RETURN;
+ END IF;
+
+ SELECT MAX(pe) INTO v_last_end FROM unnest(p_period_ends) pe;
+
+ SELECT MAX("endingBalanceDate") INTO v_base_date
+ FROM "accountingPeriodBalance"
+ WHERE "companyId" = p_company_id AND "endingBalanceDate" < p_start;
+
+ RETURN QUERY
+ WITH RECURSIVE "accountTree" AS (
+ SELECT
+ a."id",
+ a."id" AS "rootId",
+ a."isGroup"
+ FROM "account" a
+ WHERE a."companyGroupId" = p_company_group_id AND a."active" = true
+
+ UNION ALL
+
+ SELECT
+ child."id",
+ t."rootId",
+ child."isGroup"
+ FROM "accountTree" t
+ INNER JOIN "account" child ON child."parentId" = t."id"
+ WHERE t."isGroup" = true
+ AND child."companyGroupId" = p_company_group_id
+ AND child."active" = true
+ ),
+ "periods" AS (
+ SELECT pe AS "periodEnd", ord
+ FROM unnest(p_period_ends) WITH ORDINALITY AS u(pe, ord)
+ ),
+ -- The one bounded journal scan: (base snapshot, last bucket end]
+ "deltaLines" AS (
+ SELECT jl."accountId", jl."amount", j."postingDate"
+ FROM "journal" j
+ INNER JOIN "journalLine" jl ON jl."journalId" = j."id"
+ WHERE j."companyId" = p_company_id
+ AND jl."companyId" = p_company_id
+ AND j."status" <> 'Draft'
+ AND j."postingDate" > COALESCE(v_base_date, DATE '0001-01-01')
+ AND j."postingDate" <= v_last_end
+ ),
+ -- ord 0 = the pre-range sliver (base snapshot .. day before p_start):
+ -- the opening anchor that the first bucket's netChange subtracts.
+ "bucketSums" AS (
+ SELECT
+ dl."accountId",
+ CASE WHEN dl."postingDate" < p_start THEN 0::BIGINT
+ ELSE (SELECT MIN(p.ord) FROM "periods" p WHERE p."periodEnd" >= dl."postingDate")
+ END AS ord,
+ SUM(dl."amount") AS "delta"
+ FROM "deltaLines" dl
+ GROUP BY dl."accountId", 2
+ ),
+ "base" AS (
+ SELECT s."accountId", s."endingBalance"
+ FROM "accountingPeriodBalance" s
+ WHERE s."companyId" = p_company_id AND s."endingBalanceDate" = v_base_date
+ ),
+ "leafGrid" AS (
+ SELECT a."id" AS "accountId", g.ord, g."periodEnd"
+ FROM "account" a
+ CROSS JOIN (
+ SELECT 0::BIGINT AS ord, NULL::DATE AS "periodEnd"
+ UNION ALL
+ -- qualify: "periodEnd" is also a RETURNS TABLE out-param name
+ SELECT p2.ord, p2."periodEnd" FROM "periods" p2
+ ) g
+ WHERE a."companyGroupId" = p_company_group_id
+ AND a."isGroup" = false
+ AND a."active" = true
+ ),
+ "leafSeries" AS (
+ SELECT
+ lg."accountId", lg.ord, lg."periodEnd",
+ COALESCE(b."endingBalance", 0)
+ + SUM(COALESCE(bs."delta", 0))
+ OVER (PARTITION BY lg."accountId" ORDER BY lg.ord) AS "balanceAtDate"
+ FROM "leafGrid" lg
+ LEFT JOIN "bucketSums" bs ON bs."accountId" = lg."accountId" AND bs.ord = lg.ord
+ LEFT JOIN "base" b ON b."accountId" = lg."accountId"
+ ),
+ -- Filter ord 0 AFTER the window so LAG sees the opening row.
+ "leafWithChange" AS (
+ SELECT * FROM (
+ SELECT
+ ls."accountId", ls.ord, ls."periodEnd", ls."balanceAtDate",
+ ls."balanceAtDate"
+ - LAG(ls."balanceAtDate") OVER (PARTITION BY ls."accountId" ORDER BY ls.ord)
+ AS "netChange"
+ FROM "leafSeries" ls
+ ) x
+ WHERE x.ord > 0
+ )
+ SELECT
+ t."rootId" AS "accountId",
+ p."periodEnd",
+ COALESCE(SUM(lw."balanceAtDate"), 0)::NUMERIC AS "balanceAtDate",
+ COALESCE(SUM(lw."netChange"), 0)::NUMERIC AS "netChange"
+ FROM "accountTree" t
+ CROSS JOIN "periods" p
+ LEFT JOIN "leafWithChange" lw
+ ON lw."accountId" = t."id"
+ AND lw."periodEnd" = p."periodEnd"
+ AND t."isGroup" = false
+ GROUP BY t."rootId", p."periodEnd";
+END;
+$$;
diff --git a/packages/database/supabase/migrations/20260809161618_report-pins.sql b/packages/database/supabase/migrations/20260809161618_report-pins.sql
new file mode 100644
index 0000000000..06e33c7131
--- /dev/null
+++ b/packages/database/supabase/migrations/20260809161618_report-pins.sql
@@ -0,0 +1,57 @@
+-- ============================================================
+-- reportPin: per-user pin overrides for the reports hub
+-- (/x/accounting/reports). Reports are static definitions keyed by slug
+-- ("balance-sheet", "income-statement", "trial-balance"), not entity rows, so
+-- unlike documentFavorite (presence = favorited) a row here stores an explicit
+-- "pinned" value: the core financial statements default to PINNED, and a row
+-- overrides that default in either direction. Absent row = the report's
+-- default pin state.
+-- ============================================================
+
+CREATE TABLE "reportPin" (
+ "reportKey" TEXT NOT NULL,
+ "userId" TEXT NOT NULL REFERENCES "user"("id") ON DELETE CASCADE,
+ "companyId" TEXT NOT NULL,
+ "pinned" BOOLEAN NOT NULL,
+
+ "createdBy" TEXT NOT NULL REFERENCES "user"("id"),
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "updatedBy" TEXT REFERENCES "user"("id"),
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+
+ PRIMARY KEY ("reportKey", "userId", "companyId"),
+ FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE
+);
+
+CREATE INDEX "reportPin_userId_idx" ON "reportPin" ("userId");
+CREATE INDEX "reportPin_companyId_idx" ON "reportPin" ("companyId");
+CREATE INDEX "reportPin_createdBy_idx" ON "reportPin" ("createdBy");
+
+ALTER TABLE "public"."reportPin" ENABLE ROW LEVEL SECURITY;
+
+-- A personal UI preference: rows are visible/writable only by their owner,
+-- within companies the user belongs to (documentFavorite pattern + company
+-- scoping).
+CREATE POLICY "SELECT" ON "public"."reportPin"
+FOR SELECT USING (
+ (SELECT auth.uid())::text = "userId"
+ AND "companyId" = ANY ((SELECT get_companies_with_employee_role())::text[])
+);
+
+CREATE POLICY "INSERT" ON "public"."reportPin"
+FOR INSERT WITH CHECK (
+ (SELECT auth.uid())::text = "userId"
+ AND "companyId" = ANY ((SELECT get_companies_with_employee_role())::text[])
+);
+
+CREATE POLICY "UPDATE" ON "public"."reportPin"
+FOR UPDATE USING (
+ (SELECT auth.uid())::text = "userId"
+ AND "companyId" = ANY ((SELECT get_companies_with_employee_role())::text[])
+);
+
+CREATE POLICY "DELETE" ON "public"."reportPin"
+FOR DELETE USING (
+ (SELECT auth.uid())::text = "userId"
+ AND "companyId" = ANY ((SELECT get_companies_with_employee_role())::text[])
+);
diff --git a/packages/database/supabase/migrations/20260809184714_dimensional-pivot-reporting.sql b/packages/database/supabase/migrations/20260809184714_dimensional-pivot-reporting.sql
new file mode 100644
index 0000000000..aae06e43cb
--- /dev/null
+++ b/packages/database/supabase/migrations/20260809184714_dimensional-pivot-reporting.sql
@@ -0,0 +1,369 @@
+-- ============================================================
+-- Dimensional pivot reporting (spec: .ai/specs/2026-08-09-dimensional-pivot-reporting.md)
+--
+-- 1. reportView: named, shareable saved pivot views for the generic
+-- analytics reports (revenue / expenses / cogs / inventory-change /
+-- scrap). Visibility 'Company' shares read-only with every employee
+-- of the company; writes stay owner-only.
+-- 2. journalDimensionPivot: the aggregation path the account-only
+-- balance RPCs never had — GROUP BY up to two row dimensions plus a
+-- column axis (a dimension OR period buckets) over the dimension
+-- tags in journalLineDimension.
+-- 3. journalDimensionPivotLines: the drill-through behind a pivot cell.
+-- 4. reportPin key migration for the two hardcoded analytics reports
+-- replaced by generic-report presets.
+-- ============================================================
+
+DO $$ BEGIN
+ IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'reportViewVisibility') THEN
+ CREATE TYPE "reportViewVisibility" AS ENUM ('Private', 'Company');
+ END IF;
+END $$;
+
+CREATE TABLE IF NOT EXISTS "reportView" (
+ "id" TEXT NOT NULL DEFAULT id('rv'),
+ "companyId" TEXT NOT NULL,
+ "reportKey" TEXT NOT NULL,
+ "name" TEXT NOT NULL,
+ "config" JSONB NOT NULL,
+ "visibility" "reportViewVisibility" NOT NULL DEFAULT 'Private',
+ "createdBy" TEXT NOT NULL REFERENCES "user"("id"),
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "updatedBy" TEXT REFERENCES "user"("id"),
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+ CONSTRAINT "reportView_pkey" PRIMARY KEY ("id", "companyId"),
+ CONSTRAINT "reportView_companyId_fkey" FOREIGN KEY ("companyId")
+ REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT "reportView_name_unique" UNIQUE ("companyId", "reportKey", "name")
+);
+
+CREATE INDEX IF NOT EXISTS "reportView_companyId_idx" ON "reportView" ("companyId");
+CREATE INDEX IF NOT EXISTS "reportView_createdBy_idx" ON "reportView" ("createdBy");
+
+ALTER TABLE "reportView" ENABLE ROW LEVEL SECURITY;
+
+DROP POLICY IF EXISTS "SELECT" ON "reportView";
+CREATE POLICY "SELECT" ON "reportView" FOR SELECT USING (
+ "companyId" = ANY ((SELECT get_companies_with_employee_role())::text[])
+ AND ("visibility" = 'Company' OR "createdBy" = (SELECT auth.uid())::text)
+);
+DROP POLICY IF EXISTS "INSERT" ON "reportView";
+CREATE POLICY "INSERT" ON "reportView" FOR INSERT WITH CHECK (
+ "companyId" = ANY ((SELECT get_companies_with_employee_role())::text[])
+ AND "createdBy" = (SELECT auth.uid())::text
+);
+DROP POLICY IF EXISTS "UPDATE" ON "reportView";
+CREATE POLICY "UPDATE" ON "reportView" FOR UPDATE USING (
+ "companyId" = ANY ((SELECT get_companies_with_employee_role())::text[])
+ AND "createdBy" = (SELECT auth.uid())::text
+);
+DROP POLICY IF EXISTS "DELETE" ON "reportView";
+CREATE POLICY "DELETE" ON "reportView" FOR DELETE USING (
+ "companyId" = ANY ((SELECT get_companies_with_employee_role())::text[])
+ AND "createdBy" = (SELECT auth.uid())::text
+);
+
+-- Aggregation indexes: the per-line dimension joins want
+-- (journalLineId, dimensionId); the filter-side EXISTS probes and any
+-- future value-first scans want the company-scoped composite.
+CREATE INDEX IF NOT EXISTS "journalLineDimension_line_dimension_idx"
+ ON "journalLineDimension" ("journalLineId", "dimensionId");
+CREATE INDEX IF NOT EXISTS "journalLineDimension_company_dimension_value_idx"
+ ON "journalLineDimension" ("companyId", "dimensionId", "valueId", "journalLineId");
+
+-- ============================================================
+-- journalDimensionPivot: GROUP BY dimension tags over a scoped slice
+-- of the posted journal.
+--
+-- CONTRACT (enforced by getDimensionPivot in accounting.service.ts,
+-- the only caller):
+-- * Exactly one account-scope param (classes / types / ids) is
+-- non-null; classes and types are enum values passed as TEXT.
+-- * p_period_ends comes from computeReportPeriodBuckets (@carbon/utils):
+-- sorted ascending, distinct, max(p_period_ends) == p_end. Lines
+-- bucket to the FIRST period end >= postingDate.
+-- * p_column_dimension and p_period_ends are mutually exclusive;
+-- with neither, columnKey is the literal 'total'.
+-- * p_filters: [{"dimensionId": text, "valueIds": [text]}] — every
+-- entry must match (AND across filters, OR within valueIds).
+-- * NULL rowValue1Id/rowValue2Id/columnKey = the Unassigned bucket
+-- (line carries no tag for that dimension).
+-- * Row groups are capped at p_group_limit by ABS(SUM(amount)) DESC;
+-- hasMore reports whether groups were dropped. The app re-sorts —
+-- callers must never rely on result ordering (plpgsql, not sql,
+-- for exactly that lesson).
+-- * amount is SUM of the stored natural-signed journalLine.amount:
+-- within a single-class scope, positive = increase toward the
+-- account's natural balance (positive revenue = more revenue).
+-- ============================================================
+
+DROP FUNCTION IF EXISTS "journalDimensionPivot";
+CREATE OR REPLACE FUNCTION "journalDimensionPivot" (
+ p_company_group_id TEXT,
+ p_company_id TEXT,
+ p_start DATE,
+ p_end DATE,
+ p_account_classes TEXT[] DEFAULT NULL,
+ p_account_types TEXT[] DEFAULT NULL,
+ p_account_ids TEXT[] DEFAULT NULL,
+ p_row_dimension_1 TEXT DEFAULT NULL,
+ p_row_dimension_2 TEXT DEFAULT NULL,
+ p_column_dimension TEXT DEFAULT NULL,
+ p_period_ends DATE[] DEFAULT NULL,
+ p_filters JSONB DEFAULT NULL,
+ p_group_limit INT DEFAULT 1000
+)
+RETURNS TABLE (
+ "rowValue1Id" TEXT,
+ "rowValue2Id" TEXT,
+ "columnKey" TEXT,
+ "amount" NUMERIC,
+ "quantity" NUMERIC,
+ "lineCount" BIGINT,
+ "hasMore" BOOLEAN
+) LANGUAGE "plpgsql" SECURITY INVOKER SET search_path = public
+AS $$
+BEGIN
+ IF p_company_id IS NULL THEN
+ RAISE EXCEPTION 'journalDimensionPivot requires p_company_id';
+ END IF;
+ IF p_account_classes IS NULL AND p_account_types IS NULL AND p_account_ids IS NULL THEN
+ RAISE EXCEPTION 'journalDimensionPivot requires an account scope';
+ END IF;
+ IF p_column_dimension IS NOT NULL AND p_period_ends IS NOT NULL THEN
+ RAISE EXCEPTION 'journalDimensionPivot: column axis is a dimension OR period ends, not both';
+ END IF;
+
+ RETURN QUERY
+ WITH "scopedLines" AS (
+ SELECT jl."id" AS "lineId", jl."amount" AS "lineAmount",
+ COALESCE(jl."quantity", 0) AS "lineQuantity", j."postingDate"
+ FROM "journal" j
+ INNER JOIN "journalLine" jl ON jl."journalId" = j."id"
+ INNER JOIN "account" a
+ ON a."id" = jl."accountId" AND a."companyGroupId" = p_company_group_id
+ WHERE j."companyId" = p_company_id
+ AND jl."companyId" = p_company_id
+ AND j."status" <> 'Draft'
+ AND j."postingDate" >= p_start
+ AND j."postingDate" <= p_end
+ AND (
+ (p_account_ids IS NOT NULL AND jl."accountId" = ANY(p_account_ids))
+ OR (p_account_types IS NOT NULL AND a."accountType"::TEXT = ANY(p_account_types))
+ OR (p_account_classes IS NOT NULL AND a."class"::TEXT = ANY(p_account_classes))
+ )
+ AND NOT EXISTS (
+ SELECT 1
+ FROM jsonb_array_elements(COALESCE(p_filters, '[]'::jsonb)) AS f
+ WHERE NOT EXISTS (
+ SELECT 1 FROM "journalLineDimension" fd
+ WHERE fd."journalLineId" = jl."id"
+ AND fd."companyId" = p_company_id
+ AND fd."dimensionId" = f->>'dimensionId'
+ AND fd."valueId" IN (SELECT jsonb_array_elements_text(f->'valueIds'))
+ )
+ )
+ ),
+ "taggedLines" AS (
+ SELECT
+ sl."lineId", sl."lineAmount", sl."lineQuantity",
+ d1."valueId" AS "r1",
+ d2."valueId" AS "r2",
+ CASE
+ WHEN p_column_dimension IS NOT NULL THEN dc."valueId"
+ WHEN p_period_ends IS NOT NULL THEN (
+ SELECT MIN(pe)::TEXT FROM unnest(p_period_ends) pe
+ WHERE pe >= sl."postingDate"
+ )
+ ELSE 'total'
+ END AS "colKey"
+ FROM "scopedLines" sl
+ LEFT JOIN "journalLineDimension" d1
+ ON p_row_dimension_1 IS NOT NULL
+ AND d1."journalLineId" = sl."lineId"
+ AND d1."companyId" = p_company_id
+ AND d1."dimensionId" = p_row_dimension_1
+ LEFT JOIN "journalLineDimension" d2
+ ON p_row_dimension_2 IS NOT NULL
+ AND d2."journalLineId" = sl."lineId"
+ AND d2."companyId" = p_company_id
+ AND d2."dimensionId" = p_row_dimension_2
+ LEFT JOIN "journalLineDimension" dc
+ ON p_column_dimension IS NOT NULL
+ AND dc."journalLineId" = sl."lineId"
+ AND dc."companyId" = p_company_id
+ AND dc."dimensionId" = p_column_dimension
+ ),
+ "rowGroups" AS (
+ SELECT tl."r1", tl."r2",
+ ROW_NUMBER() OVER (ORDER BY ABS(SUM(tl."lineAmount")) DESC NULLS LAST) AS rn,
+ COUNT(*) OVER () AS "totalGroups"
+ FROM "taggedLines" tl
+ GROUP BY tl."r1", tl."r2"
+ ),
+ "keptGroups" AS (
+ SELECT rg."r1", rg."r2", rg."totalGroups"
+ FROM "rowGroups" rg
+ WHERE rg.rn <= p_group_limit
+ )
+ SELECT
+ tl."r1" AS "rowValue1Id",
+ tl."r2" AS "rowValue2Id",
+ tl."colKey" AS "columnKey",
+ SUM(tl."lineAmount") AS "amount",
+ SUM(tl."lineQuantity") AS "quantity",
+ COUNT(*)::BIGINT AS "lineCount",
+ (SELECT COALESCE(MAX(kg2."totalGroups"), 0) FROM "keptGroups" kg2) > p_group_limit AS "hasMore"
+ FROM "taggedLines" tl
+ INNER JOIN "keptGroups" kg
+ ON kg."r1" IS NOT DISTINCT FROM tl."r1"
+ AND kg."r2" IS NOT DISTINCT FROM tl."r2"
+ GROUP BY tl."r1", tl."r2", tl."colKey";
+END;
+$$;
+
+-- ============================================================
+-- journalDimensionPivotLines: the journal lines behind one pivot cell.
+--
+-- Dimension-match semantics per axis (row 1 / row 2 / column):
+-- * dimension param NULL -> no constraint
+-- * dimension set, value param NULL -> Unassigned (line has NO tag
+-- for that dimension)
+-- * dimension set, value param set -> tag equals the value
+-- A period column narrows postingDate via p_column_period_start/end
+-- instead of a dimension match. Same scope/filter params as the pivot.
+-- Capped at p_line_limit; the app re-sorts authoritatively.
+-- ============================================================
+
+DROP FUNCTION IF EXISTS "journalDimensionPivotLines";
+CREATE OR REPLACE FUNCTION "journalDimensionPivotLines" (
+ p_company_group_id TEXT,
+ p_company_id TEXT,
+ p_start DATE,
+ p_end DATE,
+ p_account_classes TEXT[] DEFAULT NULL,
+ p_account_types TEXT[] DEFAULT NULL,
+ p_account_ids TEXT[] DEFAULT NULL,
+ p_filters JSONB DEFAULT NULL,
+ p_row_dimension_1 TEXT DEFAULT NULL,
+ p_row_value_1 TEXT DEFAULT NULL,
+ p_row_dimension_2 TEXT DEFAULT NULL,
+ p_row_value_2 TEXT DEFAULT NULL,
+ p_column_dimension TEXT DEFAULT NULL,
+ p_column_value TEXT DEFAULT NULL,
+ p_column_period_start DATE DEFAULT NULL,
+ p_column_period_end DATE DEFAULT NULL,
+ p_line_limit INT DEFAULT 500
+)
+RETURNS TABLE (
+ "id" TEXT,
+ "postingDate" DATE,
+ "journalEntryId" TEXT,
+ "accountId" TEXT,
+ "accountName" TEXT,
+ "accountNumber" TEXT,
+ "description" TEXT,
+ "documentType" TEXT,
+ "documentId" TEXT,
+ "amount" NUMERIC,
+ "quantity" NUMERIC
+) LANGUAGE "plpgsql" SECURITY INVOKER SET search_path = public
+AS $$
+BEGIN
+ RETURN QUERY
+ SELECT
+ jl."id",
+ j."postingDate",
+ j."journalEntryId"::TEXT,
+ jl."accountId",
+ a."name" AS "accountName",
+ a."number" AS "accountNumber",
+ jl."description",
+ jl."documentType"::TEXT,
+ jl."documentId",
+ jl."amount",
+ COALESCE(jl."quantity", 0) AS "quantity"
+ FROM "journal" j
+ INNER JOIN "journalLine" jl ON jl."journalId" = j."id"
+ INNER JOIN "account" a
+ ON a."id" = jl."accountId" AND a."companyGroupId" = p_company_group_id
+ WHERE j."companyId" = p_company_id
+ AND jl."companyId" = p_company_id
+ AND j."status" <> 'Draft'
+ AND j."postingDate" >= COALESCE(p_column_period_start, p_start)
+ AND j."postingDate" <= COALESCE(p_column_period_end, p_end)
+ AND (
+ (p_account_ids IS NOT NULL AND jl."accountId" = ANY(p_account_ids))
+ OR (p_account_types IS NOT NULL AND a."accountType"::TEXT = ANY(p_account_types))
+ OR (p_account_classes IS NOT NULL AND a."class"::TEXT = ANY(p_account_classes))
+ )
+ AND NOT EXISTS (
+ SELECT 1
+ FROM jsonb_array_elements(COALESCE(p_filters, '[]'::jsonb)) AS f
+ WHERE NOT EXISTS (
+ SELECT 1 FROM "journalLineDimension" fd
+ WHERE fd."journalLineId" = jl."id"
+ AND fd."companyId" = p_company_id
+ AND fd."dimensionId" = f->>'dimensionId'
+ AND fd."valueId" IN (SELECT jsonb_array_elements_text(f->'valueIds'))
+ )
+ )
+ AND (
+ p_row_dimension_1 IS NULL
+ OR (p_row_value_1 IS NULL AND NOT EXISTS (
+ SELECT 1 FROM "journalLineDimension" d
+ WHERE d."journalLineId" = jl."id" AND d."companyId" = p_company_id
+ AND d."dimensionId" = p_row_dimension_1))
+ OR (p_row_value_1 IS NOT NULL AND EXISTS (
+ SELECT 1 FROM "journalLineDimension" d
+ WHERE d."journalLineId" = jl."id" AND d."companyId" = p_company_id
+ AND d."dimensionId" = p_row_dimension_1 AND d."valueId" = p_row_value_1))
+ )
+ AND (
+ p_row_dimension_2 IS NULL
+ OR (p_row_value_2 IS NULL AND NOT EXISTS (
+ SELECT 1 FROM "journalLineDimension" d
+ WHERE d."journalLineId" = jl."id" AND d."companyId" = p_company_id
+ AND d."dimensionId" = p_row_dimension_2))
+ OR (p_row_value_2 IS NOT NULL AND EXISTS (
+ SELECT 1 FROM "journalLineDimension" d
+ WHERE d."journalLineId" = jl."id" AND d."companyId" = p_company_id
+ AND d."dimensionId" = p_row_dimension_2 AND d."valueId" = p_row_value_2))
+ )
+ AND (
+ p_column_dimension IS NULL
+ OR (p_column_value IS NULL AND NOT EXISTS (
+ SELECT 1 FROM "journalLineDimension" d
+ WHERE d."journalLineId" = jl."id" AND d."companyId" = p_company_id
+ AND d."dimensionId" = p_column_dimension))
+ OR (p_column_value IS NOT NULL AND EXISTS (
+ SELECT 1 FROM "journalLineDimension" d
+ WHERE d."journalLineId" = jl."id" AND d."companyId" = p_company_id
+ AND d."dimensionId" = p_column_dimension AND d."valueId" = p_column_value))
+ )
+ ORDER BY j."postingDate", jl."id"
+ LIMIT p_line_limit;
+END;
+$$;
+
+-- ============================================================
+-- reportPin key migration: the hardcoded analytics reports become
+-- presets of the generic reports; carry pins over (dedupe-safe).
+-- ============================================================
+
+UPDATE "reportPin" rp SET "reportKey" = 'revenue'
+WHERE rp."reportKey" = 'revenue-by-customer'
+ AND NOT EXISTS (
+ SELECT 1 FROM "reportPin" x
+ WHERE x."reportKey" = 'revenue'
+ AND x."userId" = rp."userId" AND x."companyId" = rp."companyId");
+
+UPDATE "reportPin" rp SET "reportKey" = 'expenses'
+WHERE rp."reportKey" = 'expenses-by-supplier'
+ AND NOT EXISTS (
+ SELECT 1 FROM "reportPin" x
+ WHERE x."reportKey" = 'expenses'
+ AND x."userId" = rp."userId" AND x."companyId" = rp."companyId");
+
+DELETE FROM "reportPin"
+WHERE "reportKey" IN ('revenue-by-customer', 'expenses-by-supplier');
diff --git a/packages/database/supabase/migrations/20260809204137_analytics-account-filter.sql b/packages/database/supabase/migrations/20260809204137_analytics-account-filter.sql
new file mode 100644
index 0000000000..8efa804069
--- /dev/null
+++ b/packages/database/supabase/migrations/20260809204137_analytics-account-filter.sql
@@ -0,0 +1,260 @@
+-- ============================================================
+-- Analytics pivot: optional per-report account filter.
+--
+-- Adds p_filter_account_ids to journalDimensionPivot and
+-- journalDimensionPivotLines. It is ANDed on top of the base account
+-- scope (classes / types / ids): the base scope defines the account
+-- universe of a report, and p_filter_account_ids narrows WITHIN it to a
+-- user-picked subset. NULL/empty leaves the report unfiltered.
+--
+-- Also retires the 'cogs' analytics report (folded into the generic
+-- reports): drop any saved views / pins that referenced it.
+--
+-- Fork of 20260809184714_dimensional-pivot-reporting.sql — the two
+-- function bodies are unchanged except for the new parameter and the
+-- single AND clause in each account-scope predicate.
+-- ============================================================
+
+DROP FUNCTION IF EXISTS "journalDimensionPivot";
+CREATE OR REPLACE FUNCTION "journalDimensionPivot" (
+ p_company_group_id TEXT,
+ p_company_id TEXT,
+ p_start DATE,
+ p_end DATE,
+ p_account_classes TEXT[] DEFAULT NULL,
+ p_account_types TEXT[] DEFAULT NULL,
+ p_account_ids TEXT[] DEFAULT NULL,
+ p_row_dimension_1 TEXT DEFAULT NULL,
+ p_row_dimension_2 TEXT DEFAULT NULL,
+ p_column_dimension TEXT DEFAULT NULL,
+ p_period_ends DATE[] DEFAULT NULL,
+ p_filters JSONB DEFAULT NULL,
+ p_group_limit INT DEFAULT 1000,
+ p_filter_account_ids TEXT[] DEFAULT NULL
+)
+RETURNS TABLE (
+ "rowValue1Id" TEXT,
+ "rowValue2Id" TEXT,
+ "columnKey" TEXT,
+ "amount" NUMERIC,
+ "quantity" NUMERIC,
+ "lineCount" BIGINT,
+ "hasMore" BOOLEAN
+) LANGUAGE "plpgsql" SECURITY INVOKER SET search_path = public
+AS $$
+BEGIN
+ IF p_company_id IS NULL THEN
+ RAISE EXCEPTION 'journalDimensionPivot requires p_company_id';
+ END IF;
+ IF p_account_classes IS NULL AND p_account_types IS NULL AND p_account_ids IS NULL THEN
+ RAISE EXCEPTION 'journalDimensionPivot requires an account scope';
+ END IF;
+ IF p_column_dimension IS NOT NULL AND p_period_ends IS NOT NULL THEN
+ RAISE EXCEPTION 'journalDimensionPivot: column axis is a dimension OR period ends, not both';
+ END IF;
+
+ RETURN QUERY
+ WITH "scopedLines" AS (
+ SELECT jl."id" AS "lineId", jl."amount" AS "lineAmount",
+ COALESCE(jl."quantity", 0) AS "lineQuantity", j."postingDate"
+ FROM "journal" j
+ INNER JOIN "journalLine" jl ON jl."journalId" = j."id"
+ INNER JOIN "account" a
+ ON a."id" = jl."accountId" AND a."companyGroupId" = p_company_group_id
+ WHERE j."companyId" = p_company_id
+ AND jl."companyId" = p_company_id
+ AND j."status" <> 'Draft'
+ AND j."postingDate" >= p_start
+ AND j."postingDate" <= p_end
+ AND (
+ (p_account_ids IS NOT NULL AND jl."accountId" = ANY(p_account_ids))
+ OR (p_account_types IS NOT NULL AND a."accountType"::TEXT = ANY(p_account_types))
+ OR (p_account_classes IS NOT NULL AND a."class"::TEXT = ANY(p_account_classes))
+ )
+ AND (p_filter_account_ids IS NULL OR jl."accountId" = ANY(p_filter_account_ids))
+ AND NOT EXISTS (
+ SELECT 1
+ FROM jsonb_array_elements(COALESCE(p_filters, '[]'::jsonb)) AS f
+ WHERE NOT EXISTS (
+ SELECT 1 FROM "journalLineDimension" fd
+ WHERE fd."journalLineId" = jl."id"
+ AND fd."companyId" = p_company_id
+ AND fd."dimensionId" = f->>'dimensionId'
+ AND fd."valueId" IN (SELECT jsonb_array_elements_text(f->'valueIds'))
+ )
+ )
+ ),
+ "taggedLines" AS (
+ SELECT
+ sl."lineId", sl."lineAmount", sl."lineQuantity",
+ d1."valueId" AS "r1",
+ d2."valueId" AS "r2",
+ CASE
+ WHEN p_column_dimension IS NOT NULL THEN dc."valueId"
+ WHEN p_period_ends IS NOT NULL THEN (
+ SELECT MIN(pe)::TEXT FROM unnest(p_period_ends) pe
+ WHERE pe >= sl."postingDate"
+ )
+ ELSE 'total'
+ END AS "colKey"
+ FROM "scopedLines" sl
+ LEFT JOIN "journalLineDimension" d1
+ ON p_row_dimension_1 IS NOT NULL
+ AND d1."journalLineId" = sl."lineId"
+ AND d1."companyId" = p_company_id
+ AND d1."dimensionId" = p_row_dimension_1
+ LEFT JOIN "journalLineDimension" d2
+ ON p_row_dimension_2 IS NOT NULL
+ AND d2."journalLineId" = sl."lineId"
+ AND d2."companyId" = p_company_id
+ AND d2."dimensionId" = p_row_dimension_2
+ LEFT JOIN "journalLineDimension" dc
+ ON p_column_dimension IS NOT NULL
+ AND dc."journalLineId" = sl."lineId"
+ AND dc."companyId" = p_company_id
+ AND dc."dimensionId" = p_column_dimension
+ ),
+ "rowGroups" AS (
+ SELECT tl."r1", tl."r2",
+ ROW_NUMBER() OVER (ORDER BY ABS(SUM(tl."lineAmount")) DESC NULLS LAST) AS rn,
+ COUNT(*) OVER () AS "totalGroups"
+ FROM "taggedLines" tl
+ GROUP BY tl."r1", tl."r2"
+ ),
+ "keptGroups" AS (
+ SELECT rg."r1", rg."r2", rg."totalGroups"
+ FROM "rowGroups" rg
+ WHERE rg.rn <= p_group_limit
+ )
+ SELECT
+ tl."r1" AS "rowValue1Id",
+ tl."r2" AS "rowValue2Id",
+ tl."colKey" AS "columnKey",
+ SUM(tl."lineAmount") AS "amount",
+ SUM(tl."lineQuantity") AS "quantity",
+ COUNT(*)::BIGINT AS "lineCount",
+ (SELECT COALESCE(MAX(kg2."totalGroups"), 0) FROM "keptGroups" kg2) > p_group_limit AS "hasMore"
+ FROM "taggedLines" tl
+ INNER JOIN "keptGroups" kg
+ ON kg."r1" IS NOT DISTINCT FROM tl."r1"
+ AND kg."r2" IS NOT DISTINCT FROM tl."r2"
+ GROUP BY tl."r1", tl."r2", tl."colKey";
+END;
+$$;
+
+DROP FUNCTION IF EXISTS "journalDimensionPivotLines";
+CREATE OR REPLACE FUNCTION "journalDimensionPivotLines" (
+ p_company_group_id TEXT,
+ p_company_id TEXT,
+ p_start DATE,
+ p_end DATE,
+ p_account_classes TEXT[] DEFAULT NULL,
+ p_account_types TEXT[] DEFAULT NULL,
+ p_account_ids TEXT[] DEFAULT NULL,
+ p_filters JSONB DEFAULT NULL,
+ p_row_dimension_1 TEXT DEFAULT NULL,
+ p_row_value_1 TEXT DEFAULT NULL,
+ p_row_dimension_2 TEXT DEFAULT NULL,
+ p_row_value_2 TEXT DEFAULT NULL,
+ p_column_dimension TEXT DEFAULT NULL,
+ p_column_value TEXT DEFAULT NULL,
+ p_column_period_start DATE DEFAULT NULL,
+ p_column_period_end DATE DEFAULT NULL,
+ p_line_limit INT DEFAULT 500,
+ p_filter_account_ids TEXT[] DEFAULT NULL
+)
+RETURNS TABLE (
+ "id" TEXT,
+ "postingDate" DATE,
+ "journalEntryId" TEXT,
+ "accountId" TEXT,
+ "accountName" TEXT,
+ "accountNumber" TEXT,
+ "description" TEXT,
+ "documentType" TEXT,
+ "documentId" TEXT,
+ "amount" NUMERIC,
+ "quantity" NUMERIC
+) LANGUAGE "plpgsql" SECURITY INVOKER SET search_path = public
+AS $$
+BEGIN
+ RETURN QUERY
+ SELECT
+ jl."id",
+ j."postingDate",
+ j."journalEntryId"::TEXT,
+ jl."accountId",
+ a."name" AS "accountName",
+ a."number" AS "accountNumber",
+ jl."description",
+ jl."documentType"::TEXT,
+ jl."documentId",
+ jl."amount",
+ COALESCE(jl."quantity", 0) AS "quantity"
+ FROM "journal" j
+ INNER JOIN "journalLine" jl ON jl."journalId" = j."id"
+ INNER JOIN "account" a
+ ON a."id" = jl."accountId" AND a."companyGroupId" = p_company_group_id
+ WHERE j."companyId" = p_company_id
+ AND jl."companyId" = p_company_id
+ AND j."status" <> 'Draft'
+ AND j."postingDate" >= COALESCE(p_column_period_start, p_start)
+ AND j."postingDate" <= COALESCE(p_column_period_end, p_end)
+ AND (
+ (p_account_ids IS NOT NULL AND jl."accountId" = ANY(p_account_ids))
+ OR (p_account_types IS NOT NULL AND a."accountType"::TEXT = ANY(p_account_types))
+ OR (p_account_classes IS NOT NULL AND a."class"::TEXT = ANY(p_account_classes))
+ )
+ AND (p_filter_account_ids IS NULL OR jl."accountId" = ANY(p_filter_account_ids))
+ AND NOT EXISTS (
+ SELECT 1
+ FROM jsonb_array_elements(COALESCE(p_filters, '[]'::jsonb)) AS f
+ WHERE NOT EXISTS (
+ SELECT 1 FROM "journalLineDimension" fd
+ WHERE fd."journalLineId" = jl."id"
+ AND fd."companyId" = p_company_id
+ AND fd."dimensionId" = f->>'dimensionId'
+ AND fd."valueId" IN (SELECT jsonb_array_elements_text(f->'valueIds'))
+ )
+ )
+ AND (
+ p_row_dimension_1 IS NULL
+ OR (p_row_value_1 IS NULL AND NOT EXISTS (
+ SELECT 1 FROM "journalLineDimension" d
+ WHERE d."journalLineId" = jl."id" AND d."companyId" = p_company_id
+ AND d."dimensionId" = p_row_dimension_1))
+ OR (p_row_value_1 IS NOT NULL AND EXISTS (
+ SELECT 1 FROM "journalLineDimension" d
+ WHERE d."journalLineId" = jl."id" AND d."companyId" = p_company_id
+ AND d."dimensionId" = p_row_dimension_1 AND d."valueId" = p_row_value_1))
+ )
+ AND (
+ p_row_dimension_2 IS NULL
+ OR (p_row_value_2 IS NULL AND NOT EXISTS (
+ SELECT 1 FROM "journalLineDimension" d
+ WHERE d."journalLineId" = jl."id" AND d."companyId" = p_company_id
+ AND d."dimensionId" = p_row_dimension_2))
+ OR (p_row_value_2 IS NOT NULL AND EXISTS (
+ SELECT 1 FROM "journalLineDimension" d
+ WHERE d."journalLineId" = jl."id" AND d."companyId" = p_company_id
+ AND d."dimensionId" = p_row_dimension_2 AND d."valueId" = p_row_value_2))
+ )
+ AND (
+ p_column_dimension IS NULL
+ OR (p_column_value IS NULL AND NOT EXISTS (
+ SELECT 1 FROM "journalLineDimension" d
+ WHERE d."journalLineId" = jl."id" AND d."companyId" = p_company_id
+ AND d."dimensionId" = p_column_dimension))
+ OR (p_column_value IS NOT NULL AND EXISTS (
+ SELECT 1 FROM "journalLineDimension" d
+ WHERE d."journalLineId" = jl."id" AND d."companyId" = p_company_id
+ AND d."dimensionId" = p_column_dimension AND d."valueId" = p_column_value))
+ )
+ ORDER BY j."postingDate", jl."id"
+ LIMIT p_line_limit;
+END;
+$$;
+
+-- Retire the 'cogs' analytics report: remove its saved views and pins.
+DELETE FROM "reportView" WHERE "reportKey" = 'cogs';
+DELETE FROM "reportPin" WHERE "reportKey" = 'cogs';
diff --git a/packages/database/supabase/migrations/20260809211324_purchases-pivot-report.sql b/packages/database/supabase/migrations/20260809211324_purchases-pivot-report.sql
new file mode 100644
index 0000000000..c0ec6dc76e
--- /dev/null
+++ b/packages/database/supabase/migrations/20260809211324_purchases-pivot-report.sql
@@ -0,0 +1,247 @@
+-- ============================================================
+-- Purchases analytics pivot — sourced from the purchase invoice
+-- subledger, NOT the GL journal.
+--
+-- "Spend by supplier / biggest cost drivers by part" is a purchasing
+-- question: gross invoiced amount per line, which never nets against
+-- payments (unlike an AP/GL balance) and captures inventory, expense,
+-- and service purchases uniformly. The GL journalDimensionPivot cannot
+-- answer it (AP nets on payment; item tags don't live on AP lines).
+--
+-- Both functions mirror journalDimensionPivot's output contract so the
+-- existing PivotTree / pivotData UI renders them unchanged:
+-- * rowValue*/columnKey NULL = the Unassigned bucket.
+-- * amount = SUM of purchaseInvoiceLine."extendedPrice" (base currency,
+-- net of tax & shipping — the goods cost, comparable per part).
+-- * Row groups capped at p_group_limit by ABS(SUM(amount)); the app
+-- re-sorts, so callers must not rely on ordering.
+--
+-- Grouping fields (p_row_field_*/p_column_field), one of:
+-- supplier | supplierType | item | itemPostingGroup | costCenter
+-- resolved to a value id via CASE (no dynamic SQL). Only non-Draft,
+-- non-Voided invoices count.
+-- ============================================================
+
+DROP FUNCTION IF EXISTS "purchaseLineDimensionPivot";
+CREATE OR REPLACE FUNCTION "purchaseLineDimensionPivot" (
+ p_company_id TEXT,
+ p_start DATE,
+ p_end DATE,
+ p_row_field_1 TEXT DEFAULT NULL,
+ p_row_field_2 TEXT DEFAULT NULL,
+ p_column_field TEXT DEFAULT NULL,
+ p_period_ends DATE[] DEFAULT NULL,
+ p_group_limit INT DEFAULT 1000
+)
+RETURNS TABLE (
+ "rowValue1Id" TEXT,
+ "rowValue2Id" TEXT,
+ "columnKey" TEXT,
+ "amount" NUMERIC,
+ "quantity" NUMERIC,
+ "lineCount" BIGINT,
+ "hasMore" BOOLEAN
+) LANGUAGE "plpgsql" SECURITY INVOKER SET search_path = public
+AS $$
+BEGIN
+ IF p_company_id IS NULL THEN
+ RAISE EXCEPTION 'purchaseLineDimensionPivot requires p_company_id';
+ END IF;
+ IF p_column_field IS NOT NULL AND p_period_ends IS NOT NULL THEN
+ RAISE EXCEPTION 'purchaseLineDimensionPivot: column axis is a field OR period ends, not both';
+ END IF;
+
+ RETURN QUERY
+ WITH "scopedLines" AS (
+ SELECT
+ jl."id" AS "lineId",
+ jl."extendedPrice" AS "lineAmount",
+ COALESCE(jl."quantity", 0) AS "lineQuantity",
+ pi."postingDate" AS "postingDate",
+ pi."supplierId" AS "supplierId",
+ s."supplierTypeId" AS "supplierTypeId",
+ jl."itemId" AS "itemId",
+ ic."itemPostingGroupId" AS "itemPostingGroupId",
+ jl."costCenterId" AS "costCenterId"
+ FROM "purchaseInvoiceLine" jl
+ INNER JOIN "purchaseInvoice" pi ON pi."id" = jl."invoiceId"
+ LEFT JOIN "supplier" s ON s."id" = pi."supplierId"
+ LEFT JOIN "itemCost" ic
+ ON ic."itemId" = jl."itemId" AND ic."companyId" = pi."companyId"
+ WHERE pi."companyId" = p_company_id
+ AND jl."companyId" = p_company_id
+ AND pi."status" NOT IN ('Draft', 'Voided')
+ AND pi."postingDate" >= p_start
+ AND pi."postingDate" <= p_end
+ AND jl."extendedPrice" IS NOT NULL
+ ),
+ "taggedLines" AS (
+ SELECT
+ sl."lineId", sl."lineAmount", sl."lineQuantity",
+ CASE p_row_field_1
+ WHEN 'supplier' THEN sl."supplierId"
+ WHEN 'supplierType' THEN sl."supplierTypeId"
+ WHEN 'item' THEN sl."itemId"
+ WHEN 'itemPostingGroup' THEN sl."itemPostingGroupId"
+ WHEN 'costCenter' THEN sl."costCenterId"
+ ELSE NULL
+ END AS "r1",
+ CASE p_row_field_2
+ WHEN 'supplier' THEN sl."supplierId"
+ WHEN 'supplierType' THEN sl."supplierTypeId"
+ WHEN 'item' THEN sl."itemId"
+ WHEN 'itemPostingGroup' THEN sl."itemPostingGroupId"
+ WHEN 'costCenter' THEN sl."costCenterId"
+ ELSE NULL
+ END AS "r2",
+ CASE
+ WHEN p_column_field IS NOT NULL THEN (
+ CASE p_column_field
+ WHEN 'supplier' THEN sl."supplierId"
+ WHEN 'supplierType' THEN sl."supplierTypeId"
+ WHEN 'item' THEN sl."itemId"
+ WHEN 'itemPostingGroup' THEN sl."itemPostingGroupId"
+ WHEN 'costCenter' THEN sl."costCenterId"
+ ELSE NULL
+ END
+ )
+ WHEN p_period_ends IS NOT NULL THEN (
+ SELECT MIN(pe)::TEXT FROM unnest(p_period_ends) pe
+ WHERE pe >= sl."postingDate"
+ )
+ ELSE 'total'
+ END AS "colKey"
+ FROM "scopedLines" sl
+ ),
+ "rowGroups" AS (
+ SELECT tl."r1", tl."r2",
+ ROW_NUMBER() OVER (ORDER BY ABS(SUM(tl."lineAmount")) DESC NULLS LAST) AS rn,
+ COUNT(*) OVER () AS "totalGroups"
+ FROM "taggedLines" tl
+ GROUP BY tl."r1", tl."r2"
+ ),
+ "keptGroups" AS (
+ SELECT rg."r1", rg."r2", rg."totalGroups"
+ FROM "rowGroups" rg
+ WHERE rg.rn <= p_group_limit
+ )
+ SELECT
+ tl."r1" AS "rowValue1Id",
+ tl."r2" AS "rowValue2Id",
+ tl."colKey" AS "columnKey",
+ SUM(tl."lineAmount") AS "amount",
+ SUM(tl."lineQuantity") AS "quantity",
+ COUNT(*)::BIGINT AS "lineCount",
+ (SELECT COALESCE(MAX(kg2."totalGroups"), 0) FROM "keptGroups" kg2) > p_group_limit AS "hasMore"
+ FROM "taggedLines" tl
+ INNER JOIN "keptGroups" kg
+ ON kg."r1" IS NOT DISTINCT FROM tl."r1"
+ AND kg."r2" IS NOT DISTINCT FROM tl."r2"
+ GROUP BY tl."r1", tl."r2", tl."colKey";
+END;
+$$;
+
+-- ============================================================
+-- purchaseLinePivotLines: the invoice lines behind one pivot cell.
+-- Field-match semantics per axis (row 1 / row 2 / column):
+-- * field param NULL -> no constraint
+-- * field set, value param NULL -> Unassigned (field value IS NULL)
+-- * field set, value param set -> field value equals the value
+-- A period column narrows postingDate via p_column_period_start/end.
+-- ============================================================
+
+DROP FUNCTION IF EXISTS "purchaseLinePivotLines";
+CREATE OR REPLACE FUNCTION "purchaseLinePivotLines" (
+ p_company_id TEXT,
+ p_start DATE,
+ p_end DATE,
+ p_row_field_1 TEXT DEFAULT NULL,
+ p_row_value_1 TEXT DEFAULT NULL,
+ p_row_field_2 TEXT DEFAULT NULL,
+ p_row_value_2 TEXT DEFAULT NULL,
+ p_column_field TEXT DEFAULT NULL,
+ p_column_value TEXT DEFAULT NULL,
+ p_column_period_start DATE DEFAULT NULL,
+ p_column_period_end DATE DEFAULT NULL,
+ p_line_limit INT DEFAULT 500
+)
+RETURNS TABLE (
+ "id" TEXT,
+ "postingDate" DATE,
+ "invoiceReadableId" TEXT,
+ "supplierName" TEXT,
+ "itemReadableId" TEXT,
+ "description" TEXT,
+ "amount" NUMERIC,
+ "quantity" NUMERIC
+) LANGUAGE "plpgsql" SECURITY INVOKER SET search_path = public
+AS $$
+BEGIN
+ RETURN QUERY
+ WITH l AS (
+ SELECT
+ jl."id",
+ pi."postingDate",
+ pi."invoiceId" AS "invoiceReadableId",
+ s."name" AS "supplierName",
+ i."readableIdWithRevision" AS "itemReadableId",
+ jl."description",
+ jl."extendedPrice" AS "amount",
+ COALESCE(jl."quantity", 0) AS "quantity",
+ pi."supplierId",
+ s."supplierTypeId",
+ jl."itemId",
+ ic."itemPostingGroupId",
+ jl."costCenterId"
+ FROM "purchaseInvoiceLine" jl
+ INNER JOIN "purchaseInvoice" pi ON pi."id" = jl."invoiceId"
+ LEFT JOIN "supplier" s ON s."id" = pi."supplierId"
+ LEFT JOIN "item" i ON i."id" = jl."itemId"
+ LEFT JOIN "itemCost" ic
+ ON ic."itemId" = jl."itemId" AND ic."companyId" = pi."companyId"
+ WHERE pi."companyId" = p_company_id
+ AND jl."companyId" = p_company_id
+ AND pi."status" NOT IN ('Draft', 'Voided')
+ AND pi."postingDate" >= COALESCE(p_column_period_start, p_start)
+ AND pi."postingDate" <= COALESCE(p_column_period_end, p_end)
+ AND jl."extendedPrice" IS NOT NULL
+ )
+ SELECT
+ l."id", l."postingDate", l."invoiceReadableId", l."supplierName",
+ l."itemReadableId", l."description", l."amount", l."quantity"
+ FROM l
+ WHERE
+ (
+ p_row_field_1 IS NULL
+ OR (CASE p_row_field_1
+ WHEN 'supplier' THEN l."supplierId"
+ WHEN 'supplierType' THEN l."supplierTypeId"
+ WHEN 'item' THEN l."itemId"
+ WHEN 'itemPostingGroup' THEN l."itemPostingGroupId"
+ WHEN 'costCenter' THEN l."costCenterId"
+ END) IS NOT DISTINCT FROM p_row_value_1
+ )
+ AND (
+ p_row_field_2 IS NULL
+ OR (CASE p_row_field_2
+ WHEN 'supplier' THEN l."supplierId"
+ WHEN 'supplierType' THEN l."supplierTypeId"
+ WHEN 'item' THEN l."itemId"
+ WHEN 'itemPostingGroup' THEN l."itemPostingGroupId"
+ WHEN 'costCenter' THEN l."costCenterId"
+ END) IS NOT DISTINCT FROM p_row_value_2
+ )
+ AND (
+ p_column_field IS NULL
+ OR (CASE p_column_field
+ WHEN 'supplier' THEN l."supplierId"
+ WHEN 'supplierType' THEN l."supplierTypeId"
+ WHEN 'item' THEN l."itemId"
+ WHEN 'itemPostingGroup' THEN l."itemPostingGroupId"
+ WHEN 'costCenter' THEN l."costCenterId"
+ END) IS NOT DISTINCT FROM p_column_value
+ )
+ ORDER BY l."postingDate", l."id"
+ LIMIT p_line_limit;
+END;
+$$;
diff --git a/packages/locale/locales/de/erp.po b/packages/locale/locales/de/erp.po
index ec50c354e9..599bbc89b8 100644
--- a/packages/locale/locales/de/erp.po
+++ b/packages/locale/locales/de/erp.po
@@ -48,6 +48,10 @@ msgstr "(für diesen Kunden ausgeschlossen)"
msgid "{0, plural, one {This part is on 1 open change notice} other {This part is on # open change notices}}"
msgstr "{0, plural, one {Dieses Teil ist auf 1 offener Änderungsmitteilung} other {Dieses Teil ist auf # offenen Änderungsmitteilungen}}"
+#. placeholder {0}: selectedAccountIds.length
+msgid "{0} accounts"
+msgstr "{0} Konten"
+
#. placeholder {0}: precise?.text
msgid "{0} ago"
msgstr "vor {0}"
@@ -163,6 +167,9 @@ msgstr "{years}J."
msgid "/month/user"
msgstr "/Monat/Benutzer"
+msgid "% of total"
+msgstr "% der Summe"
+
msgid "% of Total"
msgstr "% der Gesamtsumme"
@@ -474,6 +481,9 @@ msgstr "Konto"
msgid "Account & Details"
msgstr "Konto & Details"
+msgid "Account balances with debits and credits"
+msgstr "Kontostand mit Soll- und Habenseite"
+
msgid "Account for advance payments made before goods or services are received"
msgstr "Konten Sie für Vorschusszahlungen, die vor Lieferung von Waren oder Dienstleistungen getätigt werden."
@@ -510,9 +520,15 @@ msgstr "Buchhaltung"
msgid "Accounting"
msgstr "Buchhaltung"
+msgid "Accounting is currently in beta. Request access to enable reporting, journal entries, accounting periods, fixed assets, and more."
+msgstr "Die Buchhaltung befindet sich derzeit in der Beta-Phase. Fordern Sie Zugriff an, um Berichte, Journaleinträge, Buchhaltungsperioden, Anlagevermögen und mehr zu aktivieren."
+
msgid "Accounting is disabled"
msgstr "Buchhaltung ist deaktiviert"
+msgid "Accounting is disabled for this company."
+msgstr "Die Buchhaltung ist für dieses Unternehmen deaktiviert."
+
msgid "Accounting is enabled"
msgstr "Buchhaltung ist aktiviert"
@@ -853,6 +869,9 @@ msgstr "Nach"
msgid "After (calculation method)"
msgstr "Nach (Berechnungsmethode)"
+msgid "Aging"
+msgstr "Altersanalyse"
+
msgid "Agree on the scope"
msgstr "Einigen Sie sich auf den Umfang"
@@ -871,6 +890,9 @@ msgstr "Alle"
msgid "All {total} phases are done. Nice work — your team is up and running."
msgstr "Alle {total} Phasen sind abgeschlossen. Großartig — Ihr Team ist einsatzbereit."
+msgid "All accounts"
+msgstr "Alle Konten"
+
msgid "All actions selected"
msgstr "Alle Aktionen ausgewählt"
@@ -983,6 +1005,9 @@ msgstr "Die Position einer Operation in der Warteschlange seines Arbeitszentrums
msgid "An unexpected error occurred while connecting to Onshape. Try connecting again."
msgstr "Bei der Verbindung mit Onshape ist ein unerwarteter Fehler aufgetreten. Versuchen Sie die Verbindung erneut."
+msgid "Analytics"
+msgstr "Analytik"
+
msgid "Anchors the Plan timeline to real dates. Leave blank for a relative, week-numbered timeline. Setting either one fills in the rest."
msgstr "Verankert die Plan-Zeitleiste mit echten Daten. Lassen Sie das Feld leer für eine relative, wochenweise nummerierte Zeitleiste. Das Festlegen einer der beiden Optionen füllt den Rest automatisch aus."
@@ -1026,6 +1051,9 @@ msgstr "Beliebiger Artikeltyp"
msgid "Anything not explicitly listed in scope above"
msgstr "Alles, was oben nicht explizit im Umfang aufgeführt ist"
+msgid "AP Aging"
+msgstr "Kreditorenalterung"
+
msgid "AP Clerk"
msgstr "AP-Sachbearbeiter"
@@ -1138,6 +1166,9 @@ msgstr "AQL"
msgid "AQL (Z1.4 / ISO 2859-1)"
msgstr "AQL (Z1.4 / ISO 2859-1)"
+msgid "AR Aging"
+msgstr "Debitorenalterung"
+
msgid "AR Clerk"
msgstr "AR-Sachbearbeiter"
@@ -1245,6 +1276,11 @@ msgstr "Sind Sie sicher, dass Sie {0} löschen möchten? Dies kann nicht rückg
msgid "Are you sure you want to delete {name}? This cannot be undone."
msgstr "Sind Sie sicher, dass Sie {name} löschen möchten? Dies kann nicht rückgängig gemacht werden."
+#. placeholder {0}: activeView.name
+#. placeholder {0}: viewPendingDelete.name
+msgid "Are you sure you want to delete the \"{0}\" view? This cannot be undone."
+msgstr "Sind Sie sicher, dass Sie die \"{0}\" Ansicht löschen möchten? Dies kann nicht rückgängig gemacht werden."
+
#. placeholder {0}: selectedCustomField?.name
msgid "Are you sure you want to delete the {0} field?"
msgstr "Sind Sie sicher, dass Sie das Feld {0} löschen möchten?"
@@ -1634,6 +1670,9 @@ msgstr "Anlagen-ID"
msgid "Assets"
msgstr "Vermögenswerte"
+msgid "Assets, liabilities and equity as of a date"
+msgstr "Vermögenswerte, Verbindlichkeiten und Eigenkapital an einem bestimmten Stichtag"
+
msgid "Assign printers to locations. Shipping, receiving, and work centers inherit the location default unless overridden."
msgstr "Drucker Standorten zuweisen. Versand, Empfang und Arbeitszentren erben die Standortvorgabe, sofern nicht überschrieben."
@@ -1890,6 +1929,9 @@ msgstr "Unter Sicherheitsbestand"
msgid "Beta"
msgstr "Beta"
+msgid "Biggest causes of scrap by reason, item, or work center"
+msgstr "Hauptursachen für Ausschuss nach Grund, Artikel oder Arbeitszentrum"
+
msgid "Bill of Material"
msgstr "Stückliste"
@@ -2020,12 +2062,18 @@ msgstr "von {byUser}"
msgid "By accepting the invite, you agree to the <0>Terms of Service</0> and <1>Privacy Policy</1>."
msgstr "Durch Annahme der Einladung stimmen Sie den <0>Nutzungsbedingungen</0> und der <1>Datenschutzrichtlinie</1> zu."
+msgid "By dimension"
+msgstr "Nach Dimension"
+
msgid "By Document Date"
msgstr "Nach Dokumentdatum"
msgid "By Due Date"
msgstr "Nach Fälligkeitsdatum"
+msgid "By field"
+msgstr "Nach Feld"
+
msgid "By Item"
msgstr "Nach Artikel"
@@ -2383,6 +2431,9 @@ msgstr "Suche löschen"
msgid "Clear search query"
msgstr "Suchanfrage löschen"
+msgid "Clear selection"
+msgstr "Auswahl löschen"
+
msgid "Clear this invoice with the party's posted credits as well as cash. Credits apply directly — no posting needed."
msgstr "Begleichen Sie diese Rechnung mit den gebuchten Gutschriften der Partei sowie mit Bargeld. Gutschriften werden direkt angewendet — keine Buchung erforderlich."
@@ -2416,6 +2467,9 @@ msgstr "Schließungsdatum"
msgid "Close Period"
msgstr "Zeitraum schließen"
+msgid "Close Reports"
+msgstr "Berichte schließen"
+
msgid "Close Status"
msgstr "Schließstatus"
@@ -2464,6 +2518,12 @@ msgstr "Rüsten einklappen"
msgid "Collapse subtree"
msgstr "Teilbaum einklappen"
+msgid "Column dimension"
+msgstr "Spaltendimension"
+
+msgid "Column field"
+msgstr "Spaltenfeld"
+
msgid "Column visibility and order"
msgstr "Spaltensichtbarkeit und -reihenfolge"
@@ -2560,6 +2620,9 @@ msgstr "Fertigstellungs-Barcode"
msgid "Completion Time"
msgstr "Abschlusszeit"
+msgid "Condensed P&L with margins and key subtotals"
+msgstr "Komprimierte Gewinn- und Verlustrechnung mit Margen und wichtigen Zwischensummen"
+
msgid "Conditions"
msgstr "Bedingungen"
@@ -3041,6 +3104,9 @@ msgstr "Kosten der verkauften Waren (COGS)"
msgid "Cost of Goods Sold (default)"
msgstr "Kosten der verkauften Waren (Standard)"
+msgid "Cost of Sales"
+msgstr "Kosten der verkauften Waren"
+
msgid "Costing"
msgstr "Kostenberechnung"
@@ -3852,6 +3918,10 @@ msgstr "Definieren Sie mehrstufige Stücklisten und Bill of Process (Herstellung
msgid "Delete"
msgstr "Löschen"
+#. placeholder {0}: view.name
+msgid "Delete {0}"
+msgstr "{0} löschen"
+
msgid "Delete {name}"
msgstr "Löschen {name}"
@@ -4138,6 +4208,9 @@ msgstr "Typ löschen"
msgid "Delete Unit of Measure"
msgstr "Maßeinheit löschen"
+msgid "Delete view"
+msgstr "Ansicht löschen"
+
msgid "Delete View"
msgstr "Ansicht löschen"
@@ -5241,6 +5314,9 @@ msgstr "Der Austausch des Autorisierungscodes gegen ein Zugriffstoken ist fehlge
msgid "Excluded"
msgstr "Ausgeschlossen"
+msgid "Executive P&L"
+msgstr "Geschäftsführungs-Gewinn- und Verlustrechnung"
+
msgid "Exemption Certificate"
msgstr "Ausnahmezertifikat"
@@ -5311,6 +5387,9 @@ msgstr "Aufwandseite der aufgeschobenen Steuerbewegungen (gekoppelt mit aufgesch
msgid "Expense side of deferred tax movements (paired with deferred tax liability)."
msgstr "Aktivaklasse konnte nicht erstellt werden: {0}"
+msgid "Expenses"
+msgstr "Ausgaben"
+
msgid "Expert guidance"
msgstr "Fachkundige Anleitung"
@@ -5803,6 +5882,9 @@ msgstr "Abschließen"
msgid "Finalizing a fiscal month through the Open → Locked → Closed lifecycle; a closed period is frozen and its balances snapshotted, reversible only by explicit reopen."
msgstr "Abschluss eines Geschäftsmonats durch den Open → Locked → Closed-Lebenszyklus; eine geschlossene Periode ist eingefroren und ihre Salden sind erfasst, nur durch explizites Wiedereröffnen rückgängig zu machen."
+msgid "Financial Statements"
+msgstr "Jahresabschlussberichte"
+
msgid "finish"
msgstr "Fertigerzeugnisse"
@@ -6263,9 +6345,15 @@ msgstr "Klassen"
msgid "Grades"
msgstr "Sorten"
+msgid "Gross Profit"
+msgstr "Bruttogewinn"
+
msgid "Group"
msgstr "Gruppe"
+msgid "Group by"
+msgstr "Gruppieren nach"
+
msgid "Group Members"
msgstr "Gruppenmitglieder"
@@ -6621,6 +6709,9 @@ msgstr "Einkommen / Bilanz (geerbt)"
msgid "Income Statement"
msgstr "Gewinn- und Verlustrechnung"
+msgid "Income Tax"
+msgstr "Einkommensteuer"
+
msgid "Income/Balance"
msgstr "Einnahmen/Bilanz"
@@ -7166,6 +7257,9 @@ msgstr "Arbeitseinheit"
msgid "Language"
msgstr "Sprache"
+msgid "Last 6 Months"
+msgstr "Letzte 6 Monate"
+
msgid "Last Calibration"
msgstr "Letzte Kalibrierung"
@@ -7962,6 +8056,9 @@ msgstr "Geld, das dir geschuldet wird"
msgid "Money you owe"
msgstr "Geld, das Sie schulden"
+msgid "Monthly"
+msgstr "Monatlich"
+
msgid "Months over which this asset depreciates for tax purposes (when not using MACRS)."
msgstr "Monate, über die dieses Vermögenswert für Steuerzwecke abgeschrieben wird (wenn MACRS nicht verwendet wird)."
@@ -8075,6 +8172,9 @@ msgstr "Nettobuchwert"
msgid "Net Change"
msgstr "Nettoänderung"
+msgid "Net Income"
+msgstr "Nettoeinkommen"
+
msgid "Never"
msgstr "Nie"
@@ -8567,6 +8667,9 @@ msgstr "Keine Artikel"
msgid "No items have inventory activity here yet."
msgstr "Hier gibt es noch keine Bestandsbewegungen."
+msgid "No journal lines in scope for this period"
+msgstr "Keine Journalzeilen im Bereich für diesen Zeitraum"
+
msgid "No lines to map"
msgstr "Keine Zeilen zum Zuordnen"
@@ -8666,6 +8769,9 @@ msgstr "Kein Prozess ausgewählt"
msgid "No production events recorded for this operation yet"
msgstr "Für diesen Vorgang wurden noch keine Produktionsereignisse aufgezeichnet"
+msgid "No purchases in this period"
+msgstr "Keine Käufe in diesem Zeitraum"
+
msgid "No Quote"
msgstr "Kein Angebot"
@@ -8684,6 +8790,9 @@ msgstr "Kein Referenzbild"
msgid "No remaining entities to inspect."
msgstr "Keine verbleibenden Entitäten zur Überprüfung."
+msgid "No reports match your search."
+msgstr "Keine Berichte entsprechen Ihrer Suche."
+
msgid "No results"
msgstr "Keine Ergebnisse"
@@ -8904,6 +9013,9 @@ msgstr "Mindestbestand zur Wartung für die Nutzung an diesem Standort"
msgid "On-hand inventory remains"
msgstr "Bestandsinventar vorhanden"
+msgid "On-hand value by location or item, with GL tie-out"
+msgstr "Bestandswert nach Lagerort oder Artikel mit Hauptbuch-Abstimmung"
+
msgid "On-hand value of manufactured goods (Make items)"
msgstr "Bestandswert hergestellter Waren (Herstellartikel)"
@@ -9009,6 +9121,9 @@ msgstr "Offene Aufträge"
msgid "Open menu"
msgstr "Menü öffnen"
+msgid "Open payables by supplier and age"
+msgstr "Offene Verbindlichkeiten nach Lieferant und Fälligkeitsdauer"
+
msgid "Open Purchase Invoices"
msgstr "Offene Kaufrechnungen"
@@ -9024,6 +9139,9 @@ msgstr "Offene Angebote"
msgid "Open Reactive"
msgstr "Offene reaktive Wartung"
+msgid "Open receivables by customer and age"
+msgstr "Offene Forderungen nach Kunde und Fälligkeitsdauer"
+
msgid "Open RFQs"
msgstr "Offene Anfragen"
@@ -9057,6 +9175,9 @@ msgstr "Eröffnungssaldo der bereits vor dem Hinzufügen dieses Vermögenswerts
msgid "Operating Expenses"
msgstr "Betriebsausgaben"
+msgid "Operating Income"
+msgstr "Betriebseinkommen"
+
msgid "Operation"
msgstr "Betrieb"
@@ -9172,6 +9293,12 @@ msgstr "Original"
msgid "Original Count"
msgstr "Ursprüngliche Anzahl"
+msgid "Other Expense"
+msgstr "Sonstige Ausgaben"
+
+msgid "Other Income"
+msgstr "Sonstiges Einkommen"
+
msgid "Other Income account for FX gains when a payment settles a foreign-currency invoice at a more favorable rate"
msgstr "Sonstige Einnahmen für Wechselkursgewinne, wenn eine Zahlung eine Rechnung in Fremdwährung zu einem günstigeren Kurs ausgleicht"
@@ -9557,6 +9684,11 @@ msgstr "Stück/Minute"
msgid "Pin"
msgstr "Anheften"
+#. placeholder {0}: report.name
+#. placeholder {0}: view.name
+msgid "Pin {0}"
+msgstr "Anheften {0}"
+
msgid "Pinned"
msgstr "Angeheftet"
@@ -10083,6 +10215,9 @@ msgstr "Kaufeinheit:"
msgid "Purchased"
msgstr "Gekauft"
+msgid "Purchases"
+msgstr "Käufe"
+
msgid "purchasing"
msgstr "Einkauf & Kosten der verkauften Waren"
@@ -10211,6 +10346,9 @@ msgstr "Mengenbasisierte Preisstufen für diese Überschreibung; der angewendete
msgid "Quantity: {0}"
msgstr "Menge: {0}"
+msgid "Quarterly"
+msgstr "Vierteljährlich"
+
msgid "Question"
msgstr "Frage"
@@ -10678,6 +10816,9 @@ msgstr "Auffüllungssystem"
msgid "Report"
msgstr "Bericht"
+msgid "Reporting"
+msgstr "Berichtswesen"
+
msgid "Reporting dimension"
msgstr "Berichtsdimension"
@@ -10687,6 +10828,9 @@ msgstr "Berichte"
msgid "Reprint"
msgstr "Erneut drucken"
+msgid "Request access"
+msgstr "Zugriff anfordern"
+
msgid "Request Approval"
msgstr "Genehmigung anfordern"
@@ -10821,6 +10965,12 @@ msgstr "Rückgabe ungenutzten Pickmaterials"
msgid "Rev {revision}"
msgstr "Rev {revision}"
+msgid "Revenue"
+msgstr "Umsatz"
+
+msgid "Revenue and expenses over a period"
+msgstr "Umsatz und Aufwendungen über einen Zeitraum"
+
msgid "Reverse all inventory adjustments"
msgstr "Alle Bestandsanpassungen rückgängig machen"
@@ -11153,9 +11303,15 @@ msgstr "Kontakte speichern"
msgid "Save Method"
msgstr "Methode speichern"
+msgid "Save view"
+msgstr "Ansicht speichern"
+
msgid "Save View"
msgstr "Ansicht speichern"
+msgid "Saved Views"
+msgstr "Gespeicherte Ansichten"
+
msgid "Saving..."
msgstr "Wird gespeichert..."
@@ -11868,6 +12024,15 @@ msgstr "Synchronisierungsoptionen anzeigen"
msgid "Showing {0} of {totalCount} — refine your search"
msgstr "Zeige {0} von {totalCount} — verfeinern Sie Ihre Suche"
+msgid "Showing in {parentCurrency}"
+msgstr "Anzeige in {parentCurrency}"
+
+msgid "Showing the first 500 lines"
+msgstr "Die ersten 500 Zeilen werden angezeigt"
+
+msgid "Showing the top 1,000 groups by amount"
+msgstr "Die Top 1.000 Gruppen nach Betrag werden angezeigt"
+
msgid "Shown as a faint background behind every page of generated PDFs"
msgstr "Wird als schwacher Hintergrund hinter jeder Seite generierter PDFs angezeigt"
@@ -11937,6 +12102,15 @@ msgstr "Übersprungen"
msgid "Slack"
msgstr "Slack"
+msgid "Slice asset activity by location, item, or any dimension"
+msgstr "Teile die Vermögensaktivität nach Standort, Artikel oder einer beliebigen Dimension auf"
+
+msgid "Slice expenses by location, cost center, or any dimension"
+msgstr "Teile die Ausgaben nach Standort, Kostenstelle oder einer beliebigen Dimension auf"
+
+msgid "Slice revenue by customer, customer type, or any dimension"
+msgstr "Umsatz nach Kunde, Kundentyp oder beliebiger Dimension aufschlüsseln"
+
msgid "Smoke-test the core daily flows end to end"
msgstr "Smoke-Test der täglichen Kernabläufe von Anfang bis Ende"
@@ -12018,6 +12192,9 @@ msgstr "Bestimmte Kunden"
msgid "Specific Items"
msgstr "Spezifische Artikel"
+msgid "Spend by supplier, item, or category — your biggest cost drivers"
+msgstr "Ausgaben nach Lieferant, Artikel oder Kategorie – Ihre größten Kostenverursacher"
+
msgid "Split"
msgstr "Teilen"
@@ -13343,6 +13520,9 @@ msgstr "Design"
msgid "Theme Color"
msgstr "Designfarbe"
+msgid "Then by"
+msgstr "Dann nach"
+
msgid "There are no active supplier quotes to compare for this RFQ."
msgstr "Es gibt keine aktiven Lieferantenofferten zum Vergleichen für diese Anfrage."
@@ -13585,6 +13765,9 @@ msgstr "Zeitzone"
msgid "Title"
msgstr "Titel"
+msgid "To Date"
+msgstr "Stichtag"
+
msgid "To deactivate, use the row menu and choose Deactivate Account."
msgstr "Um zu deaktivieren, verwenden Sie das Zeilenmenü und wählen Sie Konto deaktivieren."
@@ -13976,6 +14159,11 @@ msgstr "Entfernen"
msgid "Unpick {0}"
msgstr "Entnahme rückgängig machen {0}"
+#. placeholder {0}: report.name
+#. placeholder {0}: view.name
+msgid "Unpin {0}"
+msgstr "Abheften {0}"
+
msgid "Unposted Documents"
msgstr "Unveröffentlichte Dokumente"
@@ -14225,9 +14413,6 @@ msgstr "Validiert"
msgid "Validating job..."
msgstr "Auftrag wird validiert..."
-msgid "Valuation"
-msgstr "Bewertung"
-
msgid "Value"
msgstr "Wert"
@@ -14653,6 +14838,9 @@ msgstr "Was sich ändert, wenn Sie zu Carbon wechseln, und ungefähr, was es wer
msgid "What data"
msgstr "Welche Daten"
+msgid "What drove inventory up or down, by any dimension"
+msgstr "Was den Bestand nach oben oder unten getrieben hat, nach beliebiger Dimension"
+
msgid "What is {translatedTerm}?"
msgstr "{translatedTerm} ist was?"
@@ -15049,6 +15237,9 @@ msgstr "Den Wert eines Vermögenswerts über seine Lebensdauer abschreiben — e
msgid "Year"
msgstr "Jahr"
+msgid "Yearly"
+msgstr "Jährlich"
+
msgid "Yes"
msgstr "Ja"
diff --git a/packages/locale/locales/en/erp.po b/packages/locale/locales/en/erp.po
index acdc8a2815..0cb11af598 100644
--- a/packages/locale/locales/en/erp.po
+++ b/packages/locale/locales/en/erp.po
@@ -48,6 +48,10 @@ msgstr "(excluded for this customer)"
msgid "{0, plural, one {This part is on 1 open change notice} other {This part is on # open change notices}}"
msgstr "{0, plural, one {This part is on 1 open change notice} other {This part is on # open change notices}}"
+#. placeholder {0}: selectedAccountIds.length
+msgid "{0} accounts"
+msgstr "{0} accounts"
+
#. placeholder {0}: precise?.text
msgid "{0} ago"
msgstr "{0} ago"
@@ -163,6 +167,9 @@ msgstr "{years}yr"
msgid "/month/user"
msgstr "/month/user"
+msgid "% of total"
+msgstr "% of total"
+
msgid "% of Total"
msgstr "% of Total"
@@ -474,6 +481,9 @@ msgstr "Account"
msgid "Account & Details"
msgstr "Account & Details"
+msgid "Account balances with debits and credits"
+msgstr "Account balances with debits and credits"
+
msgid "Account for advance payments made before goods or services are received"
msgstr "Account for advance payments made before goods or services are received"
@@ -510,9 +520,15 @@ msgstr "accounting"
msgid "Accounting"
msgstr "Accounting"
+msgid "Accounting is currently in beta. Request access to enable reporting, journal entries, accounting periods, fixed assets, and more."
+msgstr "Accounting is currently in beta. Request access to enable reporting, journal entries, accounting periods, fixed assets, and more."
+
msgid "Accounting is disabled"
msgstr "Accounting is disabled"
+msgid "Accounting is disabled for this company."
+msgstr "Accounting is disabled for this company."
+
msgid "Accounting is enabled"
msgstr "Accounting is enabled"
@@ -853,6 +869,9 @@ msgstr "After"
msgid "After (calculation method)"
msgstr "After (calculation method)"
+msgid "Aging"
+msgstr "Aging"
+
msgid "Agree on the scope"
msgstr "Agree on the scope"
@@ -871,6 +890,9 @@ msgstr "All"
msgid "All {total} phases are done. Nice work — your team is up and running."
msgstr "All {total} phases are done. Nice work — your team is up and running."
+msgid "All accounts"
+msgstr "All accounts"
+
msgid "All actions selected"
msgstr "All actions selected"
@@ -983,6 +1005,9 @@ msgstr "An operation's position in its work center's queue — the order the flo
msgid "An unexpected error occurred while connecting to Onshape. Try connecting again."
msgstr "An unexpected error occurred while connecting to Onshape. Try connecting again."
+msgid "Analytics"
+msgstr "Analytics"
+
msgid "Anchors the Plan timeline to real dates. Leave blank for a relative, week-numbered timeline. Setting either one fills in the rest."
msgstr "Anchors the Plan timeline to real dates. Leave blank for a relative, week-numbered timeline. Setting either one fills in the rest."
@@ -1026,6 +1051,9 @@ msgstr "Any item type"
msgid "Anything not explicitly listed in scope above"
msgstr "Anything not explicitly listed in scope above"
+msgid "AP Aging"
+msgstr "AP Aging"
+
msgid "AP Clerk"
msgstr "AP Clerk"
@@ -1138,6 +1166,9 @@ msgstr "AQL"
msgid "AQL (Z1.4 / ISO 2859-1)"
msgstr "AQL (Z1.4 / ISO 2859-1)"
+msgid "AR Aging"
+msgstr "AR Aging"
+
msgid "AR Clerk"
msgstr "AR Clerk"
@@ -1245,6 +1276,11 @@ msgstr "Are you sure you want to delete {0}? This cannot be undone."
msgid "Are you sure you want to delete {name}? This cannot be undone."
msgstr "Are you sure you want to delete {name}? This cannot be undone."
+#. placeholder {0}: activeView.name
+#. placeholder {0}: viewPendingDelete.name
+msgid "Are you sure you want to delete the \"{0}\" view? This cannot be undone."
+msgstr "Are you sure you want to delete the \"{0}\" view? This cannot be undone."
+
#. placeholder {0}: selectedCustomField?.name
msgid "Are you sure you want to delete the {0} field?"
msgstr "Are you sure you want to delete the {0} field?"
@@ -1634,6 +1670,9 @@ msgstr "Asset ID"
msgid "Assets"
msgstr "Assets"
+msgid "Assets, liabilities and equity as of a date"
+msgstr "Assets, liabilities and equity as of a date"
+
msgid "Assign printers to locations. Shipping, receiving, and work centers inherit the location default unless overridden."
msgstr "Assign printers to locations. Shipping, receiving, and work centers inherit the location default unless overridden."
@@ -1890,6 +1929,9 @@ msgstr "Below safety stock"
msgid "Beta"
msgstr "Beta"
+msgid "Biggest causes of scrap by reason, item, or work center"
+msgstr "Biggest causes of scrap by reason, item, or work center"
+
msgid "Bill of Material"
msgstr "Bill of Material"
@@ -2020,12 +2062,18 @@ msgstr "by {byUser}"
msgid "By accepting the invite, you agree to the <0>Terms of Service</0> and <1>Privacy Policy</1>."
msgstr "By accepting the invite, you agree to the <0>Terms of Service</0> and <1>Privacy Policy</1>."
+msgid "By dimension"
+msgstr "By dimension"
+
msgid "By Document Date"
msgstr "By Document Date"
msgid "By Due Date"
msgstr "By Due Date"
+msgid "By field"
+msgstr "By field"
+
msgid "By Item"
msgstr "By Item"
@@ -2383,6 +2431,9 @@ msgstr "Clear search"
msgid "Clear search query"
msgstr "Clear search query"
+msgid "Clear selection"
+msgstr "Clear selection"
+
msgid "Clear this invoice with the party's posted credits as well as cash. Credits apply directly — no posting needed."
msgstr "Clear this invoice with the party's posted credits as well as cash. Credits apply directly — no posting needed."
@@ -2416,6 +2467,9 @@ msgstr "Close Date"
msgid "Close Period"
msgstr "Close Period"
+msgid "Close Reports"
+msgstr "Close Reports"
+
msgid "Close Status"
msgstr "Close Status"
@@ -2464,6 +2518,12 @@ msgstr "Collapse Setup"
msgid "Collapse subtree"
msgstr "Collapse subtree"
+msgid "Column dimension"
+msgstr "Column dimension"
+
+msgid "Column field"
+msgstr "Column field"
+
msgid "Column visibility and order"
msgstr "Column visibility and order"
@@ -2560,6 +2620,9 @@ msgstr "Completion Barcode"
msgid "Completion Time"
msgstr "Completion Time"
+msgid "Condensed P&L with margins and key subtotals"
+msgstr "Condensed P&L with margins and key subtotals"
+
msgid "Conditions"
msgstr "Conditions"
@@ -3041,6 +3104,9 @@ msgstr "Cost of goods sold (COGS)"
msgid "Cost of Goods Sold (default)"
msgstr "Cost of Goods Sold (default)"
+msgid "Cost of Sales"
+msgstr "Cost of Sales"
+
msgid "Costing"
msgstr "Costing"
@@ -3852,6 +3918,10 @@ msgstr "Define multi-level BOMs and Bill of Process (make methods)"
msgid "Delete"
msgstr "Delete"
+#. placeholder {0}: view.name
+msgid "Delete {0}"
+msgstr "Delete {0}"
+
msgid "Delete {name}"
msgstr "Delete {name}"
@@ -4138,6 +4208,9 @@ msgstr "Delete Type"
msgid "Delete Unit of Measure"
msgstr "Delete Unit of Measure"
+msgid "Delete view"
+msgstr "Delete view"
+
msgid "Delete View"
msgstr "Delete View"
@@ -5241,6 +5314,9 @@ msgstr "Exchanging the authorization code for an access token failed. Try connec
msgid "Excluded"
msgstr "Excluded"
+msgid "Executive P&L"
+msgstr "Executive P&L"
+
msgid "Exemption Certificate"
msgstr "Exemption Certificate"
@@ -5311,6 +5387,9 @@ msgstr "Expense GL account debited when inventory is shipped/issued against a sa
msgid "Expense side of deferred tax movements (paired with deferred tax liability)."
msgstr "Expense side of deferred tax movements (paired with deferred tax liability)."
+msgid "Expenses"
+msgstr "Expenses"
+
msgid "Expert guidance"
msgstr "Expert guidance"
@@ -5803,6 +5882,9 @@ msgstr "Finalize"
msgid "Finalizing a fiscal month through the Open → Locked → Closed lifecycle; a closed period is frozen and its balances snapshotted, reversible only by explicit reopen."
msgstr "Finalizing a fiscal month through the Open → Locked → Closed lifecycle; a closed period is frozen and its balances snapshotted, reversible only by explicit reopen."
+msgid "Financial Statements"
+msgstr "Financial Statements"
+
msgid "finish"
msgstr "finish"
@@ -6263,9 +6345,15 @@ msgstr "grades"
msgid "Grades"
msgstr "Grades"
+msgid "Gross Profit"
+msgstr "Gross Profit"
+
msgid "Group"
msgstr "Group"
+msgid "Group by"
+msgstr "Group by"
+
msgid "Group Members"
msgstr "Group Members"
@@ -6621,6 +6709,9 @@ msgstr "Income / Balance (inherited)"
msgid "Income Statement"
msgstr "Income Statement"
+msgid "Income Tax"
+msgstr "Income Tax"
+
msgid "Income/Balance"
msgstr "Income/Balance"
@@ -7166,6 +7257,9 @@ msgstr "Labor Unit"
msgid "Language"
msgstr "Language"
+msgid "Last 6 Months"
+msgstr "Last 6 Months"
+
msgid "Last Calibration"
msgstr "Last Calibration"
@@ -7962,6 +8056,9 @@ msgstr "Money owed to you"
msgid "Money you owe"
msgstr "Money you owe"
+msgid "Monthly"
+msgstr "Monthly"
+
msgid "Months over which this asset depreciates for tax purposes (when not using MACRS)."
msgstr "Months over which this asset depreciates for tax purposes (when not using MACRS)."
@@ -8075,6 +8172,9 @@ msgstr "Net Book Value"
msgid "Net Change"
msgstr "Net Change"
+msgid "Net Income"
+msgstr "Net Income"
+
msgid "Never"
msgstr "Never"
@@ -8567,6 +8667,9 @@ msgstr "No items"
msgid "No items have inventory activity here yet."
msgstr "No items have inventory activity here yet."
+msgid "No journal lines in scope for this period"
+msgstr "No journal lines in scope for this period"
+
msgid "No lines to map"
msgstr "No lines to map"
@@ -8666,6 +8769,9 @@ msgstr "No process selected"
msgid "No production events recorded for this operation yet"
msgstr "No production events recorded for this operation yet"
+msgid "No purchases in this period"
+msgstr "No purchases in this period"
+
msgid "No Quote"
msgstr "No Quote"
@@ -8684,6 +8790,9 @@ msgstr "No reference image"
msgid "No remaining entities to inspect."
msgstr "No remaining entities to inspect."
+msgid "No reports match your search."
+msgstr "No reports match your search."
+
msgid "No results"
msgstr "No results"
@@ -8904,6 +9013,9 @@ msgstr "On-hand floor to maintain for service use at this location"
msgid "On-hand inventory remains"
msgstr "On-hand inventory remains"
+msgid "On-hand value by location or item, with GL tie-out"
+msgstr "On-hand value by location or item, with GL tie-out"
+
msgid "On-hand value of manufactured goods (Make items)"
msgstr "On-hand value of manufactured goods (Make items)"
@@ -9009,6 +9121,9 @@ msgstr "Open jobs"
msgid "Open menu"
msgstr "Open menu"
+msgid "Open payables by supplier and age"
+msgstr "Open payables by supplier and age"
+
msgid "Open Purchase Invoices"
msgstr "Open Purchase Invoices"
@@ -9024,6 +9139,9 @@ msgstr "Open Quotes"
msgid "Open Reactive"
msgstr "Open Reactive"
+msgid "Open receivables by customer and age"
+msgstr "Open receivables by customer and age"
+
msgid "Open RFQs"
msgstr "Open RFQs"
@@ -9057,6 +9175,9 @@ msgstr "Opening balance of depreciation already booked before this asset was add
msgid "Operating Expenses"
msgstr "Operating Expenses"
+msgid "Operating Income"
+msgstr "Operating Income"
+
msgid "Operation"
msgstr "Operation"
@@ -9172,6 +9293,12 @@ msgstr "Original"
msgid "Original Count"
msgstr "Original Count"
+msgid "Other Expense"
+msgstr "Other Expense"
+
+msgid "Other Income"
+msgstr "Other Income"
+
msgid "Other Income account for FX gains when a payment settles a foreign-currency invoice at a more favorable rate"
msgstr "Other Income account for FX gains when a payment settles a foreign-currency invoice at a more favorable rate"
@@ -9557,6 +9684,11 @@ msgstr "Pieces/Minute"
msgid "Pin"
msgstr "Pin"
+#. placeholder {0}: report.name
+#. placeholder {0}: view.name
+msgid "Pin {0}"
+msgstr "Pin {0}"
+
msgid "Pinned"
msgstr "Pinned"
@@ -10083,6 +10215,9 @@ msgstr "Purchase Unit:"
msgid "Purchased"
msgstr "Purchased"
+msgid "Purchases"
+msgstr "Purchases"
+
msgid "purchasing"
msgstr "purchasing"
@@ -10211,6 +10346,9 @@ msgstr "Quantity-based pricing tiers for this override; the unit price applied i
msgid "Quantity: {0}"
msgstr "Quantity: {0}"
+msgid "Quarterly"
+msgstr "Quarterly"
+
msgid "Question"
msgstr "Question"
@@ -10678,6 +10816,9 @@ msgstr "Replenishment System"
msgid "Report"
msgstr "Report"
+msgid "Reporting"
+msgstr "Reporting"
+
msgid "Reporting dimension"
msgstr "Reporting dimension"
@@ -10687,6 +10828,9 @@ msgstr "Reports"
msgid "Reprint"
msgstr "Reprint"
+msgid "Request access"
+msgstr "Request access"
+
msgid "Request Approval"
msgstr "Request Approval"
@@ -10821,6 +10965,12 @@ msgstr "Returning unused picked material"
msgid "Rev {revision}"
msgstr "Rev {revision}"
+msgid "Revenue"
+msgstr "Revenue"
+
+msgid "Revenue and expenses over a period"
+msgstr "Revenue and expenses over a period"
+
msgid "Reverse all inventory adjustments"
msgstr "Reverse all inventory adjustments"
@@ -11153,9 +11303,15 @@ msgstr "Save contacts"
msgid "Save Method"
msgstr "Save Method"
+msgid "Save view"
+msgstr "Save view"
+
msgid "Save View"
msgstr "Save View"
+msgid "Saved Views"
+msgstr "Saved Views"
+
msgid "Saving..."
msgstr "Saving..."
@@ -11868,6 +12024,15 @@ msgstr "Show sync options"
msgid "Showing {0} of {totalCount} — refine your search"
msgstr "Showing {0} of {totalCount} — refine your search"
+msgid "Showing in {parentCurrency}"
+msgstr "Showing in {parentCurrency}"
+
+msgid "Showing the first 500 lines"
+msgstr "Showing the first 500 lines"
+
+msgid "Showing the top 1,000 groups by amount"
+msgstr "Showing the top 1,000 groups by amount"
+
msgid "Shown as a faint background behind every page of generated PDFs"
msgstr "Shown as a faint background behind every page of generated PDFs"
@@ -11937,6 +12102,15 @@ msgstr "Skipped"
msgid "Slack"
msgstr "Slack"
+msgid "Slice asset activity by location, item, or any dimension"
+msgstr "Slice asset activity by location, item, or any dimension"
+
+msgid "Slice expenses by location, cost center, or any dimension"
+msgstr "Slice expenses by location, cost center, or any dimension"
+
+msgid "Slice revenue by customer, customer type, or any dimension"
+msgstr "Slice revenue by customer, customer type, or any dimension"
+
msgid "Smoke-test the core daily flows end to end"
msgstr "Smoke-test the core daily flows end to end"
@@ -12018,6 +12192,9 @@ msgstr "Specific Customers"
msgid "Specific Items"
msgstr "Specific Items"
+msgid "Spend by supplier, item, or category — your biggest cost drivers"
+msgstr "Spend by supplier, item, or category — your biggest cost drivers"
+
msgid "Split"
msgstr "Split"
@@ -13343,6 +13520,9 @@ msgstr "Theme"
msgid "Theme Color"
msgstr "Theme Color"
+msgid "Then by"
+msgstr "Then by"
+
msgid "There are no active supplier quotes to compare for this RFQ."
msgstr "There are no active supplier quotes to compare for this RFQ."
@@ -13585,6 +13765,9 @@ msgstr "Timezone"
msgid "Title"
msgstr "Title"
+msgid "To Date"
+msgstr "To Date"
+
msgid "To deactivate, use the row menu and choose Deactivate Account."
msgstr "To deactivate, use the row menu and choose Deactivate Account."
@@ -13976,6 +14159,11 @@ msgstr "Unpick"
msgid "Unpick {0}"
msgstr "Unpick {0}"
+#. placeholder {0}: report.name
+#. placeholder {0}: view.name
+msgid "Unpin {0}"
+msgstr "Unpin {0}"
+
msgid "Unposted Documents"
msgstr "Unposted Documents"
@@ -14225,9 +14413,6 @@ msgstr "Validated"
msgid "Validating job..."
msgstr "Validating job..."
-msgid "Valuation"
-msgstr "Valuation"
-
msgid "Value"
msgstr "Value"
@@ -14653,6 +14838,9 @@ msgstr "What changes when you move to Carbon, and roughly what it's worth. Estim
msgid "What data"
msgstr "What data"
+msgid "What drove inventory up or down, by any dimension"
+msgstr "What drove inventory up or down, by any dimension"
+
msgid "What is {translatedTerm}?"
msgstr "What is {translatedTerm}?"
@@ -15049,6 +15237,9 @@ msgstr "Writing an asset's value down over its life — a monthly batch you crea
msgid "Year"
msgstr "Year"
+msgid "Yearly"
+msgstr "Yearly"
+
msgid "Yes"
msgstr "Yes"
diff --git a/packages/locale/locales/es/erp.po b/packages/locale/locales/es/erp.po
index d98abbf9af..986c4e2410 100644
--- a/packages/locale/locales/es/erp.po
+++ b/packages/locale/locales/es/erp.po
@@ -48,6 +48,10 @@ msgstr "(excluido para este cliente)"
msgid "{0, plural, one {This part is on 1 open change notice} other {This part is on # open change notices}}"
msgstr "{0, plural, one {Esta parte está en 1 aviso de cambio abierto} other {Esta parte está en # avisos de cambio abiertos}}"
+#. placeholder {0}: selectedAccountIds.length
+msgid "{0} accounts"
+msgstr "{0} cuentas"
+
#. placeholder {0}: precise?.text
msgid "{0} ago"
msgstr "{0} hace"
@@ -163,6 +167,9 @@ msgstr "{years}yr"
msgid "/month/user"
msgstr "/mes/usuario"
+msgid "% of total"
+msgstr "% del total"
+
msgid "% of Total"
msgstr "% del Total"
@@ -474,6 +481,9 @@ msgstr "Cuenta"
msgid "Account & Details"
msgstr "Cuenta y detalles"
+msgid "Account balances with debits and credits"
+msgstr "Saldos de cuenta con débitos y créditos"
+
msgid "Account for advance payments made before goods or services are received"
msgstr "Contabilice los pagos por adelantado realizados antes de recibir bienes o servicios."
@@ -510,9 +520,15 @@ msgstr "contabilidad"
msgid "Accounting"
msgstr "Contabilidad"
+msgid "Accounting is currently in beta. Request access to enable reporting, journal entries, accounting periods, fixed assets, and more."
+msgstr "La contabilidad está actualmente en beta. Solicita acceso para habilitar informes, asientos de diario, períodos contables, activos fijos y más."
+
msgid "Accounting is disabled"
msgstr "La contabilidad está deshabilitada"
+msgid "Accounting is disabled for this company."
+msgstr "La contabilidad está deshabilitada para esta empresa."
+
msgid "Accounting is enabled"
msgstr "La contabilidad está habilitada"
@@ -853,6 +869,9 @@ msgstr "Después"
msgid "After (calculation method)"
msgstr "Después (método de cálculo)"
+msgid "Aging"
+msgstr "Antigüedad"
+
msgid "Agree on the scope"
msgstr "Acordar sobre el alcance"
@@ -871,6 +890,9 @@ msgstr "Todos"
msgid "All {total} phases are done. Nice work — your team is up and running."
msgstr "Todas las {total} fases están completadas. Buen trabajo — tu equipo está en funcionamiento."
+msgid "All accounts"
+msgstr "Todas las cuentas"
+
msgid "All actions selected"
msgstr "Todas las acciones seleccionadas"
@@ -983,6 +1005,9 @@ msgstr "La posición de una operación en la cola de su centro de trabajo — el
msgid "An unexpected error occurred while connecting to Onshape. Try connecting again."
msgstr "Se produjo un error inesperado al conectar con Onshape. Vuelve a intentar la conexión."
+msgid "Analytics"
+msgstr "Análisis"
+
msgid "Anchors the Plan timeline to real dates. Leave blank for a relative, week-numbered timeline. Setting either one fills in the rest."
msgstr "Ancla la cronología del Plan a fechas reales. Déjalo en blanco para una cronología relativa numerada por semanas. Configurar cualquiera de los dos completa el resto."
@@ -1026,6 +1051,9 @@ msgstr "Cualquier tipo de artículo"
msgid "Anything not explicitly listed in scope above"
msgstr "Cualquier cosa no explícitamente listada en el alcance anterior"
+msgid "AP Aging"
+msgstr "Análisis de Antigüedad de CxP"
+
msgid "AP Clerk"
msgstr "Empleado de Cuentas por Pagar"
@@ -1138,6 +1166,9 @@ msgstr "AQL"
msgid "AQL (Z1.4 / ISO 2859-1)"
msgstr "AQL (Z1.4 / ISO 2859-1)"
+msgid "AR Aging"
+msgstr "Análisis de Antigüedad de CxC"
+
msgid "AR Clerk"
msgstr "Empleado de Cuentas por Cobrar"
@@ -1245,6 +1276,11 @@ msgstr "¿Estás seguro de que deseas eliminar {0}? Esto no se puede deshacer."
msgid "Are you sure you want to delete {name}? This cannot be undone."
msgstr "¿Estás seguro de que deseas eliminar {name}? Esto no se puede deshacer."
+#. placeholder {0}: activeView.name
+#. placeholder {0}: viewPendingDelete.name
+msgid "Are you sure you want to delete the \"{0}\" view? This cannot be undone."
+msgstr "¿Está seguro de que desea eliminar la vista \"{0}\"? Esto no se puede deshacer."
+
#. placeholder {0}: selectedCustomField?.name
msgid "Are you sure you want to delete the {0} field?"
msgstr "¿Estás seguro de que deseas eliminar el campo {0}?"
@@ -1634,6 +1670,9 @@ msgstr "ID de Activo"
msgid "Assets"
msgstr "Activos"
+msgid "Assets, liabilities and equity as of a date"
+msgstr "Activos, pasivos y patrimonio a una fecha"
+
msgid "Assign printers to locations. Shipping, receiving, and work centers inherit the location default unless overridden."
msgstr "Asigna impresoras a ubicaciones. Envíos, recepciones y centros de trabajo heredan la ubicación predeterminada a menos que se anulen."
@@ -1890,6 +1929,9 @@ msgstr "Por debajo del stock de seguridad"
msgid "Beta"
msgstr "Beta"
+msgid "Biggest causes of scrap by reason, item, or work center"
+msgstr "Mayores causas de desechos por razón, artículo o centro de trabajo"
+
msgid "Bill of Material"
msgstr "Lista de Materiales"
@@ -2020,12 +2062,18 @@ msgstr "por {byUser}"
msgid "By accepting the invite, you agree to the <0>Terms of Service</0> and <1>Privacy Policy</1>."
msgstr "Al aceptar la invitación, aceptas los <0>Términos de Servicio</0> y la <1>Política de Privacidad</1>."
+msgid "By dimension"
+msgstr "Por dimensión"
+
msgid "By Document Date"
msgstr "Por Fecha de Documento"
msgid "By Due Date"
msgstr "Por Fecha de Vencimiento"
+msgid "By field"
+msgstr "Por campo"
+
msgid "By Item"
msgstr "Por Artículo"
@@ -2383,6 +2431,9 @@ msgstr "Limpiar búsqueda"
msgid "Clear search query"
msgstr "Borrar consulta de búsqueda"
+msgid "Clear selection"
+msgstr "Limpiar selección"
+
msgid "Clear this invoice with the party's posted credits as well as cash. Credits apply directly — no posting needed."
msgstr "Liquida esta factura con los créditos registrados de la parte así como con efectivo. Los créditos se aplican directamente — no se requiere registro."
@@ -2416,6 +2467,9 @@ msgstr "Fecha de Cierre"
msgid "Close Period"
msgstr "Cerrar Período"
+msgid "Close Reports"
+msgstr "Cerrar Reportes"
+
msgid "Close Status"
msgstr "Estado de Cierre"
@@ -2464,6 +2518,12 @@ msgstr "Contraer preparación"
msgid "Collapse subtree"
msgstr "Contraer subárbol"
+msgid "Column dimension"
+msgstr "Dimensión de columna"
+
+msgid "Column field"
+msgstr "Campo de columna"
+
msgid "Column visibility and order"
msgstr "Visibilidad y orden de columnas"
@@ -2560,6 +2620,9 @@ msgstr "Código de Barras de Finalización"
msgid "Completion Time"
msgstr "Tiempo de Finalización"
+msgid "Condensed P&L with margins and key subtotals"
+msgstr "Estado de Resultados Condensado con márgenes y subtotales clave"
+
msgid "Conditions"
msgstr "Condiciones"
@@ -3041,6 +3104,9 @@ msgstr "Costo de bienes vendidos (COGS)"
msgid "Cost of Goods Sold (default)"
msgstr "Costo de Bienes Vendidos (predeterminado)"
+msgid "Cost of Sales"
+msgstr "Costo de Ventas"
+
msgid "Costing"
msgstr "Cálculo de costos"
@@ -3852,6 +3918,10 @@ msgstr "Definir BOMs multinivel y Bill of Process (métodos de fabricación)"
msgid "Delete"
msgstr "Eliminar"
+#. placeholder {0}: view.name
+msgid "Delete {0}"
+msgstr "Eliminar {0}"
+
msgid "Delete {name}"
msgstr "Eliminar {name}"
@@ -4138,6 +4208,9 @@ msgstr "Eliminar Tipo"
msgid "Delete Unit of Measure"
msgstr "Eliminar unidad de medida"
+msgid "Delete view"
+msgstr "Eliminar vista"
+
msgid "Delete View"
msgstr "Eliminar Vista"
@@ -5241,6 +5314,9 @@ msgstr "No se pudo canjear el código de autorización por un token de acceso. V
msgid "Excluded"
msgstr "Excluido"
+msgid "Executive P&L"
+msgstr "Estado de Resultados Ejecutivo"
+
msgid "Exemption Certificate"
msgstr "Certificado de Exención"
@@ -5311,6 +5387,9 @@ msgstr "Lado de gastos de los movimientos de impuestos diferidos (emparejado con
msgid "Expense side of deferred tax movements (paired with deferred tax liability)."
msgstr "Error al crear la clase de activo: {0}"
+msgid "Expenses"
+msgstr "Gastos"
+
msgid "Expert guidance"
msgstr "Orientación experta"
@@ -5803,6 +5882,9 @@ msgstr "Finalizar"
msgid "Finalizing a fiscal month through the Open → Locked → Closed lifecycle; a closed period is frozen and its balances snapshotted, reversible only by explicit reopen."
msgstr "Finalizar un mes fiscal a través del ciclo de vida Abierto → Bloqueado → Cerrado; un período cerrado se congela y sus saldos se capturan, reversibles solo mediante reapertura explícita."
+msgid "Financial Statements"
+msgstr "Estados Financieros"
+
msgid "finish"
msgstr "Productos terminados"
@@ -6263,9 +6345,15 @@ msgstr "grados"
msgid "Grades"
msgstr "Grados"
+msgid "Gross Profit"
+msgstr "Ganancia Bruta"
+
msgid "Group"
msgstr "Grupo"
+msgid "Group by"
+msgstr "Agrupar por"
+
msgid "Group Members"
msgstr "Miembros del Grupo"
@@ -6621,6 +6709,9 @@ msgstr "Ingreso / Balance (heredado)"
msgid "Income Statement"
msgstr "Estado de Resultados"
+msgid "Income Tax"
+msgstr "Impuesto a la Renta"
+
msgid "Income/Balance"
msgstr "Ingresos/Saldo"
@@ -7166,6 +7257,9 @@ msgstr "Unidad de Trabajo"
msgid "Language"
msgstr "Idioma"
+msgid "Last 6 Months"
+msgstr "Últimos 6 Meses"
+
msgid "Last Calibration"
msgstr "Última Calibración"
@@ -7962,6 +8056,9 @@ msgstr "Dinero que te deben"
msgid "Money you owe"
msgstr "Dinero que debes"
+msgid "Monthly"
+msgstr "Mensual"
+
msgid "Months over which this asset depreciates for tax purposes (when not using MACRS)."
msgstr "Meses durante los cuales este activo se deprecia para propósitos fiscales (cuando no se utiliza MACRS)."
@@ -8075,6 +8172,9 @@ msgstr "Valor Neto en Libros"
msgid "Net Change"
msgstr "Cambio Neto"
+msgid "Net Income"
+msgstr "Ingreso Neto"
+
msgid "Never"
msgstr "Nunca"
@@ -8567,6 +8667,9 @@ msgstr "Sin artículos"
msgid "No items have inventory activity here yet."
msgstr "Aún no hay actividad de inventario de artículos aquí."
+msgid "No journal lines in scope for this period"
+msgstr "Sin líneas de diario en alcance para este período"
+
msgid "No lines to map"
msgstr "Sin líneas para mapear"
@@ -8666,6 +8769,9 @@ msgstr "Ningún proceso seleccionado"
msgid "No production events recorded for this operation yet"
msgstr "Aún no se han registrado eventos de producción para esta operación"
+msgid "No purchases in this period"
+msgstr "Sin compras en este período"
+
msgid "No Quote"
msgstr "Sin Cotización"
@@ -8684,6 +8790,9 @@ msgstr "Sin imagen de referencia"
msgid "No remaining entities to inspect."
msgstr "No hay entidades restantes para inspeccionar."
+msgid "No reports match your search."
+msgstr "Ningún reporte coincide con su búsqueda."
+
msgid "No results"
msgstr "Sin resultados"
@@ -8904,6 +9013,9 @@ msgstr "Piso de existencias a mantener para uso de servicio en esta ubicación"
msgid "On-hand inventory remains"
msgstr "El inventario disponible permanece"
+msgid "On-hand value by location or item, with GL tie-out"
+msgstr "Valor disponible por ubicación o artículo, con conciliación GL"
+
msgid "On-hand value of manufactured goods (Make items)"
msgstr "Valor disponible de bienes manufacturados (artículos Fabricar)"
@@ -9009,6 +9121,9 @@ msgstr "Trabajos abiertos"
msgid "Open menu"
msgstr "Abrir menú"
+msgid "Open payables by supplier and age"
+msgstr "Cuentas por pagar abiertas por proveedor y antigüedad"
+
msgid "Open Purchase Invoices"
msgstr "Facturas de Compra Abiertas"
@@ -9024,6 +9139,9 @@ msgstr "Presupuestos Abiertos"
msgid "Open Reactive"
msgstr "Reactivo Abierto"
+msgid "Open receivables by customer and age"
+msgstr "Cuentas por cobrar abiertas por cliente y antigüedad"
+
msgid "Open RFQs"
msgstr "RFQs Abiertos"
@@ -9057,6 +9175,9 @@ msgstr "Saldo de apertura de la depreciación ya contabilizada antes de que este
msgid "Operating Expenses"
msgstr "Gastos Operativos"
+msgid "Operating Income"
+msgstr "Ingreso Operativo"
+
msgid "Operation"
msgstr "Operación"
@@ -9172,6 +9293,12 @@ msgstr "Original"
msgid "Original Count"
msgstr "Conteo Original"
+msgid "Other Expense"
+msgstr "Otro Gasto"
+
+msgid "Other Income"
+msgstr "Otro Ingreso"
+
msgid "Other Income account for FX gains when a payment settles a foreign-currency invoice at a more favorable rate"
msgstr "Cuenta de Otros Ingresos para ganancias de divisas cuando un pago liquida una factura en moneda extranjera a una tasa más favorable"
@@ -9557,6 +9684,11 @@ msgstr "Piezas/Minuto"
msgid "Pin"
msgstr "Anclar"
+#. placeholder {0}: report.name
+#. placeholder {0}: view.name
+msgid "Pin {0}"
+msgstr "Fijar {0}"
+
msgid "Pinned"
msgstr "Fijado"
@@ -10083,6 +10215,9 @@ msgstr "Unidad de Compra:"
msgid "Purchased"
msgstr "Comprado"
+msgid "Purchases"
+msgstr "Compras"
+
msgid "purchasing"
msgstr "Compras y Costo de Bienes Vendidos"
@@ -10211,6 +10346,9 @@ msgstr "Niveles de precios basados en cantidad para esta anulación; el precio u
msgid "Quantity: {0}"
msgstr "Cantidad: {0}"
+msgid "Quarterly"
+msgstr "Trimestral"
+
msgid "Question"
msgstr "Pregunta"
@@ -10678,6 +10816,9 @@ msgstr "Sistema de Reabastecimiento"
msgid "Report"
msgstr "Informe"
+msgid "Reporting"
+msgstr "Reportes"
+
msgid "Reporting dimension"
msgstr "Dimensión de informe"
@@ -10687,6 +10828,9 @@ msgstr "Informes"
msgid "Reprint"
msgstr "Reimprimir"
+msgid "Request access"
+msgstr "Solicitar acceso"
+
msgid "Request Approval"
msgstr "Solicitar Aprobación"
@@ -10821,6 +10965,12 @@ msgstr "Devolviendo material recogido no utilizado"
msgid "Rev {revision}"
msgstr "Rev {revision}"
+msgid "Revenue"
+msgstr "Ingresos"
+
+msgid "Revenue and expenses over a period"
+msgstr "Ingresos y gastos durante un período"
+
msgid "Reverse all inventory adjustments"
msgstr "Revertir todos los ajustes de inventario"
@@ -11153,9 +11303,15 @@ msgstr "Guardar contactos"
msgid "Save Method"
msgstr "Guardar Método"
+msgid "Save view"
+msgstr "Guardar vista"
+
msgid "Save View"
msgstr "Guardar Vista"
+msgid "Saved Views"
+msgstr "Vistas Guardadas"
+
msgid "Saving..."
msgstr "Guardando..."
@@ -11868,6 +12024,15 @@ msgstr "Mostrar opciones de sincronización"
msgid "Showing {0} of {totalCount} — refine your search"
msgstr "Mostrando {0} de {totalCount} — refine su búsqueda"
+msgid "Showing in {parentCurrency}"
+msgstr "Mostrando en {parentCurrency}"
+
+msgid "Showing the first 500 lines"
+msgstr "Mostrando las primeras 500 líneas"
+
+msgid "Showing the top 1,000 groups by amount"
+msgstr "Mostrando los 1,000 grupos principales por cantidad"
+
msgid "Shown as a faint background behind every page of generated PDFs"
msgstr "Se muestra como un fondo tenue detrás de cada página de los PDF generados"
@@ -11937,6 +12102,15 @@ msgstr "Omitido"
msgid "Slack"
msgstr "Slack"
+msgid "Slice asset activity by location, item, or any dimension"
+msgstr "Dividir actividad de activos por ubicación, artículo o cualquier dimensión"
+
+msgid "Slice expenses by location, cost center, or any dimension"
+msgstr "Dividir gastos por ubicación, centro de costos o cualquier dimensión"
+
+msgid "Slice revenue by customer, customer type, or any dimension"
+msgstr "Dividir ingresos por cliente, tipo de cliente o cualquier dimensión"
+
msgid "Smoke-test the core daily flows end to end"
msgstr "Prueba de humo de los flujos diarios principales de principio a fin"
@@ -12018,6 +12192,9 @@ msgstr "Clientes Específicos"
msgid "Specific Items"
msgstr "Artículos Específicos"
+msgid "Spend by supplier, item, or category — your biggest cost drivers"
+msgstr "Gasto por proveedor, artículo o categoría — sus mayores generadores de costos"
+
msgid "Split"
msgstr "Dividir"
@@ -13343,6 +13520,9 @@ msgstr "Tema"
msgid "Theme Color"
msgstr "Color de tema"
+msgid "Then by"
+msgstr "Luego por"
+
msgid "There are no active supplier quotes to compare for this RFQ."
msgstr "No hay presupuestos de proveedores activos para comparar en esta solicitud de cotización."
@@ -13585,6 +13765,9 @@ msgstr "Zona horaria"
msgid "Title"
msgstr "Título"
+msgid "To Date"
+msgstr "Hasta la Fecha"
+
msgid "To deactivate, use the row menu and choose Deactivate Account."
msgstr "Para desactivar, utilice el menú de la fila y seleccione Desactivar cuenta."
@@ -13976,6 +14159,11 @@ msgstr "Desmarcar"
msgid "Unpick {0}"
msgstr "Descartar {0}"
+#. placeholder {0}: report.name
+#. placeholder {0}: view.name
+msgid "Unpin {0}"
+msgstr "Desfijar {0}"
+
msgid "Unposted Documents"
msgstr "Documentos No Contabilizados"
@@ -14225,9 +14413,6 @@ msgstr "Validado"
msgid "Validating job..."
msgstr "Validando trabajo..."
-msgid "Valuation"
-msgstr "Valoración"
-
msgid "Value"
msgstr "Valor"
@@ -14653,6 +14838,9 @@ msgstr "Qué cambia cuando te pasas a Carbon y aproximadamente cuánto vale. Est
msgid "What data"
msgstr "Qué datos"
+msgid "What drove inventory up or down, by any dimension"
+msgstr "Qué impulsó el inventario hacia arriba o hacia abajo, por cualquier dimensión"
+
msgid "What is {translatedTerm}?"
msgstr "¿Qué es {translatedTerm}?"
@@ -15049,6 +15237,9 @@ msgstr "Reducir el valor de un activo a lo largo de su vida útil — un lote me
msgid "Year"
msgstr "Año"
+msgid "Yearly"
+msgstr "Anual"
+
msgid "Yes"
msgstr "Sí"
diff --git a/packages/locale/locales/fr/erp.po b/packages/locale/locales/fr/erp.po
index 8290882ee2..fb57a6d40c 100644
--- a/packages/locale/locales/fr/erp.po
+++ b/packages/locale/locales/fr/erp.po
@@ -48,6 +48,10 @@ msgstr "(exclu pour ce client)"
msgid "{0, plural, one {This part is on 1 open change notice} other {This part is on # open change notices}}"
msgstr "{0, plural, one {Cette pièce est sur 1 avis de modification ouvert} other {Cette pièce est sur # avis de modification ouverts}}"
+#. placeholder {0}: selectedAccountIds.length
+msgid "{0} accounts"
+msgstr "{0} comptes"
+
#. placeholder {0}: precise?.text
msgid "{0} ago"
msgstr "{0} il y a"
@@ -163,6 +167,9 @@ msgstr "{years}an"
msgid "/month/user"
msgstr "/mois/utilisateur"
+msgid "% of total"
+msgstr "% du total"
+
msgid "% of Total"
msgstr "% du Total"
@@ -474,6 +481,9 @@ msgstr "Compte"
msgid "Account & Details"
msgstr "Compte et détails"
+msgid "Account balances with debits and credits"
+msgstr "Soldes des comptes avec débits et crédits"
+
msgid "Account for advance payments made before goods or services are received"
msgstr "Comptabilisez les paiements anticipés effectués avant la réception de biens ou de services."
@@ -510,9 +520,15 @@ msgstr "comptabilité"
msgid "Accounting"
msgstr "Comptabilité"
+msgid "Accounting is currently in beta. Request access to enable reporting, journal entries, accounting periods, fixed assets, and more."
+msgstr "La comptabilité est actuellement en version bêta. Demandez l'accès pour activer les rapports, les écritures de journal, les périodes comptables, les immobilisations et bien plus."
+
msgid "Accounting is disabled"
msgstr "La comptabilité est désactivée"
+msgid "Accounting is disabled for this company."
+msgstr "La comptabilité est désactivée pour cette entreprise."
+
msgid "Accounting is enabled"
msgstr "La comptabilité est activée"
@@ -853,6 +869,9 @@ msgstr "Après"
msgid "After (calculation method)"
msgstr "Après (méthode de calcul)"
+msgid "Aging"
+msgstr "Vieillissement"
+
msgid "Agree on the scope"
msgstr "Convenir sur la portée"
@@ -871,6 +890,9 @@ msgstr "Tous"
msgid "All {total} phases are done. Nice work — your team is up and running."
msgstr "Toutes les {total} phases sont terminées. Bravo — votre équipe est opérationnelle."
+msgid "All accounts"
+msgstr "Tous les comptes"
+
msgid "All actions selected"
msgstr "Toutes les actions sélectionnées"
@@ -983,6 +1005,9 @@ msgstr "La position d'une opération dans la file d'attente de son centre de tra
msgid "An unexpected error occurred while connecting to Onshape. Try connecting again."
msgstr "Une erreur inattendue s'est produite lors de la connexion à Onshape. Réessayez de vous connecter."
+msgid "Analytics"
+msgstr "Analyse"
+
msgid "Anchors the Plan timeline to real dates. Leave blank for a relative, week-numbered timeline. Setting either one fills in the rest."
msgstr "Ancre la chronologie du Plan sur des dates réelles. Laissez vide pour une chronologie relative numérotée par semaines. Définir l'une ou l'autre remplit le reste."
@@ -1026,6 +1051,9 @@ msgstr "Tout type d'article"
msgid "Anything not explicitly listed in scope above"
msgstr "Tout ce qui n'est pas explicitement listé dans le périmètre ci-dessus"
+msgid "AP Aging"
+msgstr "Analyse AP"
+
msgid "AP Clerk"
msgstr "Commis aux comptes créditeurs"
@@ -1138,6 +1166,9 @@ msgstr "AQL"
msgid "AQL (Z1.4 / ISO 2859-1)"
msgstr "NQA (Z1.4 / ISO 2859-1)"
+msgid "AR Aging"
+msgstr "Analyse AR"
+
msgid "AR Clerk"
msgstr "Commis aux comptes clients"
@@ -1245,6 +1276,11 @@ msgstr "Êtes-vous sûr de vouloir supprimer {0} ? Cette action ne peut pas êtr
msgid "Are you sure you want to delete {name}? This cannot be undone."
msgstr "Êtes-vous sûr de vouloir supprimer {name} ? Cette action ne peut pas être annulée."
+#. placeholder {0}: activeView.name
+#. placeholder {0}: viewPendingDelete.name
+msgid "Are you sure you want to delete the \"{0}\" view? This cannot be undone."
+msgstr "Êtes-vous sûr de vouloir supprimer la vue \"{0}\" ? Cette action ne peut pas être annulée."
+
#. placeholder {0}: selectedCustomField?.name
msgid "Are you sure you want to delete the {0} field?"
msgstr "Êtes-vous sûr de vouloir supprimer le champ {0} ?"
@@ -1634,6 +1670,9 @@ msgstr "ID d'actif"
msgid "Assets"
msgstr "Actifs"
+msgid "Assets, liabilities and equity as of a date"
+msgstr "Actifs, passifs et capitaux propres à une date"
+
msgid "Assign printers to locations. Shipping, receiving, and work centers inherit the location default unless overridden."
msgstr "Attribuez des imprimantes aux emplacements. L'expédition, la réception et les centres de travail héritent de la valeur par défaut de l'emplacement sauf s'ils sont remplacés."
@@ -1890,6 +1929,9 @@ msgstr "Sous stock de sécurité"
msgid "Beta"
msgstr "Bêta"
+msgid "Biggest causes of scrap by reason, item, or work center"
+msgstr "Principales causes de rebuts par raison, article ou centre de travail"
+
msgid "Bill of Material"
msgstr "Nomenclature"
@@ -2020,12 +2062,18 @@ msgstr "par {byUser}"
msgid "By accepting the invite, you agree to the <0>Terms of Service</0> and <1>Privacy Policy</1>."
msgstr "En acceptant l'invitation, vous acceptez les <0>Conditions d'utilisation</0> et la <1>Politique de confidentialité</1>."
+msgid "By dimension"
+msgstr "Par dimension"
+
msgid "By Document Date"
msgstr "Par date du document"
msgid "By Due Date"
msgstr "Par date d'échéance"
+msgid "By field"
+msgstr "Par champ"
+
msgid "By Item"
msgstr "Par Article"
@@ -2383,6 +2431,9 @@ msgstr "Effacer la recherche"
msgid "Clear search query"
msgstr "Effacer la requête de recherche"
+msgid "Clear selection"
+msgstr "Effacer la sélection"
+
msgid "Clear this invoice with the party's posted credits as well as cash. Credits apply directly — no posting needed."
msgstr "Réglez cette facture avec les crédits comptabilisés de la partie ainsi qu'en espèces. Les crédits s'appliquent directement — aucune comptabilisation nécessaire."
@@ -2416,6 +2467,9 @@ msgstr "Date de fermeture"
msgid "Close Period"
msgstr "Fermer la période"
+msgid "Close Reports"
+msgstr "Fermer les rapports"
+
msgid "Close Status"
msgstr "État de fermeture"
@@ -2464,6 +2518,12 @@ msgstr "Réduire la configuration"
msgid "Collapse subtree"
msgstr "Réduire le sous-arbre"
+msgid "Column dimension"
+msgstr "Dimension de colonne"
+
+msgid "Column field"
+msgstr "Champ de colonne"
+
msgid "Column visibility and order"
msgstr "Visibilité et ordre des colonnes"
@@ -2560,6 +2620,9 @@ msgstr "Code-barres d'achèvement"
msgid "Completion Time"
msgstr "Temps d'exécution"
+msgid "Condensed P&L with margins and key subtotals"
+msgstr "Compte de résultat condensé avec marges et sous-totaux clés"
+
msgid "Conditions"
msgstr "Conditions"
@@ -3041,6 +3104,9 @@ msgstr "Coût des marchandises vendues (COGS)"
msgid "Cost of Goods Sold (default)"
msgstr "Coût des Marchandises Vendues (par défaut)"
+msgid "Cost of Sales"
+msgstr "Coût des ventes"
+
msgid "Costing"
msgstr "Calcul des coûts"
@@ -3852,6 +3918,10 @@ msgstr "Définir les nomenclatures multi-niveaux et la gamme de fabrication (mé
msgid "Delete"
msgstr "Supprimer"
+#. placeholder {0}: view.name
+msgid "Delete {0}"
+msgstr "Supprimer {0}"
+
msgid "Delete {name}"
msgstr "Supprimer {name}"
@@ -4138,6 +4208,9 @@ msgstr "Supprimer le type"
msgid "Delete Unit of Measure"
msgstr "Supprimer l'unité de mesure"
+msgid "Delete view"
+msgstr "Supprimer la vue"
+
msgid "Delete View"
msgstr "Supprimer la vue"
@@ -5241,6 +5314,9 @@ msgstr "L'échange du code d'autorisation contre un jeton d'accès a échoué. R
msgid "Excluded"
msgstr "Exclu"
+msgid "Executive P&L"
+msgstr "Compte de résultat exécutif"
+
msgid "Exemption Certificate"
msgstr "Certificat d'Exonération"
@@ -5311,6 +5387,9 @@ msgstr "Côté charges des mouvements d'impôt différé (appairé avec passif d
msgid "Expense side of deferred tax movements (paired with deferred tax liability)."
msgstr "Échec de la création de la classe d'actif : {0}"
+msgid "Expenses"
+msgstr "Dépenses"
+
msgid "Expert guidance"
msgstr "Conseils d'experts"
@@ -5803,6 +5882,9 @@ msgstr "Finaliser"
msgid "Finalizing a fiscal month through the Open → Locked → Closed lifecycle; a closed period is frozen and its balances snapshotted, reversible only by explicit reopen."
msgstr "Finalisation d'un mois fiscal via le cycle de vie Ouvert → Verrouillé → Fermé ; une période fermée est gelée et ses soldes sont capturés, réversible uniquement par une réouverture explicite."
+msgid "Financial Statements"
+msgstr "États financiers"
+
msgid "finish"
msgstr "Produits finis"
@@ -6263,9 +6345,15 @@ msgstr "grades"
msgid "Grades"
msgstr "Grades"
+msgid "Gross Profit"
+msgstr "Bénéfice brut"
+
msgid "Group"
msgstr "Groupe"
+msgid "Group by"
+msgstr "Grouper par"
+
msgid "Group Members"
msgstr "Membres du groupe"
@@ -6621,6 +6709,9 @@ msgstr "Revenu / Bilan (hérité)"
msgid "Income Statement"
msgstr "Compte de résultat"
+msgid "Income Tax"
+msgstr "Impôt sur le revenu"
+
msgid "Income/Balance"
msgstr "Revenu/Solde"
@@ -7166,6 +7257,9 @@ msgstr "Unité de travail"
msgid "Language"
msgstr "Langue"
+msgid "Last 6 Months"
+msgstr "6 derniers mois"
+
msgid "Last Calibration"
msgstr "Dernier étalonnage"
@@ -7962,6 +8056,9 @@ msgstr "Argent qui vous est dû"
msgid "Money you owe"
msgstr "L'argent que vous devez"
+msgid "Monthly"
+msgstr "Mensuel"
+
msgid "Months over which this asset depreciates for tax purposes (when not using MACRS)."
msgstr "Mois sur lesquels cet actif est amorti à des fins fiscales (si MACRS n'est pas utilisé)."
@@ -8075,6 +8172,9 @@ msgstr "Valeur nette comptable"
msgid "Net Change"
msgstr "Variation nette"
+msgid "Net Income"
+msgstr "Revenu net"
+
msgid "Never"
msgstr "Jamais"
@@ -8567,6 +8667,9 @@ msgstr "Aucun article"
msgid "No items have inventory activity here yet."
msgstr "Aucun article n'a encore d'activité d'inventaire ici."
+msgid "No journal lines in scope for this period"
+msgstr "Aucune ligne de journal dans le cadre pour cette période"
+
msgid "No lines to map"
msgstr "Aucune ligne à mapper"
@@ -8666,6 +8769,9 @@ msgstr "Aucun processus sélectionné"
msgid "No production events recorded for this operation yet"
msgstr "Aucun événement de production n'a encore été enregistré pour cette opération"
+msgid "No purchases in this period"
+msgstr "Aucun achat dans cette période"
+
msgid "No Quote"
msgstr "Pas de devis"
@@ -8684,6 +8790,9 @@ msgstr "Pas d'image de référence"
msgid "No remaining entities to inspect."
msgstr "Aucune entité restante à inspecter."
+msgid "No reports match your search."
+msgstr "Aucun rapport ne correspond à votre recherche."
+
msgid "No results"
msgstr "Aucun résultat"
@@ -8904,6 +9013,9 @@ msgstr "Plancher disponible à maintenir pour utilisation en service à cet empl
msgid "On-hand inventory remains"
msgstr "Stock en main disponible"
+msgid "On-hand value by location or item, with GL tie-out"
+msgstr "Valeur disponible par localisation ou article, avec rapprochement GL"
+
msgid "On-hand value of manufactured goods (Make items)"
msgstr "Valeur en stock des marchandises manufacturées (Articles Fabriquer)"
@@ -9009,6 +9121,9 @@ msgstr "Travaux en cours"
msgid "Open menu"
msgstr "Ouvrir le menu"
+msgid "Open payables by supplier and age"
+msgstr "Comptes créditeurs ouverts par fournisseur et ancienneté"
+
msgid "Open Purchase Invoices"
msgstr "Factures d'achat ouvertes"
@@ -9024,6 +9139,9 @@ msgstr "Devis Ouverts"
msgid "Open Reactive"
msgstr "Réactif Ouvert"
+msgid "Open receivables by customer and age"
+msgstr "Comptes clients ouverts par client et ancienneté"
+
msgid "Open RFQs"
msgstr "RFQ ouvertes"
@@ -9057,6 +9175,9 @@ msgstr "Solde d'ouverture de l'amortissement déjà comptabilisé avant l'ajout
msgid "Operating Expenses"
msgstr "Frais de Fonctionnement"
+msgid "Operating Income"
+msgstr "Revenu d'exploitation"
+
msgid "Operation"
msgstr "Opération"
@@ -9172,6 +9293,12 @@ msgstr "Original"
msgid "Original Count"
msgstr "Comptage initial"
+msgid "Other Expense"
+msgstr "Autre charge"
+
+msgid "Other Income"
+msgstr "Autre revenu"
+
msgid "Other Income account for FX gains when a payment settles a foreign-currency invoice at a more favorable rate"
msgstr "Compte de revenus divers pour les gains de change lorsqu'un paiement règle une facture en devise étrangère à un taux plus favorable"
@@ -9557,6 +9684,11 @@ msgstr "Pièces/Minute"
msgid "Pin"
msgstr "Épingler"
+#. placeholder {0}: report.name
+#. placeholder {0}: view.name
+msgid "Pin {0}"
+msgstr "Épingler {0}"
+
msgid "Pinned"
msgstr "Épinglé"
@@ -10083,6 +10215,9 @@ msgstr "Unité d'achat :"
msgid "Purchased"
msgstr "Acheté"
+msgid "Purchases"
+msgstr "Achats"
+
msgid "purchasing"
msgstr "Approvisionnement et Coût des Biens Vendus"
@@ -10211,6 +10346,9 @@ msgstr "Niveaux de tarification basés sur la quantité pour ce remplacement; le
msgid "Quantity: {0}"
msgstr "Quantité : {0}"
+msgid "Quarterly"
+msgstr "Trimestriel"
+
msgid "Question"
msgstr "Question"
@@ -10678,6 +10816,9 @@ msgstr "Système de réapprovisionnement"
msgid "Report"
msgstr "Rapport"
+msgid "Reporting"
+msgstr "Rapports"
+
msgid "Reporting dimension"
msgstr "Dimension de rapports"
@@ -10687,6 +10828,9 @@ msgstr "Rapports"
msgid "Reprint"
msgstr "Réimprimer"
+msgid "Request access"
+msgstr "Demander l'accès"
+
msgid "Request Approval"
msgstr "Demander l'approbation"
@@ -10821,6 +10965,12 @@ msgstr "Retour du matériel prélevé inutilisé"
msgid "Rev {revision}"
msgstr "Rév {revision}"
+msgid "Revenue"
+msgstr "Revenu"
+
+msgid "Revenue and expenses over a period"
+msgstr "Revenus et dépenses au cours d'une période"
+
msgid "Reverse all inventory adjustments"
msgstr "Inverser tous les ajustements d'inventaire"
@@ -11153,9 +11303,15 @@ msgstr "Enregistrer les contacts"
msgid "Save Method"
msgstr "Enregistrer la méthode"
+msgid "Save view"
+msgstr "Enregistrer la vue"
+
msgid "Save View"
msgstr "Enregistrer la vue"
+msgid "Saved Views"
+msgstr "Vues enregistrées"
+
msgid "Saving..."
msgstr "Enregistrement..."
@@ -11868,6 +12024,15 @@ msgstr "Afficher les options de synchronisation"
msgid "Showing {0} of {totalCount} — refine your search"
msgstr "Affichage de {0} sur {totalCount} — affinez votre recherche"
+msgid "Showing in {parentCurrency}"
+msgstr "Affichage en {parentCurrency}"
+
+msgid "Showing the first 500 lines"
+msgstr "Affichage des 500 premières lignes"
+
+msgid "Showing the top 1,000 groups by amount"
+msgstr "Affichage des 1 000 meilleurs groupes par montant"
+
msgid "Shown as a faint background behind every page of generated PDFs"
msgstr "Affiché en arrière-plan discret sur chaque page des PDF générés"
@@ -11937,6 +12102,15 @@ msgstr "Ignoré"
msgid "Slack"
msgstr "Slack"
+msgid "Slice asset activity by location, item, or any dimension"
+msgstr "Segmenter l'activité des actifs par lieu, article ou toute dimension"
+
+msgid "Slice expenses by location, cost center, or any dimension"
+msgstr "Segmenter les dépenses par lieu, centre de coûts ou toute dimension"
+
+msgid "Slice revenue by customer, customer type, or any dimension"
+msgstr "Ventiler le chiffre d'affaires par client, type de client ou toute dimension"
+
msgid "Smoke-test the core daily flows end to end"
msgstr "Tester les flux quotidiens principaux de bout en bout"
@@ -12018,6 +12192,9 @@ msgstr "Clients spécifiques"
msgid "Specific Items"
msgstr "Articles spécifiques"
+msgid "Spend by supplier, item, or category — your biggest cost drivers"
+msgstr "Dépenses par fournisseur, article ou catégorie — vos principaux moteurs de coûts"
+
msgid "Split"
msgstr "Diviser"
@@ -13343,6 +13520,9 @@ msgstr "Thème"
msgid "Theme Color"
msgstr "Couleur du thème"
+msgid "Then by"
+msgstr "Puis par"
+
msgid "There are no active supplier quotes to compare for this RFQ."
msgstr "Il n'y a pas de devis fournisseurs actifs à comparer pour cette demande de prix."
@@ -13585,6 +13765,9 @@ msgstr "Fuseau horaire"
msgid "Title"
msgstr "Titre"
+msgid "To Date"
+msgstr "À la date"
+
msgid "To deactivate, use the row menu and choose Deactivate Account."
msgstr "Pour désactiver, utilisez le menu de ligne et choisissez Désactiver le compte."
@@ -13976,6 +14159,11 @@ msgstr "Dépicker"
msgid "Unpick {0}"
msgstr "Dépicker {0}"
+#. placeholder {0}: report.name
+#. placeholder {0}: view.name
+msgid "Unpin {0}"
+msgstr "Dépingler {0}"
+
msgid "Unposted Documents"
msgstr "Documents non comptabilisés"
@@ -14225,9 +14413,6 @@ msgstr "Validé"
msgid "Validating job..."
msgstr "Validation du travail en cours..."
-msgid "Valuation"
-msgstr "Évaluation"
-
msgid "Value"
msgstr "Valeur"
@@ -14653,6 +14838,9 @@ msgstr "Ce qui change quand vous passez à Carbon, et à peu près ce que cela v
msgid "What data"
msgstr "Quelles données"
+msgid "What drove inventory up or down, by any dimension"
+msgstr "Ce qui a poussé l'inventaire à la hausse ou à la baisse, par toute dimension"
+
msgid "What is {translatedTerm}?"
msgstr "Qu'est-ce que {translatedTerm} ?"
@@ -15049,6 +15237,9 @@ msgstr "Réduire la valeur d'un actif au cours de sa vie utile — un lot mensue
msgid "Year"
msgstr "Année"
+msgid "Yearly"
+msgstr "Annuel"
+
msgid "Yes"
msgstr "Oui"
diff --git a/packages/locale/locales/hi/erp.po b/packages/locale/locales/hi/erp.po
index eb17cd60cd..78b99f04ff 100644
--- a/packages/locale/locales/hi/erp.po
+++ b/packages/locale/locales/hi/erp.po
@@ -48,6 +48,10 @@ msgstr "(इस ग्राहक के लिए बाहर रखा ग
msgid "{0, plural, one {This part is on 1 open change notice} other {This part is on # open change notices}}"
msgstr "{0, plural, one {यह भाग 1 खुली परिवर्तन सूचना पर है} other {यह भाग # खुली परिवर्तन सूचनाओं पर है}}"
+#. placeholder {0}: selectedAccountIds.length
+msgid "{0} accounts"
+msgstr "{0} खाते"
+
#. placeholder {0}: precise?.text
msgid "{0} ago"
msgstr "{0} पहले"
@@ -163,6 +167,9 @@ msgstr "{years}वर्ष"
msgid "/month/user"
msgstr "/माह/उपयोगकर्ता"
+msgid "% of total"
+msgstr "कुल का %"
+
msgid "% of Total"
msgstr "कुल का %"
@@ -474,6 +481,9 @@ msgstr "खाता"
msgid "Account & Details"
msgstr "खाता और विवरण"
+msgid "Account balances with debits and credits"
+msgstr "डेबिट और क्रेडिट के साथ खाता शेष"
+
msgid "Account for advance payments made before goods or services are received"
msgstr "माल या सेवाएं प्राप्त होने से पहले किए गए अग्रिम भुगतान के लिए खाता।"
@@ -510,9 +520,15 @@ msgstr "लेखांकन"
msgid "Accounting"
msgstr "लेखांकन"
+msgid "Accounting is currently in beta. Request access to enable reporting, journal entries, accounting periods, fixed assets, and more."
+msgstr "लेखांकन वर्तमान में बीटा में है। रिपोर्टिंग, जर्नल प्रविष्टियां, लेखांकन अवधि, अचल संपत्ति और अन्य सक्षम करने के लिए प्रवेश का अनुरोध करें।"
+
msgid "Accounting is disabled"
msgstr "लेखांकन अक्षम है"
+msgid "Accounting is disabled for this company."
+msgstr "इस कंपनी के लिए लेखांकन अक्षम है।"
+
msgid "Accounting is enabled"
msgstr "लेखांकन सक्षम है"
@@ -853,6 +869,9 @@ msgstr "के बाद"
msgid "After (calculation method)"
msgstr "बाद में (गणना विधि)"
+msgid "Aging"
+msgstr "उम्र"
+
msgid "Agree on the scope"
msgstr "दायरे पर सहमति दें"
@@ -871,6 +890,9 @@ msgstr "सभी"
msgid "All {total} phases are done. Nice work — your team is up and running."
msgstr "सभी {total} चरण पूरे हो गए। शानदार काम — आपकी टीम चल रही है।"
+msgid "All accounts"
+msgstr "सभी खाते"
+
msgid "All actions selected"
msgstr "सभी कार्य चयनित"
@@ -983,6 +1005,9 @@ msgstr "एक ऑपरेशन की अपने कार्य कें
msgid "An unexpected error occurred while connecting to Onshape. Try connecting again."
msgstr "Onshape से कनेक्ट करते समय एक अनपेक्षित त्रुटि हुई। दोबारा कनेक्ट करने का प्रयास करें।"
+msgid "Analytics"
+msgstr "विश्लेषण"
+
msgid "Anchors the Plan timeline to real dates. Leave blank for a relative, week-numbered timeline. Setting either one fills in the rest."
msgstr "योजना समयरेखा को वास्तविक तारीखों से जोड़ता है। सापेक्ष, सप्ताह-संख्या वाली समयरेखा के लिए खाली छोड़ें। किसी एक को सेट करने से बाकी भर जाता है।"
@@ -1026,6 +1051,9 @@ msgstr "किसी भी आइटम प्रकार"
msgid "Anything not explicitly listed in scope above"
msgstr "स्कोप में ऊपर स्पष्ट रूप से सूचीबद्ध कुछ भी नहीं"
+msgid "AP Aging"
+msgstr "AP एजिंग"
+
msgid "AP Clerk"
msgstr "AP क्लर्क"
@@ -1138,6 +1166,9 @@ msgstr "AQL"
msgid "AQL (Z1.4 / ISO 2859-1)"
msgstr "AQL (Z1.4 / ISO 2859-1)"
+msgid "AR Aging"
+msgstr "AR एजिंग"
+
msgid "AR Clerk"
msgstr "AR क्लर्क"
@@ -1245,6 +1276,11 @@ msgstr "क्या आप सुनिश्चित हैं कि आप
msgid "Are you sure you want to delete {name}? This cannot be undone."
msgstr "क्या आप सुनिश्चित हैं कि आप {name} को हटाना चाहते हैं? यह पूर्ववत नहीं किया जा सकता।"
+#. placeholder {0}: activeView.name
+#. placeholder {0}: viewPendingDelete.name
+msgid "Are you sure you want to delete the \"{0}\" view? This cannot be undone."
+msgstr "क्या आप सुनिश्चित हैं कि आप \"{0}\" दृश्य को हटाना चाहते हैं? इसे पूर्ववत नहीं किया जा सकता।"
+
#. placeholder {0}: selectedCustomField?.name
msgid "Are you sure you want to delete the {0} field?"
msgstr "क्या आप सुनिश्चित हैं कि आप {0} फ़ील्ड को हटाना चाहते हैं?"
@@ -1634,6 +1670,9 @@ msgstr "परिसंपत्ति ID"
msgid "Assets"
msgstr "संपत्तियां"
+msgid "Assets, liabilities and equity as of a date"
+msgstr "एक तारीख तक संपत्ति, देनदारियां और इक्विटी"
+
msgid "Assign printers to locations. Shipping, receiving, and work centers inherit the location default unless overridden."
msgstr "प्रिंटर को स्थानों को असाइन करें। शिपिंग, रिसीविंग और वर्क सेंटर स्थान डिफ़ॉल्ट को विरासत में लेते हैं जब तक कि ओवरराइड न किया जाए।"
@@ -1890,6 +1929,9 @@ msgstr "सुरक्षा स्टॉक से नीचे"
msgid "Beta"
msgstr "बीटा"
+msgid "Biggest causes of scrap by reason, item, or work center"
+msgstr "कारण, आइटम, या कार्य केंद्र द्वारा स्क्रैप के सबसे बड़े कारण"
+
msgid "Bill of Material"
msgstr "सामग्री की बिल"
@@ -2020,12 +2062,18 @@ msgstr "द्वारा {byUser}"
msgid "By accepting the invite, you agree to the <0>Terms of Service</0> and <1>Privacy Policy</1>."
msgstr "आमंत्रण स्वीकार करके, आप <0>सेवा की शर्तें</0> और <1>गोपनीयता नीति</1> से सहमत हैं।"
+msgid "By dimension"
+msgstr "आयाम द्वारा"
+
msgid "By Document Date"
msgstr "दस्तावेज़ तारीख के अनुसार"
msgid "By Due Date"
msgstr "देय तारीख के अनुसार"
+msgid "By field"
+msgstr "क्षेत्र द्वारा"
+
msgid "By Item"
msgstr "आइटम के अनुसार"
@@ -2383,6 +2431,9 @@ msgstr "खोज साफ़ करें"
msgid "Clear search query"
msgstr "खोज क्वेरी साफ़ करें"
+msgid "Clear selection"
+msgstr "चयन साफ करें"
+
msgid "Clear this invoice with the party's posted credits as well as cash. Credits apply directly — no posting needed."
msgstr "इस चालान को पार्टी के पोस्ट किए गए क्रेडिट के साथ-साथ नकद से साफ़ करें। क्रेडिट सीधे लागू होते हैं — कोई पोस्टिंग की आवश्यकता नहीं है।"
@@ -2416,6 +2467,9 @@ msgstr "बंद करने की तारीख"
msgid "Close Period"
msgstr "अवधि बंद करें"
+msgid "Close Reports"
+msgstr "रिपोर्ट बंद करें"
+
msgid "Close Status"
msgstr "स्थिति बंद करें"
@@ -2464,6 +2518,12 @@ msgstr "सेटअप को संक्षिप्त करें"
msgid "Collapse subtree"
msgstr "सबट्री को संक्षिप्त करें"
+msgid "Column dimension"
+msgstr "कॉलम आयाम"
+
+msgid "Column field"
+msgstr "कॉलम क्षेत्र"
+
msgid "Column visibility and order"
msgstr "कॉलम दृश्यता और क्रम"
@@ -2560,6 +2620,9 @@ msgstr "पूर्ण बारकोड"
msgid "Completion Time"
msgstr "पूर्ण होने का समय"
+msgid "Condensed P&L with margins and key subtotals"
+msgstr "मार्जिन और मुख्य उप-योग के साथ संक्षिप्त P&L"
+
msgid "Conditions"
msgstr "शर्तें"
@@ -3041,6 +3104,9 @@ msgstr "बेची गई वस्तुओं की लागत (COGS)"
msgid "Cost of Goods Sold (default)"
msgstr "बेची गई वस्तुओं की लागत (डिफ़ॉल्ट)"
+msgid "Cost of Sales"
+msgstr "बिक्री की लागत"
+
msgid "Costing"
msgstr "लागत"
@@ -3852,6 +3918,10 @@ msgstr "बहु-स्तरीय BOMs और Bill of Process (make methods)
msgid "Delete"
msgstr "हटाएं"
+#. placeholder {0}: view.name
+msgid "Delete {0}"
+msgstr "{0} हटाएं"
+
msgid "Delete {name}"
msgstr "{name} को हटाएं"
@@ -4138,6 +4208,9 @@ msgstr "प्रकार हटाएं"
msgid "Delete Unit of Measure"
msgstr "माप की इकाई हटाएं"
+msgid "Delete view"
+msgstr "दृश्य हटाएं"
+
msgid "Delete View"
msgstr "दृश्य हटाएं"
@@ -5241,6 +5314,9 @@ msgstr "प्राधिकरण कोड को एक्सेस टो
msgid "Excluded"
msgstr "बहिष्कृत"
+msgid "Executive P&L"
+msgstr "कार्यकारी P&L"
+
msgid "Exemption Certificate"
msgstr "छूट प्रमाणपत्र"
@@ -5311,6 +5387,9 @@ msgstr "स्थगित कर आंदोलन का व्यय पक
msgid "Expense side of deferred tax movements (paired with deferred tax liability)."
msgstr "संपत्ति वर्ग बनाने में विफल: {0}"
+msgid "Expenses"
+msgstr "खर्च"
+
msgid "Expert guidance"
msgstr "विशेषज्ञ मार्गदर्शन"
@@ -5803,6 +5882,9 @@ msgstr "अंतिम रूप दें"
msgid "Finalizing a fiscal month through the Open → Locked → Closed lifecycle; a closed period is frozen and its balances snapshotted, reversible only by explicit reopen."
msgstr "खुली → लॉक की गई → बंद जीवनचक्र के माध्यम से एक वित्तीय माह को अंतिम रूप देना; एक बंद अवधि जमी हुई है और इसके संतुलन को स्नैपशॉट किया गया है, केवल स्पष्ट पुनः खुलने से उलटा है।"
+msgid "Financial Statements"
+msgstr "वित्तीय विवरण"
+
msgid "finish"
msgstr "तैयार माल"
@@ -6263,9 +6345,15 @@ msgstr "ग्रेड"
msgid "Grades"
msgstr "ग्रेड"
+msgid "Gross Profit"
+msgstr "सकल लाभ"
+
msgid "Group"
msgstr "समूह"
+msgid "Group by"
+msgstr "द्वारा समूह"
+
msgid "Group Members"
msgstr "समूह सदस्य"
@@ -6621,6 +6709,9 @@ msgstr "आय / बैलेंस (विरासत में मिला)"
msgid "Income Statement"
msgstr "आय विवरण"
+msgid "Income Tax"
+msgstr "आयकर"
+
msgid "Income/Balance"
msgstr "आय/शेष"
@@ -7166,6 +7257,9 @@ msgstr "श्रम इकाई"
msgid "Language"
msgstr "भाषा"
+msgid "Last 6 Months"
+msgstr "पिछले 6 महीने"
+
msgid "Last Calibration"
msgstr "अंतिम अंशांकन"
@@ -7962,6 +8056,9 @@ msgstr "आपको देय धन"
msgid "Money you owe"
msgstr "आप जो पैसे देते हैं"
+msgid "Monthly"
+msgstr "मासिक"
+
msgid "Months over which this asset depreciates for tax purposes (when not using MACRS)."
msgstr "महीनों की संख्या जिसके दौरान यह संपत्ति कर उद्देश्यों के लिए मूल्यह्रास होती है (जब MACRS का उपयोग नहीं किया जा रहा है)।"
@@ -8075,6 +8172,9 @@ msgstr "नेट बुक वैल्यू"
msgid "Net Change"
msgstr "शुद्ध परिवर्तन"
+msgid "Net Income"
+msgstr "शुद्ध आय"
+
msgid "Never"
msgstr "कभी नहीं"
@@ -8567,6 +8667,9 @@ msgstr "कोई आइटम नहीं"
msgid "No items have inventory activity here yet."
msgstr "अभी तक यहाँ कोई आइटम इन्वेंटरी गतिविधि नहीं है।"
+msgid "No journal lines in scope for this period"
+msgstr "इस अवधि के लिए दायरे में कोई जर्नल लाइन नहीं"
+
msgid "No lines to map"
msgstr "मैप करने के लिए कोई लाइनें नहीं"
@@ -8666,6 +8769,9 @@ msgstr "कोई प्रक्रिया चयनित नहीं ह
msgid "No production events recorded for this operation yet"
msgstr "इस ऑपरेशन के लिए अभी तक कोई उत्पादन घटना रिकॉर्ड नहीं की गई है"
+msgid "No purchases in this period"
+msgstr "इस अवधि में कोई खरीद नहीं"
+
msgid "No Quote"
msgstr "कोई उद्धरण नहीं"
@@ -8684,6 +8790,9 @@ msgstr "कोई संदर्भ छवि नहीं"
msgid "No remaining entities to inspect."
msgstr "निरीक्षण के लिए कोई शेष इकाई नहीं है।"
+msgid "No reports match your search."
+msgstr "कोई रिपोर्ट आपकी खोज से मेल नहीं खाती।"
+
msgid "No results"
msgstr "कोई परिणाम नहीं"
@@ -8904,6 +9013,9 @@ msgstr "इस स्थान पर सेवा उपयोग के लि
msgid "On-hand inventory remains"
msgstr "हाथ में इन्वेंटरी बची है"
+msgid "On-hand value by location or item, with GL tie-out"
+msgstr "स्थान या आइटम के अनुसार हाथ में मूल्य, GL टाई-आउट के साथ"
+
msgid "On-hand value of manufactured goods (Make items)"
msgstr "निर्मित माल का मौजूदा मूल्य (Make आइटम)"
@@ -9009,6 +9121,9 @@ msgstr "खुली नौकरियां"
msgid "Open menu"
msgstr "मेनू खोलें"
+msgid "Open payables by supplier and age"
+msgstr "आपूर्तिकर्ता और आयु द्वारा खुले देनदारी"
+
msgid "Open Purchase Invoices"
msgstr "खुले क्रय चालान"
@@ -9024,6 +9139,9 @@ msgstr "खुली उद्धरणें"
msgid "Open Reactive"
msgstr "खुली प्रतिक्रियाशील"
+msgid "Open receivables by customer and age"
+msgstr "ग्राहक और आयु द्वारा खुली प्राप्य"
+
msgid "Open RFQs"
msgstr "खुले RFQ"
@@ -9057,6 +9175,9 @@ msgstr "अवक्षयण का खाता खोलने के सं
msgid "Operating Expenses"
msgstr "परिचालन व्यय"
+msgid "Operating Income"
+msgstr "परिचालन आय"
+
msgid "Operation"
msgstr "ऑपरेशन"
@@ -9172,6 +9293,12 @@ msgstr "मूल"
msgid "Original Count"
msgstr "मूल गणना"
+msgid "Other Expense"
+msgstr "अन्य व्यय"
+
+msgid "Other Income"
+msgstr "अन्य आय"
+
msgid "Other Income account for FX gains when a payment settles a foreign-currency invoice at a more favorable rate"
msgstr "विदेशी मुद्रा लाभ के लिए अन्य आय खाता जब कोई भुगतान विदेशी-मुद्रा चालान को अधिक अनुकूल दर पर निपटाता है"
@@ -9557,6 +9684,11 @@ msgstr "Pieces/Minute"
msgid "Pin"
msgstr "पिन"
+#. placeholder {0}: report.name
+#. placeholder {0}: view.name
+msgid "Pin {0}"
+msgstr "{0} को पिन करें"
+
msgid "Pinned"
msgstr "पिन किया गया"
@@ -10083,6 +10215,9 @@ msgstr "खरीद इकाई:"
msgid "Purchased"
msgstr "खरीदा गया"
+msgid "Purchases"
+msgstr "खरीद"
+
msgid "purchasing"
msgstr "क्रय और बेचे गए माल की लागत"
@@ -10211,6 +10346,9 @@ msgstr "इस ओवरराइड के लिए मात्रा-आध
msgid "Quantity: {0}"
msgstr "मात्रा: {0}"
+msgid "Quarterly"
+msgstr "त्रैमासिक"
+
msgid "Question"
msgstr "प्रश्न"
@@ -10678,6 +10816,9 @@ msgstr "पुनःपूर्ति प्रणाली"
msgid "Report"
msgstr "रिपोर्ट"
+msgid "Reporting"
+msgstr "रिपोर्टिंग"
+
msgid "Reporting dimension"
msgstr "रिपोर्टिंग आयाम"
@@ -10687,6 +10828,9 @@ msgstr "रिपोर्ट"
msgid "Reprint"
msgstr "दोबारा प्रिंट करें"
+msgid "Request access"
+msgstr "प्रवेश का अनुरोध करें"
+
msgid "Request Approval"
msgstr "अनुमोदन का अनुरोध करें"
@@ -10821,6 +10965,12 @@ msgstr "अप्रयुक्त सामग्री को वापस
msgid "Rev {revision}"
msgstr "Rev {revision}"
+msgid "Revenue"
+msgstr "राजस्व"
+
+msgid "Revenue and expenses over a period"
+msgstr "एक अवधि में राजस्व और व्यय"
+
msgid "Reverse all inventory adjustments"
msgstr "सभी इन्वेंटरी समायोजन को उलट दें"
@@ -11153,9 +11303,15 @@ msgstr "संपर्क सहेजें"
msgid "Save Method"
msgstr "विधि सहेजें"
+msgid "Save view"
+msgstr "दृश्य सहेजें"
+
msgid "Save View"
msgstr "दृश्य सहेजें"
+msgid "Saved Views"
+msgstr "सहेजे गए दृश्य"
+
msgid "Saving..."
msgstr "सहेज रहे हैं..."
@@ -11868,6 +12024,15 @@ msgstr "सिंक विकल्प दिखाएं"
msgid "Showing {0} of {totalCount} — refine your search"
msgstr "दिखा रहा है {0} का {totalCount} — अपनी खोज को परिष्कृत करें"
+msgid "Showing in {parentCurrency}"
+msgstr "में दिखाई दे रहा है {parentCurrency}"
+
+msgid "Showing the first 500 lines"
+msgstr "पहली 500 लाइनें दिखा रहे हैं"
+
+msgid "Showing the top 1,000 groups by amount"
+msgstr "राशि द्वारा शीर्ष 1,000 समूह दिखा रहे हैं"
+
msgid "Shown as a faint background behind every page of generated PDFs"
msgstr "जनरेट की गई PDF के हर पेज के पीछे हल्की पृष्ठभूमि के रूप में दिखाया जाता है"
@@ -11937,6 +12102,15 @@ msgstr "छोड़ा गया"
msgid "Slack"
msgstr "Slack"
+msgid "Slice asset activity by location, item, or any dimension"
+msgstr "स्थान, आइटम, या किसी भी आयाम द्वारा संपत्ति गतिविधि को स्लाइस करें"
+
+msgid "Slice expenses by location, cost center, or any dimension"
+msgstr "स्थान, लागत केंद्र, या किसी भी आयाम द्वारा खर्चों को स्लाइस करें"
+
+msgid "Slice revenue by customer, customer type, or any dimension"
+msgstr "ग्राहक, ग्राहक प्रकार, या किसी भी आयाम द्वारा राजस्व को स्लाइस करें"
+
msgid "Smoke-test the core daily flows end to end"
msgstr "कोर दैनिक प्रवाह को अंत से अंत तक स्मोक-टेस्ट करें"
@@ -12018,6 +12192,9 @@ msgstr "विशिष्ट ग्राहक"
msgid "Specific Items"
msgstr "विशिष्ट आइटम"
+msgid "Spend by supplier, item, or category — your biggest cost drivers"
+msgstr "आपूर्तिकर्ता, आइटम, या श्रेणी द्वारा व्यय — आपके सबसे बड़े लागत ड्राइवर"
+
msgid "Split"
msgstr "विभाजित करें"
@@ -13343,6 +13520,9 @@ msgstr "थीम"
msgid "Theme Color"
msgstr "थीम रंग"
+msgid "Then by"
+msgstr "फिर द्वारा"
+
msgid "There are no active supplier quotes to compare for this RFQ."
msgstr "इस RFQ के लिए तुलना करने के लिए कोई सक्रिय आपूर्तिकर्ता उद्धरण नहीं हैं।"
@@ -13585,6 +13765,9 @@ msgstr "समय क्षेत्र"
msgid "Title"
msgstr "शीर्षक"
+msgid "To Date"
+msgstr "दिनांक तक"
+
msgid "To deactivate, use the row menu and choose Deactivate Account."
msgstr "निष्क्रिय करने के लिए, पंक्ति मेनू का उपयोग करें और खाता निष्क्रिय करें चुनें।"
@@ -13976,6 +14159,11 @@ msgstr "अनपिक करें"
msgid "Unpick {0}"
msgstr "अनपिक {0}"
+#. placeholder {0}: report.name
+#. placeholder {0}: view.name
+msgid "Unpin {0}"
+msgstr "{0} को अनपिन करें"
+
msgid "Unposted Documents"
msgstr "अपोस्ट किए गए दस्तावेज़"
@@ -14225,9 +14413,6 @@ msgstr "सत्यापित"
msgid "Validating job..."
msgstr "नौकरी को मान्य कर रहे हैं..."
-msgid "Valuation"
-msgstr "मूल्यांकन"
-
msgid "Value"
msgstr "मान"
@@ -14653,6 +14838,9 @@ msgstr "जब आप Carbon पर जाते हैं तो क्या
msgid "What data"
msgstr "कौन सा डेटा"
+msgid "What drove inventory up or down, by any dimension"
+msgstr "किस चीज़ ने इन्वेंटरी को किसी भी आयाम द्वारा ऊपर या नीचे ले जाया"
+
msgid "What is {translatedTerm}?"
msgstr "{translatedTerm} क्या है?"
@@ -15049,6 +15237,9 @@ msgstr "किसी संपत्ति के मूल्य को उस
msgid "Year"
msgstr "साल"
+msgid "Yearly"
+msgstr "वार्षिक"
+
msgid "Yes"
msgstr "हाँ"
diff --git a/packages/locale/locales/it/erp.po b/packages/locale/locales/it/erp.po
index 009566d57f..42bf356f93 100644
--- a/packages/locale/locales/it/erp.po
+++ b/packages/locale/locales/it/erp.po
@@ -48,6 +48,10 @@ msgstr "(escluso per questo cliente)"
msgid "{0, plural, one {This part is on 1 open change notice} other {This part is on # open change notices}}"
msgstr "{0, plural, one {Questa parte è in 1 avviso di modifica aperto} other {Questa parte è in # avvisi di modifica aperti}}"
+#. placeholder {0}: selectedAccountIds.length
+msgid "{0} accounts"
+msgstr "{0} conti"
+
#. placeholder {0}: precise?.text
msgid "{0} ago"
msgstr "{0} fa"
@@ -163,6 +167,9 @@ msgstr "{years}ann"
msgid "/month/user"
msgstr "/mese/utente"
+msgid "% of total"
+msgstr "% del totale"
+
msgid "% of Total"
msgstr "% del Totale"
@@ -474,6 +481,9 @@ msgstr "Conto"
msgid "Account & Details"
msgstr "Conto e dettagli"
+msgid "Account balances with debits and credits"
+msgstr "Saldi dei conti con debiti e crediti"
+
msgid "Account for advance payments made before goods or services are received"
msgstr "Contabilizzate i pagamenti anticipati effettuati prima della ricezione di beni o servizi."
@@ -510,9 +520,15 @@ msgstr "contabilità"
msgid "Accounting"
msgstr "Contabilità"
+msgid "Accounting is currently in beta. Request access to enable reporting, journal entries, accounting periods, fixed assets, and more."
+msgstr "La contabilità è attualmente in beta. Richiedi l'accesso per abilitare report, voci di diario, periodi contabili, cespiti e altro."
+
msgid "Accounting is disabled"
msgstr "La contabilità è disabilitata"
+msgid "Accounting is disabled for this company."
+msgstr "La contabilità è disabilitata per questa azienda."
+
msgid "Accounting is enabled"
msgstr "La contabilità è abilitata"
@@ -853,6 +869,9 @@ msgstr "Dopo"
msgid "After (calculation method)"
msgstr "Dopo (metodo di calcolo)"
+msgid "Aging"
+msgstr "Scadenza"
+
msgid "Agree on the scope"
msgstr "Concordare sull'ambito"
@@ -871,6 +890,9 @@ msgstr "Tutti"
msgid "All {total} phases are done. Nice work — your team is up and running."
msgstr "Tutte le {total} fasi sono completate. Ottimo lavoro — il tuo team è operativo."
+msgid "All accounts"
+msgstr "Tutti i conti"
+
msgid "All actions selected"
msgstr "Tutte le azioni selezionate"
@@ -983,6 +1005,9 @@ msgstr "La posizione di un'operazione nella coda del suo centro di lavoro, l'ord
msgid "An unexpected error occurred while connecting to Onshape. Try connecting again."
msgstr "Si è verificato un errore inatteso durante la connessione a Onshape. Riprova a connetterti."
+msgid "Analytics"
+msgstr "Analitiche"
+
msgid "Anchors the Plan timeline to real dates. Leave blank for a relative, week-numbered timeline. Setting either one fills in the rest."
msgstr "Ancora la cronologia del Piano alle date reali. Lascia vuoto per una cronologia relativa, numerata per settimane. Impostando uno qualsiasi dei due, il resto viene compilato automaticamente."
@@ -1026,6 +1051,9 @@ msgstr "Qualsiasi tipo di articolo"
msgid "Anything not explicitly listed in scope above"
msgstr "Qualsiasi cosa non esplicitamente elencata nell'ambito di cui sopra"
+msgid "AP Aging"
+msgstr "Anzianità dei Debiti"
+
msgid "AP Clerk"
msgstr "Addetto Contabilità Fornitori"
@@ -1138,6 +1166,9 @@ msgstr "AQL"
msgid "AQL (Z1.4 / ISO 2859-1)"
msgstr "AQL (Z1.4 / ISO 2859-1)"
+msgid "AR Aging"
+msgstr "Anzianità dei Crediti"
+
msgid "AR Clerk"
msgstr "Addetto Contabilità Clienti"
@@ -1245,6 +1276,11 @@ msgstr "Sei sicuro di voler eliminare {0}? Questa azione non può essere annulla
msgid "Are you sure you want to delete {name}? This cannot be undone."
msgstr "Sei sicuro di voler eliminare {name}? Questa azione non può essere annullata."
+#. placeholder {0}: activeView.name
+#. placeholder {0}: viewPendingDelete.name
+msgid "Are you sure you want to delete the \"{0}\" view? This cannot be undone."
+msgstr "Sei sicuro di voler eliminare la visualizzazione \"{0}\"? Questa azione non può essere annullata."
+
#. placeholder {0}: selectedCustomField?.name
msgid "Are you sure you want to delete the {0} field?"
msgstr "Sei sicuro di voler eliminare il campo {0}?"
@@ -1634,6 +1670,9 @@ msgstr "ID Bene"
msgid "Assets"
msgstr "Cespiti"
+msgid "Assets, liabilities and equity as of a date"
+msgstr "Attività, passività e patrimonio netto a una data"
+
msgid "Assign printers to locations. Shipping, receiving, and work centers inherit the location default unless overridden."
msgstr "Assegna stampanti alle posizioni. Spedizione, ricezione e centri di lavoro ereditano l'impostazione predefinita della posizione se non sovrascritti."
@@ -1890,6 +1929,9 @@ msgstr "Sotto stock di sicurezza"
msgid "Beta"
msgstr "Beta"
+msgid "Biggest causes of scrap by reason, item, or work center"
+msgstr "Cause principali di scarto per motivo, articolo o centro di lavoro"
+
msgid "Bill of Material"
msgstr "Distinta Base"
@@ -2020,12 +2062,18 @@ msgstr "da {byUser}"
msgid "By accepting the invite, you agree to the <0>Terms of Service</0> and <1>Privacy Policy</1>."
msgstr "Accettando l'invito, accetti i <0>Termini di Servizio</0> e l'<1>Informativa sulla Privacy</1>."
+msgid "By dimension"
+msgstr "Per dimensione"
+
msgid "By Document Date"
msgstr "Per Data Documento"
msgid "By Due Date"
msgstr "Per Data di Scadenza"
+msgid "By field"
+msgstr "Per campo"
+
msgid "By Item"
msgstr "Per Articolo"
@@ -2383,6 +2431,9 @@ msgstr "Cancella ricerca"
msgid "Clear search query"
msgstr "Cancella query di ricerca"
+msgid "Clear selection"
+msgstr "Cancella selezione"
+
msgid "Clear this invoice with the party's posted credits as well as cash. Credits apply directly — no posting needed."
msgstr "Cancella questa fattura con i crediti registrati della parte nonché in contanti. I crediti si applicano direttamente — nessuna registrazione necessaria."
@@ -2416,6 +2467,9 @@ msgstr "Data di chiusura"
msgid "Close Period"
msgstr "Chiudi Periodo"
+msgid "Close Reports"
+msgstr "Chiudi Report"
+
msgid "Close Status"
msgstr "Stato Chiusura"
@@ -2464,6 +2518,12 @@ msgstr "Comprimi preparazione"
msgid "Collapse subtree"
msgstr "Comprimi sottostruttura"
+msgid "Column dimension"
+msgstr "Dimensione colonna"
+
+msgid "Column field"
+msgstr "Campo colonna"
+
msgid "Column visibility and order"
msgstr "Visibilità e ordine delle colonne"
@@ -2560,6 +2620,9 @@ msgstr "Codice a barre di completamento"
msgid "Completion Time"
msgstr "Tempo di completamento"
+msgid "Condensed P&L with margins and key subtotals"
+msgstr "Conto economico condensato con margini e subtotali chiave"
+
msgid "Conditions"
msgstr "Condizioni"
@@ -3041,6 +3104,9 @@ msgstr "Costo dei beni venduti (COGS)"
msgid "Cost of Goods Sold (default)"
msgstr "Costo dei Beni Venduti (predefinito)"
+msgid "Cost of Sales"
+msgstr "Costo del venduto"
+
msgid "Costing"
msgstr "Calcolo dei costi"
@@ -3852,6 +3918,10 @@ msgstr "Definire distinte base multi-livello e Bill of Process (metodi di produz
msgid "Delete"
msgstr "Elimina"
+#. placeholder {0}: view.name
+msgid "Delete {0}"
+msgstr "Elimina {0}"
+
msgid "Delete {name}"
msgstr "Elimina {name}"
@@ -4138,6 +4208,9 @@ msgstr "Elimina Tipo"
msgid "Delete Unit of Measure"
msgstr "Elimina unità di misura"
+msgid "Delete view"
+msgstr "Elimina visualizzazione"
+
msgid "Delete View"
msgstr "Elimina Vista"
@@ -5241,6 +5314,9 @@ msgstr "Lo scambio del codice di autorizzazione con un token di accesso non è r
msgid "Excluded"
msgstr "Escluso"
+msgid "Executive P&L"
+msgstr "Conto economico direttivo"
+
msgid "Exemption Certificate"
msgstr "Certificato di Esenzione"
@@ -5311,6 +5387,9 @@ msgstr "Lato spese dei movimenti di imposte differite (abbinato a passivo d'impo
msgid "Expense side of deferred tax movements (paired with deferred tax liability)."
msgstr "Impossibile creare la classe di cespiti: {0}"
+msgid "Expenses"
+msgstr "Spese"
+
msgid "Expert guidance"
msgstr "Guida di esperti"
@@ -5803,6 +5882,9 @@ msgstr "Finalizza"
msgid "Finalizing a fiscal month through the Open → Locked → Closed lifecycle; a closed period is frozen and its balances snapshotted, reversible only by explicit reopen."
msgstr "Finalizzazione di un mese fiscale attraverso il ciclo di vita Open → Locked → Closed; un periodo chiuso è bloccato e i suoi saldi vengono acquisiti, reversibili solo mediante una riapertura esplicita."
+msgid "Financial Statements"
+msgstr "Rendiconti Finanziari"
+
msgid "finish"
msgstr "Prodotti finiti"
@@ -6263,9 +6345,15 @@ msgstr "gradi"
msgid "Grades"
msgstr "Gradi"
+msgid "Gross Profit"
+msgstr "Margine lordo"
+
msgid "Group"
msgstr "Gruppo"
+msgid "Group by"
+msgstr "Raggruppa per"
+
msgid "Group Members"
msgstr "Membri del Gruppo"
@@ -6621,6 +6709,9 @@ msgstr "Reddito / Bilancio (ereditato)"
msgid "Income Statement"
msgstr "Conto Economico"
+msgid "Income Tax"
+msgstr "Imposta sul reddito"
+
msgid "Income/Balance"
msgstr "Reddito/Saldo"
@@ -7166,6 +7257,9 @@ msgstr "Unità di Lavoro"
msgid "Language"
msgstr "Lingua"
+msgid "Last 6 Months"
+msgstr "Ultimi 6 Mesi"
+
msgid "Last Calibration"
msgstr "Ultima Calibrazione"
@@ -7962,6 +8056,9 @@ msgstr "Denaro che ti è dovuto"
msgid "Money you owe"
msgstr "Denaro che devi"
+msgid "Monthly"
+msgstr "Mensile"
+
msgid "Months over which this asset depreciates for tax purposes (when not using MACRS)."
msgstr "Mesi in cui questo asset si deprezza a fini fiscali (quando non si utilizza MACRS)."
@@ -8075,6 +8172,9 @@ msgstr "Valore di Bilancio Netto"
msgid "Net Change"
msgstr "Variazione netta"
+msgid "Net Income"
+msgstr "Utile netto"
+
msgid "Never"
msgstr "Mai"
@@ -8567,6 +8667,9 @@ msgstr "Nessun articolo"
msgid "No items have inventory activity here yet."
msgstr "Nessun articolo ha attività di inventario qui ancora."
+msgid "No journal lines in scope for this period"
+msgstr "Nessuna riga di diario nell'ambito per questo periodo"
+
msgid "No lines to map"
msgstr "Nessuna riga da mappare"
@@ -8666,6 +8769,9 @@ msgstr "Nessun processo selezionato"
msgid "No production events recorded for this operation yet"
msgstr "Nessun evento di produzione ancora registrato per questa operazione"
+msgid "No purchases in this period"
+msgstr "Nessun acquisto in questo periodo"
+
msgid "No Quote"
msgstr "Nessuna offerta"
@@ -8684,6 +8790,9 @@ msgstr "Nessuna immagine di riferimento"
msgid "No remaining entities to inspect."
msgstr "Nessuna entità rimanente da ispezionare."
+msgid "No reports match your search."
+msgstr "Nessun report corrisponde alla tua ricerca."
+
msgid "No results"
msgstr "Nessun risultato"
@@ -8904,6 +9013,9 @@ msgstr "Quantità minima da mantenere per uso in servizio presso questa ubicazio
msgid "On-hand inventory remains"
msgstr "L'inventario disponibile rimane"
+msgid "On-hand value by location or item, with GL tie-out"
+msgstr "Valore disponibile per ubicazione o articolo, con riconciliazione contabile"
+
msgid "On-hand value of manufactured goods (Make items)"
msgstr "Valore disponibile dei beni fabbricati (articoli Make)"
@@ -9009,6 +9121,9 @@ msgstr "Lavori aperti"
msgid "Open menu"
msgstr "Apri menu"
+msgid "Open payables by supplier and age"
+msgstr "Debiti aperti per fornitore e anzianità"
+
msgid "Open Purchase Invoices"
msgstr "Fatture di acquisto aperte"
@@ -9024,6 +9139,9 @@ msgstr "Preventivi Aperti"
msgid "Open Reactive"
msgstr "Reattivo Aperto"
+msgid "Open receivables by customer and age"
+msgstr "Crediti aperti per cliente e anzianità"
+
msgid "Open RFQs"
msgstr "RFQ Aperti"
@@ -9057,6 +9175,9 @@ msgstr "Saldo di apertura dell'ammortamento già contabilizzato prima dell'aggiu
msgid "Operating Expenses"
msgstr "Spese Operative"
+msgid "Operating Income"
+msgstr "Utile operativo"
+
msgid "Operation"
msgstr "Operazione"
@@ -9172,6 +9293,12 @@ msgstr "Originale"
msgid "Original Count"
msgstr "Conteggio Originale"
+msgid "Other Expense"
+msgstr "Altre spese"
+
+msgid "Other Income"
+msgstr "Altre entrate"
+
msgid "Other Income account for FX gains when a payment settles a foreign-currency invoice at a more favorable rate"
msgstr "Account di Altro Reddito per guadagni in valuta estera quando un pagamento regola una fattura in valuta estera a un tasso più favorevole"
@@ -9557,6 +9684,11 @@ msgstr "Pezzi/Minuto"
msgid "Pin"
msgstr "Fissa"
+#. placeholder {0}: report.name
+#. placeholder {0}: view.name
+msgid "Pin {0}"
+msgstr "Fissa {0}"
+
msgid "Pinned"
msgstr "Fissato"
@@ -10083,6 +10215,9 @@ msgstr "Unità di acquisto:"
msgid "Purchased"
msgstr "Acquistato"
+msgid "Purchases"
+msgstr "Acquisti"
+
msgid "purchasing"
msgstr "Acquisti e Costo del Venduto"
@@ -10211,6 +10346,9 @@ msgstr "Livelli di prezzo basati sulla quantità per questo override; il prezzo
msgid "Quantity: {0}"
msgstr "Quantità: {0}"
+msgid "Quarterly"
+msgstr "Trimestrale"
+
msgid "Question"
msgstr "Domanda"
@@ -10678,6 +10816,9 @@ msgstr "Sistema di Rifornimento"
msgid "Report"
msgstr "Rapporto"
+msgid "Reporting"
+msgstr "Report"
+
msgid "Reporting dimension"
msgstr "Dimensione di reporting"
@@ -10687,6 +10828,9 @@ msgstr "Rapporti"
msgid "Reprint"
msgstr "Ristampa"
+msgid "Request access"
+msgstr "Richiedi accesso"
+
msgid "Request Approval"
msgstr "Richiedi Approvazione"
@@ -10821,6 +10965,12 @@ msgstr "Restituzione di materiale prelevato inutilizzato"
msgid "Rev {revision}"
msgstr "Rev {revision}"
+msgid "Revenue"
+msgstr "Ricavi"
+
+msgid "Revenue and expenses over a period"
+msgstr "Ricavi e spese in un periodo"
+
msgid "Reverse all inventory adjustments"
msgstr "Annulla tutti gli adeguamenti dell'inventario"
@@ -11153,9 +11303,15 @@ msgstr "Salva contatti"
msgid "Save Method"
msgstr "Salva Metodo"
+msgid "Save view"
+msgstr "Salva vista"
+
msgid "Save View"
msgstr "Salva Vista"
+msgid "Saved Views"
+msgstr "Viste salvate"
+
msgid "Saving..."
msgstr "Salvataggio in corso..."
@@ -11868,6 +12024,15 @@ msgstr "Mostra opzioni di sincronizzazione"
msgid "Showing {0} of {totalCount} — refine your search"
msgstr "Mostrando {0} di {totalCount} — raffina la tua ricerca"
+msgid "Showing in {parentCurrency}"
+msgstr "Visualizzazione in {parentCurrency}"
+
+msgid "Showing the first 500 lines"
+msgstr "Visualizzazione delle prime 500 righe"
+
+msgid "Showing the top 1,000 groups by amount"
+msgstr "Visualizzazione dei primi 1.000 gruppi per importo"
+
msgid "Shown as a faint background behind every page of generated PDFs"
msgstr "Mostrato come sfondo tenue dietro ogni pagina dei PDF generati"
@@ -11937,6 +12102,15 @@ msgstr "Saltato"
msgid "Slack"
msgstr "Slack"
+msgid "Slice asset activity by location, item, or any dimension"
+msgstr "Suddividi l'attività dei cespiti per ubicazione, articolo o qualsiasi dimensione"
+
+msgid "Slice expenses by location, cost center, or any dimension"
+msgstr "Suddividi le spese per ubicazione, centro di costo o qualsiasi dimensione"
+
+msgid "Slice revenue by customer, customer type, or any dimension"
+msgstr "Seziona ricavi per cliente, tipo cliente o qualsiasi dimensione"
+
msgid "Smoke-test the core daily flows end to end"
msgstr "Smoke-test dei flussi giornalieri principali da inizio a fine"
@@ -12018,6 +12192,9 @@ msgstr "Clienti Specifici"
msgid "Specific Items"
msgstr "Articoli Specifici"
+msgid "Spend by supplier, item, or category — your biggest cost drivers"
+msgstr "Spesa per fornitore, articolo o categoria — i tuoi principali driver di costo"
+
msgid "Split"
msgstr "Dividi"
@@ -13343,6 +13520,9 @@ msgstr "Tema"
msgid "Theme Color"
msgstr "Colore Tema"
+msgid "Then by"
+msgstr "Quindi per"
+
msgid "There are no active supplier quotes to compare for this RFQ."
msgstr "Non ci sono preventivi fornitori attivi da confrontare per questa RFQ."
@@ -13585,6 +13765,9 @@ msgstr "Fuso orario"
msgid "Title"
msgstr "Titolo"
+msgid "To Date"
+msgstr "A data"
+
msgid "To deactivate, use the row menu and choose Deactivate Account."
msgstr "Per disattivare, usa il menu della riga e scegli Disattiva Account."
@@ -13976,6 +14159,11 @@ msgstr "Annulla prelievo"
msgid "Unpick {0}"
msgstr "Annulla prelievo {0}"
+#. placeholder {0}: report.name
+#. placeholder {0}: view.name
+msgid "Unpin {0}"
+msgstr "Rimuovi {0}"
+
msgid "Unposted Documents"
msgstr "Documenti Non Registrati"
@@ -14225,9 +14413,6 @@ msgstr "Convalidato"
msgid "Validating job..."
msgstr "Convalida processo..."
-msgid "Valuation"
-msgstr "Valutazione"
-
msgid "Value"
msgstr "Valore"
@@ -14653,6 +14838,9 @@ msgstr "Cosa cambia quando passi a Carbon e approssimativamente quanto vale. Sti
msgid "What data"
msgstr "Quali dati"
+msgid "What drove inventory up or down, by any dimension"
+msgstr "Cosa ha fatto aumentare o diminuire l'inventario, per qualsiasi dimensione"
+
msgid "What is {translatedTerm}?"
msgstr "Cos'è {translatedTerm}?"
@@ -15049,6 +15237,9 @@ msgstr "Ridurre il valore di un bene nel corso della sua vita utile — un batch
msgid "Year"
msgstr "Anno"
+msgid "Yearly"
+msgstr "Annuale"
+
msgid "Yes"
msgstr "Sì"
diff --git a/packages/locale/locales/ja/erp.po b/packages/locale/locales/ja/erp.po
index be8eb557c6..8ea5f2171c 100644
--- a/packages/locale/locales/ja/erp.po
+++ b/packages/locale/locales/ja/erp.po
@@ -48,6 +48,10 @@ msgstr "(このお客様では除外されています)"
msgid "{0, plural, one {This part is on 1 open change notice} other {This part is on # open change notices}}"
msgstr "{0, plural, one {このパーツは1つの開いた変更通知に含まれています} other {このパーツは#つの開いた変更通知に含まれています}}"
+#. placeholder {0}: selectedAccountIds.length
+msgid "{0} accounts"
+msgstr "{0} 件のアカウント"
+
#. placeholder {0}: precise?.text
msgid "{0} ago"
msgstr "{0}前"
@@ -163,6 +167,9 @@ msgstr "{years}年"
msgid "/month/user"
msgstr "/月/ユーザー"
+msgid "% of total"
+msgstr "全体の %"
+
msgid "% of Total"
msgstr "総量比"
@@ -474,6 +481,9 @@ msgstr "アカウント"
msgid "Account & Details"
msgstr "アカウントと詳細"
+msgid "Account balances with debits and credits"
+msgstr "借方貸方を含む勘定残高"
+
msgid "Account for advance payments made before goods or services are received"
msgstr "商品またはサービスの受領前に行われた前払いをアカウントします。"
@@ -510,9 +520,15 @@ msgstr "会計"
msgid "Accounting"
msgstr "会計"
+msgid "Accounting is currently in beta. Request access to enable reporting, journal entries, accounting periods, fixed assets, and more."
+msgstr "会計機能は現在ベータ版です。レポート、仕訳帳、会計期間、固定資産などを有効にするためにアクセスをリクエストしてください。"
+
msgid "Accounting is disabled"
msgstr "会計は無効です"
+msgid "Accounting is disabled for this company."
+msgstr "この会社では会計機能が無効になっています。"
+
msgid "Accounting is enabled"
msgstr "会計が有効です"
@@ -853,6 +869,9 @@ msgstr "後"
msgid "After (calculation method)"
msgstr "後(計算方法)"
+msgid "Aging"
+msgstr "経過日数"
+
msgid "Agree on the scope"
msgstr "スコープに同意する"
@@ -871,6 +890,9 @@ msgstr "すべて"
msgid "All {total} phases are done. Nice work — your team is up and running."
msgstr "すべての{total}フェーズが完了しました。素晴らしい仕事です。チームが稼働しています。"
+msgid "All accounts"
+msgstr "すべてのアカウント"
+
msgid "All actions selected"
msgstr "すべてのアクションが選択されました"
@@ -983,6 +1005,9 @@ msgstr "作業センターのキューの中での操作の位置。フロアが
msgid "An unexpected error occurred while connecting to Onshape. Try connecting again."
msgstr "Onshape への接続中に予期しないエラーが発生しました。もう一度接続してください。"
+msgid "Analytics"
+msgstr "分析"
+
msgid "Anchors the Plan timeline to real dates. Leave blank for a relative, week-numbered timeline. Setting either one fills in the rest."
msgstr "計画のタイムラインを実際の日付に固定します。相対的な週番号付きタイムラインの場合は空白のままにしてください。どちらか一方を設定すると、残りが自動的に入力されます。"
@@ -1026,6 +1051,9 @@ msgstr "任意のアイテムタイプ"
msgid "Anything not explicitly listed in scope above"
msgstr "上記の範囲に明示的にリストされていないもの"
+msgid "AP Aging"
+msgstr "支払い老化分析"
+
msgid "AP Clerk"
msgstr "AP クラーク"
@@ -1138,6 +1166,9 @@ msgstr "AQL"
msgid "AQL (Z1.4 / ISO 2859-1)"
msgstr "AQL (Z1.4 / ISO 2859-1)"
+msgid "AR Aging"
+msgstr "売上老化分析"
+
msgid "AR Clerk"
msgstr "AR事務員"
@@ -1245,6 +1276,11 @@ msgstr "本当に{0}を削除してもよろしいですか?この操作は取
msgid "Are you sure you want to delete {name}? This cannot be undone."
msgstr "本当に{name}を削除してもよろしいですか?この操作は取り消せません。"
+#. placeholder {0}: activeView.name
+#. placeholder {0}: viewPendingDelete.name
+msgid "Are you sure you want to delete the \"{0}\" view? This cannot be undone."
+msgstr "「{0}」ビューを削除してもよろしいですか?この操作は元に戻せません。"
+
#. placeholder {0}: selectedCustomField?.name
msgid "Are you sure you want to delete the {0} field?"
msgstr "{0}フィールドを削除してもよろしいですか?"
@@ -1634,6 +1670,9 @@ msgstr "資産 ID"
msgid "Assets"
msgstr "資産"
+msgid "Assets, liabilities and equity as of a date"
+msgstr "特定日時点での資産、負債および資本"
+
msgid "Assign printers to locations. Shipping, receiving, and work centers inherit the location default unless overridden."
msgstr "プリンターをロケーションに割り当てます。配送、受け取り、ワークセンターは、オーバーライドされない限りロケーションのデフォルトを継承します。"
@@ -1890,6 +1929,9 @@ msgstr "安全在庫以下"
msgid "Beta"
msgstr "ベータ"
+msgid "Biggest causes of scrap by reason, item, or work center"
+msgstr "スクラップの最大原因(理由別、品目別、または作業中心別)"
+
msgid "Bill of Material"
msgstr "材料表"
@@ -2020,12 +2062,18 @@ msgstr "{byUser}による"
msgid "By accepting the invite, you agree to the <0>Terms of Service</0> and <1>Privacy Policy</1>."
msgstr "招待を受け入れることで、<0>利用規約</0>および<1>プライバシーポリシー</1>に同意するものとします。"
+msgid "By dimension"
+msgstr "ディメンション別"
+
msgid "By Document Date"
msgstr "ドキュメント日付別"
msgid "By Due Date"
msgstr "支払期日別"
+msgid "By field"
+msgstr "フィールド別"
+
msgid "By Item"
msgstr "品目別"
@@ -2383,6 +2431,9 @@ msgstr "検索をクリア"
msgid "Clear search query"
msgstr "検索クエリをクリア"
+msgid "Clear selection"
+msgstr "選択をクリア"
+
msgid "Clear this invoice with the party's posted credits as well as cash. Credits apply directly — no posting needed."
msgstr "このインボイスをパーティの転記済みクレジットおよび現金でクリアします。クレジットは直接適用されます — 転記は不要です。"
@@ -2416,6 +2467,9 @@ msgstr "終了日"
msgid "Close Period"
msgstr "期間を閉じる"
+msgid "Close Reports"
+msgstr "レポートを閉じる"
+
msgid "Close Status"
msgstr "閉鎖ステータス"
@@ -2464,6 +2518,12 @@ msgstr "段取りを折りたたむ"
msgid "Collapse subtree"
msgstr "サブツリーを折りたたむ"
+msgid "Column dimension"
+msgstr "列ディメンション"
+
+msgid "Column field"
+msgstr "列フィールド"
+
msgid "Column visibility and order"
msgstr "列の表示と順序"
@@ -2560,6 +2620,9 @@ msgstr "完了バーコード"
msgid "Completion Time"
msgstr "完了時間"
+msgid "Condensed P&L with margins and key subtotals"
+msgstr "マージンと主要小計を含む圧縮P&L"
+
msgid "Conditions"
msgstr "条件"
@@ -3041,6 +3104,9 @@ msgstr "売上原価(COGS)"
msgid "Cost of Goods Sold (default)"
msgstr "売上原価(デフォルト)"
+msgid "Cost of Sales"
+msgstr "売上原価"
+
msgid "Costing"
msgstr "原価計算"
@@ -3852,6 +3918,10 @@ msgstr "複数レベルのBOMおよびプロセス表(製造方法)を定義す
msgid "Delete"
msgstr "削除"
+#. placeholder {0}: view.name
+msgid "Delete {0}"
+msgstr "{0} を削除"
+
msgid "Delete {name}"
msgstr "{name}を削除"
@@ -4138,6 +4208,9 @@ msgstr "タイプを削除"
msgid "Delete Unit of Measure"
msgstr "測定単位を削除"
+msgid "Delete view"
+msgstr "ビューを削除"
+
msgid "Delete View"
msgstr "ビューを削除"
@@ -5241,6 +5314,9 @@ msgstr "認可コードとアクセストークンの交換に失敗しました
msgid "Excluded"
msgstr "除外"
+msgid "Executive P&L"
+msgstr "経営幹部向けP&L"
+
msgid "Exemption Certificate"
msgstr "免除証明書"
@@ -5311,6 +5387,9 @@ msgstr "繰延税金負債の動きの費用側(繰延税金負債と対にな
msgid "Expense side of deferred tax movements (paired with deferred tax liability)."
msgstr "固定資産クラスの作成に失敗しました: {0}"
+msgid "Expenses"
+msgstr "経費"
+
msgid "Expert guidance"
msgstr "専門家によるガイダンス"
@@ -5803,6 +5882,9 @@ msgstr "確定"
msgid "Finalizing a fiscal month through the Open → Locked → Closed lifecycle; a closed period is frozen and its balances snapshotted, reversible only by explicit reopen."
msgstr "開始 → ロック → クローズ ライフサイクルを通じて会計月をファイナライズします。クローズされた期間は凍結され、残高がスナップショットされ、明示的な再開でのみ取り消せます。"
+msgid "Financial Statements"
+msgstr "財務諸表"
+
msgid "finish"
msgstr "完成品"
@@ -6263,9 +6345,15 @@ msgstr "グレード"
msgid "Grades"
msgstr "等級"
+msgid "Gross Profit"
+msgstr "総利益"
+
msgid "Group"
msgstr "グループ"
+msgid "Group by"
+msgstr "グループ化"
+
msgid "Group Members"
msgstr "グループメンバー"
@@ -6621,6 +6709,9 @@ msgstr "収入/残高(継承)"
msgid "Income Statement"
msgstr "損益計算書"
+msgid "Income Tax"
+msgstr "所得税"
+
msgid "Income/Balance"
msgstr "収入/残高"
@@ -7166,6 +7257,9 @@ msgstr "労働単位"
msgid "Language"
msgstr "言語"
+msgid "Last 6 Months"
+msgstr "過去6ヶ月"
+
msgid "Last Calibration"
msgstr "最後のキャリブレーション"
@@ -7962,6 +8056,9 @@ msgstr "あなたに支払われるべき金額"
msgid "Money you owe"
msgstr "あなたが負っている金額"
+msgid "Monthly"
+msgstr "月次"
+
msgid "Months over which this asset depreciates for tax purposes (when not using MACRS)."
msgstr "このアセットが税務上償却される月数(MACRS使用時以外)。"
@@ -8075,6 +8172,9 @@ msgstr "純簿価額"
msgid "Net Change"
msgstr "純変化"
+msgid "Net Income"
+msgstr "純利益"
+
msgid "Never"
msgstr "なし"
@@ -8567,6 +8667,9 @@ msgstr "アイテムなし"
msgid "No items have inventory activity here yet."
msgstr "ここにはまだアイテムの在庫活動がありません。"
+msgid "No journal lines in scope for this period"
+msgstr "この期間のスコープ内にジャーナルラインがありません"
+
msgid "No lines to map"
msgstr "マップするラインがありません"
@@ -8666,6 +8769,9 @@ msgstr "プロセスが選択されていません"
msgid "No production events recorded for this operation yet"
msgstr "この操作で記録された生産イベントはまだありません"
+msgid "No purchases in this period"
+msgstr "この期間に購入がありません"
+
msgid "No Quote"
msgstr "見積なし"
@@ -8684,6 +8790,9 @@ msgstr "参照画像がありません"
msgid "No remaining entities to inspect."
msgstr "検査する残りのエンティティはありません。"
+msgid "No reports match your search."
+msgstr "検索に一致するレポートはありません。"
+
msgid "No results"
msgstr "結果がありません"
@@ -8904,6 +9013,9 @@ msgstr "このロケーションでのサービス使用のために維持する
msgid "On-hand inventory remains"
msgstr "現在庫が残っています"
+msgid "On-hand value by location or item, with GL tie-out"
+msgstr "GL仕訳帳との照合付き場所または品目別手持ち在庫価値"
+
msgid "On-hand value of manufactured goods (Make items)"
msgstr "製造品(メイク品目)の現在高価値"
@@ -9009,6 +9121,9 @@ msgstr "未処理ジョブ"
msgid "Open menu"
msgstr "メニューを開く"
+msgid "Open payables by supplier and age"
+msgstr "仕入先および期間別未払い債務"
+
msgid "Open Purchase Invoices"
msgstr "未払い購買請求書"
@@ -9024,6 +9139,9 @@ msgstr "オープン見積"
msgid "Open Reactive"
msgstr "オープン反応"
+msgid "Open receivables by customer and age"
+msgstr "顧客および期間別売上債権"
+
msgid "Open RFQs"
msgstr "オープンRFQ"
@@ -9057,6 +9175,9 @@ msgstr "このアセットがCarbonに追加される前に既に予約されて
msgid "Operating Expenses"
msgstr "営業費"
+msgid "Operating Income"
+msgstr "営業利益"
+
msgid "Operation"
msgstr "操作"
@@ -9172,6 +9293,12 @@ msgstr "元"
msgid "Original Count"
msgstr "元のカウント"
+msgid "Other Expense"
+msgstr "その他費用"
+
+msgid "Other Income"
+msgstr "その他収益"
+
msgid "Other Income account for FX gains when a payment settles a foreign-currency invoice at a more favorable rate"
msgstr "支払いが外貨建て請求書をより有利なレートで決済する場合のFX利益に対するその他の収益勘定"
@@ -9557,6 +9684,11 @@ msgstr "個/分"
msgid "Pin"
msgstr "ピン"
+#. placeholder {0}: report.name
+#. placeholder {0}: view.name
+msgid "Pin {0}"
+msgstr "{0}をピン留"
+
msgid "Pinned"
msgstr "ピン留め"
@@ -10083,6 +10215,9 @@ msgstr "購入単位:"
msgid "Purchased"
msgstr "購入済み"
+msgid "Purchases"
+msgstr "購買"
+
msgid "purchasing"
msgstr "購買と売上原価"
@@ -10211,6 +10346,9 @@ msgstr "このオーバーライドの数量ベースの価格設定層。適用
msgid "Quantity: {0}"
msgstr "数量: {0}"
+msgid "Quarterly"
+msgstr "四半期"
+
msgid "Question"
msgstr "質問"
@@ -10678,6 +10816,9 @@ msgstr "補充システム"
msgid "Report"
msgstr "レポート"
+msgid "Reporting"
+msgstr "レポーティング"
+
msgid "Reporting dimension"
msgstr "報告ディメンション"
@@ -10687,6 +10828,9 @@ msgstr "レポート"
msgid "Reprint"
msgstr "再印刷"
+msgid "Request access"
+msgstr "アクセスをリクエスト"
+
msgid "Request Approval"
msgstr "承認をリクエスト"
@@ -10821,6 +10965,12 @@ msgstr "未使用の仕分け材料を返却中"
msgid "Rev {revision}"
msgstr "Rev {revision}"
+msgid "Revenue"
+msgstr "売上"
+
+msgid "Revenue and expenses over a period"
+msgstr "期間にわたる収益と費用"
+
msgid "Reverse all inventory adjustments"
msgstr "すべての在庫調整を取り消す"
@@ -11153,9 +11303,15 @@ msgstr "連絡先を保存"
msgid "Save Method"
msgstr "メソッドを保存"
+msgid "Save view"
+msgstr "ビューを保存"
+
msgid "Save View"
msgstr "ビューを保存"
+msgid "Saved Views"
+msgstr "保存済みビュー"
+
msgid "Saving..."
msgstr "保存中..."
@@ -11868,6 +12024,15 @@ msgstr "同期オプションを表示"
msgid "Showing {0} of {totalCount} — refine your search"
msgstr "{0} / {totalCount} を表示中 — 検索を絞り込みます"
+msgid "Showing in {parentCurrency}"
+msgstr "{parentCurrency}で表示"
+
+msgid "Showing the first 500 lines"
+msgstr "最初の 500 行を表示中"
+
+msgid "Showing the top 1,000 groups by amount"
+msgstr "金額別上位 1,000 グループを表示中"
+
msgid "Shown as a faint background behind every page of generated PDFs"
msgstr "生成されたPDFの各ページの背景に薄く表示されます"
@@ -11937,6 +12102,15 @@ msgstr "スキップ"
msgid "Slack"
msgstr "Slack"
+msgid "Slice asset activity by location, item, or any dimension"
+msgstr "資産活動を場所、品目、または任意のディメンション別に表示"
+
+msgid "Slice expenses by location, cost center, or any dimension"
+msgstr "経費を場所、コスト センター、または任意のディメンション別に表示"
+
+msgid "Slice revenue by customer, customer type, or any dimension"
+msgstr "顧客、顧客タイプ、またはディメンション別に売上をスライス"
+
msgid "Smoke-test the core daily flows end to end"
msgstr "コア日次フローのスモークテストを端から端まで実施"
@@ -12018,6 +12192,9 @@ msgstr "特定の顧客"
msgid "Specific Items"
msgstr "特定の品目"
+msgid "Spend by supplier, item, or category — your biggest cost drivers"
+msgstr "仕入先、品目、またはカテゴリー別の支出 — 最大のコスト ドライバー"
+
msgid "Split"
msgstr "分割"
@@ -13343,6 +13520,9 @@ msgstr "テーマ"
msgid "Theme Color"
msgstr "テーマカラー"
+msgid "Then by"
+msgstr "次に"
+
msgid "There are no active supplier quotes to compare for this RFQ."
msgstr "このRFQに比較するアクティブなサプライヤー見積もりがありません。"
@@ -13585,6 +13765,9 @@ msgstr "タイムゾーン"
msgid "Title"
msgstr "タイトル"
+msgid "To Date"
+msgstr "終了日"
+
msgid "To deactivate, use the row menu and choose Deactivate Account."
msgstr "無効化するには、行メニューを使用して、アカウント無効化を選択します。"
@@ -13976,6 +14159,11 @@ msgstr "ピック解除"
msgid "Unpick {0}"
msgstr "ピック解除 {0}"
+#. placeholder {0}: report.name
+#. placeholder {0}: view.name
+msgid "Unpin {0}"
+msgstr "{0}をピン留め解除"
+
msgid "Unposted Documents"
msgstr "未転記書類"
@@ -14225,9 +14413,6 @@ msgstr "検証済み"
msgid "Validating job..."
msgstr "ジョブを検証中..."
-msgid "Valuation"
-msgstr "評価"
-
msgid "Value"
msgstr "値"
@@ -14653,6 +14838,9 @@ msgstr "Carbonに移行するときに何が変わるか、およびおおよそ
msgid "What data"
msgstr "どのデータ"
+msgid "What drove inventory up or down, by any dimension"
+msgstr "在庫の増減を駆動した要因(ディメンション別)"
+
msgid "What is {translatedTerm}?"
msgstr "{translatedTerm}とは何ですか?"
@@ -15049,6 +15237,9 @@ msgstr "資産の価値をその耐用年数にわたって削減する — 作
msgid "Year"
msgstr "年"
+msgid "Yearly"
+msgstr "年次"
+
msgid "Yes"
msgstr "はい"
diff --git a/packages/locale/locales/ko/erp.po b/packages/locale/locales/ko/erp.po
index 5b0ab3daa4..19a98d670d 100644
--- a/packages/locale/locales/ko/erp.po
+++ b/packages/locale/locales/ko/erp.po
@@ -48,6 +48,10 @@ msgstr "(이 고객에게는 제외됨)"
msgid "{0, plural, one {This part is on 1 open change notice} other {This part is on # open change notices}}"
msgstr "{0, plural, one {이 부품은 1개의 미완료 변경 공지에 포함되어 있습니다} other {이 부품은 #개의 미완료 변경 공지에 포함되어 있습니다}}"
+#. placeholder {0}: selectedAccountIds.length
+msgid "{0} accounts"
+msgstr "{0} 계정"
+
#. placeholder {0}: precise?.text
msgid "{0} ago"
msgstr "{0} 전"
@@ -163,6 +167,9 @@ msgstr "{years}년"
msgid "/month/user"
msgstr "/월/사용자"
+msgid "% of total"
+msgstr "총계의 %"
+
msgid "% of Total"
msgstr "전체의 %"
@@ -474,6 +481,9 @@ msgstr "계정"
msgid "Account & Details"
msgstr "계정 및 세부정보"
+msgid "Account balances with debits and credits"
+msgstr "차변과 대변이 포함된 계정 잔액"
+
msgid "Account for advance payments made before goods or services are received"
msgstr "재화나 서비스를 받기 전에 지급한 선급금 계정"
@@ -510,9 +520,15 @@ msgstr "회계"
msgid "Accounting"
msgstr "회계"
+msgid "Accounting is currently in beta. Request access to enable reporting, journal entries, accounting periods, fixed assets, and more."
+msgstr "회계는 현재 베타 버전입니다. 보고, 분개, 회계 기간, 고정 자산 등을 활성화하려면 액세스를 요청하세요."
+
msgid "Accounting is disabled"
msgstr "회계가 비활성화됨"
+msgid "Accounting is disabled for this company."
+msgstr "이 회사에서는 회계가 비활성화되어 있습니다."
+
msgid "Accounting is enabled"
msgstr "회계가 활성화됨"
@@ -853,6 +869,9 @@ msgstr "이후"
msgid "After (calculation method)"
msgstr "이후(계산 방법)"
+msgid "Aging"
+msgstr "연령 분석"
+
msgid "Agree on the scope"
msgstr "범위에 합의"
@@ -871,6 +890,9 @@ msgstr "전체"
msgid "All {total} phases are done. Nice work — your team is up and running."
msgstr "{total}단계가 모두 완료되었습니다. 수고하셨습니다 — 팀이 이제 정상 가동 중입니다."
+msgid "All accounts"
+msgstr "모든 계정"
+
msgid "All actions selected"
msgstr "모든 조치가 선택됨"
@@ -983,6 +1005,9 @@ msgstr "작업 센터의 작업 대기열에서 작업의 위치(현장이 작
msgid "An unexpected error occurred while connecting to Onshape. Try connecting again."
msgstr "Onshape에 연결하는 중 예기치 않은 오류가 발생했습니다. 다시 연결해 보세요."
+msgid "Analytics"
+msgstr "분석"
+
msgid "Anchors the Plan timeline to real dates. Leave blank for a relative, week-numbered timeline. Setting either one fills in the rest."
msgstr "계획 타임라인을 실제 날짜에 고정합니다. 비워두면 주 번호 기반의 상대적 타임라인이 됩니다. 둘 중 하나를 설정하면 나머지가 자동으로 채워집니다."
@@ -1026,6 +1051,9 @@ msgstr "모든 품목 유형"
msgid "Anything not explicitly listed in scope above"
msgstr "위 범위에 명시적으로 나열되지 않은 모든 사항"
+msgid "AP Aging"
+msgstr "AP 에이징"
+
msgid "AP Clerk"
msgstr "매입채무 담당자"
@@ -1138,6 +1166,9 @@ msgstr "AQL"
msgid "AQL (Z1.4 / ISO 2859-1)"
msgstr "AQL(Z1.4 / ISO 2859-1)"
+msgid "AR Aging"
+msgstr "AR 에이징"
+
msgid "AR Clerk"
msgstr "매출채권 담당자"
@@ -1245,6 +1276,11 @@ msgstr "{0}을(를) 삭제하시겠습니까? 이 작업은 되돌릴 수 없습
msgid "Are you sure you want to delete {name}? This cannot be undone."
msgstr "{name}을(를) 삭제하시겠습니까? 이 작업은 되돌릴 수 없습니다."
+#. placeholder {0}: activeView.name
+#. placeholder {0}: viewPendingDelete.name
+msgid "Are you sure you want to delete the \"{0}\" view? This cannot be undone."
+msgstr "정말로 \"{0}\" 보기를 삭제하시겠습니까? 이 작업은 실행 취소할 수 없습니다."
+
#. placeholder {0}: selectedCustomField?.name
msgid "Are you sure you want to delete the {0} field?"
msgstr "{0} 필드를 삭제하시겠습니까?"
@@ -1634,6 +1670,9 @@ msgstr "자산 ID"
msgid "Assets"
msgstr "자산"
+msgid "Assets, liabilities and equity as of a date"
+msgstr "특정 날짜 기준 자산, 부채 및 자본"
+
msgid "Assign printers to locations. Shipping, receiving, and work centers inherit the location default unless overridden."
msgstr "위치에 프린터를 배정하세요. 출하, 입고, 작업장은 재정의되지 않는 한 위치의 기본값을 상속받습니다."
@@ -1890,6 +1929,9 @@ msgstr "안전재고 미만"
msgid "Beta"
msgstr "베타"
+msgid "Biggest causes of scrap by reason, item, or work center"
+msgstr "이유, 품목 또는 작업 센터별 스크랩의 가장 큰 원인"
+
msgid "Bill of Material"
msgstr "자재명세서"
@@ -2020,12 +2062,18 @@ msgstr "{byUser}"
msgid "By accepting the invite, you agree to the <0>Terms of Service</0> and <1>Privacy Policy</1>."
msgstr "초대를 수락하면 <0>서비스 약관</0> 및 <1>개인정보 처리방침</1>에 동의하는 것으로 간주됩니다."
+msgid "By dimension"
+msgstr "차원별"
+
msgid "By Document Date"
msgstr "문서 날짜 기준"
msgid "By Due Date"
msgstr "만기일 기준"
+msgid "By field"
+msgstr "필드별"
+
msgid "By Item"
msgstr "항목별"
@@ -2383,6 +2431,9 @@ msgstr "검색어 지우기"
msgid "Clear search query"
msgstr "검색 쿼리 지우기"
+msgid "Clear selection"
+msgstr "선택 해제"
+
msgid "Clear this invoice with the party's posted credits as well as cash. Credits apply directly — no posting needed."
msgstr "이 인보이스를 현금뿐 아니라 거래처의 전기된 크레딧으로도 정리하세요. 크레딧은 별도 전기 없이 바로 적용됩니다."
@@ -2416,6 +2467,9 @@ msgstr "마감일"
msgid "Close Period"
msgstr "기간 종료"
+msgid "Close Reports"
+msgstr "보고서 닫기"
+
msgid "Close Status"
msgstr "종료 상태"
@@ -2464,6 +2518,12 @@ msgstr "셋업 접기"
msgid "Collapse subtree"
msgstr "하위 트리 접기"
+msgid "Column dimension"
+msgstr "열 차원"
+
+msgid "Column field"
+msgstr "열 필드"
+
msgid "Column visibility and order"
msgstr "열 표시 여부 및 순서"
@@ -2560,6 +2620,9 @@ msgstr "완료 바코드"
msgid "Completion Time"
msgstr "완료 시간"
+msgid "Condensed P&L with margins and key subtotals"
+msgstr "마진 및 주요 소계를 포함한 축약 손익계산"
+
msgid "Conditions"
msgstr "조건"
@@ -3041,6 +3104,9 @@ msgstr "매출원가(COGS)"
msgid "Cost of Goods Sold (default)"
msgstr "매출원가(기본값)"
+msgid "Cost of Sales"
+msgstr "매출원가"
+
msgid "Costing"
msgstr "원가 계산"
@@ -3852,6 +3918,10 @@ msgstr "다단계 자재명세서(BOM)와 공정(BOP)을 정의하세요(제작
msgid "Delete"
msgstr "삭제"
+#. placeholder {0}: view.name
+msgid "Delete {0}"
+msgstr "{0} 삭제"
+
msgid "Delete {name}"
msgstr "{name} 삭제"
@@ -4138,6 +4208,9 @@ msgstr "유형 삭제"
msgid "Delete Unit of Measure"
msgstr "측정 단위 삭제"
+msgid "Delete view"
+msgstr "보기 삭제"
+
msgid "Delete View"
msgstr "보기 삭제"
@@ -5241,6 +5314,9 @@ msgstr "인증 코드를 액세스 토큰으로 교환하지 못했습니다.
msgid "Excluded"
msgstr "제외됨"
+msgid "Executive P&L"
+msgstr "경영진 손익계산"
+
msgid "Exemption Certificate"
msgstr "면세 증명서"
@@ -5311,6 +5387,9 @@ msgstr "판매에 따라 재고가 출하/불출될 때 차변에 기록되는
msgid "Expense side of deferred tax movements (paired with deferred tax liability)."
msgstr "이연법인세 변동의 비용 측면(이연법인세부채와 짝을 이룸)입니다."
+msgid "Expenses"
+msgstr "비용"
+
msgid "Expert guidance"
msgstr "전문가 안내"
@@ -5803,6 +5882,9 @@ msgstr "확정"
msgid "Finalizing a fiscal month through the Open → Locked → Closed lifecycle; a closed period is frozen and its balances snapshotted, reversible only by explicit reopen."
msgstr "열림 → 잠김 → 종료 라이프사이클을 통해 회계 월을 마무리하는 것으로서, 종료된 기간은 고정되고 잔액은 스냅샷되며 명시적 재개를 통해서만 취소할 수 있습니다."
+msgid "Financial Statements"
+msgstr "재무제표"
+
msgid "finish"
msgstr "마감"
@@ -6263,9 +6345,15 @@ msgstr "등급"
msgid "Grades"
msgstr "등급"
+msgid "Gross Profit"
+msgstr "매출총이익"
+
msgid "Group"
msgstr "그룹"
+msgid "Group by"
+msgstr "그룹화 기준"
+
msgid "Group Members"
msgstr "그룹 구성원"
@@ -6621,6 +6709,9 @@ msgstr "손익/재무상태(상속됨)"
msgid "Income Statement"
msgstr "손익계산서"
+msgid "Income Tax"
+msgstr "소득세"
+
msgid "Income/Balance"
msgstr "손익/재무상태"
@@ -7166,6 +7257,9 @@ msgstr "노무 단위"
msgid "Language"
msgstr "언어"
+msgid "Last 6 Months"
+msgstr "지난 6개월"
+
msgid "Last Calibration"
msgstr "마지막 교정"
@@ -7962,6 +8056,9 @@ msgstr "귀사가 받아야 할 금액"
msgid "Money you owe"
msgstr "귀사가 지급해야 할 금액"
+msgid "Monthly"
+msgstr "월간"
+
msgid "Months over which this asset depreciates for tax purposes (when not using MACRS)."
msgstr "MACRS를 사용하지 않을 경우, 이 자산을 세무상 상각하는 개월 수입니다."
@@ -8075,6 +8172,9 @@ msgstr "순 장부 가치"
msgid "Net Change"
msgstr "순변동"
+msgid "Net Income"
+msgstr "순이익"
+
msgid "Never"
msgstr "안 함"
@@ -8567,6 +8667,9 @@ msgstr "품목 없음"
msgid "No items have inventory activity here yet."
msgstr "아직 여기에 재고 활동이 있는 항목이 없습니다."
+msgid "No journal lines in scope for this period"
+msgstr "이 기간에 대한 범위 내 분개선이 없습니다"
+
msgid "No lines to map"
msgstr "매핑할 라인이 없습니다"
@@ -8666,6 +8769,9 @@ msgstr "프로세스를 선택하지 않았습니다"
msgid "No production events recorded for this operation yet"
msgstr "이 공정작업에 대해 아직 기록된 생산 이벤트가 없습니다"
+msgid "No purchases in this period"
+msgstr "이 기간에 구매가 없습니다"
+
msgid "No Quote"
msgstr "견적 없음"
@@ -8684,6 +8790,9 @@ msgstr "참조 이미지 없음"
msgid "No remaining entities to inspect."
msgstr "검사할 개체가 남아 있지 않습니다."
+msgid "No reports match your search."
+msgstr "검색 결과와 일치하는 보고서가 없습니다."
+
msgid "No results"
msgstr "결과 없음"
@@ -8904,6 +9013,9 @@ msgstr "이 위치에서 서비스용으로 유지해야 할 최소 보유 재
msgid "On-hand inventory remains"
msgstr "보유 재고가 남아 있습니다"
+msgid "On-hand value by location or item, with GL tie-out"
+msgstr "GL 검증이 포함된 위치 또는 항목별 현재고 가치"
+
msgid "On-hand value of manufactured goods (Make items)"
msgstr "제조 상품(완성품)의 현재 재고 가치"
@@ -9009,6 +9121,9 @@ msgstr "미결 작업"
msgid "Open menu"
msgstr "메뉴 열기"
+msgid "Open payables by supplier and age"
+msgstr "공급자 및 기간별 미지급금"
+
msgid "Open Purchase Invoices"
msgstr "미결 구매 인보이스"
@@ -9024,6 +9139,9 @@ msgstr "미결 견적"
msgid "Open Reactive"
msgstr "미결 반응형 정비"
+msgid "Open receivables by customer and age"
+msgstr "고객 및 기간별 미수금"
+
msgid "Open RFQs"
msgstr "미결 견적요청"
@@ -9057,6 +9175,9 @@ msgstr "이 자산이 Carbon에 등록되기 전에 이미 계상된 감가상
msgid "Operating Expenses"
msgstr "영업비용"
+msgid "Operating Income"
+msgstr "영업이익"
+
msgid "Operation"
msgstr "공정작업"
@@ -9172,6 +9293,12 @@ msgstr "원본"
msgid "Original Count"
msgstr "원본 계산"
+msgid "Other Expense"
+msgstr "기타 비용"
+
+msgid "Other Income"
+msgstr "기타 수익"
+
msgid "Other Income account for FX gains when a payment settles a foreign-currency invoice at a more favorable rate"
msgstr "외화 인보이스가 더 유리한 환율로 결제될 때 발생하는 환차익에 대한 기타수익 계정"
@@ -9557,6 +9684,11 @@ msgstr "개/분"
msgid "Pin"
msgstr "핀"
+#. placeholder {0}: report.name
+#. placeholder {0}: view.name
+msgid "Pin {0}"
+msgstr "{0} 고정"
+
msgid "Pinned"
msgstr "고정됨"
@@ -10083,6 +10215,9 @@ msgstr "구매 단위:"
msgid "Purchased"
msgstr "구매됨"
+msgid "Purchases"
+msgstr "구매"
+
msgid "purchasing"
msgstr "구매"
@@ -10211,6 +10346,9 @@ msgstr "이 재정의에 대한 수량 기반 가격 등급으로, 주문 라인
msgid "Quantity: {0}"
msgstr "수량: {0}"
+msgid "Quarterly"
+msgstr "분기별"
+
msgid "Question"
msgstr "질문"
@@ -10678,6 +10816,9 @@ msgstr "보충 시스템"
msgid "Report"
msgstr "보고서"
+msgid "Reporting"
+msgstr "보고"
+
msgid "Reporting dimension"
msgstr "보고 차원"
@@ -10687,6 +10828,9 @@ msgstr "보고서"
msgid "Reprint"
msgstr "재출력"
+msgid "Request access"
+msgstr "액세스 요청"
+
msgid "Request Approval"
msgstr "승인 요청"
@@ -10821,6 +10965,12 @@ msgstr "미사용 선택 재료 반환 중"
msgid "Rev {revision}"
msgstr "Rev {revision}"
+msgid "Revenue"
+msgstr "수익"
+
+msgid "Revenue and expenses over a period"
+msgstr "일정 기간의 수익 및 비용"
+
msgid "Reverse all inventory adjustments"
msgstr "모든 재고 조정 취소"
@@ -11153,9 +11303,15 @@ msgstr "연락처 저장"
msgid "Save Method"
msgstr "저장 방법"
+msgid "Save view"
+msgstr "보기 저장"
+
msgid "Save View"
msgstr "보기 저장"
+msgid "Saved Views"
+msgstr "저장된 보기"
+
msgid "Saving..."
msgstr "저장 중..."
@@ -11868,6 +12024,15 @@ msgstr "동기화 옵션 표시"
msgid "Showing {0} of {totalCount} — refine your search"
msgstr "{0}개/총 {totalCount}개 표시 — 검색 범위 좁혀보기"
+msgid "Showing in {parentCurrency}"
+msgstr "{parentCurrency}로 표시"
+
+msgid "Showing the first 500 lines"
+msgstr "처음 500줄을 표시하고 있습니다"
+
+msgid "Showing the top 1,000 groups by amount"
+msgstr "금액별 상위 1,000개 그룹을 표시하고 있습니다"
+
msgid "Shown as a faint background behind every page of generated PDFs"
msgstr "생성된 PDF의 모든 페이지 배경에 옅게 표시됩니다"
@@ -11937,6 +12102,15 @@ msgstr "건너뜀"
msgid "Slack"
msgstr "Slack"
+msgid "Slice asset activity by location, item, or any dimension"
+msgstr "위치, 품목 또는 모든 차원별 자산 활동 분석"
+
+msgid "Slice expenses by location, cost center, or any dimension"
+msgstr "위치, 비용 센터 또는 모든 차원별 비용 분석"
+
+msgid "Slice revenue by customer, customer type, or any dimension"
+msgstr "고객, 고객 유형 또는 모든 차원별 수익 분석"
+
msgid "Smoke-test the core daily flows end to end"
msgstr "핵심 일일 업무 흐름을 처음부터 끝까지 스모크 테스트하세요"
@@ -12018,6 +12192,9 @@ msgstr "특정 고객"
msgid "Specific Items"
msgstr "특정 품목"
+msgid "Spend by supplier, item, or category — your biggest cost drivers"
+msgstr "공급업체, 품목 또는 카테고리별 지출 — 가장 큰 비용 동인"
+
msgid "Split"
msgstr "분할"
@@ -13343,6 +13520,9 @@ msgstr "테마"
msgid "Theme Color"
msgstr "테마 색상"
+msgid "Then by"
+msgstr "그 다음"
+
msgid "There are no active supplier quotes to compare for this RFQ."
msgstr "이 RFQ와 비교할 활성 공급업체 견적이 없습니다."
@@ -13585,6 +13765,9 @@ msgstr "시간대"
msgid "Title"
msgstr "제목"
+msgid "To Date"
+msgstr "마감일"
+
msgid "To deactivate, use the row menu and choose Deactivate Account."
msgstr "비활성화하려면 행 메뉴를 사용하여 계정 비활성화를 선택하세요."
@@ -13976,6 +14159,11 @@ msgstr "피킹 취소"
msgid "Unpick {0}"
msgstr "{0} 피킹 취소"
+#. placeholder {0}: report.name
+#. placeholder {0}: view.name
+msgid "Unpin {0}"
+msgstr "{0} 고정 해제"
+
msgid "Unposted Documents"
msgstr "미전기 문서"
@@ -14225,9 +14413,6 @@ msgstr "검증됨"
msgid "Validating job..."
msgstr "작업 검증 중..."
-msgid "Valuation"
-msgstr "평가"
-
msgid "Value"
msgstr "값"
@@ -14653,6 +14838,9 @@ msgstr "Carbon으로 전환하면 무엇이 달라지고 그 가치는 대략
msgid "What data"
msgstr "어떤 데이터"
+msgid "What drove inventory up or down, by any dimension"
+msgstr "모든 차원별 재고를 높이거나 낮춘 요인"
+
msgid "What is {translatedTerm}?"
msgstr "{translatedTerm}란 무엇인가요?"
@@ -15049,6 +15237,9 @@ msgstr "자산의 가치를 내용연수에 걸쳐 상각하는 것 — 매월
msgid "Year"
msgstr "연도"
+msgid "Yearly"
+msgstr "연간"
+
msgid "Yes"
msgstr "예"
diff --git a/packages/locale/locales/pl/erp.po b/packages/locale/locales/pl/erp.po
index e8c2443731..16eda92e60 100644
--- a/packages/locale/locales/pl/erp.po
+++ b/packages/locale/locales/pl/erp.po
@@ -48,6 +48,10 @@ msgstr "(wykluczone dla tego klienta)"
msgid "{0, plural, one {This part is on 1 open change notice} other {This part is on # open change notices}}"
msgstr "{0, plural, one {Ta część znajduje się na 1 otwartym zgłoszeniu zmian} other {Ta część znajduje się na # otwartych zgłoszeniach zmian}}"
+#. placeholder {0}: selectedAccountIds.length
+msgid "{0} accounts"
+msgstr "{0} konta"
+
#. placeholder {0}: precise?.text
msgid "{0} ago"
msgstr "{0} temu"
@@ -163,6 +167,9 @@ msgstr "{years}r"
msgid "/month/user"
msgstr "/miesiąc/użytkownik"
+msgid "% of total"
+msgstr "% całości"
+
msgid "% of Total"
msgstr "% całości"
@@ -474,6 +481,9 @@ msgstr "Konto"
msgid "Account & Details"
msgstr "Konto i szczegóły"
+msgid "Account balances with debits and credits"
+msgstr "Salda kont z debetami i kredytami"
+
msgid "Account for advance payments made before goods or services are received"
msgstr "Rozliczaj zaliczki dokonane przed otrzymaniem towarów lub usług."
@@ -510,9 +520,15 @@ msgstr "rachunkowość"
msgid "Accounting"
msgstr "Rachunkowość"
+msgid "Accounting is currently in beta. Request access to enable reporting, journal entries, accounting periods, fixed assets, and more."
+msgstr "Rachunkowość jest obecnie w fazie beta. Poproś o dostęp, aby włączyć raportowanie, wpisy dziennika, okresy rachunkowe, aktywa trwałe i wiele więcej."
+
msgid "Accounting is disabled"
msgstr "Rachunkowość jest wyłączona"
+msgid "Accounting is disabled for this company."
+msgstr "Rachunkowość jest wyłączona dla tej firmy."
+
msgid "Accounting is enabled"
msgstr "Rachunkowość jest włączona"
@@ -853,6 +869,9 @@ msgstr "Po"
msgid "After (calculation method)"
msgstr "Po (metoda obliczenia)"
+msgid "Aging"
+msgstr "Wiekowanie"
+
msgid "Agree on the scope"
msgstr "Uzgodnij zakres"
@@ -871,6 +890,9 @@ msgstr "Wszystko"
msgid "All {total} phases are done. Nice work — your team is up and running."
msgstr "Wszystkie {total} fazy są gotowe. Świetna robota — Twój zespół jest już w pełni operacyjny."
+msgid "All accounts"
+msgstr "Wszystkie konta"
+
msgid "All actions selected"
msgstr "Wszystkie akcje zaznaczone"
@@ -983,6 +1005,9 @@ msgstr "Pozycja operacji w kolejce jej centrum pracy — kolejność, w której
msgid "An unexpected error occurred while connecting to Onshape. Try connecting again."
msgstr "Podczas łączenia z Onshape wystąpił nieoczekiwany błąd. Spróbuj połączyć się ponownie."
+msgid "Analytics"
+msgstr "Analityka"
+
msgid "Anchors the Plan timeline to real dates. Leave blank for a relative, week-numbered timeline. Setting either one fills in the rest."
msgstr "Zakotwicza oś czasu Planu do rzeczywistych dat. Pozostaw puste, aby uzyskać względną oś czasu z numerami tygodni. Ustawienie jednej z nich wypełni resztę."
@@ -1026,6 +1051,9 @@ msgstr "Dowolny typ przedmiotu"
msgid "Anything not explicitly listed in scope above"
msgstr "Wszystko, co nie jest wyraźnie wymienione w zakresie powyżej"
+msgid "AP Aging"
+msgstr "Wiekowanie zobowiązań"
+
msgid "AP Clerk"
msgstr "Pracownik ds. zobowiązań"
@@ -1138,6 +1166,9 @@ msgstr "AQL"
msgid "AQL (Z1.4 / ISO 2859-1)"
msgstr "AQL (Z1.4 / ISO 2859-1)"
+msgid "AR Aging"
+msgstr "Wiekowanie należności"
+
msgid "AR Clerk"
msgstr "Pracownik ds. rozrachunków z odbiorcami"
@@ -1245,6 +1276,11 @@ msgstr "Czy na pewno chcesz usunąć {0}? Tej operacji nie można cofnąć."
msgid "Are you sure you want to delete {name}? This cannot be undone."
msgstr "Czy na pewno chcesz usunąć {name}? Tej operacji nie można cofnąć."
+#. placeholder {0}: activeView.name
+#. placeholder {0}: viewPendingDelete.name
+msgid "Are you sure you want to delete the \"{0}\" view? This cannot be undone."
+msgstr "Czy na pewno chcesz usunąć widok \"{0}\"? Tej czynności nie można cofnąć."
+
#. placeholder {0}: selectedCustomField?.name
msgid "Are you sure you want to delete the {0} field?"
msgstr "Czy na pewno chcesz usunąć pole {0}?"
@@ -1634,6 +1670,9 @@ msgstr "ID aktywu"
msgid "Assets"
msgstr "Aktywa"
+msgid "Assets, liabilities and equity as of a date"
+msgstr "Aktywa, pasywa i kapitał na dzień"
+
msgid "Assign printers to locations. Shipping, receiving, and work centers inherit the location default unless overridden."
msgstr "Przypisz drukarki do lokalizacji. Wysyłka, odbiór i centra pracy dziedziczą domyślne ustawienia lokalizacji, chyba że zostaną zastąpione."
@@ -1890,6 +1929,9 @@ msgstr "Poniżej zapasu bezpieczeństwa"
msgid "Beta"
msgstr "Beta"
+msgid "Biggest causes of scrap by reason, item, or work center"
+msgstr "Największe przyczyny odpadów wg przyczyny, pozycji lub centrum pracy"
+
msgid "Bill of Material"
msgstr "Zestawienie Materiałów"
@@ -2020,12 +2062,18 @@ msgstr "przez {byUser}"
msgid "By accepting the invite, you agree to the <0>Terms of Service</0> and <1>Privacy Policy</1>."
msgstr "Akceptując zaproszenie, zgadzasz się na <0>Warunki Usługi</0> i <1>Politykę Prywatności</1>."
+msgid "By dimension"
+msgstr "Wg wymiaru"
+
msgid "By Document Date"
msgstr "Według daty dokumentu"
msgid "By Due Date"
msgstr "Według daty wymagalności"
+msgid "By field"
+msgstr "Według pola"
+
msgid "By Item"
msgstr "Wg pozycji"
@@ -2383,6 +2431,9 @@ msgstr "Wyczyść wyszukiwanie"
msgid "Clear search query"
msgstr "Wyczyść zapytanie wyszukiwania"
+msgid "Clear selection"
+msgstr "Wyczyść zaznaczenie"
+
msgid "Clear this invoice with the party's posted credits as well as cash. Credits apply directly — no posting needed."
msgstr "Wyczyść tę fakturę za pomocą zaksięgowanych kredytów strony oraz gotówki. Kredyty są stosowane bezpośrednio — nie jest wymagane żadne zaksięgowanie."
@@ -2416,6 +2467,9 @@ msgstr "Data zamknięcia"
msgid "Close Period"
msgstr "Zamknij Okres"
+msgid "Close Reports"
+msgstr "Zamknij raporty"
+
msgid "Close Status"
msgstr "Status Zamknięcia"
@@ -2464,6 +2518,12 @@ msgstr "Zwiń Setup"
msgid "Collapse subtree"
msgstr "Zwiń poddrzewo"
+msgid "Column dimension"
+msgstr "Wymiar kolumny"
+
+msgid "Column field"
+msgstr "Pole kolumny"
+
msgid "Column visibility and order"
msgstr "Widoczność i kolejność kolumn"
@@ -2560,6 +2620,9 @@ msgstr "Kod kreskowy ukończenia"
msgid "Completion Time"
msgstr "Czas ukończenia"
+msgid "Condensed P&L with margins and key subtotals"
+msgstr "Skrócone rachunki zysków i strat z marżami i kluczowymi subtotalami"
+
msgid "Conditions"
msgstr "Warunki"
@@ -3041,6 +3104,9 @@ msgstr "Koszt Sprzedanych Towarów (COGS)"
msgid "Cost of Goods Sold (default)"
msgstr "Koszt Sprzedanych Towarów (domyślny)"
+msgid "Cost of Sales"
+msgstr "Koszt sprzedaży"
+
msgid "Costing"
msgstr "Wycena"
@@ -3852,6 +3918,10 @@ msgstr "Definiuj wielopoziomowe BOM i Bill of Process (metody produkcji)"
msgid "Delete"
msgstr "Usuń"
+#. placeholder {0}: view.name
+msgid "Delete {0}"
+msgstr "Usuń {0}"
+
msgid "Delete {name}"
msgstr "Usuń {name}"
@@ -4138,6 +4208,9 @@ msgstr "Usuń typ"
msgid "Delete Unit of Measure"
msgstr "Usuń jednostkę miary"
+msgid "Delete view"
+msgstr "Usuń widok"
+
msgid "Delete View"
msgstr "Usuń widok"
@@ -5241,6 +5314,9 @@ msgstr "Wymiana kodu autoryzacji na token dostępu nie udała się. Spróbuj po
msgid "Excluded"
msgstr "Wykluczone"
+msgid "Executive P&L"
+msgstr "Rachunek zysków i strat dla kierownictwa"
+
msgid "Exemption Certificate"
msgstr "Certifikat Zwolnienia"
@@ -5311,6 +5387,9 @@ msgstr "Strona wydatków ruchu podatku odroczonego (sparowany z zobowiązaniem z
msgid "Expense side of deferred tax movements (paired with deferred tax liability)."
msgstr "Nie udało się utworzyć klasy zasobu: {0}"
+msgid "Expenses"
+msgstr "Wydatki"
+
msgid "Expert guidance"
msgstr "Fachowe wskazówki"
@@ -5803,6 +5882,9 @@ msgstr "Sfinalizuj"
msgid "Finalizing a fiscal month through the Open → Locked → Closed lifecycle; a closed period is frozen and its balances snapshotted, reversible only by explicit reopen."
msgstr "Finalizowanie miesiąca obrachunkowego przez cykl życia Otwarte → Zablokowane → Zamknięte; zamknięty okres jest zamrożony i jego salda są zdjęte, odwracalne tylko przez jawne ponowne otwarcie."
+msgid "Financial Statements"
+msgstr "Sprawozdania finansowe"
+
msgid "finish"
msgstr "Wyroby gotowe"
@@ -6263,9 +6345,15 @@ msgstr "stopnie"
msgid "Grades"
msgstr "Gatunki"
+msgid "Gross Profit"
+msgstr "Zysk brutto"
+
msgid "Group"
msgstr "Grupa"
+msgid "Group by"
+msgstr "Grupuj wg"
+
msgid "Group Members"
msgstr "Członkowie grupy"
@@ -6621,6 +6709,9 @@ msgstr "Dochód / Saldo (odziedziczone)"
msgid "Income Statement"
msgstr "Rachunek zysków i strat"
+msgid "Income Tax"
+msgstr "Podatek dochodowy"
+
msgid "Income/Balance"
msgstr "Dochód/Saldo"
@@ -7166,6 +7257,9 @@ msgstr "Jednostka pracy"
msgid "Language"
msgstr "Język"
+msgid "Last 6 Months"
+msgstr "Ostatnie 6 miesięcy"
+
msgid "Last Calibration"
msgstr "Ostatnia Kalibracja"
@@ -7962,6 +8056,9 @@ msgstr "Pieniądze należne Tobie"
msgid "Money you owe"
msgstr "Pieniądze, które jesteś winien"
+msgid "Monthly"
+msgstr "Miesięcznie"
+
msgid "Months over which this asset depreciates for tax purposes (when not using MACRS)."
msgstr "Miesiące, przez które ten składnik aktywów jest amortyzowany dla celów podatkowych (jeśli nie jest używany MACRS)."
@@ -8075,6 +8172,9 @@ msgstr "Wartość netto w księgach"
msgid "Net Change"
msgstr "Zmiana netto"
+msgid "Net Income"
+msgstr "Dochód netto"
+
msgid "Never"
msgstr "Nigdy"
@@ -8567,6 +8667,9 @@ msgstr "Brak artykułów"
msgid "No items have inventory activity here yet."
msgstr "Brak aktywności magazynowej tutaj."
+msgid "No journal lines in scope for this period"
+msgstr "Brak wierszy dziennika w zakresie dla tego okresu"
+
msgid "No lines to map"
msgstr "Brak linii do mapowania"
@@ -8666,6 +8769,9 @@ msgstr "Nie wybrano procesu"
msgid "No production events recorded for this operation yet"
msgstr "Brak zarejestrowanych zdarzeń produkcyjnych dla tej operacji"
+msgid "No purchases in this period"
+msgstr "Brak zakupów w tym okresie"
+
msgid "No Quote"
msgstr "Brak oferty"
@@ -8684,6 +8790,9 @@ msgstr "Brak obrazu referencyjnego"
msgid "No remaining entities to inspect."
msgstr "Brak pozostałych jednostek do sprawdzenia."
+msgid "No reports match your search."
+msgstr "Brak raportów pasujących do wyszukiwania."
+
msgid "No results"
msgstr "Brak wyników"
@@ -8904,6 +9013,9 @@ msgstr "Minimalna ilość do utrzymania na potrzeby serwisu w tej lokalizacji"
msgid "On-hand inventory remains"
msgstr "Pozostały zapas w magazynie"
+msgid "On-hand value by location or item, with GL tie-out"
+msgstr "Wartość dostępna według lokalizacji lub pozycji, z powiązaniem do księgi głównej"
+
msgid "On-hand value of manufactured goods (Make items)"
msgstr "Wartość dostępna wyrobów wytworzonych (Pozycje produkcyjne)"
@@ -9009,6 +9121,9 @@ msgstr "Otwarte zadania"
msgid "Open menu"
msgstr "Otwórz menu"
+msgid "Open payables by supplier and age"
+msgstr "Otwarte zobowiązania wg dostawcy i wieku"
+
msgid "Open Purchase Invoices"
msgstr "Otwarte faktury zakupu"
@@ -9024,6 +9139,9 @@ msgstr "Otwarte Oferty"
msgid "Open Reactive"
msgstr "Otwarte reaktywne"
+msgid "Open receivables by customer and age"
+msgstr "Otwarte należności wg odbiorcy i wieku"
+
msgid "Open RFQs"
msgstr "Otwarte Zapytania Ofertowe"
@@ -9057,6 +9175,9 @@ msgstr "Saldo otwarcia amortyzacji już zaksięgowanej przed dodaniem tego zasob
msgid "Operating Expenses"
msgstr "Koszty Operacyjne"
+msgid "Operating Income"
+msgstr "Dochód z działalności operacyjnej"
+
msgid "Operation"
msgstr "Operacja"
@@ -9172,6 +9293,12 @@ msgstr "Oryginalne"
msgid "Original Count"
msgstr "Oryginalne Liczenie"
+msgid "Other Expense"
+msgstr "Inne wydatki"
+
+msgid "Other Income"
+msgstr "Inne przychody"
+
msgid "Other Income account for FX gains when a payment settles a foreign-currency invoice at a more favorable rate"
msgstr "Konto dochodów pozostałych dla zysków walutowych, gdy płatność rozlicza fakturę w walucie obcej po kursie bardziej korzystnym"
@@ -9557,6 +9684,11 @@ msgstr "Sztuk/Minutę"
msgid "Pin"
msgstr "Przypnij"
+#. placeholder {0}: report.name
+#. placeholder {0}: view.name
+msgid "Pin {0}"
+msgstr "Przypnij {0}"
+
msgid "Pinned"
msgstr "Przypięte"
@@ -10083,6 +10215,9 @@ msgstr "Jednostka zakupu:"
msgid "Purchased"
msgstr "Zakupione"
+msgid "Purchases"
+msgstr "Zakupy"
+
msgid "purchasing"
msgstr "Zakupy i Koszt Sprzedanych Towarów"
@@ -10211,6 +10346,9 @@ msgstr "Poziomy cen oparte na ilości dla tego zastąpienia; zastosowana cena je
msgid "Quantity: {0}"
msgstr "Ilość: {0}"
+msgid "Quarterly"
+msgstr "Kwartalnie"
+
msgid "Question"
msgstr "Pytanie"
@@ -10678,6 +10816,9 @@ msgstr "System uzupełniania zapasów"
msgid "Report"
msgstr "Raport"
+msgid "Reporting"
+msgstr "Raportowanie"
+
msgid "Reporting dimension"
msgstr "Wymiar raportowania"
@@ -10687,6 +10828,9 @@ msgstr "Raporty"
msgid "Reprint"
msgstr "Wydruk ponownie"
+msgid "Request access"
+msgstr "Poproś o dostęp"
+
msgid "Request Approval"
msgstr "Poproś o zatwierdzenie"
@@ -10821,6 +10965,12 @@ msgstr "Zwracanie nieużywanego pobranego materiału"
msgid "Rev {revision}"
msgstr "Wer. {revision}"
+msgid "Revenue"
+msgstr "Przychody"
+
+msgid "Revenue and expenses over a period"
+msgstr "Przychody i wydatki w danym okresie"
+
msgid "Reverse all inventory adjustments"
msgstr "Odwróć wszystkie korekty zapasów"
@@ -11153,9 +11303,15 @@ msgstr "Zapisz kontakty"
msgid "Save Method"
msgstr "Zapisz metodę"
+msgid "Save view"
+msgstr "Zapisz widok"
+
msgid "Save View"
msgstr "Zapisz Widok"
+msgid "Saved Views"
+msgstr "Zapisane widoki"
+
msgid "Saving..."
msgstr "Zapisywanie..."
@@ -11868,6 +12024,15 @@ msgstr "Pokaż opcje synchronizacji"
msgid "Showing {0} of {totalCount} — refine your search"
msgstr "Wyświetlanie {0} z {totalCount} — uściśl wyszukiwanie"
+msgid "Showing in {parentCurrency}"
+msgstr "Wyświetlanie w {parentCurrency}"
+
+msgid "Showing the first 500 lines"
+msgstr "Pokazywanie pierwszych 500 linii"
+
+msgid "Showing the top 1,000 groups by amount"
+msgstr "Pokazywanie 1000 najlepszych grup wg kwoty"
+
msgid "Shown as a faint background behind every page of generated PDFs"
msgstr "Wyświetlany jako delikatne tło za każdą stroną wygenerowanych plików PDF"
@@ -11937,6 +12102,15 @@ msgstr "Pominięte"
msgid "Slack"
msgstr "Slack"
+msgid "Slice asset activity by location, item, or any dimension"
+msgstr "Podziel aktywność aktywów według lokalizacji, pozycji lub dowolnego wymiaru"
+
+msgid "Slice expenses by location, cost center, or any dimension"
+msgstr "Podziel wydatki według lokalizacji, centrum kosztów lub dowolnego wymiaru"
+
+msgid "Slice revenue by customer, customer type, or any dimension"
+msgstr "Podziel przychody wg klienta, typu klienta lub dowolnego wymiaru"
+
msgid "Smoke-test the core daily flows end to end"
msgstr "Smoke-test podstawowych codziennych przepływów od końca do końca"
@@ -12018,6 +12192,9 @@ msgstr "Konkretni klienci"
msgid "Specific Items"
msgstr "Określone artykuły"
+msgid "Spend by supplier, item, or category — your biggest cost drivers"
+msgstr "Wydatki według dostawcy, pozycji lub kategorii — Twoje największe czynniki kosztowe"
+
msgid "Split"
msgstr "Podziel"
@@ -13343,6 +13520,9 @@ msgstr "Motyw"
msgid "Theme Color"
msgstr "Kolor motywu"
+msgid "Then by"
+msgstr "Następnie wg"
+
msgid "There are no active supplier quotes to compare for this RFQ."
msgstr "Brak aktywnych ofert dostawców do porównania dla tego zapytania ofertowego."
@@ -13585,6 +13765,9 @@ msgstr "Strefa czasowa"
msgid "Title"
msgstr "Tytuł"
+msgid "To Date"
+msgstr "Do dnia"
+
msgid "To deactivate, use the row menu and choose Deactivate Account."
msgstr "Aby dezaktywować, użyj menu wiersza i wybierz Deaktywuj konto."
@@ -13976,6 +14159,11 @@ msgstr "Cofnij pobranie"
msgid "Unpick {0}"
msgstr "Cofnij {0}"
+#. placeholder {0}: report.name
+#. placeholder {0}: view.name
+msgid "Unpin {0}"
+msgstr "Odepnij {0}"
+
msgid "Unposted Documents"
msgstr "Nieopublikowane dokumenty"
@@ -14225,9 +14413,6 @@ msgstr "Zweryfikowane"
msgid "Validating job..."
msgstr "Walidacja zadania..."
-msgid "Valuation"
-msgstr "Wycena"
-
msgid "Value"
msgstr "Wartość"
@@ -14653,6 +14838,9 @@ msgstr "Co się zmienia, gdy przechodzisz na Carbon i mniej więcej ile to warte
msgid "What data"
msgstr "Jakie dane"
+msgid "What drove inventory up or down, by any dimension"
+msgstr "Co spowodowało wzrost lub spadek zapasów, wg dowolnego wymiaru"
+
msgid "What is {translatedTerm}?"
msgstr "Co to jest {translatedTerm}?"
@@ -15049,6 +15237,9 @@ msgstr "Zmniejszanie wartości składnika aktywów w trakcie jego użyteczności
msgid "Year"
msgstr "Rok"
+msgid "Yearly"
+msgstr "Rocznie"
+
msgid "Yes"
msgstr "Tak"
diff --git a/packages/locale/locales/pt/erp.po b/packages/locale/locales/pt/erp.po
index 05af748b29..33cce34bbf 100644
--- a/packages/locale/locales/pt/erp.po
+++ b/packages/locale/locales/pt/erp.po
@@ -48,6 +48,10 @@ msgstr "(excluído para este cliente)"
msgid "{0, plural, one {This part is on 1 open change notice} other {This part is on # open change notices}}"
msgstr "{0, plural, one {Esta parte está em 1 aviso de mudança aberto} other {Esta parte está em # avisos de mudança abertos}}"
+#. placeholder {0}: selectedAccountIds.length
+msgid "{0} accounts"
+msgstr "{0} contas"
+
#. placeholder {0}: precise?.text
msgid "{0} ago"
msgstr "{0} atrás"
@@ -163,6 +167,9 @@ msgstr "{years}ano"
msgid "/month/user"
msgstr "/mês/utilizador"
+msgid "% of total"
+msgstr "% do total"
+
msgid "% of Total"
msgstr "% do Total"
@@ -474,6 +481,9 @@ msgstr "Conta"
msgid "Account & Details"
msgstr "Conta e detalhes"
+msgid "Account balances with debits and credits"
+msgstr "Saldos de contas com débitos e créditos"
+
msgid "Account for advance payments made before goods or services are received"
msgstr "Contabilizar os pagamentos antecipados realizados antes do recebimento de bens ou serviços."
@@ -510,9 +520,15 @@ msgstr "contabilidade"
msgid "Accounting"
msgstr "Contabilidade"
+msgid "Accounting is currently in beta. Request access to enable reporting, journal entries, accounting periods, fixed assets, and more."
+msgstr "A contabilidade está atualmente em beta. Solicite acesso para habilitar relatórios, lançamentos contábeis, períodos contábeis, ativos fixos e muito mais."
+
msgid "Accounting is disabled"
msgstr "A contabilidade está desativada"
+msgid "Accounting is disabled for this company."
+msgstr "A contabilidade está desabilitada para esta empresa."
+
msgid "Accounting is enabled"
msgstr "Contabilidade está ativada"
@@ -853,6 +869,9 @@ msgstr "Após"
msgid "After (calculation method)"
msgstr "Depois (método de cálculo)"
+msgid "Aging"
+msgstr "Envelhecimento"
+
msgid "Agree on the scope"
msgstr "Concordar sobre o escopo"
@@ -871,6 +890,9 @@ msgstr "Todos"
msgid "All {total} phases are done. Nice work — your team is up and running."
msgstr "Todas as {total} fases estão concluídas. Excelente trabalho — sua equipe está funcionando."
+msgid "All accounts"
+msgstr "Todas as contas"
+
msgid "All actions selected"
msgstr "Todas as ações selecionadas"
@@ -983,6 +1005,9 @@ msgstr "A posição de uma operação na fila de seu centro de trabalho — a or
msgid "An unexpected error occurred while connecting to Onshape. Try connecting again."
msgstr "Ocorreu um erro inesperado ao conectar ao Onshape. Tente conectar novamente."
+msgid "Analytics"
+msgstr "Análises"
+
msgid "Anchors the Plan timeline to real dates. Leave blank for a relative, week-numbered timeline. Setting either one fills in the rest."
msgstr "Ancora a cronologia do Plano em datas reais. Deixe em branco para uma cronologia relativa, numerada por semanas. Definir qualquer uma delas preenche o resto."
@@ -1026,6 +1051,9 @@ msgstr "Qualquer tipo de item"
msgid "Anything not explicitly listed in scope above"
msgstr "Qualquer coisa não explicitamente listada no escopo acima"
+msgid "AP Aging"
+msgstr "Envelhecimento de Contas a Pagar"
+
msgid "AP Clerk"
msgstr "Assistente de Contas a Pagar"
@@ -1138,6 +1166,9 @@ msgstr "AQL"
msgid "AQL (Z1.4 / ISO 2859-1)"
msgstr "AQL (Z1.4 / ISO 2859-1)"
+msgid "AR Aging"
+msgstr "Envelhecimento de Contas a Receber"
+
msgid "AR Clerk"
msgstr "Funcionário de Contas a Receber"
@@ -1245,6 +1276,11 @@ msgstr "Tem a certeza de que deseja eliminar {0}? Esta ação não pode ser desf
msgid "Are you sure you want to delete {name}? This cannot be undone."
msgstr "Tem a certeza de que deseja eliminar {name}? Esta ação não pode ser desfeita."
+#. placeholder {0}: activeView.name
+#. placeholder {0}: viewPendingDelete.name
+msgid "Are you sure you want to delete the \"{0}\" view? This cannot be undone."
+msgstr "Tem certeza de que deseja excluir a visualização \"{0}\"? Isto não pode ser desfeito."
+
#. placeholder {0}: selectedCustomField?.name
msgid "Are you sure you want to delete the {0} field?"
msgstr "Tem a certeza de que deseja eliminar o campo {0}?"
@@ -1634,6 +1670,9 @@ msgstr "ID do Ativo"
msgid "Assets"
msgstr "Ativos"
+msgid "Assets, liabilities and equity as of a date"
+msgstr "Ativos, passivos e patrimônio líquido em uma data"
+
msgid "Assign printers to locations. Shipping, receiving, and work centers inherit the location default unless overridden."
msgstr "Atribua impressoras a locais. Envio, recebimento e centros de trabalho herdam o padrão do local, a menos que sejam substituídos."
@@ -1890,6 +1929,9 @@ msgstr "Abaixo do estoque de segurança"
msgid "Beta"
msgstr "Beta"
+msgid "Biggest causes of scrap by reason, item, or work center"
+msgstr "Maiores causas de sucata por motivo, item ou centro de trabalho"
+
msgid "Bill of Material"
msgstr "Lista de Materiais"
@@ -2020,12 +2062,18 @@ msgstr "por {byUser}"
msgid "By accepting the invite, you agree to the <0>Terms of Service</0> and <1>Privacy Policy</1>."
msgstr "Ao aceitar o convite, você concorda com os <0>Termos de Serviço</0> e a <1>Política de Privacidade</1>."
+msgid "By dimension"
+msgstr "Por dimensão"
+
msgid "By Document Date"
msgstr "Por Data do Documento"
msgid "By Due Date"
msgstr "Por Data de Vencimento"
+msgid "By field"
+msgstr "Por campo"
+
msgid "By Item"
msgstr "Por Item"
@@ -2383,6 +2431,9 @@ msgstr "Limpar pesquisa"
msgid "Clear search query"
msgstr "Limpar consulta de pesquisa"
+msgid "Clear selection"
+msgstr "Limpar seleção"
+
msgid "Clear this invoice with the party's posted credits as well as cash. Credits apply directly — no posting needed."
msgstr "Limpe esta fatura com os créditos lançados da parte bem como dinheiro. Os créditos se aplicam diretamente — nenhum lançamento necessário."
@@ -2416,6 +2467,9 @@ msgstr "Data de Encerramento"
msgid "Close Period"
msgstr "Fechar Período"
+msgid "Close Reports"
+msgstr "Fechar Relatórios"
+
msgid "Close Status"
msgstr "Status de Fechamento"
@@ -2464,6 +2518,12 @@ msgstr "Recolher Configuração"
msgid "Collapse subtree"
msgstr "Recolher subárvore"
+msgid "Column dimension"
+msgstr "Dimensão da coluna"
+
+msgid "Column field"
+msgstr "Campo de coluna"
+
msgid "Column visibility and order"
msgstr "Visibilidade e ordem das colunas"
@@ -2560,6 +2620,9 @@ msgstr "Código de Barras de Conclusão"
msgid "Completion Time"
msgstr "Tempo de Conclusão"
+msgid "Condensed P&L with margins and key subtotals"
+msgstr "P&L Condensado com margens e subtotais principais"
+
msgid "Conditions"
msgstr "Condições"
@@ -3041,6 +3104,9 @@ msgstr "Custo dos bens vendidos (COGS)"
msgid "Cost of Goods Sold (default)"
msgstr "Custo dos Bens Vendidos (padrão)"
+msgid "Cost of Sales"
+msgstr "Custo das Vendas"
+
msgid "Costing"
msgstr "Custeio"
@@ -3852,6 +3918,10 @@ msgstr "Definir BOMs multi-nível e Bill of Process (métodos de fabricação)"
msgid "Delete"
msgstr "Eliminar"
+#. placeholder {0}: view.name
+msgid "Delete {0}"
+msgstr "Excluir {0}"
+
msgid "Delete {name}"
msgstr "Eliminar {name}"
@@ -4138,6 +4208,9 @@ msgstr "Excluir Tipo"
msgid "Delete Unit of Measure"
msgstr "Excluir unidade de medida"
+msgid "Delete view"
+msgstr "Excluir visualização"
+
msgid "Delete View"
msgstr "Eliminar Visualização"
@@ -5241,6 +5314,9 @@ msgstr "A troca do código de autorização por um token de acesso falhou. Tente
msgid "Excluded"
msgstr "Excluído"
+msgid "Executive P&L"
+msgstr "P&L Executivo"
+
msgid "Exemption Certificate"
msgstr "Certificado de Isenção"
@@ -5311,6 +5387,9 @@ msgstr "Lado de despesa dos movimentos de imposto diferido (emparelhado com pass
msgid "Expense side of deferred tax movements (paired with deferred tax liability)."
msgstr "Falha ao criar classe de ativo: {0}"
+msgid "Expenses"
+msgstr "Despesas"
+
msgid "Expert guidance"
msgstr "Orientação especializada"
@@ -5803,6 +5882,9 @@ msgstr "Finalizar"
msgid "Finalizing a fiscal month through the Open → Locked → Closed lifecycle; a closed period is frozen and its balances snapshotted, reversible only by explicit reopen."
msgstr "Finalizar um mês fiscal através do ciclo de vida Aberto → Bloqueado → Fechado; um período fechado é congelado e seus saldos são capturados, reversível apenas por reabertura explícita."
+msgid "Financial Statements"
+msgstr "Demonstrações Financeiras"
+
msgid "finish"
msgstr "Produtos acabados"
@@ -6263,9 +6345,15 @@ msgstr "classificações"
msgid "Grades"
msgstr "Graus"
+msgid "Gross Profit"
+msgstr "Lucro Bruto"
+
msgid "Group"
msgstr "Grupo"
+msgid "Group by"
+msgstr "Agrupar por"
+
msgid "Group Members"
msgstr "Membros do Grupo"
@@ -6621,6 +6709,9 @@ msgstr "Renda / Saldo (herdado)"
msgid "Income Statement"
msgstr "Demonstração de Resultados"
+msgid "Income Tax"
+msgstr "Imposto de Renda"
+
msgid "Income/Balance"
msgstr "Receita/Saldo"
@@ -7166,6 +7257,9 @@ msgstr "Unidade de Trabalho"
msgid "Language"
msgstr "Idioma"
+msgid "Last 6 Months"
+msgstr "Últimos 6 Meses"
+
msgid "Last Calibration"
msgstr "Última Calibração"
@@ -7962,6 +8056,9 @@ msgstr "Dinheiro que lhe devem"
msgid "Money you owe"
msgstr "Dinheiro que você deve"
+msgid "Monthly"
+msgstr "Mensal"
+
msgid "Months over which this asset depreciates for tax purposes (when not using MACRS)."
msgstr "Meses durante os quais este ativo se deprecia para fins fiscais (quando não está usando MACRS)."
@@ -8075,6 +8172,9 @@ msgstr "Valor Líquido Contábil"
msgid "Net Change"
msgstr "Alteração Líquida"
+msgid "Net Income"
+msgstr "Lucro Líquido"
+
msgid "Never"
msgstr "Nunca"
@@ -8567,6 +8667,9 @@ msgstr "Nenhum item"
msgid "No items have inventory activity here yet."
msgstr "Nenhum item teve atividade de inventário aqui ainda."
+msgid "No journal lines in scope for this period"
+msgstr "Nenhuma linha de diário no escopo para este período"
+
msgid "No lines to map"
msgstr "Nenhuma linha para mapear"
@@ -8666,6 +8769,9 @@ msgstr "Nenhum processo selecionado"
msgid "No production events recorded for this operation yet"
msgstr "Ainda não há eventos de produção registados para esta operação"
+msgid "No purchases in this period"
+msgstr "Nenhuma compra neste período"
+
msgid "No Quote"
msgstr "Sem Cotação"
@@ -8684,6 +8790,9 @@ msgstr "Nenhuma imagem de referência"
msgid "No remaining entities to inspect."
msgstr "Nenhuma entidade restante para inspecionar."
+msgid "No reports match your search."
+msgstr "Nenhum relatório corresponde à sua busca."
+
msgid "No results"
msgstr "Sem resultados"
@@ -8904,6 +9013,9 @@ msgstr "Piso de estoque em mão a manter para uso de serviço neste local"
msgid "On-hand inventory remains"
msgstr "Inventário em mão permanece"
+msgid "On-hand value by location or item, with GL tie-out"
+msgstr "Valor em mão por localização ou item, com reconciliação GL"
+
msgid "On-hand value of manufactured goods (Make items)"
msgstr "Valor em mãos de bens manufaturados (itens de fabricação)"
@@ -9009,6 +9121,9 @@ msgstr "Trabalhos abertos"
msgid "Open menu"
msgstr "Abrir menu"
+msgid "Open payables by supplier and age"
+msgstr "Contas a pagar em aberto por fornecedor e idade"
+
msgid "Open Purchase Invoices"
msgstr "Faturas de Compra Abertas"
@@ -9024,6 +9139,9 @@ msgstr "Cotações Abertas"
msgid "Open Reactive"
msgstr "Reativo Aberto"
+msgid "Open receivables by customer and age"
+msgstr "Contas a receber em aberto por cliente e idade"
+
msgid "Open RFQs"
msgstr "RFQs Abertos"
@@ -9057,6 +9175,9 @@ msgstr "Saldo de abertura da depreciação já contabilizada antes de este ativo
msgid "Operating Expenses"
msgstr "Despesas Operacionais"
+msgid "Operating Income"
+msgstr "Lucro Operacional"
+
msgid "Operation"
msgstr "Operação"
@@ -9172,6 +9293,12 @@ msgstr "Original"
msgid "Original Count"
msgstr "Contagem Original"
+msgid "Other Expense"
+msgstr "Outra Despesa"
+
+msgid "Other Income"
+msgstr "Outra Receita"
+
msgid "Other Income account for FX gains when a payment settles a foreign-currency invoice at a more favorable rate"
msgstr "Conta de Outras Receitas para ganhos de câmbio quando um pagamento liquida uma fatura em moeda estrangeira a uma taxa mais favorável"
@@ -9557,6 +9684,11 @@ msgstr "Peças/Minuto"
msgid "Pin"
msgstr "Fixar"
+#. placeholder {0}: report.name
+#. placeholder {0}: view.name
+msgid "Pin {0}"
+msgstr "Fixar {0}"
+
msgid "Pinned"
msgstr "Fixado"
@@ -10083,6 +10215,9 @@ msgstr "Unidade de Compra:"
msgid "Purchased"
msgstr "Comprado"
+msgid "Purchases"
+msgstr "Compras"
+
msgid "purchasing"
msgstr "Compras e Custo dos Bens Vendidos"
@@ -10211,6 +10346,9 @@ msgstr "Níveis de preço baseados em quantidade para esta substituição; o pre
msgid "Quantity: {0}"
msgstr "Quantidade: {0}"
+msgid "Quarterly"
+msgstr "Trimestral"
+
msgid "Question"
msgstr "Pergunta"
@@ -10678,6 +10816,9 @@ msgstr "Sistema de Reabastecimento"
msgid "Report"
msgstr "Relatório"
+msgid "Reporting"
+msgstr "Relatórios"
+
msgid "Reporting dimension"
msgstr "Dimensão de relatório"
@@ -10687,6 +10828,9 @@ msgstr "Relatórios"
msgid "Reprint"
msgstr "Reimprimir"
+msgid "Request access"
+msgstr "Solicitar acesso"
+
msgid "Request Approval"
msgstr "Solicitar Aprovação"
@@ -10821,6 +10965,12 @@ msgstr "Retornando material coletado não utilizado"
msgid "Rev {revision}"
msgstr "Rev {revision}"
+msgid "Revenue"
+msgstr "Receita"
+
+msgid "Revenue and expenses over a period"
+msgstr "Receita e despesas em um período"
+
msgid "Reverse all inventory adjustments"
msgstr "Reverter todos os ajustes de inventário"
@@ -11153,9 +11303,15 @@ msgstr "Guardar contactos"
msgid "Save Method"
msgstr "Salvar Método"
+msgid "Save view"
+msgstr "Salvar visualização"
+
msgid "Save View"
msgstr "Guardar Visualização"
+msgid "Saved Views"
+msgstr "Visualizações Salvas"
+
msgid "Saving..."
msgstr "Guardando..."
@@ -11868,6 +12024,15 @@ msgstr "Mostrar opções de sincronização"
msgid "Showing {0} of {totalCount} — refine your search"
msgstr "Mostrando {0} de {totalCount} — refine sua pesquisa"
+msgid "Showing in {parentCurrency}"
+msgstr "Exibindo em {parentCurrency}"
+
+msgid "Showing the first 500 lines"
+msgstr "Mostrando as primeiras 500 linhas"
+
+msgid "Showing the top 1,000 groups by amount"
+msgstr "Mostrando os 1.000 grupos principais por valor"
+
msgid "Shown as a faint background behind every page of generated PDFs"
msgstr "Exibido como um fundo suave atrás de cada página dos PDFs gerados"
@@ -11937,6 +12102,15 @@ msgstr "Ignorado"
msgid "Slack"
msgstr "Slack"
+msgid "Slice asset activity by location, item, or any dimension"
+msgstr "Dividir atividade de ativos por localização, item ou qualquer dimensão"
+
+msgid "Slice expenses by location, cost center, or any dimension"
+msgstr "Dividir despesas por localização, centro de custo ou qualquer dimensão"
+
+msgid "Slice revenue by customer, customer type, or any dimension"
+msgstr "Dividir receita por cliente, tipo de cliente ou qualquer dimensão"
+
msgid "Smoke-test the core daily flows end to end"
msgstr "Teste de fumaça dos fluxos diários principais de ponta a ponta"
@@ -12018,6 +12192,9 @@ msgstr "Clientes Específicos"
msgid "Specific Items"
msgstr "Itens Específicos"
+msgid "Spend by supplier, item, or category — your biggest cost drivers"
+msgstr "Gastos por fornecedor, item ou categoria — seus maiores impulsionadores de custo"
+
msgid "Split"
msgstr "Dividir"
@@ -13343,6 +13520,9 @@ msgstr "Tema"
msgid "Theme Color"
msgstr "Cor do Tema"
+msgid "Then by"
+msgstr "Depois por"
+
msgid "There are no active supplier quotes to compare for this RFQ."
msgstr "Não há cotações de fornecedor ativas para comparar para este RFQ."
@@ -13585,6 +13765,9 @@ msgstr "Fuso Horário"
msgid "Title"
msgstr "Título"
+msgid "To Date"
+msgstr "Até a Data"
+
msgid "To deactivate, use the row menu and choose Deactivate Account."
msgstr "Para desativar, use o menu de linha e escolha Desativar Conta."
@@ -13976,6 +14159,11 @@ msgstr "Desmarcar"
msgid "Unpick {0}"
msgstr "Desmarcar {0}"
+#. placeholder {0}: report.name
+#. placeholder {0}: view.name
+msgid "Unpin {0}"
+msgstr "Desafixar {0}"
+
msgid "Unposted Documents"
msgstr "Documentos Não Lançados"
@@ -14225,9 +14413,6 @@ msgstr "Validado"
msgid "Validating job..."
msgstr "Validando trabalho..."
-msgid "Valuation"
-msgstr "Avaliação"
-
msgid "Value"
msgstr "Valor"
@@ -14653,6 +14838,9 @@ msgstr "O que muda quando você migra para o Carbon e aproximadamente quanto val
msgid "What data"
msgstr "Que dados"
+msgid "What drove inventory up or down, by any dimension"
+msgstr "O que impulsionou o inventário para cima ou para baixo, por qualquer dimensão"
+
msgid "What is {translatedTerm}?"
msgstr "O que é {translatedTerm}?"
@@ -15049,6 +15237,9 @@ msgstr "Reduzir o valor de um ativo ao longo de sua vida útil — um lote mensa
msgid "Year"
msgstr "Ano"
+msgid "Yearly"
+msgstr "Anual"
+
msgid "Yes"
msgstr "Sim"
diff --git a/packages/locale/locales/ru/erp.po b/packages/locale/locales/ru/erp.po
index bc566bda9a..99ec98ab41 100644
--- a/packages/locale/locales/ru/erp.po
+++ b/packages/locale/locales/ru/erp.po
@@ -48,6 +48,10 @@ msgstr "(исключено для этого клиента)"
msgid "{0, plural, one {This part is on 1 open change notice} other {This part is on # open change notices}}"
msgstr "{0, plural, one {Эта деталь находится на 1 открытой уведомлении об изменении} other {Эта деталь находится на # открытых уведомлениях об изменении}}"
+#. placeholder {0}: selectedAccountIds.length
+msgid "{0} accounts"
+msgstr "{0} счётов"
+
#. placeholder {0}: precise?.text
msgid "{0} ago"
msgstr "{0} назад"
@@ -163,6 +167,9 @@ msgstr "{years}год"
msgid "/month/user"
msgstr "/месяц/пользователь"
+msgid "% of total"
+msgstr "% от общего"
+
msgid "% of Total"
msgstr "% от всего"
@@ -474,6 +481,9 @@ msgstr "Счет"
msgid "Account & Details"
msgstr "Счет и детали"
+msgid "Account balances with debits and credits"
+msgstr "Остатки счетов с дебетами и кредитами"
+
msgid "Account for advance payments made before goods or services are received"
msgstr "Учет авансовых платежей, произведенных до получения товаров или услуг."
@@ -510,9 +520,15 @@ msgstr "бухгалтерия"
msgid "Accounting"
msgstr "Бухгалтерия"
+msgid "Accounting is currently in beta. Request access to enable reporting, journal entries, accounting periods, fixed assets, and more."
+msgstr "Учет находится в стадии бета-тестирования. Запросите доступ для включения отчетности, журналов проводок, учетных периодов, основных средств и многого другого."
+
msgid "Accounting is disabled"
msgstr "Бухгалтерский учет отключен"
+msgid "Accounting is disabled for this company."
+msgstr "Учет отключен для этой компании."
+
msgid "Accounting is enabled"
msgstr "Бухгалтерский учет включен"
@@ -853,6 +869,9 @@ msgstr "После"
msgid "After (calculation method)"
msgstr "После (способ расчета)"
+msgid "Aging"
+msgstr "Возраст"
+
msgid "Agree on the scope"
msgstr "Согласовать область охвата"
@@ -871,6 +890,9 @@ msgstr "Все"
msgid "All {total} phases are done. Nice work — your team is up and running."
msgstr "Все {total} этапов завершены. Отличная работа — ваша команда готова к работе."
+msgid "All accounts"
+msgstr "Все счёта"
+
msgid "All actions selected"
msgstr "Все действия выбраны"
@@ -983,6 +1005,9 @@ msgstr "Положение операции в очереди её рабоче
msgid "An unexpected error occurred while connecting to Onshape. Try connecting again."
msgstr "При подключении к Onshape произошла непредвиденная ошибка. Повторите попытку подключения."
+msgid "Analytics"
+msgstr "Аналитика"
+
msgid "Anchors the Plan timeline to real dates. Leave blank for a relative, week-numbered timeline. Setting either one fills in the rest."
msgstr "Привязывает временную шкалу плана к реальным датам. Оставьте пустым для относительной временной шкалы с номерами недель. Установка одной из них заполнит остальное."
@@ -1026,6 +1051,9 @@ msgstr "Любой тип товара"
msgid "Anything not explicitly listed in scope above"
msgstr "Все, что не указано явно в области действия выше"
+msgid "AP Aging"
+msgstr "Анализ возраста кредиторской задолженности"
+
msgid "AP Clerk"
msgstr "Специалист по учету кредиторской задолженности"
@@ -1138,6 +1166,9 @@ msgstr "AQL"
msgid "AQL (Z1.4 / ISO 2859-1)"
msgstr "АПК (Z1.4 / ISO 2859-1)"
+msgid "AR Aging"
+msgstr "Анализ возраста дебиторской задолженности"
+
msgid "AR Clerk"
msgstr "Специалист по расчетам с дебиторами"
@@ -1245,6 +1276,11 @@ msgstr "Вы уверены, что хотите удалить {0}? Это де
msgid "Are you sure you want to delete {name}? This cannot be undone."
msgstr "Вы уверены, что хотите удалить {name}? Это действие невозможно отменить."
+#. placeholder {0}: activeView.name
+#. placeholder {0}: viewPendingDelete.name
+msgid "Are you sure you want to delete the \"{0}\" view? This cannot be undone."
+msgstr "Вы уверены, что хотите удалить представление \"{0}\"? Это действие невозможно отменить."
+
#. placeholder {0}: selectedCustomField?.name
msgid "Are you sure you want to delete the {0} field?"
msgstr "Вы уверены, что хотите удалить поле {0}?"
@@ -1634,6 +1670,9 @@ msgstr "ID активов"
msgid "Assets"
msgstr "Активы"
+msgid "Assets, liabilities and equity as of a date"
+msgstr "Активы, обязательства и капитал на дату"
+
msgid "Assign printers to locations. Shipping, receiving, and work centers inherit the location default unless overridden."
msgstr "Назначьте принтеры местоположениям. Доставка, получение и рабочие центры наследуют значение по умолчанию для местоположения, если не переопределено."
@@ -1890,6 +1929,9 @@ msgstr "Ниже страховой запас"
msgid "Beta"
msgstr "Бета"
+msgid "Biggest causes of scrap by reason, item, or work center"
+msgstr "Основные причины брака по причине, товару или производственному участку"
+
msgid "Bill of Material"
msgstr "Спецификация материалов"
@@ -2020,12 +2062,18 @@ msgstr "от {byUser}"
msgid "By accepting the invite, you agree to the <0>Terms of Service</0> and <1>Privacy Policy</1>."
msgstr "Принимая приглашение, вы соглашаетесь с <0>Условиями обслуживания</0> и <1>Политикой конфиденциальности</1>."
+msgid "By dimension"
+msgstr "По измерению"
+
msgid "By Document Date"
msgstr "По дате документа"
msgid "By Due Date"
msgstr "По дате платежа"
+msgid "By field"
+msgstr "По полю"
+
msgid "By Item"
msgstr "По товару"
@@ -2383,6 +2431,9 @@ msgstr "Очистить поиск"
msgid "Clear search query"
msgstr "Очистить поисковый запрос"
+msgid "Clear selection"
+msgstr "Очистить выделение"
+
msgid "Clear this invoice with the party's posted credits as well as cash. Credits apply directly — no posting needed."
msgstr "Погасите этот счет с помощью опубликованных кредитов стороны, а также наличных средств. Кредиты применяются напрямую — публикация не требуется."
@@ -2416,6 +2467,9 @@ msgstr "Дата закрытия"
msgid "Close Period"
msgstr "Закрыть период"
+msgid "Close Reports"
+msgstr "Закрыть отчеты"
+
msgid "Close Status"
msgstr "Статус закрытия"
@@ -2464,6 +2518,12 @@ msgstr "Свернуть настройку"
msgid "Collapse subtree"
msgstr "Свернуть поддерево"
+msgid "Column dimension"
+msgstr "Измерение столбца"
+
+msgid "Column field"
+msgstr "Поле столбца"
+
msgid "Column visibility and order"
msgstr "Видимость и порядок столбцов"
@@ -2560,6 +2620,9 @@ msgstr "Штрихкод завершения"
msgid "Completion Time"
msgstr "Время завершения"
+msgid "Condensed P&L with margins and key subtotals"
+msgstr "Сокращенный П&У с прибыльностью и ключевыми итогами"
+
msgid "Conditions"
msgstr "Условия"
@@ -3041,6 +3104,9 @@ msgstr "Себестоимость реализованной продукции
msgid "Cost of Goods Sold (default)"
msgstr "Себестоимость реализованной продукции (по умолчанию)"
+msgid "Cost of Sales"
+msgstr "Себестоимость продаж"
+
msgid "Costing"
msgstr "Расчет стоимости"
@@ -3852,6 +3918,10 @@ msgstr "Определите многоуровневые спецификаци
msgid "Delete"
msgstr "Удалить"
+#. placeholder {0}: view.name
+msgid "Delete {0}"
+msgstr "Удалить {0}"
+
msgid "Delete {name}"
msgstr "Удалить {name}"
@@ -4138,6 +4208,9 @@ msgstr "Удалить тип"
msgid "Delete Unit of Measure"
msgstr "Удалить единицу измерения"
+msgid "Delete view"
+msgstr "Удалить представление"
+
msgid "Delete View"
msgstr "Удалить представление"
@@ -5241,6 +5314,9 @@ msgstr "Не удалось обменять код авторизации на
msgid "Excluded"
msgstr "Исключено"
+msgid "Executive P&L"
+msgstr "П&У для руководства"
+
msgid "Exemption Certificate"
msgstr "Сертификат освобождения"
@@ -5311,6 +5387,9 @@ msgstr "Сторона расходов в отношении отложенно
msgid "Expense side of deferred tax movements (paired with deferred tax liability)."
msgstr "Не удалось создать класс активов: {0}"
+msgid "Expenses"
+msgstr "Расходы"
+
msgid "Expert guidance"
msgstr "Экспертное руководство"
@@ -5803,6 +5882,9 @@ msgstr "Завершить"
msgid "Finalizing a fiscal month through the Open → Locked → Closed lifecycle; a closed period is frozen and its balances snapshotted, reversible only by explicit reopen."
msgstr "Финализация налогового месяца через цикл жизни Открыто → Заблокировано → Закрыто; закрытый период заморожен и его остатки снимаются, обратимо только явным повторным открытием."
+msgid "Financial Statements"
+msgstr "Финансовые отчеты"
+
msgid "finish"
msgstr "Готовая продукция"
@@ -6263,9 +6345,15 @@ msgstr "сорта"
msgid "Grades"
msgstr "Сорта"
+msgid "Gross Profit"
+msgstr "Валовая прибыль"
+
msgid "Group"
msgstr "Группа"
+msgid "Group by"
+msgstr "Группировать по"
+
msgid "Group Members"
msgstr "Члены группы"
@@ -6621,6 +6709,9 @@ msgstr "Доход / Баланс (унаследованный)"
msgid "Income Statement"
msgstr "Отчет о прибылях и убытках"
+msgid "Income Tax"
+msgstr "Налог на прибыль"
+
msgid "Income/Balance"
msgstr "Доход/Баланс"
@@ -7166,6 +7257,9 @@ msgstr "Единица труда"
msgid "Language"
msgstr "Язык"
+msgid "Last 6 Months"
+msgstr "Последние 6 месяцев"
+
msgid "Last Calibration"
msgstr "Последняя калибровка"
@@ -7962,6 +8056,9 @@ msgstr "Деньги, которые вам должны"
msgid "Money you owe"
msgstr "Деньги, которые вы должны"
+msgid "Monthly"
+msgstr "Ежемесячно"
+
msgid "Months over which this asset depreciates for tax purposes (when not using MACRS)."
msgstr "Месяцы, в течение которых это имущество амортизируется в налоговых целях (при отсутствии MACRS)."
@@ -8075,6 +8172,9 @@ msgstr "Чистая балансовая стоимость"
msgid "Net Change"
msgstr "Чистое изменение"
+msgid "Net Income"
+msgstr "Чистый доход"
+
msgid "Never"
msgstr "Никогда"
@@ -8567,6 +8667,9 @@ msgstr "Нет позиций"
msgid "No items have inventory activity here yet."
msgstr "Здесь еще нет активности с товарами."
+msgid "No journal lines in scope for this period"
+msgstr "Нет строк журнала в пределах этого периода"
+
msgid "No lines to map"
msgstr "Нет строк для сопоставления"
@@ -8666,6 +8769,9 @@ msgstr "Процесс не выбран"
msgid "No production events recorded for this operation yet"
msgstr "Для этой операции еще не записано ни одного производственного события"
+msgid "No purchases in this period"
+msgstr "Нет покупок в этом периоде"
+
msgid "No Quote"
msgstr "Нет предложения"
@@ -8684,6 +8790,9 @@ msgstr "Нет эталонного изображения"
msgid "No remaining entities to inspect."
msgstr "Нет оставшихся объектов для проверки."
+msgid "No reports match your search."
+msgstr "Никакие отчеты не соответствуют вашему поиску."
+
msgid "No results"
msgstr "Нет результатов"
@@ -8904,6 +9013,9 @@ msgstr "Минимальный остаток для обслуживания в
msgid "On-hand inventory remains"
msgstr "Остаток на складе"
+msgid "On-hand value by location or item, with GL tie-out"
+msgstr "Стоимость в наличии по локации или позиции с согласованием главной книги"
+
msgid "On-hand value of manufactured goods (Make items)"
msgstr "Текущая стоимость произведённых товаров (Товары на производство)"
@@ -9009,6 +9121,9 @@ msgstr "Открытые заказы"
msgid "Open menu"
msgstr "Открыть меню"
+msgid "Open payables by supplier and age"
+msgstr "Открытые счета к оплате по поставщикам и срокам"
+
msgid "Open Purchase Invoices"
msgstr "Открытые счета-фактуры"
@@ -9024,6 +9139,9 @@ msgstr "Открытые предложения"
msgid "Open Reactive"
msgstr "Открытые реактивные"
+msgid "Open receivables by customer and age"
+msgstr "Открытые счета к получению по клиентам и срокам"
+
msgid "Open RFQs"
msgstr "Открытые РФП"
@@ -9057,6 +9175,9 @@ msgstr "Начальный баланс амортизации, уже учте
msgid "Operating Expenses"
msgstr "Операционные расходы"
+msgid "Operating Income"
+msgstr "Операционный доход"
+
msgid "Operation"
msgstr "Операция"
@@ -9172,6 +9293,12 @@ msgstr "Оригинал"
msgid "Original Count"
msgstr "Исходный подсчет"
+msgid "Other Expense"
+msgstr "Прочие расходы"
+
+msgid "Other Income"
+msgstr "Прочие доходы"
+
msgid "Other Income account for FX gains when a payment settles a foreign-currency invoice at a more favorable rate"
msgstr "Счет прочих доходов для прибыли от валютных операций при расчете по иностранной валюте по более выгодному курсу"
@@ -9557,6 +9684,11 @@ msgstr "Деталей/Минуту"
msgid "Pin"
msgstr "Закрепить"
+#. placeholder {0}: report.name
+#. placeholder {0}: view.name
+msgid "Pin {0}"
+msgstr "Закрепить {0}"
+
msgid "Pinned"
msgstr "Закреплено"
@@ -10083,6 +10215,9 @@ msgstr "Единица покупки:"
msgid "Purchased"
msgstr "Закупленный"
+msgid "Purchases"
+msgstr "Покупки"
+
msgid "purchasing"
msgstr "Закупки и стоимость проданных товаров"
@@ -10211,6 +10346,9 @@ msgstr "Ярусы цен на основе количества для этог
msgid "Quantity: {0}"
msgstr "Количество: {0}"
+msgid "Quarterly"
+msgstr "Ежеквартально"
+
msgid "Question"
msgstr "Вопрос"
@@ -10678,6 +10816,9 @@ msgstr "Система пополнения"
msgid "Report"
msgstr "Отчет"
+msgid "Reporting"
+msgstr "Отчетность"
+
msgid "Reporting dimension"
msgstr "Измерение отчётности"
@@ -10687,6 +10828,9 @@ msgstr "Отчеты"
msgid "Reprint"
msgstr "Перепечать"
+msgid "Request access"
+msgstr "Запросить доступ"
+
msgid "Request Approval"
msgstr "Запросить одобрение"
@@ -10821,6 +10965,12 @@ msgstr "Возврат неиспользованного отобранного
msgid "Rev {revision}"
msgstr "Ред. {revision}"
+msgid "Revenue"
+msgstr "Выручка"
+
+msgid "Revenue and expenses over a period"
+msgstr "Доход и расходы за период"
+
msgid "Reverse all inventory adjustments"
msgstr "Отменить все корректировки запасов"
@@ -11153,9 +11303,15 @@ msgstr "Сохранить контакты"
msgid "Save Method"
msgstr "Сохранить метод"
+msgid "Save view"
+msgstr "Сохранить представление"
+
msgid "Save View"
msgstr "Сохранить представление"
+msgid "Saved Views"
+msgstr "Сохраненные представления"
+
msgid "Saving..."
msgstr "Сохранение..."
@@ -11868,6 +12024,15 @@ msgstr "Показать параметры синхронизации"
msgid "Showing {0} of {totalCount} — refine your search"
msgstr "Показано {0} из {totalCount} — уточните поиск"
+msgid "Showing in {parentCurrency}"
+msgstr "Отображение в {parentCurrency}"
+
+msgid "Showing the first 500 lines"
+msgstr "Показано первые 500 строк"
+
+msgid "Showing the top 1,000 groups by amount"
+msgstr "Показано топ 1000 групп по сумме"
+
msgid "Shown as a faint background behind every page of generated PDFs"
msgstr "Отображается как бледный фон на каждой странице сгенерированных PDF-файлов"
@@ -11937,6 +12102,15 @@ msgstr "Пропущено"
msgid "Slack"
msgstr "Slack"
+msgid "Slice asset activity by location, item, or any dimension"
+msgstr "Разбить активность активов по местоположению, товару или любому измерению"
+
+msgid "Slice expenses by location, cost center, or any dimension"
+msgstr "Разбить расходы по местоположению, центру затрат или любому измерению"
+
+msgid "Slice revenue by customer, customer type, or any dimension"
+msgstr "Разделить доход по клиенту, типу клиента или любому измерению"
+
msgid "Smoke-test the core daily flows end to end"
msgstr "Дымовое тестирование основных ежедневных процессов от начала до конца"
@@ -12018,6 +12192,9 @@ msgstr "Конкретные клиенты"
msgid "Specific Items"
msgstr "Конкретные товары"
+msgid "Spend by supplier, item, or category — your biggest cost drivers"
+msgstr "Расходы по поставщику, товару или категории — ваши основные драйверы затрат"
+
msgid "Split"
msgstr "Разделить"
@@ -13343,6 +13520,9 @@ msgstr "Тема"
msgid "Theme Color"
msgstr "Цвет темы"
+msgid "Then by"
+msgstr "Затем по"
+
msgid "There are no active supplier quotes to compare for this RFQ."
msgstr "Нет активных предложений поставщиков для сравнения по этому РФП."
@@ -13585,6 +13765,9 @@ msgstr "Часовой пояс"
msgid "Title"
msgstr "Название"
+msgid "To Date"
+msgstr "До даты"
+
msgid "To deactivate, use the row menu and choose Deactivate Account."
msgstr "Чтобы отключить, используйте меню строки и выберите Деактивировать учетную запись."
@@ -13976,6 +14159,11 @@ msgstr "Отменить выбор"
msgid "Unpick {0}"
msgstr "Отменить выбор {0}"
+#. placeholder {0}: report.name
+#. placeholder {0}: view.name
+msgid "Unpin {0}"
+msgstr "Открепить {0}"
+
msgid "Unposted Documents"
msgstr "Неопубликованные документы"
@@ -14225,9 +14413,6 @@ msgstr "Проверено"
msgid "Validating job..."
msgstr "Проверка задания..."
-msgid "Valuation"
-msgstr "Оценка"
-
msgid "Value"
msgstr "Значение"
@@ -14653,6 +14838,9 @@ msgstr "Что изменится при переходе на Carbon и при
msgid "What data"
msgstr "Какие данные"
+msgid "What drove inventory up or down, by any dimension"
+msgstr "Что повлияло на инвентаризацию вверх или вниз, по любому измерению"
+
msgid "What is {translatedTerm}?"
msgstr "Что такое {translatedTerm}?"
@@ -15049,6 +15237,9 @@ msgstr "Снижение стоимости актива в течение ег
msgid "Year"
msgstr "Год"
+msgid "Yearly"
+msgstr "Ежегодно"
+
msgid "Yes"
msgstr "Да"
diff --git a/packages/locale/locales/tr/erp.po b/packages/locale/locales/tr/erp.po
index 42feca47bb..2f2d5b4ecf 100644
--- a/packages/locale/locales/tr/erp.po
+++ b/packages/locale/locales/tr/erp.po
@@ -48,6 +48,10 @@ msgstr "(bu müşteri için hariç tutulmuş)"
msgid "{0, plural, one {This part is on 1 open change notice} other {This part is on # open change notices}}"
msgstr "{0, plural, one {Bu parça 1 açık değişiklik bildirisinde yer alıyor} other {Bu parça # açık değişiklik bildirisinde yer alıyor}}"
+#. placeholder {0}: selectedAccountIds.length
+msgid "{0} accounts"
+msgstr "{0} hesaplar"
+
#. placeholder {0}: precise?.text
msgid "{0} ago"
msgstr "{0} önce"
@@ -163,6 +167,9 @@ msgstr "{years}yr"
msgid "/month/user"
msgstr "/ay/kullanıcı"
+msgid "% of total"
+msgstr "Toplamın %"
+
msgid "% of Total"
msgstr "% Toplam"
@@ -474,6 +481,9 @@ msgstr "Hesap"
msgid "Account & Details"
msgstr "Hesap ve ayrıntılar"
+msgid "Account balances with debits and credits"
+msgstr "Borç ve alacak bakiyeleri"
+
msgid "Account for advance payments made before goods or services are received"
msgstr "Mal veya hizmet alınmadan önce yapılan peşin ödemeleri hesaplayın."
@@ -510,9 +520,15 @@ msgstr "muhasebe"
msgid "Accounting"
msgstr "Muhasebe"
+msgid "Accounting is currently in beta. Request access to enable reporting, journal entries, accounting periods, fixed assets, and more."
+msgstr "Muhasebe şu anda beta aşamasındadır. Raporlama, günlük girişler, muhasebe dönemleri, sabit varlıklar ve daha fazlasını etkinleştirmek için erişim isteyin."
+
msgid "Accounting is disabled"
msgstr "Muhasebe devre dışı"
+msgid "Accounting is disabled for this company."
+msgstr "Bu şirket için muhasebe devre dışı bırakılmıştır."
+
msgid "Accounting is enabled"
msgstr "Muhasebe etkinleştirilmiş"
@@ -853,6 +869,9 @@ msgstr "Sonra"
msgid "After (calculation method)"
msgstr "Sonra (hesaplama yöntemi)"
+msgid "Aging"
+msgstr "Yaşlandırma"
+
msgid "Agree on the scope"
msgstr "Kapsamda anlaş"
@@ -871,6 +890,9 @@ msgstr "Tümü"
msgid "All {total} phases are done. Nice work — your team is up and running."
msgstr "Tüm {total} aşama tamamlandı. Harika iş — ekibiniz çalışmaya başladı."
+msgid "All accounts"
+msgstr "Tüm hesaplar"
+
msgid "All actions selected"
msgstr "Tüm eylemler seçildi"
@@ -983,6 +1005,9 @@ msgstr "Bir işin iş merkezinin kuyruğundaki konumu — işinin çekildiği s
msgid "An unexpected error occurred while connecting to Onshape. Try connecting again."
msgstr "Onshape'e bağlanırken beklenmeyen bir hata oluştu. Yeniden bağlanmayı deneyin."
+msgid "Analytics"
+msgstr "Analitik"
+
msgid "Anchors the Plan timeline to real dates. Leave blank for a relative, week-numbered timeline. Setting either one fills in the rest."
msgstr "Plan zaman çizelgesini gerçek tarihlere sabitleyin. Göreceli, hafta numaralı bir zaman çizelgesi için boş bırakın. Her ikisinden birini ayarlamak geri kalanını doldurur."
@@ -1026,6 +1051,9 @@ msgstr "Herhangi bir ürün tipi"
msgid "Anything not explicitly listed in scope above"
msgstr "Yukarıda açıkça kapsamda listelenmemiş herhangi bir şey"
+msgid "AP Aging"
+msgstr "AP Yaşlandırma"
+
msgid "AP Clerk"
msgstr "AP Muhasebesi Görevlisi"
@@ -1138,6 +1166,9 @@ msgstr "AQL"
msgid "AQL (Z1.4 / ISO 2859-1)"
msgstr "AQL (Z1.4 / ISO 2859-1)"
+msgid "AR Aging"
+msgstr "AR Yaşlandırma"
+
msgid "AR Clerk"
msgstr "AR Görevlisi"
@@ -1245,6 +1276,11 @@ msgstr "Emin misiniz ki {0}'ı silmek istiyorsunuz? Bu geri alınamaz."
msgid "Are you sure you want to delete {name}? This cannot be undone."
msgstr "{name} adlı yedeği silmek istediğinizden emin misiniz? Bu işlem geri alınamaz."
+#. placeholder {0}: activeView.name
+#. placeholder {0}: viewPendingDelete.name
+msgid "Are you sure you want to delete the \"{0}\" view? This cannot be undone."
+msgstr "\"{0}\" görünümünü silmek istediğinizden emin misiniz? Bu işlem geri alınamaz."
+
#. placeholder {0}: selectedCustomField?.name
msgid "Are you sure you want to delete the {0} field?"
msgstr "{0} alanını silmek istediğinizden emin misiniz?"
@@ -1634,6 +1670,9 @@ msgstr "Varlık Kimliği"
msgid "Assets"
msgstr "Varlıklar"
+msgid "Assets, liabilities and equity as of a date"
+msgstr "Bir tarih itibariyle aktif, pasif ve öz kaynak"
+
msgid "Assign printers to locations. Shipping, receiving, and work centers inherit the location default unless overridden."
msgstr "Yazıcıları konumlara atayın. Sevkiyat, kabul ve iş merkezleri, geçersiz kılınmadıkça konum varsayılanını miras alır."
@@ -1890,6 +1929,9 @@ msgstr "Emniyet stoğunun altında"
msgid "Beta"
msgstr "Beta"
+msgid "Biggest causes of scrap by reason, item, or work center"
+msgstr "Nedene, ürüne veya iş merkezine göre ıskartanın en büyük nedenleri"
+
msgid "Bill of Material"
msgstr "Malzeme Listesi"
@@ -2020,12 +2062,18 @@ msgstr "by {byUser}"
msgid "By accepting the invite, you agree to the <0>Terms of Service</0> and <1>Privacy Policy</1>."
msgstr "Davetiyeyi kabul ederek, <0>Hizmet Şartları</0> ve <1>Gizlilik Politikası</1>'na katılırsınız."
+msgid "By dimension"
+msgstr "Boyuta göre"
+
msgid "By Document Date"
msgstr "Belge Tarihine Göre"
msgid "By Due Date"
msgstr "Vade Tarihine Göre"
+msgid "By field"
+msgstr "Alana göre"
+
msgid "By Item"
msgstr "Ürüne Göre"
@@ -2383,6 +2431,9 @@ msgstr "Aramayı temizle"
msgid "Clear search query"
msgstr "Arama sorgusunu temizle"
+msgid "Clear selection"
+msgstr "Seçimi temizle"
+
msgid "Clear this invoice with the party's posted credits as well as cash. Credits apply directly — no posting needed."
msgstr "Bu faturayı tarafın deftere nakledilmiş kredileri ve nakit ile kapatın. Krediler doğrudan uygulanır — deftere nakil gerekmez."
@@ -2416,6 +2467,9 @@ msgstr "Kapatma Tarihi"
msgid "Close Period"
msgstr "Dönemi Kapat"
+msgid "Close Reports"
+msgstr "Raporları Kapat"
+
msgid "Close Status"
msgstr "Kapanış Durumu"
@@ -2464,6 +2518,12 @@ msgstr "Kurulumu Daralt"
msgid "Collapse subtree"
msgstr "Alt ağacı daralt"
+msgid "Column dimension"
+msgstr "Sütun boyutu"
+
+msgid "Column field"
+msgstr "Sütun alanı"
+
msgid "Column visibility and order"
msgstr "Sütun görünürlüğü ve sırası"
@@ -2560,6 +2620,9 @@ msgstr "Tamamlama Barkodu"
msgid "Completion Time"
msgstr "Tamamlama Süresi"
+msgid "Condensed P&L with margins and key subtotals"
+msgstr "Marjlar ve kilit alt toplamlarla sıkıştırılmış P&L"
+
msgid "Conditions"
msgstr "Koşullar"
@@ -3041,6 +3104,9 @@ msgstr "Satılan Malların Maliyeti (COGS)"
msgid "Cost of Goods Sold (default)"
msgstr "Satılan Malların Maliyeti (varsayılan)"
+msgid "Cost of Sales"
+msgstr "Satışların Maliyeti"
+
msgid "Costing"
msgstr "Maliyetlendirme"
@@ -3852,6 +3918,10 @@ msgstr "Çok seviyeli BOM'ları ve Bill of Process'i (üretim yöntemlerini) tan
msgid "Delete"
msgstr "Sil"
+#. placeholder {0}: view.name
+msgid "Delete {0}"
+msgstr "{0} Sil"
+
msgid "Delete {name}"
msgstr "{name} sil"
@@ -4138,6 +4208,9 @@ msgstr "Türü Sil"
msgid "Delete Unit of Measure"
msgstr "Ölçü Birimini Sil"
+msgid "Delete view"
+msgstr "Görünümü sil"
+
msgid "Delete View"
msgstr "Görünümü Sil"
@@ -5241,6 +5314,9 @@ msgstr "Yetkilendirme kodunun erişim belirteciyle değiştirilmesi başarısız
msgid "Excluded"
msgstr "Hariç Tutulan"
+msgid "Executive P&L"
+msgstr "Yönetici P&L"
+
msgid "Exemption Certificate"
msgstr "İstisnai Sertifika"
@@ -5311,6 +5387,9 @@ msgstr "Ertelenmiş vergi hareketlerinin gider tarafı (ertelenmiş vergi yükü
msgid "Expense side of deferred tax movements (paired with deferred tax liability)."
msgstr "Varlık sınıfı oluşturulamadı: {0}"
+msgid "Expenses"
+msgstr "Giderler"
+
msgid "Expert guidance"
msgstr "Uzman rehberliği"
@@ -5803,6 +5882,9 @@ msgstr "Onayla"
msgid "Finalizing a fiscal month through the Open → Locked → Closed lifecycle; a closed period is frozen and its balances snapshotted, reversible only by explicit reopen."
msgstr "Mali bir ayı Açık → Kilitli → Kapalı yaşam döngüsü aracılığıyla sonlandırma; kapalı bir dönem donmuştur ve bakiyeleri anlık görüntülenmiş, yalnızca açık yeniden açılarak tersine çevrilebilir."
+msgid "Financial Statements"
+msgstr "Mali Tablolar"
+
msgid "finish"
msgstr "Bitmiş ürünler"
@@ -6263,9 +6345,15 @@ msgstr "sınıflar"
msgid "Grades"
msgstr "Dereceler"
+msgid "Gross Profit"
+msgstr "Brüt Kar"
+
msgid "Group"
msgstr "Grup"
+msgid "Group by"
+msgstr "Grupla"
+
msgid "Group Members"
msgstr "Üye Grupları"
@@ -6621,6 +6709,9 @@ msgstr "Gelir / Bakiye (Devralınan)"
msgid "Income Statement"
msgstr "Gelir Tablosu"
+msgid "Income Tax"
+msgstr "Gelir Vergisi"
+
msgid "Income/Balance"
msgstr "Gelir/Bakiye"
@@ -7166,6 +7257,9 @@ msgstr "İşçilik Birimi"
msgid "Language"
msgstr "Dil"
+msgid "Last 6 Months"
+msgstr "Son 6 Ay"
+
msgid "Last Calibration"
msgstr "Son Kalibrasyon"
@@ -7962,6 +8056,9 @@ msgstr "Size borçlu"
msgid "Money you owe"
msgstr "Borçlu olduğunuz para"
+msgid "Monthly"
+msgstr "Aylık"
+
msgid "Months over which this asset depreciates for tax purposes (when not using MACRS)."
msgstr "Bu varlığın vergi amaçları için amorti edildiği aylar (MACRS kullanılmıyorsa)."
@@ -8075,6 +8172,9 @@ msgstr "Net Defter Değeri"
msgid "Net Change"
msgstr "Net Değişim"
+msgid "Net Income"
+msgstr "Net Gelir"
+
msgid "Never"
msgstr "Asla"
@@ -8567,6 +8667,9 @@ msgstr "Öğe yok"
msgid "No items have inventory activity here yet."
msgstr "Burada henüz hiçbir maddenin envanter hareketi yok."
+msgid "No journal lines in scope for this period"
+msgstr "Bu dönem için kapsam içinde günlük satırı yok"
+
msgid "No lines to map"
msgstr "Eşlenecek satır yok"
@@ -8666,6 +8769,9 @@ msgstr "Hiçbir işlem seçilmedi"
msgid "No production events recorded for this operation yet"
msgstr "Bu işlem için henüz üretim etkinliği kaydedilmedi"
+msgid "No purchases in this period"
+msgstr "Bu dönemde satın alma yok"
+
msgid "No Quote"
msgstr "Teklif Yok"
@@ -8684,6 +8790,9 @@ msgstr "Referans resim yok"
msgid "No remaining entities to inspect."
msgstr "İncelenecek kalan varlık yok."
+msgid "No reports match your search."
+msgstr "Aramanızla eşleşen rapor yok."
+
msgid "No results"
msgstr "Sonuç bulunamadı"
@@ -8904,6 +9013,9 @@ msgstr "Bu konumdaki servis kullanımı için korunacak minimum stok seviyesi"
msgid "On-hand inventory remains"
msgstr "Eldeki envanter kaldı"
+msgid "On-hand value by location or item, with GL tie-out"
+msgstr "Konum veya öğeye göre eldeki değer, GL bağlantılı olarak"
+
msgid "On-hand value of manufactured goods (Make items)"
msgstr "Üretilen malların (Üretim ürünleri) eldeki değeri"
@@ -9009,6 +9121,9 @@ msgstr "Açık işler"
msgid "Open menu"
msgstr "Menüyü aç"
+msgid "Open payables by supplier and age"
+msgstr "Tedarikçi ve yaşa göre açık borçlar"
+
msgid "Open Purchase Invoices"
msgstr "Açık Satın Alma Faturaları"
@@ -9024,6 +9139,9 @@ msgstr "Açık Teklifler"
msgid "Open Reactive"
msgstr "Açık Reaktif"
+msgid "Open receivables by customer and age"
+msgstr "Müşteri ve yaşa göre açık alacaklar"
+
msgid "Open RFQs"
msgstr "Açık RFQ'lar"
@@ -9057,6 +9175,9 @@ msgstr "Bu varlık Carbon'a eklenmeden önce zaten deftere geçirilmiş amortism
msgid "Operating Expenses"
msgstr "İşletme Giderleri"
+msgid "Operating Income"
+msgstr "İşletme Geliri"
+
msgid "Operation"
msgstr "Operasyon"
@@ -9172,6 +9293,12 @@ msgstr "Orijinal"
msgid "Original Count"
msgstr "Orijinal Sayım"
+msgid "Other Expense"
+msgstr "Diğer Gider"
+
+msgid "Other Income"
+msgstr "Diğer Gelir"
+
msgid "Other Income account for FX gains when a payment settles a foreign-currency invoice at a more favorable rate"
msgstr "Bir ödeme yabancı para birimindeki bir faturayı daha uygun bir oranda kapatırken FX kazançları için Diğer Gelir hesabı"
@@ -9557,6 +9684,11 @@ msgstr "Parça/Dakika"
msgid "Pin"
msgstr "Sabitle"
+#. placeholder {0}: report.name
+#. placeholder {0}: view.name
+msgid "Pin {0}"
+msgstr "Sabitle {0}"
+
msgid "Pinned"
msgstr "Sabitlenmiş"
@@ -10083,6 +10215,9 @@ msgstr "Satın Alma Birimi:"
msgid "Purchased"
msgstr "Satın Alındı"
+msgid "Purchases"
+msgstr "Satın almalar"
+
msgid "purchasing"
msgstr "Satın Alma ve Satılan Malların Maliyeti"
@@ -10211,6 +10346,9 @@ msgstr "Bu geçersiz kılma için miktar tabanlı fiyatlandırma seviyeleri; uyg
msgid "Quantity: {0}"
msgstr "Miktar: {0}"
+msgid "Quarterly"
+msgstr "Üç Aylık"
+
msgid "Question"
msgstr "Soru"
@@ -10678,6 +10816,9 @@ msgstr "Yenileştirme Sistemi"
msgid "Report"
msgstr "Rapor"
+msgid "Reporting"
+msgstr "Raporlama"
+
msgid "Reporting dimension"
msgstr "Raporlama boyutu"
@@ -10687,6 +10828,9 @@ msgstr "Raporlar"
msgid "Reprint"
msgstr "Yeniden Yazdır"
+msgid "Request access"
+msgstr "Erişim İste"
+
msgid "Request Approval"
msgstr "Onay Talebi Oluştur"
@@ -10821,6 +10965,12 @@ msgstr "Kullanılmayan alınan malzeme iade ediliyor"
msgid "Rev {revision}"
msgstr "Sürüm {revision}"
+msgid "Revenue"
+msgstr "Gelir"
+
+msgid "Revenue and expenses over a period"
+msgstr "Bir dönem içinde gelir ve giderler"
+
msgid "Reverse all inventory adjustments"
msgstr "Tüm envanter ayarlamalarını geri alır"
@@ -11153,9 +11303,15 @@ msgstr "Kişileri kaydet"
msgid "Save Method"
msgstr "Yöntemi Kaydet"
+msgid "Save view"
+msgstr "Görünümü kaydet"
+
msgid "Save View"
msgstr "Görünümü Kaydet"
+msgid "Saved Views"
+msgstr "Kaydedilen Görünümler"
+
msgid "Saving..."
msgstr "Kaydediliyor..."
@@ -11868,6 +12024,15 @@ msgstr "Senkronizasyon seçeneklerini göster"
msgid "Showing {0} of {totalCount} — refine your search"
msgstr "{0} / {totalCount} gösteriliyor — aramanızı daraltın"
+msgid "Showing in {parentCurrency}"
+msgstr "{parentCurrency} cinsinden gösteriliyor"
+
+msgid "Showing the first 500 lines"
+msgstr "İlk 500 satır gösteriliyor"
+
+msgid "Showing the top 1,000 groups by amount"
+msgstr "Miktar açısından ilk 1.000 grup gösteriliyor"
+
msgid "Shown as a faint background behind every page of generated PDFs"
msgstr "Oluşturulan PDF'lerin her sayfasının arkasında soluk bir arka plan olarak gösterilir"
@@ -11937,6 +12102,15 @@ msgstr "Atlanmış"
msgid "Slack"
msgstr "Slack"
+msgid "Slice asset activity by location, item, or any dimension"
+msgstr "Konum, ürün veya herhangi bir boyuta göre varlık aktivitesini böl"
+
+msgid "Slice expenses by location, cost center, or any dimension"
+msgstr "Konum, maliyet merkezi veya herhangi bir boyuta göre giderleri böl"
+
+msgid "Slice revenue by customer, customer type, or any dimension"
+msgstr "Müşteri, müşteri türü veya herhangi bir boyuta göre geliri böl"
+
msgid "Smoke-test the core daily flows end to end"
msgstr "Temel günlük akışları uçtan uca test et"
@@ -12018,6 +12192,9 @@ msgstr "Belirli Müşteriler"
msgid "Specific Items"
msgstr "Belirli Ürünler"
+msgid "Spend by supplier, item, or category — your biggest cost drivers"
+msgstr "Tedarikçi, ürün veya kategoriye göre harcama — en büyük maliyet sürücüleriniz"
+
msgid "Split"
msgstr "Bölünmüş"
@@ -13343,6 +13520,9 @@ msgstr "Tema"
msgid "Theme Color"
msgstr "Tema Rengi"
+msgid "Then by"
+msgstr "Sonra"
+
msgid "There are no active supplier quotes to compare for this RFQ."
msgstr "Bu RFQ için karşılaştırılacak aktif tedarikçi teklifi bulunmamaktadır."
@@ -13585,6 +13765,9 @@ msgstr "Saat Dilim"
msgid "Title"
msgstr "Unvan"
+msgid "To Date"
+msgstr "Bitiş Tarihi"
+
msgid "To deactivate, use the row menu and choose Deactivate Account."
msgstr "Deaktif hale getirmek için, satır menüsünü kullanın ve Hesabı Deaktif Et'i seçin."
@@ -13976,6 +14159,11 @@ msgstr "Çıkart"
msgid "Unpick {0}"
msgstr "Çıkart {0}"
+#. placeholder {0}: report.name
+#. placeholder {0}: view.name
+msgid "Unpin {0}"
+msgstr "Sabitlemeyi Kaldır {0}"
+
msgid "Unposted Documents"
msgstr "Deftere Geçmemiş Belgeler"
@@ -14225,9 +14413,6 @@ msgstr "Doğrulandı"
msgid "Validating job..."
msgstr "İş doğrulanıyor..."
-msgid "Valuation"
-msgstr "Değerleme"
-
msgid "Value"
msgstr "Değer"
@@ -14653,6 +14838,9 @@ msgstr "Carbon'a geçtiğinizde neler değişir ve kabaca ne kadar değerli olur
msgid "What data"
msgstr "Hangi veri"
+msgid "What drove inventory up or down, by any dimension"
+msgstr "Envanterin yükselmesine veya düşmesine neyin sebep olduğu, herhangi bir boyuta göre"
+
msgid "What is {translatedTerm}?"
msgstr "{translatedTerm} nedir?"
@@ -15049,6 +15237,9 @@ msgstr "Bir varlığın değerini faydalı kullanım süresi boyunca azaltma —
msgid "Year"
msgstr "Yıl"
+msgid "Yearly"
+msgstr "Yıllık"
+
msgid "Yes"
msgstr "Evet"
diff --git a/packages/locale/locales/zh/erp.po b/packages/locale/locales/zh/erp.po
index e967b85c24..a8ae9ad4ae 100644
--- a/packages/locale/locales/zh/erp.po
+++ b/packages/locale/locales/zh/erp.po
@@ -48,6 +48,10 @@ msgstr "(已为此客户排除)"
msgid "{0, plural, one {This part is on 1 open change notice} other {This part is on # open change notices}}"
msgstr "{0, plural, one {此零件包含在1个开放的更改单中} other {此零件包含在#个开放的更改单中}}"
+#. placeholder {0}: selectedAccountIds.length
+msgid "{0} accounts"
+msgstr "{0} 个账户"
+
#. placeholder {0}: precise?.text
msgid "{0} ago"
msgstr "{0} 前"
@@ -163,6 +167,9 @@ msgstr "{years}年"
msgid "/month/user"
msgstr "/月/用户"
+msgid "% of total"
+msgstr "占总数百分比"
+
msgid "% of Total"
msgstr "占总数的 %"
@@ -474,6 +481,9 @@ msgstr "账户"
msgid "Account & Details"
msgstr "账户和详细信息"
+msgid "Account balances with debits and credits"
+msgstr "账户借贷余额"
+
msgid "Account for advance payments made before goods or services are received"
msgstr "收到商品或服务前支付的预付款的计账。"
@@ -510,9 +520,15 @@ msgstr "会计"
msgid "Accounting"
msgstr "会计"
+msgid "Accounting is currently in beta. Request access to enable reporting, journal entries, accounting periods, fixed assets, and more."
+msgstr "会计功能目前处于测试版。请求访问权限以启用报告、日记账、会计期间、固定资产等功能。"
+
msgid "Accounting is disabled"
msgstr "会计已禁用"
+msgid "Accounting is disabled for this company."
+msgstr "此公司已禁用会计功能。"
+
msgid "Accounting is enabled"
msgstr "会计已启用"
@@ -853,6 +869,9 @@ msgstr "之后"
msgid "After (calculation method)"
msgstr "之后(计算方法)"
+msgid "Aging"
+msgstr "账龄分析"
+
msgid "Agree on the scope"
msgstr "就范围达成一致"
@@ -871,6 +890,9 @@ msgstr "全部"
msgid "All {total} phases are done. Nice work — your team is up and running."
msgstr "所有 {total} 个阶段已完成。做得很好——你的团队已启动并运行。"
+msgid "All accounts"
+msgstr "所有账户"
+
msgid "All actions selected"
msgstr "所有操作已选中"
@@ -983,6 +1005,9 @@ msgstr "一个操作在其工作中心队列中的位置——车间拿起工作
msgid "An unexpected error occurred while connecting to Onshape. Try connecting again."
msgstr "连接 Onshape 时发生意外错误。请重新连接。"
+msgid "Analytics"
+msgstr "分析"
+
msgid "Anchors the Plan timeline to real dates. Leave blank for a relative, week-numbered timeline. Setting either one fills in the rest."
msgstr "将计划时间表锚定到实际日期。留空以获得相对的、按周编号的时间表。设置其中任何一个会填充其余部分。"
@@ -1026,6 +1051,9 @@ msgstr "任何物品类型"
msgid "Anything not explicitly listed in scope above"
msgstr "未在上述范围内明确列出的任何内容"
+msgid "AP Aging"
+msgstr "应付账款账龄"
+
msgid "AP Clerk"
msgstr "应付账款文员"
@@ -1138,6 +1166,9 @@ msgstr "AQL"
msgid "AQL (Z1.4 / ISO 2859-1)"
msgstr "AQL (Z1.4 / ISO 2859-1)"
+msgid "AR Aging"
+msgstr "应收账款账龄"
+
msgid "AR Clerk"
msgstr "应收账款文员"
@@ -1245,6 +1276,11 @@ msgstr "您确定要删除 {0} 吗?此操作无法撤销。"
msgid "Are you sure you want to delete {name}? This cannot be undone."
msgstr "您确定要删除 {name} 吗?此操作无法撤销。"
+#. placeholder {0}: activeView.name
+#. placeholder {0}: viewPendingDelete.name
+msgid "Are you sure you want to delete the \"{0}\" view? This cannot be undone."
+msgstr "您确定要删除\"{0}\"视图吗?此操作无法撤销。"
+
#. placeholder {0}: selectedCustomField?.name
msgid "Are you sure you want to delete the {0} field?"
msgstr "你确定要删除 {0} 字段吗?"
@@ -1634,6 +1670,9 @@ msgstr "资产ID"
msgid "Assets"
msgstr "资产"
+msgid "Assets, liabilities and equity as of a date"
+msgstr "特定日期的资产、负债和权益"
+
msgid "Assign printers to locations. Shipping, receiving, and work centers inherit the location default unless overridden."
msgstr "将打印机分配到位置。运输、接收和工作中心继承位置默认值,除非被覆盖。"
@@ -1890,6 +1929,9 @@ msgstr "低于安全库存"
msgid "Beta"
msgstr "测试版"
+msgid "Biggest causes of scrap by reason, item, or work center"
+msgstr "按原因、物料或工作中心显示最大报废原因"
+
msgid "Bill of Material"
msgstr "物料清单"
@@ -2020,12 +2062,18 @@ msgstr "由 {byUser}"
msgid "By accepting the invite, you agree to the <0>Terms of Service</0> and <1>Privacy Policy</1>."
msgstr "通过接受邀请,您同意<0>服务条款</0>和<1>隐私政策</1>。"
+msgid "By dimension"
+msgstr "按维度"
+
msgid "By Document Date"
msgstr "按单据日期"
msgid "By Due Date"
msgstr "按到期日期"
+msgid "By field"
+msgstr "按字段"
+
msgid "By Item"
msgstr "按物品"
@@ -2383,6 +2431,9 @@ msgstr "清除搜索"
msgid "Clear search query"
msgstr "清除搜索查询"
+msgid "Clear selection"
+msgstr "清除选择"
+
msgid "Clear this invoice with the party's posted credits as well as cash. Credits apply directly — no posting needed."
msgstr "用该方的已过账贷项和现金清算此发票。贷项直接应用——无需过账。"
@@ -2416,6 +2467,9 @@ msgstr "关闭日期"
msgid "Close Period"
msgstr "关闭期间"
+msgid "Close Reports"
+msgstr "关闭报告"
+
msgid "Close Status"
msgstr "关闭状态"
@@ -2464,6 +2518,12 @@ msgstr "折叠设置"
msgid "Collapse subtree"
msgstr "折叠子树"
+msgid "Column dimension"
+msgstr "列维度"
+
+msgid "Column field"
+msgstr "列字段"
+
msgid "Column visibility and order"
msgstr "列的可见性和顺序"
@@ -2560,6 +2620,9 @@ msgstr "完成条码"
msgid "Completion Time"
msgstr "完成时间"
+msgid "Condensed P&L with margins and key subtotals"
+msgstr "精简损益表,含利润率和关键小计"
+
msgid "Conditions"
msgstr "条件"
@@ -3041,6 +3104,9 @@ msgstr "销售成本(COGS)"
msgid "Cost of Goods Sold (default)"
msgstr "销售成本(默认)"
+msgid "Cost of Sales"
+msgstr "销售成本"
+
msgid "Costing"
msgstr "成本"
@@ -3852,6 +3918,10 @@ msgstr "定义多级物料清单和工艺流程(制造方法)"
msgid "Delete"
msgstr "删除"
+#. placeholder {0}: view.name
+msgid "Delete {0}"
+msgstr "删除 {0}"
+
msgid "Delete {name}"
msgstr "删除 {name}"
@@ -4138,6 +4208,9 @@ msgstr "删除类型"
msgid "Delete Unit of Measure"
msgstr "删除计量单位"
+msgid "Delete view"
+msgstr "删除视图"
+
msgid "Delete View"
msgstr "删除视图"
@@ -5241,6 +5314,9 @@ msgstr "用授权代码交换访问令牌失败。请重新连接。"
msgid "Excluded"
msgstr "已排除"
+msgid "Executive P&L"
+msgstr "执行损益表"
+
msgid "Exemption Certificate"
msgstr "豁免证书"
@@ -5311,6 +5387,9 @@ msgstr "递延税款变动的费用方面(与递延税款负债配对)。"
msgid "Expense side of deferred tax movements (paired with deferred tax liability)."
msgstr "无法创建资产类别: {0}"
+msgid "Expenses"
+msgstr "费用"
+
msgid "Expert guidance"
msgstr "专家指导"
@@ -5803,6 +5882,9 @@ msgstr "完成"
msgid "Finalizing a fiscal month through the Open → Locked → Closed lifecycle; a closed period is frozen and its balances snapshotted, reversible only by explicit reopen."
msgstr "通过打开 → 锁定 → 关闭生命周期完成财政月份;关闭的期间被冻结并其余额快照,仅可通过显式重新打开来反转。"
+msgid "Financial Statements"
+msgstr "财务报表"
+
msgid "finish"
msgstr "成品"
@@ -6263,9 +6345,15 @@ msgstr "等级"
msgid "Grades"
msgstr "等级"
+msgid "Gross Profit"
+msgstr "毛利润"
+
msgid "Group"
msgstr "组"
+msgid "Group by"
+msgstr "分组依据"
+
msgid "Group Members"
msgstr "群组成员"
@@ -6621,6 +6709,9 @@ msgstr "收入/余额(已继承)"
msgid "Income Statement"
msgstr "利润表"
+msgid "Income Tax"
+msgstr "所得税"
+
msgid "Income/Balance"
msgstr "收入/余额"
@@ -7166,6 +7257,9 @@ msgstr "劳动单位"
msgid "Language"
msgstr "语言"
+msgid "Last 6 Months"
+msgstr "最近6个月"
+
msgid "Last Calibration"
msgstr "最后校准"
@@ -7962,6 +8056,9 @@ msgstr "你欠的钱"
msgid "Money you owe"
msgstr "你欠的钱"
+msgid "Monthly"
+msgstr "每月"
+
msgid "Months over which this asset depreciates for tax purposes (when not using MACRS)."
msgstr "该资产按税务目的折旧的月数(不使用MACRS时)。"
@@ -8075,6 +8172,9 @@ msgstr "账面净值"
msgid "Net Change"
msgstr "净变化"
+msgid "Net Income"
+msgstr "净收入"
+
msgid "Never"
msgstr "永不"
@@ -8567,6 +8667,9 @@ msgstr "无项目"
msgid "No items have inventory activity here yet."
msgstr "此处尚无项目的库存活动。"
+msgid "No journal lines in scope for this period"
+msgstr "本期范围内没有日记账行"
+
msgid "No lines to map"
msgstr "没有行需要映射"
@@ -8666,6 +8769,9 @@ msgstr "未选择工艺"
msgid "No production events recorded for this operation yet"
msgstr "此操作尚未记录任何生产事件"
+msgid "No purchases in this period"
+msgstr "此期间无采购"
+
msgid "No Quote"
msgstr "无报价"
@@ -8684,6 +8790,9 @@ msgstr "没有参考图像"
msgid "No remaining entities to inspect."
msgstr "没有剩余的实体可检查。"
+msgid "No reports match your search."
+msgstr "未找到与搜索条件匹配的报告。"
+
msgid "No results"
msgstr "无结果"
@@ -8904,6 +9013,9 @@ msgstr "在此位置维护用于服务的最低库存"
msgid "On-hand inventory remains"
msgstr "现有库存仍然存在"
+msgid "On-hand value by location or item, with GL tie-out"
+msgstr "按地点或物品统计的在手价值,含总账对账"
+
msgid "On-hand value of manufactured goods (Make items)"
msgstr "制造商品(制造项)的现有价值"
@@ -9009,6 +9121,9 @@ msgstr "未结工单"
msgid "Open menu"
msgstr "打开菜单"
+msgid "Open payables by supplier and age"
+msgstr "按供应商和账龄统计的未清应付账款"
+
msgid "Open Purchase Invoices"
msgstr "未结采购发票"
@@ -9024,6 +9139,9 @@ msgstr "未结报价"
msgid "Open Reactive"
msgstr "开放反应"
+msgid "Open receivables by customer and age"
+msgstr "按客户和账龄统计的未清应收账款"
+
msgid "Open RFQs"
msgstr "未结RFQ"
@@ -9057,6 +9175,9 @@ msgstr "在将此资产添加到Carbon之前已入账的折旧的期初余额(
msgid "Operating Expenses"
msgstr "运营费用"
+msgid "Operating Income"
+msgstr "营业收入"
+
msgid "Operation"
msgstr "操作"
@@ -9172,6 +9293,12 @@ msgstr "原始"
msgid "Original Count"
msgstr "原始盘点"
+msgid "Other Expense"
+msgstr "其他费用"
+
+msgid "Other Income"
+msgstr "其他收入"
+
msgid "Other Income account for FX gains when a payment settles a foreign-currency invoice at a more favorable rate"
msgstr "当付款以更优惠的汇率结清外币发票时,外汇收益的其他收入账户"
@@ -9557,6 +9684,11 @@ msgstr "件/分钟"
msgid "Pin"
msgstr "固定"
+#. placeholder {0}: report.name
+#. placeholder {0}: view.name
+msgid "Pin {0}"
+msgstr "固定{0}"
+
msgid "Pinned"
msgstr "已固定"
@@ -10083,6 +10215,9 @@ msgstr "采购单位:"
msgid "Purchased"
msgstr "已购买"
+msgid "Purchases"
+msgstr "采购"
+
msgid "purchasing"
msgstr "采购和已售商品成本"
@@ -10211,6 +10346,9 @@ msgstr "此覆盖的基于数量的定价层;应用的单价是满足订单行
msgid "Quantity: {0}"
msgstr "数量:{0}"
+msgid "Quarterly"
+msgstr "季度"
+
msgid "Question"
msgstr "问题"
@@ -10678,6 +10816,9 @@ msgstr "补充系统"
msgid "Report"
msgstr "报告"
+msgid "Reporting"
+msgstr "报表"
+
msgid "Reporting dimension"
msgstr "报告维度"
@@ -10687,6 +10828,9 @@ msgstr "报告"
msgid "Reprint"
msgstr "重新打印"
+msgid "Request access"
+msgstr "请求访问"
+
msgid "Request Approval"
msgstr "请求批准"
@@ -10821,6 +10965,12 @@ msgstr "返回未使用的拣配物料"
msgid "Rev {revision}"
msgstr "Rev {revision}"
+msgid "Revenue"
+msgstr "收入"
+
+msgid "Revenue and expenses over a period"
+msgstr "期间的收入和费用"
+
msgid "Reverse all inventory adjustments"
msgstr "反转所有库存调整"
@@ -11153,9 +11303,15 @@ msgstr "保存联系人"
msgid "Save Method"
msgstr "保存方法"
+msgid "Save view"
+msgstr "保存视图"
+
msgid "Save View"
msgstr "保存视图"
+msgid "Saved Views"
+msgstr "已保存视图"
+
msgid "Saving..."
msgstr "保存中..."
@@ -11868,6 +12024,15 @@ msgstr "显示同步选项"
msgid "Showing {0} of {totalCount} — refine your search"
msgstr "显示 {0} 个,共 {totalCount} 个 — 优化搜索"
+msgid "Showing in {parentCurrency}"
+msgstr "显示货币:{parentCurrency}"
+
+msgid "Showing the first 500 lines"
+msgstr "显示前500行"
+
+msgid "Showing the top 1,000 groups by amount"
+msgstr "按金额显示前1,000个分组"
+
msgid "Shown as a faint background behind every page of generated PDFs"
msgstr "作为淡色背景显示在每个生成的PDF页面后面"
@@ -11937,6 +12102,15 @@ msgstr "已跳过"
msgid "Slack"
msgstr "Slack"
+msgid "Slice asset activity by location, item, or any dimension"
+msgstr "按位置、项目或任何维度细分资产活动"
+
+msgid "Slice expenses by location, cost center, or any dimension"
+msgstr "按位置、成本中心或任何维度细分支出"
+
+msgid "Slice revenue by customer, customer type, or any dimension"
+msgstr "按客户、客户类型或任何维度划分收入"
+
msgid "Smoke-test the core daily flows end to end"
msgstr "端到端烟雾测试核心日常流程"
@@ -12018,6 +12192,9 @@ msgstr "特定客户"
msgid "Specific Items"
msgstr "特定项目"
+msgid "Spend by supplier, item, or category — your biggest cost drivers"
+msgstr "按供应商、项目或类别的支出 — 您最大的成本驱动因素"
+
msgid "Split"
msgstr "分割"
@@ -13343,6 +13520,9 @@ msgstr "主题"
msgid "Theme Color"
msgstr "主题颜色"
+msgid "Then by"
+msgstr "然后按"
+
msgid "There are no active supplier quotes to compare for this RFQ."
msgstr "此RFQ没有有效的供应商报价可比较。"
@@ -13585,6 +13765,9 @@ msgstr "时区"
msgid "Title"
msgstr "标题"
+msgid "To Date"
+msgstr "截止日期"
+
msgid "To deactivate, use the row menu and choose Deactivate Account."
msgstr "要停用,请使用行菜单并选择停用账户。"
@@ -13976,6 +14159,11 @@ msgstr "取消拣选"
msgid "Unpick {0}"
msgstr "取消拣选 {0}"
+#. placeholder {0}: report.name
+#. placeholder {0}: view.name
+msgid "Unpin {0}"
+msgstr "取消固定{0}"
+
msgid "Unposted Documents"
msgstr "未过账单据"
@@ -14225,9 +14413,6 @@ msgstr "已验证"
msgid "Validating job..."
msgstr "正在验证工作..."
-msgid "Valuation"
-msgstr "估值"
-
msgid "Value"
msgstr "值"
@@ -14653,6 +14838,9 @@ msgstr "当您迁移到 Carbon 时会发生什么变化,以及大致的价值
msgid "What data"
msgstr "什么数据"
+msgid "What drove inventory up or down, by any dimension"
+msgstr "按任何维度推动库存上升或下降的因素"
+
msgid "What is {translatedTerm}?"
msgstr "{translatedTerm}是什么?"
@@ -15049,6 +15237,9 @@ msgstr "在资产的使用寿命期间降低其价值 — 您创建、作为草
msgid "Year"
msgstr "年份"
+msgid "Yearly"
+msgstr "年度"
+
msgid "Yes"
msgstr "是"
diff --git a/packages/utils/src/accounting.test.ts b/packages/utils/src/accounting.test.ts
new file mode 100644
index 0000000000..faf002fa2f
--- /dev/null
+++ b/packages/utils/src/accounting.test.ts
@@ -0,0 +1,201 @@
+import { describe, expect, it } from "vitest";
+import {
+ computeReportPeriodBuckets,
+ defaultReportRange,
+ fiscalYearAndPeriodFor,
+ MAX_REPORT_PERIOD_BUCKETS
+} from "./accounting";
+
+describe("defaultReportRange", () => {
+ it("spans the current partial month plus the five preceding whole months", () => {
+ // End mid-month → start is the 1st of the month five months earlier.
+ expect(defaultReportRange("2026-08-09")).toEqual({
+ startDate: "2026-03-01",
+ endDate: "2026-08-09"
+ });
+ });
+
+ it("crosses the year boundary without drift", () => {
+ expect(defaultReportRange("2026-02-15")).toEqual({
+ startDate: "2025-09-01",
+ endDate: "2026-02-15"
+ });
+ });
+});
+
+describe("computeReportPeriodBuckets — month", () => {
+ it("splits a calendar range into calendar months", () => {
+ const buckets = computeReportPeriodBuckets(
+ "2026-01-01",
+ "2026-03-31",
+ "month",
+ 1
+ );
+ expect(buckets.map((b) => [b.key, b.start, b.end])).toEqual([
+ ["2026-01", "2026-01-01", "2026-01-31"],
+ ["2026-02", "2026-02-01", "2026-02-28"],
+ ["2026-03", "2026-03-01", "2026-03-31"]
+ ]);
+ expect(buckets.every((b) => !b.isPartial)).toBe(true);
+ });
+
+ it("starts the first bucket mid-month without flagging it partial", () => {
+ const buckets = computeReportPeriodBuckets(
+ "2026-01-15",
+ "2026-02-28",
+ "month",
+ 1
+ );
+ expect(buckets[0]?.start).toBe("2026-01-15");
+ expect(buckets[0]?.end).toBe("2026-01-31");
+ expect(buckets[0]?.isPartial).toBe(false);
+ });
+
+ it("clamps and flags the trailing partial month", () => {
+ const buckets = computeReportPeriodBuckets(
+ "2026-01-01",
+ "2026-02-15",
+ "month",
+ 1
+ );
+ expect(buckets).toHaveLength(2);
+ expect(buckets[1]?.end).toBe("2026-02-15");
+ expect(buckets[1]?.isPartial).toBe(true);
+ expect(buckets[0]?.isPartial).toBe(false);
+ });
+
+ it("handles a single-bucket range", () => {
+ const buckets = computeReportPeriodBuckets(
+ "2026-02-01",
+ "2026-02-28",
+ "month",
+ 1
+ );
+ expect(buckets).toHaveLength(1);
+ expect(buckets[0]?.isPartial).toBe(false);
+ });
+
+ it("returns empty for an inverted range", () => {
+ expect(
+ computeReportPeriodBuckets("2026-03-01", "2026-01-01", "month", 1)
+ ).toEqual([]);
+ });
+
+ it("keeps the most recent buckets when the cap is exceeded", () => {
+ const buckets = computeReportPeriodBuckets(
+ "2000-01-01",
+ "2026-12-31",
+ "month",
+ 1
+ );
+ expect(buckets).toHaveLength(MAX_REPORT_PERIOD_BUCKETS);
+ expect(buckets[buckets.length - 1]?.end).toBe("2026-12-31");
+ expect(buckets[0]?.key).toBe("2022-01");
+ });
+});
+
+describe("computeReportPeriodBuckets — quarter", () => {
+ it("uses calendar quarters for a January fiscal start", () => {
+ const buckets = computeReportPeriodBuckets(
+ "2026-01-01",
+ "2026-12-31",
+ "quarter",
+ 1
+ );
+ expect(buckets.map((b) => [b.key, b.start, b.end, b.quarter])).toEqual([
+ ["FY2026-Q1", "2026-01-01", "2026-03-31", 1],
+ ["FY2026-Q2", "2026-04-01", "2026-06-30", 2],
+ ["FY2026-Q3", "2026-07-01", "2026-09-30", 3],
+ ["FY2026-Q4", "2026-10-01", "2026-12-31", 4]
+ ]);
+ });
+
+ it("uses fiscal quarters for an April fiscal start", () => {
+ // April start: Q1 = Apr-Jun, Q2 = Jul-Sep, Q3 = Oct-Dec, Q4 = Jan-Mar.
+ // FY named by its ending calendar year: Apr 2025 belongs to FY2026.
+ const buckets = computeReportPeriodBuckets(
+ "2025-04-01",
+ "2026-03-31",
+ "quarter",
+ 4
+ );
+ expect(buckets.map((b) => [b.key, b.start, b.end])).toEqual([
+ ["FY2026-Q1", "2025-04-01", "2025-06-30"],
+ ["FY2026-Q2", "2025-07-01", "2025-09-30"],
+ ["FY2026-Q3", "2025-10-01", "2025-12-31"],
+ ["FY2026-Q4", "2026-01-01", "2026-03-31"]
+ ]);
+ });
+
+ it("aligns a mid-quarter start to the containing fiscal quarter's end", () => {
+ const buckets = computeReportPeriodBuckets(
+ "2025-05-15",
+ "2025-08-31",
+ "quarter",
+ 4
+ );
+ expect(buckets.map((b) => [b.key, b.start, b.end, b.isPartial])).toEqual([
+ ["FY2026-Q1", "2025-05-15", "2025-06-30", false],
+ ["FY2026-Q2", "2025-07-01", "2025-08-31", true]
+ ]);
+ });
+});
+
+describe("computeReportPeriodBuckets — year", () => {
+ it("splits on fiscal-year boundaries for a January start", () => {
+ const buckets = computeReportPeriodBuckets(
+ "2024-01-01",
+ "2026-06-30",
+ "year",
+ 1
+ );
+ expect(buckets.map((b) => [b.key, b.start, b.end, b.isPartial])).toEqual([
+ ["FY2024", "2024-01-01", "2024-12-31", false],
+ ["FY2025", "2025-01-01", "2025-12-31", false],
+ ["FY2026", "2026-01-01", "2026-06-30", true]
+ ]);
+ });
+
+ it("splits on fiscal-year boundaries for a July start", () => {
+ // July start: FY2026 runs Jul 2025 - Jun 2026
+ const buckets = computeReportPeriodBuckets(
+ "2025-07-01",
+ "2026-06-30",
+ "year",
+ 7
+ );
+ expect(buckets.map((b) => [b.key, b.start, b.end, b.isPartial])).toEqual([
+ ["FY2026", "2025-07-01", "2026-06-30", false]
+ ]);
+ });
+
+ it("aligns a mid-fiscal-year start to the fiscal year end", () => {
+ const buckets = computeReportPeriodBuckets(
+ "2025-10-01",
+ "2026-09-30",
+ "year",
+ 7
+ );
+ expect(buckets.map((b) => [b.key, b.start, b.end, b.isPartial])).toEqual([
+ ["FY2026", "2025-10-01", "2026-06-30", false],
+ ["FY2027", "2026-07-01", "2026-09-30", true]
+ ]);
+ });
+});
+
+describe("fiscalYearAndPeriodFor (bucket key grounding)", () => {
+ it("names the fiscal year by its ending calendar year", () => {
+ expect(fiscalYearAndPeriodFor(2025, 7, 7)).toEqual({
+ fiscalYear: 2026,
+ periodNumber: 1
+ });
+ expect(fiscalYearAndPeriodFor(2026, 6, 7)).toEqual({
+ fiscalYear: 2026,
+ periodNumber: 12
+ });
+ expect(fiscalYearAndPeriodFor(2026, 2, 1)).toEqual({
+ fiscalYear: 2026,
+ periodNumber: 2
+ });
+ });
+});
diff --git a/packages/utils/src/accounting.ts b/packages/utils/src/accounting.ts
index cc1e14f661..4604280286 100644
--- a/packages/utils/src/accounting.ts
+++ b/packages/utils/src/accounting.ts
@@ -1,3 +1,5 @@
+import type { CalendarDate } from "@internationalized/date";
+import { endOfMonth, parseDate } from "@internationalized/date";
import { formatDate } from "./date";
type AccountType = "asset" | "liability" | "equity" | "revenue" | "expense";
@@ -102,3 +104,127 @@ export function fiscalYearAndPeriodFor(
export function formatPeriodLabel(startDate: string, locale?: string): string {
return formatDate(startDate, { year: "numeric", month: "long" }, locale);
}
+
+/**
+ * The default reporting window every range report opens on: the trailing six
+ * months — the current partial month plus the five preceding whole months.
+ * `endDate` is a `YYYY-MM-DD` date in the caller's business timezone (server
+ * loaders pass the company-tz today; the client PeriodSelector passes the local
+ * today). Single source of truth so the selector's label and the loader's query
+ * can never drift ("All Time" in the picker while the data was really 6 months).
+ */
+export function defaultReportRange(endDate: string): {
+ startDate: string;
+ endDate: string;
+} {
+ return {
+ startDate: parseDate(endDate)
+ .subtract({ months: 5 })
+ .set({ day: 1 })
+ .toString(),
+ endDate
+ };
+}
+
+export type ReportColumnGranularity = "month" | "quarter" | "year";
+
+export type ReportPeriodBucket = {
+ key: string; // "2026-02" | "FY2026-Q1" | "FY2026" — stable Record key
+ start: string; // ISO date (bucket start; the first bucket starts at the range start)
+ end: string; // ISO date, clamped to the range end
+ fiscalYear: number;
+ quarter?: number; // 1-4, fiscal quarters (only for "quarter")
+ isPartial: boolean; // end was clamped before the bucket's natural end
+};
+
+// Guards a monthly bucketing of a very wide range; when exceeded the MOST
+// RECENT buckets are kept (the trailing periods are what reports compare).
+export const MAX_REPORT_PERIOD_BUCKETS = 60;
+
+function fiscalYearStartFor(
+ date: CalendarDate,
+ startMonth: number
+): CalendarDate {
+ const year = date.month >= startMonth ? date.year : date.year - 1;
+ return date.set({ year, month: startMonth, day: 1 });
+}
+
+// Natural (unclamped) end of the bucket containing `date`.
+function bucketNaturalEnd(
+ date: CalendarDate,
+ granularity: ReportColumnGranularity,
+ startMonth: number
+): CalendarDate {
+ switch (granularity) {
+ case "month":
+ return endOfMonth(date);
+ case "quarter": {
+ const { periodNumber } = fiscalYearAndPeriodFor(
+ date.year,
+ date.month,
+ startMonth
+ );
+ const monthsIntoQuarter = (periodNumber - 1) % 3;
+ const quarterStart = date
+ .subtract({ months: monthsIntoQuarter })
+ .set({ day: 1 });
+ return endOfMonth(quarterStart.add({ months: 2 }));
+ }
+ case "year":
+ return endOfMonth(
+ fiscalYearStartFor(date, startMonth).add({ months: 11 })
+ );
+ }
+}
+
+// Splits [startDate, endDate] into contiguous fiscal-aware buckets. Bucket ends
+// after the first fall on natural boundaries (month/fiscal-quarter/fiscal-year
+// ends); the trailing bucket is clamped to endDate and flagged isPartial when
+// clamped early. The result is the ONLY valid producer of the p_period_ends
+// argument to the accountTreeBalancePeriodSeries RPC (sorted ascending,
+// distinct, all >= startDate).
+export function computeReportPeriodBuckets(
+ startDate: string,
+ endDate: string,
+ granularity: ReportColumnGranularity,
+ fiscalStartMonth: number // 1-12
+): ReportPeriodBucket[] {
+ const rangeStart = parseDate(startDate);
+ const rangeEnd = parseDate(endDate);
+ if (rangeEnd.compare(rangeStart) < 0) return [];
+
+ const buckets: ReportPeriodBucket[] = [];
+ let cursor = rangeStart;
+ while (cursor.compare(rangeEnd) <= 0) {
+ const naturalEnd = bucketNaturalEnd(cursor, granularity, fiscalStartMonth);
+ const isPartial = naturalEnd.compare(rangeEnd) > 0;
+ const end = isPartial ? rangeEnd : naturalEnd;
+ const { fiscalYear, periodNumber } = fiscalYearAndPeriodFor(
+ cursor.year,
+ cursor.month,
+ fiscalStartMonth
+ );
+ const quarter = Math.ceil(periodNumber / 3);
+ const key =
+ granularity === "month"
+ ? `${cursor.year}-${String(cursor.month).padStart(2, "0")}`
+ : granularity === "quarter"
+ ? `FY${fiscalYear}-Q${quarter}`
+ : `FY${fiscalYear}`;
+
+ buckets.push({
+ key,
+ start: cursor.toString(),
+ end: end.toString(),
+ fiscalYear,
+ ...(granularity === "quarter" ? { quarter } : {}),
+ isPartial
+ });
+
+ cursor = naturalEnd.add({ days: 1 });
+ }
+
+ return buckets.length > MAX_REPORT_PERIOD_BUCKETS
+ ? buckets.slice(-MAX_REPORT_PERIOD_BUCKETS)
+ : buckets;
+}