Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
feat(accounting): customer/supplier and invoice number on the general ledger (#2026)
Brad Barbin835b19a5cbcd
diff --git a/.ai/runs/2026-10-23-average-cost-purchases.md b/.ai/runs/2026-10-23-average-cost-purchases.mdnew file mode 100644index 0000000000..c045485652--- /dev/null+++ b/.ai/runs/2026-10-23-average-cost-purchases.md@@ -0,0 +1,33 @@+# Bugfix run: Average costing wrong for purchased items++- Date: 2026-10-23+- Mode: fully-autonomous+- Request: "do we support average cost (in addition to lifo and fifo) and is it correct?" → "ok fix it"+- Phase plan: root-cause [run, inline in conversation] · instrument [skip — static cause is HIGH] · fix [run] · test [skip — pure posting logic, regression tests cover it] · commit [skip — not asked]++## Decisions++- instrument: skip — cause read directly from code, HIGH confidence.+- browser test: skip — no UI change.+- local DB is down (localhost:54322): database regressions are written but skip; pure tests carry the red→green proof. Did not start the shared stack.+- moving-average formula mirrors complete_job_to_inventory: (prior on-hand × cost + value) / (prior + quantity), cost kept when the result has no stock. Keeps valuation (qty × cost) equal to what the journals booked.+- invoice variance on an Average item: on-hand share (company-wide on-hand, shared across the invoice's lines of the item) to inventory, rest to PPV — the same rule the legacy self-heal path already uses.+- updatePurchasedPrices: stops writing unitCost for Average items only; FIFO/LIFO/Standard behavior unchanged (out of scope).++## Phase log++- root-cause (HIGH): Average outbound uses itemCost.unitCost; PO receipts never update it; updatePurchasedPrices overwrites it with a trailing-12-month Σcost/Σqty over every costLedger row (incl. PO planning rows); invoice variance capitalized fully because Average never draws receipt layers down.++- fix: READY. movingAverageUnitCost + applyAverageCostChanges (shared.service.ts); wired into postReceipt post + void, postPurchaseInvoice post (direct received lines, on-hand write-up) + void; buildPurchaseInvoicePostingLines caps an Average item's write-up at on-hand shared across lines; updatePurchasedPrices skips Average.+- gates: biome PASS · typecheck(erp) PASS · erp vitest (DB URL unset) 2744 passed / 473 skipped. average-cost.test.ts (live DB) written, NOT run — DB down.++## Outcome++- Committed on PR #2026. Known gaps left: existing Average costs not backfilled; asset return-to-inventory at NBV and manual unitCost edits do not move the average.++## Review follow-up (2026-10-25, CodeRabbit on #2026)++- movingAverageUnitCost blends negative on-hand as zero: a receipt into negative stock takes its own cost (raw blending gave 30 for a 20 receipt, or a negative cost). complete_job_to_inventory still blends the raw prior quantity; not changed here (migration).+- postReceipt: negative receipt lines now enter the Average change at the cost calculateCOGS relieved, so a receipt mixing positive and negative lines of one item keeps on-hand × cost equal to the journal.+- purchase invoice void: reverses each received PO line's write-up as read from the original journal (the line's only debit to the raw materials / finished goods account) instead of Σ adjustment children. Covers legacy self-heal layers and stored write-ups, which the post added to the average and the void never took back.+- gates: biome PASS · typecheck(erp) PASS · pure tests 41 passed. DB tests (average-cost.test.ts, lease.test.ts) still not run: no local database.diff --git a/apps/erp/app/modules/accounting/AGENTS.md b/apps/erp/app/modules/accounting/AGENTS.mdindex de6faef63c..6e4da453e3 100644--- a/apps/erp/app/modules/accounting/AGENTS.md+++ b/apps/erp/app/modules/accounting/AGENTS.md@@ -4,7 +4,7 @@ Chart of accounts, journal entries, general ledger, fiscal periods, currencies,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,general-ledger,inventory-valuation,revenue-waterfall,rental-utilization,lease-net-investment}` — 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).-The **General Ledger** (`general-ledger.tsx`, hub card in Close Reports) lists every line of the `journalLines` view (Posted and Reversed journals only) for one company and a date range: `getGeneralLedgerLines` (paged, the shared `Table` with account / source / document type filters, search and sorts) and `getAllGeneralLedgerLines` (`fetchAll`, every line) for the Download, served by the resource route `general-ledger[.]csv.tsx`. Both routes parse the request with `resolveGeneralLedgerRequest` (`general-ledger.server.ts`): one company (lines are in its base currency, so "All Companies" is off — `allowAllCompanies={false}` on `ReportFilters`) and the trial balance's default range.+The **General Ledger** (`general-ledger.tsx`, hub card in Close Reports) lists every line of the `journalLines` view (Posted and Reversed journals only) for one company and a date range: `getGeneralLedgerLines` (paged, the shared `Table` with account / source / document type filters, search and sorts) and `getAllGeneralLedgerLines` (`fetchAll`, every line) for the Download, served by the resource route `general-ledger[.]csv.tsx`. The page and the CSV both carry Customer / Supplier, Invoice Number and Supplier Invoice Number (Supplier Invoice Number hidden by default on the page; none sortable or filterable, since they are not view columns): `withGeneralLedgerCounterparties` reads each line's `documentType` + `documentId` (the source record's `id`; "Invoice" ids are tried in both invoice tables, and a payment line's `documentLineReference` is the invoice it settles) and `generalLedgerCounterparty` (`accounting.utils.ts`) resolves one line. Lines with no customer/supplier document (jobs, inventory, manual entries) leave them blank. Both routes parse the request with `resolveGeneralLedgerRequest` (`general-ledger.server.ts`): one company (lines are in its base currency, so "All Companies" is off — `allowAllCompanies={false}` on `ReportFilters`) and the trial balance's default range.**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/ui` (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.diff --git a/apps/erp/app/modules/accounting/accounting.service.ts b/apps/erp/app/modules/accounting/accounting.service.tsindex 7529d4b023..8c5625ea29 100644--- a/apps/erp/app/modules/accounting/accounting.service.ts+++ b/apps/erp/app/modules/accounting/accounting.service.ts@@ -296,6 +296,8 @@ import {depreciationRunLinesMatch,diffJournalLines,fiscalYearPeriodDates,+ type GeneralLedgerDocument,+ generalLedgerCounterparty,hasAccountingCutover,hidesSupersededJournals,isFutureRunPeriod,@@ -317,6 +319,7 @@ import type {AccountLedgerLine,ChartPeriodSeries,GeneralLedgerLine,+ GeneralLedgerRow,PeriodCell,Transaction,TranslatedBalance@@ -474,7 +477,7 @@ export async function getAccountLedger(// only — the lines the trial balance sums. The `journalLines` view filters the// same statuses; the report states them so it holds if the view changes.const GENERAL_LEDGER_LINE_COLUMNS =- "id, journalId, journalEntryId, postingDate, status, sourceType, journalDescription, description, amount, accountId, documentType, account(number, name, class)";+ "id, journalId, journalEntryId, postingDate, status, sourceType, journalDescription, description, amount, accountId, documentType, documentId, documentLineReference, account(number, name, class)";type GeneralLedgerArgs = Pick<GenericQueryFilters, "sorts" | "filters"> & {search: string | null;@@ -540,6 +543,191 @@ export async function getAllGeneralLedgerLines();}+const NO_DOCUMENT: GeneralLedgerDocument = {+ invoiceNumber: null,+ supplierInvoiceNumber: null,+ customerId: null,+ supplierId: null,+ merchantName: null+};++/**+ * General ledger lines with their customer or supplier name and invoice+ * numbers, read from the documents they were posted from — the page's and the+ * CSV's Customer / Supplier, Invoice Number and Supplier Invoice Number.+ *+ * "Invoice" ids are tried against both invoice tables: the opening balance+ * and revenue recognition journals carry no purchase/sales `sourceType` to+ * tell them apart. A payment line's `documentLineReference` is the invoice it+ * settles. Lines of other document types (jobs, inventory, manual entries)+ * have no counterparty and are not read.+ */+export async function withGeneralLedgerCounterparties(+ client: SupabaseClient<Database>,+ companyId: string,+ lines: GeneralLedgerLine[]+): Promise<+ | { data: GeneralLedgerRow[]; error: null }+ | { data: null; error: PostgrestError }+> {+ const idsByType = new Map<string, Set<string>>();+ const addId = (type: string, id: string | null) => {+ if (!id) return;+ const ids = idsByType.get(type) ?? new Set<string>();+ ids.add(id);+ idsByType.set(type, ids);+ };+ for (const line of lines) {+ if (!line.documentType) continue;+ addId(line.documentType, line.documentId);+ if (line.documentType === "Payment") {+ addId("Invoice", line.documentLineReference);+ }+ }+ const idsOf = (...types: string[]) => [+ ...new Set(types.flatMap((type) => [...(idsByType.get(type) ?? [])]))+ ];++ const documents = new Map<string, GeneralLedgerDocument>();+ const add = (+ rows: ({ id: string } & Partial<GeneralLedgerDocument>)[] | null+ ) => {+ for (const { id, ...document } of rows ?? []) {+ documents.set(id, { ...NO_DOCUMENT, ...document });+ }+ };++ const invoiceIds = idsOf("Invoice");+ const reads = await Promise.all([+ fetchAllByIds(invoiceIds, (batch) =>+ client+ .from("salesInvoice")+ .select("id, invoiceNumber:invoiceId, customerId")+ .eq("companyId", companyId)+ .in("id", batch)+ .order("id")+ ),+ fetchAllByIds(invoiceIds, (batch) =>+ client+ .from("purchaseInvoice")+ .select(+ "id, invoiceNumber:invoiceId, supplierInvoiceNumber:supplierReference, supplierId"+ )+ .eq("companyId", companyId)+ .in("id", batch)+ .order("id")+ ),+ fetchAllByIds(idsOf("Payment"), (batch) =>+ client+ .from("payment")+ .select("id, customerId, supplierId")+ .eq("companyId", companyId)+ .in("id", batch)+ .order("id")+ ),+ fetchAllByIds(idsOf("Memo"), (batch) =>+ client+ .from("memo")+ .select("id, customerId, supplierId")+ .eq("companyId", companyId)+ .in("id", batch)+ .order("id")+ ),+ fetchAllByIds(idsOf("Receipt"), (batch) =>+ client+ .from("receipt")+ .select("id, supplierId")+ .eq("companyId", companyId)+ .in("id", batch)+ .order("id")+ ),+ fetchAllByIds(idsOf("Sales Shipment", "Return Order"), (batch) =>+ client+ .from("shipment")+ .select("id, customerId, supplierId")+ .eq("companyId", companyId)+ .in("id", batch)+ .order("id")+ ),+ fetchAllByIds(idsOf("Charge"), (batch) =>+ client+ .from("charge")+ .select("id, supplierId, merchantName")+ .eq("companyId", companyId)+ .in("id", batch)+ .order("id")+ ),+ fetchAllByIds(idsOf("Contract"), (batch) =>+ client+ .from("customerContract")+ .select("id, customerId")+ .eq("companyId", companyId)+ .in("id", batch)+ .order("id")+ ),+ fetchAllByIds(idsOf("Rental Agreement"), (batch) =>+ client+ .from("rentalAgreement")+ .select("id, customerId")+ .eq("companyId", companyId)+ .in("id", batch)+ .order("id")+ ),+ fetchAllByIds(idsOf("Lease"), (batch) =>+ client+ .from("lease")+ .select("id, supplierId")+ .eq("companyId", companyId)+ .in("id", batch)+ .order("id")+ )+ ]);+ for (const read of reads) {+ if (read.error) return { data: null, error: read.error };+ add(read.data);+ }++ const customerIds = new Set<string>();+ const supplierIds = new Set<string>();+ for (const document of documents.values()) {+ if (document.customerId) customerIds.add(document.customerId);+ if (document.supplierId) supplierIds.add(document.supplierId);+ }+ const [customers, suppliers] = await Promise.all([+ fetchAllByIds([...customerIds], (batch) =>+ client+ .from("customer")+ .select("id, name")+ .eq("companyId", companyId)+ .in("id", batch)+ .order("id")+ ),+ fetchAllByIds([...supplierIds], (batch) =>+ client+ .from("supplier")+ .select("id, name")+ .eq("companyId", companyId)+ .in("id", batch)+ .order("id")+ )+ ]);+ if (customers.error) return { data: null, error: customers.error };+ if (suppliers.error) return { data: null, error: suppliers.error };++ const partyNames = new Map<string, string>();+ for (const party of [...customers.data, ...suppliers.data]) {+ partyNames.set(party.id, party.name);+ }++ return {+ data: lines.map((line) => ({+ ...line,+ ...generalLedgerCounterparty(line, documents, partyNames)+ })),+ error: null+ };+}+export async function getAccountLedgerSummary(client: SupabaseClient<Database>,companyGroupId: string,diff --git a/apps/erp/app/modules/accounting/accounting.utils.test.ts b/apps/erp/app/modules/accounting/accounting.utils.test.tsindex 42a6a9f8a2..665c2240ff 100644--- a/apps/erp/app/modules/accounting/accounting.utils.test.ts+++ b/apps/erp/app/modules/accounting/accounting.utils.test.ts@@ -18,6 +18,7 @@ import {depreciationRunLineDisplay,depreciationRunLinesMatch,diffJournalLines,+ generalLedgerCounterparty,getLastDayOfMonth,getMacrsPercentage,getMonthsBetween,@@ -1361,3 +1362,101 @@ describe("hasAccountingCutover", () => {expect(hasAccountingCutover(null)).toBe(false);});});++describe("generalLedgerCounterparty", () => {+ const document = {+ invoiceNumber: null,+ supplierInvoiceNumber: null,+ customerId: null,+ supplierId: null,+ merchantName: null+ };+ const documents = new Map([+ ["si1", { ...document, invoiceNumber: "INV000012", customerId: "cust1" }],+ [+ "pi1",+ {+ ...document,+ invoiceNumber: "PI000007",+ supplierInvoiceNumber: "ACME-4471",+ supplierId: "sup1"+ }+ ],+ ["pay1", { ...document, customerId: "cust1" }],+ ["ch1", { ...document, merchantName: "Hardware Store" }]+ ]);+ const partyNames = new Map([+ ["cust1", "Orbital Corp"],+ ["sup1", "Acme Metals"]+ ]);+ const line = (+ documentType: string | null,+ documentId: string | null,+ documentLineReference: string | null = null+ ) => ({ documentType, documentId, documentLineReference });++ it("names a sales invoice's customer and number", () => {+ expect(+ generalLedgerCounterparty(line("Invoice", "si1"), documents, partyNames)+ ).toEqual({+ party: "Orbital Corp",+ invoiceNumber: "INV000012",+ supplierInvoiceNumber: null+ });+ });++ it("names a purchase invoice's supplier and both numbers", () => {+ expect(+ generalLedgerCounterparty(line("Invoice", "pi1"), documents, partyNames)+ ).toEqual({+ party: "Acme Metals",+ invoiceNumber: "PI000007",+ supplierInvoiceNumber: "ACME-4471"+ });+ });++ it("reads a payment line's invoice from its line reference", () => {+ expect(+ generalLedgerCounterparty(+ line("Payment", "pay1", "si1"),+ documents,+ partyNames+ )+ ).toEqual({+ party: "Orbital Corp",+ invoiceNumber: "INV000012",+ supplierInvoiceNumber: null+ });+ });++ it("falls back to a charge's merchant when it has no supplier", () => {+ expect(+ generalLedgerCounterparty(line("Charge", "ch1"), documents, partyNames)+ ).toEqual({+ party: "Hardware Store",+ invoiceNumber: null,+ supplierInvoiceNumber: null+ });+ });++ it("leaves a line with no document blank", () => {+ expect(+ generalLedgerCounterparty(line(null, null), documents, partyNames)+ ).toEqual({+ party: null,+ invoiceNumber: null,+ supplierInvoiceNumber: null+ });+ expect(+ generalLedgerCounterparty(+ line("Job Receipt", "job1"),+ documents,+ partyNames+ )+ ).toEqual({+ party: null,+ invoiceNumber: null,+ supplierInvoiceNumber: null+ });+ });+});diff --git a/apps/erp/app/modules/accounting/accounting.utils.ts b/apps/erp/app/modules/accounting/accounting.utils.tsindex a66d61c7ce..54d11af9c6 100644--- a/apps/erp/app/modules/accounting/accounting.utils.ts+++ b/apps/erp/app/modules/accounting/accounting.utils.ts@@ -1138,6 +1138,62 @@ function isCalendarDateString(value: string): boolean {// non-deletable system definition).export const LOCK_PERIOD_TASK_NAME = "Lock the period";+/**+ * What the document behind a general ledger line says about who it was with.+ * Keyed by the document's id: every posting writes the record's `id`+ * (an `xid()`, unique across tables) into `journalLine.documentId`.+ */+export type GeneralLedgerDocument = {+ invoiceNumber: string | null;+ supplierInvoiceNumber: string | null;+ customerId: string | null;+ supplierId: string | null;+ // A card charge with no supplier still names who was paid+ merchantName: string | null;+};++export type GeneralLedgerCounterparty = {+ party: string | null;+ invoiceNumber: string | null;+ supplierInvoiceNumber: string | null;+};++/**+ * The customer or supplier and the invoice of a general ledger line. An+ * invoice line names its invoice in `documentId`; a payment line names the+ * payment there and the invoice it settles in `documentLineReference`.+ */+export function generalLedgerCounterparty(+ line: {+ documentType: string | null;+ documentId: string | null;+ documentLineReference: string | null;+ },+ documents: ReadonlyMap<string, GeneralLedgerDocument>,+ partyNames: ReadonlyMap<string, string>+): GeneralLedgerCounterparty {+ const document = line.documentId ? documents.get(line.documentId) : undefined;+ const invoice =+ line.documentType === "Payment" && line.documentLineReference+ ? documents.get(line.documentLineReference)+ : document;++ const partyId =+ document?.customerId ??+ document?.supplierId ??+ invoice?.customerId ??+ invoice?.supplierId;++ return {+ party:+ (partyId ? partyNames.get(partyId) : undefined) ??+ document?.merchantName ??+ null,+ invoiceNumber: invoice?.invoiceNumber ?? null,+ supplierInvoiceNumber: invoice?.supplierInvoiceNumber ?? null+ };+}+/** The companies a financial report covers: every company for "all", the one* named, else the user's own. Null when the selection is empty or names a* company outside the group, so a report never reads another group's ledger. */diff --git a/apps/erp/app/modules/accounting/types.ts b/apps/erp/app/modules/accounting/types.tsindex 65d7987070..d8e0bc62d4 100644--- a/apps/erp/app/modules/accounting/types.ts+++ b/apps/erp/app/modules/accounting/types.ts@@ -24,6 +24,7 @@ import type {getPurchaseLinePivotLines,getReportViews} from "./accounting.service";+import type { GeneralLedgerCounterparty } from "./accounting.utils";export type Account = NonNullable<Awaited<ReturnType<typeof getAccount>>["data"]@@ -457,6 +458,9 @@ export type GeneralLedgerLine = NonNullable<NonNullable<Awaited<ReturnType<typeof getGeneralLedgerLines>>>["data"]>[number];+/** A general ledger line with the customer or supplier and invoice it was posted from. */+export type GeneralLedgerRow = GeneralLedgerLine & GeneralLedgerCounterparty;+export type JournalEntryListItem = NonNullable<NonNullable<Awaited<ReturnType<typeof getJournalEntries>>>["data"]>[number];diff --git a/apps/erp/app/modules/accounting/ui/Reports/GeneralLedgerTable.tsx b/apps/erp/app/modules/accounting/ui/Reports/GeneralLedgerTable.tsxindex 77c3cfc926..88056821ec 100644--- a/apps/erp/app/modules/accounting/ui/Reports/GeneralLedgerTable.tsx+++ b/apps/erp/app/modules/accounting/ui/Reports/GeneralLedgerTable.tsx@@ -11,8 +11,11 @@ import {LuBookmark,LuCalendar,LuCircleDollarSign,+ LuContainer,LuFileText,LuLandmark,+ LuQrCode,+ LuReceipt,LuTag} from "react-icons/lu";import { DateTime, Hyperlink, Table } from "~/components";@@ -23,34 +26,34 @@ import {journalEntrySourceTypes,journalLineDocumentType} from "../../accounting.models";-import type { AccountClass, GeneralLedgerLine } from "../../types";+import type { AccountClass, GeneralLedgerRow } from "../../types";import JournalEntryStatus from "../JournalEntries/JournalEntryStatus";type GeneralLedgerTableProps = {- data: GeneralLedgerLine[];+ data: GeneralLedgerRow[];count: number;accounts: { id: string; number: string | null; name: string | null }[];currencyCode: string;};const defaultColumnVisibility = {- documentType: false+ supplierInvoiceNumber: false};-function accountLabel(line: GeneralLedgerLine) {+function accountLabel(line: GeneralLedgerRow) {return [line.account?.number, line.account?.name].filter(Boolean).join(" ");}// `amount` is signed by the account's natural balance, so debit and credit// depend on the account's class-function debitOf(line: GeneralLedgerLine) {+function debitOf(line: GeneralLedgerRow) {return toDisplayDebit(line.amount ?? 0,(line.account?.class ?? "Asset") as AccountClass);}-function creditOf(line: GeneralLedgerLine) {+function creditOf(line: GeneralLedgerRow) {return toDisplayCredit(line.amount ?? 0,(line.account?.class ?? "Asset") as AccountClass@@ -62,7 +65,7 @@ const GeneralLedgerTable = memo(const { t } = useLingui();const currencyFormatter = useCurrencyFormatter({ currency: currencyCode });- const columns = useMemo<ColumnDef<GeneralLedgerLine>[]>(+ const columns = useMemo<ColumnDef<GeneralLedgerRow>[]>(() => [{accessorKey: "postingDate",@@ -130,6 +133,30 @@ const GeneralLedgerTable = memo(row.description ?? row.journalDescription ?? null}},+ {+ id: "debit",+ header: t`Debit`,+ cell: ({ row }) => {+ const debit = debitOf(row.original);+ return debit !== 0 ? currencyFormatter.format(debit) : "";+ },+ meta: {+ icon: <LuCircleDollarSign />,+ exportValue: debitOf+ }+ },+ {+ id: "credit",+ header: t`Credit`,+ cell: ({ row }) => {+ const credit = creditOf(row.original);+ return credit !== 0 ? currencyFormatter.format(credit) : "";+ },+ meta: {+ icon: <LuCircleDollarSign />,+ exportValue: creditOf+ }+ },{accessorKey: "sourceType",header: t`Source`,@@ -162,28 +189,33 @@ const GeneralLedgerTable = memo(}}},+ // Read from the line's document, not columns of the view, so they+ // are neither sortable nor filterable{- id: "debit",- header: t`Debit`,- cell: ({ row }) => {- const debit = debitOf(row.original);- return debit !== 0 ? currencyFormatter.format(debit) : "";- },+ id: "party",+ header: t`Customer / Supplier`,+ cell: ({ row }) => row.original.party ?? "",meta: {- icon: <LuCircleDollarSign />,- exportValue: debitOf+ icon: <LuContainer />,+ exportValue: (row) => row.party}},{- id: "credit",- header: t`Credit`,- cell: ({ row }) => {- const credit = creditOf(row.original);- return credit !== 0 ? currencyFormatter.format(credit) : "";- },+ id: "invoiceNumber",+ header: t`Invoice Number`,+ cell: ({ row }) => row.original.invoiceNumber ?? "",meta: {- icon: <LuCircleDollarSign />,- exportValue: creditOf+ icon: <LuReceipt />,+ exportValue: (row) => row.invoiceNumber+ }+ },+ {+ id: "supplierInvoiceNumber",+ header: t`Supplier Invoice Number`,+ cell: ({ row }) => row.original.supplierInvoiceNumber ?? "",+ meta: {+ icon: <LuQrCode />,+ exportValue: (row) => row.supplierInvoiceNumber}}],@@ -191,7 +223,7 @@ const GeneralLedgerTable = memo();return (- <Table<GeneralLedgerLine>+ <Table<GeneralLedgerRow>data={data}columns={columns}count={count}diff --git a/apps/erp/app/modules/inventory/inventory.service.ts b/apps/erp/app/modules/inventory/inventory.service.tsindex 858bcde03e..afdcf00f6f 100644--- a/apps/erp/app/modules/inventory/inventory.service.ts+++ b/apps/erp/app/modules/inventory/inventory.service.ts@@ -138,6 +138,8 @@ import {import * as settingsService from "~/modules/settings/settings.service";import {type AdjustmentItemCost,+ type AverageCostChange,+ applyAverageCostChanges,assertCompanyRecords,assertPostable,attributesContain,@@ -10404,6 +10406,22 @@ export async function postReceipt("Cannot void: stock received on this receipt was already consumed. Correct the remainder with an inventory adjustment instead.");}+ // The receipt's units leave an Average item at the cost they came+ // in at. Before the reversing item ledger rows: on-hand as it stood.+ await applyAverageCostChanges(trx, {+ companyId,+ changes: receiptCostLedger.flatMap((row) =>+ row.itemId+ ? [+ {+ itemId: row.itemId,+ quantity: -Number(row.quantity),+ value: -Number(row.cost)+ }+ ]+ : []+ )+ });if (costLedgerPlan.layerIdsToClose.length > 0) {await trx.updateTable("costLedger")@@ -10654,6 +10672,9 @@ export async function postReceipt(itemId: string;quantity: number;}[] = [];+ // What each line books (a negative line at the cost it relieves),+ // for an Average item's unit cost.+ const averageCostChanges: AverageCostChange[] = [];const isOutsideProcessing =purchaseOrder.data.purchaseOrderType === "Outside Processing";@@ -11129,6 +11150,11 @@ export async function postReceipt(// Cost layers: the receipt is the sole creator of purchase layers.// The invoice later adjusts them via appliesToCostLedgerId children.if (createsLayers && !isNegativeReceipt) {+ averageCostChanges.push({+ itemId: receiptLine.itemId!,+ quantity: receivedQuantity,+ value: receiptLineCosts[index]!.cost+ });if (invoiceFirstQty > 0) {costLedgerInserts.push({itemLedgerType: "Purchase",@@ -11458,6 +11484,11 @@ export async function postReceipt(? cogsResult.totalCost: receiptLineCosts[consumption.index]!.cost;relievedCostByLine.set(consumption.index, consumedCost);+ averageCostChanges.push({+ itemId: consumption.itemId,+ quantity: -consumption.quantity,+ value: -consumedCost+ });costLedgerInserts.push({itemLedgerType: "Purchase",costLedgerType: "Direct Cost",@@ -11594,6 +11625,11 @@ export async function postReceipt(.execute();}}+ // Before the item ledger rows below: on-hand as it stood.+ await applyAverageCostChanges(trx, {+ companyId,+ changes: averageCostChanges+ });for await (const [purchaseOrderLineId, update] of Object.entries(purchaseOrderLineUpdatesdiff --git a/apps/erp/app/modules/invoicing/invoicing.service.ts b/apps/erp/app/modules/invoicing/invoicing.service.tsindex 00eba63995..148881ea8b 100644--- a/apps/erp/app/modules/invoicing/invoicing.service.ts+++ b/apps/erp/app/modules/invoicing/invoicing.service.ts@@ -184,6 +184,8 @@ import {} from "~/modules/sales/sales.service";import { getCompanySettings } from "~/modules/settings/settings.service";import {+ type AverageCostChange,+ applyAverageCostChanges,assertNoMigrationClearing,assertPostable,calculateCOGS,@@ -13856,10 +13858,36 @@ function allocate(};}+/**+ * An Average item's coverage: its receipt layers are never drawn down, so+ * they cannot say what is still in stock. The item's on-hand does, and the+ * layers only carry the write-up — capped, oldest first, at the on-hand the+ * invoice's earlier lines of the item have not already taken.+ */+function averageCoverage(+ coverage: Extract<VarianceCoverage, { receiptLayers: unknown }>,+ onHand: number+): Extract<VarianceCoverage, { receiptLayers: unknown }> {+ let left = Math.max(0, onHand);+ return {+ receiptLayers: coverage.receiptLayers.map((layer) => {+ const remainingQuantity = Math.min(+ Math.max(layer.remainingQuantity, 0),+ left+ );+ left -= remainingQuantity;+ return { ...layer, remainingQuantity };+ }),+ onHandQuantity: Math.max(0, onHand)+ };+}+export function buildPurchaseInvoicePostingLines(input: BuildPurchaseInvoicePostingLinesInput): PurchaseInvoicePosting {const { invoice, accounts, payables, supplierTypeId } = input;+ // An Average item's on-hand still free to take a write-up, per item.+ const averageOnHandLeft = new Map<string, number>();const clearings = new Map<string, Clearing>();// The variance of the lines that share a stored write-up, per item.@@ -14002,11 +14030,35 @@ export function buildPurchaseInvoicePostingLines(// Received units clear GR/IR at their receipt cost.const clearing = clearings.get(line.id);if (clearing) {+ const { coverage } = purchaseOrderLine;+ const averageItemId =+ item.costingMethod === "Average" && "receiptLayers" in coverage+ ? item.itemId+ : null;+ const onHandLeft =+ averageItemId && "receiptLayers" in coverage+ ? (averageOnHandLeft.get(averageItemId) ??+ coverage.onHandQuantity)+ : 0;const { allocation, selfHealQuantity } = allocate(clearing,- purchaseOrderLine.coverage,+ averageItemId && "receiptLayers" in coverage+ ? averageCoverage(coverage, onHandLeft)+ : coverage,item.itemId ? (writeUpVarianceByItem.get(item.itemId) ?? 0) : 0);+ if (averageItemId) {+ const covered =+ selfHealQuantity ++ allocation.perLayer.reduce(+ (sum, entry) => sum + entry.appliedQuantity,+ 0+ );+ averageOnHandLeft.set(+ averageItemId,+ Math.max(0, onHandLeft - covered)+ );+ }receivedVariances.set(line.id, {quantity: clearing.quantity,receiptCost: clearing.receiptCost,@@ -14796,6 +14848,64 @@ export async function postPurchaseInvoice(!selfHealLayersVoid.includes(entry));+ // What the void takes back off an Average item: the units a direct+ // line received and their cost, and the write-up each received PO line+ // booked. The write-up is read from the journal, where it is that+ // line's only debit to an inventory account: it is the posting's+ // `inventoryShare` whether it went onto receipt layers, into a legacy+ // self-heal layer (whose cost also holds the receipt's) or nowhere.+ const accountDefaultsVoid = await getDefaultPostingGroup(db, companyId);+ if (accountDefaultsVoid.error || !accountDefaultsVoid.data) {+ throw new Error("Failed to fetch account defaults");+ }+ const inventoryAccountsVoid = new Set([+ accountDefaultsVoid.data.rawMaterialsAccount,+ accountDefaultsVoid.data.finishedGoodsAccount+ ]);+ const itemIdByLineReferenceVoid = new Map(+ invoiceLinesVoid.data.flatMap((line) =>+ line.purchaseOrderLineId && line.itemId+ ? [+ [+ journalReference.to.purchaseInvoice(line.purchaseOrderLineId),+ line.itemId+ ] as const+ ]+ : []+ )+ );+ const receivedItemIdsVoid = new Set(+ originalItemLedger.data.map((entry) => entry.itemId)+ );+ const averageCostChangesVoid: AverageCostChange[] = [+ ...originalItemLedger.data.map((entry) => ({+ itemId: entry.itemId,+ quantity: -Number(entry.quantity),+ value: 0+ })),+ ...plainCostLedgerVoid.flatMap((entry) =>+ entry.itemId && receivedItemIdsVoid.has(entry.itemId)+ ? [+ {+ itemId: entry.itemId,+ quantity: 0,+ value: -Number(entry.cost)+ }+ ]+ : []+ ),+ ...originalJournalLines.flatMap((entry) => {+ const itemId = entry.documentLineReference+ ? itemIdByLineReferenceVoid.get(entry.documentLineReference)+ : undefined;+ return itemId &&+ entry.accountId &&+ inventoryAccountsVoid.has(entry.accountId)+ ? [{ itemId, quantity: 0, value: -Number(entry.amount) }]+ : [];+ })+ ];+const reversingCostLedger: Database["public"]["Tables"]["costLedger"]["Insert"][] =plainCostLedgerVoid.map((entry) => ({itemLedgerType: entry.itemLedgerType,@@ -14897,6 +15007,12 @@ export async function postPurchaseInvoice(.execute();}+ // Before the reversing item ledger rows: on-hand as it stood.+ await applyAverageCostChanges(trx, {+ companyId,+ changes: averageCostChangesVoid+ });+if (reversingItemLedger.length > 0) {await trx.insertInto("itemLedger")@@ -15220,6 +15336,8 @@ export async function postPurchaseInvoice(const itemLedgerInserts: Database["public"]["Tables"]["itemLedger"]["Insert"][] =[];+ // What the journal books to an Average item's inventory, per line.+ const averageCostChanges: AverageCostChange[] = [];const purchaseInvoiceLinesByPurchaseOrderLine =purchaseInvoiceLines.data.reduce<@@ -15453,22 +15571,28 @@ export async function postPurchaseInvoice(];}));- const selfHealItemIds = [+ // The on-hand of an item whose receipts wrote no layer, and of an+ // Average item, whose layers are never drawn down.+ const onHandItemIds = [...new Set(layerLines- .filter((line) => layersByInvoiceLine.get(line.id)?.length === 0)+ .filter(+ (line) =>+ layersByInvoiceLine.get(line.id)?.length === 0 ||+ itemOf(line.itemId).costingMethod === "Average"+ ).map((line) => line.itemId as string))];const onHand =- selfHealItemIds.length > 0+ onHandItemIds.length > 0? await db.selectFrom("itemLedger").select((eb) => ["itemId",eb.fn.sum<number>("quantity").as("quantity")])- .where("itemId", "in", selfHealItemIds)+ .where("itemId", "in", onHandItemIds).where("companyId", "=", companyId).groupBy("itemId").execute()@@ -15747,6 +15871,11 @@ export async function postPurchaseInvoice(// Only create item ledger entries if the receipt is being posted// (not when skipReceiptPost is true, as entries will be created when the receipt is posted later)if (itemTrackingType === "Inventory" && !skipReceiptPost) {+ averageCostChanges.push({+ itemId: invoiceLine.itemId!,+ quantity: invoiceLineQuantityInInventoryUnit,+ value: totalLineCostWithWeightedShipping+ });itemLedgerInserts.push({postingDate: today,itemId: invoiceLine.itemId!,@@ -15791,6 +15920,18 @@ export async function postPurchaseInvoice(// invoice adjusts the receipt's layers instead of creating its own.if (!received) continue;+ // The on-hand share the journal writes up inventory with.+ if (+ invoiceLine.itemId &&+ Math.abs(received.allocation.inventoryShare) > VARIANCE_THRESHOLD+ ) {+ averageCostChanges.push({+ itemId: invoiceLine.itemId,+ quantity: 0,+ value: round(received.allocation.inventoryShare)+ });+ }+// Subledger: adjustment child rows on the covered layers, consumed// alongside their parent by calculateCOGS.for (const entry of received.allocation.perLayer) {@@ -16312,6 +16453,12 @@ export async function postPurchaseInvoice(.execute();}+ // Before the item ledger rows below: on-hand as it stood.+ await applyAverageCostChanges(trx, {+ companyId,+ changes: averageCostChanges+ });+if (itemLedgerInserts.length > 0) {await trx.insertInto("itemLedger")diff --git a/apps/erp/app/modules/purchasing/purchasing.service.ts b/apps/erp/app/modules/purchasing/purchasing.service.tsindex 5acaff3989..f3036d2cb5 100644--- a/apps/erp/app/modules/purchasing/purchasing.service.ts+++ b/apps/erp/app/modules/purchasing/purchasing.service.ts@@ -7696,6 +7696,10 @@ export async function updatePurchasedPrices(.set(itemCostUpdate).where("itemId", "=", itemCostUpdate.itemId!).where("companyId", "=", companyId)+ // An Average item's unit cost is its moving average, kept by the+ // receipts and invoices that move its value; a year of purchase+ // history is not what is on hand.+ .where("costingMethod", "!=", "Average").execute();}}diff --git a/apps/erp/app/modules/shared/shared.service.ts b/apps/erp/app/modules/shared/shared.service.tsindex eee1876377..30637a7c69 100644--- a/apps/erp/app/modules/shared/shared.service.ts+++ b/apps/erp/app/modules/shared/shared.service.ts@@ -16045,6 +16045,120 @@ export function computeCurrentUnitCost(return Number(itemCost.unitCost ?? 0);}}++/**+ * An Average item's unit cost after `quantity` units worth `value` come in+ * (or go out, both negative) at a cost of their own: a receipt, a voided+ * receipt, an invoice's write-up (`quantity` 0). The same moving average+ * complete_job_to_inventory keeps, so on-hand × unit cost stays what the+ * journals booked. With nothing left on hand the cost stays as it was.+ * Negative on-hand (shipped before it was received) blends in as zero: those+ * units hold no stock to average with, so a receipt into them takes its own+ * cost rather than a skewed, possibly negative, one.+ */+export function movingAverageUnitCost({+ onHand,+ unitCost,+ quantity,+ value+}: {+ onHand: number;+ unitCost: number;+ quantity: number;+ value: number;+}): number {+ const held = Math.max(onHand, 0);+ const after = held + quantity;+ if (after <= EPSILON) return unitCost;+ return (held * unitCost + value) / after;+}++/** Units and value a posting moves at their own cost, per item. */+export type AverageCostChange = {+ itemId: string;+ quantity: number;+ value: number;+};++/**+ * Folds `changes` into the unit cost of every Average item among them+ * (`movingAverageUnitCost`); other costing methods are left alone. Call it+ * BEFORE the posting inserts its own item ledger rows: on-hand is read as it+ * stood before them. Locks the cost rows, so two postings of one item+ * average in turn.+ */+export async function applyAverageCostChanges(+ trx: Transaction<DB>,+ { companyId, changes }: { companyId: string; changes: AverageCostChange[] }+): Promise<void> {+ const byItem = new Map<string, { quantity: number; value: number }>();+ for (const change of changes) {+ const total = byItem.get(change.itemId) ?? { quantity: 0, value: 0 };+ total.quantity += change.quantity;+ total.value += change.value;+ byItem.set(change.itemId, total);+ }+ if (byItem.size === 0) return;++ const averageCosts = await trx+ .selectFrom("itemCost")+ .select(["itemId", "unitCost"])+ .where("companyId", "=", companyId)+ .where("itemId", "in", [...byItem.keys()])+ .where("costingMethod", "=", "Average")+ .orderBy("itemId")+ .forUpdate()+ .execute();+ if (averageCosts.length === 0) return;++ const onHand = await trx+ .selectFrom("itemLedger")+ .select((eb) => ["itemId", eb.fn.sum<number>("quantity").as("quantity")])+ .where("companyId", "=", companyId)+ .where(+ "itemId",+ "in",+ averageCosts.map((row) => row.itemId)+ )+ .groupBy("itemId")+ .execute();+ const onHandByItem = new Map(+ onHand.map((row) => [row.itemId, Number(row.quantity ?? 0)])+ );++ const updates = averageCosts.flatMap((row) => {+ const unitCost = Number(row.unitCost ?? 0);+ const change = byItem.get(row.itemId)!;+ const next = round(+ movingAverageUnitCost({+ onHand: onHandByItem.get(row.itemId) ?? 0,+ unitCost,+ quantity: change.quantity,+ value: change.value+ })+ );+ return equals(next, unitCost) ? [] : [{ itemId: row.itemId, next }];+ });+ if (updates.length === 0) return;++ await trx+ .updateTable("itemCost")+ .set({+ unitCost: sql<number>`CASE "itemId" ${sql.join(+ updates.map(+ ({ itemId, next }) => sql`WHEN ${itemId} THEN ${next}::numeric`+ ),+ sql` `+ )} END`+ })+ .where("companyId", "=", companyId)+ .where(+ "itemId",+ "in",+ updates.map((update) => update.itemId)+ )+ .execute();+}export interface BookAdjustmentArgs {ledger: {postingDate: string; // yyyy-MM-dddiff --git a/apps/erp/app/routes/x+/reports+/general-ledger.tsx b/apps/erp/app/routes/x+/reports+/general-ledger.tsxindex 39898de68e..e11d4de7a6 100644--- a/apps/erp/app/routes/x+/reports+/general-ledger.tsx+++ b/apps/erp/app/routes/x+/reports+/general-ledger.tsx@@ -11,7 +11,8 @@ import type { LoaderFunctionArgs } from "react-router";import { useLoaderData, useLocation } from "react-router";import {getAccountsList,- getGeneralLedgerLines+ getGeneralLedgerLines,+ withGeneralLedgerCounterparties} from "~/modules/accounting/accounting.service";import {GeneralLedgerTable,@@ -54,8 +55,20 @@ export async function loader({ request }: LoaderFunctionArgs) {);}+ const rows = await withGeneralLedgerCounterparties(+ client,+ selectedCompany.id,+ lines.data ?? []+ );+ if (rows.error) {+ throw redirect(+ path.to.reports,+ await flash(request, error(rows.error, "Failed to load general ledger"))+ );+ }+return {- lines: lines.data ?? [],+ lines: rows.data,count: lines.count ?? 0,accounts: accounts.data ?? [],companies,diff --git a/apps/erp/app/routes/x+/reports+/general-ledger[.]csv.tsx b/apps/erp/app/routes/x+/reports+/general-ledger[.]csv.tsxindex 51a2e0c1ed..2b29d5f71d 100644--- a/apps/erp/app/routes/x+/reports+/general-ledger[.]csv.tsx+++ b/apps/erp/app/routes/x+/reports+/general-ledger[.]csv.tsx@@ -6,7 +6,10 @@ import { CSV_CONTENT_TYPE, encodeCsv } from "@carbon/files/csv";import { getLogger } from "@carbon/logger";import { toDisplayCredit, toDisplayDebit } from "@carbon/utils";import type { LoaderFunctionArgs } from "react-router";-import { getAllGeneralLedgerLines } from "~/modules/accounting/accounting.service";+import {+ getAllGeneralLedgerLines,+ withGeneralLedgerCounterparties+} from "~/modules/accounting/accounting.service";import type { AccountClass } from "~/modules/accounting/types";import { resolveGeneralLedgerRequest } from "./general-ledger.server";@@ -33,8 +36,23 @@ export async function loader({ request }: LoaderFunctionArgs) {});}+ const rows = await withGeneralLedgerCounterparties(+ client,+ selectedCompany.id,+ lines.data ?? []+ );+ if (rows.error) {+ logger.error("Failed to read the general ledger's documents", {+ companyId: selectedCompany.id,+ error: rows.error+ });+ throw new Response("The general ledger could not be exported.", {+ status: 500+ });+ }+const csv = encodeCsv(- (lines.data ?? []).map((line) => {+ rows.data.map((line) => {const accountClass = (line.account?.class ?? "Asset") as AccountClass;return {Date: line.postingDate,@@ -43,11 +61,14 @@ export async function loader({ request }: LoaderFunctionArgs) {"Account Number": line.account?.number,"Account Name": line.account?.name,Description: line.description ?? line.journalDescription,- Source: line.sourceType,- "Document Type": line.documentType,Debit: toDisplayDebit(line.amount ?? 0, accountClass),Credit: toDisplayCredit(line.amount ?? 0, accountClass),- Currency: selectedCompany.baseCurrencyCode+ Currency: selectedCompany.baseCurrencyCode,+ Source: line.sourceType,+ "Document Type": line.documentType,+ "Customer / Supplier": line.party,+ "Invoice Number": line.invoiceNumber,+ "Supplier Invoice Number": line.supplierInvoiceNumber};}),{@@ -58,11 +79,14 @@ export async function loader({ request }: LoaderFunctionArgs) {"Account Number","Account Name","Description",- "Source",- "Document Type","Debit","Credit",- "Currency"+ "Currency",+ "Source",+ "Document Type",+ "Customer / Supplier",+ "Invoice Number",+ "Supplier Invoice Number"]});diff --git a/apps/erp/test/database/average-cost.test.ts b/apps/erp/test/database/average-cost.test.tsnew file mode 100644index 0000000000..3db29c32cd--- /dev/null+++ b/apps/erp/test/database/average-cost.test.ts@@ -0,0 +1,68 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++// An Average item's unit cost against the live database: a purchase receipt+// averages its cost into the stock on hand, and voiding it takes it out again.++import { expect } from "vitest";+import { postReceipt } from "../../app/modules/inventory/inventory.service";+import { invokePosting } from "../../app/modules/shared/shared.service";+import {+ alwaysPostFixture,+ type Fixture,+ receiveFromPurchaseOrder,+ seed,+ stockPart,+ unwrap+} from "./fixtures/always-post";+import { handlesOf } from "./fixtures/handles";+import { databaseTest } from "./fixtures/local-database";++async function useAverageCost(f: Fixture, unitCost: number) {+ await seed(f, (trx) =>+ trx+ .updateTable("itemCost")+ .set({ costingMethod: "Average", unitCost })+ .where("itemId", "=", f.partId)+ .where("companyId", "=", f.companyId)+ .execute()+ );+}++async function unitCostOf(f: Fixture): Promise<number> {+ const row = await f.db+ .selectFrom("itemCost")+ .select("unitCost")+ .where("itemId", "=", f.partId)+ .where("companyId", "=", f.companyId)+ .executeTakeFirstOrThrow();+ return Number(row.unitCost);+}++databaseTest(+ "a purchase receipt averages an Average item's cost into the stock on hand, and its void takes it out",+ async () => {+ const f = await alwaysPostFixture();+ try {+ await useAverageCost(f, 10);+ await stockPart(f, 10);++ // 10 on hand at 10, 10 received at 20.+ const receiptId = await receiveFromPurchaseOrder(f, "1", 20);+ expect(await unitCostOf(f)).toBe(15);++ unwrap(+ await invokePosting(+ handlesOf(f.ctx),+ "post-receipt",+ { type: "void", receiptId },+ postReceipt+ )+ );+ expect(await unitCostOf(f)).toBe(10);+ } finally {+ await f.cleanup();+ }+ }+);diff --git a/apps/erp/test/database/fixtures/always-post.ts b/apps/erp/test/database/fixtures/always-post.tsindex 643a3f2b5c..1b27b7c958 100644--- a/apps/erp/test/database/fixtures/always-post.ts+++ b/apps/erp/test/database/fixtures/always-post.ts@@ -495,7 +495,8 @@ export async function stockPart(export async function receiveFromPurchaseOrder(f: Fixture,- key = "1"+ key = "1",+ unitPrice = 10): Promise<string> {const purchaseOrderId = `${f.prefix}-po-${key}`;await seed(f, async (trx) => {@@ -532,7 +533,7 @@ export async function receiveFromPurchaseOrder(purchaseOrderLineType: "Part",itemId: f.partId,purchaseQuantity: 10,- supplierUnitPrice: 10,+ supplierUnitPrice: unitPrice,exchangeRate: 1,conversionFactor: 1,inventoryUnitOfMeasureCode: "EA",diff --git a/apps/erp/test/database/lib/moving-average-unit-cost.test.ts b/apps/erp/test/database/lib/moving-average-unit-cost.test.tsnew file mode 100644index 0000000000..a1bfb4c91a--- /dev/null+++ b/apps/erp/test/database/lib/moving-average-unit-cost.test.ts@@ -0,0 +1,88 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { describe, expect, it } from "vitest";+import { movingAverageUnitCost } from "~/modules/shared/shared.service";++describe("movingAverageUnitCost", () => {+ it("blends a receipt into the stock on hand", () => {+ // 10 on hand at 10, 10 received for 200.+ expect(+ movingAverageUnitCost({+ onHand: 10,+ unitCost: 10,+ quantity: 10,+ value: 200+ })+ ).toBe(15);+ });++ it("takes the receipt's own cost when nothing is on hand", () => {+ expect(+ movingAverageUnitCost({ onHand: 0, unitCost: 10, quantity: 10, value: 200 })+ ).toBe(20);+ });++ it("ignores how long ago the stock on hand was bought", () => {+ // 100 bought at 10 over a year ago, 5 shipped since, 10 received at 20.+ // A trailing-year average of the cost ledger read 30 here.+ const cost = movingAverageUnitCost({+ onHand: 95,+ unitCost: 10,+ quantity: 10,+ value: 200+ });+ expect(cost).toBeCloseTo((95 * 10 + 200) / 105, 10);+ });++ it("spreads a price variance over the units on hand", () => {+ // 4 on hand at 10 take an 8 write-up: 12 a unit.+ expect(+ movingAverageUnitCost({ onHand: 4, unitCost: 10, quantity: 0, value: 8 })+ ).toBe(12);+ });++ it("takes units out at their own cost", () => {+ // A voided receipt of 10 for 200 out of 20 on hand at 15.+ expect(+ movingAverageUnitCost({+ onHand: 20,+ unitCost: 15,+ quantity: -10,+ value: -200+ })+ ).toBe(10);+ });++ it("takes the receipt's own cost into negative stock", () => {+ // 5 shipped before any were received, then 10 received for 200. Blending+ // the -5 at 10 read 30; for 20, (−50 + 20) / 5 read a negative cost.+ expect(+ movingAverageUnitCost({ onHand: -5, unitCost: 10, quantity: 10, value: 200 })+ ).toBe(20);+ expect(+ movingAverageUnitCost({ onHand: -5, unitCost: 10, quantity: 10, value: 20 })+ ).toBe(2);+ });++ it("keeps the cost when a receipt does not cover negative stock", () => {+ expect(+ movingAverageUnitCost({ onHand: -5, unitCost: 10, quantity: -2, value: -20 })+ ).toBe(10);+ });++ it("keeps the cost when nothing is left on hand", () => {+ expect(+ movingAverageUnitCost({+ onHand: 10,+ unitCost: 15,+ quantity: -10,+ value: -200+ })+ ).toBe(15);+ expect(+ movingAverageUnitCost({ onHand: 0, unitCost: 15, quantity: 0, value: 8 })+ ).toBe(15);+ });+});diff --git a/apps/erp/test/database/post-purchase-invoice/posting-lines.test.ts b/apps/erp/test/database/post-purchase-invoice/posting-lines.test.tsindex e750713908..b5fc8afdb8 100644--- a/apps/erp/test/database/post-purchase-invoice/posting-lines.test.ts+++ b/apps/erp/test/database/post-purchase-invoice/posting-lines.test.ts@@ -149,6 +149,83 @@ describe("buildPurchaseInvoicePostingLines", () => {});});+ it("writes up an Average item's inventory only for the units still on hand", () => {+ // Average costing never draws a receipt layer down, so the layer still+ // reads 10 remaining after 6 of the 10 were sold. On-hand (4) decides.+ const { lines, receivedVariances } = build([+ ordered(+ "a",+ 10,+ 100,+ {+ quantityReceived: 10,+ receiptGroups: [{ quantity: 10, cost: 80 }],+ coverage: {+ receiptLayers: [+ { id: "layer-1", quantity: 10, remainingQuantity: 10 }+ ],+ onHandQuantity: 4+ }+ },+ { ...part, costingMethod: "Average" }+ )+ ]);++ expect(summary(lines)).toEqual([+ { accountId: "grni", amount: debit("liability", 80), quantity: 10 },+ { accountId: "raw", amount: debit("asset", 8), quantity: 10 },+ { accountId: "ppv", amount: debit("expense", 12), quantity: 10 },+ { accountId: "ap", amount: credit("liability", 100), quantity: 10 }+ ]);+ expect(receivedVariances.get("a")?.allocation.perLayer).toEqual([+ { costLedgerId: "layer-1", appliedQuantity: 4, adjustmentCost: 8 }+ ]);+ });++ it("shares an Average item's on-hand across the invoice's lines of that item", () => {+ // Two lines of 5, each 2 a unit over receipt cost, with 6 on hand: the+ // first line's 5 units are on hand, then only 1 of the second's.+ const average = { ...part, costingMethod: "Average" as const };+ const coverage = (id: string) => ({+ receiptLayers: [{ id, quantity: 5, remainingQuantity: 5 }],+ onHandQuantity: 6+ });+ const { lines } = build([+ ordered(+ "a",+ 5,+ 50,+ {+ quantityReceived: 5,+ receiptGroups: [{ quantity: 5, cost: 40 }],+ coverage: coverage("layer-a")+ },+ average+ ),+ ordered(+ "b",+ 5,+ 50,+ {+ quantityReceived: 5,+ receiptGroups: [{ quantity: 5, cost: 40 }],+ coverage: coverage("layer-b")+ },+ average+ )+ ]);++ expect(summary(lines)).toEqual([+ { accountId: "grni", amount: debit("liability", 40), quantity: 5 },+ { accountId: "raw", amount: debit("asset", 10), quantity: 5 },+ { accountId: "ap", amount: credit("liability", 50), quantity: 5 },+ { accountId: "grni", amount: debit("liability", 40), quantity: 5 },+ { accountId: "raw", amount: debit("asset", 2), quantity: 5 },+ { accountId: "ppv", amount: debit("expense", 8), quantity: 5 },+ { accountId: "ap", amount: credit("liability", 50), quantity: 5 }+ ]);+ });+it("skips the units an earlier invoice cleared and accrues the units not yet received", () => {// Two receipts of 3 (at 6, then at 9); an earlier invoice cleared 3, so// this invoice of 5 clears the second receipt and accrues 2.diff --git a/docs/content/docs/reference/financial-reports.mdx b/docs/content/docs/reference/financial-reports.mdxindex 70e431529f..aa40a9a741 100644--- a/docs/content/docs/reference/financial-reports.mdx+++ b/docs/content/docs/reference/financial-reports.mdx@@ -68,11 +68,11 @@ The account ledger drawer (the drill-down you get by clicking an account on any## General Ledger-The **General Ledger** report lists every posted journal line in a date range, one row per line: posting date, journal entry, account, description, source and the debit or credit. Open it from **Accounting → Reports → General Ledger**. It reads the same Posted and Reversed journals as the statements, so its lines for an account and range add up to that account's Trial Balance movement.+The **General Ledger** report lists every posted journal line in a date range, one row per line: posting date, journal entry, account, description, the debit or credit, source, document type, and the customer or supplier and invoice number of the document it was posted from. A payment line names the invoice it settles; the supplier's own invoice number is a hidden column you can show. Open it from **Accounting → Reports → General Ledger**. It reads the same Posted and Reversed journals as the statements, so its lines for an account and range add up to that account's Trial Balance movement.- It shows one company at a time, in that company's base currency. The company selector has no "All Companies" option here.- The period picker sets the range and defaults to the trailing six months, as the Trial Balance does.-- Filter the table by account, source or document type, search by journal entry number or description, and sort by any column. Lines sort by posting date, then journal entry, by default.+- Filter the table by account, source or document type, search by journal entry number or description, and sort by date, journal entry, account, description, source or document type. Lines sort by posting date, then journal entry, by default.- **Download** exports every line in the range with the current filters, not only the page on screen.## Relateddiff --git a/packages/locale/locales/de/erp.po b/packages/locale/locales/de/erp.poindex 861220ebe7..31383a0d5a 100644--- a/packages/locale/locales/de/erp.po+++ b/packages/locale/locales/de/erp.po@@ -6758,6 +6758,9 @@ msgstr "Kunde"msgid "Customer"msgstr "Kunde"+msgid "Customer / Supplier"+msgstr "Kunde / Lieferant"+msgid "Customer Accounts"msgstr "Kundenkonten"diff --git a/packages/locale/locales/en/erp.po b/packages/locale/locales/en/erp.poindex 1c5c3eb21f..418f43518c 100644--- a/packages/locale/locales/en/erp.po+++ b/packages/locale/locales/en/erp.po@@ -6758,6 +6758,9 @@ msgstr "customer"msgid "Customer"msgstr "Customer"+msgid "Customer / Supplier"+msgstr "Customer / Supplier"+msgid "Customer Accounts"msgstr "Customer Accounts"diff --git a/packages/locale/locales/es/erp.po b/packages/locale/locales/es/erp.poindex fb54f148ca..a0f6391a7b 100644--- a/packages/locale/locales/es/erp.po+++ b/packages/locale/locales/es/erp.po@@ -6758,6 +6758,9 @@ msgstr "cliente"msgid "Customer"msgstr "Cliente"+msgid "Customer / Supplier"+msgstr "Cliente / Proveedor"+msgid "Customer Accounts"msgstr "Cuentas de Cliente"diff --git a/packages/locale/locales/fr/erp.po b/packages/locale/locales/fr/erp.poindex 0a276e987c..a4c657b252 100644--- a/packages/locale/locales/fr/erp.po+++ b/packages/locale/locales/fr/erp.po@@ -6758,6 +6758,9 @@ msgstr "client"msgid "Customer"msgstr "Client"+msgid "Customer / Supplier"+msgstr "Client / Fournisseur"+msgid "Customer Accounts"msgstr "Comptes Clients"diff --git a/packages/locale/locales/hi/erp.po b/packages/locale/locales/hi/erp.poindex d90c28afbc..5b83b1bed1 100644--- a/packages/locale/locales/hi/erp.po+++ b/packages/locale/locales/hi/erp.po@@ -6758,6 +6758,9 @@ msgstr "ग्राहक"msgid "Customer"msgstr "ग्राहक"+msgid "Customer / Supplier"+msgstr "ग्राहक / आपूर्तिकर्ता"+msgid "Customer Accounts"msgstr "ग्राहक खाते"diff --git a/packages/locale/locales/it/erp.po b/packages/locale/locales/it/erp.poindex cf23b4d6bc..8262642982 100644--- a/packages/locale/locales/it/erp.po+++ b/packages/locale/locales/it/erp.po@@ -6758,6 +6758,9 @@ msgstr "cliente"msgid "Customer"msgstr "Cliente"+msgid "Customer / Supplier"+msgstr "Cliente / Fornitore"+msgid "Customer Accounts"msgstr "Account Cliente"diff --git a/packages/locale/locales/ja/erp.po b/packages/locale/locales/ja/erp.poindex 693fdc9870..b4ba2bad41 100644--- a/packages/locale/locales/ja/erp.po+++ b/packages/locale/locales/ja/erp.po@@ -6758,6 +6758,9 @@ msgstr "得意先"msgid "Customer"msgstr "得意先"+msgid "Customer / Supplier"+msgstr "得意先 / 仕入先"+msgid "Customer Accounts"msgstr "得意先アカウント"diff --git a/packages/locale/locales/ko/erp.po b/packages/locale/locales/ko/erp.poindex 37343a5003..d101745e4a 100644--- a/packages/locale/locales/ko/erp.po+++ b/packages/locale/locales/ko/erp.po@@ -6758,6 +6758,9 @@ msgstr "고객"msgid "Customer"msgstr "고객"+msgid "Customer / Supplier"+msgstr "고객 / 공급업체"+msgid "Customer Accounts"msgstr "고객 계정"diff --git a/packages/locale/locales/pl/erp.po b/packages/locale/locales/pl/erp.poindex 59b4db5def..c81daebd19 100644--- a/packages/locale/locales/pl/erp.po+++ b/packages/locale/locales/pl/erp.po@@ -6758,6 +6758,9 @@ msgstr "klient"msgid "Customer"msgstr "Klient"+msgid "Customer / Supplier"+msgstr "Klient / Dostawca"+msgid "Customer Accounts"msgstr "Konta Klientów"diff --git a/packages/locale/locales/pt/erp.po b/packages/locale/locales/pt/erp.poindex a8c30462ed..8f8096b036 100644--- a/packages/locale/locales/pt/erp.po+++ b/packages/locale/locales/pt/erp.po@@ -6758,6 +6758,9 @@ msgstr "cliente"msgid "Customer"msgstr "Cliente"+msgid "Customer / Supplier"+msgstr "Cliente / Fornecedor"+msgid "Customer Accounts"msgstr "Contas de Cliente"diff --git a/packages/locale/locales/ru/erp.po b/packages/locale/locales/ru/erp.poindex 928ce5f680..f1fc8ad866 100644--- a/packages/locale/locales/ru/erp.po+++ b/packages/locale/locales/ru/erp.po@@ -6758,6 +6758,9 @@ msgstr "покупатель"msgid "Customer"msgstr "Покупатель"+msgid "Customer / Supplier"+msgstr "Покупатель / Поставщик"+msgid "Customer Accounts"msgstr "Счета покупателя"diff --git a/packages/locale/locales/tr/erp.po b/packages/locale/locales/tr/erp.poindex c6ca0adbc0..ac2722b513 100644--- a/packages/locale/locales/tr/erp.po+++ b/packages/locale/locales/tr/erp.po@@ -6758,6 +6758,9 @@ msgstr "müşteri"msgid "Customer"msgstr "Müşteri"+msgid "Customer / Supplier"+msgstr "Müşteri / Tedarikçi"+msgid "Customer Accounts"msgstr "Müşteri Hesapları"diff --git a/packages/locale/locales/zh/erp.po b/packages/locale/locales/zh/erp.poindex 9f5dc83a62..479c4e456a 100644--- a/packages/locale/locales/zh/erp.po+++ b/packages/locale/locales/zh/erp.po@@ -6758,6 +6758,9 @@ msgstr "客户"msgid "Customer"msgstr "客户"+msgid "Customer / Supplier"+msgstr "客户 / 供应商"+msgid "Customer Accounts"msgstr "客户账户"