Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
feat(inventory): flat correction rows, auto from-to comments
Sidwebworks2b1ef4bcedee
diff --git a/.claude/rules/inventory-system.md b/.claude/rules/inventory-system.mdindex d4f2683312..a1a549a306 100644--- a/.claude/rules/inventory-system.md+++ b/.claude/rules/inventory-system.md@@ -44,7 +44,9 @@ Key service functions (verified):`correctedQuantity − effective` (effective = root + all prior corrections in the group),so repeat corrections converge. `documentType`/`documentId` are copied from the originalso document-scoped movement views keep including the fix. Entry point: "Correct Quantity"- context action on `StockMovementsTable` → `stock-movements/$ledgerId/correct` route.+ context action on `StockMovementsTable` → `stock-movements/$ledgerId/correct` route (whose+ loader returns the authoritative effective quantity for the modal pre-fill). Corrections+ render as normal flat rows with an `isCorrection` badge — no nesting/expandable grouping.Inventory counts have NO count-level rectify; Posted is terminal.- Storage units: `getStorageUnit(s)`, `getStorageUnitRoots`, `getStorageUnitChildren`,`getStorageUnitTree`, `getStorageUnitsTreeForLocation`, `getDefaultStorageUnitForJob`,diff --git a/apps/erp/app/modules/agent/kb/docs/reference/inventory.md b/apps/erp/app/modules/agent/kb/docs/reference/inventory.mdindex bf4df7c2bb..ecdaa03ad0 100644--- a/apps/erp/app/modules/agent/kb/docs/reference/inventory.md+++ b/apps/erp/app/modules/agent/kb/docs/reference/inventory.md@@ -29,7 +29,7 @@ Two kinds of transfer move stock. A **warehouse transfer** moves it between loca## Correcting a movement-The ledger is append-only — a posted movement is never edited or deleted. To fix one, use **"Correct Quantity"** on the movement in the Stock Movements screen and enter the quantity it should have been. Carbon books one **opposite movement for the difference**, linked to the original and dated with the original's posting date, so both sit in the right time period and the correction nests under the original in the list. The journal for the correction posts into the original's accounting period. A **locked** period refuses the correction until it's unlocked; a **closed** period is permanent — once a movement's period has closed, it can no longer be corrected. Correcting the same movement again measures against what it currently nets to, so repeated corrections converge instead of stacking.+The ledger is append-only — a posted movement is never edited or deleted. To fix one, use **"Correct Quantity"** on the movement in the Stock Movements screen and enter the quantity it should have been. Carbon books one **opposite movement for the difference**, linked to the original and dated with the original's posting date, so both sit in the right time period. The correction appears as its own row, flagged with a **Correction** badge that links it back to the movement it fixes. The journal for the correction posts into the original's accounting period. A **locked** period refuses the correction until it's unlocked; a **closed** period is permanent — once a movement's period has closed, it can no longer be corrected. Correcting the same movement again measures against what it currently nets to, so repeated corrections converge instead of stacking.## Valuediff --git a/apps/erp/app/modules/inventory/ui/StockMovements/StockMovementsTable.tsx b/apps/erp/app/modules/inventory/ui/StockMovements/StockMovementsTable.tsxindex ba10f34c28..fc63ac49ba 100644--- a/apps/erp/app/modules/inventory/ui/StockMovements/StockMovementsTable.tsx+++ b/apps/erp/app/modules/inventory/ui/StockMovements/StockMovementsTable.tsx@@ -6,10 +6,10 @@ import {LuArrowRightLeft,LuBlocks,LuCalendar,- LuCornerDownRight,LuFileText,LuHash,LuMapPin,+ LuMessageSquare,LuMoveDown,LuMoveUp,LuQrCode,@@ -201,6 +201,18 @@ const StockMovementsTable = memo(icon: <LuQrCode />}},+ {+ accessorKey: "comment",+ header: t`Comment`,+ cell: ({ row }) => (+ <span className="truncate text-muted-foreground">+ {row.original.comment ?? ""}+ </span>+ ),+ meta: {+ icon: <LuMessageSquare />+ }+ },{accessorKey: "postingDate",header: t`Posting Date`,@@ -237,63 +249,6 @@ const StockMovementsTable = memo(];}, [people, locations, locationsById, t, formatDate]);- // Group corrections under the movement they fix. Corrections whose original- // is on this page are hidden from the flat list and revealed by expanding the- // original (chevron), like the accounting/audit-log expandable rows. A- // correction whose original isn't on the page stays inline (still badged).- const { displayData, correctionsByOriginal } = useMemo(() => {- const byId = new Map(data.map((m) => [m.id, m]));-- // Walk a correction up its `correctionOfItemLedgerId` chain to the topmost- // ancestor present on this page. Historical corrections can chain (a fix- // of a fix links to the prior correction, not the original), so we must- // resolve to the ULTIMATE root — otherwise a grandchild correction would- // be hidden but never re-shown under any visible row.- const rootOf = (m: StockMovement) => {- let cur = m;- const seen = new Set<string>();- while (- cur.correctionOfItemLedgerId &&- byId.has(cur.correctionOfItemLedgerId) &&- cur.id &&- !seen.has(cur.id)- ) {- seen.add(cur.id);- cur = byId.get(cur.correctionOfItemLedgerId) as StockMovement;- }- return cur;- };-- const byOriginal = new Map<string, StockMovement[]>();- const nestedIds = new Set<string>();- for (const m of data) {- if (!m.correctionOfItemLedgerId) continue;- const root = rootOf(m);- // No on-page ancestor (root resolves back to itself) → leave inline.- if (!root.id || root.id === m.id) continue;- const list = byOriginal.get(root.id) ?? [];- list.push(m);- byOriginal.set(root.id, list);- if (m.id) nestedIds.add(m.id);- }- // Order each group oldest-first so a chain reads original → fix → fix.- for (const list of byOriginal.values()) {- list.sort((a, b) => (a.entryNumber ?? 0) - (b.entryNumber ?? 0));- }- return {- correctionsByOriginal: byOriginal,- displayData:- nestedIds.size === 0- ? data- : data.filter((m) => !(m.id && nestedIds.has(m.id)))- };- }, [data]);-- const canExpandRow = useCallback(- (row: StockMovement) => !!row.id && correctionsByOriginal.has(row.id),- [correctionsByOriginal]- );-const renderContextMenu = useCallback((row: StockMovement) => (<MenuItem@@ -307,56 +262,16 @@ const StockMovementsTable = memo([permissions, t]);- const renderExpandedRow = useCallback(- (row: StockMovement) => {- const corrections = row.id- ? correctionsByOriginal.get(row.id)- : undefined;- if (!corrections?.length) return null;- return (- <div className="pl-[52px] pr-4">- {corrections.map((c) => (- <div- key={c.id}- className="grid grid-cols-[16px_minmax(0,1fr)_auto] items-center gap-x-3 py-2 text-sm"- >- <LuCornerDownRight className="size-3.5 shrink-0 text-muted-foreground" />- <div className="flex min-w-0 items-center gap-2.5">- <Badge variant="yellow" className="shrink-0">- {t`Correction`}- </Badge>- <Enumerable value={c.entryType} />- <QuantityDelta value={c.quantity} />- <span className="truncate text-muted-foreground">- {c.storageUnitName ?? c.locationName ?? "—"}- </span>- </div>- <div className="flex shrink-0 items-center gap-2 text-muted-foreground">- <span className="tabular-nums text-xs">- {formatDate(c.postingDate)}- </span>- <EmployeeAvatar employeeId={c.createdBy} />- </div>- </div>- ))}- </div>- );- },- [correctionsByOriginal, formatDate, t]- );-return (<><Table<(typeof data)[number]>- data={displayData}+ data={data}columns={columns}count={count}defaultColumnPinning={{left: ["itemReadableId"]}}renderContextMenu={renderContextMenu}- renderExpandedRow={renderExpandedRow}- canExpandRow={canExpandRow}title={t`Inventory Movements`}table="itemLedger"withSavedViewdiff --git a/docs/content/docs/reference/inventory.mdx b/docs/content/docs/reference/inventory.mdxindex cea120e09a..3dbb6b18c6 100644--- a/docs/content/docs/reference/inventory.mdx+++ b/docs/content/docs/reference/inventory.mdx@@ -34,7 +34,7 @@ Two kinds of transfer move stock. A **warehouse transfer** moves it between loca## Correcting a movement-The ledger is append-only — a posted movement is never edited or deleted. To fix one, use **"Correct Quantity"** on the movement in the Stock Movements screen and enter the quantity it should have been. Carbon books one **opposite movement for the difference**, linked to the original and dated with the original's posting date, so both sit in the right time period and the correction nests under the original in the list. The journal for the correction posts into the original's accounting period. A **locked** period refuses the correction until it's unlocked; a **closed** period is permanent — once a movement's period has closed, it can no longer be corrected. Correcting the same movement again measures against what it currently nets to, so repeated corrections converge instead of stacking.+The ledger is append-only — a posted movement is never edited or deleted. To fix one, use **"Correct Quantity"** on the movement in the Stock Movements screen and enter the quantity it should have been. Carbon books one **opposite movement for the difference**, linked to the original and dated with the original's posting date, so both sit in the right time period. The correction appears as its own row, flagged with a **Correction** badge that links it back to the movement it fixes. The journal for the correction posts into the original's accounting period. A **locked** period refuses the correction until it's unlocked; a **closed** period is permanent — once a movement's period has closed, it can no longer be corrected. Correcting the same movement again measures against what it currently nets to, so repeated corrections converge instead of stacking.## Valuediff --git a/packages/database/src/swagger-docs-schema.ts b/packages/database/src/swagger-docs-schema.tsindex df36015fe7..f5f7fc25e0 100644--- a/packages/database/src/swagger-docs-schema.ts+++ b/packages/database/src/swagger-docs-schema.ts@@ -82591,10 +82591,10 @@ export default {$ref: "#/parameters/rowFilter.companySettings.plmReleaseControl"},{- $ref: "#/parameters/rowFilter.companySettings.incompletePickingListPolicy"+ $ref: "#/parameters/rowFilter.companySettings.autoSelectMaterialWithoutPickingList"},{- $ref: "#/parameters/rowFilter.companySettings.autoSelectMaterialWithoutPickingList"+ $ref: "#/parameters/rowFilter.companySettings.incompletePickingListPolicy"},{$ref: "#/parameters/rowFilter.companySettings.includeMaterialsOnTraveler"@@ -82788,10 +82788,10 @@ export default {$ref: "#/parameters/rowFilter.companySettings.plmReleaseControl"},{- $ref: "#/parameters/rowFilter.companySettings.incompletePickingListPolicy"+ $ref: "#/parameters/rowFilter.companySettings.autoSelectMaterialWithoutPickingList"},{- $ref: "#/parameters/rowFilter.companySettings.autoSelectMaterialWithoutPickingList"+ $ref: "#/parameters/rowFilter.companySettings.incompletePickingListPolicy"},{$ref: "#/parameters/rowFilter.companySettings.includeMaterialsOnTraveler"@@ -82939,10 +82939,10 @@ export default {$ref: "#/parameters/rowFilter.companySettings.plmReleaseControl"},{- $ref: "#/parameters/rowFilter.companySettings.incompletePickingListPolicy"+ $ref: "#/parameters/rowFilter.companySettings.autoSelectMaterialWithoutPickingList"},{- $ref: "#/parameters/rowFilter.companySettings.autoSelectMaterialWithoutPickingList"+ $ref: "#/parameters/rowFilter.companySettings.incompletePickingListPolicy"},{$ref: "#/parameters/rowFilter.companySettings.includeMaterialsOnTraveler"@@ -100085,7 +100085,7 @@ export default {properties: {id: {description:- "Note:\nThis is a Foreign Key to `supplierLocation.id`.<fk table='supplierLocation' column='id'/>",+ "Note:\nThis is a Primary Key.<pk/>\nThis is a Foreign Key to `supplierLocation.id`.<fk table='supplierLocation' column='id'/>",format: "text",type: "string"},@@ -100134,7 +100134,7 @@ export default {},supplierLocationId: {description:- "Note:\nThis is a Primary Key.<pk/>\nThis is a Foreign Key to `supplierLocation.id`.<fk table='supplierLocation' column='id'/>",+ "Note:\nThis is a Foreign Key to `supplierLocation.id`.<fk table='supplierLocation' column='id'/>",format: "text",type: "string"},@@ -133723,8 +133723,8 @@ export default {"showCustomerReadableId","autoStartOperationTimer","plmReleaseControl",- "incompletePickingListPolicy","autoSelectMaterialWithoutPickingList",+ "incompletePickingListPolicy","includeMaterialsOnTraveler"],properties: {@@ -133962,16 +133962,16 @@ export default {format: "text",type: "string"},- incompletePickingListPolicy: {- default: "warn",- format: "text",- type: "string"- },autoSelectMaterialWithoutPickingList: {default: false,format: "boolean",type: "boolean"},+ incompletePickingListPolicy: {+ default: "warn",+ format: "text",+ type: "string"+ },includeMaterialsOnTraveler: {default: false,format: "boolean",@@ -178590,14 +178590,14 @@ export default {in: "query",type: "string"},- "rowFilter.companySettings.incompletePickingListPolicy": {- name: "incompletePickingListPolicy",+ "rowFilter.companySettings.autoSelectMaterialWithoutPickingList": {+ name: "autoSelectMaterialWithoutPickingList",required: false,in: "query",type: "string"},- "rowFilter.companySettings.autoSelectMaterialWithoutPickingList": {- name: "autoSelectMaterialWithoutPickingList",+ "rowFilter.companySettings.incompletePickingListPolicy": {+ name: "incompletePickingListPolicy",required: false,in: "query",type: "string"diff --git a/packages/database/src/types.ts b/packages/database/src/types.tsindex 2e85be7bbd..8afce629d0 100644--- a/packages/database/src/types.ts+++ b/packages/database/src/types.ts@@ -64505,14 +64505,14 @@ export type Database = {},{foreignKeyName: "partner_id_fkey"- columns: ["supplierLocationId"]+ columns: ["id"]isOneToOne: falsereferencedRelation: "supplierLocation"referencedColumns: ["id"]},{foreignKeyName: "partner_id_fkey"- columns: ["id"]+ columns: ["supplierLocationId"]isOneToOne: falsereferencedRelation: "supplierLocation"referencedColumns: ["id"]@@ -66151,14 +66151,14 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey"- columns: ["supplierCountryCode"]+ columns: ["customerCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["customerCountryCode"]+ columns: ["supplierCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]@@ -69537,21 +69537,21 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey"- columns: ["invoiceCountryCode"]+ columns: ["shipmentCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["shipmentCountryCode"]+ columns: ["customerCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["customerCountryCode"]+ columns: ["invoiceCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]@@ -70098,14 +70098,14 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey"- columns: ["paymentCountryCode"]+ columns: ["customerCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["customerCountryCode"]+ columns: ["paymentCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]diff --git a/packages/database/supabase/functions/correct-stock-movement/index.ts b/packages/database/supabase/functions/correct-stock-movement/index.tsindex 7d4db91427..e4a21e6397 100644--- a/packages/database/supabase/functions/correct-stock-movement/index.ts+++ b/packages/database/supabase/functions/correct-stock-movement/index.ts@@ -114,6 +114,12 @@ serve(async (req: Request) => {);}+ // A correction row shows only its delta (+4), which doesn't tell the reader+ // the from→to intent — so when the user gives no reason, self-document it.+ const resolvedComment =+ comment?.trim() ||+ `Corrected from ${effectiveQuantity} to ${correctedQuantity}`;+const [itemResult, itemCostResult, accountingSettings, trackingQuantities] =await Promise.all([client@@ -275,9 +281,7 @@ serve(async (req: Request) => {inventoryAdjustmentVarianceAccount:accountDefaults.data.inventoryAdjustmentVarianceAccount,},- description: comment?.trim()- ? `Stock Movement Correction — ${comment.trim()}`- : "Stock Movement Correction",+ description: `Stock Movement Correction — ${resolvedComment}`,userId,dimensions: dimensionMap,}@@ -317,7 +321,7 @@ serve(async (req: Request) => {documentType: root.documentType,documentId: root.documentId,correctionOfItemLedgerId: root.id,- comment: comment ?? null,+ comment: resolvedComment,companyId,createdBy: userId,},diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.tsindex 2e85be7bbd..8afce629d0 100644--- a/packages/database/supabase/functions/lib/types.ts+++ b/packages/database/supabase/functions/lib/types.ts@@ -64505,14 +64505,14 @@ export type Database = {},{foreignKeyName: "partner_id_fkey"- columns: ["supplierLocationId"]+ columns: ["id"]isOneToOne: falsereferencedRelation: "supplierLocation"referencedColumns: ["id"]},{foreignKeyName: "partner_id_fkey"- columns: ["id"]+ columns: ["supplierLocationId"]isOneToOne: falsereferencedRelation: "supplierLocation"referencedColumns: ["id"]@@ -66151,14 +66151,14 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey"- columns: ["supplierCountryCode"]+ columns: ["customerCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["customerCountryCode"]+ columns: ["supplierCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]@@ -69537,21 +69537,21 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey"- columns: ["invoiceCountryCode"]+ columns: ["shipmentCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["shipmentCountryCode"]+ columns: ["customerCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["customerCountryCode"]+ columns: ["invoiceCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]@@ -70098,14 +70098,14 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey"- columns: ["paymentCountryCode"]+ columns: ["customerCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["customerCountryCode"]+ columns: ["paymentCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]