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(inventory): CSV imports for opening stock quantities

Raul784666c528be
diff --git a/.claude/rules/csv-import-system.md b/.claude/rules/csv-import-system.md
index 9d3c40d96a..044726b222 100644
--- a/.claude/rules/csv-import-system.md
+++ b/.claude/rules/csv-import-system.md
@@ -74,7 +74,8 @@ Other exports: `creatableLookups`, and types `CreatableLookup`, `CreatableForm`.
`operations`, `partWithMethod`, `materialSubstance`, `materialForm`, `materialFinish`,
`materialGrade`, `materialType`, `materialDimension`, `unitOfMeasure`,
`storageType` → `parts`;
-`workCenter`, `process`, `scrapReason` → `production`; `storageUnit` → `inventory`;
+`workCenter`, `process`, `scrapReason` → `production`; `storageUnit`,
+`inventoryQuantity`, `batchQuantity`, `serialQuantity` → `inventory`;
`department` → `people`; `itemPostingGroup`, `fixedAsset` → `accounting`.
An import's permission is the one its table's **RLS INSERT policy** requires, not
@@ -89,7 +90,8 @@ The edge function's own `table` enum (`import-csv/index.ts`) accepts: `consumabl
`partWithMethod`, `part`, `service`, `supplier`, `supplierContact`, `tool`,
`workCenter`, `process`, `storageUnit`, `unitOfMeasure`, `itemPostingGroup`,
`storageType`, `scrapReason`, `department`, `materialSubstance`, `materialForm`,
-`materialFinish`, `materialGrade`, `materialType`, `materialDimension`. Note it does
+`materialFinish`, `materialGrade`, `materialType`, `materialDimension`,
+`inventoryQuantity`, `batchQuantity`, `serialQuantity`. Note it does
**not** list `fixedAsset` (see Gotchas).
### Service import (rides the item path)
@@ -125,6 +127,83 @@ same file resolves and an unresolved/cyclic/self parent reports a per-row error
of rolling back the whole import. The DB same-location / no-cycle interceptors
(`20260417000200`) are the final guard; their exceptions are caught per row.
+### Opening-stock imports (additive Positive Adjmt. only)
+
+`inventoryQuantity`, `batchQuantity` and `serialQuantity` load on-hand stock for
+items that already exist, one import per `itemTrackingType` (Inventory / Batch /
+Serial; Non-Inventory has none). Surfaced from the Inventory → Quantities table
+(`InventoryTable.tsx`). Handled by `import-csv/stock-quantity-import.ts`; the pure
+per-row decision is `classify-stock-row.ts` (tested by `classify-stock-row.test.ts`).
+
+- **Columns**: `readableId` (Part Number), `revision` (blank → `"0"`), `locationId`
+ (enum via the shared `locationFetcher`, re-checked against the company's locations),
+ `storageUnitName` (optional, resolved case-insensitively within the row's location
+ like the storageUnit natural key; named-but-missing is a row error, never created),
+ `quantity` (Inventory/Batch; must be > 0), `batchNumber` / `serialNumber`,
+ `expirationDate` (Batch/Serial; optional ISO `YYYY-MM-DD`), `comment` (itemLedger
+ comment). Serial rows have no Quantity: each row is 1 unit.
+- **Item resolution**: readableId + revision (method-import key). `item_unique`
+ includes `type`, so several items can share the key; `buildStockItemMap` prefers
+ the candidate whose tracking type matches the import, else the first by
+ `(type, id)`. Wrong tracking type, missing item or missing `itemCost` row → row error.
+- **Storage units**: only `active` units resolve, matching
+ `getStorageUnitsListForLocation` in the manual adjustment; an inactive name is the
+ "not found in this location" row error.
+- **Dedup**: Batch/Serial key on `(itemId, readableId)`. A number already on that item
+ (any status) or repeated in the file → `skipped`. Same number on different items is
+ fine. Inventory rows have **no natural key**: re-importing posts them again.
+- **Writes** mirror post-inventory-adjustment's Positive Adjmt.: Batch/Serial rows
+ insert a new `trackedEntity` (sourceDocument "Item", `"Inventory Adjustment"`
+ attributes stamp with reason "Created via CSV import", Fixed Duration shelf-life
+ fallback when no expiry), then every row gets an `itemLedger` row, a `costLedger`
+ layer at current item cost and (accounting on) a balanced `journalLine` pair with
+ its `journalLineDimension` tags — posting date = company today, `documentType`
+ NULL. With accounting enabled the whole file shares ONE journal, created only if
+ some row carries value (post-inventory-count pattern). Accounting context is
+ resolved before the transaction; the whole file writes in one transaction.
+- **Bulk writes, not `bookAdjustment` per row.** `bookAdjustment` costs ~7 round
+ trips per movement, which is ~7 rows/second — a 2,000-row file exceeded the edge
+ runtime's wall clock and rolled back. The importer instead plans every row in
+ memory and writes one statement per table per 500-row chunk (`INSERT_CHUNK_SIZE`).
+ The rows are byte-for-byte what `bookAdjustment` writes because **both call the
+ same pure builders** in `shared/plan-adjustment.ts` — `buildItemLedgerRow`,
+ `buildCostLedgerRow`, `buildAdjustmentJournalLines`, `buildJournalLineDimensions`,
+ `toJournalLineDocumentType` — and the same open-layer query (`loadOpenCostLayers`
+ in `shared/post-adjustment.ts`, which takes a list of item ids and chunks its
+ applied-child lookup over the layer ids, since open layers per item are
+ unbounded). Do not fork a row shape or an arithmetic step into the importer:
+ a column added to a builder must reach both paths at once, which is the whole
+ reason the item ledger row is built there too rather than inline.
+- **Ids come back keyed, not positional.** Each movement's `itemLedger` id is the
+ `documentId` on its cost layer and journal lines, so a reordered `RETURNING`
+ would silently attach them to the wrong movement. `itemLedger` returns
+ `["id", "entryNumber"]` and each chunk is sorted by that SERIAL; `journalLine`
+ returns `["id", "journalLineReference"]` and the pair is grouped by the
+ reference the importer generated per movement.
+- **The plan itself is pure and tested.** `planStockRows` in
+ `shared/plan-adjustment.ts` takes the file's rows plus the item costs and open
+ layers and returns, per row, `{ carriesValue, cost, postsJournal }` — the
+ per-item grouping, the cost replay, the scatter back onto source rows and the
+ journal filter. The transaction body only inserts what it returns.
+ `shared/plan-adjustment.test.ts` covers mixed items, repeated rows for one item,
+ a zero-cost item, accounting disabled and a Non-Inventory / zero-quantity row.
+- **Cost layers are replayed, not hoisted.** `bookAdjustment` re-reads the item's
+ open layers before every increase, so row n+1 sees the layer row n wrote.
+ `planIncreaseUnitCosts` reproduces that in memory from one snapshot per item.
+ Standard/Average ignore layers, so their unit cost is constant per item; FIFO/LIFO
+ are unchanged by adding a layer at the current weighted average **in exact
+ arithmetic** — but the layer is stored at `round(q × u, 5)`, so the average drifts
+ by the rounding and the drift is scaled by the next row's quantity (a 1-unit row at
+ ⅓ stores 0.33333, and a following 1000-unit row books 333.33, not 333.33333).
+ Hoisting one unit cost per item would therefore change what is written. Pinned by
+ `shared/plan-adjustment.test.ts`, which asserts the plan equals booking the rows
+ one at a time for all four costing methods.
+- No Unique ID column and no `externalIntegrationMapping` writes. Business rules
+ (`evaluateLinesForSurface`) that the single-record adjustment route runs are NOT
+ evaluated by the import. The journal description is the fixed
+ "Inventory Adjustment — CSV import" (no per-row comment), and a zero-cost row
+ posts no journal lines.
+
### Configuration-lookup imports (skip-duplicate, create-only)
`unitOfMeasure`, `itemPostingGroup`, `storageType`, `scrapReason` and `department`
@@ -171,7 +250,7 @@ parent is an `errors` row. New rows get a DB-generated `xid()` id.
Action only (no loader). Steps:
1. `notFound` if `tableId` missing or not a key of `importPermissions`.
-2. `requirePermissions(request, { update: importPermissions[table] })`.
+2. `requirePermissions(request, { update: importPermissions[table] })`, plus `create` on the same module for tables in `importRequiresCreate` (the three stock imports, matching the single-record adjustment's `create: inventory` route gate and `update: inventory` Save button).
3. Validate form against `importSchemas[table].extend({ filePath, enumMappings })`.
`enumMappings` arrives as a JSON **string** and is `JSON.parse`d before the service call.
4. `columnMappings` = the remaining validated form fields after destructuring `filePath`
diff --git a/apps/erp/app/modules/agent/kb/docs/reference/import-export.md b/apps/erp/app/modules/agent/kb/docs/reference/import-export.md
index 5ec504c41b..20a897a7cc 100644
--- a/apps/erp/app/modules/agent/kb/docs/reference/import-export.md
+++ b/apps/erp/app/modules/agent/kb/docs/reference/import-export.md
@@ -27,6 +27,7 @@ Bulk import is deliberately scoped. A **Bulk Import** menu appears in the table
- **Parts, Materials, Tools, Consumables, Fixtures**: From each item type's list. A single row can optionally create a supplier-part link, set purchasing lead time, and seed unit cost alongside the item.
- **Work Centers**: From the work centers list, including labor, machine, and overhead rates and a location.
- **Processes**: From the processes list.
+ - **Inventory, Batch, and Serial Quantities**: From **Inventory → Quantities**. Adds opening stock for items that already exist, one import per tracking type. See [Opening stock](#opening-stock).
Beyond these table buttons, the importer also understands three **method** formats used to load bills of materials and operations against parts: a focused BOM file, a focused Operations file, and a combined part-with-method file that creates parts and their full BOM and routing together. These are richer, row-typed CSVs (each row is tagged `PART`, `BOM`, `BOP`, `STEP`, `TOOL`, or `PARAM`) driven from the method-building UI rather than a plain list screen.
@@ -59,6 +60,26 @@ Matching by Unique ID uses a shared external-mapping table keyed to the `csv` so
Import writes the entity's standard fields plus its documented side-tables (address, payment, supplier-part, cost). It does **not** map into per-company custom fields. Set those in the app after importing, or via the record's own form.
+## Opening stock
+
+The **Inventory → Quantities** table carries three imports that load on-hand stock, typically once during go-live. Each row is posted as a **Positive Adjmt.** through the same posting core as a manual inventory adjustment: an item ledger entry at the item's current cost, dated today, and, when accounting is enabled, a line pair on **one** inventory adjustment journal for the whole file. A row whose item has zero cost posts no journal lines. Inventory adjustment business rules are not evaluated on import. These imports only ever **add** stock; they never reduce or set a quantity.
+
+Pick the import that matches the item's tracking type. A row whose item is tracked differently is reported as an error naming the right import, and Non-Inventory items can't be stocked at all.
+
+ - **Inventory Quantities**: For items tracked as **Inventory**. Columns: Part Number, Revision, Location, Storage Unit, Quantity, Comment.
+ - **Batch Quantities**: For items tracked as **Batch**. Columns: Part Number, Revision, Location, Storage Unit, Batch Number, Quantity, Expiration Date, Comment. Each row creates a new batch.
+ - **Serial Quantities**: For items tracked as **Serial**. Columns: Part Number, Revision, Location, Storage Unit, Serial Number, Expiration Date, Comment. There's no Quantity column: every row is one unit.
+
+Rules shared by all three:
+
+- **Part Number + Revision** must match an existing item; a blank Revision means `0`. An unknown item is an error.
+- **Location** is mapped to one of your locations in the wizard. **Storage Unit** is optional and matched by name within that location, ignoring case. A named storage unit that doesn't exist there is an error; the import never creates one.
+- **Quantity** must be a positive number.
+- **Expiration Date** is optional and must be written `YYYY-MM-DD`. Left blank, an item with a fixed-duration shelf life gets its expiry calculated the same way a manual adjustment does.
+- There's no Unique ID column, so these imports don't record CSV id mappings.
+
+Inventory-tracked rows have no natural key, so every valid row posts, every time. Importing the same file twice doubles the quantities. Batch and serial rows are protected: a batch or serial number that already exists on that item (in any status) is **skipped**, and a number repeated in the file is skipped after its first row. The same serial number on two different items is allowed.
+
## Errors and partial failures
Import is **row-level tolerant**. A bad row doesn't abort the whole file: it's collected and reported while the good rows still import. The results come back as four numbers plus two lists:
@@ -69,7 +90,7 @@ Import is **row-level tolerant**. A bad row doesn't abort the whole file: it's c
Because the results carry each failed row's original cells, the wizard's results view shows you exactly which rows to fix without re-parsing your file. A hard failure (the file can't be downloaded, or an unexpected database error) is the only case that fails the whole import and returns an error message instead of a per-row report.
-The import function writes with a privileged database connection that bypasses RLS, so your **permission to import is checked once**, up front, when you submit: sales for customers, purchasing for suppliers, parts for items and methods, production for work centers and processes. If you lack that module's update permission, the import is refused before any write.
+The import function writes with a privileged database connection that bypasses RLS, so your **permission to import is checked once**, up front, when you submit: sales for customers, purchasing for suppliers, parts for items and methods, production for work centers and processes, inventory for storage units and opening stock. If you lack that module's update permission, the import is refused before any write. Opening stock imports also need inventory create permission, the same as a manual inventory adjustment.
## Related
@@ -77,6 +98,7 @@ The import function writes with a privileged database connection that bypasses R
- Methods Bills of materials and routings, loaded by the BOM, Operations, and combined method imports.
- Suppliers and customers The partner records the customer and supplier importers create, including their addresses and terms.
- Work centers The capacity records the work-center importer creates.
+ - Inventory On-hand quantities and the manual adjustments the opening-stock imports post.
## Troubleshooting
@@ -86,7 +108,7 @@ The gates and quiet defaults that surprise people during an import.
The import URL's `tableId` isn't a key of `importPermissions`, so the route rejects it before any work (`import.$tableId.tsx:16-17`). Import from the entity's own list-screen **Bulk Import** button, which only appears on supported tables, rather than hitting the route directly.
### The import is refused before any row is written
-The importer bypasses row-level security, so your **module update permission is checked once, up front** on submit (`import.$tableId.tsx:20-22`): sales for customers, purchasing for suppliers, parts for items and methods, production for work centers and processes. Without that module's update permission the whole import is refused. Get the permission, then re-submit.
+The importer bypasses row-level security, so your **module update permission is checked once, up front** on submit (`import.$tableId.tsx:20-22`): sales for customers, purchasing for suppliers, parts for items and methods, production for work centers and processes, inventory for storage units and opening stock. Opening stock also needs inventory create permission. Without the required permission the whole import is refused. Get the permission, then re-submit.
### A fixed-asset CSV is rejected
`fixedAsset` has a models entry but is **not** in the import edge function's own table enum (`packages/database/supabase/functions/import-csv/index.ts:18-33`), so it's rejected. Create fixed assets in the app. Individual BOM material lines (`methodMaterial`) are likewise not wired up — use the BOM/method imports or the app.
@@ -97,5 +119,11 @@ When a CSV value has no mapping to a Carbon enum, the row imports with that fiel
### Re-importing created duplicates — or didn't update what I expected
The importer matches by the CSV's Unique ID first (via a stored `csv`-source mapping), then falls back to Name. If neither matches an existing record, the row is inserted. Records created in the app with no CSV mapping are matched by **Name** — a name mismatch (or a blank Name, which errors) breaks the update and can create a new row instead.
+### Opening stock doubled after a second import
+The Inventory Quantities import has no natural key: every valid row posts a Positive Adjmt. each time the file is imported. Reverse the extra movements from the item's inventory page (a Negative Adjmt. or a correction) rather than re-importing. Batch and Serial Quantities skip numbers that already exist on the item, so re-importing those files is safe.
+
+### An opening-stock row says the item is tracked differently
+Each opening-stock import accepts one tracking type (Inventory, Batch, or Serial). The error names the import to use instead; move the row to that file.
+
### My custom fields are blank after import
Import writes standard fields plus documented side-tables (address, payment, supplier-part, cost) only — it does **not** map into per-company custom fields. Set those on the record's form after importing.
diff --git a/apps/erp/app/modules/agent/kb/manifest.json b/apps/erp/app/modules/agent/kb/manifest.json
index af519c59bc..99816dd785 100644
--- a/apps/erp/app/modules/agent/kb/manifest.json
+++ b/apps/erp/app/modules/agent/kb/manifest.json
@@ -713,6 +713,7 @@
"What you can import",
"The import flow",
"Insert, update, or skip",
+ "Opening stock",
"Errors and partial failures",
"Related",
"Troubleshooting",
@@ -721,6 +722,8 @@
"A fixed-asset CSV is rejected",
"An enum column imported as the wrong value",
"Re-importing created duplicates — or didn't update what I expected",
+ "Opening stock doubled after a second import",
+ "An opening-stock row says the item is tracked differently",
"My custom fields are blank after import"
]
},
diff --git a/apps/erp/app/modules/inventory/ui/Inventory/InventoryTable.tsx b/apps/erp/app/modules/inventory/ui/Inventory/InventoryTable.tsx
index 4ba3404301..d9f0254556 100644
--- a/apps/erp/app/modules/inventory/ui/Inventory/InventoryTable.tsx
+++ b/apps/erp/app/modules/inventory/ui/Inventory/InventoryTable.tsx
@@ -645,6 +645,20 @@ const InventoryTable = memo(
data={data}
defaultColumnVisibility={defaultColumnVisibility}
defaultColumnPinning={defaultColumnPinning}
+ importCSV={[
+ {
+ table: "inventoryQuantity" as const,
+ label: t`Inventory Quantities`
+ },
+ {
+ table: "batchQuantity" as const,
+ label: t`Batch Quantities`
+ },
+ {
+ table: "serialQuantity" as const,
+ label: t`Serial Quantities`
+ }
+ ]}
primaryAction={
<div className="flex items-center gap-2">
<Combobox
diff --git a/apps/erp/app/modules/shared/imports.models.ts b/apps/erp/app/modules/shared/imports.models.ts
index dbc2a903e8..05cf292ae8 100644
--- a/apps/erp/app/modules/shared/imports.models.ts
+++ b/apps/erp/app/modules/shared/imports.models.ts
@@ -203,6 +203,70 @@ const materialFormFetcher = async (
.order("name");
};
+const locationFetcher = async (
+ client: SupabaseClient<Database>,
+ companyId: string
+) => {
+ return client
+ .from("location")
+ .select("id, name")
+ .eq("companyId", companyId)
+ .order("name");
+};
+
+// Opening-stock imports (inventoryQuantity / batchQuantity / serialQuantity).
+// Additive only: every row posts one Positive Adjmt. for an existing item.
+const stockImportItemFields = {
+ readableId: {
+ label: "Part Number",
+ required: true,
+ type: "string"
+ },
+ revision: {
+ label: "Revision",
+ required: false,
+ type: "string",
+ default: "0"
+ }
+} as const;
+const stockImportPlacementFields = {
+ locationId: {
+ label: "Location",
+ required: true,
+ type: "enum",
+ enumData: {
+ description: "The location the stock is in — match by location name",
+ fetcher: locationFetcher
+ }
+ },
+ storageUnitName: {
+ label: "Storage Unit",
+ required: false,
+ type: "string"
+ }
+} as const;
+const stockImportQuantityField = {
+ quantity: {
+ label: "Quantity",
+ required: true,
+ type: "number"
+ }
+} as const;
+const stockImportExpirationField = {
+ expirationDate: {
+ label: "Expiration Date",
+ required: false,
+ type: "string"
+ }
+} as const;
+const stockImportCommentField = {
+ comment: {
+ label: "Comment",
+ required: false,
+ type: "string"
+ }
+} as const;
+
// Row-type discriminator + explicit parent key. Spread into every method entry.
const methodParentKeyFields = {
rowType: {
@@ -1692,16 +1756,7 @@ export const fieldMappings = {
enumData: {
description:
"The location this storage unit belongs to — match by location name",
- fetcher: async (
- client: SupabaseClient<Database>,
- companyId: string
- ) => {
- return client
- .from("location")
- .select("id, name")
- .eq("companyId", companyId)
- .order("name");
- }
+ fetcher: locationFetcher
}
},
parentName: {
@@ -1967,6 +2022,35 @@ export const fieldMappings = {
required: false,
type: "boolean"
}
+ },
+ inventoryQuantity: {
+ ...stockImportItemFields,
+ ...stockImportPlacementFields,
+ ...stockImportQuantityField,
+ ...stockImportCommentField
+ },
+ batchQuantity: {
+ ...stockImportItemFields,
+ ...stockImportPlacementFields,
+ batchNumber: {
+ label: "Batch Number",
+ required: true,
+ type: "string"
+ },
+ ...stockImportQuantityField,
+ ...stockImportExpirationField,
+ ...stockImportCommentField
+ },
+ serialQuantity: {
+ ...stockImportItemFields,
+ ...stockImportPlacementFields,
+ serialNumber: {
+ label: "Serial Number",
+ required: true,
+ type: "string"
+ },
+ ...stockImportExpirationField,
+ ...stockImportCommentField
}
} as const;
@@ -2001,9 +2085,19 @@ export const importPermissions: Record<keyof typeof fieldMappings, string> = {
materialDimension: "parts",
quote: "sales",
quoteLine: "sales",
- quoteWithLines: "sales"
+ quoteWithLines: "sales",
+ inventoryQuantity: "inventory",
+ batchQuantity: "inventory",
+ serialQuantity: "inventory"
};
+// Imports that post stock also require `create` on their module: the
+// single-record inventory adjustment route requires `create: inventory`, and
+// its Save button requires `update: inventory`, so an import of the same rows
+// requires both.
+export const importRequiresCreate: ReadonlySet<keyof typeof fieldMappings> =
+ new Set(["inventoryQuantity", "batchQuantity", "serialQuantity"]);
+
// Quote import validation is intentionally permissive at the mapping layer (every
// cell an optional string); the app-side importer (`sales.import.server.ts`) does
// the authoritative per-row validation (required fields, customer/part resolution,
@@ -2097,6 +2191,47 @@ const methodPartSchema = {
leadTime: z.string().optional()
};
+// Zod fragments for the opening-stock imports. The mapping layer only checks a
+// column is mapped; the import-csv edge function does the per-row validation
+// (item resolution, tracking type, positive quantity, ISO dates, duplicates).
+const stockImportItemSchema = {
+ readableId: z
+ .string()
+ .min(1, { message: "Part Number is required" })
+ .describe("The part number of an existing item"),
+ revision: z.string().optional().describe("The item revision (defaults to 0)")
+};
+const stockImportPlacementSchema = {
+ locationId: z
+ .string()
+ .min(1, { message: "Location is required" })
+ .describe("The location the stock is in"),
+ storageUnitName: z
+ .string()
+ .optional()
+ .describe(
+ "The name of an existing storage unit in that location (optional)"
+ )
+};
+const stockImportQuantitySchema = {
+ quantity: z
+ .string()
+ .min(1, { message: "Quantity is required" })
+ .describe("The quantity to add — a positive number")
+};
+const stockImportExpirationSchema = {
+ expirationDate: z
+ .string()
+ .optional()
+ .describe("The expiration date as YYYY-MM-DD (optional)")
+};
+const stockImportCommentSchema = {
+ comment: z
+ .string()
+ .optional()
+ .describe("A comment stored on the inventory adjustment (optional)")
+};
+
export const importSchemas: Record<
keyof typeof fieldMappings,
z.ZodObject<any>
@@ -2904,5 +3039,32 @@ export const importSchemas: Record<
}),
quote: z.object(quoteImportSchemaFields),
quoteLine: z.object(quoteImportSchemaFields),
- quoteWithLines: z.object(quoteImportSchemaFields)
+ quoteWithLines: z.object(quoteImportSchemaFields),
+ inventoryQuantity: z.object({
+ ...stockImportItemSchema,
+ ...stockImportPlacementSchema,
+ ...stockImportQuantitySchema,
+ ...stockImportCommentSchema
+ }),
+ batchQuantity: z.object({
+ ...stockImportItemSchema,
+ ...stockImportPlacementSchema,
+ batchNumber: z
+ .string()
+ .min(1, { message: "Batch Number is required" })
+ .describe("The batch (lot) number the stock is received under"),
+ ...stockImportQuantitySchema,
+ ...stockImportExpirationSchema,
+ ...stockImportCommentSchema
+ }),
+ serialQuantity: z.object({
+ ...stockImportItemSchema,
+ ...stockImportPlacementSchema,
+ serialNumber: z
+ .string()
+ .min(1, { message: "Serial Number is required" })
+ .describe("The serial number of the unit; each row is one unit"),
+ ...stockImportExpirationSchema,
+ ...stockImportCommentSchema
+ })
} as const;
diff --git a/apps/erp/app/routes/x+/shared+/import.$tableId.tsx b/apps/erp/app/routes/x+/shared+/import.$tableId.tsx
index 6d69f4345d..a5c9f1bc0a 100644
--- a/apps/erp/app/routes/x+/shared+/import.$tableId.tsx
+++ b/apps/erp/app/routes/x+/shared+/import.$tableId.tsx
@@ -8,7 +8,12 @@ import {
importQuotes,
isQuoteImportTable
} from "~/modules/sales/sales.import.server";
-import { importCsv, importPermissions, importSchemas } from "~/modules/shared";
+import {
+ importCsv,
+ importPermissions,
+ importRequiresCreate,
+ importSchemas
+} from "~/modules/shared";
import { getDatabaseClient } from "~/services/database.server";
export async function action({ request, params }: ActionFunctionArgs) {
@@ -25,7 +30,10 @@ export async function action({ request, params }: ActionFunctionArgs) {
const { companyId, companyGroupId, userId } = await requirePermissions(
request,
{
- update: importPermissions[table]
+ update: importPermissions[table],
+ ...(importRequiresCreate.has(table)
+ ? { create: importPermissions[table] }
+ : {})
}
);
diff --git a/docs/content/docs/reference/import-export.mdx b/docs/content/docs/reference/import-export.mdx
index 3782a1a474..229287fc81 100644
--- a/docs/content/docs/reference/import-export.mdx
+++ b/docs/content/docs/reference/import-export.mdx
@@ -33,6 +33,7 @@ Bulk import is deliberately scoped. A **Bulk Import** menu appears in the table
<Field name="Parts, Materials, Tools, Consumables, Fixtures">From each item type's list. A single row can optionally create a supplier-part link, set purchasing lead time, and seed unit cost alongside the item.</Field>
<Field name="Work Centers">From the work centers list, including labor, machine, and overhead rates and a location.</Field>
<Field name="Processes">From the processes list.</Field>
+ <Field name="Inventory, Batch, and Serial Quantities">From **Inventory → Quantities**. Adds opening stock for items that already exist, one import per <Term id="item-tracking-type">tracking type</Term>. See [Opening stock](#opening-stock).</Field>
</FieldTable>
Beyond these table buttons, the importer also understands three **method** formats used to load bills of materials and operations against parts: a focused BOM file, a focused Operations file, and a combined part-with-method file that creates parts and their full BOM and routing together. These are richer, row-typed CSVs (each row is tagged `PART`, `BOM`, `BOP`, `STEP`, `TOOL`, or `PARAM`) driven from the method-building UI rather than a plain list screen.
@@ -81,6 +82,30 @@ Matching by Unique ID uses a shared external-mapping table keyed to the `csv` so
Import writes the entity's standard fields plus its documented side-tables (address, payment, supplier-part, cost). It does **not** map into per-company custom fields. Set those in the app after importing, or via the record's own form.
</Callout>
+## Opening stock
+
+The **Inventory → Quantities** table carries three imports that load on-hand stock, typically once during go-live. Each row is posted as a **Positive Adjmt.** through the same posting core as a manual inventory adjustment: an item ledger entry at the item's current cost, dated today, and, when accounting is enabled, a line pair on **one** inventory adjustment journal for the whole file. A row whose item has zero cost posts no journal lines. Inventory adjustment business rules are not evaluated on import. These imports only ever **add** stock; they never reduce or set a quantity.
+
+Pick the import that matches the item's tracking type. A row whose item is tracked differently is reported as an error naming the right import, and Non-Inventory items can't be stocked at all.
+
+<FieldTable>
+ <Field name="Inventory Quantities">For items tracked as **Inventory**. Columns: Part Number, Revision, Location, Storage Unit, Quantity, Comment.</Field>
+ <Field name="Batch Quantities">For items tracked as **Batch**. Columns: Part Number, Revision, Location, Storage Unit, Batch Number, Quantity, Expiration Date, Comment. Each row creates a new batch.</Field>
+ <Field name="Serial Quantities">For items tracked as **Serial**. Columns: Part Number, Revision, Location, Storage Unit, Serial Number, Expiration Date, Comment. There's no Quantity column: every row is one unit.</Field>
+</FieldTable>
+
+Rules shared by all three:
+
+- **Part Number + Revision** must match an existing item; a blank Revision means `0`. An unknown item is an error.
+- **Location** is mapped to one of your locations in the wizard. **Storage Unit** is optional and matched by name within that location, ignoring case. A named storage unit that doesn't exist there is an error; the import never creates one.
+- **Quantity** must be a positive number.
+- **Expiration Date** is optional and must be written `YYYY-MM-DD`. Left blank, an item with a fixed-duration shelf life gets its expiry calculated the same way a manual adjustment does.
+- There's no Unique ID column, so these imports don't record CSV id mappings.
+
+<Callout type="warn" title="Re-importing an Inventory Quantities file adds the stock again">
+Inventory-tracked rows have no natural key, so every valid row posts, every time. Importing the same file twice doubles the quantities. Batch and serial rows are protected: a batch or serial number that already exists on that item (in any status) is **skipped**, and a number repeated in the file is skipped after its first row. The same serial number on two different items is allowed.
+</Callout>
+
## Errors and partial failures
Import is **row-level tolerant**. A bad row doesn't abort the whole file: it's collected and reported while the good rows still import. The results come back as four numbers plus two lists:
@@ -92,7 +117,7 @@ Import is **row-level tolerant**. A bad row doesn't abort the whole file: it's c
Because the results carry each failed row's original cells, the wizard's results view shows you exactly which rows to fix without re-parsing your file. A hard failure (the file can't be downloaded, or an unexpected database error) is the only case that fails the whole import and returns an error message instead of a per-row report.
<Callout type="warn" title="Import bypasses row-level security by design">
-The import function writes with a privileged database connection that bypasses RLS, so your **permission to import is checked once**, up front, when you submit: sales for customers, purchasing for suppliers, parts for items and methods, production for work centers and processes. If you lack that module's update permission, the import is refused before any write.
+The import function writes with a privileged database connection that bypasses RLS, so your **permission to import is checked once**, up front, when you submit: sales for customers, purchasing for suppliers, parts for items and methods, production for work centers and processes, inventory for storage units and opening stock. If you lack that module's update permission, the import is refused before any write. Opening stock imports also need inventory create permission, the same as a manual inventory adjustment.
</Callout>
## Related
@@ -102,6 +127,7 @@ The import function writes with a privileged database connection that bypasses R
<Card title="Methods" href="/docs/reference/methods">Bills of materials and routings, loaded by the BOM, Operations, and combined method imports.</Card>
<Card title="Suppliers and customers" href="/docs/reference/suppliers-and-customers">The partner records the customer and supplier importers create, including their addresses and terms.</Card>
<Card title="Work centers" href="/docs/reference/work-centers">The capacity records the work-center importer creates.</Card>
+ <Card title="Inventory" href="/docs/reference/inventory">On-hand quantities and the manual adjustments the opening-stock imports post.</Card>
</Cards>
<AgentContext>
@@ -113,7 +139,7 @@ The gates and quiet defaults that surprise people during an import.
The import URL's `tableId` isn't a key of `importPermissions`, so the route rejects it before any work (`import.$tableId.tsx:16-17`). Import from the entity's own list-screen **Bulk Import** button, which only appears on supported tables, rather than hitting the route directly.
### The import is refused before any row is written
-The importer bypasses row-level security, so your **module update permission is checked once, up front** on submit (`import.$tableId.tsx:20-22`): sales for customers, purchasing for suppliers, parts for items and methods, production for work centers and processes. Without that module's update permission the whole import is refused. Get the permission, then re-submit.
+The importer bypasses row-level security, so your **module update permission is checked once, up front** on submit (`import.$tableId.tsx:20-22`): sales for customers, purchasing for suppliers, parts for items and methods, production for work centers and processes, inventory for storage units and opening stock. Opening stock also needs inventory create permission. Without the required permission the whole import is refused. Get the permission, then re-submit.
### A fixed-asset CSV is rejected
`fixedAsset` has a models entry but is **not** in the import edge function's own table enum (`packages/database/supabase/functions/import-csv/index.ts:18-33`), so it's rejected. Create fixed assets in the app. Individual BOM material lines (`methodMaterial`) are likewise not wired up — use the BOM/method imports or the app.
@@ -124,6 +150,12 @@ When a CSV value has no mapping to a Carbon enum, the row imports with that fiel
### Re-importing created duplicates — or didn't update what I expected
The importer matches by the CSV's Unique ID first (via a stored `csv`-source mapping), then falls back to Name. If neither matches an existing record, the row is inserted. Records created in the app with no CSV mapping are matched by **Name** — a name mismatch (or a blank Name, which errors) breaks the update and can create a new row instead.
+### Opening stock doubled after a second import
+The Inventory Quantities import has no natural key: every valid row posts a Positive Adjmt. each time the file is imported. Reverse the extra movements from the item's inventory page (a Negative Adjmt. or a correction) rather than re-importing. Batch and Serial Quantities skip numbers that already exist on the item, so re-importing those files is safe.
+
+### An opening-stock row says the item is tracked differently
+Each opening-stock import accepts one tracking type (Inventory, Batch, or Serial). The error names the import to use instead; move the row to that file.
+
### My custom fields are blank after import
Import writes standard fields plus documented side-tables (address, payment, supplier-part, cost) only — it does **not** map into per-company custom fields. Set those on the record's form after importing.
</AgentContext>
diff --git a/packages/database/supabase/functions/import-csv/classify-stock-row.test.ts b/packages/database/supabase/functions/import-csv/classify-stock-row.test.ts
new file mode 100644
index 0000000000..327fefa3d0
--- /dev/null
+++ b/packages/database/supabase/functions/import-csv/classify-stock-row.test.ts
@@ -0,0 +1,310 @@
+import { assertEquals } from "https://deno.land/[email protected]/testing/asserts.ts";
+import {
+ buildStockItemMap,
+ classifyStockRow,
+ isIsoDate,
+ itemKey,
+ type StockImportTable,
+ type StockItemInfo,
+ storageUnitKey,
+ trackedKey,
+} from "./classify-stock-row.ts";
+
+const items = new Map<string, StockItemInfo>([
+ [itemKey("PN-INV", "0"), { id: "inv-1", itemTrackingType: "Inventory", hasItemCost: true }],
+ [itemKey("PN-INV", "B"), { id: "inv-b", itemTrackingType: "Inventory", hasItemCost: true }],
+ [itemKey("PN-BATCH", "0"), { id: "bat-1", itemTrackingType: "Batch", hasItemCost: true }],
+ [itemKey("PN-SER", "0"), { id: "ser-1", itemTrackingType: "Serial", hasItemCost: true }],
+ [itemKey("PN-SER2", "0"), { id: "ser-2", itemTrackingType: "Serial", hasItemCost: true }],
+ [itemKey("PN-SVC", "0"), { id: "svc-1", itemTrackingType: "Non-Inventory", hasItemCost: true }],
+ [itemKey("PN-NOCOST", "0"), { id: "nc-1", itemTrackingType: "Inventory", hasItemCost: false }],
+]);
+
+const ctx = (overrides: Partial<Parameters<typeof classifyStockRow>[0]> = {}) => ({
+ itemMap: items,
+ locationIds: new Set(["loc-1", "loc-2"]),
+ storageUnitMap: new Map([[storageUnitKey("loc-1", "Bin A"), "su-a"]]),
+ existingTrackedKeys: new Set<string>(),
+ seenTrackedKeys: new Set<string>(),
+ ...overrides,
+});
+
+const classify = (
+ table: StockImportTable,
+ record: Record<string, string>,
+ overrides: Partial<Parameters<typeof classifyStockRow>[0]> = {}
+) => classifyStockRow({ ...ctx(overrides), table, record });
+
+const reason = (d: ReturnType<typeof classifyStockRow>) =>
+ d.action === "skip" ? `${d.category}: ${d.reason}` : "post";
+
+Deno.test("inventory row resolves item, location, storage unit and quantity", () => {
+ assertEquals(
+ classify("inventoryQuantity", {
+ readableId: " PN-INV ",
+ revision: "",
+ locationId: "loc-1",
+ storageUnitName: "bin a",
+ quantity: "12.5",
+ comment: " opening balance ",
+ }),
+ {
+ action: "post",
+ row: {
+ itemId: "inv-1",
+ locationId: "loc-1",
+ storageUnitId: "su-a",
+ quantity: 12.5,
+ readableId: null,
+ expirationDate: null,
+ comment: "opening balance",
+ trackedKey: null,
+ },
+ }
+ );
+});
+
+Deno.test("revision selects the matching item revision", () => {
+ const d = classify("inventoryQuantity", {
+ readableId: "PN-INV",
+ revision: "B",
+ locationId: "loc-1",
+ quantity: "1",
+ });
+ assertEquals(d.action === "post" ? d.row.itemId : null, "inv-b");
+});
+
+Deno.test("blank storage unit posts to the location with no storage unit", () => {
+ const d = classify("inventoryQuantity", {
+ readableId: "PN-INV",
+ locationId: "loc-2",
+ quantity: "3",
+ });
+ assertEquals(d.action === "post" ? d.row.storageUnitId : "x", null);
+});
+
+Deno.test("missing part number and unknown item are errors", () => {
+ assertEquals(
+ reason(classify("inventoryQuantity", { locationId: "loc-1", quantity: "1" })),
+ "error: Missing required Part Number"
+ );
+ assertEquals(
+ reason(classify("inventoryQuantity", { readableId: "NOPE", revision: "C", locationId: "loc-1", quantity: "1" })),
+ "error: Item NOPE rev C not found"
+ );
+});
+
+Deno.test("tracking type mismatch points at the right import", () => {
+ assertEquals(
+ reason(classify("inventoryQuantity", { readableId: "PN-BATCH", locationId: "loc-1", quantity: "1" })),
+ "error: Item PN-BATCH rev 0 is Batch tracked; use the Batch Quantities import"
+ );
+ assertEquals(
+ reason(classify("serialQuantity", { readableId: "PN-INV", locationId: "loc-1", serialNumber: "S1" })),
+ "error: Item PN-INV rev 0 is Inventory tracked; use the Inventory Quantities import"
+ );
+ assertEquals(
+ reason(classify("inventoryQuantity", { readableId: "PN-SVC", locationId: "loc-1", quantity: "1" })),
+ "error: Item PN-SVC rev 0 is Non-Inventory tracked and holds no stock"
+ );
+});
+
+Deno.test("location must be present and belong to the company", () => {
+ assertEquals(
+ reason(classify("inventoryQuantity", { readableId: "PN-INV", quantity: "1" })),
+ "error: Missing required Location"
+ );
+ assertEquals(
+ reason(classify("inventoryQuantity", { readableId: "PN-INV", locationId: "other", quantity: "1" })),
+ "error: Location not found"
+ );
+});
+
+Deno.test("a named storage unit that is not in the row's location is an error", () => {
+ assertEquals(
+ reason(classify("inventoryQuantity", { readableId: "PN-INV", locationId: "loc-2", storageUnitName: "Bin A", quantity: "1" })),
+ 'error: Storage unit "Bin A" not found in this location'
+ );
+});
+
+Deno.test("quantity must be a positive number", () => {
+ for (const quantity of ["", "0", "-2", "abc", "Infinity"]) {
+ assertEquals(
+ reason(classify("batchQuantity", { readableId: "PN-BATCH", locationId: "loc-1", batchNumber: "L1", quantity })),
+ "error: Quantity must be a positive number"
+ );
+ }
+});
+
+Deno.test("serial rows are always one unit and ignore any quantity", () => {
+ const d = classify("serialQuantity", {
+ readableId: "PN-SER",
+ locationId: "loc-1",
+ serialNumber: "SN-1",
+ quantity: "5",
+ });
+ assertEquals(d.action === "post" ? d.row.quantity : null, 1);
+});
+
+Deno.test("batch and serial numbers are required", () => {
+ assertEquals(
+ reason(classify("batchQuantity", { readableId: "PN-BATCH", locationId: "loc-1", quantity: "1" })),
+ "error: Missing required Batch Number"
+ );
+ assertEquals(
+ reason(classify("serialQuantity", { readableId: "PN-SER", locationId: "loc-1", serialNumber: " " })),
+ "error: Missing required Serial Number"
+ );
+});
+
+Deno.test("expiration date is optional and must be a real ISO date", () => {
+ const base = { readableId: "PN-BATCH", locationId: "loc-1", batchNumber: "L1", quantity: "2" };
+ const ok = classify("batchQuantity", { ...base, expirationDate: "2027-02-28" });
+ assertEquals(ok.action === "post" ? ok.row.expirationDate : null, "2027-02-28");
+ assertEquals(
+ reason(classify("batchQuantity", { ...base, expirationDate: "2027-02-30" })),
+ 'error: Expiration Date "2027-02-30" is not a valid date (use YYYY-MM-DD)'
+ );
+ assertEquals(
+ reason(classify("batchQuantity", { ...base, expirationDate: "02/01/2027" })),
+ 'error: Expiration Date "02/01/2027" is not a valid date (use YYYY-MM-DD)'
+ );
+});
+
+Deno.test("isIsoDate handles leap years", () => {
+ assertEquals(isIsoDate("2028-02-29"), true);
+ assertEquals(isIsoDate("2027-02-29"), false);
+ assertEquals(isIsoDate("2100-02-29"), false);
+ assertEquals(isIsoDate("2000-02-29"), true);
+ assertEquals(isIsoDate("2027-13-01"), false);
+});
+
+Deno.test("an item without an item cost record is an error", () => {
+ assertEquals(
+ reason(classify("inventoryQuantity", { readableId: "PN-NOCOST", locationId: "loc-1", quantity: "1" })),
+ "error: Item PN-NOCOST rev 0 has no item cost record"
+ );
+});
+
+Deno.test("a serial that already exists on the item is skipped", () => {
+ assertEquals(
+ reason(
+ classify(
+ "serialQuantity",
+ { readableId: "PN-SER", locationId: "loc-1", serialNumber: "SN-1" },
+ { existingTrackedKeys: new Set([trackedKey("ser-1", "SN-1")]) }
+ )
+ ),
+ 'skipped: Serial number "SN-1" already exists for this item'
+ );
+});
+
+Deno.test("a serial repeated in the file is skipped; the same serial on another item posts", () => {
+ const seenTrackedKeys = new Set<string>();
+ const first = classify(
+ "serialQuantity",
+ { readableId: "PN-SER", locationId: "loc-1", serialNumber: "SN-1" },
+ { seenTrackedKeys }
+ );
+ assertEquals(first.action, "post");
+ if (first.action === "post") seenTrackedKeys.add(first.row.trackedKey!);
+
+ assertEquals(
+ reason(
+ classify(
+ "serialQuantity",
+ { readableId: "PN-SER", locationId: "loc-2", serialNumber: "SN-1" },
+ { seenTrackedKeys }
+ )
+ ),
+ 'skipped: Duplicate serial number "SN-1" for this item in file'
+ );
+ assertEquals(
+ classify(
+ "serialQuantity",
+ { readableId: "PN-SER2", locationId: "loc-1", serialNumber: "SN-1" },
+ { seenTrackedKeys }
+ ).action,
+ "post"
+ );
+});
+
+Deno.test("an existing batch number on the item is skipped", () => {
+ assertEquals(
+ reason(
+ classify(
+ "batchQuantity",
+ { readableId: "PN-BATCH", locationId: "loc-1", batchNumber: "L1", quantity: "4" },
+ { existingTrackedKeys: new Set([trackedKey("bat-1", "L1")]) }
+ )
+ ),
+ 'skipped: Batch number "L1" already exists for this item'
+ );
+});
+
+Deno.test("a batch repeated in the file for the same item is skipped; the same batch on another item posts", () => {
+ const batchItems = new Map(items);
+ batchItems.set(itemKey("PN-BATCH2", "0"), { id: "bat-2", itemTrackingType: "Batch", hasItemCost: true });
+ const seenTrackedKeys = new Set<string>();
+ const first = classify(
+ "batchQuantity",
+ { readableId: "PN-BATCH", locationId: "loc-1", batchNumber: "L1", quantity: "4" },
+ { itemMap: batchItems, seenTrackedKeys }
+ );
+ assertEquals(first.action, "post");
+ if (first.action === "post") seenTrackedKeys.add(first.row.trackedKey!);
+
+ assertEquals(
+ reason(
+ classify(
+ "batchQuantity",
+ { readableId: "PN-BATCH", locationId: "loc-2", batchNumber: "L1", quantity: "2" },
+ { itemMap: batchItems, seenTrackedKeys }
+ )
+ ),
+ 'skipped: Duplicate batch number "L1" for this item in file'
+ );
+ assertEquals(
+ classify(
+ "batchQuantity",
+ { readableId: "PN-BATCH2", locationId: "loc-1", batchNumber: "L1", quantity: "2" },
+ { itemMap: batchItems, seenTrackedKeys }
+ ).action,
+ "post"
+ );
+});
+
+Deno.test("items sharing Part Number + Revision: the one matching the import's tracking type wins", () => {
+ const candidates = [
+ { id: "a-part", readableId: "X-100", revision: "0", itemTrackingType: "Batch", hasItemCost: true },
+ { id: "b-tool", readableId: "X-100", revision: "0", itemTrackingType: "Inventory", hasItemCost: true },
+ ];
+ assertEquals(buildStockItemMap("inventoryQuantity", candidates).get(itemKey("X-100", "0"))?.id, "b-tool");
+ assertEquals(buildStockItemMap("batchQuantity", candidates).get(itemKey("X-100", "0"))?.id, "a-part");
+ // Neither matches: the first candidate in input order wins, so the row error
+ // names a stable item.
+ assertEquals(buildStockItemMap("serialQuantity", candidates).get(itemKey("X-100", "0"))?.id, "a-part");
+ // A null revision keys as "0".
+ assertEquals(
+ buildStockItemMap("batchQuantity", [{ ...candidates[0], revision: null }]).get(itemKey("X-100", "0"))?.id,
+ "a-part"
+ );
+});
+
+Deno.test("inventory rows have no natural key: identical rows both post", () => {
+ const record = { readableId: "PN-INV", locationId: "loc-1", quantity: "1" };
+ const seenTrackedKeys = new Set<string>();
+ assertEquals(classify("inventoryQuantity", record, { seenTrackedKeys }).action, "post");
+ assertEquals(classify("inventoryQuantity", record, { seenTrackedKeys }).action, "post");
+ assertEquals(seenTrackedKeys.size, 0);
+});
+
+Deno.test("inventory rows ignore an expiration date column", () => {
+ const d = classify("inventoryQuantity", {
+ readableId: "PN-INV",
+ locationId: "loc-1",
+ quantity: "1",
+ expirationDate: "not a date",
+ });
+ assertEquals(d.action === "post" ? d.row.expirationDate : "x", null);
+});
diff --git a/packages/database/supabase/functions/import-csv/classify-stock-row.ts b/packages/database/supabase/functions/import-csv/classify-stock-row.ts
new file mode 100644
index 0000000000..95b894f846
--- /dev/null
+++ b/packages/database/supabase/functions/import-csv/classify-stock-row.ts
@@ -0,0 +1,245 @@
+// Pure per-row decision for the opening-stock CSV imports (inventoryQuantity,
+// batchQuantity, serialQuantity). No DB, no I/O — so it is unit-testable with
+// `deno test`. The driver (`stock-quantity-import.ts`) preloads the lookups,
+// owns the running `seenTrackedKeys` set and applies the returned action.
+//
+// Every accepted row becomes ONE Positive Adjmt. — these imports only ever add
+// stock, never reduce or set it.
+
+export type StockImportTable =
+ | "inventoryQuantity"
+ | "batchQuantity"
+ | "serialQuantity";
+
+// The item tracking type each import accepts.
+export const STOCK_IMPORT_TRACKING_TYPE: Record<StockImportTable, string> = {
+ inventoryQuantity: "Inventory",
+ batchQuantity: "Batch",
+ serialQuantity: "Serial",
+};
+
+// The import a user should reach for, per tracking type, for the mismatch
+// error message.
+const IMPORT_LABEL_BY_TRACKING_TYPE: Record<string, string> = {
+ Inventory: "Inventory Quantities",
+ Batch: "Batch Quantities",
+ Serial: "Serial Quantities",
+};
+
+export type StockItemInfo = {
+ id: string;
+ itemTrackingType: string | null;
+ hasItemCost: boolean;
+};
+
+export type StockRowResolved = {
+ itemId: string;
+ locationId: string;
+ storageUnitId: string | null;
+ quantity: number;
+ // Batch / serial number; null for Inventory rows.
+ readableId: string | null;
+ expirationDate: string | null;
+ comment: string | null;
+ // In-file / existing dedup key for Batch / Serial rows; null for Inventory.
+ trackedKey: string | null;
+};
+
+export type StockRowDecision =
+ | { action: "post"; row: StockRowResolved }
+ | { action: "skip"; reason: string; category: "error" | "skipped" };
+
+const text = (s: string | undefined): string => (s ?? "").trim();
+
+// Same shape as method-import.ts: readableId + revision, blank revision → "0".
+export const itemKey = (readableId: string, revision: string) =>
+ `${readableId} ${revision || "0"}`;
+
+// readableId + revision → item (method-import key). item_unique also includes
+// `type`, so two items (e.g. a Part and a Tool) can share the key. Ties break
+// deterministically: the candidate whose tracking type matches this import
+// wins; otherwise the first candidate in input order (the driver orders the
+// query by type, id).
+export function buildStockItemMap(
+ table: StockImportTable,
+ candidates: Array<{
+ id: string;
+ readableId: string;
+ revision: string | null;
+ itemTrackingType: string | null;
+ hasItemCost: boolean;
+ }>
+): Map<string, StockItemInfo> {
+ const expected = STOCK_IMPORT_TRACKING_TYPE[table];
+ const map = new Map<string, StockItemInfo>();
+ for (const c of candidates) {
+ const key = itemKey(c.readableId, c.revision ?? "0");
+ const current = map.get(key);
+ if (
+ !current ||
+ (current.itemTrackingType !== expected &&
+ c.itemTrackingType === expected)
+ ) {
+ map.set(key, {
+ id: c.id,
+ itemTrackingType: c.itemTrackingType,
+ hasItemCost: c.hasItemCost,
+ });
+ }
+ }
+ return map;
+}
+
+// Storage unit names are unique per location (storageUnit_name_locationId_key)
+// and resolved case-insensitively — the storageUnit import's natural key.
+export const storageUnitKey = (locationId: string, name: string) =>
+ `${locationId}::${name.trim().toLowerCase()}`;
+
+// A batch / serial number is unique per item, not per company: the same serial
+// on two different items is allowed.
+export const trackedKey = (itemId: string, readableId: string) =>
+ `${itemId}::${readableId}`;
+
+// ISO calendar date (YYYY-MM-DD) that actually exists. Hand-rolled rather than
+// JS Date, which silently rolls 2026-02-30 over to March.
+export function isIsoDate(value: string): boolean {
+ const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(value);
+ if (!match) return false;
+ const year = Number(match[1]);
+ const month = Number(match[2]);
+ const day = Number(match[3]);
+ if (month < 1 || month > 12 || day < 1) return false;
+ const leap = (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
+ const daysInMonth = [31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
+ return day <= daysInMonth[month - 1];
+}
+
+export function classifyStockRow(params: {
+ table: StockImportTable;
+ record: Record<string, string>;
+ itemMap: Map<string, StockItemInfo>;
+ locationIds: Set<string>;
+ storageUnitMap: Map<string, string>;
+ existingTrackedKeys: Set<string>;
+ seenTrackedKeys: Set<string>;
+}): StockRowDecision {
+ const {
+ table,
+ record,
+ itemMap,
+ locationIds,
+ storageUnitMap,
+ existingTrackedKeys,
+ seenTrackedKeys,
+ } = params;
+ const error = (reason: string): StockRowDecision => ({
+ action: "skip",
+ reason,
+ category: "error",
+ });
+
+ const readableId = text(record.readableId);
+ const revision = text(record.revision) || "0";
+ if (!readableId) return error("Missing required Part Number");
+
+ const item = itemMap.get(itemKey(readableId, revision));
+ if (!item) return error(`Item ${readableId} rev ${revision} not found`);
+
+ const expectedTrackingType = STOCK_IMPORT_TRACKING_TYPE[table];
+ if (item.itemTrackingType !== expectedTrackingType) {
+ const other = IMPORT_LABEL_BY_TRACKING_TYPE[item.itemTrackingType ?? ""];
+ return error(
+ other
+ ? `Item ${readableId} rev ${revision} is ${item.itemTrackingType} tracked; use the ${other} import`
+ : `Item ${readableId} rev ${revision} is ${
+ item.itemTrackingType ?? "not"
+ } tracked and holds no stock`
+ );
+ }
+
+ const locationId = text(record.locationId);
+ if (!locationId) return error("Missing required Location");
+ if (!locationIds.has(locationId)) return error("Location not found");
+
+ const storageUnitName = text(record.storageUnitName);
+ let storageUnitId: string | null = null;
+ if (storageUnitName) {
+ storageUnitId =
+ storageUnitMap.get(storageUnitKey(locationId, storageUnitName)) ?? null;
+ if (!storageUnitId) {
+ return error(
+ `Storage unit "${storageUnitName}" not found in this location`
+ );
+ }
+ }
+
+ // Serial rows carry no Quantity: each row is exactly one unit.
+ let quantity = 1;
+ if (table !== "serialQuantity") {
+ const raw = text(record.quantity);
+ quantity = raw === "" ? Number.NaN : Number(raw);
+ if (!Number.isFinite(quantity) || quantity <= 0) {
+ return error("Quantity must be a positive number");
+ }
+ }
+
+ let trackedNumber: string | null = null;
+ if (table === "batchQuantity") {
+ trackedNumber = text(record.batchNumber);
+ if (!trackedNumber) return error("Missing required Batch Number");
+ } else if (table === "serialQuantity") {
+ trackedNumber = text(record.serialNumber);
+ if (!trackedNumber) return error("Missing required Serial Number");
+ }
+
+ let expirationDate: string | null = null;
+ if (table !== "inventoryQuantity") {
+ const raw = text(record.expirationDate);
+ if (raw) {
+ if (!isIsoDate(raw)) {
+ return error(
+ `Expiration Date "${raw}" is not a valid date (use YYYY-MM-DD)`
+ );
+ }
+ expirationDate = raw;
+ }
+ }
+
+ if (!item.hasItemCost) {
+ return error(`Item ${readableId} rev ${revision} has no item cost record`);
+ }
+
+ let key: string | null = null;
+ if (trackedNumber) {
+ const label = table === "serialQuantity" ? "Serial number" : "Batch number";
+ key = trackedKey(item.id, trackedNumber);
+ if (existingTrackedKeys.has(key)) {
+ return {
+ action: "skip",
+ reason: `${label} "${trackedNumber}" already exists for this item`,
+ category: "skipped",
+ };
+ }
+ if (seenTrackedKeys.has(key)) {
+ return {
+ action: "skip",
+ reason: `Duplicate ${label.toLowerCase()} "${trackedNumber}" for this item in file`,
+ category: "skipped",
+ };
+ }
+ }
+
+ return {
+ action: "post",
+ row: {
+ itemId: item.id,
+ locationId,
+ storageUnitId,
+ quantity,
+ readableId: trackedNumber,
+ expirationDate,
+ comment: text(record.comment) || null,
+ trackedKey: key,
+ },
+ };
+}
diff --git a/packages/database/supabase/functions/import-csv/index.ts b/packages/database/supabase/functions/import-csv/index.ts
index cfa9a3c4a7..b705471b91 100644
--- a/packages/database/supabase/functions/import-csv/index.ts
+++ b/packages/database/supabase/functions/import-csv/index.ts
@@ -13,6 +13,7 @@ import { classifyImportRow } from "./classify-import-row.ts";
import { importConfigLookups } from "./config-lookup-import.ts";
import { importMaterialProperties } from "./material-property-import.ts";
import { importMethods } from "./method-import.ts";
+import { importStockQuantities } from "./stock-quantity-import.ts";
const pool = getConnectionPool(1);
const db = getDatabaseClient<DB>(pool);
@@ -47,6 +48,9 @@ const importCsvValidator = z.object({
"materialGrade",
"materialType",
"materialDimension",
+ "inventoryQuantity",
+ "batchQuantity",
+ "serialQuantity",
]),
filePath: z.string(),
columnMappings: z.record(z.string(), z.string()),
@@ -3214,6 +3218,18 @@ serve(async (req: Request) => {
});
break;
}
+ case "inventoryQuantity":
+ case "batchQuantity":
+ case "serialQuantity": {
+ await importStockQuantities(db, client, {
+ table,
+ mappedRecords,
+ companyId,
+ userId,
+ summary,
+ });
+ break;
+ }
default: {
throw new Error(`Invalid table: ${table}`);
}
diff --git a/packages/database/supabase/functions/import-csv/stock-quantity-import.ts b/packages/database/supabase/functions/import-csv/stock-quantity-import.ts
new file mode 100644
index 0000000000..8acfef6d13
--- /dev/null
+++ b/packages/database/supabase/functions/import-csv/stock-quantity-import.ts
@@ -0,0 +1,565 @@
+// Opening-stock importer — backs the `inventoryQuantity`, `batchQuantity` and
+// `serialQuantity` CSV imports. Additive only: every accepted row is ONE
+// Positive Adjmt., booked exactly the way the single-record inventory
+// adjustment (post-inventory-adjustment) books a positive adjustment:
+//
+// - Batch / Serial rows first create a new trackedEntity (same columns and
+// "Inventory Adjustment" attributes stamp as a new entity there).
+// - The movement writes what the shared posting core (`bookAdjustment`) writes
+// for a positive adjustment: item ledger + cost layer at the item's current
+// cost + (when companySettings.accountingEnabled) a balanced journal against
+// the inventory adjustment variance account. EVERY one of those rows is
+// BUILT by the pure builders `bookAdjustment` itself uses
+// (`shared/plan-adjustment.ts`: `buildItemLedgerRow`, `buildCostLedgerRow`,
+// `buildAdjustmentJournalLines`, `buildJournalLineDimensions`) and
+// inserted in bulk — one statement per table per chunk instead of ~7 round
+// trips per row, which is what keeps a large file inside the edge runtime's
+// wall clock.
+// - With accounting on, the whole import shares ONE adjustment journal,
+// created lazily on the first movement that carries value — the
+// post-inventory-count pattern.
+//
+// Row validation / dedup lives in the pure `classify-stock-row.ts`. No
+// externalIntegrationMapping writes: there is no Unique ID column.
+
+import { parseDate } from "@internationalized/date";
+import type { SupabaseClient } from "@supabase/supabase-js";
+import { nanoid } from "https://deno.land/x/[email protected]/mod.ts";
+import type { Kysely } from "kysely";
+import type { DB } from "../lib/database.ts";
+import { datetime, getCompanyTimeZone } from "../lib/datetime.ts";
+import { getFunctionLogger } from "../lib/logging.ts";
+import type { Database, Json } from "../lib/types.ts";
+import { getCurrentAccountingPeriod } from "../shared/get-accounting-period.ts";
+import { getDefaultPostingGroup } from "../shared/get-posting-group.ts";
+import {
+ buildAdjustmentJournalLines,
+ buildCostLedgerRow,
+ buildItemLedgerRow,
+ buildJournalLineDimensions,
+ carriesAdjustmentValue,
+ planStockRows,
+} from "../shared/plan-adjustment.ts";
+import {
+ createAdjustmentJournal,
+ loadOpenCostLayers,
+} from "../shared/post-adjustment.ts";
+import {
+ buildStockItemMap,
+ classifyStockRow,
+ STOCK_IMPORT_TRACKING_TYPE,
+ type StockImportTable,
+ type StockRowResolved,
+ storageUnitKey,
+ trackedKey,
+} from "./classify-stock-row.ts";
+
+const logger = getFunctionLogger("import-csv");
+
+type Rec = Record<string, string>;
+type Summary = {
+ inserted: number;
+ updated: number;
+ errors: Array<{ row: number; reason: string }>;
+ skipped: Array<{ row: number; reason: string }>;
+};
+
+const text = (s: string | undefined): string => (s ?? "").trim();
+
+// Rows per INSERT. Every statement here is a plain multi-row VALUES insert, so
+// the ceiling is Postgres' 65535 bind parameters: the widest table written
+// (itemLedger, 14 columns) is ~7k parameters at this size, and the deepest
+// fan-out (journalLineDimension, 3 tags × 2 lines per row) still lands inside
+// one statement per 84 source rows.
+const INSERT_CHUNK_SIZE = 500;
+
+const chunked = <T>(rows: T[], size = INSERT_CHUNK_SIZE): T[][] => {
+ const chunks: T[][] = [];
+ for (let i = 0; i < rows.length; i += size) {
+ chunks.push(rows.slice(i, i + size));
+ }
+ return chunks;
+};
+
+export async function importStockQuantities(
+ db: Kysely<DB>,
+ client: SupabaseClient<Database>,
+ args: {
+ table: StockImportTable;
+ mappedRecords: Rec[];
+ companyId: string;
+ userId: string;
+ summary: Summary;
+ }
+): Promise<void> {
+ const { table, mappedRecords, companyId, userId, summary } = args;
+ const isTracked = table !== "inventoryQuantity";
+
+ // 1. preload lookups ------------------------------------------------------
+ const readableIds = [
+ ...new Set(mappedRecords.map((r) => text(r.readableId)).filter(Boolean)),
+ ];
+ const items =
+ readableIds.length > 0
+ ? await db
+ .selectFrom("item")
+ .select([
+ "id",
+ "readableId",
+ "revision",
+ "readableIdWithRevision",
+ "itemTrackingType",
+ "replenishmentSystem",
+ "type",
+ ])
+ .where("companyId", "=", companyId)
+ .where("readableId", "in", readableIds)
+ .orderBy("type")
+ .orderBy("id")
+ .execute()
+ : [];
+
+ const itemIds = items.map((i) => i.id);
+ const [itemCosts, shelfLives] =
+ itemIds.length > 0
+ ? await Promise.all([
+ db
+ .selectFrom("itemCost")
+ .select([
+ "itemId",
+ "costingMethod",
+ "unitCost",
+ "standardCost",
+ "itemPostingGroupId",
+ ])
+ .where("companyId", "=", companyId)
+ .where("itemId", "in", itemIds)
+ .execute(),
+ isTracked
+ ? db
+ .selectFrom("itemShelfLife")
+ .select(["itemId", "mode", "days"])
+ .where("companyId", "=", companyId)
+ .where("itemId", "in", itemIds)
+ .execute()
+ : Promise.resolve([]),
+ ])
+ : [[], []];
+ const itemCostByItem = new Map(itemCosts.map((c) => [c.itemId, c]));
+ const shelfLifeByItem = new Map(shelfLives.map((s) => [s.itemId, s]));
+
+ // readableId + revision → item; ties broken in `buildStockItemMap`. The
+ // query order (type, id) makes the fallback pick deterministic.
+ const itemMap = buildStockItemMap(
+ table,
+ items.map((i) => ({
+ id: i.id,
+ readableId: i.readableId,
+ revision: i.revision,
+ itemTrackingType: i.itemTrackingType,
+ hasItemCost: itemCostByItem.has(i.id),
+ }))
+ );
+ const itemById = new Map(items.map((i) => [i.id, i]));
+
+ const locations = await db
+ .selectFrom("location")
+ .select(["id"])
+ .where("companyId", "=", companyId)
+ .execute();
+ const locationIds = new Set(locations.map((l) => l.id));
+
+ const referencedLocationIds = [
+ ...new Set(
+ mappedRecords
+ .map((r) => text(r.locationId))
+ .filter((l) => l !== "" && locationIds.has(l))
+ ),
+ ];
+ const storageUnits =
+ referencedLocationIds.length > 0
+ ? await db
+ .selectFrom("storageUnit")
+ .select(["id", "name", "locationId"])
+ .where("companyId", "=", companyId)
+ .where("locationId", "in", referencedLocationIds)
+ // Only active units, as the single-record adjustment offers
+ // (getStorageUnitsListForLocation); an inactive name falls through
+ // to the "not found in this location" row error.
+ .where("active", "=", true)
+ .execute()
+ : [];
+ const storageUnitMap = new Map<string, string>();
+ for (const u of storageUnits) {
+ storageUnitMap.set(storageUnitKey(u.locationId, u.name), u.id);
+ }
+
+ // Existing batch / serial numbers on the referenced items, any status.
+ const existingTrackedKeys = new Set<string>();
+ if (isTracked && itemIds.length > 0) {
+ const numberField = table === "serialQuantity" ? "serialNumber" : "batchNumber";
+ const numbers = [
+ ...new Set(mappedRecords.map((r) => text(r[numberField])).filter(Boolean)),
+ ];
+ if (numbers.length > 0) {
+ const existing = await db
+ .selectFrom("trackedEntity")
+ .select(["itemId", "readableId"])
+ .where("companyId", "=", companyId)
+ .where("itemId", "in", itemIds)
+ .where("readableId", "in", numbers)
+ .execute();
+ for (const e of existing) {
+ if (e.itemId && e.readableId) {
+ existingTrackedKeys.add(trackedKey(e.itemId, e.readableId));
+ }
+ }
+ }
+ }
+
+ // 2. classify -------------------------------------------------------------
+ const seenTrackedKeys = new Set<string>();
+ const planned: StockRowResolved[] = [];
+ for (const [rowIndex, record] of mappedRecords.entries()) {
+ const decision = classifyStockRow({
+ table,
+ record,
+ itemMap,
+ locationIds,
+ storageUnitMap,
+ existingTrackedKeys,
+ seenTrackedKeys,
+ });
+ if (decision.action === "skip") {
+ (decision.category === "error" ? summary.errors : summary.skipped).push({
+ row: rowIndex,
+ reason: decision.reason,
+ });
+ continue;
+ }
+ // Claim the dedup slot only once the row is valid, so a rejected row never
+ // blocks a later legitimate row with the same number.
+ if (decision.row.trackedKey) seenTrackedKeys.add(decision.row.trackedKey);
+ planned.push(decision.row);
+ }
+
+ logger.info({
+ function: "import-stock-quantities",
+ table,
+ trackingType: STOCK_IMPORT_TRACKING_TYPE[table],
+ totalRecords: mappedRecords.length,
+ planned: planned.length,
+ skipped: summary.skipped.length,
+ errors: summary.errors.length,
+ });
+
+ if (planned.length === 0) return;
+
+ // 3. accounting context — resolved BEFORE the transaction, as
+ // post-inventory-adjustment / post-inventory-count do (REST hops
+ // mid-transaction park the size-1 pool in idle-in-transaction).
+ const today = datetime
+ .today(await getCompanyTimeZone(client, companyId))
+ .toString();
+ const nowIso = new Date().toISOString();
+
+ const accountingSettings = await client
+ .from("companySettings")
+ .select("accountingEnabled")
+ .eq("id", companyId)
+ .single();
+ // Fail closed: a failed settings read must not silently post without GL.
+ if (accountingSettings.error) {
+ throw new Error("Failed to fetch company settings");
+ }
+ const accountingEnabled = accountingSettings.data?.accountingEnabled ?? false;
+ const accountDefaults = accountingEnabled
+ ? await getDefaultPostingGroup(client, companyId)
+ : null;
+ if (accountingEnabled && (accountDefaults?.error || !accountDefaults?.data)) {
+ throw new Error("Error getting account defaults");
+ }
+ const accountingPeriodId = accountingEnabled
+ ? await getCurrentAccountingPeriod(client, companyId, db, today)
+ : null;
+
+ // Active dimensions for the company group — journal lines get Item /
+ // ItemPostingGroup / Location tags.
+ const dimensionMap: Record<string, string> = {};
+ if (accountingEnabled) {
+ const companyRecord = await client
+ .from("company")
+ .select("companyGroupId")
+ .eq("id", companyId)
+ .single();
+ if (companyRecord.error) throw new Error("Failed to fetch company");
+ const dimensions = await client
+ .from("dimension")
+ .select("id, entityType")
+ .eq("companyGroupId", companyRecord.data.companyGroupId)
+ .eq("active", true)
+ .in("entityType", ["Item", "ItemPostingGroup", "Location"]);
+ // Fail closed: journal lines must not silently lose dimension tags.
+ if (dimensions.error) throw new Error("Failed to fetch dimensions");
+ for (const dim of dimensions.data ?? []) {
+ if (dim.entityType) dimensionMap[dim.entityType] = dim.id;
+ }
+ }
+
+ const accounting =
+ accountingEnabled && accountDefaults?.data && accountingPeriodId
+ ? {
+ accountingPeriodId,
+ accountDefaults: {
+ rawMaterialsAccount: accountDefaults.data.rawMaterialsAccount,
+ finishedGoodsAccount: accountDefaults.data.finishedGoodsAccount,
+ inventoryAdjustmentVarianceAccount:
+ accountDefaults.data.inventoryAdjustmentVarianceAccount,
+ },
+ description: "Inventory Adjustment — CSV import",
+ userId,
+ dimensions: dimensionMap,
+ }
+ : null;
+
+ // Fixed Duration shelf-life fallback for a new tracked entity with no typed
+ // expiry — same rule as post-inventory-adjustment's
+ // resolveExpirationForNewEntity. Other modes stay NULL.
+ const resolveExpiration = (row: StockRowResolved): string | null => {
+ if (row.expirationDate) return row.expirationDate;
+ const shelfLife = shelfLifeByItem.get(row.itemId);
+ if (shelfLife?.mode === "Fixed Duration" && shelfLife.days) {
+ return parseDate(today).add({ days: Number(shelfLife.days) }).toString();
+ }
+ return null;
+ };
+
+ // 4. write — whole file in one transaction --------------------------------
+ // Everything is planned in memory first, then written table by table in bulk.
+ // The rows are byte-for-byte what `bookAdjustment` writes per movement
+ // because every one of them — item ledger, cost layer, journal line,
+ // journal line dimension — comes out of the builders in
+ // `shared/plan-adjustment.ts` that `bookAdjustment` itself calls, and the
+ // cost layers are valued by replaying the per-row read (see
+ // `planIncreaseUnitCosts`). Nothing here re-derives a field.
+ await db.transaction().execute(async (trx) => {
+ // A tracked entity's id is ours to choose, so the ledger rows can name it
+ // before anything is inserted.
+ const trackedEntityIds = planned.map(() => (isTracked ? nanoid() : null));
+
+ // Value every row up front. `planStockRows` (pure, tested) does the whole
+ // per-file plan: which rows carry value at all (bookAdjustment's early
+ // return — classifyStockRow already rejects both cases, so it guards a
+ // future column rather than a live branch), each row's layer cost from the
+ // per-item replay, and which rows post to the GL.
+ const planInputs = planned.map((row) => ({
+ itemId: row.itemId,
+ quantity: row.quantity,
+ itemTrackingType: itemById.get(row.itemId)!.itemTrackingType,
+ }));
+ const openLayersByItem = await loadOpenCostLayers(trx, {
+ itemIds: [
+ ...new Set(
+ planInputs
+ .filter((row) =>
+ carriesAdjustmentValue(row.quantity, row.itemTrackingType)
+ )
+ .map((row) => row.itemId)
+ ),
+ ],
+ companyId,
+ });
+ const rowPlans = planStockRows({
+ rows: planInputs,
+ itemCosts: itemCostByItem,
+ openLayersByItem,
+ hasAccounting: accounting !== null,
+ });
+
+ // Tracked entities first: the ledger rows reference them.
+ if (isTracked) {
+ const trackedEntityRows = planned.map((row, rowIndex) => {
+ const item = itemById.get(row.itemId)!;
+ const expirationDate = resolveExpiration(row);
+ // Stamp the trace blob so the popover Source / Override steps show
+ // where the entity originated (post-inventory-adjustment shape).
+ const adjustmentStamp = {
+ userId,
+ at: nowIso,
+ reason: "Created via CSV import",
+ };
+ const attributes: Record<string, unknown> = {
+ "Inventory Adjustment": adjustmentStamp,
+ ...(expirationDate
+ ? {
+ expiryOverrides: [
+ {
+ previous: null,
+ next: expirationDate,
+ reason: adjustmentStamp.reason,
+ source: "Inventory Adjustment",
+ userId: adjustmentStamp.userId,
+ at: adjustmentStamp.at,
+ },
+ ],
+ }
+ : {}),
+ };
+ return {
+ id: trackedEntityIds[rowIndex]!,
+ sourceDocument: "Item",
+ sourceDocumentId: row.itemId,
+ sourceDocumentReadableId: item.readableIdWithRevision ?? undefined,
+ itemId: row.itemId,
+ readableId: row.readableId,
+ quantity: row.quantity,
+ status: "Available" as const,
+ expirationDate,
+ attributes: attributes as unknown as Json,
+ companyId,
+ createdBy: userId,
+ };
+ });
+ for (const rows of chunked(trackedEntityRows)) {
+ await trx.insertInto("trackedEntity").values(rows).execute();
+ }
+ }
+
+ // Item ledger. The generated id is each movement's documentId on its cost
+ // ledger and journal lines, so the ids have to come back mapped to their
+ // source row. `entryNumber` is a SERIAL assigned as the VALUES rows are
+ // formed, so sorting each chunk by it recovers the source order without
+ // depending on RETURNING's output order.
+ const itemLedgerIds: string[] = [];
+ for (const rows of chunked(
+ planned.map((row, rowIndex) =>
+ buildItemLedgerRow({
+ postingDate: today,
+ entryType: "Positive Adjmt.",
+ documentType: null,
+ documentId: null,
+ correctionOfItemLedgerId: null,
+ itemId: row.itemId,
+ locationId: row.locationId,
+ storageUnitId: row.storageUnitId,
+ trackedEntityId: trackedEntityIds[rowIndex],
+ quantity: row.quantity,
+ comment: row.comment,
+ scrapReasonId: null,
+ companyId,
+ createdBy: userId,
+ })
+ )
+ )) {
+ const inserted = await trx
+ .insertInto("itemLedger")
+ .values(rows)
+ .returning(["id", "entryNumber"])
+ .execute();
+ inserted.sort((a, b) => Number(a.entryNumber) - Number(b.entryNumber));
+ for (const row of inserted) itemLedgerIds.push(row.id);
+ }
+ if (itemLedgerIds.length !== planned.length) {
+ throw new Error("Item ledger insert did not return a row per movement");
+ }
+
+ // Cost layers.
+ const costLedgerRows = planned.flatMap((row, rowIndex) =>
+ rowPlans[rowIndex].carriesValue
+ ? [
+ buildCostLedgerRow({
+ entryType: "Positive Adjmt.",
+ documentType: null,
+ documentId: itemLedgerIds[rowIndex],
+ itemId: row.itemId,
+ quantity: row.quantity,
+ cost: rowPlans[rowIndex].cost,
+ postingDate: today,
+ companyId,
+ }),
+ ]
+ : []
+ );
+ for (const rows of chunked(costLedgerRows)) {
+ await trx.insertInto("costLedger").values(rows).execute();
+ }
+
+ // Journal. A zero-value movement posts no lines, so an all-zero-cost file
+ // creates no journal at all — the lazy `getJournalId` behaviour, decided
+ // once here instead of per row.
+ const postingRowIndexes = planned
+ .map((_, rowIndex) => rowIndex)
+ .filter((rowIndex) => rowPlans[rowIndex].postsJournal);
+ if (accounting && postingRowIndexes.length > 0) {
+ const journalId = await createAdjustmentJournal(trx, {
+ companyId,
+ accountingPeriodId: accounting.accountingPeriodId,
+ description: accounting.description,
+ postingDate: today,
+ userId,
+ });
+
+ // `journalLineReference` already identifies a movement's line pair (it
+ // is what ties the two sides together on the per-row path), so it is
+ // also how the inserted ids find their way back to their movement — no
+ // positional assumption about RETURNING.
+ const referenceByRowIndex = new Map<number, string>(
+ postingRowIndexes.map((rowIndex) => [rowIndex, nanoid()])
+ );
+ const journalLineRows = postingRowIndexes.flatMap((rowIndex) => {
+ const row = planned[rowIndex];
+ const item = itemById.get(row.itemId)!;
+ return buildAdjustmentJournalLines({
+ journalId,
+ documentId: itemLedgerIds[rowIndex],
+ documentType: null,
+ journalLineReference: referenceByRowIndex.get(rowIndex)!,
+ isGain: true,
+ cost: rowPlans[rowIndex].cost,
+ quantity: row.quantity,
+ replenishmentSystem: item.replenishmentSystem,
+ accountDefaults: accounting.accountDefaults,
+ companyId,
+ });
+ });
+ const journalLineIdsByReference = new Map<string, string[]>();
+ for (const rows of chunked(journalLineRows)) {
+ const inserted = await trx
+ .insertInto("journalLine")
+ .values(rows)
+ .returning(["id", "journalLineReference"])
+ .execute();
+ for (const line of inserted) {
+ const reference = line.journalLineReference;
+ const ids = journalLineIdsByReference.get(reference) ?? [];
+ ids.push(line.id);
+ journalLineIdsByReference.set(reference, ids);
+ }
+ }
+
+ const dimensionRows = postingRowIndexes.flatMap((rowIndex) => {
+ const row = planned[rowIndex];
+ const reference = referenceByRowIndex.get(rowIndex)!;
+ const journalLineIds = journalLineIdsByReference.get(reference) ?? [];
+ if (journalLineIds.length !== 2) {
+ throw new Error(
+ "Journal line insert did not return a pair per movement"
+ );
+ }
+ return buildJournalLineDimensions({
+ journalLineIds,
+ dimensions: accounting.dimensions,
+ itemId: row.itemId,
+ itemPostingGroupId: itemCostByItem.get(row.itemId)!.itemPostingGroupId,
+ locationId: row.locationId,
+ companyId,
+ });
+ });
+ for (const rows of chunked(dimensionRows)) {
+ await trx.insertInto("journalLineDimension").values(rows).execute();
+ }
+ }
+
+ summary.inserted += planned.length;
+ });
+}
diff --git a/packages/database/supabase/functions/shared/plan-adjustment.test.ts b/packages/database/supabase/functions/shared/plan-adjustment.test.ts
new file mode 100644
index 0000000000..edc71d9618
--- /dev/null
+++ b/packages/database/supabase/functions/shared/plan-adjustment.test.ts
@@ -0,0 +1,545 @@
+import { assertEquals } from "https://deno.land/[email protected]/testing/asserts.ts";
+import {
+ buildAdjustmentJournalLines,
+ buildCostLedgerRow,
+ buildItemLedgerRow,
+ buildJournalLineDimensions,
+ planIncreaseUnitCosts,
+ planStockRows,
+ toJournalLineDocumentType,
+} from "./plan-adjustment.ts";
+import type { AdjustmentItemCost } from "./post-adjustment-cost.ts";
+import { computeCurrentUnitCost } from "./post-adjustment-cost.ts";
+import { round } from "./precision.ts";
+
+const accountDefaults = {
+ rawMaterialsAccount: "raw",
+ finishedGoodsAccount: "fg",
+ inventoryAdjustmentVarianceAccount: "variance",
+};
+
+// The read the per-row path performs before each increase, reproduced from the
+// layers written so far. `planIncreaseUnitCosts` must agree with this for a
+// whole file, which is the batch path's entire correctness claim.
+const bookOneAtATime = (
+ itemCost: Parameters<typeof computeCurrentUnitCost>[0],
+ openLayers: Parameters<typeof computeCurrentUnitCost>[1],
+ quantities: number[]
+) => {
+ const layers = [...openLayers];
+ return quantities.map((quantity) => {
+ const unitCost = computeCurrentUnitCost(itemCost, layers);
+ const row = buildCostLedgerRow({
+ entryType: "Positive Adjmt.",
+ documentType: null,
+ documentId: "il",
+ itemId: "item",
+ quantity,
+ cost: quantity * unitCost,
+ postingDate: "2026-09-22",
+ companyId: "c",
+ });
+ if ((row.remainingQuantity ?? 0) > 0) {
+ layers.push({
+ quantity: row.quantity!,
+ remainingQuantity: row.remainingQuantity!,
+ cost: row.cost!,
+ appliedChildCost: 0,
+ });
+ }
+ return row.cost;
+ });
+};
+
+const plannedCosts = (
+ itemCost: Parameters<typeof computeCurrentUnitCost>[0],
+ openLayers: Parameters<typeof computeCurrentUnitCost>[1],
+ quantities: number[]
+) =>
+ planIncreaseUnitCosts(itemCost, openLayers, quantities).map((increase) =>
+ round(increase.cost)
+ );
+
+Deno.test("Standard: every row of an item costs the same, layers ignored", () => {
+ const itemCost = {
+ costingMethod: "Standard" as const,
+ unitCost: 3,
+ standardCost: 5,
+ };
+ const increases = planIncreaseUnitCosts(itemCost, [], [2, 10, 1]);
+ assertEquals(
+ increases.map((i) => i.unitCost),
+ [5, 5, 5]
+ );
+ assertEquals(
+ increases.map((i) => i.cost),
+ [10, 50, 5]
+ );
+});
+
+Deno.test("Average: every row of an item costs the same, layers ignored", () => {
+ const itemCost = {
+ costingMethod: "Average" as const,
+ unitCost: 7.25,
+ standardCost: 0,
+ };
+ const increases = planIncreaseUnitCosts(
+ itemCost,
+ [{ quantity: 100, remainingQuantity: 100, cost: 1, appliedChildCost: 0 }],
+ [4, 4]
+ );
+ assertEquals(
+ increases.map((i) => i.unitCost),
+ [7.25, 7.25]
+ );
+});
+
+Deno.test("FIFO: a layer added at the current average leaves it unchanged", () => {
+ // 100 @ $10 open. Every row books at $10 and the average stays $10, because
+ // a layer of q units carrying q × $10 contributes exactly the average back.
+ const itemCost = {
+ costingMethod: "FIFO" as const,
+ unitCost: 1,
+ standardCost: 0,
+ };
+ const increases = planIncreaseUnitCosts(
+ itemCost,
+ [{ quantity: 100, remainingQuantity: 100, cost: 1000, appliedChildCost: 0 }],
+ [5, 5, 5]
+ );
+ assertEquals(
+ increases.map((i) => i.unitCost),
+ [10, 10, 10]
+ );
+});
+
+Deno.test("FIFO: the first row seeds the fallback cost and later rows average over it", () => {
+ const itemCost = {
+ costingMethod: "FIFO" as const,
+ unitCost: 4.5,
+ standardCost: 0,
+ };
+ const increases = planIncreaseUnitCosts(itemCost, [], [2, 8]);
+ assertEquals(
+ increases.map((i) => i.unitCost),
+ [4.5, 4.5]
+ );
+ assertEquals(
+ increases.map((i) => i.cost),
+ [9, 36]
+ );
+});
+
+Deno.test("FIFO: a rounded layer cost carries into the next row, exactly as the per-row path does", () => {
+ // The equivalence is only exact in real arithmetic: the layer is STORED at
+ // round(q × u, 5), so a 1-unit row at 1/3 stores 0.33333 and the next row
+ // averages over 0.33333, not over 1/3. A hoisted unit cost would book
+ // 333.33333 for the 1000-unit row; the per-row path books 333.33.
+ const itemCost = {
+ costingMethod: "FIFO" as const,
+ unitCost: 1 / 3,
+ standardCost: 0,
+ };
+ const planned = plannedCosts(itemCost, [], [1, 1000]);
+ assertEquals(planned, [0.33333, 333.33]);
+ assertEquals(planned, bookOneAtATime(itemCost, [], [1, 1000]));
+ // What hoisting one unit cost per item would have produced.
+ assertEquals(round(1000 * (1 / 3)), 333.33333);
+});
+
+Deno.test("planIncreaseUnitCosts matches booking the rows one at a time", () => {
+ const openLayers = [
+ { quantity: 7, remainingQuantity: 3, cost: 21.55, appliedChildCost: 1.3 },
+ { quantity: 12, remainingQuantity: 12, cost: 149.99, appliedChildCost: 0 },
+ ];
+ const quantities = [1, 3.5, 0.125, 1000, 17];
+ for (const costingMethod of [
+ "Standard",
+ "Average",
+ "FIFO",
+ "LIFO",
+ ] as const) {
+ const itemCost = { costingMethod, unitCost: 1 / 7, standardCost: 2.5 };
+ assertEquals(
+ plannedCosts(itemCost, openLayers, quantities),
+ bookOneAtATime(itemCost, openLayers, quantities),
+ costingMethod
+ );
+ }
+});
+
+Deno.test("planIncreaseUnitCosts is per item: one item's layers never reach another", () => {
+ // The driver groups rows by item and calls this once per item, so a mixed
+ // file is two independent replays. Proven by planning the same item's rows
+ // interleaved and alone.
+ const itemCost = {
+ costingMethod: "FIFO" as const,
+ unitCost: 1 / 3,
+ standardCost: 0,
+ };
+ const other = {
+ costingMethod: "FIFO" as const,
+ unitCost: 99,
+ standardCost: 0,
+ };
+ assertEquals(
+ plannedCosts(itemCost, [], [1, 1000]),
+ plannedCosts(itemCost, [], [1, 1000])
+ );
+ assertEquals(plannedCosts(other, [], [1]), [99]);
+});
+
+Deno.test("A zero-quantity row opens no layer for the next row to see", () => {
+ const itemCost = {
+ costingMethod: "FIFO" as const,
+ unitCost: 4,
+ standardCost: 0,
+ };
+ // The middle row rounds to a zero quantity, so its layer has
+ // remainingQuantity 0 and the open-layer query would not return it.
+ const increases = planIncreaseUnitCosts(itemCost, [], [0, 0, 6]);
+ assertEquals(
+ increases.map((i) => i.unitCost),
+ [4, 4, 4]
+ );
+});
+
+Deno.test("buildCostLedgerRow opens a layer on an increase and none on a decrease", () => {
+ const increase = buildCostLedgerRow({
+ entryType: "Positive Adjmt.",
+ documentType: null,
+ documentId: "il1",
+ itemId: "item",
+ quantity: 5,
+ cost: 12.345678,
+ postingDate: "2026-09-22",
+ companyId: "c",
+ });
+ assertEquals(increase.quantity, 5);
+ assertEquals(increase.cost, 12.34568);
+ assertEquals(increase.remainingQuantity, 5);
+ assertEquals(increase.adjustment, false);
+ assertEquals(increase.costLedgerType, "Direct Cost");
+
+ const decrease = buildCostLedgerRow({
+ entryType: "Negative Adjmt.",
+ documentType: null,
+ documentId: "il2",
+ itemId: "item",
+ quantity: -5,
+ cost: -50,
+ postingDate: "2026-09-22",
+ companyId: "c",
+ });
+ assertEquals(decrease.quantity, -5);
+ assertEquals(decrease.remainingQuantity, 0);
+});
+
+Deno.test("buildAdjustmentJournalLines balances a gain against the variance account", () => {
+ const [inventory, offset] = buildAdjustmentJournalLines({
+ journalId: "j1",
+ documentId: "il1",
+ documentType: null,
+ journalLineReference: "ref",
+ isGain: true,
+ cost: 250,
+ quantity: 10,
+ replenishmentSystem: "Buy",
+ accountDefaults,
+ companyId: "c",
+ });
+ assertEquals(inventory.accountId, "raw");
+ assertEquals(inventory.description, "Raw Materials Account");
+ assertEquals(inventory.amount, 250);
+ assertEquals(inventory.documentType, "Inventory Adjustment");
+ assertEquals(offset.accountId, "variance");
+ assertEquals(offset.amount, -250);
+ assertEquals(inventory.amount + offset.amount, 0);
+ assertEquals(inventory.journalLineReference, offset.journalLineReference);
+});
+
+Deno.test("buildAdjustmentJournalLines sends a Make item to finished goods", () => {
+ const [inventory] = buildAdjustmentJournalLines({
+ journalId: "j1",
+ documentId: "il1",
+ journalLineReference: "ref",
+ isGain: true,
+ cost: 1,
+ quantity: 1,
+ replenishmentSystem: "Make",
+ accountDefaults,
+ companyId: "c",
+ });
+ assertEquals(inventory.accountId, "fg");
+});
+
+Deno.test("toJournalLineDocumentType falls back for types the journal enum lacks", () => {
+ assertEquals(toJournalLineDocumentType(null), "Inventory Adjustment");
+ assertEquals(toJournalLineDocumentType("Sales Invoice"), "Inventory Adjustment");
+ assertEquals(toJournalLineDocumentType("Inventory Count"), "Inventory Count");
+});
+
+Deno.test("buildJournalLineDimensions tags every line with the active dimensions", () => {
+ const rows = buildJournalLineDimensions({
+ journalLineIds: ["l1", "l2"],
+ dimensions: { Item: "d-item", Location: "d-loc" },
+ itemId: "item",
+ itemPostingGroupId: "ipg",
+ locationId: "loc",
+ companyId: "c",
+ });
+ // ItemPostingGroup has a value but no active dimension, so it is not tagged.
+ assertEquals(rows.length, 4);
+ assertEquals(
+ rows.map((r) => `${r.journalLineId}:${r.dimensionId}:${r.valueId}`),
+ [
+ "l1:d-item:item",
+ "l1:d-loc:loc",
+ "l2:d-item:item",
+ "l2:d-loc:loc",
+ ]
+ );
+});
+
+Deno.test("buildJournalLineDimensions skips a dimension whose value is null", () => {
+ const rows = buildJournalLineDimensions({
+ journalLineIds: ["l1"],
+ dimensions: { Item: "d-item", ItemPostingGroup: "d-ipg", Location: "d-loc" },
+ itemId: "item",
+ itemPostingGroupId: null,
+ locationId: null,
+ companyId: "c",
+ });
+ assertEquals(rows.length, 1);
+ assertEquals(rows[0].dimensionId, "d-item");
+});
+
+Deno.test("buildItemLedgerRow rounds the quantity and defaults the optional columns", () => {
+ const row = buildItemLedgerRow({
+ postingDate: "2026-09-22",
+ entryType: "Positive Adjmt.",
+ itemId: "item",
+ locationId: "loc",
+ storageUnitId: null,
+ trackedEntityId: "te1",
+ quantity: 2.1234567,
+ companyId: "c",
+ createdBy: "u",
+ });
+ assertEquals(row.quantity, 2.12346);
+ assertEquals(row.entryType, "Positive Adjmt.");
+ assertEquals(row.documentType, null);
+ assertEquals(row.documentId, null);
+ assertEquals(row.correctionOfItemLedgerId, null);
+ assertEquals(row.comment, null);
+ assertEquals(row.scrapReasonId, null);
+ assertEquals(row.trackedEntityId, "te1");
+});
+
+Deno.test("buildItemLedgerRow keeps a decrease signed and carries the passed columns", () => {
+ const row = buildItemLedgerRow({
+ postingDate: "2026-09-22",
+ entryType: "Negative Adjmt.",
+ documentType: "Scrap",
+ documentId: "doc1",
+ correctionOfItemLedgerId: "il0",
+ itemId: "item",
+ locationId: null,
+ storageUnitId: "su1",
+ trackedEntityId: null,
+ quantity: -5,
+ comment: "note",
+ scrapReasonId: "sr1",
+ companyId: "c",
+ createdBy: "u",
+ });
+ assertEquals(row.quantity, -5);
+ assertEquals(row.documentType, "Scrap");
+ assertEquals(row.documentId, "doc1");
+ assertEquals(row.correctionOfItemLedgerId, "il0");
+ assertEquals(row.storageUnitId, "su1");
+ assertEquals(row.comment, "note");
+ assertEquals(row.scrapReasonId, "sr1");
+});
+
+// --- planStockRows: the batching decision the importer writes from ---------
+
+const itemCosts = (
+ entries: Record<string, AdjustmentItemCost>
+): Map<string, AdjustmentItemCost> => new Map(Object.entries(entries));
+
+const fifo = (unitCost: number): AdjustmentItemCost => ({
+ costingMethod: "FIFO",
+ unitCost,
+ standardCost: 0,
+});
+
+Deno.test("planStockRows scatters each item's replayed costs back onto its own rows", () => {
+ // A mixed file with one item's rows NOT adjacent. Item A's two rows differ
+ // (the rounded-layer case), so a scatter that dropped or swapped an index
+ // would put B's cost — or A's other row's cost — on the wrong row.
+ const rows = [
+ { itemId: "A", quantity: 1, itemTrackingType: "Inventory" },
+ { itemId: "B", quantity: 2, itemTrackingType: "Inventory" },
+ { itemId: "A", quantity: 1000, itemTrackingType: "Inventory" },
+ ];
+ const plans = planStockRows({
+ rows,
+ itemCosts: itemCosts({
+ A: fifo(1 / 3),
+ B: { costingMethod: "Standard", unitCost: 0, standardCost: 5 },
+ }),
+ openLayersByItem: new Map(),
+ hasAccounting: true,
+ });
+
+ const replayA = planIncreaseUnitCosts(fifo(1 / 3), [], [1, 1000]);
+ assertEquals(
+ plans.map((p) => round(p.cost)),
+ [round(replayA[0].cost), 10, round(replayA[1].cost)]
+ );
+ assertEquals(
+ plans.map((p) => round(p.cost)),
+ [0.33333, 10, 333.33]
+ );
+ assertEquals(
+ plans.map((p) => p.carriesValue),
+ [true, true, true]
+ );
+ assertEquals(
+ plans.map((p) => p.postsJournal),
+ [true, true, true]
+ );
+});
+
+Deno.test("planStockRows replays several rows of ONE item in file order", () => {
+ const quantities = [1, 1000, 3];
+ const rows = quantities.map((quantity) => ({
+ itemId: "A",
+ quantity,
+ itemTrackingType: "Inventory",
+ }));
+ const plans = planStockRows({
+ rows,
+ itemCosts: itemCosts({ A: fifo(1 / 3) }),
+ openLayersByItem: new Map(),
+ hasAccounting: true,
+ });
+ assertEquals(
+ plans.map((p) => round(p.cost)),
+ planIncreaseUnitCosts(fifo(1 / 3), [], quantities).map((i) =>
+ round(i.cost)
+ )
+ );
+});
+
+Deno.test("planStockRows values against the item's open layers", () => {
+ const plans = planStockRows({
+ rows: [{ itemId: "A", quantity: 5, itemTrackingType: "Inventory" }],
+ itemCosts: itemCosts({ A: fifo(1) }),
+ openLayersByItem: new Map([
+ [
+ "A",
+ [
+ {
+ quantity: 100,
+ remainingQuantity: 100,
+ cost: 1000,
+ appliedChildCost: 0,
+ },
+ ],
+ ],
+ ]),
+ hasAccounting: true,
+ });
+ // $10 average from the open layer, not the $1 itemCost fallback.
+ assertEquals(plans[0].cost, 50);
+});
+
+Deno.test("planStockRows: a zero-cost item plans a cost layer but no journal", () => {
+ const plans = planStockRows({
+ rows: [
+ { itemId: "A", quantity: 5, itemTrackingType: "Inventory" },
+ { itemId: "A", quantity: 9, itemTrackingType: "Inventory" },
+ ],
+ itemCosts: itemCosts({
+ A: { costingMethod: "Average", unitCost: 0, standardCost: 0 },
+ }),
+ openLayersByItem: new Map(),
+ hasAccounting: true,
+ });
+ assertEquals(
+ plans.map((p) => p.cost),
+ [0, 0]
+ );
+ // The layer is still written — only the journal pair is suppressed.
+ assertEquals(
+ plans.map((p) => p.carriesValue),
+ [true, true]
+ );
+ assertEquals(
+ plans.map((p) => p.postsJournal),
+ [false, false]
+ );
+ const row = buildCostLedgerRow({
+ entryType: "Positive Adjmt.",
+ documentType: null,
+ documentId: "il1",
+ itemId: "A",
+ quantity: 5,
+ cost: plans[0].cost,
+ postingDate: "2026-09-22",
+ companyId: "c",
+ });
+ assertEquals(row.cost, 0);
+ assertEquals(row.remainingQuantity, 5);
+});
+
+Deno.test("planStockRows: accounting disabled posts no journal on any row", () => {
+ const plans = planStockRows({
+ rows: [
+ { itemId: "A", quantity: 3, itemTrackingType: "Inventory" },
+ { itemId: "B", quantity: 4, itemTrackingType: "Batch" },
+ ],
+ itemCosts: itemCosts({
+ A: { costingMethod: "Average", unitCost: 2, standardCost: 0 },
+ B: { costingMethod: "Average", unitCost: 2, standardCost: 0 },
+ }),
+ openLayersByItem: new Map(),
+ hasAccounting: false,
+ });
+ // Cost layers are unaffected by the GL setting; only the journal is.
+ assertEquals(
+ plans.map((p) => p.cost),
+ [6, 8]
+ );
+ assertEquals(
+ plans.map((p) => p.postsJournal),
+ [false, false]
+ );
+});
+
+Deno.test("planStockRows: a Non-Inventory or zero-quantity row carries no value", () => {
+ const plans = planStockRows({
+ rows: [
+ { itemId: "A", quantity: 5, itemTrackingType: "Non-Inventory" },
+ { itemId: "A", quantity: 0, itemTrackingType: "Inventory" },
+ { itemId: "A", quantity: 2, itemTrackingType: "Inventory" },
+ ],
+ itemCosts: itemCosts({ A: fifo(3) }),
+ openLayersByItem: new Map(),
+ hasAccounting: true,
+ });
+ assertEquals(
+ plans.map((p) => p.carriesValue),
+ [false, false, true]
+ );
+ assertEquals(
+ plans.map((p) => p.cost),
+ [0, 0, 6]
+ );
+ assertEquals(
+ plans.map((p) => p.postsJournal),
+ [false, false, true]
+ );
+});
diff --git a/packages/database/supabase/functions/shared/plan-adjustment.ts b/packages/database/supabase/functions/shared/plan-adjustment.ts
new file mode 100644
index 0000000000..306aec04c7
--- /dev/null
+++ b/packages/database/supabase/functions/shared/plan-adjustment.ts
@@ -0,0 +1,366 @@
+// Pure row planning for inventory adjustment postings. No I/O, so it is
+// unit-testable with `deno test` and — more importantly — it is the SINGLE
+// copy of the arithmetic that `bookAdjustment` (one movement at a time) and
+// the bulk opening-stock importer (a whole CSV in a handful of statements)
+// both write. Neither may re-derive a cost, an account side or a dimension
+// tag on its own.
+
+import { Database } from "../lib/types.ts";
+import { credit, debit } from "../lib/utils.ts";
+import { resolveInventoryAccount } from "./get-posting-group.ts";
+import {
+ AdjustmentItemCost,
+ computeCurrentUnitCost,
+ OpenCostLayer,
+} from "./post-adjustment-cost.ts";
+import { round } from "./precision.ts";
+
+type ItemLedgerInsert = Database["public"]["Tables"]["itemLedger"]["Insert"];
+type CostLedgerInsert = Database["public"]["Tables"]["costLedger"]["Insert"];
+type JournalLineInsert = Database["public"]["Tables"]["journalLine"]["Insert"];
+type JournalLineDimensionInsert =
+ Database["public"]["Tables"]["journalLineDimension"]["Insert"];
+type ItemLedgerDocumentType =
+ Database["public"]["Enums"]["itemLedgerDocumentType"];
+type JournalLineDocumentType =
+ Database["public"]["Enums"]["journalLineDocumentType"];
+
+// itemLedgerDocumentType values that also exist on journalLineDocumentType.
+// The journal line falls back to 'Inventory Adjustment' for ledger documentType
+// values the journal enum doesn't carry (e.g. 'Sales Invoice', 'Direct
+// Transfer', 'Posted Assembly') — inserting those would fail the enum cast.
+export const JOURNAL_LINE_SAFE_DOCUMENT_TYPES: ReadonlySet<string> = new Set([
+ "Sales Shipment",
+ "Purchase Receipt",
+ "Purchase Invoice",
+ "Transfer Shipment",
+ "Job Consumption",
+ "Job Receipt",
+ "Batch Split",
+ "Maintenance Consumption",
+ "Inventory Count",
+ "Non-Conformance",
+ "Inbound Inspection",
+ "Scrap",
+]);
+
+export function toJournalLineDocumentType(
+ documentType: ItemLedgerDocumentType | null | undefined
+): JournalLineDocumentType {
+ return (
+ documentType && JOURNAL_LINE_SAFE_DOCUMENT_TYPES.has(documentType)
+ ? documentType
+ : "Inventory Adjustment"
+ ) as JournalLineDocumentType;
+}
+
+// The item ledger row for a movement — the stock movement itself, written
+// before anything that references it. `quantity` is SIGNED (positive for an
+// increase, negative for a decrease) and is the only field with arithmetic on
+// it. Every caller goes through here so a column added to the movement lands
+// on the single-record path and the bulk importer at once.
+export function buildItemLedgerRow(args: {
+ postingDate: string;
+ entryType: Database["public"]["Enums"]["itemLedgerType"];
+ documentType?: ItemLedgerDocumentType | null;
+ documentId?: string | null;
+ correctionOfItemLedgerId?: string | null;
+ itemId: string;
+ locationId: string | null;
+ storageUnitId: string | null;
+ trackedEntityId: string | null;
+ quantity: number;
+ comment?: string | null;
+ scrapReasonId?: string | null;
+ companyId: string;
+ createdBy: string;
+}): ItemLedgerInsert {
+ return {
+ postingDate: args.postingDate,
+ entryType: args.entryType,
+ documentType: args.documentType ?? null,
+ documentId: args.documentId ?? null,
+ correctionOfItemLedgerId: args.correctionOfItemLedgerId ?? null,
+ itemId: args.itemId,
+ locationId: args.locationId,
+ storageUnitId: args.storageUnitId,
+ trackedEntityId: args.trackedEntityId,
+ quantity: round(args.quantity),
+ comment: args.comment ?? null,
+ scrapReasonId: args.scrapReasonId ?? null,
+ companyId: args.companyId,
+ createdBy: args.createdBy,
+ };
+}
+
+// One cost-ledger row for a movement. `quantity` and `cost` are SIGNED —
+// negative for a decrease (the relief of carrying value), positive for an
+// increase. A decrease leaves nothing to consume later, so its layer opens
+// with remainingQuantity 0; an increase opens a layer for its full quantity.
+export function buildCostLedgerRow(args: {
+ entryType: Database["public"]["Enums"]["itemLedgerType"];
+ documentType?: ItemLedgerDocumentType | null;
+ documentId: string;
+ itemId: string;
+ quantity: number;
+ cost: number;
+ postingDate: string;
+ companyId: string;
+}): CostLedgerInsert {
+ const quantity = round(args.quantity);
+ return {
+ itemLedgerType: args.entryType,
+ costLedgerType: "Direct Cost",
+ adjustment: false,
+ documentType: args.documentType ?? null,
+ documentId: args.documentId,
+ itemId: args.itemId,
+ quantity,
+ cost: round(args.cost),
+ remainingQuantity: quantity > 0 ? quantity : 0,
+ postingDate: args.postingDate,
+ companyId: args.companyId,
+ };
+}
+
+// The balanced pair for a movement that carries value: the inventory account
+// against the offset (variance / scrap) account. `cost` and `quantity` are
+// ABSOLUTE; `isGain` picks which side each account takes.
+export function buildAdjustmentJournalLines(args: {
+ journalId: string;
+ documentId: string;
+ documentType?: ItemLedgerDocumentType | null;
+ journalLineReference: string;
+ isGain: boolean;
+ cost: number;
+ quantity: number;
+ replenishmentSystem:
+ | Database["public"]["Enums"]["itemReplenishmentSystem"]
+ | null;
+ accountDefaults: {
+ rawMaterialsAccount: string;
+ finishedGoodsAccount: string;
+ inventoryAdjustmentVarianceAccount: string;
+ };
+ offsetAccount?: string | null;
+ offsetDescription?: string;
+ companyId: string;
+}): [JournalLineInsert, JournalLineInsert] {
+ const inventoryAccount = resolveInventoryAccount(
+ args.replenishmentSystem,
+ args.accountDefaults
+ );
+ const documentType = toJournalLineDocumentType(args.documentType);
+ const quantity = round(args.quantity);
+ const shared = {
+ journalId: args.journalId,
+ quantity,
+ documentType,
+ documentId: args.documentId,
+ journalLineReference: args.journalLineReference,
+ companyId: args.companyId,
+ };
+ return [
+ {
+ ...shared,
+ accountId: inventoryAccount.account,
+ description: inventoryAccount.description,
+ amount: round(
+ args.isGain ? debit("asset", args.cost) : credit("asset", args.cost)
+ ),
+ },
+ {
+ ...shared,
+ accountId:
+ args.offsetAccount ??
+ args.accountDefaults.inventoryAdjustmentVarianceAccount,
+ description: args.offsetDescription ?? "Inventory Adjustment",
+ amount: round(
+ args.isGain ? credit("expense", args.cost) : debit("expense", args.cost)
+ ),
+ },
+ ];
+}
+
+// Dimension tags (post-shipment precedent): every line of the entry gets the
+// movement's Item / ItemPostingGroup / Location, for whichever dimensions are
+// active on the company group, plus any caller-supplied extras.
+export function buildJournalLineDimensions(args: {
+ journalLineIds: string[];
+ dimensions: Record<string, string>;
+ itemId: string;
+ itemPostingGroupId?: string | null;
+ locationId: string | null;
+ extraDimensions?: Array<{ entityType: string; valueId: string }>;
+ companyId: string;
+}): JournalLineDimensionInsert[] {
+ const dimensionValues: Array<[string, string | null | undefined]> = [
+ ["Item", args.itemId],
+ ["ItemPostingGroup", args.itemPostingGroupId],
+ ["Location", args.locationId],
+ ...(args.extraDimensions ?? []).map(
+ (d) => [d.entityType, d.valueId] as [string, string]
+ ),
+ ];
+ return args.journalLineIds.flatMap((journalLineId) =>
+ dimensionValues
+ .filter(([entityType, valueId]) => args.dimensions[entityType] && valueId)
+ .map(([entityType, valueId]) => ({
+ journalLineId,
+ dimensionId: args.dimensions[entityType],
+ valueId: valueId as string,
+ companyId: args.companyId,
+ }))
+ );
+}
+
+export interface PlannedIncrease {
+ /** The layer's unit cost, as `computeCurrentUnitCost` would return it. */
+ unitCost: number;
+ /** quantity × unitCost, unrounded — `buildCostLedgerRow` rounds it. */
+ cost: number;
+}
+
+// Successive increases for ONE item, in the order they will be written.
+//
+// Booking them one at a time re-reads the item's open cost layers before every
+// row, so row n+1 sees the layer row n just wrote. This replays that read in
+// memory from a SINGLE starting snapshot, which is what lets the caller write
+// the whole file in a few statements instead of a query per row.
+//
+// Why the replay and not one hoisted unit cost per item:
+//
+// - Standard and Average ignore the layers entirely (`computeCurrentUnitCost`
+// returns standardCost / itemCost.unitCost), so every row of an item gets
+// the same unit cost. The replay reproduces that for free.
+// - FIFO and LIFO take the remaining-quantity-weighted average of the open
+// layers. Adding a layer of quantity q at exactly that average u contributes
+// value q·u against quantity q, so the average is unchanged: (V + q·u) /
+// (R + q) = (u·R + q·u) / (R + q) = u. In EXACT arithmetic the cost is
+// therefore hoistable. It is not hoistable as written, because the layer is
+// stored as round(q·u, 5) (`buildCostLedgerRow`): row n+1 reads the rounded
+// cost back and divides by q, so the average drifts by up to half a unit of
+// the 5th decimal per row — and the drift is scaled up by the next row's
+// quantity. A 1-unit row at 1/3 stores 0.33333; a following 1000-unit row
+// then books 333.33, not 333.33333. Replaying the rounded layer keeps the
+// batch path byte-identical to the per-row path instead of "close".
+// - The fallback branch (no open layers → itemCost.unitCost) is covered by the
+// same replay: the first row opens a layer at that fallback cost, and every
+// later row averages over it.
+//
+// Rows whose quantity rounds to 0 open no layer the next row can see (the
+// open-layer query filters remainingQuantity > 0), so they are skipped here
+// exactly as the query would skip them.
+export function planIncreaseUnitCosts(
+ itemCost: AdjustmentItemCost,
+ openLayers: OpenCostLayer[],
+ quantities: number[]
+): PlannedIncrease[] {
+ const layers = [...openLayers];
+ return quantities.map((quantity) => {
+ const unitCost = computeCurrentUnitCost(itemCost, layers);
+ // Build the layer through the same builder the caller will insert with,
+ // and read the stored values back off it — the replay must see what the
+ // database would have handed the next row, not a second derivation of it.
+ // Only quantity / remainingQuantity / cost are read, so the identity
+ // fields are placeholders.
+ const row = buildCostLedgerRow({
+ entryType: "Positive Adjmt.",
+ documentType: null,
+ documentId: "",
+ itemId: "",
+ quantity,
+ cost: quantity * unitCost,
+ postingDate: "",
+ companyId: "",
+ });
+ if ((row.remainingQuantity ?? 0) > 0) {
+ // New layers carry no applied adjustment children.
+ layers.push({
+ quantity: row.quantity as number,
+ remainingQuantity: row.remainingQuantity as number,
+ cost: row.cost as number,
+ appliedChildCost: 0,
+ });
+ }
+ return { unitCost, cost: quantity * unitCost };
+ });
+}
+
+// Whether a movement carries value at all — `bookAdjustment`'s early return:
+// a Non-Inventory item or a zero-quantity movement books the ledger row alone,
+// with no cost layer and no journal.
+export function carriesAdjustmentValue(
+ quantity: number,
+ itemTrackingType: string | null
+): boolean {
+ return quantity !== 0 && itemTrackingType !== "Non-Inventory";
+}
+
+export interface StockRowPlanInput {
+ itemId: string;
+ quantity: number;
+ itemTrackingType: string | null;
+}
+
+export interface StockRowPlan {
+ /** false ⇒ ledger row only: no cost layer, no journal line. */
+ carriesValue: boolean;
+ /** The layer's cost, unrounded; 0 when the row carries no value. */
+ cost: number;
+ /** Whether this row contributes a journal line pair. */
+ postsJournal: boolean;
+}
+
+// The whole-file plan the bulk opening-stock importer writes from, one entry
+// per source row in source order.
+//
+// This is the batching itself, kept pure and away from the transaction: group
+// the valued rows by item, replay each item's cost layers once
+// (`planIncreaseUnitCosts`), scatter the per-item costs back onto the rows
+// they came from, and decide which rows post to the GL. `bookAdjustment` makes
+// the same three decisions one movement at a time; getting the scatter or the
+// journal filter wrong here is what would put a wrong cost on every row, so it
+// is a function with a test rather than a loop inside a transaction.
+export function planStockRows(args: {
+ rows: StockRowPlanInput[];
+ itemCosts: ReadonlyMap<string, AdjustmentItemCost>;
+ openLayersByItem: ReadonlyMap<string, OpenCostLayer[]>;
+ /** false ⇒ accounting disabled: no journal at all. */
+ hasAccounting: boolean;
+}): StockRowPlan[] {
+ const plans: StockRowPlan[] = args.rows.map((row) => ({
+ carriesValue: carriesAdjustmentValue(row.quantity, row.itemTrackingType),
+ cost: 0,
+ postsJournal: false,
+ }));
+
+ const rowIndexesByItem = new Map<string, number[]>();
+ args.rows.forEach((row, rowIndex) => {
+ if (!plans[rowIndex].carriesValue) return;
+ const indexes = rowIndexesByItem.get(row.itemId) ?? [];
+ indexes.push(rowIndex);
+ rowIndexesByItem.set(row.itemId, indexes);
+ });
+
+ for (const [itemId, rowIndexes] of rowIndexesByItem) {
+ const itemCost = args.itemCosts.get(itemId);
+ if (!itemCost) {
+ throw new Error(`No item cost for item ${itemId}`);
+ }
+ const increases = planIncreaseUnitCosts(
+ itemCost,
+ args.openLayersByItem.get(itemId) ?? [],
+ rowIndexes.map((rowIndex) => args.rows[rowIndex].quantity)
+ );
+ rowIndexes.forEach((rowIndex, n) => {
+ const cost = increases[n].cost;
+ plans[rowIndex].cost = cost;
+ // A zero-value movement posts no journal — `bookAdjustment`'s
+ // `!accounting || cost === 0` guard, per row.
+ plans[rowIndex].postsJournal = args.hasAccounting && cost !== 0;
+ });
+ }
+
+ return plans;
+}
diff --git a/packages/database/supabase/functions/shared/post-adjustment.ts b/packages/database/supabase/functions/shared/post-adjustment.ts
index 4801de6537..e6666c433b 100644
--- a/packages/database/supabase/functions/shared/post-adjustment.ts
+++ b/packages/database/supabase/functions/shared/post-adjustment.ts
@@ -2,15 +2,19 @@ import { nanoid } from "https://deno.land/x/[email protected]/mod.ts";
import { Transaction } from "kysely";
import { DB } from "../lib/database.ts";
import { Database } from "../lib/types.ts";
-import { credit, debit } from "../lib/utils.ts";
import { calculateCOGS } from "./calculate-cogs.ts";
import { getNextSequence } from "./get-next-sequence.ts";
-import { resolveInventoryAccount } from "./get-posting-group.ts";
+import {
+ buildAdjustmentJournalLines,
+ buildCostLedgerRow,
+ buildItemLedgerRow,
+ buildJournalLineDimensions,
+} from "./plan-adjustment.ts";
import {
AdjustmentItemCost,
computeCurrentUnitCost,
+ OpenCostLayer,
} from "./post-adjustment-cost.ts";
-import { round } from "./precision.ts";
export { computeCurrentUnitCost } from "./post-adjustment-cost.ts";
export type {
@@ -101,25 +105,6 @@ export interface BookAdjustmentArgs {
fixedUnitCost?: number;
}
-// itemLedgerDocumentType values that also exist on journalLineDocumentType.
-// The journal line falls back to 'Inventory Adjustment' for ledger documentType
-// values the journal enum doesn't carry (e.g. 'Sales Invoice', 'Direct
-// Transfer', 'Posted Assembly') — inserting those would fail the enum cast.
-const JOURNAL_LINE_SAFE_DOCUMENT_TYPES: ReadonlySet<string> = new Set([
- "Sales Shipment",
- "Purchase Receipt",
- "Purchase Invoice",
- "Transfer Shipment",
- "Job Consumption",
- "Job Receipt",
- "Batch Split",
- "Maintenance Consumption",
- "Inventory Count",
- "Non-Conformance",
- "Inbound Inspection",
- "Scrap",
-]);
-
export interface BookAdjustmentResult {
itemLedgerId: string;
journalId: string | null;
@@ -166,6 +151,82 @@ export async function createAdjustmentJournal(
return journal.id;
}
+// The open cost layers an INCREASE values itself against, per item. Same
+// filters as calculateCOGS so both sides of the math agree: positive
+// remaining quantity, not an adjustment child, and not a 'Purchase Order'
+// planning artifact. Applied adjustment children (invoice-vs-receipt price
+// corrections) are folded into each layer's `appliedChildCost`.
+//
+// Takes a LIST of items so the bulk importer reads every item it is about to
+// post in a couple of queries instead of two per row. `bookAdjustment` passes
+// one.
+const CHILD_LAYER_CHUNK_SIZE = 500;
+
+export async function loadOpenCostLayers(
+ trx: Transaction<DB>,
+ args: { itemIds: string[]; companyId: string }
+): Promise<Map<string, OpenCostLayer[]>> {
+ const byItem = new Map<string, OpenCostLayer[]>();
+ if (args.itemIds.length === 0) return byItem;
+
+ const openLayers = await trx
+ .selectFrom("costLedger")
+ .select(["id", "itemId", "quantity", "remainingQuantity", "cost"])
+ .where("itemId", "in", args.itemIds)
+ .where("companyId", "=", args.companyId)
+ .where("remainingQuantity", ">", 0)
+ .where("adjustment", "=", false)
+ .where("appliesToCostLedgerId", "is", null)
+ .where((eb) =>
+ eb.or([
+ eb("documentType", "is", null),
+ eb("documentType", "!=", "Purchase Order"),
+ ])
+ )
+ .execute();
+ if (openLayers.length === 0) return byItem;
+
+ // The child lookup is chunked over the LAYER ids, not the item ids: open
+ // layers are receipts not yet consumed, so their count is data-dependent and
+ // unbounded. The bulk importer reaches here with every referenced item's
+ // layers at once, and a single `in (...)` over them would exceed Postgres'
+ // 65535 bind parameters on a large file against well-stocked items.
+ const appliedChildCostByLayer = new Map<string, number>();
+ const layerIds = openLayers.map((layer) => layer.id);
+ for (let i = 0; i < layerIds.length; i += CHILD_LAYER_CHUNK_SIZE) {
+ const children = await trx
+ .selectFrom("costLedger")
+ .select(["appliesToCostLedgerId", "cost"])
+ .where(
+ "appliesToCostLedgerId",
+ "in",
+ layerIds.slice(i, i + CHILD_LAYER_CHUNK_SIZE)
+ )
+ .where("companyId", "=", args.companyId)
+ .execute();
+ for (const child of children) {
+ const key = child.appliesToCostLedgerId as string;
+ appliedChildCostByLayer.set(
+ key,
+ (appliedChildCostByLayer.get(key) ?? 0) + Number(child.cost)
+ );
+ }
+ }
+
+ for (const layer of openLayers) {
+ const itemId = layer.itemId as string;
+ const list = byItem.get(itemId) ?? [];
+ list.push({
+ quantity: Number(layer.quantity),
+ remainingQuantity: Number(layer.remainingQuantity),
+ cost: Number(layer.cost),
+ appliedChildCost: appliedChildCostByLayer.get(layer.id) ?? 0,
+ });
+ byItem.set(itemId, list);
+ }
+ return byItem;
+}
+
// Book one adjustment movement inside the caller's transaction: the item
// ledger row, cost-layer maintenance (consume via calculateCOGS on decreases,
// create a layer at current cost on increases), and — when accounting is
@@ -181,22 +242,24 @@ export async function bookAdjustment(
const inserted = await trx
.insertInto("itemLedger")
- .values({
- postingDate: ledger.postingDate,
- entryType: ledger.entryType,
- documentType: ledger.documentType ?? null,
- documentId: ledger.documentId ?? null,
- correctionOfItemLedgerId: ledger.correctionOfItemLedgerId ?? null,
- itemId: ledger.itemId,
- locationId: ledger.locationId,
- storageUnitId: ledger.storageUnitId,
- trackedEntityId: ledger.trackedEntityId,
- quantity: round(ledger.quantity),
- comment: ledger.comment ?? null,
- scrapReasonId: ledger.scrapReasonId ?? null,
- companyId,
- createdBy: ledger.createdBy,
- })
+ .values(
+ buildItemLedgerRow({
+ postingDate: ledger.postingDate,
+ entryType: ledger.entryType,
+ documentType: ledger.documentType,
+ documentId: ledger.documentId,
+ correctionOfItemLedgerId: ledger.correctionOfItemLedgerId,
+ itemId: ledger.itemId,
+ locationId: ledger.locationId,
+ storageUnitId: ledger.storageUnitId,
+ trackedEntityId: ledger.trackedEntityId,
+ quantity: ledger.quantity,
+ comment: ledger.comment,
+ scrapReasonId: ledger.scrapReasonId,
+ companyId,
+ createdBy: ledger.createdBy,
+ })
+ )
.returning(["id"])
.executeTakeFirstOrThrow();
@@ -224,19 +287,18 @@ export async function bookAdjustment(
await trx
.insertInto("costLedger")
- .values({
- itemLedgerType: ledger.entryType,
- costLedgerType: "Direct Cost",
- adjustment: false,
- documentType: ledger.documentType ?? null,
- documentId,
- itemId: ledger.itemId,
- quantity: round(-absQuantity),
- cost: round(-cogs.totalCost),
- remainingQuantity: 0,
- postingDate: ledger.postingDate,
- companyId,
- })
+ .values(
+ buildCostLedgerRow({
+ entryType: ledger.entryType,
+ documentType: ledger.documentType,
+ documentId,
+ itemId: ledger.itemId,
+ quantity: -absQuantity,
+ cost: -cogs.totalCost,
+ postingDate: ledger.postingDate,
+ companyId,
+ })
+ )
.execute();
} else if (args.fixedUnitCost != null) {
// Increase at a caller-fixed unit cost: Unscrap restores stock at the
@@ -245,86 +307,45 @@ export async function bookAdjustment(
await trx
.insertInto("costLedger")
- .values({
- itemLedgerType: ledger.entryType,
- costLedgerType: "Direct Cost",
- adjustment: false,
- documentType: ledger.documentType ?? null,
- documentId,
- itemId: ledger.itemId,
- quantity: round(absQuantity),
- cost: round(cost),
- remainingQuantity: round(absQuantity),
- postingDate: ledger.postingDate,
- companyId,
- })
- .execute();
- } else {
- // Increase: create a layer at the item's current carrying cost. Same
- // open-layer filters as calculateCOGS so both sides of the math agree.
- const openLayers = await trx
- .selectFrom("costLedger")
- .select(["id", "quantity", "remainingQuantity", "cost"])
- .where("itemId", "=", ledger.itemId)
- .where("companyId", "=", companyId)
- .where("remainingQuantity", ">", 0)
- .where("adjustment", "=", false)
- .where("appliesToCostLedgerId", "is", null)
- .where((eb) =>
- eb.or([
- eb("documentType", "is", null),
- eb("documentType", "!=", "Purchase Order"),
- ])
+ .values(
+ buildCostLedgerRow({
+ entryType: ledger.entryType,
+ documentType: ledger.documentType,
+ documentId,
+ itemId: ledger.itemId,
+ quantity: absQuantity,
+ cost,
+ postingDate: ledger.postingDate,
+ companyId,
+ })
)
.execute();
-
- const appliedChildCostByLayer = new Map<string, number>();
- if (openLayers.length > 0) {
- const children = await trx
- .selectFrom("costLedger")
- .select(["appliesToCostLedgerId", "cost"])
- .where(
- "appliesToCostLedgerId",
- "in",
- openLayers.map((layer) => layer.id)
- )
- .where("companyId", "=", companyId)
- .execute();
- for (const child of children) {
- const key = child.appliesToCostLedgerId as string;
- appliedChildCostByLayer.set(
- key,
- (appliedChildCostByLayer.get(key) ?? 0) + Number(child.cost)
- );
- }
- }
-
+ } else {
+ // Increase: create a layer at the item's current carrying cost.
+ const openLayers = await loadOpenCostLayers(trx, {
+ itemIds: [ledger.itemId],
+ companyId,
+ });
const unitCost = computeCurrentUnitCost(
itemCost,
- openLayers.map((layer) => ({
- quantity: Number(layer.quantity),
- remainingQuantity: Number(layer.remainingQuantity),
- cost: Number(layer.cost),
- appliedChildCost: appliedChildCostByLayer.get(layer.id) ?? 0,
- }))
+ openLayers.get(ledger.itemId) ?? []
);
cost = absQuantity * unitCost;
await trx
.insertInto("costLedger")
- .values({
- itemLedgerType: ledger.entryType,
- costLedgerType: "Direct Cost",
- adjustment: false,
- documentType: ledger.documentType ?? null,
- documentId,
- itemId: ledger.itemId,
- quantity: round(absQuantity),
- cost: round(cost),
- remainingQuantity: round(absQuantity),
- postingDate: ledger.postingDate,
- companyId,
- })
+ .values(
+ buildCostLedgerRow({
+ entryType: ledger.entryType,
+ documentType: ledger.documentType,
+ documentId,
+ itemId: ledger.itemId,
+ quantity: absQuantity,
+ cost,
+ postingDate: ledger.postingDate,
+ companyId,
+ })
+ )
.execute();
}
@@ -345,72 +366,36 @@ export async function bookAdjustment(
sourceType: accounting.sourceType,
});
- const inventoryAccount = resolveInventoryAccount(
- item.replenishmentSystem,
- accounting.accountDefaults
- );
- const journalLineReference = nanoid();
- const journalLineDocumentType = (
- ledger.documentType &&
- JOURNAL_LINE_SAFE_DOCUMENT_TYPES.has(ledger.documentType)
- ? ledger.documentType
- : "Inventory Adjustment"
- ) as Database["public"]["Enums"]["journalLineDocumentType"];
- const isGain = ledger.quantity > 0;
-
const journalLines = await trx
.insertInto("journalLine")
- .values([
- {
- journalId,
- accountId: inventoryAccount.account,
- description: inventoryAccount.description,
- amount: round(isGain ? debit("asset", cost) : credit("asset", cost)),
- quantity: round(absQuantity),
- documentType: journalLineDocumentType,
- documentId,
- journalLineReference,
- companyId,
- },
- {
+ .values(
+ buildAdjustmentJournalLines({
journalId,
- accountId:
- accounting.offsetAccount ??
- accounting.accountDefaults.inventoryAdjustmentVarianceAccount,
- description: accounting.offsetDescription ?? "Inventory Adjustment",
- amount: round(isGain ? credit("expense", cost) : debit("expense", cost)),
- quantity: round(absQuantity),
- documentType: journalLineDocumentType,
documentId,
- journalLineReference,
+ documentType: ledger.documentType,
+ journalLineReference: nanoid(),
+ isGain: ledger.quantity > 0,
+ cost,
+ quantity: absQuantity,
+ replenishmentSystem: item.replenishmentSystem,
+ accountDefaults: accounting.accountDefaults,
+ offsetAccount: accounting.offsetAccount,
+ offsetDescription: accounting.offsetDescription,
companyId,
- },
- ])
+ })
+ )
.returning(["id"])
.execute();
- // Dimension tags (post-shipment precedent): every line of the entry gets
- // the movement's Item / ItemPostingGroup / Location, for whichever
- // dimensions are active on the company group.
- const dimensions = accounting.dimensions ?? {};
- const dimensionValues: Array<[string, string | null | undefined]> = [
- ["Item", ledger.itemId],
- ["ItemPostingGroup", item.itemPostingGroupId],
- ["Location", ledger.locationId],
- ...(accounting.extraDimensions ?? []).map(
- (d) => [d.entityType, d.valueId] as [string, string]
- ),
- ];
- const journalLineDimensionInserts = journalLines.flatMap((line) =>
- dimensionValues
- .filter(([entityType, valueId]) => dimensions[entityType] && valueId)
- .map(([entityType, valueId]) => ({
- journalLineId: line.id,
- dimensionId: dimensions[entityType],
- valueId: valueId as string,
- companyId,
- }))
- );
+ const journalLineDimensionInserts = buildJournalLineDimensions({
+ journalLineIds: journalLines.map((line) => line.id),
+ dimensions: accounting.dimensions ?? {},
+ itemId: ledger.itemId,
+ itemPostingGroupId: item.itemPostingGroupId,
+ locationId: ledger.locationId,
+ extraDimensions: accounting.extraDimensions,
+ companyId,
+ });
if (journalLineDimensionInserts.length > 0) {
await trx
.insertInto("journalLineDimension")
diff --git a/packages/locale/locales/de/erp.po b/packages/locale/locales/de/erp.po
index 9fbedde1d9..7a731cd361 100644
--- a/packages/locale/locales/de/erp.po
+++ b/packages/locale/locales/de/erp.po
@@ -2976,6 +2976,9 @@ msgstr "Chargennummer"
msgid "Batch Properties"
msgstr "Batch-Eigenschaften"
+msgid "Batch Quantities"
+msgstr "Losmengen"
+
msgid "Batch Size"
msgstr "Chargengröße"
@@ -9054,6 +9057,9 @@ msgstr "Bestandsbewegungen"
msgid "Inventory Qty"
msgstr "Bestandsmenge"
+msgid "Inventory Quantities"
+msgstr "Bestandsmengen"
+
msgid "Inventory Tracking"
msgstr "Bestandsverfolgung"
@@ -15655,6 +15661,9 @@ msgstr "Seriennummern zur Rückgabe"
msgid "Serial or Batch Tracking Required"
msgstr "Serien- oder Chargenverfolgung erforderlich"
+msgid "Serial Quantities"
+msgstr "Serienmengen"
+
msgid "Serial tracking"
msgstr "Seriennummernverfolgung"
diff --git a/packages/locale/locales/en/erp.po b/packages/locale/locales/en/erp.po
index 38dff3d42d..b50b52ad35 100644
--- a/packages/locale/locales/en/erp.po
+++ b/packages/locale/locales/en/erp.po
@@ -2976,6 +2976,9 @@ msgstr "Batch Number"
msgid "Batch Properties"
msgstr "Batch Properties"
+msgid "Batch Quantities"
+msgstr "Batch Quantities"
+
msgid "Batch Size"
msgstr "Batch Size"
@@ -9054,6 +9057,9 @@ msgstr "Inventory Movements"
msgid "Inventory Qty"
msgstr "Inventory Qty"
+msgid "Inventory Quantities"
+msgstr "Inventory Quantities"
+
msgid "Inventory Tracking"
msgstr "Inventory Tracking"
@@ -15655,6 +15661,9 @@ msgstr "Serial numbers to return"
msgid "Serial or Batch Tracking Required"
msgstr "Serial or Batch Tracking Required"
+msgid "Serial Quantities"
+msgstr "Serial Quantities"
+
msgid "Serial tracking"
msgstr "Serial tracking"
diff --git a/packages/locale/locales/es/erp.po b/packages/locale/locales/es/erp.po
index 72817595df..4773478ec5 100644
--- a/packages/locale/locales/es/erp.po
+++ b/packages/locale/locales/es/erp.po
@@ -2976,6 +2976,9 @@ msgstr "Número de Lote"
msgid "Batch Properties"
msgstr "Propiedades de Lote"
+msgid "Batch Quantities"
+msgstr "Cantidades de Lote de Producción"
+
msgid "Batch Size"
msgstr "Tamaño de Lote"
@@ -9054,6 +9057,9 @@ msgstr "Movimientos de Inventario"
msgid "Inventory Qty"
msgstr "Cantidad de Inventario"
+msgid "Inventory Quantities"
+msgstr "Cantidades del Inventario"
+
msgid "Inventory Tracking"
msgstr "Seguimiento de Inventario"
@@ -15655,6 +15661,9 @@ msgstr "Números de serie a devolver"
msgid "Serial or Batch Tracking Required"
msgstr "Seguimiento Serial o por Lote Requerido"
+msgid "Serial Quantities"
+msgstr "Cantidades de Serie"
+
msgid "Serial tracking"
msgstr "Seguimiento de números de serie"
diff --git a/packages/locale/locales/fr/erp.po b/packages/locale/locales/fr/erp.po
index aca637d9fb..41308d23e1 100644
--- a/packages/locale/locales/fr/erp.po
+++ b/packages/locale/locales/fr/erp.po
@@ -2976,6 +2976,9 @@ msgstr "Numéro de lot"
msgid "Batch Properties"
msgstr "Propriétés de lot"
+msgid "Batch Quantities"
+msgstr "Quantités de lot de production"
+
msgid "Batch Size"
msgstr "Taille de lot"
@@ -9054,6 +9057,9 @@ msgstr "Mouvements d'inventaire"
msgid "Inventory Qty"
msgstr "Quantité Inventaire"
+msgid "Inventory Quantities"
+msgstr "Quantités des stocks"
+
msgid "Inventory Tracking"
msgstr "Suivi des stocks"
@@ -15655,6 +15661,9 @@ msgstr "Numéros de série à retourner"
msgid "Serial or Batch Tracking Required"
msgstr "Suivi en série ou par lot requis"
+msgid "Serial Quantities"
+msgstr "Quantités de série"
+
msgid "Serial tracking"
msgstr "Suivi des numéros de série"
diff --git a/packages/locale/locales/hi/erp.po b/packages/locale/locales/hi/erp.po
index 907424f05d..20c3e5a912 100644
--- a/packages/locale/locales/hi/erp.po
+++ b/packages/locale/locales/hi/erp.po
@@ -2976,6 +2976,9 @@ msgstr "बैच नंबर"
msgid "Batch Properties"
msgstr "बैच प्रॉपर्टीज़"
+msgid "Batch Quantities"
+msgstr "बैच मात्राएं"
+
msgid "Batch Size"
msgstr "बैच आकार"
@@ -9054,6 +9057,9 @@ msgstr "इन्वेंटरी मूवमेंट्स"
msgid "Inventory Qty"
msgstr "इन्वेंटरी मात्रा"
+msgid "Inventory Quantities"
+msgstr "इन्वेंटरी मात्राएं"
+
msgid "Inventory Tracking"
msgstr "इन्वेंटरी ट्रैकिंग"
@@ -15655,6 +15661,9 @@ msgstr "रिटर्न के लिए सीरियल नंबर"
msgid "Serial or Batch Tracking Required"
msgstr "सीरियल या बैच ट्रैकिंग आवश्यक है"
+msgid "Serial Quantities"
+msgstr "क्रमांक मात्राएं"
+
msgid "Serial tracking"
msgstr "सीरियल ट्रैकिंग"
diff --git a/packages/locale/locales/it/erp.po b/packages/locale/locales/it/erp.po
index ee6aefd219..70dae46aa4 100644
--- a/packages/locale/locales/it/erp.po
+++ b/packages/locale/locales/it/erp.po
@@ -2976,6 +2976,9 @@ msgstr "Numero Lotto"
msgid "Batch Properties"
msgstr "Proprietà Batch"
+msgid "Batch Quantities"
+msgstr "Quantità lotto di produzione"
+
msgid "Batch Size"
msgstr "Dimensione lotto"
@@ -9054,6 +9057,9 @@ msgstr "Movimenti di magazzino"
msgid "Inventory Qty"
msgstr "Quantità Inventario"
+msgid "Inventory Quantities"
+msgstr "Quantità magazzino"
+
msgid "Inventory Tracking"
msgstr "Tracciamento Inventario"
@@ -15655,6 +15661,9 @@ msgstr "Numeri di serie da restituire"
msgid "Serial or Batch Tracking Required"
msgstr "Tracciamento Seriale o Batch Richiesto"
+msgid "Serial Quantities"
+msgstr "Quantità seriali"
+
msgid "Serial tracking"
msgstr "Tracciamento dei numeri di serie"
diff --git a/packages/locale/locales/ja/erp.po b/packages/locale/locales/ja/erp.po
index 46ebfb1340..17a5038ac2 100644
--- a/packages/locale/locales/ja/erp.po
+++ b/packages/locale/locales/ja/erp.po
@@ -2976,6 +2976,9 @@ msgstr "バッチ番号"
msgid "Batch Properties"
msgstr "バッチプロパティ"
+msgid "Batch Quantities"
+msgstr "バッチ数量"
+
msgid "Batch Size"
msgstr "バッチサイズ"
@@ -9054,6 +9057,9 @@ msgstr "在庫移動"
msgid "Inventory Qty"
msgstr "在庫数量"
+msgid "Inventory Quantities"
+msgstr "在庫数量"
+
msgid "Inventory Tracking"
msgstr "在庫追跡"
@@ -15655,6 +15661,9 @@ msgstr "返品するシリアル番号"
msgid "Serial or Batch Tracking Required"
msgstr "シリアルまたはバッチ追跡が必要です"
+msgid "Serial Quantities"
+msgstr "シリアル数量"
+
msgid "Serial tracking"
msgstr "シリアルトラッキング"
diff --git a/packages/locale/locales/ko/erp.po b/packages/locale/locales/ko/erp.po
index 4655fac2f8..0c7805e9aa 100644
--- a/packages/locale/locales/ko/erp.po
+++ b/packages/locale/locales/ko/erp.po
@@ -2976,6 +2976,9 @@ msgstr "배치 번호"
msgid "Batch Properties"
msgstr "배치 속성"
+msgid "Batch Quantities"
+msgstr "배치 수량"
+
msgid "Batch Size"
msgstr "배치 크기"
@@ -9054,6 +9057,9 @@ msgstr "재고 이동"
msgid "Inventory Qty"
msgstr "재고 수량"
+msgid "Inventory Quantities"
+msgstr "재고 수량"
+
msgid "Inventory Tracking"
msgstr "재고 추적"
@@ -15655,6 +15661,9 @@ msgstr "반품할 시리얼 번호"
msgid "Serial or Batch Tracking Required"
msgstr "일련번호 또는 배치 추적 필요"
+msgid "Serial Quantities"
+msgstr "일련번호 수량"
+
msgid "Serial tracking"
msgstr "일련번호 추적"
diff --git a/packages/locale/locales/pl/erp.po b/packages/locale/locales/pl/erp.po
index cc8729288d..161c9233e1 100644
--- a/packages/locale/locales/pl/erp.po
+++ b/packages/locale/locales/pl/erp.po
@@ -2976,6 +2976,9 @@ msgstr "Numer partii"
msgid "Batch Properties"
msgstr "Właściwości partii"
+msgid "Batch Quantities"
+msgstr "Ilości partii produkcyjnych"
+
msgid "Batch Size"
msgstr "Rozmiar partii"
@@ -9054,6 +9057,9 @@ msgstr "Ruchy Magazynowe"
msgid "Inventory Qty"
msgstr "Ilość w magazynie"
+msgid "Inventory Quantities"
+msgstr "Ilości zapasów"
+
msgid "Inventory Tracking"
msgstr "Śledzenie zapasów"
@@ -15655,6 +15661,9 @@ msgstr "Numery seryjne do zwrotu"
msgid "Serial or Batch Tracking Required"
msgstr "Wymagane śledzenie seryjne lub partyjne"
+msgid "Serial Quantities"
+msgstr "Ilości seryjne"
+
msgid "Serial tracking"
msgstr "Śledzenie numerów seryjnych"
diff --git a/packages/locale/locales/pt/erp.po b/packages/locale/locales/pt/erp.po
index d635a8b1eb..0be3207991 100644
--- a/packages/locale/locales/pt/erp.po
+++ b/packages/locale/locales/pt/erp.po
@@ -2976,6 +2976,9 @@ msgstr "Número do Lote"
msgid "Batch Properties"
msgstr "Propriedades em Lote"
+msgid "Batch Quantities"
+msgstr "Quantidades de Lotes de Produção"
+
msgid "Batch Size"
msgstr "Tamanho do Lote"
@@ -9054,6 +9057,9 @@ msgstr "Movimentações de Inventário"
msgid "Inventory Qty"
msgstr "Qtd. Inventário"
+msgid "Inventory Quantities"
+msgstr "Quantidades de Inventário"
+
msgid "Inventory Tracking"
msgstr "Rastreamento de Inventário"
@@ -15655,6 +15661,9 @@ msgstr "Números de série para devolver"
msgid "Serial or Batch Tracking Required"
msgstr "Rastreamento Serial ou em Lote Obrigatório"
+msgid "Serial Quantities"
+msgstr "Quantidades de Série"
+
msgid "Serial tracking"
msgstr "Rastreamento de série"
diff --git a/packages/locale/locales/ru/erp.po b/packages/locale/locales/ru/erp.po
index 1bb2a77782..a9a87cf8a0 100644
--- a/packages/locale/locales/ru/erp.po
+++ b/packages/locale/locales/ru/erp.po
@@ -2976,6 +2976,9 @@ msgstr "Номер партии"
msgid "Batch Properties"
msgstr "Свойства партии"
+msgid "Batch Quantities"
+msgstr "Количество по сериям"
+
msgid "Batch Size"
msgstr "Размер партии"
@@ -9054,6 +9057,9 @@ msgstr "Движения по товарно-материальным ценно
msgid "Inventory Qty"
msgstr "Кол-во в инвентаре"
+msgid "Inventory Quantities"
+msgstr "Количество в запасах"
+
msgid "Inventory Tracking"
msgstr "Отслеживание запасов"
@@ -15655,6 +15661,9 @@ msgstr "Серийные номера для возврата"
msgid "Serial or Batch Tracking Required"
msgstr "Требуется отслеживание по серийному номеру или партии"
+msgid "Serial Quantities"
+msgstr "Количество по серийным номерам"
+
msgid "Serial tracking"
msgstr "Отслеживание серийных номеров"
diff --git a/packages/locale/locales/tr/erp.po b/packages/locale/locales/tr/erp.po
index f883964e3f..350bf3505f 100644
--- a/packages/locale/locales/tr/erp.po
+++ b/packages/locale/locales/tr/erp.po
@@ -2976,6 +2976,9 @@ msgstr "Lot Numarası"
msgid "Batch Properties"
msgstr "Toplu Özellikler"
+msgid "Batch Quantities"
+msgstr "Parti Miktarları"
+
msgid "Batch Size"
msgstr "Lot Boyutu"
@@ -9054,6 +9057,9 @@ msgstr "Envanter Hareketleri"
msgid "Inventory Qty"
msgstr "Stok Miktarı"
+msgid "Inventory Quantities"
+msgstr "Envanter Miktarları"
+
msgid "Inventory Tracking"
msgstr "Stok Takibi"
@@ -15655,6 +15661,9 @@ msgstr "İade edilecek seri numaraları"
msgid "Serial or Batch Tracking Required"
msgstr "Seri veya Parti Takibi Gerekli"
+msgid "Serial Quantities"
+msgstr "Seri Miktarları"
+
msgid "Serial tracking"
msgstr "Seri numarası takibi"
diff --git a/packages/locale/locales/zh/erp.po b/packages/locale/locales/zh/erp.po
index 48bb234c7c..1590741163 100644
--- a/packages/locale/locales/zh/erp.po
+++ b/packages/locale/locales/zh/erp.po
@@ -2976,6 +2976,9 @@ msgstr "批号"
msgid "Batch Properties"
msgstr "批量属性"
+msgid "Batch Quantities"
+msgstr "生产批次数量"
+
msgid "Batch Size"
msgstr "批量大小"
@@ -9054,6 +9057,9 @@ msgstr "库存移动"
msgid "Inventory Qty"
msgstr "库存数量"
+msgid "Inventory Quantities"
+msgstr "库存数量"
+
msgid "Inventory Tracking"
msgstr "库存跟踪"
@@ -15655,6 +15661,9 @@ msgstr "要退货的序列号"
msgid "Serial or Batch Tracking Required"
msgstr "序列号或批次跟踪必需"
+msgid "Serial Quantities"
+msgstr "序列号数量"
+
msgid "Serial tracking"
msgstr "序列号追踪"