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
fix(items): "update all matching items" runs the same item functions as a selection, so a bad value is refused before the job starts
aashu36d4c3b095f8
diff --git a/.ai/specs/2026-10-13-infinite-scroll-tables.md b/.ai/specs/2026-10-13-infinite-scroll-tables.mdindex 4afed2c697..102c36ea39 100644--- a/.ai/specs/2026-10-13-infinite-scroll-tables.md+++ b/.ai/specs/2026-10-13-infinite-scroll-tables.md@@ -472,7 +472,7 @@ The user approved the spec, then asked for the whole pipeline (plan, build, test- [x] **Review fix B: a cursor names its order (R4)** — **Autonomous:** A cursor stores `keys`, each keyset column with its direction (`createdAt:desc`). If the keys differ from the request's order, the query adds a filter that no row matches (`and(id.is.null,id.not.is.null)`). The list then ends instead of restarting at page 1. A cursor without `keys` does not decode.- [x] **Review fix B: offset tokens (S3)** — **Autonomous:** Printing jobs and the audit log use `encodeOffsetToken` / `decodeOffsetToken`, not a `Cursor` with an offset in `id`. A failed later page of either returns `listError`.- [x] **Review fix B: no cursor in MCP (R3)** — **Autonomous:** `getAccountLedger` (MCP) pages by `offset` only. The 4 ledger drawers call `getAccountLedgerPage` (`accounting.server.ts`), which reads `getAccountLedgerLines` (no `@mcp` tag) and replaced `getConsolidatedAccountLedger`. `getAssemblyInstructions` (MCP) takes its old flat args with `offset?` again and ends with `query = setGenericQueryFilters(…); return query;`; with only `limit` it reads from offset 0. The list reads `getAssemblyInstructionsPage` (no `@mcp` tag). Typing the MCP args as `GenericQueryFilters & {…}` was rejected: the generator then publishes them nested under `args`, a contract change.-- [x] **Merge with the service-function refactor (2026-10-20)** — **Autonomous:** main removed module barrels and moved operations into `defineServiceFn` consts. The bulk routes now call main's operations for a selection and start the background job for `allMatching` (or a selection too big for one request). The background job's production work runs main's operations (`releaseCheckedJobs`, `releaseBatches`, `updateBatch`) in `systemContext` on behalf of the user (`utils/production-bulk-actions.server.ts`); its other building blocks moved into the module service files (`bulkUpdateItems` → `items.service.ts`, `bulkDeleteJobs` → `production.service.ts`, `bulkDeletePurchaseOrders` → `purchasing.service.ts`, the user queue helpers → `users.service.ts`). `getAccountLedgerPage` moved to `accounting.service.ts` and `loadPeriodRuns` to `routes/x+/accounting+/period-runs.server.ts`, where main put them.+- [x] **Merge with the service-function refactor (2026-10-20)** — **Autonomous:** main removed module barrels and moved operations into `defineServiceFn` consts. The bulk routes now call main's operations for a selection and start the background job for `allMatching` (or a selection too big for one request). The background job's production work runs main's operations (`releaseCheckedJobs`, `releaseBatches`, `updateBatch`) in `systemContext` on behalf of the user (`utils/production-bulk-actions.server.ts`); its other building blocks moved into the module service files (`bulkDeleteJobs` → `production.service.ts`, `bulkDeletePurchaseOrders` → `purchasing.service.ts`, the user queue helpers → `users.service.ts`). `getAccountLedgerPage` moved to `accounting.service.ts` and `loadPeriodRuns` to `routes/x+/accounting+/period-runs.server.ts`, where main put them. Later, `bulkUpdateItems` became `utils/item-bulk-actions.server.ts`: each chunk runs main's item operations (`setItemTrackingType`, `setItemSourcing`, `setItemPostingGroup`) in `systemContext`, so the value is validated and the writes match the in-request path.- [x] **Review fix B: sync operations (R17)** — **Autonomous:** `getSyncOperations` counts on the first page only (no `after`, offset 0). It quotes the cursor values with the escape of `cursor.ts`, copied into ee because ee cannot import the app.- [x] **Review fix C: per-row extras come with each page (C1)** — **Autonomous:** `loadListPage` takes `mapRows(rows, context)`, which runs on every page after a load without an error. Jobs (batches and the tracked entity), Suppliers (report contacts), Tracked Entities (shelf-life policy) and Workflows (published version number, last run) put the value on the row, and their tables read it from the row. `onPage` and every "merge later pages" state are gone; `InfiniteOptions.onPage` is removed. The Jobs tracked-entity lookup moved from the browser to the loader (the loader's client, filtered by `companyId`). — One page carries its own values, so a revalidation re-read of the loaded pages refreshes them too.- [x] **Review fix C: the planning grids own their rows (C1, B4, B5)** — **Autonomous:** The planning loaders attach each item's actions to its row (`withPlanningActions`, `planning-action-scope.ts`), and to the linked drawer row. The table calls `useInfiniteRows` with `ignoreParams: [PLANNING_DRAWER_PARAM]` and passes it as `infiniteRows`. The drawer rows add the linked row only when it is not loaded, and the actions are read from those rows, so a loaded drawer row is counted once (production and purchasing alike). The constants are now `PURCHASING_PLANNING_PAGING` and `PRODUCTION_PLANNING_PAGING`. A failed later page returns `listErrorPage("items")`; a failed page 1 now throws its redirect (it was a bare `redirect(...)`). This replaces the Review fix B note that the two planning constants keep their names.diff --git a/apps/erp/app/modules/items/items.service.ts b/apps/erp/app/modules/items/items.service.tsindex c66f753f4d..146962abe6 100644--- a/apps/erp/app/modules/items/items.service.ts+++ b/apps/erp/app/modules/items/items.service.ts@@ -43,7 +43,6 @@ import { getLogger } from "@carbon/logger";import { oncePerRead } from "@carbon/logger/middleware.server";import { NotificationEvent } from "@carbon/notifications";import {- chunkArray,datetime,getReadableIdWithRevision,isUniqueViolation,@@ -100,10 +99,8 @@ import {type configurationRuleValidator,type consumableValidator,type customerPartValidator,- deriveItemMethodUpdate,EACH_UNIT_OF_MEASURE_CODE,type getMethodValidator,- type ItemBulkUpdateField,ItemTrackingType,isAllowedChangeNoticeTransition,type itemCostValidator,@@ -11275,199 +11272,3 @@ export async function saveMethodRefusal(ctx: ServiceContext, targetId: string) {});return lock.ok ? null : ctx.error("rule", lock.message);}--/**- * The bulk Update of the item tables (Parts, Materials, Tools, Consumables,- * Services). Called by `x+/items+/update.tsx` with the selected items and by- * the background bulk-action job (`~/utils/table-jobs.server`) with up to 100- * items at a time.- */--export type BulkUpdateItemsResult = {- /** Items updated. */- done: number;- /** Ids that are not an item of the company. */- skipped: number;- /** Items whose chunk failed. */- failed: number;- /** The first failure's message, or null. */- error: string | null;-};--/** An `.in()` filter rides in the request URL, so items go 100 at a time. */-const ITEM_BULK_CHUNK = 100;--/**- * Sets one field on many items. Writes as `client` (the user), and the- * cascades through `db`. Each chunk commits on its own: a failed chunk leaves- * the chunks before it applied, and the result counts both, so the caller can- * say what was done.- */-export async function bulkUpdateItems(- client: SupabaseClient<Database>,- db: Kysely<KyselyDatabase>,- args: {- itemIds: string[];- field: ItemBulkUpdateField;- value: string;- companyId: string;- userId: string;- }-): Promise<BulkUpdateItemsResult> {- const result: BulkUpdateItemsResult = {- done: 0,- skipped: 0,- failed: 0,- error: null- };- const ids = [...new Set(args.itemIds.filter(Boolean))];- for (const chunk of chunkArray(ids, ITEM_BULK_CHUNK)) {- // The writes below trust these ids (the itemCost insert names them), so- // keep only the company's own items.- const items = await client- .from("item")- .select("id")- .in("id", chunk)- .eq("companyId", args.companyId);- if (items.error) {- logger.error("Failed to read the items of a bulk update", {- companyId: args.companyId,- error: items.error- });- result.failed += chunk.length;- result.error ??= items.error.message;- continue;- }- const itemIds = items.data.map((item) => item.id);- result.skipped += chunk.length - itemIds.length;- if (itemIds.length === 0) continue;-- const error = await updateItemsChunk(client, db, { ...args, itemIds });- if (error) {- logger.error("Failed to bulk update items", {- companyId: args.companyId,- field: args.field,- error- });- result.failed += itemIds.length;- result.error ??= error;- } else {- result.done += itemIds.length;- }- }- return result;-}--/** One chunk of `bulkUpdateItems`. Answers the error message, or null. */-async function updateItemsChunk(- client: SupabaseClient<Database>,- db: Kysely<KyselyDatabase>,- {- itemIds,- field,- value,- companyId,- userId- }: {- itemIds: string[];- field: ItemBulkUpdateField;- value: string;- companyId: string;- userId: string;- }-): Promise<string | null> {- const updatedAt = datetime.timestamp();- switch (field) {- case "itemTrackingType": {- const newType = value as InventoryItemType;- const update = await client- .from("item")- .update({ itemTrackingType: newType, updatedBy: userId, updatedAt })- .in("id", itemIds)- .eq("companyId", companyId);- if (update.error) return update.error.message;- try {- await cascadeItemTrackingType(db, {- itemIds,- companyId,- newType,- userId- });- } catch (err) {- logger.error("Failed to cascade item tracking type", {- companyId,- error: err- });- return "Failed to cascade tracking flags";- }- return null;- }- case "replenishmentSystem":- case "defaultMethodType":- case "sourcingType": {- // These three fields are interlocked and each mirror down to the item's- // method materials. updateItemMethodAndSourcing applies the item write- // and the cascade in one transaction, so they can't be left half-applied.- const { itemUpdate, cascade } = deriveItemMethodUpdate(field, value);- try {- await updateItemMethodAndSourcing(db, {- itemIds,- companyId,- userId,- itemUpdate,- cascade- });- } catch (err) {- logger.error("Failed to update item method/sourcing", {- companyId,- field,- error: err- });- return "Failed to update item";- }- return null;- }- case "itemPostingGroupId": {- // One read for the chunk, then one update of the items that have an- // itemCost row and one insert for the rest.- const existing = await client- .from("itemCost")- .select("itemId")- .in("itemId", itemIds)- .eq("companyId", companyId);- if (existing.error) return existing.error.message;- const withCost = new Set(existing.data.map((row) => row.itemId));- const itemPostingGroupId = value || null;-- if (withCost.size > 0) {- const update = await client- .from("itemCost")- .update({ itemPostingGroupId, updatedBy: userId, updatedAt })- .in("itemId", [...withCost])- .eq("companyId", companyId);- if (update.error) return update.error.message;- }-- const missing = itemIds.filter((itemId) => !withCost.has(itemId));- if (missing.length > 0) {- const insert = await client.from("itemCost").insert(- missing.map((itemId) => ({- itemId,- itemPostingGroupId,- costingMethod: "Standard" as const,- standardCost: 0,- unitCost: 0,- costIsAdjusted: false,- companyId,- createdBy: userId,- updatedBy: userId,- createdAt: updatedAt,- updatedAt- }))- );- if (insert.error) return insert.error.message;- }- return null;- }- }-}diff --git a/apps/erp/app/routes/x+/items+/update.tsx b/apps/erp/app/routes/x+/items+/update.tsxindex 1e9f9e2d31..a0354bd82f 100644--- a/apps/erp/app/routes/x+/items+/update.tsx+++ b/apps/erp/app/routes/x+/items+/update.tsx@@ -13,6 +13,7 @@ import {type itemTrackingTypes} from "~/modules/items/items.models";import type { methodType, sourcingType } from "~/modules/shared/shared.models";+import { isItemBulkUpdateValue } from "~/utils/item-bulk-actions.server";import { bulkStartFormResponse } from "~/utils/table-jobs";import { startAllMatchingBulkAction } from "~/utils/table-jobs.server";@@ -65,6 +66,9 @@ export async function action(args: ActionFunctionArgs) {// Every matching row: the background job updates them 100 at a time// (bulkUpdateItems).if (allMatching && isItemBulkUpdateField(field)) {+ if (!isItemBulkUpdateValue(field, value)) {+ return invalid(`${value} is not a valid ${field}`);+ }const { companyId, userId } = await requirePermissions(args.request, {update: "parts"});diff --git a/apps/erp/app/utils/item-bulk-actions.server.ts b/apps/erp/app/utils/item-bulk-actions.server.tsnew file mode 100644index 0000000000..91d0d55d76--- /dev/null+++ b/apps/erp/app/utils/item-bulk-actions.server.ts@@ -0,0 +1,132 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import type { ServiceContext } from "@carbon/api/service-fn.server";+import { getLogger } from "@carbon/logger";+import { chunkArray } from "@carbon/utils";+import {+ type ItemBulkUpdateField,+ itemReplenishmentSystems,+ itemTrackingTypes+} from "~/modules/items/items.models";+import {+ setItemPostingGroup,+ setItemSourcing,+ setItemTrackingType+} from "~/modules/items/items.server";+import { methodType, sourcingType } from "~/modules/shared/shared.models";++/**+ * The background bulk-action job's slices of the items tables' Update+ * (`~/utils/table-jobs.server`). Each chunk runs the items service function+ * the in-request action runs, so the value is checked and the cascades run+ * the same way on both paths.+ */++const logger = getLogger("erp", "item-bulk-actions");++/** An `.in()` filter rides in the request URL, so items go 100 at a time. */+const ITEM_BULK_CHUNK = 100;++const allowedValues: Partial<Record<ItemBulkUpdateField, readonly string[]>> = {+ itemTrackingType: itemTrackingTypes,+ replenishmentSystem: itemReplenishmentSystems,+ defaultMethodType: methodType,+ sourcingType: sourcingType+};++/** Whether `value` is one the field takes. Any item group id (or none) is. */+export function isItemBulkUpdateValue(+ field: ItemBulkUpdateField,+ value: string+) {+ const allowed = allowedValues[field];+ return allowed === undefined || allowed.includes(value);+}++function updateItems(+ ctx: ServiceContext,+ ids: string[],+ field: ItemBulkUpdateField,+ value: string+) {+ switch (field) {+ case "itemTrackingType":+ return setItemTrackingType(ctx, {+ ids,+ itemTrackingType: value as (typeof itemTrackingTypes)[number]+ });+ case "replenishmentSystem":+ case "defaultMethodType":+ case "sourcingType":+ return setItemSourcing(ctx, { ids, [field]: value });+ case "itemPostingGroupId":+ return setItemPostingGroup(ctx, {+ ids,+ itemPostingGroupId: value || null+ });+ }+}++export type BulkUpdateItemsResult = {+ done: number;+ /** Ids that are not the company's items. */+ skipped: number;+ /** Items whose chunk failed. */+ failed: number;+ error: string | null;+};++/**+ * Sets one field on many items, 100 at a time. Each chunk commits on its own:+ * a failed chunk leaves the chunks before it applied, and the result counts+ * both, so the caller can say what was done.+ */+export async function bulkUpdateItems(+ ctx: ServiceContext,+ {+ itemIds,+ field,+ value+ }: { itemIds: string[]; field: ItemBulkUpdateField; value: string }+): Promise<BulkUpdateItemsResult> {+ const companyId = ctx.company.id;+ const result: BulkUpdateItemsResult = {+ done: 0,+ skipped: 0,+ failed: 0,+ error: null+ };+ const ids = [...new Set(itemIds.filter(Boolean))];+ for (const chunk of chunkArray(ids, ITEM_BULK_CHUNK)) {+ // The item group write inserts a cost row for each id, so keep only the+ // company's own items.+ const items = await ctx.asCaller.supabase+ .from("item")+ .select("id")+ .in("id", chunk)+ .eq("companyId", companyId);+ if (items.error) {+ logger.error("Failed to read the items of a bulk update", {+ companyId,+ error: items.error+ });+ result.failed += chunk.length;+ result.error ??= items.error.message;+ continue;+ }+ const owned = items.data.map((item) => item.id);+ result.skipped += chunk.length - owned.length;+ if (owned.length === 0) continue;++ const update = await updateItems(ctx, owned, field, value);+ if (update.error) {+ result.failed += owned.length;+ result.error ??= update.error.message;+ } else {+ result.done += owned.length;+ }+ }+ return result;+}diff --git a/apps/erp/app/utils/table-jobs.server.ts b/apps/erp/app/utils/table-jobs.server.tsindex b840fe043e..e59a53af4c 100644--- a/apps/erp/app/utils/table-jobs.server.ts+++ b/apps/erp/app/utils/table-jobs.server.ts@@ -23,7 +23,6 @@ import {import { getLogger } from "@carbon/logger";import { nanoid } from "nanoid";import { isItemBulkUpdateField } from "~/modules/items/items.models";-import { bulkUpdateItems } from "~/modules/items/items.service";import { bulkDeleteJobs } from "~/modules/production/production.service";import { bulkDeletePurchaseOrders } from "~/modules/purchasing/purchasing.service";import { systemContext } from "~/modules/service-context.server";@@ -34,8 +33,11 @@ import {queueUserDeactivations,selectUsersForBulkAction} from "~/modules/users/users.service";-import { getDatabaseClient } from "~/services/database.server";import { decodeCursor } from "./cursor";+import {+ bulkUpdateItems,+ isItemBulkUpdateValue+} from "./item-bulk-actions.server";import { fetchListPage, getListDefinition } from "./list-registry/index.server";import {bulkDissolveBatches,@@ -151,7 +153,6 @@ type BulkActionRunContext = TableJobContext & {/** The user's client, signed again when its token is four minutes old:* RLS applies as it does to the action route. */getClient: ReturnType<typeof userClientFactory>;- db: ReturnType<typeof getDatabaseClient>;};/** What a bulk action does to one chunk of ids (at most 100); throws only@@ -201,25 +202,23 @@ function userClientFactory(userId: string) {}/**- * Each bulk action with a background path runs the same server function as+ * Each bulk action with a background path runs the same service functions as* its action route, so the per-row checks are the same on both paths.*/const BULK_ACTION_RUNS: Record<TableBulkActionKey, BulkActionRun> = {"items.update": async (ids, { field, value }, context) => {- if (!isItemBulkUpdateField(field) || typeof value !== "string") {+ if (+ !isItemBulkUpdateField(field) ||+ typeof value !== "string" ||+ !isItemBulkUpdateValue(field, value)+ ) {throw new Error("The item update is not valid");}- const result = await bulkUpdateItems(- await context.getClient(),- context.db,- {- itemIds: ids,- field,- value,- companyId: context.companyId,- userId: context.userId- }- );+ const result = await bulkUpdateItems(await jobServiceContext(context), {+ itemIds: ids,+ field,+ value+ });return {done: result.done,skipped: result.skipped,@@ -442,8 +441,7 @@ async function runBulkAction(action.params,{...context,- getClient: userClientFactory(context.userId),- db: getDatabaseClient()+ getClient: userClientFactory(context.userId)},carry);