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.

fix(api): clear errors and JSON-shaped inputs for the API and MCP (#2053)

Sidcdd7a5645b8c
diff --git a/.ai/lessons.md b/.ai/lessons.md
index 5e0b85c954..433268bb07 100644
--- a/.ai/lessons.md
+++ b/.ai/lessons.md
@@ -4169,3 +4169,13 @@ The write was then removed (nothing reads it), so the rail always starts collaps
**Rule:** A second reader of an `.xbf` opens it from a stream (`Open(std::istream&, doc)`), which skips the path check, and calls `xcaf_app()->Close(doc)` when done. Test any new pass over the ingest's xbf through `run_ingest`, not only through the converter.
**Applies to:** `crates/occt-bridge/src/*.cc` (any function that opens a BinXCAF document), `apps/assembler/src/actions/optimize.rs` (`run_ingest`).
+
+## A form validator is not an API contract
+
+**Context:** `production_createJobOperation` answered a bare 500 "Failed to insert job operation" to an API caller (2026-10-27).
+
+**Problem:** Operations moved from routes kept the route's input and error handling. The form sent a fresh client-made `id` for each new row, so the create input required one and an API caller had to invent it; a reused id failed the insert. The route's toast-only `ctx.error("internal", "Failed to …", error)` (448 of them) then hid the database's reason, so a duplicate key or a reference to nothing read as our failure.
+
+**Rule:** A create input leaves the new row's `id` optional when the table has a default (`mcp-create-inputs.test.ts` fails otherwise). A database refusal the caller can fix is reported as itself: `defineServiceFn` maps an `internal` error whose cause is one (`databaseRefusal`), so don't swallow the cause. A yes/no field is a real boolean that also parses the form's `"true"` / `"false"` (`booleanField`, `shared.models.ts`), so the API publishes `boolean`. A rich-text (JSON) column takes `optionalTiptapDoc` / `requiredTiptapDoc`, never `z.string()` or `z.unknown()`: a raw string is stored as a JSON scalar the editor cannot read. A JSON value a form posts as text takes `jsonInput(schema)`. Never `z.preprocess` / `z.coerce` / `z.any()` bare in an operation's input: the manifest publishes those as "anything".
+
+**Applies to:** every `defineServiceFn` in `apps/erp/app/modules/*/*.server.ts`, and any validator reused as an operation's input.
diff --git a/apps/erp/app/modules/accounting/accounting.server.ts b/apps/erp/app/modules/accounting/accounting.server.ts
index b8a9560bfa..5954f71a5b 100644
--- a/apps/erp/app/modules/accounting/accounting.server.ts
+++ b/apps/erp/app/modules/accounting/accounting.server.ts
@@ -17,6 +17,7 @@ import { insertSalesOrder } from "~/modules/sales/sales.service";
import { invokeCreate, invokePosting } from "~/modules/shared/shared.service";
import { getUserDefaults } from "~/modules/users/users.service";
import { fromServerFn } from "../shared/shared.service";
+import { fixedAssetClassValidator } from "./accounting.models";
import * as service from "./accounting.service";
import {
accountMoveRefusal,
@@ -4183,14 +4184,14 @@ export const getFixedAssetClassesList = defineServiceFn({
* @mcp
*/
export const createFixedAssetClass = defineServiceFn({
- input: z.looseObject({ data: z.unknown() }),
+ input: fixedAssetClassValidator.omit({ id: true }),
permission: { create: "accounting" },
async run(ctx, input) {
return unwrap(
ctx,
await service.upsertFixedAssetClass(
ctx.asCaller.supabase,
- payload(ctx, input.data).forCreate() as never
+ payload(ctx, input).forCreate() as never
)
);
}
@@ -4205,9 +4206,7 @@ export const createFixedAssetClass = defineServiceFn({
* @mcp
*/
export const updateFixedAssetClass = defineServiceFn({
- input: z.looseObject({
- id: z.string()
- }),
+ input: fixedAssetClassValidator.partial().extend({ id: z.string() }),
permission: { update: "accounting" },
async run(ctx, input) {
return unwrap(
diff --git a/apps/erp/app/modules/inventory/inventory.models.ts b/apps/erp/app/modules/inventory/inventory.models.ts
index 5fb88f9fd0..99e9b97d88 100644
--- a/apps/erp/app/modules/inventory/inventory.models.ts
+++ b/apps/erp/app/modules/inventory/inventory.models.ts
@@ -16,6 +16,7 @@ import {
import { z } from "zod";
import { zfd } from "zod-form-data";
import { batchPropertyDataTypes } from "../items/items.models";
+import { booleanField } from "../shared/shared.models";
export const demandPeriodTypes = ["Week", "Day", "Month"] as const;
export const demandSourceTypes = ["Sales Order", "Job Material"] as const;
@@ -428,7 +429,7 @@ export const shipmentFixedAssetLineUpdateValidator = z.discriminatedUnion(
z.object({
id: z.string().min(1),
field: z.literal("shipped"),
- value: z.enum(["true", "false"])
+ value: booleanField()
}),
z.object({
id: z.string().min(1),
@@ -449,7 +450,7 @@ export const receiptFixedAssetLineUpdateValidator = z.discriminatedUnion(
z.object({
id: z.string().min(1),
field: z.literal("received"),
- value: z.enum(["true", "false"])
+ value: booleanField()
}),
z.object({
id: z.string().min(1),
diff --git a/apps/erp/app/modules/inventory/inventory.server.ts b/apps/erp/app/modules/inventory/inventory.server.ts
index 6e48e316aa..c065754310 100644
--- a/apps/erp/app/modules/inventory/inventory.server.ts
+++ b/apps/erp/app/modules/inventory/inventory.server.ts
@@ -51,6 +51,10 @@ import {
getCompanySettings,
getNextSequence
} from "~/modules/settings/settings.service";
+import {
+ booleanField,
+ optionalTiptapDoc
+} from "~/modules/shared/shared.models";
import {
getCompanyTimeZone,
getLocationTimeZone,
@@ -1975,7 +1979,7 @@ export const updateShipmentFixedAssetLine = defineServiceFn({
.from("shipmentFixedAssetLine")
.update({
...(change.field === "shipped"
- ? { shipped: change.value === "true" }
+ ? { shipped: change.value }
: change.field === "serialNumber"
? { serialNumber: change.value || null }
: { meter: change.value === "" ? null : Number(change.value) }),
@@ -3247,7 +3251,7 @@ export const updatePickingList = defineServiceFn({
locationId: z.string().min(1),
assignee: z.string().optional(),
dueDate: z.string().optional(),
- notes: z.string().optional(),
+ notes: optionalTiptapDoc,
customFields: z.record(z.string(), z.unknown()).optional()
}),
permission: { update: "inventory" },
@@ -5983,8 +5987,8 @@ export const createStockTransferLine = defineServiceFn({
fromStorageUnitId: z.string().optional(),
toStorageUnitId: z.string().optional(),
quantity: z.number().min(0),
- requiresBatchTracking: z.enum(["true", "false"]),
- requiresSerialTracking: z.enum(["true", "false"])
+ requiresBatchTracking: booleanField(),
+ requiresSerialTracking: booleanField()
}),
permission: { create: "inventory" },
async run(ctx, input) {
@@ -6020,8 +6024,8 @@ export const updateStockTransferLine = defineServiceFn({
fromStorageUnitId: z.string().optional(),
toStorageUnitId: z.string().optional(),
quantity: z.number().min(0),
- requiresBatchTracking: z.enum(["true", "false"]),
- requiresSerialTracking: z.enum(["true", "false"]),
+ requiresBatchTracking: booleanField(),
+ requiresSerialTracking: booleanField(),
id: z.string().describe("The line to update.").optional()
})
.required({ id: true }),
diff --git a/apps/erp/app/modules/inventory/inventory.service.ts b/apps/erp/app/modules/inventory/inventory.service.ts
index 205061ba1e..0b4ddf8abd 100644
--- a/apps/erp/app/modules/inventory/inventory.service.ts
+++ b/apps/erp/app/modules/inventory/inventory.service.ts
@@ -5186,12 +5186,20 @@ export async function printEntityLabels(
}
}
+// Omitted per member, so `field` still tells the `value` types apart.
+type ReceiptFixedAssetLineChange =
+ z.output<typeof receiptFixedAssetLineUpdateValidator> extends infer Change
+ ? Change extends unknown
+ ? Omit<Change, "id">
+ : never
+ : never;
+
export function receiptFixedAssetLineChange(
- change: Omit<z.output<typeof receiptFixedAssetLineUpdateValidator>, "id">
+ change: ReceiptFixedAssetLineChange
) {
switch (change.field) {
case "received":
- return { received: change.value === "true" };
+ return { received: change.value };
case "serialNumber":
return { serialNumber: change.value || null };
case "meter":
diff --git a/apps/erp/app/modules/invoicing/invoicing.server.ts b/apps/erp/app/modules/invoicing/invoicing.server.ts
index 130d88033f..01377ba0d4 100644
--- a/apps/erp/app/modules/invoicing/invoicing.server.ts
+++ b/apps/erp/app/modules/invoicing/invoicing.server.ts
@@ -778,10 +778,10 @@ export const createPurchaseInvoice = defineServiceFn({
lines: z
.array(
z.object({
- partNumber: z.coerce.string().nullish(),
- description: z.coerce.string().nullish(),
- quantity: z.coerce.number().nullish(),
- unitPrice: z.coerce.number().nullish()
+ partNumber: z.coerce.string<string>().nullish(),
+ description: z.coerce.string<string>().nullish(),
+ quantity: z.coerce.number<number>().nullish(),
+ unitPrice: z.coerce.number<number>().nullish()
})
)
.default([]),
diff --git a/apps/erp/app/modules/items/AGENTS.md b/apps/erp/app/modules/items/AGENTS.md
index aa0271af0c..ffe8057479 100644
--- a/apps/erp/app/modules/items/AGENTS.md
+++ b/apps/erp/app/modules/items/AGENTS.md
@@ -103,7 +103,7 @@ import { itemValidator, itemTrackingTypes, itemReplenishmentSystems } from "~/mo
## Change Orders (sub-area)
-Engineering-change-order (ECO) workflow — a **top-to-bottom**, affected-items-first process: the user picks the parts/tools to change, sets a **per-item change type** (`Version` / `Revision` / `Replacement Part` / `New Part`), edits each item's BOM/BOP/attributes directly on a **real CO-owned Draft `makeMethod`** (via the normal embedded editors), and releases the CO — which activates each draft and propagates via supersession (except a net-new `New Part`, which has no predecessor). Lives **inside** the Items module (not a standalone module). Permission key is `parts` — loaders/actions use `requirePermissions(request, { view | update | delete | create: "parts" })`. Routes live under `apps/erp/app/routes/x+/items+/change-notice+/` (detail + `affected`/`action` child mutations) and `x+/items+/change-notices+/` (list + Types config); URLs are `/x/items/change-notice(s)…`. The **create form is the exception**: it lives at a top-level `apps/erp/app/routes/x+/change-notice+/new.tsx` (URL `/x/change-notice/new`, path helper `path.to.newChangeNotice`) so it renders with the app sidebar like `/x/part/new` and `/x/sales-order/new`, not nested under the Items module layout. Navigation is a "Change Notices" group in the Items sidebar (`useItemsSubmodules`). The `$id` **detail page uses the standard 3-pane detail convention** (`PanelProvider` + `ResizablePanels` from `~/components/Layout/Panels`, like sales-order / job): `ChangeNoticeExplorer` (affected-items list) is the explorer, the content is a URL-addressed `Outlet`, and `ChangeNoticeProperties` (header fields + affected assemblies + impact + release dialog, self-contained via `useRouteData`) is the properties panel. `$id.tsx` keeps `hideModuleSidebar: true` so the Items grouped sidebar doesn't stack next to the explorer. **The content follows the sales-order top-level-detail + line-route split:** `$id.details.tsx` is the **CO overview** (the `ChangeNoticeStatusFlow` state bar + the two rich-text narrative fields `reasonForChange` / `description` via `ChangeNoticeContent`, debounced 2.5s then POSTed to the `$id.content` action (NOT a direct `carbon.from("changeOrder").update` like the quality issue — that had no server-side place to enforce the engineering lock) — plus the **CO-wide Changes rollup** (`ChangeNoticeChanges` — every affected item's authoring diff, rendered between the description and the actions, same label+`ChangeNoticeDiffViewer` list as the release dialog) and the action tasks via the shared `ActionTaskList` + "Add Actions" modal, reconciled through `$id.action`); each affected item is its own **line route** `$id.$affectedId.details.tsx` (URL `/x/items/change-notice/$id/$affectedId/details`, `path.to.changeNoticeAffectedItem`, rendering `AffectedItemDetail`), linked from the explorer (Revision / Replacement Part rows show "OLD → NEW" with the minted item's number, resolved from the items store; a **New Part shows a single id** — it is net-new, so its `newItemId` equals its `itemId` and there is no predecessor to arrow from, guarded by `newItemId !== itemId`). **Purchasable draft items get supplier-part management on the line**: a Revision/New Part line whose draft part is `Buy`/`Buy and Make` renders the embedded `SupplierParts` grid (data from `partData.supplierParts`, already in the `$id` loader); its create/edit drawers are child routes `$id.$affectedId.details.new.tsx` / `$id.$affectedId.details.$supplierPartId.tsx` (the `SupplierPartForm` posts to the PART purchasing actions — the part create and edit actions return the `createSupplierPart` / `updateSupplierPart` result instead of redirecting so embedded callers stay put, and a duplicate supplier shows as a field error under Supplier), and delete is the action-only `$id.$affectedId.details.$supplierPartId.delete.tsx` (`path.to.changeNoticeDeleteSupplierPart`). `$id._index` redirects to the overview; the header CO-id links back to it. Plain-text reason/description entered on the create form are converted to tiptap JSON on insert (`toRichText` in `items.service.ts`).
+Engineering-change-order (ECO) workflow — a **top-to-bottom**, affected-items-first process: the user picks the parts/tools to change, sets a **per-item change type** (`Version` / `Revision` / `Replacement Part` / `New Part`), edits each item's BOM/BOP/attributes directly on a **real CO-owned Draft `makeMethod`** (via the normal embedded editors), and releases the CO — which activates each draft and propagates via supersession (except a net-new `New Part`, which has no predecessor). Lives **inside** the Items module (not a standalone module). Permission key is `parts` — loaders/actions use `requirePermissions(request, { view | update | delete | create: "parts" })`. Routes live under `apps/erp/app/routes/x+/items+/change-notice+/` (detail + `affected`/`action` child mutations) and `x+/items+/change-notices+/` (list + Types config); URLs are `/x/items/change-notice(s)…`. The **create form is the exception**: it lives at a top-level `apps/erp/app/routes/x+/change-notice+/new.tsx` (URL `/x/change-notice/new`, path helper `path.to.newChangeNotice`) so it renders with the app sidebar like `/x/part/new` and `/x/sales-order/new`, not nested under the Items module layout. Navigation is a "Change Notices" group in the Items sidebar (`useItemsSubmodules`). The `$id` **detail page uses the standard 3-pane detail convention** (`PanelProvider` + `ResizablePanels` from `~/components/Layout/Panels`, like sales-order / job): `ChangeNoticeExplorer` (affected-items list) is the explorer, the content is a URL-addressed `Outlet`, and `ChangeNoticeProperties` (header fields + affected assemblies + impact + release dialog, self-contained via `useRouteData`) is the properties panel. `$id.tsx` keeps `hideModuleSidebar: true` so the Items grouped sidebar doesn't stack next to the explorer. **The content follows the sales-order top-level-detail + line-route split:** `$id.details.tsx` is the **CO overview** (the `ChangeNoticeStatusFlow` state bar + the two rich-text narrative fields `reasonForChange` / `description` via `ChangeNoticeContent`, debounced 2.5s then POSTed to the `$id.content` action (NOT a direct `carbon.from("changeOrder").update` like the quality issue — that had no server-side place to enforce the engineering lock) — plus the **CO-wide Changes rollup** (`ChangeNoticeChanges` — every affected item's authoring diff, rendered between the description and the actions, same label+`ChangeNoticeDiffViewer` list as the release dialog) and the action tasks via the shared `ActionTaskList` + "Add Actions" modal, reconciled through `$id.action`); each affected item is its own **line route** `$id.$affectedId.details.tsx` (URL `/x/items/change-notice/$id/$affectedId/details`, `path.to.changeNoticeAffectedItem`, rendering `AffectedItemDetail`), linked from the explorer (Revision / Replacement Part rows show "OLD → NEW" with the minted item's number, resolved from the items store; a **New Part shows a single id** — it is net-new, so its `newItemId` equals its `itemId` and there is no predecessor to arrow from, guarded by `newItemId !== itemId`). **Purchasable draft items get supplier-part management on the line**: a Revision/New Part line whose draft part is `Buy`/`Buy and Make` renders the embedded `SupplierParts` grid (data from `partData.supplierParts`, already in the `$id` loader); its create/edit drawers are child routes `$id.$affectedId.details.new.tsx` / `$id.$affectedId.details.$supplierPartId.tsx` (the `SupplierPartForm` posts to the PART purchasing actions — the part create and edit actions return the `createSupplierPart` / `updateSupplierPart` result instead of redirecting so embedded callers stay put, and a duplicate supplier shows as a field error under Supplier), and delete is the action-only `$id.$affectedId.details.$supplierPartId.delete.tsx` (`path.to.changeNoticeDeleteSupplierPart`). `$id._index` redirects to the overview; the header CO-id links back to it. Reason and description are taken as Markdown or a Tiptap document and stored as a document (`optionalTiptapDoc`, `shared.models.ts`), on create and update.
**No staged mirror tables.** The v1 `changeOrderStaged*` tables were deleted. A CO's per-affected-item edits now live on a **real Draft `makeMethod`** whose `makeMethod.changeOrderId` points at the CO, edited via the embedded real `BillOfMaterial` / `BillOfProcess` editors on the CO detail page. The **same** draft method also surfaces on the affected item's own master page (`/x/part|tool/$itemId/details`): the item-detail loaders (`x+/part+/$itemId{.,}.tsx`, `x+/tool+/$itemId.details.tsx`) select it like any other method and **no longer exclude `changeOrderId`-stamped drafts**, so a revision/new-part item created by an open CO shows its BOM/BOP on the item master too — the two surfaces edit the same rows and stay in sync. (`Active` is still preferred as the default selection, so a `Version` CO's existing item keeps its live method by default.) `changeOrderId` is cleared at release.
diff --git a/apps/erp/app/modules/items/items.models.ts b/apps/erp/app/modules/items/items.models.ts
index e8506cd1d8..c6d51dd0a5 100644
--- a/apps/erp/app/modules/items/items.models.ts
+++ b/apps/erp/app/modules/items/items.models.ts
@@ -248,10 +248,10 @@ export const itemValidator = z.object({
// itemShelfLife row. Truly absent fields (non-form callers like MCP that
// don't set shelfLifeMode at all) remain undefined, which the upsert
// helper treats as a no-op.
- shelfLifeMode: z.preprocess(
- (v) => (v === "" ? "NotManaged" : v),
- z.enum(shelfLifeModes).optional()
- ),
+ shelfLifeMode: z
+ .union([z.literal(""), z.enum(shelfLifeModes)])
+ .transform((v) => (v === "" ? "NotManaged" : v))
+ .optional(),
shelfLifeDays: zfd.numeric(z.number().positive().optional()),
shelfLifeTriggerProcessId: zfd.text(z.string().optional()),
// Whether the clock starts when the trigger process begins ('Before') or
diff --git a/apps/erp/app/modules/items/items.server.ts b/apps/erp/app/modules/items/items.server.ts
index b5192a0ff2..41a7713261 100644
--- a/apps/erp/app/modules/items/items.server.ts
+++ b/apps/erp/app/modules/items/items.server.ts
@@ -29,7 +29,13 @@ import {
import { z } from "zod";
import { flattenTree } from "~/components/TreeView";
import { replanAfterItemChange } from "~/modules/production/production.server";
-import { methodType, sourcingType } from "~/modules/shared/shared.models";
+import {
+ booleanField,
+ methodType,
+ optionalTiptapDoc,
+ requiredTiptapDoc,
+ sourcingType
+} from "~/modules/shared/shared.models";
import {
getCompanyTimeZone,
isActiveCompanyEmployee,
@@ -1403,6 +1409,8 @@ export const recalculateItemCost = defineServiceFn({
export const createChangeNotice = defineServiceFn({
input: changeNoticeValidator.omit({ id: true, type: true }).extend({
openDate: z.string().optional(),
+ reasonForChange: optionalTiptapDoc,
+ description: optionalTiptapDoc,
customFields: customFieldsInput
}),
permission: { create: "parts" },
@@ -1415,8 +1423,8 @@ export const createChangeNotice = defineServiceFn({
const created = await service.insertChangeNotice(client, {
changeNoticeId: input.changeOrderId || undefined,
name: input.name,
- reasonForChange: service.toRichText(input.reasonForChange),
- description: service.toRichText(input.description),
+ reasonForChange: input.reasonForChange,
+ description: input.description,
priority: input.priority,
changeNoticeTypeId: input.changeOrderTypeId || undefined,
nonConformanceId: input.nonConformanceId || undefined,
@@ -4598,13 +4606,13 @@ export const createMethodMaterial = defineServiceFn({
input: z.looseObject({
id: z
.string()
- .describe(
- "Updates the existing record with this key; creates one when there is none."
- ),
+ .min(1)
+ .optional()
+ .describe("The new material's id; the table makes one when left out."),
makeMethodId: z.string().min(1),
order: z.number().min(0),
itemType: z.enum(["Part", "Material", "Consumable"]),
- kit: z.enum(["true", "false"]).optional(),
+ kit: booleanField().optional(),
methodType: z.enum([
"Purchase to Order",
"Pull from Inventory",
@@ -4658,7 +4666,7 @@ export const updateMethodMaterial = defineServiceFn({
makeMethodId: z.string().min(1),
order: z.number().min(0),
itemType: z.enum(["Part", "Material", "Consumable"]),
- kit: z.enum(["true", "false"]).optional(),
+ kit: booleanField().optional(),
methodType: z.enum([
"Purchase to Order",
"Pull from Inventory",
@@ -4966,7 +4974,7 @@ export const createMethodOperationStep = defineServiceFn({
input: z.looseObject({
operationId: z.string().min(1),
name: z.string().min(1),
- description: z.string().min(1),
+ description: requiredTiptapDoc,
type: z.enum([
"Task",
"Value",
@@ -5029,7 +5037,7 @@ export const updateMethodOperationStep = defineServiceFn({
.looseObject({
operationId: z.string().min(1),
name: z.string().min(1),
- description: z.string().min(1),
+ description: requiredTiptapDoc,
type: z.enum([
"Task",
"Value",
@@ -6256,8 +6264,8 @@ export const updateChangeNotice = defineServiceFn({
changeOrderTypeId: z.string().nullable().optional(),
nonConformanceId: z.string().nullable().optional(),
openDate: z.string().optional(),
- reasonForChange: z.unknown().optional(),
- description: z.unknown().optional(),
+ reasonForChange: optionalTiptapDoc,
+ description: optionalTiptapDoc,
dueDate: z.string().nullable().optional(),
assignee: z.string().nullable().optional(),
customFields: z.unknown().optional()
diff --git a/apps/erp/app/modules/items/items.service.ts b/apps/erp/app/modules/items/items.service.ts
index a1b5d98178..c6f69e8b56 100644
--- a/apps/erp/app/modules/items/items.service.ts
+++ b/apps/erp/app/modules/items/items.service.ts
@@ -37,7 +37,6 @@ import {
TEMP_STAGING_BUCKET
} from "@carbon/files";
import { supportedModelTypes } from "@carbon/files/cad";
-import { TiptapText } from "@carbon/files/markdown";
import { trigger } from "@carbon/jobs";
import { getLogger } from "@carbon/logger";
import { oncePerRead } from "@carbon/logger/middleware.server";
@@ -4583,7 +4582,8 @@ export async function upsertMethodMaterial(
client: SupabaseClient<Database>,
methodMaterial:
- | (z.infer<typeof methodMaterialValidator> & {
+ | (Omit<z.infer<typeof methodMaterialValidator>, "id"> & {
+ id?: string;
companyId: string;
createdBy: string;
customFields?: Json;
@@ -4596,8 +4596,10 @@ export async function upsertMethodMaterial(
) {
// The MCP/API path skips methodMaterialValidator, and the insert spreads the
// id over the column default — so a blank id was stored as "" and the next
- // blank create collided with it.
- if (!methodMaterial.id?.trim()) {
+ // blank create collided with it. A create may leave the id out: the column
+ // default makes one.
+ const blankId = methodMaterial.id !== undefined && !methodMaterial.id.trim();
+ if (blankId || ("updatedBy" in methodMaterial && !methodMaterial.id)) {
return {
data: null,
error: { message: "Material ID is required" }
@@ -10353,13 +10355,6 @@ export const isMakeMethodId = (id: string) => id.startsWith("make_");
// ── Change notices ──────────────────────────────────────────────────────────
-// Reason and description arrive as Markdown; the columns are tiptap JSON, so
-// non-empty text becomes a doc the detail page's editor can edit.
-export function toRichText(value: string | undefined): Json | undefined {
- if (!value) return undefined;
- return TiptapText(value).toDocument() as unknown as Json;
-}
-
const onShapeDataValidator = z.object({
index: z.string(),
id: z.string().optional(),
diff --git a/apps/erp/app/modules/production/production.models.ts b/apps/erp/app/modules/production/production.models.ts
index 6e7ccfbb98..a8df9d4b33 100644
--- a/apps/erp/app/modules/production/production.models.ts
+++ b/apps/erp/app/modules/production/production.models.ts
@@ -8,6 +8,7 @@ import { z } from "zod";
import { zfd } from "zod-form-data";
import { plannedOrderValidator } from "../purchasing/purchasing.models";
import {
+ jsonInput,
methodItemType,
methodOperationOrders,
methodType,
@@ -200,11 +201,11 @@ export function getDueDateForColumn(
return undefined;
}
-export const schedulePriorityValidator = z.preprocess(
- (value) =>
- typeof value === "string" && value.trim().length === 0 ? undefined : value,
- zfd.numeric(z.number().refine(Number.isFinite, "Priority must be finite"))
-);
+// A number from the API, or the board's text. Blank text is refused rather
+// than read as 0.
+export const schedulePriorityValidator = z
+ .union([z.number(), z.string().trim().min(1).transform(Number)])
+ .pipe(z.number().refine(Number.isFinite, "Priority must be finite"));
/**
* A Queued assemblyPlanJob older than this never got picked up by the worker
@@ -312,7 +313,7 @@ const baseJobValidator = z.object({
.string()
.min(1, { message: "Unit of measure is required" }),
modelUploadId: zfd.text(z.string().optional()),
- configuration: z.any().optional(),
+ configuration: jsonInput(z.record(z.string(), z.any()).nullable().optional()),
// Make to Asset: the job completes to a fixed asset instead of inventory —
// either capitalised into a class, or its cost swept onto one asset that is
// already under construction. At most one is set (DB CHECK, refined below).
@@ -345,7 +346,9 @@ export const bulkJobValidator = z
locationId: z.string().min(1, { message: "Location is required" }),
customerId: zfd.text(z.string().optional()),
modelUploadId: zfd.text(z.string().optional()),
- configuration: z.any().optional()
+ configuration: jsonInput(
+ z.record(z.string(), z.any()).nullable().optional()
+ )
})
.refine(
(data) => {
@@ -1496,17 +1499,6 @@ export const stepPlanWarningsSchema = z.object({
plannedMotion: z.unknown().optional()
});
-const jsonField = <T extends z.ZodTypeAny>(schema: T) =>
- z.preprocess((raw) => {
- if (typeof raw !== "string") return raw;
- if (raw.trim() === "") return undefined;
- try {
- return JSON.parse(raw);
- } catch {
- return raw;
- }
- }, schema);
-
export const assemblyInstructionValidator = z.object({
id: zfd.text(z.string().optional()),
name: z.string().trim().min(1, { message: "Name is required" }),
@@ -1608,10 +1600,10 @@ const assemblyInstructionStepFields = z.object({
minValue: zfd.numeric(z.number().min(0).optional()),
maxValue: zfd.numeric(z.number().min(0).optional()),
listValues: stepListValues,
- componentNodeIds: jsonField(z.array(z.string()).optional()),
- motion: jsonField(motionSchema.optional()),
- camera: jsonField(cameraSchema.nullable().optional()),
- fastener: jsonField(fastenerSchema.nullable().optional()),
+ componentNodeIds: jsonInput(z.array(z.string()).optional()),
+ motion: jsonInput(motionSchema.optional()),
+ camera: jsonInput(cameraSchema.nullable().optional()),
+ fastener: jsonInput(fastenerSchema.nullable().optional()),
durationSeconds: zfd.numeric(z.number().positive().optional())
});
@@ -1663,12 +1655,12 @@ export const assemblyInstructionStepNewValidator = assemblyInstructionStepFields
* round-tripping the whole step form. `camera: null` clears it (auto-frame).
*/
export const assemblyInstructionStepMotionValidator = z.object({
- motion: jsonField(motionSchema.optional()),
+ motion: jsonInput(motionSchema.optional()),
// Put back the motion the step had before the author first drew a path.
reset: zfd.checkbox(),
- camera: jsonField(cameraSchema.nullable().optional()),
+ camera: jsonInput(cameraSchema.nullable().optional()),
// The build's orientation from this step on; `null` = same as the step before.
- orientation: jsonField(orientationSchema.nullable().optional())
+ orientation: jsonInput(orientationSchema.nullable().optional())
});
/**
@@ -1677,11 +1669,11 @@ export const assemblyInstructionStepMotionValidator = z.object({
* form. An empty array is valid — a process-only step with no components.
*/
export const assemblyInstructionStepComponentsValidator = z.object({
- componentNodeIds: jsonField(z.array(z.string()))
+ componentNodeIds: jsonInput(z.array(z.string()))
});
export const assemblyInstructionStepHiddenComponentsValidator = z.object({
- hiddenComponentNodeIds: jsonField(z.array(z.string()))
+ hiddenComponentNodeIds: jsonInput(z.array(z.string()))
});
export const assemblySubAssemblyNewValidator = z.object({
@@ -1698,7 +1690,7 @@ export const assemblyStepComponentsReassignValidator = z
.object({
// Absent for "remove" (unassign from every step); required otherwise.
targetStepId: z.string().optional(),
- componentNodeIds: jsonField(z.array(z.string()).min(1)),
+ componentNodeIds: jsonInput(z.array(z.string()).min(1)),
mode: z.enum(["move", "duplicate", "remove"])
})
.refine((v) => v.mode === "remove" || !!v.targetStepId, {
@@ -1753,7 +1745,7 @@ export const assemblyUnitValidator = z.object({
id: zfd.text(z.string().optional()),
modelUploadId: z.string().min(1),
name: z.string().trim().min(1, { message: "Name is required" }),
- componentNodeIds: jsonField(z.array(z.string()).min(1)),
+ componentNodeIds: jsonInput(z.array(z.string()).min(1)),
itemId: zfd.text(z.string().optional())
});
@@ -1850,7 +1842,7 @@ export const peopleDayValidator = z.object({
note: zfd.text(z.string().optional()),
// day-scoped overtime: a longer DAY, not extra hours per station
overtimeHours: zfd.numeric(z.number().min(0).max(16)),
- rows: jsonField(
+ rows: jsonInput(
z
.array(
z.object({
diff --git a/apps/erp/app/modules/production/production.server.ts b/apps/erp/app/modules/production/production.server.ts
index 0302649dbf..68f2a68832 100644
--- a/apps/erp/app/modules/production/production.server.ts
+++ b/apps/erp/app/modules/production/production.server.ts
@@ -44,7 +44,9 @@ import { resolveJobConfiguration } from "~/modules/sales/sales.utils";
import {
inspectionPlanRequired,
methodItemType,
- methodType
+ methodType,
+ optionalTiptapDoc,
+ requiredTiptapDoc
} from "~/modules/shared/shared.models";
import {
getCompanyTimeZone,
@@ -2326,8 +2328,9 @@ const jobMaterialInput = z.object({
* @mcp
*/
export const createJobMaterial = defineServiceFn({
- // The caller chooses the row's id (the bill of material's new row keeps it).
- input: jobMaterialInput.extend({ id: z.string() }),
+ // The bill of material sends its new row's id, so the row keeps its key;
+ // without one the table makes it.
+ input: jobMaterialInput.extend({ id: z.string().min(1).optional() }),
permission: { create: "production" },
async run(ctx, material) {
@@ -2556,12 +2559,16 @@ export const deleteJobMaterials = defineServiceFn({
// The bill of process form requires times, units and rates; the API fills a
// new operation's from its work center or process, and an update leaves out
// what it was not sent.
-const jobOperationInput = baseJobOperationValidator
- .extend({
- workCenterId: zfd.text(z.string().optional()),
- jobId: z.string(),
- customFields: customFieldsInput
- })
+const jobOperationFields = baseJobOperationValidator.extend({
+ workCenterId: zfd.text(z.string().optional()),
+ jobId: z.string(),
+ customFields: customFieldsInput
+});
+const jobOperationInput = jobOperationFields.refine(...inspectionPlanRequired);
+// A new operation's id is optional: the table makes one. The bill of process
+// sends its own, so the row it shows before the save keeps its key.
+const newJobOperationInput = jobOperationFields
+ .extend({ id: z.string().min(1).optional() })
.refine(...inspectionPlanRequired);
/**
@@ -2578,7 +2585,7 @@ const jobOperationInput = baseJobOperationValidator
* @mcp
*/
export const createJobOperation = defineServiceFn({
- input: jobOperationInput,
+ input: newJobOperationInput,
permission: { create: "production" },
async run(ctx, input) {
@@ -2596,13 +2603,10 @@ export const createJobOperation = defineServiceFn({
ctx.asSystem.pg,
{ ...operation, companyId: ctx.company.id, createdBy: ctx.auditUserId }
);
- if (insert.error || !insert.data?.id) {
- return ctx.error(
- "internal",
- "Failed to insert job operation",
- insert.error
- );
- }
+ const inserted = unwrap(ctx, insert);
+ if (inserted instanceof CarbonError) return inserted;
+ if (!inserted)
+ return ctx.error("internal", "Failed to insert job operation");
const recalculated = await service.recalculateMaterialMethod(ctx, {
jobId: operation.jobId,
@@ -2610,7 +2614,7 @@ export const createJobOperation = defineServiceFn({
dependencies: true
});
if (recalculated) return recalculated;
- return { id: insert.data.id };
+ return { id: inserted.id };
}
});
@@ -5055,22 +5059,14 @@ export const setProcedureFields = defineServiceFn({
input: z.object({
ids: z.array(z.string()).min(1),
name: z.string().optional(),
- content: z.string().optional(),
+ content: optionalTiptapDoc,
status: z.enum(procedureStatus).optional(),
processId: z.string().optional(),
tags: z.array(z.string()).optional()
}),
permission: { update: "production" },
- async run(ctx, { ids, content, ...fields }) {
- let parsedContent: Json | undefined;
- if (content !== undefined) {
- try {
- parsedContent = JSON.parse(content);
- } catch {
- return ctx.error("validation", "Invalid procedure content");
- }
- }
+ async run(ctx, { ids, content: parsedContent, ...fields }) {
let update = ctx.asCaller.supabase
.from("procedure")
.update({
@@ -7752,7 +7748,7 @@ export const insertJob = defineServiceFn({
quoteId: z.string().optional(),
quoteLineId: z.string().optional(),
modelUploadId: z.string().optional(),
- notes: z.string().optional(),
+ notes: optionalTiptapDoc,
customFields: z.unknown().optional(),
configuration: z.record(z.string(), z.unknown()).optional(),
fixedAssetClassId: z.string().nullable().optional(),
@@ -7811,7 +7807,7 @@ export const createJobOperationStep = defineServiceFn({
input: z.looseObject({
operationId: z.string().min(1),
name: z.string().min(1),
- description: z.string().min(1),
+ description: requiredTiptapDoc,
type: z.enum([
"Task",
"Value",
@@ -7859,7 +7855,7 @@ export const updateJobOperationStep = defineServiceFn({
.looseObject({
operationId: z.string().min(1),
name: z.string().min(1),
- description: z.string().min(1),
+ description: requiredTiptapDoc,
type: z.enum([
"Task",
"Value",
@@ -8259,7 +8255,7 @@ export const createProcedure = defineServiceFn({
name: z.string().min(1),
version: z.number().min(0),
processId: z.string().optional(),
- content: z.string().optional(),
+ content: optionalTiptapDoc,
copyFromId: z.string().optional(),
id: z
.string()
@@ -8292,7 +8288,7 @@ export const updateProcedure = defineServiceFn({
name: z.string().min(1),
version: z.number().min(0),
processId: z.string().optional(),
- content: z.string().optional(),
+ content: optionalTiptapDoc,
copyFromId: z.string().optional(),
id: z
.string()
@@ -8324,7 +8320,7 @@ export const createProcedureStep = defineServiceFn({
input: z.looseObject({
procedureId: z.string().min(1),
name: z.string().min(1),
- description: z.string().optional(),
+ description: optionalTiptapDoc,
type: z.enum([
"Task",
"Value",
@@ -8371,7 +8367,7 @@ export const updateProcedureStep = defineServiceFn({
.looseObject({
procedureId: z.string().min(1),
name: z.string().min(1),
- description: z.string().optional(),
+ description: optionalTiptapDoc,
type: z.enum([
"Task",
"Value",
@@ -9513,7 +9509,7 @@ export const upsertAssemblyInstructionStep = defineServiceFn({
"Inspection"
])
.optional(),
- description: z.unknown().optional(),
+ description: optionalTiptapDoc,
required: z.boolean().optional(),
unitOfMeasureCode: z.string().nullable().optional(),
minValue: z.number().nullable().optional(),
@@ -9787,7 +9783,7 @@ export const insertAssemblyInstructionStep = defineServiceFn({
"Inspection"
])
.optional(),
- description: z.unknown().optional(),
+ description: optionalTiptapDoc,
required: z.boolean().optional(),
unitOfMeasureCode: z.string().nullable().optional(),
minValue: z.number().nullable().optional(),
diff --git a/apps/erp/app/modules/production/production.service.ts b/apps/erp/app/modules/production/production.service.ts
index 6db1c26e3b..fe89ae04c0 100644
--- a/apps/erp/app/modules/production/production.service.ts
+++ b/apps/erp/app/modules/production/production.service.ts
@@ -4152,7 +4152,8 @@ export async function upsertJob(
export async function upsertJobMaterial(
client: SupabaseClient<Database>,
jobMaterial:
- | (z.infer<typeof jobMaterialValidator> & {
+ | (Omit<z.infer<typeof jobMaterialValidator>, "id"> & {
+ id?: string;
jobId: string;
jobOperationId?: string;
companyId: string;
@@ -4198,7 +4199,8 @@ export async function upsertJobOperation(
client: SupabaseClient<Database>,
db: Kysely<KyselyDatabase>,
jobOperation:
- | (z.infer<typeof jobOperationValidator> & {
+ | (Omit<z.infer<typeof jobOperationValidator>, "id"> & {
+ id?: string;
jobId: string;
companyId: string;
createdBy: string;
diff --git a/apps/erp/app/modules/purchasing/purchasing.server.ts b/apps/erp/app/modules/purchasing/purchasing.server.ts
index d0dadfa081..27386fc681 100644
--- a/apps/erp/app/modules/purchasing/purchasing.server.ts
+++ b/apps/erp/app/modules/purchasing/purchasing.server.ts
@@ -65,6 +65,7 @@ import {
getCompany,
getCompanySettings
} from "~/modules/settings/settings.service";
+import { optionalTiptapDoc } from "~/modules/shared/shared.models";
import {
getLocationTimeZone,
invokePosting,
@@ -5266,8 +5267,8 @@ export const insertPurchaseOrder = defineServiceFn({
supplierQuoteId: z.string().optional(),
receiptRequestedDate: z.string().optional(),
supplierReference: z.string().optional(),
- notes: z.unknown().optional(),
- externalNotes: z.unknown().optional(),
+ notes: optionalTiptapDoc,
+ externalNotes: optionalTiptapDoc,
customFields: z.unknown().optional()
}),
permission: { create: "purchasing" },
diff --git a/apps/erp/app/modules/quality/quality.server.ts b/apps/erp/app/modules/quality/quality.server.ts
index 43717ee5ad..4e652ba31a 100644
--- a/apps/erp/app/modules/quality/quality.server.ts
+++ b/apps/erp/app/modules/quality/quality.server.ts
@@ -31,6 +31,7 @@ import {
setPurchaseReturnOrderLineTrackedEntities,
upsertPurchaseReturnOrderLine
} from "~/modules/purchasing/purchasing.service";
+import { optionalTiptapDoc } from "~/modules/shared/shared.models";
import {
getLocationTimeZone,
invokePosting,
@@ -273,7 +274,8 @@ export const updateIssueField = defineServiceFn({
"closeDate",
"quantity"
]),
- value: z.string().nullish()
+ // A list field takes a list, or the form's comma-separated text.
+ value: z.union([z.string(), z.array(z.string())]).nullish()
}),
permission: { update: "quality" },
@@ -300,10 +302,12 @@ export const updateIssueField = defineServiceFn({
.update(
unchecked({
[field]: isArrayField
- ? value
- ? value.split(",")
- : []
- : value || null,
+ ? Array.isArray(value)
+ ? value
+ : value
+ ? value.split(",")
+ : []
+ : (Array.isArray(value) ? value.join(",") : value) || null,
updatedBy: ctx.auditUserId,
updatedAt: datetime.timestamp()
})
@@ -3281,7 +3285,7 @@ export const createGaugeCalibrationRecord = defineServiceFn({
calibrationAttempts: z.array(
z.looseObject({ reference: z.number(), actual: z.number() })
),
- notes: z.string().optional(),
+ notes: optionalTiptapDoc,
inspectionStatus: z.enum(["Pass", "Fail"]),
customFields: z.unknown().optional(),
id: z
@@ -3325,7 +3329,7 @@ export const updateGaugeCalibrationRecord = defineServiceFn({
calibrationAttempts: z.array(
z.looseObject({ reference: z.number(), actual: z.number() })
),
- notes: z.string().optional(),
+ notes: optionalTiptapDoc,
inspectionStatus: z.enum(["Pass", "Fail"]),
customFields: z.unknown().optional(),
id: z
@@ -3697,7 +3701,7 @@ export const createQualityDocument = defineServiceFn({
input: z.looseObject({
name: z.string().min(1),
version: z.number().min(0),
- content: z.string().optional(),
+ content: optionalTiptapDoc,
copyFromId: z.string().optional(),
id: z
.string()
@@ -3736,7 +3740,7 @@ export const updateQualityDocument = defineServiceFn({
.looseObject({
name: z.string().min(1),
version: z.number().min(0),
- content: z.string().optional(),
+ content: optionalTiptapDoc,
copyFromId: z.string().optional(),
id: z
.string()
diff --git a/apps/erp/app/modules/resources/resources.server.ts b/apps/erp/app/modules/resources/resources.server.ts
index 73e45e7919..12abe57432 100644
--- a/apps/erp/app/modules/resources/resources.server.ts
+++ b/apps/erp/app/modules/resources/resources.server.ts
@@ -16,6 +16,7 @@ import { z } from "zod";
import { zfd } from "zod-form-data";
import { notifyScheduleInputsChanged } from "~/modules/production/production.service";
import { getCompany } from "~/modules/settings/settings.service";
+import { optionalTiptapDoc } from "~/modules/shared/shared.models";
import {
invalidateLocationTimeZone,
refuseUnlessOwned
@@ -688,18 +689,13 @@ export const updateMaintenanceSchedule = defineServiceFn({
* @mcp
*/
export const createMaintenanceDispatch = defineServiceFn({
- input: maintenanceDispatchValidator,
+ input: maintenanceDispatchValidator.extend({
+ content: optionalTiptapDoc
+ }),
permission: { create: "resources" },
async run(ctx, input) {
- let content: Json | undefined;
- if (input.content) {
- try {
- content = JSON.parse(input.content);
- } catch {
- return ctx.error("validation", "The dispatch notes are not valid");
- }
- }
+ const content: Json | undefined = input.content;
const result = await service.insertMaintenanceDispatch(
ctx.asCaller.supabase,
@@ -3335,7 +3331,7 @@ export const updatePartner = defineServiceFn({
export const createTraining = defineServiceFn({
input: z.looseObject({
name: z.string().min(1),
- content: z.string().optional(),
+ content: optionalTiptapDoc,
grantsAbilityId: z.string().optional(),
id: z
.string()
@@ -3366,7 +3362,7 @@ export const updateTraining = defineServiceFn({
input: z
.looseObject({
name: z.string().min(1),
- content: z.string().optional(),
+ content: optionalTiptapDoc,
grantsAbilityId: z.string().optional(),
id: z
.string()
diff --git a/apps/erp/app/modules/sales/sales.models.ts b/apps/erp/app/modules/sales/sales.models.ts
index 60833c4cfc..b04c124c63 100644
--- a/apps/erp/app/modules/sales/sales.models.ts
+++ b/apps/erp/app/modules/sales/sales.models.ts
@@ -21,6 +21,7 @@ import { currencyCodes } from "../accounting/types";
import {
incoterms,
itemType,
+ jsonInput,
methodItemType,
methodOperationOrders,
methodType,
@@ -351,16 +352,6 @@ export const priceResolutionInputValidator = z.object({
configuration: z.record(z.string(), z.unknown()).optional()
});
-const parseJsonField = (value: unknown) => {
- if (typeof value !== "string") return value;
- if (value.trim() === "") return undefined;
- try {
- return JSON.parse(value);
- } catch {
- return value;
- }
-};
-
// One step of how a price was resolved — the shape of PriceTraceStep (types.ts).
export const priceTraceStepValidator = z.object({
step: z.string(),
@@ -399,8 +390,7 @@ export const pricingRuleValidator = z
validTo: zfd.text(z.string().optional()),
priority: zfd.numeric(z.number().int().min(0).optional().default(0)),
active: zfd.checkbox(),
- configurationPrices: z.preprocess(
- parseJsonField,
+ configurationPrices: jsonInput(
z.array(pricingRuleConfigurationPriceValidator).optional()
)
})
@@ -515,9 +505,9 @@ export const quoteLineValidator = z.object({
taxPercent: zfd.numeric(
z.number().min(0).max(1, { message: "Tax percent must be between 0 and 1" })
),
- internalNotes: z.any().optional(),
- externalNotes: z.any().optional(),
- configuration: z.any().optional()
+ internalNotes: optionalTiptapDoc,
+ externalNotes: optionalTiptapDoc,
+ configuration: jsonInput(z.record(z.string(), z.any()).nullable().optional())
});
export const quoteMaterialValidator = z
@@ -1004,14 +994,12 @@ export const salesOrderLineValidator = z
unitPrice: zfd.numeric(z.number().optional()),
exchangeRate: zfd.numeric(z.number().optional()),
// Configurator values keyed by configurationParameter key, posted as JSON.
- configuration: z.preprocess(
- parseJsonField,
+ configuration: jsonInput(
z.record(z.string(), z.any()).nullable().optional()
),
// How unitPrice was resolved, posted as JSON; "null" clears it when the
// price was typed rather than resolved.
- priceTrace: z.preprocess(
- parseJsonField,
+ priceTrace: jsonInput(
z.array(priceTraceStepValidator).nullable().optional()
)
})
diff --git a/apps/erp/app/modules/sales/sales.server.ts b/apps/erp/app/modules/sales/sales.server.ts
index b7cfbf82be..98200c1113 100644
--- a/apps/erp/app/modules/sales/sales.server.ts
+++ b/apps/erp/app/modules/sales/sales.server.ts
@@ -49,7 +49,8 @@ import {
} from "~/modules/settings/settings.service";
import {
inspectionPlanRequired,
- optionalTiptapDoc
+ optionalTiptapDoc,
+ requiredTiptapDoc
} from "~/modules/shared/shared.models";
import {
getCompanyTimeZone,
@@ -150,9 +151,9 @@ export const createSalesRfq = defineServiceFn({
lines: z
.array(
z.object({
- partNumber: z.coerce.string().nullish(),
- description: z.coerce.string().nullish(),
- quantity: z.coerce.number().nullish()
+ partNumber: z.coerce.string<string>().nullish(),
+ description: z.coerce.string<string>().nullish(),
+ quantity: z.coerce.number<number>().nullish()
})
)
.default([]),
@@ -3087,7 +3088,7 @@ const quoteMaterialInput = z.object({
* @mcp
*/
export const createQuoteMaterial = defineServiceFn({
- input: quoteMaterialInput,
+ input: quoteMaterialInput.extend({ id: z.string().min(1).optional() }),
permission: { create: "sales" },
async run(ctx, { customFields, ...material }) {
@@ -3279,12 +3280,17 @@ export const deleteQuoteMaterialsAndReprice = defineServiceFn({
// The bill of process form requires times, units and rates; the API fills a
// new operation's from its work center or process, and an update leaves out
// what it was not sent.
-const quoteOperationInput = baseQuoteOperationValidator
- .extend({
- quoteId: z.string(),
- quoteLineId: z.string(),
- customFields: customFieldValues.optional()
- })
+const quoteOperationFields = baseQuoteOperationValidator.extend({
+ quoteId: z.string(),
+ quoteLineId: z.string(),
+ customFields: customFieldValues.optional()
+});
+const quoteOperationInput = quoteOperationFields.refine(
+ ...inspectionPlanRequired
+);
+// A new operation's id is optional: the table makes one.
+const newQuoteOperationInput = quoteOperationFields
+ .extend({ id: z.string().min(1).optional() })
.refine(...inspectionPlanRequired);
/**
@@ -3300,7 +3306,7 @@ const quoteOperationInput = baseQuoteOperationValidator
* @mcp
*/
export const createQuoteOperation = defineServiceFn({
- input: quoteOperationInput,
+ input: newQuoteOperationInput,
permission: { create: "sales" },
async run(ctx, { customFields, ...input }) {
@@ -3320,15 +3326,11 @@ export const createQuoteOperation = defineServiceFn({
createdBy: ctx.auditUserId,
customFields
});
- if (inserted.error || !inserted.data?.id) {
- return ctx.error(
- "internal",
- "Failed to insert quote operation",
- inserted.error
- );
- }
+ const row = unwrap(ctx, inserted);
+ if (row instanceof CarbonError) return row;
+ if (!row) return ctx.error("internal", "Failed to insert quote operation");
await service.repriceQuoteLine(ctx, { quoteId, quoteLineId });
- return { id: inserted.data.id };
+ return { id: row.id };
}
});
@@ -7915,7 +7917,7 @@ export const createQuoteOperationStep = defineServiceFn({
input: z.looseObject({
operationId: z.string().min(1),
name: z.string().min(1),
- description: z.string().min(1),
+ description: requiredTiptapDoc,
type: z.enum([
"Task",
"Value",
@@ -7963,7 +7965,7 @@ export const updateQuoteOperationStep = defineServiceFn({
.looseObject({
operationId: z.string().min(1),
name: z.string().min(1),
- description: z.string().min(1),
+ description: requiredTiptapDoc,
type: z.enum([
"Task",
"Value",
diff --git a/apps/erp/app/modules/sales/sales.service.ts b/apps/erp/app/modules/sales/sales.service.ts
index bc0b19ea9c..aea84eb3e6 100644
--- a/apps/erp/app/modules/sales/sales.service.ts
+++ b/apps/erp/app/modules/sales/sales.service.ts
@@ -5395,7 +5395,8 @@ export async function upsertQuoteLineMethod(
export async function upsertQuoteMaterial(
client: SupabaseClient<Database>,
quoteMaterial:
- | (z.infer<typeof quoteMaterialValidator> & {
+ | (Omit<z.infer<typeof quoteMaterialValidator>, "id"> & {
+ id?: string;
quoteId: string;
quoteLineId: string;
quoteOperationId?: string;
diff --git a/apps/erp/app/modules/shared/shared.models.test.ts b/apps/erp/app/modules/shared/shared.models.test.ts
index 7b902ba0d0..2ae3928a99 100644
--- a/apps/erp/app/modules/shared/shared.models.test.ts
+++ b/apps/erp/app/modules/shared/shared.models.test.ts
@@ -4,11 +4,15 @@
import { TiptapText } from "@carbon/files/markdown";
import { describe, expect, it } from "vitest";
+import { z } from "zod";
import {
+ booleanField,
+ jsonInput,
normalizeOperationSourceIds,
operationStepValidator,
optionalPlainTextDoc,
optionalTiptapDoc,
+ requiredTiptapDoc,
toTiptapDoc
} from "./shared.models";
@@ -285,3 +289,63 @@ describe("operationStepValidator list options", () => {
).toBe(true);
});
});
+
+// An API caller sends JSON values; a form sends text. Each input helper takes
+// both and gives the code the same value.
+
+describe("requiredTiptapDoc", () => {
+ it("stores Markdown text and a document alike as a document", () => {
+ expect(requiredTiptapDoc.parse("hi")).toEqual(doc);
+ expect(requiredTiptapDoc.parse(doc)).toEqual(doc);
+ });
+
+ it("reads a document sent as JSON text as that document", () => {
+ expect(requiredTiptapDoc.parse(JSON.stringify(doc))).toEqual(doc);
+ });
+
+ it("refuses an empty value", () => {
+ expect(requiredTiptapDoc.safeParse(" ").success).toBe(false);
+ expect(requiredTiptapDoc.safeParse(undefined).success).toBe(false);
+ });
+});
+
+describe("jsonInput", () => {
+ const schema = z.object({
+ configuration: jsonInput(
+ z.record(z.string(), z.any()).nullable().optional()
+ )
+ });
+
+ it("takes the value itself or the form's JSON text", () => {
+ expect(schema.parse({ configuration: { size: 2 } })).toEqual({
+ configuration: { size: 2 }
+ });
+ expect(schema.parse({ configuration: '{"size":2}' })).toEqual({
+ configuration: { size: 2 }
+ });
+ });
+
+ it("reads empty text as no value", () => {
+ expect(schema.parse({ configuration: "" })).toEqual({});
+ });
+
+ it("refuses text that is not the value", () => {
+ expect(schema.safeParse({ configuration: "size=2" }).success).toBe(false);
+ });
+});
+
+describe("booleanField", () => {
+ it.each([
+ [true, true],
+ [false, false],
+ ["true", true],
+ ["false", false]
+ ])("reads %s as %s", (value, expected) => {
+ expect(booleanField().parse(value)).toBe(expected);
+ });
+
+ it("refuses anything else", () => {
+ expect(booleanField().safeParse("yes").success).toBe(false);
+ expect(booleanField().safeParse(undefined).success).toBe(false);
+ });
+});
diff --git a/apps/erp/app/modules/shared/shared.models.ts b/apps/erp/app/modules/shared/shared.models.ts
index 19ccccd64f..4deee83e02 100644
--- a/apps/erp/app/modules/shared/shared.models.ts
+++ b/apps/erp/app/modules/shared/shared.models.ts
@@ -157,6 +157,33 @@ export type OperationType = (typeof operationTypes)[number];
// The same holds for the work center: Outside Processing runs at the supplier,
// and a work center left over from an in-house type put the operation on the
// MES Work Centers board.
+/**
+ * A yes/no field. An API caller sends a JSON boolean and a form posts
+ * `"true"` / `"false"`; both parse to a boolean. Typed as taking a boolean, so
+ * the published API schema says `boolean`: the form's strings are its own.
+ */
+export const booleanField = () =>
+ z.preprocess(
+ (value) => (value === "true" ? true : value === "false" ? false : value),
+ z.boolean()
+ ) as unknown as z.ZodType<boolean, boolean>;
+
+/**
+ * A JSON value. A form posts it as text in a hidden field; an API caller sends
+ * the value itself. Typed as the value, so the published API schema describes
+ * it instead of "anything". Text that is not JSON is left for `schema` to refuse.
+ */
+export const jsonInput = <T extends z.ZodTypeAny>(schema: T) =>
+ z.preprocess((value) => {
+ if (typeof value !== "string") return value;
+ if (value.trim() === "") return undefined;
+ try {
+ return JSON.parse(value);
+ } catch {
+ return value;
+ }
+ }, schema) as unknown as T;
+
export function normalizeOperationSourceIds<
T extends {
operationType?: string;
@@ -299,6 +326,11 @@ export const optionalTiptapDoc = tiptapDocInput();
*/
export const optionalPlainTextDoc = tiptapDocInput("text");
+/** Required rich text: Markdown, or a Tiptap document. */
+export const requiredTiptapDoc = z
+ .union([z.string().trim().min(1), tiptapDocumentInput])
+ .transform((value): any => toTiptapDoc(value));
+
/**
* A List step's options. Blank rows (the empty row "Add option" leaves) are
* dropped before the step's refine runs, so a trailing empty row never blocks a
diff --git a/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json b/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json
index 420f1266f3..493eaa0bfa 100644
--- a/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json
+++ b/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json
@@ -10,7 +10,7 @@
{"name":"accounting_createDepreciationRun","classification":"WRITE","schema":"9401c1cd4d61","response":"20eda0d52ae4","permission":"accounting:create","paginates":false},
{"name":"accounting_createDimension","classification":"DESTRUCTIVE","schema":"9fe9f795f35e","response":"660c8bead643","permission":"accounting:create","paginates":false},
{"name":"accounting_createFiscalYearPeriods","classification":"WRITE","schema":"96bc1e1d05f5","response":"none","permission":"accounting:create","paginates":false},
- {"name":"accounting_createFixedAssetClass","classification":"WRITE","schema":"8889fba12746","response":"3797626bd17e","permission":"accounting:create","paginates":false},
+ {"name":"accounting_createFixedAssetClass","classification":"WRITE","schema":"237efd83a0ef","response":"3797626bd17e","permission":"accounting:create","paginates":false},
{"name":"accounting_createIntercompanyTransaction","classification":"WRITE","schema":"dc8b65b9e82b","response":"3797626bd17e","permission":"accounting:create","paginates":false},
{"name":"accounting_createJournalEntry","classification":"WRITE","schema":"31b84d65b2ac","response":"3797626bd17e","permission":"accounting:create","paginates":false},
{"name":"accounting_createPaymentTerm","classification":"WRITE","schema":"7f289a52d7a3","response":"3797626bd17e","permission":"accounting:create","paginates":false},
@@ -134,7 +134,7 @@
{"name":"accounting_updateDimension","classification":"DESTRUCTIVE","schema":"bc296a45be9e","response":"660c8bead643","permission":"accounting:update","paginates":false},
{"name":"accounting_updateFiscalYearSettings","classification":"WRITE","schema":"fb433e35b233","response":"bcde375ebd4c","permission":"accounting:update","paginates":false},
{"name":"accounting_updateFixedAsset","classification":"WRITE","schema":"7cf19679ef1c","response":"3797626bd17e","permission":"accounting:update","paginates":false},
- {"name":"accounting_updateFixedAssetClass","classification":"WRITE","schema":"7f8214d1083f","response":"3797626bd17e","permission":"accounting:update","paginates":false},
+ {"name":"accounting_updateFixedAssetClass","classification":"WRITE","schema":"cf8e3c6f398f","response":"3797626bd17e","permission":"accounting:update","paginates":false},
{"name":"accounting_updatePaymentTerm","classification":"WRITE","schema":"c587f43c70ec","response":"3797626bd17e","permission":"accounting:update","paginates":false},
{"name":"accounting_updateProject","classification":"WRITE","schema":"a7f9ae38f142","response":"3797626bd17e","permission":"accounting:update","paginates":false},
{"name":"accounting_updateReportView","classification":"WRITE","schema":"1a8d77edd96c","response":"47a0e7255225","permission":"accounting:update","paginates":false},
@@ -164,7 +164,7 @@
{"name":"inventory_createShipment","classification":"WRITE","schema":"40665d54c304","response":"3797626bd17e","permission":"inventory:create","paginates":false},
{"name":"inventory_createShippingMethod","classification":"WRITE","schema":"35c841d658b9","response":"3797626bd17e","permission":"inventory:create","paginates":false},
{"name":"inventory_createStockTransfer","classification":"WRITE","schema":"d2eae4a05698","response":"8db339addf8f","permission":"inventory:create","paginates":false},
- {"name":"inventory_createStockTransferLine","classification":"WRITE","schema":"61a124703a26","response":"3797626bd17e","permission":"inventory:create","paginates":false},
+ {"name":"inventory_createStockTransferLine","classification":"WRITE","schema":"0a096156ace8","response":"3797626bd17e","permission":"inventory:create","paginates":false},
{"name":"inventory_createStorageType","classification":"WRITE","schema":"dac43048240a","response":"3797626bd17e","permission":"parts:create","paginates":false},
{"name":"inventory_createStorageUnit","classification":"WRITE","schema":"8dc350e360ad","response":"3797626bd17e","permission":"inventory:create","paginates":false},
{"name":"inventory_createWarehouseTransferLine","classification":"WRITE","schema":"1c4aec41902a","response":"3797626bd17e","permission":"inventory:update","paginates":false},
@@ -283,15 +283,15 @@
{"name":"inventory_updateInventoryCountLine","classification":"WRITE","schema":"e59c475ac625","response":"3797626bd17e","permission":"inventory:update","paginates":false},
{"name":"inventory_updateInventoryCountStatus","classification":"WRITE","schema":"7ef2505ff688","response":"7ef2505ff688","permission":"inventory:update","paginates":false},
{"name":"inventory_updateKanban","classification":"WRITE","schema":"78797e4ff232","response":"3797626bd17e","permission":"inventory:update","paginates":false},
- {"name":"inventory_updatePickingList","classification":"WRITE","schema":"cb8e9e110bfa","response":"0a4ec3e7319b","permission":"inventory:update","paginates":false},
+ {"name":"inventory_updatePickingList","classification":"WRITE","schema":"a4d7ff25aa62","response":"0a4ec3e7319b","permission":"inventory:update","paginates":false},
{"name":"inventory_updateReceipt","classification":"WRITE","schema":"02e274bc337e","response":"3797626bd17e","permission":"inventory:update","paginates":false},
- {"name":"inventory_updateReceiptFixedAssetLine","classification":"WRITE","schema":"a7515d002c5d","response":"3797626bd17e","permission":"inventory:update","paginates":false},
+ {"name":"inventory_updateReceiptFixedAssetLine","classification":"WRITE","schema":"5bcbd680831b","response":"3797626bd17e","permission":"inventory:update","paginates":false},
{"name":"inventory_updateReceiptLines","classification":"WRITE","schema":"3a91317efcce","response":"0eb0c2be01ed","permission":"inventory:update","paginates":false},
{"name":"inventory_updateShipment","classification":"WRITE","schema":"14ecca1fc57d","response":"3797626bd17e","permission":"inventory:update","paginates":false},
- {"name":"inventory_updateShipmentFixedAssetLine","classification":"WRITE","schema":"ab168f9d9366","response":"3797626bd17e","permission":"inventory:update","paginates":false},
+ {"name":"inventory_updateShipmentFixedAssetLine","classification":"WRITE","schema":"7e62c1ad15f9","response":"3797626bd17e","permission":"inventory:update","paginates":false},
{"name":"inventory_updateShipmentLines","classification":"WRITE","schema":"3a4fe03b9c85","response":"0eb0c2be01ed","permission":"inventory:update","paginates":false},
{"name":"inventory_updateShippingMethod","classification":"WRITE","schema":"1b5e5991be6c","response":"3797626bd17e","permission":"inventory:update","paginates":false},
- {"name":"inventory_updateStockTransferLine","classification":"WRITE","schema":"3577763da43f","response":"3797626bd17e","permission":"inventory:create+update","paginates":false},
+ {"name":"inventory_updateStockTransferLine","classification":"WRITE","schema":"ac37438bc69d","response":"3797626bd17e","permission":"inventory:create+update","paginates":false},
{"name":"inventory_updateStockTransferLines","classification":"WRITE","schema":"17ef89b7d868","response":"0eb0c2be01ed","permission":"inventory:update","paginates":false},
{"name":"inventory_updateStorageType","classification":"WRITE","schema":"7b9e512cc925","response":"3797626bd17e","permission":"parts:update","paginates":false},
{"name":"inventory_updateStorageUnit","classification":"WRITE","schema":"62405012c8e5","response":"3797626bd17e","permission":"inventory:update","paginates":false},
@@ -306,7 +306,7 @@
{"name":"invoicing_applyCreditsToInvoices","classification":"DESTRUCTIVE","schema":"44fe03d8575b","response":"none","permission":"invoicing:update","paginates":false},
{"name":"invoicing_createMemo","classification":"WRITE","schema":"dcabfad9d03c","response":"1e0d0fa1a854","permission":"invoicing:create","paginates":false},
{"name":"invoicing_createPayment","classification":"WRITE","schema":"655768d847ef","response":"9afa42aa85f3","permission":"invoicing:create","paginates":false},
- {"name":"invoicing_createPurchaseInvoice","classification":"WRITE","schema":"9de21d765491","response":"24b4b1602470","permission":"invoicing:create","paginates":false},
+ {"name":"invoicing_createPurchaseInvoice","classification":"WRITE","schema":"647eed933101","response":"24b4b1602470","permission":"invoicing:create","paginates":false},
{"name":"invoicing_createPurchaseInvoiceFromPurchaseOrder","classification":"WRITE","schema":"47850e9f092b","response":"873673b16fc8","permission":"invoicing:create","paginates":false},
{"name":"invoicing_createPurchaseInvoiceLine","classification":"WRITE","schema":"d8628a901bbc","response":"3797626bd17e","permission":"invoicing:create","paginates":false},
{"name":"invoicing_createSalesInvoiceFromSalesOrder","classification":"WRITE","schema":"6e4655763b3f","response":"873673b16fc8","permission":"invoicing:create","paginates":false},
@@ -388,7 +388,7 @@
{"name":"items_addItemPredecessor","classification":"WRITE","schema":"62c99356d14b","response":"c838ffde6390","permission":"parts:update","paginates":false},
{"name":"items_assertMethodOperationIsDraft","classification":"WRITE","schema":"3561ad8e0d42","response":"c407a9edb930","permission":"parts:update","paginates":false},
{"name":"items_copyMethod","classification":"DESTRUCTIVE","schema":"149990a9b059","response":"d12019e0a561","permission":"parts:update","paginates":false},
- {"name":"items_createChangeNotice","classification":"WRITE","schema":"4ba09c051d82","response":"8e58a21e4c94","permission":"parts:create","paginates":false},
+ {"name":"items_createChangeNotice","classification":"WRITE","schema":"24261bc023cf","response":"8e58a21e4c94","permission":"parts:create","paginates":false},
{"name":"items_createChangeNoticeForItem","classification":"WRITE","schema":"4fe1ddc95e07","response":"a443ac9aa1f1","permission":"parts:create","paginates":false},
{"name":"items_createChangeNoticeType","classification":"WRITE","schema":"dac43048240a","response":"3797626bd17e","permission":"parts:create","paginates":false},
{"name":"items_createConsumable","classification":"WRITE","schema":"e0ed6a5c0e19","response":"none","permission":"parts:create","paginates":false},
@@ -398,15 +398,15 @@
{"name":"items_createMaterial","classification":"WRITE","schema":"822977f984eb","response":"none","permission":"parts:create","paginates":false},
{"name":"items_createMaterialForm","classification":"WRITE","schema":"67eb529210df","response":"3797626bd17e","permission":"parts:create","paginates":false},
{"name":"items_createMaterialSubstance","classification":"WRITE","schema":"67eb529210df","response":"3797626bd17e","permission":"parts:create","paginates":false},
- {"name":"items_createMethodMaterial","classification":"WRITE","schema":"85baff25f028","response":"3797626bd17e","permission":"parts:create","paginates":false},
+ {"name":"items_createMethodMaterial","classification":"WRITE","schema":"a988e5d27e27","response":"3797626bd17e","permission":"parts:create","paginates":false},
{"name":"items_createMethodOperation","classification":"WRITE","schema":"62965bbd75c5","response":"3797626bd17e","permission":"parts:create","paginates":false},
{"name":"items_createMethodOperationParameter","classification":"WRITE","schema":"e05336a75e66","response":"3797626bd17e","permission":"parts:create","paginates":false},
- {"name":"items_createMethodOperationStep","classification":"WRITE","schema":"8e97b59e9ee0","response":"3797626bd17e","permission":"parts:create","paginates":false},
+ {"name":"items_createMethodOperationStep","classification":"WRITE","schema":"0c92531e7eaa","response":"3797626bd17e","permission":"parts:create","paginates":false},
{"name":"items_createMethodOperationStepSlide","classification":"WRITE","schema":"079dafff0e23","response":"3797626bd17e","permission":"parts:create","paginates":false},
{"name":"items_createMethodOperationTool","classification":"WRITE","schema":"60a5d239cf03","response":"3797626bd17e","permission":"parts:create","paginates":false},
{"name":"items_createMethodVersion","classification":"WRITE","schema":"cd53dc57847a","response":"e83987f24b08","permission":"parts:create","paginates":false},
{"name":"items_createModelUploadUrl","classification":"WRITE","schema":"098974972159","response":"56f546fd3bc7","permission":"parts:create+update","paginates":false},
- {"name":"items_createPart","classification":"WRITE","schema":"4206b71c74bb","response":"baa524ddff70","permission":"parts:create","paginates":false},
+ {"name":"items_createPart","classification":"WRITE","schema":"6ad4831db814","response":"baa524ddff70","permission":"parts:create","paginates":false},
{"name":"items_createPickMethod","classification":"WRITE","schema":"dbe3b3c9dd58","response":"bcde375ebd4c","permission":"parts:create","paginates":false},
{"name":"items_createRevision","classification":"WRITE","schema":"3488d3b3792b","response":"3797626bd17e","permission":"parts:create","paginates":false},
{"name":"items_createService","classification":"WRITE","schema":"8cf44c6e12d3","response":"9b123283f2f8","permission":"parts:create","paginates":false},
@@ -549,7 +549,7 @@
{"name":"items_setMethodMaterialStepLink","classification":"DESTRUCTIVE","schema":"17d57d014843","response":"bcde375ebd4c","permission":"parts:update","paginates":false},
{"name":"items_setMethodOperationToolStepLink","classification":"DESTRUCTIVE","schema":"0205115c2a9c","response":"bcde375ebd4c","permission":"parts:update","paginates":false},
{"name":"items_setMethodOperationWorkInstruction","classification":"WRITE","schema":"72bf0481bc32","response":"3797626bd17e","permission":"parts:update","paginates":false},
- {"name":"items_updateChangeNotice","classification":"WRITE","schema":"bc0a8bcfbdb8","response":"3797626bd17e","permission":"parts:update","paginates":false},
+ {"name":"items_updateChangeNotice","classification":"WRITE","schema":"86a8f9d7647d","response":"3797626bd17e","permission":"parts:update","paginates":false},
{"name":"items_updateChangeNoticeActionOrder","classification":"WRITE","schema":"582d2c771eaa","response":"none","permission":"parts:update","paginates":false},
{"name":"items_updateChangeNoticeActionStatus","classification":"WRITE","schema":"7f9d94960d15","response":"3797626bd17e","permission":"parts:update","paginates":false},
{"name":"items_updateChangeNoticeAffectedItemChangeType","classification":"WRITE","schema":"fd1f74726c79","response":"3797626bd17e","permission":"parts:update","paginates":false},
@@ -569,19 +569,19 @@
{"name":"items_updateMaterialForm","classification":"WRITE","schema":"3b325222ac99","response":"3797626bd17e","permission":"parts:update","paginates":false},
{"name":"items_updateMaterialOrder","classification":"WRITE","schema":"60a7bcc6c0a3","response":"f9f1ba0210e3","permission":"parts:update","paginates":false},
{"name":"items_updateMaterialSubstance","classification":"WRITE","schema":"3b325222ac99","response":"3797626bd17e","permission":"parts:update","paginates":false},
- {"name":"items_updateMethodMaterial","classification":"WRITE","schema":"85baff25f028","response":"3797626bd17e","permission":"parts:create+update","paginates":false},
+ {"name":"items_updateMethodMaterial","classification":"WRITE","schema":"bee0a5c6efe2","response":"3797626bd17e","permission":"parts:create+update","paginates":false},
{"name":"items_updateMethodOperation","classification":"WRITE","schema":"051b779ed99c","response":"3797626bd17e","permission":"parts:create+update","paginates":false},
{"name":"items_updateMethodOperationParameter","classification":"WRITE","schema":"7ab14ae5050b","response":"3797626bd17e","permission":"parts:update","paginates":false},
- {"name":"items_updateMethodOperationStep","classification":"WRITE","schema":"2a34a54df226","response":"3797626bd17e","permission":"parts:update","paginates":false},
+ {"name":"items_updateMethodOperationStep","classification":"WRITE","schema":"ff346e07ed73","response":"3797626bd17e","permission":"parts:update","paginates":false},
{"name":"items_updateMethodOperationStepSlide","classification":"WRITE","schema":"c64f09e0594b","response":"3797626bd17e","permission":"parts:update","paginates":false},
{"name":"items_updateMethodOperationTool","classification":"WRITE","schema":"2285dc35c71d","response":"3797626bd17e","permission":"parts:update","paginates":false},
{"name":"items_updateOperationOrder","classification":"WRITE","schema":"60a7bcc6c0a3","response":"f9f1ba0210e3","permission":"parts:update","paginates":false},
- {"name":"items_updatePart","classification":"WRITE","schema":"4206b71c74bb","response":"3797626bd17e","permission":"parts:update","paginates":false},
+ {"name":"items_updatePart","classification":"WRITE","schema":"6ad4831db814","response":"3797626bd17e","permission":"parts:update","paginates":false},
{"name":"items_updatePickMethod","classification":"WRITE","schema":"dbe3b3c9dd58","response":"bcde375ebd4c","permission":"parts:update","paginates":false},
{"name":"items_updateRevision","classification":"WRITE","schema":"959ca7bb400f","response":"bcde375ebd4c","permission":"parts:update","paginates":false},
{"name":"items_updateService","classification":"WRITE","schema":"c7e9c9249d9e","response":"9b123283f2f8","permission":"parts:update","paginates":false},
{"name":"items_updateSupplierPart","classification":"WRITE","schema":"da1b4d36d0d8","response":"3797626bd17e","permission":"parts:update","paginates":false},
- {"name":"items_updateTool","classification":"WRITE","schema":"5d9952d97f09","response":"3797626bd17e","permission":"parts:update","paginates":false},
+ {"name":"items_updateTool","classification":"WRITE","schema":"1c86779db14e","response":"3797626bd17e","permission":"parts:update","paginates":false},
{"name":"items_updateUnitOfMeasure","classification":"WRITE","schema":"26238fb01c1b","response":"3797626bd17e","permission":"parts:update","paginates":false},
{"name":"items_upsertChangeNoticeRequiredAction","classification":"WRITE","schema":"10095195c05f","response":"3797626bd17e","permission":"parts:create+update","paginates":false},
{"name":"items_upsertConfigurationParameter","classification":"WRITE","schema":"afbee02c34bb","response":"bcde375ebd4c","permission":"parts:create+update","paginates":false},
@@ -663,22 +663,22 @@
{"name":"production_createAssemblyInstructionStepSlide","classification":"WRITE","schema":"079dafff0e23","response":"3797626bd17e","permission":"production:create","paginates":false},
{"name":"production_createBatch","classification":"WRITE","schema":"e4cb11866b3a","response":"d6f069964d23","permission":"production:update","paginates":false},
{"name":"production_createFailureMode","classification":"WRITE","schema":"f51d093840b8","response":"8394fbabd845","permission":"production:create","paginates":false},
- {"name":"production_createJob","classification":"WRITE","schema":"841ed7f7a528","response":"4999bd4be598","permission":"production:create","paginates":false},
+ {"name":"production_createJob","classification":"WRITE","schema":"3b8e4cf245db","response":"4999bd4be598","permission":"production:create","paginates":false},
{"name":"production_createJobDocumentUploadUrl","classification":"WRITE","schema":"685f6d6e5714","response":"4ad76afe0777","permission":"production:create","paginates":false},
- {"name":"production_createJobMaterial","classification":"WRITE","schema":"92eaf1e6fefe","response":"3797626bd17e","permission":"production:create","paginates":false},
- {"name":"production_createJobOperation","classification":"WRITE","schema":"7753bcafccc4","response":"3797626bd17e","permission":"production:create","paginates":false},
+ {"name":"production_createJobMaterial","classification":"WRITE","schema":"e363a929dda5","response":"3797626bd17e","permission":"production:create","paginates":false},
+ {"name":"production_createJobOperation","classification":"WRITE","schema":"040c9b7e3cc2","response":"3797626bd17e","permission":"production:create","paginates":false},
{"name":"production_createJobOperationParameter","classification":"WRITE","schema":"e05336a75e66","response":"3797626bd17e","permission":"production:create","paginates":false},
- {"name":"production_createJobOperationStep","classification":"WRITE","schema":"8e97b59e9ee0","response":"3797626bd17e","permission":"production:create","paginates":false},
+ {"name":"production_createJobOperationStep","classification":"WRITE","schema":"0c92531e7eaa","response":"3797626bd17e","permission":"production:create","paginates":false},
{"name":"production_createJobOperationStepSlide","classification":"WRITE","schema":"079dafff0e23","response":"3797626bd17e","permission":"production:create","paginates":false},
{"name":"production_createJobOperationTool","classification":"WRITE","schema":"60a5d239cf03","response":"3797626bd17e","permission":"production:create","paginates":false},
- {"name":"production_createJobs","classification":"WRITE","schema":"d12e26631b3e","response":"267b4780c1d3","permission":"production:create","paginates":false},
+ {"name":"production_createJobs","classification":"WRITE","schema":"3055e208a444","response":"267b4780c1d3","permission":"production:create","paginates":false},
{"name":"production_createMaintenanceDispatchComment","classification":"WRITE","schema":"0c205f004651","response":"3797626bd17e","permission":"production:create","paginates":false},
{"name":"production_createMaintenanceDispatchEvent","classification":"WRITE","schema":"882b42caf30c","response":"3797626bd17e","permission":"production:create","paginates":false},
{"name":"production_createMaintenanceDispatchItem","classification":"WRITE","schema":"c9df2d5b631f","response":"3797626bd17e","permission":"production:create","paginates":false},
{"name":"production_createMaintenanceSchedule","classification":"WRITE","schema":"2541e4f50141","response":"3797626bd17e","permission":"production:create","paginates":false},
- {"name":"production_createProcedure","classification":"WRITE","schema":"020550cf414d","response":"3797626bd17e","permission":"production:create","paginates":false},
+ {"name":"production_createProcedure","classification":"WRITE","schema":"cc953e756250","response":"3797626bd17e","permission":"production:create","paginates":false},
{"name":"production_createProcedureParameter","classification":"WRITE","schema":"0ea0375d7dd6","response":"3797626bd17e","permission":"production:create","paginates":false},
- {"name":"production_createProcedureStep","classification":"WRITE","schema":"928df9e1694b","response":"3797626bd17e","permission":"production:create","paginates":false},
+ {"name":"production_createProcedureStep","classification":"WRITE","schema":"d6304331b8e7","response":"3797626bd17e","permission":"production:create","paginates":false},
{"name":"production_createProductionEvent","classification":"WRITE","schema":"d55db96dfe94","response":"acb6e3edad0f","permission":"production:create","paginates":false},
{"name":"production_createProductionQuantity","classification":"WRITE","schema":"aeaea19fd65e","response":"3797626bd17e","permission":"production:create","paginates":false},
{"name":"production_createScrapReason","classification":"WRITE","schema":"f51d093840b8","response":"8394fbabd845","permission":"production:create","paginates":false},
@@ -800,8 +800,8 @@
{"name":"production_getWorkCenterRequiredAbilities","classification":"READ","schema":"75b90f67d533","response":"7418ea1fc0a7","permission":"production:view","paginates":false},
{"name":"production_getWorkCenterReservationsRange","classification":"READ","schema":"c310a7ca038d","response":"a7e9bc09d2ab","permission":"production:view","paginates":false},
{"name":"production_getWorkCenterShifts","classification":"READ","schema":"ef138c43c92c","response":"2b4835f80e6c","permission":"production:view","paginates":false},
- {"name":"production_insertAssemblyInstructionStep","classification":"WRITE","schema":"bf4512d170cc","response":"00404e686415","permission":"production:create","paginates":false},
- {"name":"production_insertJob","classification":"WRITE","schema":"f450754aacd3","response":"ad63dfd9d877","permission":"production:create","paginates":false},
+ {"name":"production_insertAssemblyInstructionStep","classification":"WRITE","schema":"0ae0a151262e","response":"00404e686415","permission":"production:create","paginates":false},
+ {"name":"production_insertJob","classification":"WRITE","schema":"3dec87ac6f73","response":"ad63dfd9d877","permission":"production:create","paginates":false},
{"name":"production_makeAssemblySubAssembly","classification":"WRITE","schema":"bd69d909a2e4","response":"00404e686415","permission":"production:update","paginates":false},
{"name":"production_mapAssemblyComponent","classification":"WRITE","schema":"4b0e8ad9fe70","response":"3189c67145d5","permission":"production:update","paginates":false},
{"name":"production_markPersonAbsent","classification":"WRITE","schema":"16a1cd418a2e","response":"3797626bd17e","permission":"production:update","paginates":false},
@@ -810,12 +810,12 @@
{"name":"production_mergeBatchOutputs","classification":"WRITE","schema":"49385ebfc807","response":"305ef06ceb72","permission":"production:update","paginates":false},
{"name":"production_movePerson","classification":"WRITE","schema":"a726aa587ccc","response":"3797626bd17e","permission":"production:update","paginates":false},
{"name":"production_movePersonWeek","classification":"WRITE","schema":"c790955c93cc","response":"3d90cb5d0437","permission":"production:update","paginates":false},
- {"name":"production_moveScheduleJob","classification":"WRITE","schema":"6e18ba72229f","response":"3797626bd17e","permission":"production:update","paginates":false},
+ {"name":"production_moveScheduleJob","classification":"WRITE","schema":"a1d26647e73e","response":"3797626bd17e","permission":"production:update","paginates":false},
{"name":"production_notifyScheduleInputsChanged","classification":"WRITE","schema":"a2cb3b753e9c","response":"b520ca8e3ab4","permission":"production:update","paginates":false},
{"name":"production_orderPlannedJobs","classification":"WRITE","schema":"145543a6765b","response":"2519eb8f6e46","permission":"production:create","paginates":false},
{"name":"production_pauseJob","classification":"WRITE","schema":"4999bd4be598","response":"64aaffa78287","permission":"production:update","paginates":false},
{"name":"production_planJobFromPlanning","classification":"WRITE","schema":"863c89f4ad8e","response":"8e58a21e4c94","permission":"production:update","paginates":false},
- {"name":"production_reassignAssemblyComponents","classification":"DESTRUCTIVE","schema":"71d135315dea","response":"3797626bd17e","permission":"production:update","paginates":false},
+ {"name":"production_reassignAssemblyComponents","classification":"DESTRUCTIVE","schema":"3614ea28d76c","response":"3797626bd17e","permission":"production:update","paginates":false},
{"name":"production_recalculateJobRequirements","classification":"WRITE","schema":"7f8214d1083f","response":"9e056a59d695","permission":"production:update","paginates":false},
{"name":"production_reconvertAssemblyModel","classification":"DESTRUCTIVE","schema":"3797626bd17e","response":"277f7d872d8c","permission":"production:update","paginates":false},
{"name":"production_releaseBatches","classification":"WRITE","schema":"b6b41ae3a2b7","response":"340a1cb28ff4","permission":"production:update","paginates":false},
@@ -840,9 +840,9 @@
{"name":"production_setJobQuantity","classification":"WRITE","schema":"14db87743cc7","response":"0eb0c2be01ed","permission":"production:update","paginates":false},
{"name":"production_setJobSalesOrderLine","classification":"WRITE","schema":"9b91d34f8382","response":"0eb0c2be01ed","permission":"production:update","paginates":false},
{"name":"production_setPeopleOvertime","classification":"WRITE","schema":"89851b04ba54","response":"393a0d83325c","permission":"production:update","paginates":false},
- {"name":"production_setPersonDay","classification":"WRITE","schema":"b2bcad277f44","response":"3d90cb5d0437","permission":"production:update","paginates":false},
+ {"name":"production_setPersonDay","classification":"WRITE","schema":"b610d345119b","response":"3d90cb5d0437","permission":"production:update","paginates":false},
{"name":"production_setPersonHours","classification":"WRITE","schema":"c99328071885","response":"3797626bd17e","permission":"production:update","paginates":false},
- {"name":"production_setProcedureFields","classification":"WRITE","schema":"e76f126b5b16","response":"0eb0c2be01ed","permission":"production:update","paginates":false},
+ {"name":"production_setProcedureFields","classification":"WRITE","schema":"9594e06855e0","response":"0eb0c2be01ed","permission":"production:update","paginates":false},
{"name":"production_syncAssemblyToOperation","classification":"DESTRUCTIVE","schema":"da43bcac38a0","response":"4348d3bad80b","permission":"production:update","paginates":false},
{"name":"production_syncJobOperationProcedure","classification":"WRITE","schema":"4db296880a62","response":"c407a9edb930","permission":"production:update","paginates":false},
{"name":"production_unassignPerson","classification":"DESTRUCTIVE","schema":"3797626bd17e","response":"3797626bd17e","permission":"production:update","paginates":false},
@@ -860,12 +860,12 @@
{"name":"production_updateBatch","classification":"WRITE","schema":"c54fb480a6d1","response":"979f64cb9229","permission":"production:update","paginates":false},
{"name":"production_updateFailureMode","classification":"WRITE","schema":"afedffe2be69","response":"8394fbabd845","permission":"production:update","paginates":false},
{"name":"production_updateJobBatchNumber","classification":"WRITE","schema":"6e1e7ec3a9f5","response":"f7a40899c090","permission":"production:update","paginates":false},
- {"name":"production_updateJobDetails","classification":"WRITE","schema":"bcbce6ae7798","response":"3797626bd17e","permission":"production:update","paginates":false},
+ {"name":"production_updateJobDetails","classification":"WRITE","schema":"5dd741869118","response":"3797626bd17e","permission":"production:update","paginates":false},
{"name":"production_updateJobMaterial","classification":"WRITE","schema":"92eaf1e6fefe","response":"4ea32bd70246","permission":"production:create","paginates":false},
{"name":"production_updateJobMaterialOrder","classification":"WRITE","schema":"60a7bcc6c0a3","response":"60cd1f553572","permission":"production:update","paginates":false},
{"name":"production_updateJobOperation","classification":"WRITE","schema":"7753bcafccc4","response":"3797626bd17e","permission":"production:create","paginates":false},
{"name":"production_updateJobOperationParameter","classification":"WRITE","schema":"7ab14ae5050b","response":"3797626bd17e","permission":"production:update","paginates":false},
- {"name":"production_updateJobOperationStep","classification":"WRITE","schema":"2a34a54df226","response":"3797626bd17e","permission":"production:update","paginates":false},
+ {"name":"production_updateJobOperationStep","classification":"WRITE","schema":"ff346e07ed73","response":"3797626bd17e","permission":"production:update","paginates":false},
{"name":"production_updateJobOperationStepOrder","classification":"WRITE","schema":"33fd534d3ffe","response":"60cd1f553572","permission":"production:update","paginates":false},
{"name":"production_updateJobOperationStepSlide","classification":"WRITE","schema":"c64f09e0594b","response":"3797626bd17e","permission":"production:update","paginates":false},
{"name":"production_updateJobOperationTool","classification":"WRITE","schema":"2285dc35c71d","response":"3797626bd17e","permission":"production:update","paginates":false},
@@ -876,15 +876,15 @@
{"name":"production_updateMaintenanceSchedule","classification":"WRITE","schema":"a71abb3e6290","response":"3797626bd17e","permission":"production:update","paginates":false},
{"name":"production_updateMethodOperationStepOrder","classification":"WRITE","schema":"4289859b65d6","response":"c407a9edb930","permission":"none","paginates":false},
{"name":"production_updatePlannedJob","classification":"WRITE","schema":"36a2dd1a51c5","response":"8e58a21e4c94","permission":"production:update","paginates":false},
- {"name":"production_updateProcedure","classification":"WRITE","schema":"edb9af57e01a","response":"3797626bd17e","permission":"production:update","paginates":false},
+ {"name":"production_updateProcedure","classification":"WRITE","schema":"a560aed14ea9","response":"3797626bd17e","permission":"production:update","paginates":false},
{"name":"production_updateProcedureParameter","classification":"WRITE","schema":"fbaaaf15b2b3","response":"3797626bd17e","permission":"production:update","paginates":false},
- {"name":"production_updateProcedureStep","classification":"WRITE","schema":"549be9a0a0d9","response":"3797626bd17e","permission":"production:update","paginates":false},
+ {"name":"production_updateProcedureStep","classification":"WRITE","schema":"8cad89b901ba","response":"3797626bd17e","permission":"production:update","paginates":false},
{"name":"production_updateProcedureStepOrder","classification":"WRITE","schema":"33fd534d3ffe","response":"60cd1f553572","permission":"production:update","paginates":false},
{"name":"production_updateProductionEvent","classification":"WRITE","schema":"5ae7126208e7","response":"acb6e3edad0f","permission":"production:update","paginates":false},
{"name":"production_updateQuoteOperationStepOrder","classification":"WRITE","schema":"4289859b65d6","response":"c407a9edb930","permission":"none","paginates":false},
{"name":"production_updateScrapReason","classification":"WRITE","schema":"afedffe2be69","response":"8394fbabd845","permission":"production:update","paginates":false},
{"name":"production_upsertAssemblyInstruction","classification":"WRITE","schema":"140b31338c4e","response":"3797626bd17e","permission":"production:create+update","paginates":false},
- {"name":"production_upsertAssemblyInstructionStep","classification":"WRITE","schema":"69932a4f176d","response":"3797626bd17e","permission":"production:create+update","paginates":false},
+ {"name":"production_upsertAssemblyInstructionStep","classification":"WRITE","schema":"eb99ef73a121","response":"3797626bd17e","permission":"production:create+update","paginates":false},
{"name":"production_upsertAssemblyInstructionStepMaterial","classification":"WRITE","schema":"cec21b948809","response":"3797626bd17e","permission":"production:create+update","paginates":false},
{"name":"production_upsertAssemblyInstructionStepTool","classification":"WRITE","schema":"f7254eb12e98","response":"3797626bd17e","permission":"production:create+update","paginates":false},
{"name":"production_upsertAssemblyUnit","classification":"WRITE","schema":"6755e4574f31","response":"3797626bd17e","permission":"production:create+update","paginates":false},
@@ -1001,7 +1001,7 @@
{"name":"purchasing_getSupplierTypes","classification":"READ","schema":"cd40ae40fad5","response":"e0001a83b60b","permission":"purchasing:view","paginates":true},
{"name":"purchasing_getSupplierTypesList","classification":"READ","schema":"31b84d65b2ac","response":"ce08332e0ce6","permission":"purchasing:view","paginates":false},
{"name":"purchasing_insertLease","classification":"WRITE","schema":"55753efdb84c","response":"f6631a819d19","permission":"purchasing:create","paginates":false},
- {"name":"purchasing_insertPurchaseOrder","classification":"WRITE","schema":"b7f7ea3824d5","response":"73785d310369","permission":"purchasing:create","paginates":false},
+ {"name":"purchasing_insertPurchaseOrder","classification":"WRITE","schema":"2c3f044014cd","response":"73785d310369","permission":"purchasing:create","paginates":false},
{"name":"purchasing_insertPurchaseReturnOrder","classification":"WRITE","schema":"8faa8981ada0","response":"d53d13c89312","permission":"purchasing:create","paginates":false},
{"name":"purchasing_insertSupplierContact","classification":"WRITE","schema":"442dcf7c63d4","response":"3797626bd17e","permission":"purchasing:create","paginates":false},
{"name":"purchasing_insertSupplierLocation","classification":"WRITE","schema":"e401ef4fb9c3","response":"3797626bd17e","permission":"purchasing:create","paginates":false},
@@ -1055,13 +1055,13 @@
{"name":"purchasing_upsertPurchasingRFQSuppliers","classification":"DESTRUCTIVE","schema":"769394a6f909","response":"5c9ba5bee3f1","permission":"purchasing:create+update","paginates":false},
{"name":"quality_activateGauge","classification":"DESTRUCTIVE","schema":"059138c6b8da","response":"bcde375ebd4c","permission":"quality:delete+update","paginates":false},
{"name":"quality_completeIssue","classification":"WRITE","schema":"3797626bd17e","response":"3797626bd17e","permission":"quality:update","paginates":false},
- {"name":"quality_createGaugeCalibrationRecord","classification":"WRITE","schema":"9fd203fd91da","response":"3797626bd17e","permission":"quality:create","paginates":false},
+ {"name":"quality_createGaugeCalibrationRecord","classification":"WRITE","schema":"e852f8e8f99a","response":"3797626bd17e","permission":"quality:create","paginates":false},
{"name":"quality_createGaugeType","classification":"WRITE","schema":"f51d093840b8","response":"8394fbabd845","permission":"quality:create","paginates":false},
{"name":"quality_createIssue","classification":"WRITE","schema":"8f4e29a0f4cf","response":"67030fdab724","permission":"quality:create","paginates":false},
{"name":"quality_createIssueAssociation","classification":"WRITE","schema":"6abd32611fef","response":"f16bdda80515","permission":"quality:update","paginates":false},
{"name":"quality_createIssueType","classification":"WRITE","schema":"f51d093840b8","response":"8394fbabd845","permission":"quality:create","paginates":false},
{"name":"quality_createIssueWorkflow","classification":"WRITE","schema":"2ee341acc3e0","response":"3797626bd17e","permission":"quality:create","paginates":false},
- {"name":"quality_createQualityDocument","classification":"WRITE","schema":"9614a292c98d","response":"3797626bd17e","permission":"quality:create","paginates":false},
+ {"name":"quality_createQualityDocument","classification":"WRITE","schema":"6347dad4fdb0","response":"3797626bd17e","permission":"quality:create","paginates":false},
{"name":"quality_createRequiredAction","classification":"WRITE","schema":"f6f70a91c352","response":"8394fbabd845","permission":"quality:create","paginates":false},
{"name":"quality_deactivateGauge","classification":"DESTRUCTIVE","schema":"059138c6b8da","response":"bcde375ebd4c","permission":"quality:delete+update","paginates":false},
{"name":"quality_decideQualityDocumentApproval","classification":"WRITE","schema":"03770b06d8f1","response":"febf01bee291","permission":"quality:update","paginates":false},
@@ -1140,16 +1140,16 @@
{"name":"quality_setIssueTaskStatus","classification":"WRITE","schema":"4b9a245ad2cf","response":"6857d1b1a4e8","permission":"quality:update","paginates":false},
{"name":"quality_setIssueTaskSupplier","classification":"WRITE","schema":"b6b0275e1616","response":"3797626bd17e","permission":"quality:update","paginates":false},
{"name":"quality_updateGauge","classification":"WRITE","schema":"d26a7f29a929","response":"3797626bd17e","permission":"quality:update","paginates":false},
- {"name":"quality_updateGaugeCalibrationRecord","classification":"WRITE","schema":"780ab591e1b5","response":"3797626bd17e","permission":"quality:create+update","paginates":false},
+ {"name":"quality_updateGaugeCalibrationRecord","classification":"WRITE","schema":"c391a732b02f","response":"3797626bd17e","permission":"quality:create+update","paginates":false},
{"name":"quality_updateGaugeType","classification":"WRITE","schema":"afedffe2be69","response":"8394fbabd845","permission":"quality:update","paginates":false},
{"name":"quality_updateInspectionDocumentSampling","classification":"WRITE","schema":"42714a7976eb","response":"bcde375ebd4c","permission":"quality:update","paginates":false},
{"name":"quality_updateIssue","classification":"WRITE","schema":"336ea2add45b","response":"3797626bd17e","permission":"quality:update","paginates":false},
{"name":"quality_updateIssueActionProcesses","classification":"DESTRUCTIVE","schema":"4ddcbb8d1ac6","response":"bcde375ebd4c","permission":"quality:update","paginates":false},
- {"name":"quality_updateIssueField","classification":"WRITE","schema":"8712a26ffddc","response":"0eb0c2be01ed","permission":"quality:update","paginates":false},
+ {"name":"quality_updateIssueField","classification":"WRITE","schema":"f446898eb020","response":"0eb0c2be01ed","permission":"quality:update","paginates":false},
{"name":"quality_updateIssueItemField","classification":"WRITE","schema":"32444013b5c4","response":"3797626bd17e","permission":"quality:update","paginates":false},
{"name":"quality_updateIssueType","classification":"WRITE","schema":"afedffe2be69","response":"8394fbabd845","permission":"quality:update","paginates":false},
{"name":"quality_updateIssueWorkflow","classification":"WRITE","schema":"1f02dc4f3e49","response":"3797626bd17e","permission":"quality:create+update","paginates":false},
- {"name":"quality_updateQualityDocument","classification":"WRITE","schema":"7f1d2f8ce693","response":"3797626bd17e","permission":"quality:update","paginates":false},
+ {"name":"quality_updateQualityDocument","classification":"WRITE","schema":"82b15831f5c8","response":"3797626bd17e","permission":"quality:update","paginates":false},
{"name":"quality_updateQualityDocumentField","classification":"WRITE","schema":"241fb5b89617","response":"0eb0c2be01ed","permission":"quality:update","paginates":false},
{"name":"quality_updateRequiredAction","classification":"WRITE","schema":"84851898a6e5","response":"8394fbabd845","permission":"quality:update","paginates":false},
{"name":"quality_updateRisk","classification":"WRITE","schema":"059e5e53b44b","response":"3797626bd17e","permission":"quality:update","paginates":false},
@@ -1161,14 +1161,14 @@
{"name":"resources_createContractor","classification":"DESTRUCTIVE","schema":"f2767d28cf12","response":"bcde375ebd4c","permission":"resources:create","paginates":false},
{"name":"resources_createFailureMode","classification":"WRITE","schema":"c922337b313e","response":"8394fbabd845","permission":"resources:create","paginates":false},
{"name":"resources_createLocation","classification":"WRITE","schema":"140095be5d68","response":"3797626bd17e","permission":"resources:create","paginates":false},
- {"name":"resources_createMaintenanceDispatch","classification":"WRITE","schema":"629d474dc047","response":"ede36af7307d","permission":"resources:create","paginates":false},
+ {"name":"resources_createMaintenanceDispatch","classification":"WRITE","schema":"de1db649e301","response":"ede36af7307d","permission":"resources:create","paginates":false},
{"name":"resources_createMaintenanceDispatchComment","classification":"WRITE","schema":"0c205f004651","response":"3797626bd17e","permission":"resources:create","paginates":false},
{"name":"resources_createMaintenanceDispatchItem","classification":"WRITE","schema":"bb6dfef16ca0","response":"31c4f3f69c9a","permission":"resources:update","paginates":false},
{"name":"resources_createMaintenanceEvent","classification":"WRITE","schema":"6e76bd1f09c1","response":"8e58a21e4c94","permission":"resources:update","paginates":false},
{"name":"resources_createMaintenanceSchedule","classification":"WRITE","schema":"b84710917cca","response":"3797626bd17e","permission":"resources:create","paginates":false},
{"name":"resources_createPartner","classification":"WRITE","schema":"376ead8bb039","response":"bcde375ebd4c","permission":"resources:create","paginates":false},
{"name":"resources_createProcess","classification":"WRITE","schema":"b8fd049d80e2","response":"3797626bd17e","permission":"resources:create","paginates":false},
- {"name":"resources_createTraining","classification":"WRITE","schema":"627644497b66","response":"3797626bd17e","permission":"resources:create","paginates":false},
+ {"name":"resources_createTraining","classification":"WRITE","schema":"1a78a529f34a","response":"3797626bd17e","permission":"resources:create","paginates":false},
{"name":"resources_createTrainingAssignment","classification":"WRITE","schema":"70b3c1aa623e","response":"3797626bd17e","permission":"resources:create","paginates":false},
{"name":"resources_createTrainingQuestion","classification":"WRITE","schema":"8ec2c941ed74","response":"3797626bd17e","permission":"resources:create","paginates":false},
{"name":"resources_createWorkCenter","classification":"WRITE","schema":"fd853b10d45a","response":"3797626bd17e","permission":"resources:create+update","paginates":false},
@@ -1253,7 +1253,7 @@
{"name":"resources_updatePartner","classification":"WRITE","schema":"376ead8bb039","response":"bcde375ebd4c","permission":"resources:update","paginates":false},
{"name":"resources_updateProcess","classification":"DESTRUCTIVE","schema":"f0e77e52ebff","response":"3797626bd17e","permission":"resources:create+delete+update","paginates":false},
{"name":"resources_updateSuggestionEmoji","classification":"WRITE","schema":"5f9afdcc2556","response":"bcde375ebd4c","permission":"resources:update","paginates":false},
- {"name":"resources_updateTraining","classification":"WRITE","schema":"6097fcf86545","response":"3797626bd17e","permission":"resources:update","paginates":false},
+ {"name":"resources_updateTraining","classification":"WRITE","schema":"ec3c87821182","response":"3797626bd17e","permission":"resources:update","paginates":false},
{"name":"resources_updateTrainingAssignment","classification":"WRITE","schema":"c787b54127d0","response":"3797626bd17e","permission":"resources:update","paginates":false},
{"name":"resources_updateTrainingField","classification":"WRITE","schema":"26fe82ccc9b2","response":"0eb0c2be01ed","permission":"resources:update","paginates":false},
{"name":"resources_updateTrainingQuestion","classification":"WRITE","schema":"f029f3fda91d","response":"3797626bd17e","permission":"resources:update","paginates":false},
@@ -1283,11 +1283,11 @@
{"name":"sales_createOpportunityDocumentUploadUrl","classification":"WRITE","schema":"9d023be224ef","response":"4ad76afe0777","permission":"sales:create","paginates":false},
{"name":"sales_createOpportunityLineDocumentUploadUrl","classification":"WRITE","schema":"89370e60a3e7","response":"4ad76afe0777","permission":"sales:create","paginates":false},
{"name":"sales_createPricingRule","classification":"WRITE","schema":"6b9956ef81b3","response":"3797626bd17e","permission":"sales:create","paginates":false},
- {"name":"sales_createQuoteLine","classification":"WRITE","schema":"f490cabfaa4e","response":"bb48df81da15","permission":"sales:create","paginates":false},
- {"name":"sales_createQuoteMaterial","classification":"WRITE","schema":"8c29d66dac67","response":"8e58a21e4c94","permission":"sales:create","paginates":false},
- {"name":"sales_createQuoteOperation","classification":"WRITE","schema":"bdc2bb4c515e","response":"3797626bd17e","permission":"sales:create","paginates":false},
+ {"name":"sales_createQuoteLine","classification":"WRITE","schema":"dcb267890d2b","response":"bb48df81da15","permission":"sales:create","paginates":false},
+ {"name":"sales_createQuoteMaterial","classification":"WRITE","schema":"1b71bdccd3cc","response":"8e58a21e4c94","permission":"sales:create","paginates":false},
+ {"name":"sales_createQuoteOperation","classification":"WRITE","schema":"c5a4d6656972","response":"3797626bd17e","permission":"sales:create","paginates":false},
{"name":"sales_createQuoteOperationParameter","classification":"WRITE","schema":"e05336a75e66","response":"3797626bd17e","permission":"sales:create","paginates":false},
- {"name":"sales_createQuoteOperationStep","classification":"WRITE","schema":"8e97b59e9ee0","response":"3797626bd17e","permission":"sales:create","paginates":false},
+ {"name":"sales_createQuoteOperationStep","classification":"WRITE","schema":"0c92531e7eaa","response":"3797626bd17e","permission":"sales:create","paginates":false},
{"name":"sales_createQuoteOperationTool","classification":"WRITE","schema":"60a5d239cf03","response":"3797626bd17e","permission":"sales:create","paginates":false},
{"name":"sales_createRentalAgreement","classification":"WRITE","schema":"3d2ec5205417","response":"a443ac9aa1f1","permission":"sales:create","paginates":false},
{"name":"sales_createRentalAgreementCharge","classification":"WRITE","schema":"2084581f9746","response":"3797626bd17e","permission":"sales:create","paginates":false},
@@ -1295,9 +1295,9 @@
{"name":"sales_createReplacementSalesOrder","classification":"WRITE","schema":"3fdcd215dc22","response":"3797626bd17e","permission":"sales:create","paginates":false},
{"name":"sales_createReturnOrderLine","classification":"WRITE","schema":"f0f787b6d728","response":"f9d1513a44f3","permission":"sales:create","paginates":false},
{"name":"sales_createReturnReason","classification":"WRITE","schema":"5607534c1255","response":"3797626bd17e","permission":"sales:create","paginates":false},
- {"name":"sales_createSalesOrderLine","classification":"WRITE","schema":"91896427de3a","response":"8f061af39e95","permission":"sales:create","paginates":false},
+ {"name":"sales_createSalesOrderLine","classification":"WRITE","schema":"1e749569c4c8","response":"8f061af39e95","permission":"sales:create","paginates":false},
{"name":"sales_createSalesReturnOrderCredit","classification":"WRITE","schema":"a752775acc57","response":"00404e686415","permission":"invoicing:create","paginates":false},
- {"name":"sales_createSalesRfq","classification":"WRITE","schema":"38323ad62e6d","response":"0c1a1b93cca3","permission":"sales:create","paginates":false},
+ {"name":"sales_createSalesRfq","classification":"WRITE","schema":"80ed1c7536b4","response":"0c1a1b93cca3","permission":"sales:create","paginates":false},
{"name":"sales_createSalesRFQ","classification":"WRITE","schema":"bd0f125f410c","response":"2e56e1180d37","permission":"sales:create","paginates":false},
{"name":"sales_createSalesRFQLine","classification":"WRITE","schema":"c5b3b3cfaa0d","response":"3797626bd17e","permission":"sales:create","paginates":false},
{"name":"sales_deleteCustomer","classification":"DESTRUCTIVE","schema":"9671bf9bdd53","response":"bcde375ebd4c","permission":"sales:delete","paginates":false},
@@ -1477,7 +1477,7 @@
{"name":"sales_updatePricingRule","classification":"WRITE","schema":"a558835d70d7","response":"3797626bd17e","permission":"sales:update","paginates":false},
{"name":"sales_updateQuoteDetails","classification":"WRITE","schema":"a3980b202b22","response":"c726ae407913","permission":"sales:update","paginates":false},
{"name":"sales_updateQuoteExchangeRate","classification":"WRITE","schema":"222e5249c015","response":"bcde375ebd4c","permission":"sales:update","paginates":false},
- {"name":"sales_updateQuoteLine","classification":"WRITE","schema":"29659b4ffe67","response":"8529f8fc63c9","permission":"sales:create","paginates":false},
+ {"name":"sales_updateQuoteLine","classification":"WRITE","schema":"ff6e832a9c4a","response":"8529f8fc63c9","permission":"sales:create","paginates":false},
{"name":"sales_updateQuoteLineOrder","classification":"WRITE","schema":"323824b4392c","response":"none","permission":"sales:update","paginates":false},
{"name":"sales_updateQuoteLinePrecision","classification":"WRITE","schema":"cf30feb01e5c","response":"none","permission":"sales:update","paginates":false},
{"name":"sales_updateQuoteMaterial","classification":"WRITE","schema":"8c29d66dac67","response":"4ea32bd70246","permission":"sales:create","paginates":false},
@@ -1485,7 +1485,7 @@
{"name":"sales_updateQuoteOperation","classification":"WRITE","schema":"bdc2bb4c515e","response":"3797626bd17e","permission":"sales:create","paginates":false},
{"name":"sales_updateQuoteOperationOrder","classification":"WRITE","schema":"60a7bcc6c0a3","response":"60cd1f553572","permission":"sales:update","paginates":false},
{"name":"sales_updateQuoteOperationParameter","classification":"WRITE","schema":"7ab14ae5050b","response":"3797626bd17e","permission":"sales:update","paginates":false},
- {"name":"sales_updateQuoteOperationStep","classification":"WRITE","schema":"2a34a54df226","response":"3797626bd17e","permission":"sales:update","paginates":false},
+ {"name":"sales_updateQuoteOperationStep","classification":"WRITE","schema":"ff346e07ed73","response":"3797626bd17e","permission":"sales:update","paginates":false},
{"name":"sales_updateQuoteOperationTool","classification":"WRITE","schema":"2285dc35c71d","response":"3797626bd17e","permission":"sales:update","paginates":false},
{"name":"sales_updateRentalAgreementCharge","classification":"WRITE","schema":"438676fd9225","response":"3797626bd17e","permission":"sales:update","paginates":false},
{"name":"sales_updateRentalAgreementLine","classification":"WRITE","schema":"194674afe1af","response":"3797626bd17e","permission":"sales:update","paginates":false},
@@ -1493,7 +1493,7 @@
{"name":"sales_updateReturnReason","classification":"WRITE","schema":"03734363977f","response":"3797626bd17e","permission":"sales:update","paginates":false},
{"name":"sales_updateSalesOrderDetails","classification":"WRITE","schema":"cdfda47dd459","response":"d160a49d6787","permission":"sales:update","paginates":false},
{"name":"sales_updateSalesOrderExchangeRate","classification":"WRITE","schema":"222e5249c015","response":"bcde375ebd4c","permission":"sales:update","paginates":false},
- {"name":"sales_updateSalesOrderLine","classification":"WRITE","schema":"1f7aae174849","response":"8f061af39e95","permission":"sales:create","paginates":false},
+ {"name":"sales_updateSalesOrderLine","classification":"WRITE","schema":"aa4e634c9f14","response":"8f061af39e95","permission":"sales:create","paginates":false},
{"name":"sales_updateSalesOrderLineOrder","classification":"WRITE","schema":"bc4baf1732ad","response":"none","permission":"sales:update","paginates":false},
{"name":"sales_updateSalesRFQ","classification":"WRITE","schema":"2cb421dde994","response":"2e56e1180d37","permission":"sales:update","paginates":false},
{"name":"sales_updateSalesRFQLine","classification":"WRITE","schema":"827ecf864e53","response":"3797626bd17e","permission":"sales:update","paginates":false},
diff --git a/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.details.tsx b/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.details.tsx
index 73344a4f8d..8dd27118c5 100644
--- a/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.details.tsx
+++ b/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.details.tsx
@@ -237,6 +237,8 @@ export default function QuoteLine() {
quantity: line.quantity ?? [1],
unitOfMeasureCode: line.unitOfMeasureCode ?? "",
taxPercent: line.taxPercent ?? 0,
+ // A configuration is stored as an object of parameter values.
+ configuration: line.configuration as Record<string, any> | null,
...getCustomFields(line.customFields)
};
diff --git a/apps/erp/app/routes/x+/stock-transfer+/$id.line.$lineId.tsx b/apps/erp/app/routes/x+/stock-transfer+/$id.line.$lineId.tsx
index 82225c8311..360ac8fb90 100644
--- a/apps/erp/app/routes/x+/stock-transfer+/$id.line.$lineId.tsx
+++ b/apps/erp/app/routes/x+/stock-transfer+/$id.line.$lineId.tsx
@@ -32,8 +32,8 @@ export async function action(args: ActionFunctionArgs) {
...line,
id: lineId,
stockTransferId: id,
- requiresBatchTracking: requiresBatchTracking ? "true" : "false",
- requiresSerialTracking: requiresSerialTracking ? "true" : "false"
+ requiresBatchTracking: Boolean(requiresBatchTracking),
+ requiresSerialTracking: Boolean(requiresSerialTracking)
});
// An error is toasted and the drawer stays open.
if (result.error) return result;
diff --git a/apps/erp/app/routes/x+/stock-transfer+/$id.line.new.tsx b/apps/erp/app/routes/x+/stock-transfer+/$id.line.new.tsx
index 7f4675107b..ec44bceb68 100644
--- a/apps/erp/app/routes/x+/stock-transfer+/$id.line.new.tsx
+++ b/apps/erp/app/routes/x+/stock-transfer+/$id.line.new.tsx
@@ -38,8 +38,8 @@ export async function action(args: ActionFunctionArgs) {
...line,
// The line goes on the transfer in the URL, the one whose lock is checked.
stockTransferId: id,
- requiresBatchTracking: requiresBatchTracking ? "true" : "false",
- requiresSerialTracking: requiresSerialTracking ? "true" : "false"
+ requiresBatchTracking: Boolean(requiresBatchTracking),
+ requiresSerialTracking: Boolean(requiresSerialTracking)
});
// An error is toasted and the drawer stays open.
if (result.error) return result;
diff --git a/apps/erp/test/database/service-fn-guards.test.ts b/apps/erp/test/database/service-fn-guards.test.ts
index 2438016340..12aa90a4a2 100644
--- a/apps/erp/test/database/service-fn-guards.test.ts
+++ b/apps/erp/test/database/service-fn-guards.test.ts
@@ -366,8 +366,8 @@ describeLocal("published operations hold their routes' checks", () => {
stockTransferId: ids.releasedStockTransfer,
itemId: ids.serial,
quantity: 1,
- requiresBatchTracking: "false",
- requiresSerialTracking: "true"
+ requiresBatchTracking: false,
+ requiresSerialTracking: true
});
expect(result.error?.category).toBe("rule");
@@ -387,8 +387,8 @@ describeLocal("published operations hold their routes' checks", () => {
itemId: ids.serial,
quantity: 1,
pickedQuantity: 1,
- requiresBatchTracking: "false",
- requiresSerialTracking: "true"
+ requiresBatchTracking: false,
+ requiresSerialTracking: true
} as never);
expect(result.error).toBeNull();
diff --git a/apps/erp/test/mcp-create-inputs.test.ts b/apps/erp/test/mcp-create-inputs.test.ts
new file mode 100644
index 0000000000..1a9eb7e738
--- /dev/null
+++ b/apps/erp/test/mcp-create-inputs.test.ts
@@ -0,0 +1,37 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+import { describe, expect, it } from "vitest";
+import metadata from "../app/routes/api+/mcp+/lib/tool-metadata.json";
+
+// A create whose input requires the new row's `id` makes an API caller invent
+// one, and a reused or copied id fails the insert. The table makes one; a form
+// that needs its own key may still send it.
+
+type Tool = { name: string; schema: { required?: string[] } };
+
+// Creates where `id` is not the new row's key, so it must be sent.
+const ID_IS_NOT_THE_NEW_ROW: Record<string, string> = {
+ items_createPart: "the part number",
+ items_createMaterial: "the material number",
+ items_createTool: "the tool number",
+ items_createConsumable: "the consumable number",
+ people_insertEmployeeJob: "the employee's user",
+ quality_createIssueAssociation: "the record linked to the issue",
+ resources_createContractor: "the supplier contact the contractor is",
+ resources_createPartner: "the supplier location the partner is"
+};
+
+const CREATE = /^[a-z]+_(create|insert|add)[A-Z]/;
+
+describe("create operations", () => {
+ it("leave the new row's id to the table", () => {
+ const requireId = (metadata.tools as Tool[])
+ .filter((tool) => CREATE.test(tool.name))
+ .filter((tool) => tool.schema.required?.includes("id"))
+ .map((tool) => tool.name)
+ .filter((name) => !(name in ID_IS_NOT_THE_NEW_ROW));
+ expect(requireId).toEqual([]);
+ });
+});
diff --git a/packages/api/AGENTS.md b/packages/api/AGENTS.md
index b4eab7281a..0efc6faee3 100644
--- a/packages/api/AGENTS.md
+++ b/packages/api/AGENTS.md
@@ -52,7 +52,7 @@ pnpm run check:manifest # digest current?
|---------|----------|
| `.` (index) | Manifest types: `ManifestEntry`, `ToolPermission`, `Classification`, `PermissionAction`, and `SERVICE_RULE_ERROR_CODE` (re-exports `./schema` too). Client-safe |
| `./schema` | `jsonSchema()` pass-through Standard Schema wrapper, `CarbonJsonSchemaConverter` (OpenAPI generator plugin), `CARBON_VENDOR` |
-| `./service-fn.server` | `defineServiceFn`, `CarbonError`, `ERROR_STATUS`, `createServiceContext`, `ServiceContext`, `Result`, `RouteResult`, `toResult`. `ctx.transaction` rolls back on a returned refusal — a bare `CarbonError` or a composed service function's `{ data, error }` — and returns it as the error. A failure log names the input's keys, never its values |
+| `./service-fn.server` | `defineServiceFn`, `CarbonError`, `ERROR_STATUS`, `createServiceContext`, `ServiceContext`, `Result`, `RouteResult`, `toResult`. `ctx.transaction` rolls back on a returned refusal — a bare `CarbonError` or a composed service function's `{ data, error }` — and returns it as the error. A failure log names the input's keys, never its values. An `internal` error (returned or thrown) whose cause is a database refusal the caller can fix — a duplicate key, a reference to nothing, a missing or malformed value, RLS — goes out as that refusal (`databaseRefusal`, `database-refusal.ts`): its category, and the operation's message followed by the field it names, never the value |
| `./carbon.server` | What a route calls: `carbon(request)` (the operations bound to the caller, typed through the app's `Register` augmentation), `carbonFor(auth)` (the same, for a caller the route authenticated another way, such as the Onshape panel's bearer token), `respond(request, result).redirect(to, { message, onError })`, `registerCarbon` (the app's router and context, called once from `entry.server.tsx` via `apps/erp/app/modules/carbon.server.ts`), `bindServiceFns` / `Api` |
| `./permissions` | `hasPermissions`, `permissionsFromClaims`, `resolvePermissions` and the `Permissions` / `PermissionRule` / `ModulePermissions` types. A keyed rule refuses a value with no rule of its own (an inherited key included) as `InvalidInputError` (400) naming the field; the `defineServiceFn` gate and `invokePosting` (`authorizePostingCaller`, ERP `shared.service.ts`) both check by these rules |
| `./errors` | `ServerFnError`, `InvalidInputError`, `ForbiddenError`, `NotFoundError`, `isDataLayerError`, `isServerFailure`, `toServerFnError`, `RAISED_EXCEPTION` — the postings' error classes. `isServerFailure` is the database or network failing, not the request: a Node system error (`connect ECONNREFUSED …`), `pg` / `pg-pool`'s connection errors, a SQLSTATE of class 08, 40, 53, 57, 58 or XX, Kysely's `NoResultError`. `toServerFnError` makes one a 500 with no message, whatever the default status |
diff --git a/packages/api/src/database-refusal.test.ts b/packages/api/src/database-refusal.test.ts
new file mode 100644
index 0000000000..e127dd9b97
--- /dev/null
+++ b/packages/api/src/database-refusal.test.ts
@@ -0,0 +1,144 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+import { describe, expect, it, vi } from "vitest";
+import { z } from "zod";
+
+vi.mock("@carbon/logger", () => ({
+ getLogger: () => ({ error: vi.fn(), warn: vi.fn() })
+}));
+
+import { databaseRefusal } from "./database-refusal";
+import { createServiceContext, defineServiceFn } from "./service-fn.server";
+
+// Shapes copied from what PostgREST and node-postgres return.
+const duplicateId = {
+ code: "23505",
+ message: 'duplicate key value violates unique constraint "jobOperation_pkey"',
+ details: 'Key (id, "companyId")=(abc, c1) already exists.'
+};
+const missingProcedure = {
+ code: "23503",
+ message:
+ 'insert or update on table "jobOperation" violates foreign key constraint "jobOperation_procedureId_fkey"',
+ details: 'Key ("procedureId")=(p1) is not present in table "procedure".'
+};
+
+describe("databaseRefusal", () => {
+ it("names the duplicate key, without the company or the value", () => {
+ expect(databaseRefusal(duplicateId)).toEqual({
+ category: "conflict",
+ message: 'A record with this "id" already exists.'
+ });
+ });
+
+ it("names the reference that matches nothing", () => {
+ expect(databaseRefusal(missingProcedure)).toEqual({
+ category: "conflict",
+ message: '"procedureId" does not match an existing "procedure".'
+ });
+ });
+
+ it("says what still uses a record that cannot be deleted", () => {
+ expect(
+ databaseRefusal({
+ code: "23503",
+ detail: 'Key (id)=(x) is still referenced from table "jobMaterial".'
+ })?.message
+ ).toBe('It is still used by a "jobMaterial" record; remove that first.');
+ });
+
+ it("names a missing required column, from PostgREST or node-postgres", () => {
+ const message =
+ 'null value in column "processId" of relation "jobOperation" violates not-null constraint';
+ expect(databaseRefusal({ code: "23502", message })?.message).toBe(
+ '"processId" is required.'
+ );
+ expect(
+ databaseRefusal({ code: "23502", message, column: "processId" })
+ ).toEqual({ category: "validation", message: '"processId" is required.' });
+ });
+
+ it("passes a bad value's own message through as a validation error", () => {
+ expect(
+ databaseRefusal({
+ code: "22P02",
+ message: 'invalid input value for enum "factor": "Hours"'
+ })
+ ).toEqual({
+ category: "validation",
+ message: 'Invalid input value for enum "factor": "Hours".'
+ });
+ });
+
+ it("finds a driver error wrapped one cause deep", () => {
+ expect(
+ databaseRefusal(new Error("wrapped", { cause: duplicateId }))?.category
+ ).toBe("conflict");
+ });
+
+ it("leaves failures the caller cannot fix alone", () => {
+ expect(databaseRefusal({ code: "08006", message: "connection" })).toBe(
+ null
+ );
+ expect(databaseRefusal(new Error("boom"))).toBe(null);
+ expect(databaseRefusal(null)).toBe(null);
+ });
+});
+
+describe("a service function's database refusal", () => {
+ const ctx = createServiceContext({
+ actor: { type: "system", onBehalfOf: "user-1" },
+ company: { id: "c1", groupId: "g1" },
+ caller: {} as never,
+ system: () => ({}) as never,
+ pg: () => ({}) as never,
+ kv: () => ({}) as never
+ });
+
+ it("is reported as the refusal, after the operation's own message", async () => {
+ const create = defineServiceFn({
+ input: z.object({}),
+ permission: {},
+ async run(ctx) {
+ return ctx.error(
+ "internal",
+ "Failed to insert job operation",
+ duplicateId
+ );
+ }
+ });
+ const { error } = await create(ctx, {});
+ expect(error).toMatchObject({
+ category: "conflict",
+ status: 409,
+ message:
+ 'Failed to insert job operation: A record with this "id" already exists.'
+ });
+ });
+
+ it("is reported as the refusal when the driver throws it", async () => {
+ const create = defineServiceFn({
+ input: z.object({}),
+ permission: {},
+ async run() {
+ throw Object.assign(new Error("fk"), missingProcedure);
+ }
+ });
+ const { error } = await create(ctx, {});
+ expect(error).toMatchObject({ category: "conflict", status: 409 });
+ });
+
+ it("keeps any other internal failure internal", async () => {
+ const create = defineServiceFn({
+ input: z.object({}),
+ permission: {},
+ async run(ctx) {
+ return ctx.error("internal", "Failed", new Error("timeout"));
+ }
+ });
+ const { error } = await create(ctx, {});
+ expect(error).toMatchObject({ category: "internal", message: "Failed" });
+ });
+});
diff --git a/packages/api/src/database-refusal.ts b/packages/api/src/database-refusal.ts
new file mode 100644
index 0000000000..ee32a63712
--- /dev/null
+++ b/packages/api/src/database-refusal.ts
@@ -0,0 +1,140 @@
+// 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.
+
+// What a database refusal means for the caller. Postgres refuses a write the
+// caller can fix (a duplicate id, a reference to nothing, a missing or badly
+// formed value) with a SQLSTATE; this names the category and says which field,
+// so an API caller is not left with a bare 500. Values are never repeated: only
+// column, table and constraint names, which are the API's own field names.
+
+import type { ErrorCategory } from "./service-fn.server";
+
+export type DatabaseRefusal = { category: ErrorCategory; message: string };
+
+type Fields = {
+ code: string;
+ message: string;
+ details: string;
+ column?: string;
+ table?: string;
+ constraint?: string;
+};
+
+function fieldsOf(error: unknown): Fields | null {
+ if (error === null || typeof error !== "object") return null;
+ const e = error as Record<string, unknown>;
+ if (typeof e.code !== "string" || e.code === "") return null;
+ const text = (value: unknown) => (typeof value === "string" ? value : "");
+ return {
+ code: e.code,
+ message: text(e.message),
+ // PostgREST names it `details`; node-postgres `detail`.
+ details: text(e.details) || text(e.detail),
+ column: text(e.column) || undefined,
+ table: text(e.table) || undefined,
+ constraint: text(e.constraint) || undefined
+ };
+}
+
+const IDENTITY_COLUMNS = new Set(["companyId", "companyGroupId"]);
+
+/** The columns of `Key (a, b)=(…)` in a constraint's detail, identity columns left out. */
+function keyColumns(details: string): string[] {
+ const match = /Key \(([^)]+)\)=/.exec(details);
+ if (!match) return [];
+ return match[1]!
+ .split(",")
+ .map((column) => column.trim().replace(/^"|"$/g, ""))
+ .filter((column) => !IDENTITY_COLUMNS.has(column));
+}
+
+function quoted(pattern: RegExp, text: string): string | undefined {
+ return pattern.exec(text)?.[1];
+}
+
+function list(columns: string[]): string {
+ return columns.map((column) => `"${column}"`).join(", ");
+}
+
+function uniqueViolation(f: Fields): string {
+ const columns = keyColumns(f.details);
+ return columns.length
+ ? `A record with this ${list(columns)} already exists.`
+ : "A record with these values already exists.";
+}
+
+function foreignKeyViolation(f: Fields): string {
+ const referencedBy = quoted(
+ /still referenced from table "([^"]+)"/,
+ f.details
+ );
+ if (referencedBy) {
+ return `It is still used by a "${referencedBy}" record; remove that first.`;
+ }
+ const columns = keyColumns(f.details);
+ const target = quoted(/not present in table "([^"]+)"/, f.details);
+ if (columns.length) {
+ return target
+ ? `${list(columns)} does not match an existing "${target}".`
+ : `${list(columns)} does not match an existing record.`;
+ }
+ return "A referenced record does not exist.";
+}
+
+function notNullViolation(f: Fields): string {
+ const column = f.column ?? quoted(/column "([^"]+)"/, f.message);
+ return column ? `"${column}" is required.` : "A required field was missing.";
+}
+
+function checkViolation(f: Fields): string {
+ const constraint =
+ f.constraint ?? quoted(/check constraint "([^"]+)"/, f.message);
+ return constraint
+ ? `The values break the rule "${constraint}".`
+ : "The values break a rule on this record.";
+}
+
+// SQLSTATE → category and message. Class 22 (data exception) is the caller's
+// value: Postgres' own message names the type and is safe to show.
+const REFUSALS: Record<string, (f: Fields) => DatabaseRefusal> = {
+ "23505": (f) => ({ category: "conflict", message: uniqueViolation(f) }),
+ "23503": (f) => ({ category: "conflict", message: foreignKeyViolation(f) }),
+ "23502": (f) => ({ category: "validation", message: notNullViolation(f) }),
+ "23514": (f) => ({ category: "validation", message: checkViolation(f) }),
+ "22P02": (f) => ({ category: "validation", message: dataMessage(f) }),
+ "22001": (f) => ({ category: "validation", message: dataMessage(f) }),
+ "22003": (f) => ({ category: "validation", message: dataMessage(f) }),
+ "22007": (f) => ({ category: "validation", message: dataMessage(f) }),
+ "22008": (f) => ({ category: "validation", message: dataMessage(f) }),
+ "42501": () => ({
+ category: "forbidden",
+ message: "You do not have permission to do this"
+ }),
+ PGRST116: () => ({
+ category: "notFound",
+ message: "No matching record was found."
+ })
+};
+
+function dataMessage(f: Fields): string {
+ return f.message ? `${capitalize(f.message)}.` : "A value is not valid.";
+}
+
+function capitalize(text: string): string {
+ return text.charAt(0).toUpperCase() + text.slice(1).replace(/\.$/, "");
+}
+
+/**
+ * The refusal a database error stands for, or null when it is not one the
+ * caller can fix (a connection failure, a bug in our SQL). Looks one `cause`
+ * deep, for an error that wraps the driver's.
+ */
+export function databaseRefusal(error: unknown): DatabaseRefusal | null {
+ for (const candidate of [error, (error as { cause?: unknown })?.cause]) {
+ const fields = fieldsOf(candidate);
+ const refusal = fields && REFUSALS[fields.code];
+ if (refusal) return refusal(fields);
+ }
+ return null;
+}
diff --git a/packages/api/src/service-fn.server.ts b/packages/api/src/service-fn.server.ts
index 9eddf4f32e..41c8d4fa14 100644
--- a/packages/api/src/service-fn.server.ts
+++ b/packages/api/src/service-fn.server.ts
@@ -8,6 +8,7 @@ import type { redis } from "@carbon/kv";
import { getLogger } from "@carbon/logger";
import type { SupabaseClient } from "@supabase/supabase-js";
import { z } from "zod";
+import { databaseRefusal } from "./database-refusal";
import {
hasPermissions,
type ModulePermissions,
@@ -396,21 +397,29 @@ export function defineServiceFn<I extends z.ZodType, R>(definition: {
return { data: out, error: null } as Outcome<R>;
}
if (out.category === "internal") {
- logger.error("Service function failed: {message}: {error}", {
- message: out.message,
- companyId: ctx.company.id,
- inputKeys: keysOf(input),
- error: out.cause
- });
+ const refused = refusalFromDatabase(out.message, out.cause);
+ logger[refused ? "warn" : "error"](
+ "Service function failed: {message}: {error}",
+ {
+ message: out.message,
+ companyId: ctx.company.id,
+ inputKeys: keysOf(input),
+ error: out.cause
+ }
+ );
+ if (refused) return failed(refused);
}
return failed(out);
} catch (err) {
- logger.error("Service function threw: {error}", {
+ const refused = refusalFromDatabase(undefined, err);
+ logger[refused ? "warn" : "error"]("Service function threw: {error}", {
companyId: ctx.company.id,
inputKeys: keysOf(input),
error: err
});
- return failed(new CarbonError("internal", "Something went wrong", err));
+ return failed(
+ refused ?? new CarbonError("internal", "Something went wrong", err)
+ );
}
};
@@ -420,6 +429,26 @@ export function defineServiceFn<I extends z.ZodType, R>(definition: {
});
}
+/**
+ * An `internal` failure whose cause is a database refusal the caller can fix
+ * (a duplicate id, a reference to nothing, a missing value) is that refusal:
+ * its category, and a message that names the field after the operation's own.
+ */
+function refusalFromDatabase(
+ message: string | undefined,
+ cause: unknown
+): CarbonError | null {
+ const known = databaseRefusal(cause);
+ if (!known) return null;
+ return new CarbonError(
+ known.category,
+ message
+ ? `${message.replace(/[.:]\s*$/, "")}: ${known.message}`
+ : known.message,
+ cause
+ );
+}
+
/** A `CarbonError` as it crosses to the client: its fields, never its cause. */
export type SerializedError<E> =
E extends CarbonError<infer C>
diff --git a/packages/api/src/service-tools.server.ts b/packages/api/src/service-tools.server.ts
index 9ba380ffd4..5e57e65fad 100644
--- a/packages/api/src/service-tools.server.ts
+++ b/packages/api/src/service-tools.server.ts
@@ -8,6 +8,7 @@
// engine's throw into a refusal (`run`).
import { failSpan, inSpan } from "@carbon/logger/span";
+import { databaseRefusal } from "./database-refusal";
import { RAISED_EXCEPTION, ServerFnError, toServerFnError } from "./errors";
import { SERVICE_RULE_ERROR_CODE } from "./rule-error";
import {
@@ -159,17 +160,6 @@ export function payload<T>(ctx: ServiceContext, value: T) {
return builder;
}
-const DATABASE_REFUSALS: Record<string, [ErrorCategory, string]> = {
- "23505": ["conflict", "A record with these values already exists."],
- "23503": [
- "conflict",
- "The operation would violate a reference between records."
- ],
- "23502": ["validation", "A required field was missing."],
- "42501": ["forbidden", "You do not have permission to do this"],
- PGRST116: ["notFound", "No matching record was found."]
-};
-
function serviceRefusal(ctx: ServiceContext, error: unknown): CarbonError {
if (isRecord(error) && error.code === SERVICE_RULE_ERROR_CODE) {
return ctx.error("rule", String(error.message));
@@ -183,10 +173,9 @@ function serviceRefusal(ctx: ServiceContext, error: unknown): CarbonError {
) {
return ctx.error("rule", error.message, error);
}
- const code = isRecord(error) ? String(error.code ?? "") : "";
- const known = DATABASE_REFUSALS[code];
+ const known = databaseRefusal(error);
return known
- ? ctx.error(known[0], known[1], error)
+ ? ctx.error(known.category, known.message, error)
: ctx.error("internal", "The operation could not be completed.", error);
}