Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
feat(api): CAD model upload API, signed webhooks, method and model webhooks (#1949)
Brad Barbinf782ba51d2d3
diff --git a/.ai/plans/2026-10-16-cad-integration-api-gaps.md b/.ai/plans/2026-10-16-cad-integration-api-gaps.mdnew file mode 100644index 0000000000..be12fdacef--- /dev/null+++ b/.ai/plans/2026-10-16-cad-integration-api-gaps.md@@ -0,0 +1,69 @@+# CAD integration API gaps++From an integrator's review (a CAD program pushing parts, BOMs and models into+Carbon). Gap 4 (per-app credentials) and the NC-program field are out of scope.++## 1. Create a 3D model through the API++The uncommitted item-only pair (`createItemModelUploadUrl` / `attachItemModel`)+signed into the company bucket (50 MB cap) and attached to items only.++- [x] `items_createModelUploadUrl` — signs into `temp-staging` (2.5 GB, where the+ browser stages raw CAD) at `${companyId}/models/${modelId}.${ext}`.+- [x] `items_insertModelUpload` — records the upload, attaches it to at most one+ of item / job / sales RFQ line / quote line / sales order line, optional+ `convert` (STEP → `assembly-convert`), always `model-optimize`.+- [x] `api+/model.upload.ts` calls `insertModelUpload` (one path; the route keeps+ the assembler health check).+- [x] Manifest digest regenerated.++## 2. Signed webhooks++- [x] Migration: vault-backed per-webhook signing secret+ (`get_webhook_signing_secret` get-or-create, `rotate_…`, `delete_…`,+ service role only).+- [x] Delivery signs the exact body: `Carbon-Signature: t=<unix>,v1=<hex>`,+ HMAC-SHA256 over `${t}.${body}`, keyed by the secret string. Pure helper ++ tests in `webhook-body.ts`.+- [x] ee: `getWebhookSigningSecret` (runtime) / `revealWebhookSigningSecret` /+ `rotateWebhookSigningSecret` (`requireEntitlement`); the secret is dropped by+ `sync_webhook_subscription` when the webhook row is deleted.+- [x] Settings → Webhooks edit drawer: reveal + roll.+- [x] Docs: replace "treat the URL as the secret" with verification.++## 3. Webhooks for methods and models++- [x] `webhookTable` rows: makeMethod, methodMaterial, methodOperation, modelUpload,+ plus changeOrder / changeOrderAffectedItem (asked for by the hotice session; both+ already emit events).+- [x] `attachments.ts`: `events: true` for makeMethod, methodOperation, modelUpload;+ generated authz migration.+- [x] Docs table.++## Verification++Static: erp / ee / jobs typecheck, jobs + checks + content tests (the two jobs+`*.database.test.ts` files point at another database and were not run), Biome,+the `authz` migration test, the conformance gate.++Live, on the worktree stack (2026-10-17), with test data removed afterwards:++1. `crbn up` applied the 3 migrations. `authz check` reports no drift. The types+ carry the 3 functions.+2. The secret functions, in a rolled-back transaction: get creates the secret once,+ rotate replaces it, a wrong company gets null, `anon` / `authenticated` get the+ guard error. Deleting the webhook removes the secret and the subscription.+3. A key scoped to `parts_*` called `items_createModelUploadUrl` over `/api/v1`, PUT a+ STEP file to `temp-staging`, then called `items_insertModelUpload` with an+ `itemId` and `convert`. The item got the model. `model-optimize` and+ `assembly-convert` were sent.+4. `api+/model.upload.ts`, called with the browser session and two targets (a sales+ order line and its item), linked both.+5. A `makeMethod` webhook delivered a signed UPDATE to a local receiver. The+ verifier on the docs page accepts it, and refuses a changed body, a wrong secret+ and an old `t`.+6. Settings → Webhooks: Reveal shows the Vault secret. Roll asks to confirm, shows+ the new secret, and keeps the drawer open. The next delivery verifies with the+ new secret.++Left for the commit: `lingui:extract` for the new strings.diff --git a/.claude/rules/commercial-licensing.md b/.claude/rules/commercial-licensing.mdindex 310069ba81..7fea4ac256 100644--- a/.claude/rules/commercial-licensing.md+++ b/.claude/rules/commercial-licensing.md@@ -142,7 +142,9 @@ Refactor one at a time; each PR should leave the tree green.- ✅ **API keys** — `upsertApiKey`/`deleteApiKey` in `packages/ee/src/api-keys.server.ts`,`requireEntitlement("API_KEYS")`; routes gate with `requireFeature`.- ✅ **Webhooks** — authoring in `packages/ee/src/webhooks.server.ts`- (`requireEntitlement("WEBHOOKS")`); delivery degrades at runtime via `companyHasFeature`.+ (`requireEntitlement("WEBHOOKS")`, including `revealWebhookSigningSecret` /+ `rotateWebhookSigningSecret`); delivery degrades at runtime via `companyHasFeature` and+ signs with the ungated `getWebhookSigningSecret`.- ✅ **Two-factor** — the `requireMfa` company policy in `packages/ee/src/two-factor.server.ts`,`requireEntitlement("TWO_FACTOR")` scoped to ENABLING only (a downgrade can still disable).- ✅ **Forecast** — `upsert/deleteDemandForecasts` + `upsert/deleteDemandProjections` indiff --git a/.claude/rules/event-system.md b/.claude/rules/event-system.mdindex 43f0f808b0..85df9f9ddc 100644--- a/.claude/rules/event-system.md+++ b/.claude/rules/event-system.md@@ -102,6 +102,7 @@ Since `20260807234512_webhooks-via-event-system.sql`, user-configured webhooks (- **Subscriptions are derived, not app-managed.** The `sync_webhook_subscription` AFTER-ROW interceptor — registered via `attach_event_trigger('webhook', ARRAY[]::TEXT[], ARRAY['sync_webhook_subscription'])`, so it follows the same convention as `sync_create_customer_entries` — maintains a subscription named `webhook-<webhook.id>` with `handlerType 'WEBHOOK'` and `config {url, webhookId}`. The `webhook` table is the single source of truth, so UI/API/MCP writers all work without lifecycle code. It deletes-then-recreates on UPDATE because `table` is editable and uniqueness is `(companyId, name, table)`.- **The body is a PUBLIC contract**: `{type, record, old?, companyId, table, eventId}` — documented at `docs/content/docs/building/webhooks.mdx` and pinned by `webhook.test.ts`. `toWebhookBody` maps the queue event onto it. Two traps: DELETE takes `record` from the event's `old` (its `new` is null), and `companyId` is **not** on the event — the drainer forwards it from the queue message.+- **Every delivery is signed** (`20261017030352_webhook-signing-secrets.sql`): `Carbon-Signature: t=<unix>,v1=<hex HMAC-SHA256 of "${t}.${body}">`, keyed by the webhook's own `whsec_…` secret in Vault (`webhook:<companyId>:<webhookId>`). `get_webhook_signing_secret` creates it on first use, `rotate_webhook_signing_secret` replaces it (both service-role only, called over Kysely through `@carbon/ee/webhooks.server`), and `sync_webhook_subscription` drops it when the webhook row is deleted. `webhook.ts` serialises the body once and signs those bytes per attempt (`signWebhookBody`, `webhook-body.ts`, pinned by `webhook-body.test.ts`); a webhook with no secret (its row is gone) is skipped. Settings → Webhooks reveals and rolls it (`x+/settings+/webhooks.secret.$id.tsx`, `update: settings`).- Delivery moved from at-most-once to **at-least-once** (Inngest `retries: 3`); `increment_webhook_error` fires only on the final attempt so counters stay one-per-event. `eventId` is the pgmq `msgId` — stable across an event's retries (it is also the Inngest idempotency key), distinct per change — and is the documented de-dup key. `type` + `record.id` is NOT usable: two genuine updates to a row share both.## Notesdiff --git a/.claude/rules/mcp-tools-reference.md b/.claude/rules/mcp-tools-reference.mdindex fdafb4031d..6eab7e1f94 100644--- a/.claude/rules/mcp-tools-reference.md+++ b/.claude/rules/mcp-tools-reference.md@@ -739,6 +739,14 @@ the model context or the MCP dispatch.so the `private` bucket's storage RLS will refuse the signed-URL mint — same classof limitation as the blocked note-table tools. OAuth is the supported path.+**CAD models** follow the same two steps with their own pair:+`items_createModelUploadUrl` (`{ name }` → `{ signedUrl, token, path, modelId }`,+signed into the `temp-staging` bucket, 2.5 GB) and `items_insertModelUpload`+(`{ modelId, path, name, size, itemId?, jobId?, salesRfqLineId?, quoteLineId?,+salesOrderLineId?, convert? }`). The `temp-staging` storage policies read the key's+scopes (`parts_create` / `parts_update`), so an API key with those scopes can mint+the URL and upload — unlike the document pair above, which signs into a company bucket.+## Gotchas- The generator takes a service's parameters from the AST (name, optionality,diff --git a/apps/erp/app/modules/items/AGENTS.md b/apps/erp/app/modules/items/AGENTS.mdindex a7b1b34e68..ec86fcf160 100644--- a/apps/erp/app/modules/items/AGENTS.md+++ b/apps/erp/app/modules/items/AGENTS.md@@ -75,6 +75,7 @@ pnpm --filter @carbon/erp test- `upsertPickMethodWithShelfLife` — pick method with shelf life configuration- `getConfigurationParameters` / `getConfigurationRules` — product configurator- `createItemDocumentUploadUrl` — MCP file upload (step 1): presigned URL for an item document (`parts/{itemId}` folder); pair with `documents_insertUploadedDocument`. See `.claude/rules/mcp-tools-reference.md` → "File uploads"+- `createModelUploadUrl` / `insertModelUpload` — the API/MCP CAD model upload, and the one path the browser's `api+/model.upload.ts` shares: step 1 signs an upload into `temp-staging` (2.5 GB, where the dropzone stages raw CAD) at `${companyId}/models/${modelId}.${ext}`; step 2 records the `modelUpload` row, links it to any of `itemId` / `jobId` / `salesRfqLineId` / `quoteLineId` / `salesOrderLineId` (each checked first, all scoped by `companyId`), and starts `model-optimize` (plus `assembly-convert` for a STEP file with `convert`). No transaction spans the row and the links: a failed link returns an error, the model row stands and is still processed## Key Exports@@ -91,7 +92,7 @@ Engineering-change-order (ECO) workflow — a **top-to-bottom**, affected-items-Change-order code follows the one-service/models/server-per-module convention — it lives in the module's canonical files, NOT separate `changeNotice.*` files: `items.service.ts` holds header CRUD + guarded stage transition + Types config + affected-item CRUD + the CO-owned Draft orchestration (`createChangeNoticeDraftMethod` / `addChangeNoticeAffectedItem` / `updateChangeNoticeAffectedItemChangeType` / cutover + `mintPlaceholderPart` + `getTopLevelProductsForItems` rollup) + the `diffMethod` pure engine + `getChangeNoticeDiff` authoring-diff wrapper + item↔CO traceability reads (`findChangeNoticesForItem`, linked-NCR reverse) + freeform action-task CRUD; `items.server.ts` holds the server-only release path (`applyChangeNotice` orchestration + `releaseAffectedItem` + notifications); `items.models.ts` holds the validators + state machine + `changeNoticeChangeTypes` + diff types. Non-server exports come through the Items barrel — import from `~/modules/items`; the server file is imported directly from `~/modules/items/items.server`.-**Approval gate (optional, `APPROVAL_RULES` plan feature).** When the company has an enabled `changeOrder` approval rule (Settings → Approval Rules → Change Notices; amount-less, at most one rule), `Engineering Complete → Implementation` is gated. The CO code is wiring only; the lifecycle lives in the shared `@carbon/ee/approvals/document.server` helpers. `$id.status.tsx` calls `openApprovalRequests` and notifies the approvers instead of moving the status. `$id.approval.tsx` calls `decideApprovalRequest`; approving runs the CAS `Engineering Complete → Implementation` inside `approveRequest`, rejecting leaves the status. Cancel and delete call `cancelPendingApprovals`. The `$id` loader returns `approval` (`getDocumentApprovalState`, only at Engineering Complete). While a request is pending, engineering-scope edits are locked: `getChangeNoticeEngineeringLock` (items.server.ts) backs both `requireChangeNoticeEditable` and `checkRevisionLock`, and `useChangeNoticeEngineeringLock` (`ui/ChangeNotice/lock-ui.tsx`) is the UI half. Workflow scope stays editable. Without a rule, stages advance freely; a CO reaches Done via `applyChangeNotice`. **Same-part parallel COs are now allowed** — the one-open-CO-per-part guard was dropped; `findOtherOpenChangeNoticesForItem` still exists but is advisory (no route/service enforces it).+**Approval gate (optional, `APPROVAL_RULES` plan feature).** When the company has an enabled `changeOrder` approval rule (Settings → Approval Rules → Change Notices; amount-less, at most one rule), `Engineering Complete → Implementation` is gated. The CO code is wiring only; the lifecycle lives in the shared `@carbon/ee/approvals/document.server` helpers. `$id.status.tsx` (via `transitionChangeNotice`, items.server.ts) calls `openApprovalRequests` and notifies the approvers instead of moving the status. Everything after the gate (release on Done, approval withdrawal, stage notifications) is `transitionChangeNoticeStatus` in items.service.ts. The API/MCP tool `updateChangeNoticeStatus` shares it, and with a rule enabled it refuses Engineering Complete → Implementation rather than opening a request (opening one needs the service role and plan check, which a service can't import). `$id.approval.tsx` calls `decideApprovalRequest`; approving runs the CAS `Engineering Complete → Implementation` inside `approveRequest`, rejecting leaves the status. Cancel and delete call `cancelPendingApprovals`. The `$id` loader returns `approval` (`getDocumentApprovalState`, only at Engineering Complete). While a request is pending, engineering-scope edits are locked: `getChangeNoticeEngineeringLock` (items.server.ts) backs both `requireChangeNoticeEditable` and `checkRevisionLock`, and `useChangeNoticeEngineeringLock` (`ui/ChangeNotice/lock-ui.tsx`) is the UI half. Workflow scope stays editable. Without a rule, stages advance freely; a CO reaches Done via `applyChangeNotice`. **Same-part parallel COs are now allowed** — the one-open-CO-per-part guard was dropped; `findOtherOpenChangeNoticesForItem` still exists but is advisory (no route/service enforces it).### Key CO conceptsdiff --git a/apps/erp/app/modules/items/items.server.ts b/apps/erp/app/modules/items/items.server.tsindex be01229baf..7afa981a55 100644--- a/apps/erp/app/modules/items/items.server.ts+++ b/apps/erp/app/modules/items/items.server.ts@@ -7,6 +7,7 @@ import { getCarbonServiceRole } from "@carbon/auth/client.server";import { flash } from "@carbon/auth/session.server";import { type Database, fetchAllByIds } from "@carbon/database";import type { Kysely, KyselyDatabase } from "@carbon/database/client";+import { openApprovalRequests } from "@carbon/ee/approvals/document.server";import { hasPendingApproval } from "@carbon/ee/approvals.server";import { trigger } from "@carbon/jobs";import { getLogger } from "@carbon/logger";@@ -15,14 +16,13 @@ import { NotificationEvent } from "@carbon/notifications";import type { SupabaseClient } from "@supabase/supabase-js";import { data } from "react-router";import {- activateMethodVersion,findChangeNoticesForItem,getChangeNoticeTypesList,getItemSupersededBy,getItemSupersession,getMakeMethodById,getMakeMethods,- upsertItemSupersession+ transitionChangeNoticeStatus} from "~/modules/items";import { getCompanySettings } from "~/modules/settings";import type { plmReleaseControl } from "./items.models";@@ -32,7 +32,7 @@ import {changeNoticeAwaitingApprovalMessage,changeNoticeLockedMessage,changeNoticeOpenStatuses,- supersessionModes+ type changeNoticeStatus} from "./items.models";const logger = getLogger("erp", "change-orders");@@ -444,326 +444,119 @@ export async function requireEditableChangeNoticeRoute();}-// Maps a notifying stage to its notification event. Only Start / Implementation-// / Done notify; Draft / Engineering Complete are silent, so callers simply-// don't invoke this for those stages.-export const changeNoticeStageEvent: Record<string, NotificationEvent> = {- Start: NotificationEvent.ChangeNoticeStarted,- Implementation: NotificationEvent.ChangeNoticeImplementation,- Done: NotificationEvent.ChangeNoticeDone-};--// Notifies the people involved in the CO — its assignee plus every action-task-// assignee — on a stage entry (best-effort). Deliberately NOT a company-wide-// broadcast; the notify function dedupes and drops the acting user itself.-export async function notifyChangeNoticeTransition(args: {- client: SupabaseClient<Database>;- event: NotificationEvent;- changeNoticeId: string;- companyId: string;- userId: string;-}): Promise<void> {- try {- const [changeNotice, actionTasks] = await Promise.all([- args.client- .from("changeOrder")- .select("assignee")- .eq("id", args.changeNoticeId)- .eq("companyId", args.companyId)- .single(),- args.client- .from("changeOrderActionTask")- .select("assignee")- .eq("changeOrderId", args.changeNoticeId)- .eq("companyId", args.companyId)- .not("assignee", "is", null)- ]);-- if (changeNotice.error) {- logger.error("Failed to resolve change notice for CO notification", {- error: changeNotice.error,- changeNoticeId: args.changeNoticeId,- companyId: args.companyId- });- return;- }-- if (actionTasks.error) {- logger.error("Failed to resolve CO action-task assignees", {- error: actionTasks.error,- changeNoticeId: args.changeNoticeId,- companyId: args.companyId- });- }-- const userIds = [- ...new Set(- [- changeNotice.data?.assignee,- ...(actionTasks.data ?? []).map((task) => task.assignee)- ].filter((id): id is string => !!id)- )- ];-- if (userIds.length === 0) return;-- await trigger("notify", {- event: args.event,- companyId: args.companyId,- documentId: args.changeNoticeId,- recipient: { type: "users", userIds },- from: args.userId- });- } catch (e) {- logger.error("Failed to trigger change notice notification", { error: e });- }-}-// =============================================================================-// applyChangeNotice — the top-to-bottom "release", run on the Implementation →-// Done transition (this function IS that transition). It materializes each-// affected item's CO-staged end-state onto a NEW inactive revision, activates-// it, then auto-writes the oldRev → newRev supersession (Q1/Q2/Q5).-//-// Atomicity (G2): createRevision + activateMethodVersion call the get-method /-// convert operations, each of which commits its own transaction, so this CANNOT-// be one Kysely transaction. The apply is therefore an idempotent, CAS-guarded orchestration:-// - PER-AFFECTED-ITEM idempotency: each changeOrderAffectedItem gets its-// created revision id stamped into `newItemId` at the END of its processing.-// A re-run skips any affected item whose `newItemId` is already set, so a-// partial failure re-run resumes at the first unprocessed item instead of-// re-creating revisions.-// - CO-LEVEL idempotency: the final flip to 'Done' is a compare-and-swap on-// status='Implementation', so a re-run can't double-transition the CO; only-// the closing status flip is transactional.+// transitionChangeNotice — the status route's transition. The approval gate is+// here because opening a request needs the service role and the plan check+// (`@carbon/ee/approvals/document.server`); everything after the gate is+// `transitionChangeNoticeStatus` in items.service.ts, the same path the+// API/MCP `items_updateChangeNoticeStatus` tool takes.+// - Engineering Complete → Implementation is gated by an approval rule when one+// is set: it opens the request and leaves the status alone (approving it+// performs the transition).+// `approval` on the result says a request was opened or was already pending, in+// which case the status did not change.// =============================================================================-export async function applyChangeNotice(+type ChangeNoticeStatus = (typeof changeNoticeStatus)[number];+export type ChangeNoticeTransitionResult =+ | {+ data: {+ id: string;+ status: ChangeNoticeStatus;+ approval?: "requested" | "already-pending";+ };+ error: null;+ }+ | { data: null; error: { message: string; cause?: unknown } };++export async function transitionChangeNotice(client: SupabaseClient<Database>,db: Kysely<KyselyDatabase>,args: {- changeNoticeId: string;- userId: string;+ id: string;companyId: string;+ userId: string;+ fromStatus: ChangeNoticeStatus;+ toStatus: ChangeNoticeStatus;+ assignee?: string | null;}-): Promise<{ data: { id: string } | null; error: { message: string } | null }> {- const { changeNoticeId, userId, companyId } = args;-- const cn = await client- .from("changeOrder")- .select("id, status")- .eq("id", changeNoticeId)- .eq("companyId", companyId)- .single();- if (cn.error || !cn.data) {- return { data: null, error: { message: "Change notice not found" } };- }- if (cn.data.status !== "Implementation") {- return {- data: null,- error: { message: "Change notice must be at Implementation to apply" }- };- }-- // Load the affected items with change type + draft refs + cutover config.- // v2: the draft make method already holds the edited BOM/BOP; release just- // activates it (and reveals the new item for Revision/New Part). Idempotency- // is per-item inside releaseAffectedItem (skip once the draft is no longer- // CO-owned).- const affectedItems = await client- .from("changeOrderAffectedItem")- .select(- "id, itemId, changeType, draftMakeMethodId, baseMakeMethodId, newItemId, supersessionMode, discontinuationDate, successorEffectivityDate"- )- .eq("changeOrderId", changeNoticeId)- .eq("companyId", companyId)- .order("sortOrder", { ascending: true })- .order("createdAt", { ascending: true });- if (affectedItems.error) {- return { data: null, error: affectedItems.error };- }-- // Release New Part (net-new) items first, so a parent assembly whose draft BOM- // references a new part resolves to an already-active item when its own method- // activates. Stable sort preserves the sortOrder/createdAt order within groups.- const ordered = [...(affectedItems.data ?? [])].sort(- (a, b) =>- (a.changeType === "New Part" ? 0 : 1) -- (b.changeType === "New Part" ? 0 : 1)- );+): Promise<ChangeNoticeTransitionResult> {+ const { id, companyId, userId, fromStatus, toStatus } = args;++ if (fromStatus === "Engineering Complete" && toStatus === "Implementation") {+ // fromStatus comes from the caller: a stale view must not open a request for+ // a notice that is no longer at Engineering Complete.+ const current = await client+ .from("changeOrder")+ .select("status")+ .eq("id", id)+ .eq("companyId", companyId)+ .maybeSingle();+ if (current.data?.status !== fromStatus) {+ return {+ data: null,+ error: {+ message:+ "The change notice was updated by someone else. Refresh and try again.",+ cause: current.error+ }+ };+ }- for (const affected of ordered) {- const result = await releaseAffectedItem(client, db, {- changeNoticeId,+ const opened = await openApprovalRequests(getCarbonServiceRole(), {+ documentType: "changeOrder",+ documentIds: [id],companyId,- userId,- affected+ userId});- if (result.error) return { data: null, error: result.error };- }- // Final compare-and-swap: Implementation → Done (the only transactional write).- try {- const updated = await db.transaction().execute(async (trx) => {- const res = await trx- .updateTable("changeOrder")- .set({ status: "Done", updatedBy: userId })- .where("id", "=", changeNoticeId)- .where("companyId", "=", companyId)- .where("status", "=", "Implementation")- .executeTakeFirst();- return Number(res.numUpdatedRows);- });- if (updated === 0) {+ if (opened.status === "opened" && opened.approverIds.length > 0) {+ await trigger("notify", {+ event: NotificationEvent.ApprovalRequested,+ companyId,+ documentId: id,+ documentType: "changeOrder",+ recipient: { type: "users", userIds: opened.approverIds },+ from: userId+ }).catch((e) =>+ logger.error("Failed to notify change notice approvers", {+ companyId,+ changeNoticeId: id,+ error: e+ })+ );+ }++ if (opened.status === "failed") {return {data: null,- error: { message: "Change notice has already been applied" }+ error: { message: "Failed to submit for approval" }+ };+ }+ if (opened.status !== "not-required") {+ return {+ data: {+ id,+ status: fromStatus,+ approval:+ opened.requested.length > 0 ? "requested" : "already-pending"+ },+ error: null};}- } catch (err) {- return {- data: null,- error: { message: err instanceof Error ? err.message : "Apply failed" }- };}- return { data: { id: changeNoticeId }, error: null };-}--// ------------------------------------------------------------------------------// releaseAffectedItem (v2) — dispatch by change type. The CO-owned Draft make-// method already holds the edited BOM/BOP, so release just:-// Version → activate the Draft on the SAME item (prior Active →-// Archived); no new item, no supersession.-// Revision → activate the Draft + reveal the new revision item + auto-// oldRev→newRev supersession.-// Replacement Part → activate the Draft + reveal the new part + auto-// affected→new supersession.-// New Part → activate the Draft + reveal the net-new part; NO-// supersession (no predecessor).-// Idempotent: once the Draft's changeOrderId is cleared it counts as released.-// ------------------------------------------------------------------------------async function releaseAffectedItem(- client: SupabaseClient<Database>,- db: Kysely<KyselyDatabase>,- input: {- changeNoticeId: string;- companyId: string;- userId: string;- affected: {- id: string;- itemId: string;- changeType: Database["public"]["Enums"]["changeOrderChangeType"];- draftMakeMethodId: string | null;- baseMakeMethodId: string | null;- newItemId: string | null;- supersessionMode: Database["public"]["Enums"]["supersessionMode"] | null;- discontinuationDate: string | null;- successorEffectivityDate: string | null;+ const result = await transitionChangeNoticeStatus(client, db, args);+ if (result.error || !result.data) {+ return {+ data: null,+ error: {+ message:+ result.error?.message ?? "Failed to update change notice status",+ cause: result.error+ }};}-): Promise<{ error: { message: string } | null }> {- const { changeNoticeId, companyId, userId, affected } = input;- const { changeType, draftMakeMethodId, newItemId } = affected;- const sourceItemId = affected.itemId;-- if (!draftMakeMethodId) {- return { error: { message: "Affected item has no draft make method" } };- }-- // Idempotency: a Draft still owned by this CO has not been released yet; once- // released we clear changeOrderId, so a re-run skips it.- const draft = await client- .from("makeMethod")- .select("changeOrderId")- .eq("id", draftMakeMethodId)- .eq("companyId", companyId)- .maybeSingle();- if (draft.error) return { error: draft.error };- if (!draft.data || !draft.data.changeOrderId) {- return { error: null };- }-- // Activate the Draft method (Draft → Active; prior Active → Archived). A- // Version simply appends a new Active version and archives the prior one — the- // prior version's rows are preserved as method history, so there is nothing to- // merge even if another CO released a newer version in the meantime.- const activated = await activateMethodVersion(client, db, {- id: draftMakeMethodId,- companyId,- userId- });- if (activated.error) {- return { error: { message: "Failed to activate method" } };- }-- // Reveal the new item for Revision / New Part (Version edits the same item).- if (newItemId) {- const reveal = await client- .from("item")- .update({- active: true,- changeOrderId: changeNoticeId,- updatedBy: userId,- updatedAt: new Date().toISOString()- })- .eq("id", newItemId)- .eq("companyId", companyId);- if (reveal.error) return { error: reveal.error };- }-- // Auto supersession: Revision (oldRev→newRev) / Replacement Part (affected→new).- // Version edits the SAME item, and a net-new New Part has NO predecessor — so- // neither writes a supersession (they still reveal their item above). This runs- // BEFORE clearing the CO-ownership marker so a supersession failure leaves the- // draft still owned by the CO (changeOrderId set) — the item is re-attempted on- // retry instead of the CO silently completing without its required supersession.- // Re-runs are safe: activate/reveal are idempotent and upsertItemSupersession is- // an upsert.- if (- (changeType === "Revision" || changeType === "Replacement Part") &&- newItemId- ) {- const sup = await upsertItemSupersession(client, {- itemId: sourceItemId,- successorItemId: newItemId,- supersessionMode: normalizeSupersessionMode(affected.supersessionMode),- // Empty per-item dates mean "effective immediately at release" — the- // supersession redirect map treats a null successorEffectivityDate as- // always-effective. Cutover timing is driven purely per affected item now.- discontinuationDate: affected.discontinuationDate ?? undefined,- successorEffectivityDate: affected.successorEffectivityDate ?? undefined,- companyId,- createdBy: userId,- updatedBy: userId- });- if (sup.error) {- logger.error("Failed to write revision supersession", {- error: sup.error- });- return { error: sup.error };- }- }-- // Clear CO ownership on the Draft — the FINAL, idempotency-marking step. Once- // cleared the draft is normal method history and a re-run skips this item.- const clear = await client- .from("makeMethod")- .update({ changeOrderId: null })- .eq("id", draftMakeMethodId)- .eq("companyId", companyId);- if (clear.error) return { error: clear.error };-- return { error: null };-}--// Coerce a possibly-null DB supersession mode to a valid enum member, defaulting-// to 'Consume First' (Q3 default) when unset/invalid.-function normalizeSupersessionMode(- mode: string | null | undefined-): Database["public"]["Enums"]["supersessionMode"] {- return (supersessionModes as readonly string[]).includes(mode ?? "")- ? (mode as Database["public"]["Enums"]["supersessionMode"])- : "Consume First";+ return { data: result.data, error: null };}// -----------------------------------------------------------------------------diff --git a/apps/erp/app/modules/items/items.service.ts b/apps/erp/app/modules/items/items.service.tsindex a71e89d89d..28ea96bc6f 100644--- a/apps/erp/app/modules/items/items.service.ts+++ b/apps/erp/app/modules/items/items.service.ts@@ -19,11 +19,18 @@ import {type SupplierPriceBreak,supplierPartCurrency} from "@carbon/database/supplier-part-price";-import { storage } from "@carbon/files";+import {+ isUnsafeStoragePath,+ storage,+ TEMP_STAGING_BUCKET+} from "@carbon/files";+import { supportedModelTypes } from "@carbon/files/cad";import { getLogger } from "@carbon/logger";+import { NotificationEvent } from "@carbon/notifications";import { serverFns } from "@carbon/server-functions";import { datetime, isUniqueViolation, withPathIds } from "@carbon/utils";import type { PostgrestError, SupabaseClient } from "@supabase/supabase-js";+import { nanoid } from "nanoid";import type { z } from "zod";import { createDocumentUploadUrl } from "~/modules/documents/documents.service";import type { GenericQueryFilters } from "~/utils/query";@@ -53,6 +60,7 @@ import {type ChangeNoticeChangeType,type ChangeNoticeError,type ChangeNoticeItemDiff,+ changeNoticeNotifyStages,changeNoticeOpenStatuses,type changeNoticeStatus,type changeNoticeTaskStatus,@@ -97,6 +105,7 @@ import {type serviceValidator,type shelfLifeModes,type shelfLifeTriggerTimings,+ supersessionModes,type supplierPartValidator,type toolValidator,type unitOfMeasureValidator@@ -7052,8 +7061,7 @@ export async function deleteChangeNotice(// Stage transition — the single guarded writer (G8), a compare-and-swap (G2).// Forward-only (isAllowedChangeNoticeTransition).// ------------------------------------------------------------------------------/** @mcp update */-export async function updateChangeNoticeStatus(+async function setChangeNoticeStatus(client: SupabaseClient<Database>,update: {id: string;@@ -7111,6 +7119,494 @@ export async function updateChangeNoticeStatus(return { data: result.data, error: null };}+// Maps a notifying stage to its notification event. Only Start / Implementation+// / Done notify; Draft / Engineering Complete are silent, so callers simply+// don't invoke this for those stages.+export const changeNoticeStageEvent: Record<string, NotificationEvent> = {+ Start: NotificationEvent.ChangeNoticeStarted,+ Implementation: NotificationEvent.ChangeNoticeImplementation,+ Done: NotificationEvent.ChangeNoticeDone+};++// Notifies the people involved in the CO — its assignee plus every action-task+// assignee — on a stage entry (best-effort). Deliberately NOT a company-wide+// broadcast; the notify function dedupes and drops the acting user itself.+export async function notifyChangeNoticeTransition(args: {+ client: SupabaseClient<Database>;+ event: NotificationEvent;+ changeNoticeId: string;+ companyId: string;+ userId: string;+}): Promise<void> {+ try {+ const [changeNotice, actionTasks] = await Promise.all([+ args.client+ .from("changeOrder")+ .select("assignee")+ .eq("id", args.changeNoticeId)+ .eq("companyId", args.companyId)+ .single(),+ args.client+ .from("changeOrderActionTask")+ .select("assignee")+ .eq("changeOrderId", args.changeNoticeId)+ .eq("companyId", args.companyId)+ .not("assignee", "is", null)+ ]);++ if (changeNotice.error) {+ logger.error("Failed to resolve change notice for CO notification", {+ error: changeNotice.error,+ changeNoticeId: args.changeNoticeId,+ companyId: args.companyId+ });+ return;+ }++ if (actionTasks.error) {+ logger.error("Failed to resolve CO action-task assignees", {+ error: actionTasks.error,+ changeNoticeId: args.changeNoticeId,+ companyId: args.companyId+ });+ }++ const userIds = [+ ...new Set(+ [+ changeNotice.data?.assignee,+ ...(actionTasks.data ?? []).map((task) => task.assignee)+ ].filter((id): id is string => !!id)+ )+ ];++ if (userIds.length === 0) return;++ const { trigger } = await import("@carbon/jobs");+ await trigger("notify", {+ event: args.event,+ companyId: args.companyId,+ documentId: args.changeNoticeId,+ recipient: { type: "users", userIds },+ from: args.userId+ });+ } catch (e) {+ logger.error("Failed to trigger change notice notification", { error: e });+ }+}++// =============================================================================+// applyChangeNotice — the top-to-bottom "release", run on the Implementation →+// Done transition (this function IS that transition). It materializes each+// affected item's CO-staged end-state onto a NEW inactive revision, activates+// it, then auto-writes the oldRev → newRev supersession (Q1/Q2/Q5).+//+// Atomicity (G2): createRevision + activateMethodVersion call the get-method /+// convert operations, each of which commits its own transaction, so this CANNOT+// be one Kysely transaction. The apply is therefore an idempotent, CAS-guarded orchestration:+// - PER-AFFECTED-ITEM idempotency: each changeOrderAffectedItem gets its+// created revision id stamped into `newItemId` at the END of its processing.+// A re-run skips any affected item whose `newItemId` is already set, so a+// partial failure re-run resumes at the first unprocessed item instead of+// re-creating revisions.+// - CO-LEVEL idempotency: the final flip to 'Done' is a compare-and-swap on+// status='Implementation', so a re-run can't double-transition the CO; only+// the closing status flip is transactional.+// =============================================================================+export async function applyChangeNotice(+ client: SupabaseClient<Database>,+ db: Kysely<KyselyDatabase>,+ args: {+ changeNoticeId: string;+ userId: string;+ companyId: string;+ }+): Promise<{ data: { id: string } | null; error: { message: string } | null }> {+ const { changeNoticeId, userId, companyId } = args;++ const cn = await client+ .from("changeOrder")+ .select("id, status")+ .eq("id", changeNoticeId)+ .eq("companyId", companyId)+ .single();+ if (cn.error || !cn.data) {+ return { data: null, error: { message: "Change notice not found" } };+ }+ if (cn.data.status !== "Implementation") {+ return {+ data: null,+ error: { message: "Change notice must be at Implementation to apply" }+ };+ }++ // Load the affected items with change type + draft refs + cutover config.+ // v2: the draft make method already holds the edited BOM/BOP; release just+ // activates it (and reveals the new item for Revision/New Part). Idempotency+ // is per-item inside releaseAffectedItem (skip once the draft is no longer+ // CO-owned).+ const affectedItems = await client+ .from("changeOrderAffectedItem")+ .select(+ "id, itemId, changeType, draftMakeMethodId, baseMakeMethodId, newItemId, supersessionMode, discontinuationDate, successorEffectivityDate"+ )+ .eq("changeOrderId", changeNoticeId)+ .eq("companyId", companyId)+ .order("sortOrder", { ascending: true })+ .order("createdAt", { ascending: true });+ if (affectedItems.error) {+ return { data: null, error: affectedItems.error };+ }++ // Release New Part (net-new) items first, so a parent assembly whose draft BOM+ // references a new part resolves to an already-active item when its own method+ // activates. Stable sort preserves the sortOrder/createdAt order within groups.+ const ordered = [...(affectedItems.data ?? [])].sort(+ (a, b) =>+ (a.changeType === "New Part" ? 0 : 1) -+ (b.changeType === "New Part" ? 0 : 1)+ );++ for (const affected of ordered) {+ const result = await releaseAffectedItem(client, db, {+ changeNoticeId,+ companyId,+ userId,+ affected+ });+ if (result.error) return { data: null, error: result.error };+ }++ // Final compare-and-swap: Implementation → Done (the only transactional write).+ try {+ const updated = await db.transaction().execute(async (trx) => {+ const res = await trx+ .updateTable("changeOrder")+ .set({ status: "Done", updatedBy: userId })+ .where("id", "=", changeNoticeId)+ .where("companyId", "=", companyId)+ .where("status", "=", "Implementation")+ .executeTakeFirst();+ return Number(res.numUpdatedRows);+ });+ if (updated === 0) {+ return {+ data: null,+ error: { message: "Change notice has already been applied" }+ };+ }+ } catch (err) {+ return {+ data: null,+ error: { message: err instanceof Error ? err.message : "Apply failed" }+ };+ }++ return { data: { id: changeNoticeId }, error: null };+}++// -----------------------------------------------------------------------------+// releaseAffectedItem (v2) — dispatch by change type. The CO-owned Draft make+// method already holds the edited BOM/BOP, so release just:+// Version → activate the Draft on the SAME item (prior Active →+// Archived); no new item, no supersession.+// Revision → activate the Draft + reveal the new revision item + auto+// oldRev→newRev supersession.+// Replacement Part → activate the Draft + reveal the new part + auto+// affected→new supersession.+// New Part → activate the Draft + reveal the net-new part; NO+// supersession (no predecessor).+// Idempotent: once the Draft's changeOrderId is cleared it counts as released.+// -----------------------------------------------------------------------------+async function releaseAffectedItem(+ client: SupabaseClient<Database>,+ db: Kysely<KyselyDatabase>,+ input: {+ changeNoticeId: string;+ companyId: string;+ userId: string;+ affected: {+ id: string;+ itemId: string;+ changeType: Database["public"]["Enums"]["changeOrderChangeType"];+ draftMakeMethodId: string | null;+ baseMakeMethodId: string | null;+ newItemId: string | null;+ supersessionMode: Database["public"]["Enums"]["supersessionMode"] | null;+ discontinuationDate: string | null;+ successorEffectivityDate: string | null;+ };+ }+): Promise<{ error: { message: string } | null }> {+ const { changeNoticeId, companyId, userId, affected } = input;+ const { changeType, draftMakeMethodId, newItemId } = affected;+ const sourceItemId = affected.itemId;++ if (!draftMakeMethodId) {+ return { error: { message: "Affected item has no draft make method" } };+ }++ // Idempotency: a Draft still owned by this CO has not been released yet; once+ // released we clear changeOrderId, so a re-run skips it.+ const draft = await client+ .from("makeMethod")+ .select("changeOrderId")+ .eq("id", draftMakeMethodId)+ .eq("companyId", companyId)+ .maybeSingle();+ if (draft.error) return { error: draft.error };+ if (!draft.data || !draft.data.changeOrderId) {+ return { error: null };+ }++ // Activate the Draft method (Draft → Active; prior Active → Archived). A+ // Version simply appends a new Active version and archives the prior one — the+ // prior version's rows are preserved as method history, so there is nothing to+ // merge even if another CO released a newer version in the meantime.+ const activated = await activateMethodVersion(client, db, {+ id: draftMakeMethodId,+ companyId,+ userId+ });+ if (activated.error) {+ return { error: { message: "Failed to activate method" } };+ }++ // Reveal the new item for Revision / New Part (Version edits the same item).+ if (newItemId) {+ const reveal = await client+ .from("item")+ .update({+ active: true,+ changeOrderId: changeNoticeId,+ updatedBy: userId,+ updatedAt: new Date().toISOString()+ })+ .eq("id", newItemId)+ .eq("companyId", companyId);+ if (reveal.error) return { error: reveal.error };+ }++ // Auto supersession: Revision (oldRev→newRev) / Replacement Part (affected→new).+ // Version edits the SAME item, and a net-new New Part has NO predecessor — so+ // neither writes a supersession (they still reveal their item above). This runs+ // BEFORE clearing the CO-ownership marker so a supersession failure leaves the+ // draft still owned by the CO (changeOrderId set) — the item is re-attempted on+ // retry instead of the CO silently completing without its required supersession.+ // Re-runs are safe: activate/reveal are idempotent and upsertItemSupersession is+ // an upsert.+ if (+ (changeType === "Revision" || changeType === "Replacement Part") &&+ newItemId+ ) {+ const sup = await upsertItemSupersession(client, {+ itemId: sourceItemId,+ successorItemId: newItemId,+ supersessionMode: normalizeSupersessionMode(affected.supersessionMode),+ // Empty per-item dates mean "effective immediately at release" — the+ // supersession redirect map treats a null successorEffectivityDate as+ // always-effective. Cutover timing is driven purely per affected item now.+ discontinuationDate: affected.discontinuationDate ?? undefined,+ successorEffectivityDate: affected.successorEffectivityDate ?? undefined,+ companyId,+ createdBy: userId,+ updatedBy: userId+ });+ if (sup.error) {+ logger.error("Failed to write revision supersession", {+ error: sup.error+ });+ return { error: sup.error };+ }+ }++ // Clear CO ownership on the Draft — the FINAL, idempotency-marking step. Once+ // cleared the draft is normal method history and a re-run skips this item.+ const clear = await client+ .from("makeMethod")+ .update({ changeOrderId: null })+ .eq("id", draftMakeMethodId)+ .eq("companyId", companyId);+ if (clear.error) return { error: clear.error };++ return { error: null };+}++// Coerce a possibly-null DB supersession mode to a valid enum member, defaulting+// to 'Consume First' (Q3 default) when unset/invalid.+function normalizeSupersessionMode(+ mode: string | null | undefined+): Database["public"]["Enums"]["supersessionMode"] {+ return (supersessionModes as readonly string[]).includes(mode ?? "")+ ? (mode as Database["public"]["Enums"]["supersessionMode"])+ : "Consume First";+}++// -----------------------------------------------------------------------------+// transitionChangeNoticeStatus — a change notice's status change after the+// approval gate, shared by the status route (items.server transitionChangeNotice,+// which opens approval requests first) and the API/MCP tool below:+// - → Done IS the release: applyChangeNotice activates the drafts.+// - Every other forward move is the guarded compare-and-swap.+// - Cancelling, or advancing past the approval gate, withdraws pending+// approval requests (Kysely: the requests belong to the approvers, not the+// caller's RLS).+// - Entering Start / Implementation / Done notifies the people on the notice.+// -----------------------------------------------------------------------------+export async function transitionChangeNoticeStatus(+ client: SupabaseClient<Database>,+ db: Kysely<KyselyDatabase>,+ args: {+ id: string;+ companyId: string;+ userId: string;+ fromStatus: (typeof changeNoticeStatus)[number];+ toStatus: (typeof changeNoticeStatus)[number];+ assignee?: string | null;+ }+): Promise<{+ data: { id: string; status: (typeof changeNoticeStatus)[number] } | null;+ error: { message: string } | null;+}> {+ const { id, companyId, userId, fromStatus, toStatus, assignee } = args;++ if (toStatus === "Done") {+ if (!isAllowedChangeNoticeTransition(fromStatus, toStatus)) {+ return {+ data: null,+ error: {+ message: `Cannot change status from ${fromStatus} to ${toStatus}`+ }+ };+ }+ const applied = await applyChangeNotice(client, db, {+ changeNoticeId: id,+ userId,+ companyId+ });+ if (applied.error || !applied.data) {+ return {+ data: null,+ error: {+ message: `Failed to apply change notice: ${applied.error?.message ?? "unknown error"}`+ }+ };+ }+ } else {+ const update = await setChangeNoticeStatus(client, {+ id,+ companyId,+ fromStatus,+ toStatus,+ assignee,+ updatedBy: userId+ });+ if (update.error || !update.data) {+ return {+ data: null,+ error: {+ message:+ update.error?.message ?? "Failed to update change notice status"+ }+ };+ }+ }++ if (+ toStatus === "Cancelled" ||+ (fromStatus === "Engineering Complete" && toStatus === "Implementation")+ ) {+ try {+ await db+ .updateTable("approvalRequest")+ .set({+ status: "Cancelled",+ updatedBy: userId,+ updatedAt: datetime.timestamp()+ })+ .where("documentType", "=", "changeOrder")+ .where("documentId", "=", id)+ .where("companyId", "=", companyId)+ .where("status", "=", "Pending")+ .execute();+ } catch (e) {+ logger.error("Failed to cancel change notice approval requests", {+ companyId,+ changeNoticeId: id,+ error: e+ });+ }+ }++ if (changeNoticeNotifyStages.includes(toStatus)) {+ await notifyChangeNoticeTransition({+ client,+ event: changeNoticeStageEvent[toStatus],+ changeNoticeId: id,+ companyId,+ userId+ });+ }++ return { data: { id, status: toStatus }, error: null };+}++/**+ * Moves a change notice to another status, releasing it on Done.+ * → Done activates its draft make methods and new revisions; cancelling withdraws pending+ * approval requests; entering Start, Implementation or Done notifies the people+ * on the notice. When the company has an enabled change-notice approval rule,+ * Engineering Complete → Implementation is refused: approval is requested and+ * decided in Carbon, and approving it performs the move.+ * @mcp update+ */+export async function updateChangeNoticeStatus(+ client: SupabaseClient<Database>,+ db: Kysely<KyselyDatabase>,+ update: {+ id: string;+ companyId: string;+ fromStatus: (typeof changeNoticeStatus)[number];+ toStatus: (typeof changeNoticeStatus)[number];+ assignee?: string | null;+ updatedBy: string;+ }+): Promise<{+ data: { id: string; status: (typeof changeNoticeStatus)[number] } | null;+ error: { message: string } | null;+}> {+ const { updatedBy, ...rest } = update;++ if (+ rest.fromStatus === "Engineering Complete" &&+ rest.toStatus === "Implementation"+ ) {+ // Kysely, not the caller's client: approval rules are readable only with+ // settings_view, and a rule the caller cannot see must still gate.+ const rule = await db+ .selectFrom("approvalRule")+ .select("id")+ .where("documentType", "=", "changeOrder")+ .where("companyId", "=", rest.companyId)+ .where("enabled", "=", true)+ .executeTakeFirst();+ if (rule) {+ return {+ data: null,+ error: {+ message:+ "Moving this change notice to Implementation needs approval. Submit it for approval in Carbon; approving it moves the status."+ }+ };+ }+ }++ return transitionChangeNoticeStatus(client, db, {+ ...rest,+ userId: updatedBy+ });+}+// -----------------------------------------------------------------------------// Change Notice Types (the "Category" lookup — configured like Issue Types)// -----------------------------------------------------------------------------@@ -7389,7 +7885,7 @@ export async function mintPlaceholderPart(// Revision → new inactive revision item + its Draft method (attrs/docs).// New Part → new inactive part number (new readableId) + copied Draft method.// All three keep the user client (the release path uses the same client for the-// same privileged method helpers — see applyChangeNotice / items.server).+// same privileged method helpers — see applyChangeNotice).// =============================================================================// Mint the next readableId for a CO-derived New Part, following the SAME numbering@@ -9588,6 +10084,268 @@ export async function getChangeNoticeDiff(return { data: { items }, error: null };}+/**+ * Create a presigned upload URL for a CAD model (STEP or another supported+ * format). First step of the two-step model upload: PUT the file bytes to the+ * returned `signedUrl`, then call `insertModelUpload` with the returned `modelId`,+ * `path` and the file's size in bytes. The file is staged in the `temp-staging`+ * bucket, as the browser upload does, so models up to 2.5 GB are accepted.+ * @mcp create — the non-browser counterpart of the CAD model dropzone+ */+export async function createModelUploadUrl(+ client: SupabaseClient<Database>,+ args: { companyId: string; name: string }+) {+ const extension = args.name.split(".").pop()?.toLowerCase() ?? "";+ if (!supportedModelTypes.includes(extension)) {+ return {+ data: null,+ error: {+ message: `Unsupported model file "${args.name}": use ${supportedModelTypes.join(", ")}`+ }+ };+ }+ const modelId = nanoid();+ const path = `${args.companyId}/models/${modelId}.${extension}`;+ const signed = await storage(client)+ .from(TEMP_STAGING_BUCKET)+ .createSignedUploadUrl(path, { upsert: true });+ if (signed.error) return { data: null, error: signed.error };+ return { data: { ...signed.data, modelId, path }, error: null };+}++const modelUploadTargets = [+ "item",+ "job",+ "salesRfqLine",+ "quoteLine",+ "salesOrderLine"+] as const;++/**+ * Record a CAD model uploaded with `createModelUploadUrl`, as the CAD model+ * dropzone does, and make it the model of the records named: an item, a job, a+ * sales RFQ line, a quote line and/or a sales order line (a line and its item+ * together, as the dropzone does). With none the model is only recorded; pass+ * its id as `modelUploadId` to `upsertPart` or `upsertJob` later. Starts the optimisation job, which also renders the thumbnail. Set+ * `convert` for a STEP file whose assembly structure is needed (assembly+ * instructions, step slides).+ * @mcp create — second step of the model upload+ */+export async function insertModelUpload(+ client: SupabaseClient<Database>,+ args: {+ companyId: string;+ createdBy: string;+ modelId: string;+ /** The `path` returned by `createModelUploadUrl`. */+ path: string;+ /** The file name, shown in the viewer. */+ name: string;+ /** The file's size in bytes. */+ size: number;+ itemId?: string;+ jobId?: string;+ salesRfqLineId?: string;+ quoteLineId?: string;+ salesOrderLineId?: string;+ /** Convert a STEP file into an assembly (GLB + graph) now, not on first use. */+ convert?: boolean;+ }+) {+ const { companyId, createdBy, modelId, path, name, size } = args;+ // The path comes from the caller: it must be the one minted for this model,+ // inside this tenant's storage prefix.+ if (+ !path.startsWith(`${companyId}/models/${modelId}.`) ||+ isUnsafeStoragePath(path)+ ) {+ return { data: null, error: { message: "Invalid model path" } };+ }++ const ids = {+ item: args.itemId,+ job: args.jobId,+ salesRfqLine: args.salesRfqLineId,+ quoteLine: args.quoteLineId,+ salesOrderLine: args.salesOrderLineId+ };+ const targets = modelUploadTargets.flatMap((table) => {+ const id = ids[table];+ return id ? [{ table, id }] : [];+ });++ // Check the records first, so a wrong id does not leave an unattached model.+ const found = await Promise.all(+ targets.map(({ table, id }) =>+ client+ .from(table)+ .select("id")+ .eq("id", id)+ .eq("companyId", companyId)+ .maybeSingle()+ )+ );+ for (const [index, result] of found.entries()) {+ if (result.error) return { data: null, error: result.error };+ if (!result.data) {+ return {+ data: null,+ error: { message: `${targets[index]!.table} not found` }+ };+ }+ }++ const inserted = await client.from("modelUpload").insert({+ id: modelId,+ modelPath: path,+ name,+ size,+ // Frozen as-uploaded bytes: `size` is later overwritten with the compacted+ // (.zst) stored size, but the viewer's reduction badge compares the original.+ originalSize: size,+ // Frozen as-uploaded path: `modelPath` is later repointed at the compacted+ // artifact (STEP → `.xbf.zst`), but downloads must serve the original bytes.+ // Mesh compaction nulls this again (its `.zst` decompresses to the original).+ originalPath: path,+ companyId,+ createdBy+ });+ if (inserted.error) return { data: null, error: inserted.error };++ const linked = await Promise.all(+ targets.map(({ table, id }) =>+ client+ .from(table)+ .update({ modelUploadId: modelId })+ .eq("id", id)+ .eq("companyId", companyId)+ .select("id")+ .maybeSingle()+ )+ );+ const failed = linked.findIndex((result) => result.error || !result.data);+ const failedTable = failed === -1 ? null : targets[failed]!.table;+ if (failedTable) {+ logger.error("Failed to attach a model upload", {+ companyId,+ modelUploadId: modelId,+ table: failedTable,+ error: linked[failed]!.error+ });+ }++ const { trigger } = await import("@carbon/jobs");+ const isStep = [".step", ".stp"].some((ext) =>+ path.toLowerCase().endsWith(ext)+ );+ if (args.convert && isStep) {+ // Skipped by the job when no assembler is configured; the viewer then+ // parses the raw model.+ try {+ await trigger("assembly-convert", {+ companyId,+ modelUploadId: modelId,+ userId: createdBy+ });+ } catch (e) {+ logger.error("Failed to start model conversion", {+ companyId,+ modelUploadId: modelId,+ error: e+ });+ }+ }+ // Optimises a mesh model into a compact GLB and renders the thumbnail. The+ // job derives the format from the stored file and skips other inputs.+ try {+ await trigger("model-optimize", {+ modelUploadId: modelId,+ companyId,+ userId: createdBy+ });+ } catch (e) {+ logger.error("Failed to start model optimisation", {+ companyId,+ modelUploadId: modelId,+ error: e+ });+ }++ if (failedTable) {+ // The model row stands (and is processed); only the link is missing.+ return {+ data: null,+ error: linked[failed]!.error ?? {+ message: `The model ${modelId} was saved but could not be attached to the ${failedTable}`+ }+ };+ }+ return { data: { modelUploadId: modelId }, error: null };+}++const thumbnailExtensions = ["png", "jpg", "jpeg", "webp"];++/**+ * Create a presigned upload URL for an item's own thumbnail image (PNG, JPEG or+ * WebP). PUT the bytes to `signedUrl`, then call `updateItemThumbnail` with the+ * returned `path`. An item thumbnail is shown in place of the one rendered from+ * its model.+ * @mcp create — the non-browser counterpart of the thumbnail upload+ */+export async function createItemThumbnailUploadUrl(+ client: SupabaseClient<Database>,+ args: { companyId: string; itemId: string; name: string }+) {+ const extension = args.name.split(".").pop()?.toLowerCase() ?? "";+ if (!thumbnailExtensions.includes(extension)) {+ return {+ data: null,+ error: {+ message: `Unsupported thumbnail "${args.name}": use ${thumbnailExtensions.join(", ")}`+ }+ };+ }+ const path = `${args.companyId}/thumbnails/${args.itemId}/${nanoid()}.${extension}`;+ const signed = await storage(client)+ .company(args.companyId)+ .createSignedUploadUrl(path, { upsert: true });+ if (signed.error) return { data: null, error: signed.error };+ return { data: { ...signed.data, path }, error: null };+}++/**+ * Set an item's thumbnail to an image uploaded with+ * `createItemThumbnailUploadUrl`, or clear it (`thumbnailPath: null`) to show+ * the one rendered from its model.+ * @mcp update+ */+export async function updateItemThumbnail(+ client: SupabaseClient<Database>,+ args: {+ companyId: string;+ itemId: string;+ thumbnailPath: string | null;+ updatedBy: string;+ }+) {+ const { companyId, itemId, thumbnailPath, updatedBy } = args;+ if (+ thumbnailPath !== null &&+ (!thumbnailPath.startsWith(`${companyId}/thumbnails/${itemId}/`) ||+ isUnsafeStoragePath(thumbnailPath))+ ) {+ return { data: null, error: { message: "Invalid thumbnail path" } };+ }+ return client+ .from("item")+ .update({ thumbnailPath, updatedBy })+ .eq("id", itemId)+ .eq("companyId", companyId)+ .select("id, thumbnailPath")+ .single();+}+/*** Create a presigned upload URL for an item (part/material/tool/consumable/service)* document. First step of the two-step upload flow: PUT the file bytes to thediff --git a/apps/erp/app/modules/settings/ui/Webhooks/WebhookForm.tsx b/apps/erp/app/modules/settings/ui/Webhooks/WebhookForm.tsxindex 03de59e581..8832f04bb8 100644--- a/apps/erp/app/modules/settings/ui/Webhooks/WebhookForm.tsx+++ b/apps/erp/app/modules/settings/ui/Webhooks/WebhookForm.tsx@@ -30,6 +30,7 @@ import { usePermissions } from "~/hooks";import { path } from "~/utils/path";import { webhookValidator } from "../../settings.models";import type { getWebhookTables } from "../../settings.service";+import WebhookSigningSecret from "./WebhookSigningSecret";type WebhookFormProps = {initialValues: z.infer<typeof webhookValidator>;@@ -129,6 +130,13 @@ const WebhookForm = ({helperText={t`The endpoint that receives a POST request with the updated data when the table is updated`}/>+ {isEditing && (+ <WebhookSigningSecret+ webhookId={initialValues.id!}+ isDisabled={!permissions.can("update", "settings")}+ />+ )}+<Separator /><Boolean name="active" label={t`Active`} bordered />diff --git a/apps/erp/app/modules/settings/ui/Webhooks/WebhookSigningSecret.tsx b/apps/erp/app/modules/settings/ui/Webhooks/WebhookSigningSecret.tsxnew file mode 100644index 0000000000..f22724498e--- /dev/null+++ b/apps/erp/app/modules/settings/ui/Webhooks/WebhookSigningSecret.tsx@@ -0,0 +1,141 @@+// 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 { useAction } from "@carbon/query";+import {+ Alert,+ AlertDescription,+ Button,+ Copy,+ FormControl,+ FormHelperText,+ FormLabel,+ HStack,+ Input as InputBase,+ InputGroup,+ InputRightElement,+ toast+} from "@carbon/react";+import { Trans, useLingui } from "@lingui/react/macro";+import { useState } from "react";+import { path } from "~/utils/path";++type SigningSecretResponse =+ | { secret: string; error: null }+ | { secret: null; error: string };++// Lives inside the webhook drawer's form, so it submits with fetcher calls,+// never a nested <form>.+export default function WebhookSigningSecret({+ webhookId,+ isDisabled+}: {+ webhookId: string;+ isDisabled: boolean;+}) {+ const { t } = useLingui();+ const [secret, setSecret] = useState<string | null>(null);+ const [confirmingRoll, setConfirmingRoll] = useState(false);++ const reveal = useAction<SigningSecretResponse>({+ onSuccess: (data) => setSecret(data.secret),+ onError: (data) => toast.error(data.error ?? t`Failed to reveal the secret`)+ });+ const roll = useAction<SigningSecretResponse>({+ onSuccess: (data) => {+ setSecret(data.secret);+ toast.success(t`Rolled the signing secret`);+ },+ onError: (data) => toast.error(data.error ?? t`Failed to roll the secret`)+ });++ const action = path.to.webhookSigningSecret(webhookId);++ return (+ <FormControl>+ <FormLabel>+ <Trans>Signing secret</Trans>+ </FormLabel>+ <InputGroup>+ <InputBase+ isReadOnly+ aria-label={t`Signing secret`}+ value={secret ?? "whsec_••••••••••••••••"}+ className="font-mono"+ />+ <InputRightElement className={secret ? "w-[2.75rem]" : "w-auto pr-1"}>+ {secret ? (+ <Copy+ text={secret}+ label={t`Copy signing secret`}+ variant="ghost"+ />+ ) : (+ <Button+ type="button"+ variant="ghost"+ size="sm"+ isDisabled={isDisabled}+ isLoading={reveal.isPending}+ onClick={() => reveal.load(action)}+ >+ <Trans>Reveal</Trans>+ </Button>+ )}+ </InputRightElement>+ </InputGroup>+ <FormHelperText>+ <Trans>+ Every delivery carries a Carbon-Signature header signed with this+ secret. Verify it to know a request came from Carbon.+ </Trans>+ </FormHelperText>+ {confirmingRoll ? (+ <Alert variant="warning" className="mt-2">+ <AlertDescription>+ <Trans>+ Deliveries are signed with the new secret at once. Update your+ endpoint with it.+ </Trans>+ </AlertDescription>+ <HStack className="mt-2">+ <Button+ type="button"+ variant="destructive"+ size="sm"+ isLoading={roll.isPending}+ onClick={() => {+ roll.submit(null, { method: "post", action });+ setConfirmingRoll(false);+ }}+ >+ <Trans>Roll secret</Trans>+ </Button>+ <Button+ type="button"+ variant="secondary"+ size="sm"+ onClick={() => setConfirmingRoll(false)}+ >+ <Trans>Cancel</Trans>+ </Button>+ </HStack>+ </Alert>+ ) : (+ <div className="mt-2">+ <Button+ type="button"+ variant="secondary"+ size="sm"+ isDisabled={isDisabled}+ isLoading={roll.isPending}+ onClick={() => setConfirmingRoll(true)}+ >+ <Trans>Roll secret</Trans>+ </Button>+ </div>+ )}+ </FormControl>+ );+}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.jsonindex 19dca72290..b6fd573d75 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@@ -1,5 +1,5 @@{- "totalTools": 1556,+ "totalTools": 1560,"modules": 15,"tools": [{"name":"account_deleteUserAttributeValue","classification":"DESTRUCTIVE","paramCount":2,"schema":"0d38e12233b4","response":"bcde375ebd4c","injectAuth":"companyId+userId","permission":"none","paginates":false},@@ -370,6 +370,8 @@{"name":"items_copyItem","classification":"WRITE","paramCount":8,"schema":"9c8674273b59","response":"4e1a8f1febce","injectAuth":"companyId+createdBy+updatedBy+userId","permission":"parts:create","paginates":false},{"name":"items_copyMakeMethod","classification":"WRITE","paramCount":8,"schema":"9c8674273b59","response":"4e1a8f1febce","injectAuth":"companyId+createdBy+updatedBy+userId","permission":"parts:create","paginates":false},{"name":"items_createItemDocumentUploadUrl","classification":"WRITE","paramCount":2,"schema":"6dcd390c3681","response":"4ad76afe0777","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create","paginates":false},+ {"name":"items_createItemThumbnailUploadUrl","classification":"WRITE","paramCount":2,"schema":"6dcd390c3681","response":"e7dd9ea63165","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create","paginates":false},+ {"name":"items_createModelUploadUrl","classification":"WRITE","paramCount":1,"schema":"098974972159","response":"56f546fd3bc7","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create","paginates":false},{"name":"items_createRevision","classification":"WRITE","paramCount":3,"schema":"59340adc1219","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create","paginates":false},{"name":"items_deleteChangeNotice","classification":"DESTRUCTIVE","paramCount":1,"schema":"29578070edb2","response":"bcde375ebd4c","injectAuth":"companyId","permission":"parts:delete","paginates":false},{"name":"items_deleteChangeNoticeAction","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"parts:delete","paginates":false},@@ -504,6 +506,7 @@{"name":"items_getUnitOfMeasuresList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"1333b6f93ca5","injectAuth":"companyId","permission":"parts:view","paginates":false},{"name":"items_getUnitOfMeasureUsage","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"bf91be568e5a","injectAuth":"companyId","permission":"parts:view","paginates":false},{"name":"items_insertChangeNotice","classification":"WRITE","paramCount":12,"schema":"c534f032ec75","response":"9645fed81b3e","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create","paginates":false},+ {"name":"items_insertModelUpload","classification":"WRITE","paramCount":10,"schema":"22ea49929c8c","response":"277f7d872d8c","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create","paginates":false},{"name":"items_lookupBuyPrice","classification":"READ","paramCount":3,"schema":"c440ca0b7efc","response":"cddf8275afa1","injectAuth":"companyId","permission":"parts:view","paginates":false},{"name":"items_matchItemIdByText","classification":"READ","paramCount":1,"schema":"f2e9aceb3e6b","response":"174e29b899b9","injectAuth":"companyId","permission":"parts:view","paginates":false},{"name":"items_removeChangeNoticeAffectedItem","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"parts:update","paginates":false},@@ -523,6 +526,7 @@{"name":"items_updateItem","classification":"WRITE","paramCount":18,"schema":"f24ba73701ab","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"parts:update","paginates":false},{"name":"items_updateItemCost","classification":"WRITE","paramCount":2,"schema":"c55de757a7e4","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"parts:update","paginates":false},{"name":"items_updateItemMethodAndSourcing","classification":"WRITE","paramCount":3,"schema":"1165eb54378a","response":"none","injectAuth":"companyId+updatedBy+userId","permission":"parts:update","paginates":false},+ {"name":"items_updateItemThumbnail","classification":"WRITE","paramCount":2,"schema":"023aafe5b1be","response":"f806de8159c8","injectAuth":"companyId+updatedBy","permission":"parts:update","paginates":false},{"name":"items_updateMaterialOrder","classification":"WRITE","paramCount":1,"schema":"c822495a7892","response":"646de62ab761","injectAuth":"companyId+updatedBy","permission":"parts:update","paginates":false,"result":"envelopes"},{"name":"items_updateMaterialProperties","classification":"WRITE","paramCount":7,"schema":"ba2c8db7ad05","response":"82322ed42796","injectAuth":"companyId+updatedBy","permission":"parts:update","paginates":false},{"name":"items_updateOperationOrder","classification":"WRITE","paramCount":1,"schema":"c822495a7892","response":"646de62ab761","injectAuth":"companyId+updatedBy","permission":"parts:update","paginates":false,"result":"envelopes"},diff --git a/apps/erp/app/routes/api+/model.upload.ts b/apps/erp/app/routes/api+/model.upload.tsindex 8293104265..80f973346e 100644--- a/apps/erp/app/routes/api+/model.upload.ts+++ b/apps/erp/app/routes/api+/model.upload.ts@@ -2,13 +2,20 @@// 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 { error } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";-import { isUnsafeStoragePath } from "@carbon/files";-import { trigger } from "@carbon/jobs";+import { getLogger } from "@carbon/logger";import type { ActionFunctionArgs } from "react-router";+import { insertModelUpload } from "~/modules/items";import { isAssemblerServiceHealthy } from "~/modules/production/production.server";+const logger = getLogger("erp", "model-upload");++const optional = (value: FormDataEntryValue | null) =>+ typeof value === "string" && value ? value : undefined;++// The browser's second step after it has staged the file. API callers use the+// `items_createModelUploadUrl` + `items_insertModelUpload` tools, which share+// `insertModelUpload` with this route.export async function action({ request }: ActionFunctionArgs) {const { client, companyId, userId } = await requirePermissions(request, {update: "parts"@@ -19,13 +26,6 @@ export async function action({ request }: ActionFunctionArgs) {const name = formData.get("name") as string;const modelPath = formData.get("modelPath") as string;const size = parseInt(formData.get("size") as string);- const convert = formData.get("convert") === "true";-- const itemId = formData.get("itemId") as string | null;- const salesRfqLineId = formData.get("salesRfqLineId") as string | null;- const quoteLineId = formData.get("quoteLineId") as string | null;- const salesOrderLineId = formData.get("salesOrderLineId") as string | null;- const jobId = formData.get("jobId") as string | null;if (!modelId) {throw new Error("File ID is required");@@ -36,98 +36,40 @@ export async function action({ request }: ActionFunctionArgs) {if (!modelPath) {throw new Error("Model path is required");}- // The path is client-supplied; never let it point outside this tenant's- // storage prefix or escape via traversal.- if (- !modelPath.startsWith(`${companyId}/`) ||- isUnsafeStoragePath(modelPath)- ) {- throw new Error("Invalid model path");- }-- const modelRecord = await client.from("modelUpload").insert({- id: modelId,- modelPath,- name,- size,- // Frozen as-uploaded bytes: `size` is later overwritten with the compacted- // (.zst) stored size, but the viewer's reduction badge compares the original.- originalSize: size,- // Frozen as-uploaded path: `modelPath` is later repointed at the compacted- // artifact (STEP → `.xbf.zst`), but downloads must serve the original bytes.- // Mesh compaction nulls this again (its `.zst` decompresses to the original).- originalPath: modelPath,- companyId,- createdBy: userId- });-- if (modelRecord.error) {- throw new Error("Failed to record upload: " + modelRecord.error.message);- }-- if (itemId) {- await client- .from("item")- .update({ modelUploadId: modelId })- .eq("id", itemId);- }- if (salesRfqLineId) {- await client- .from("salesRfqLine")- .update({ modelUploadId: modelId })- .eq("id", salesRfqLineId);- }- if (quoteLineId) {- await client- .from("quoteLine")- .update({ modelUploadId: modelId })- .eq("id", quoteLineId);- }- if (salesOrderLineId) {- await client- .from("salesOrderLine")- .update({ modelUploadId: modelId })- .eq("id", salesOrderLineId);- }- if (jobId) {- await client.from("job").update({ modelUploadId: modelId }).eq("id", jobId);- }-- // Thumbnail is generated by model-optimize on success (it renders the GLB the- // optimise produces) — firing it here, before the GLB exists, always failed.// Conversion to assembly-instruction artifacts (GLB + graph) is lazy by// default: most uploaded models never become assemblies. Callers that will// render the model on the shop floor (e.g. BOP step model slides) opt in// with `convert` so the assembler service produces the fast-loading GLB up- // front. Best-effort: STEP-only, skipped when the assembler is down — the- // viewer falls back to parsing the raw model client-side.- const isStep = [".step", ".stp"].some((ext) =>- modelPath.toLowerCase().endsWith(ext)- );- if (convert && isStep && (await isAssemblerServiceHealthy())) {- try {- await trigger("assembly-convert", {- companyId,- modelUploadId: modelId,- userId- });- } catch (err) {- console.error("Failed to start model conversion", err);- }- }+ // front. Best-effort: skipped when the assembler is down — the viewer falls+ // back to parsing the raw model client-side.+ const convert =+ formData.get("convert") === "true" && (await isAssemblerServiceHealthy());- // Eager optimisation: the assembler's /v1/optimize turns a mesh model into a- // compact optimised GLB. The job derives the format from the stored file and- // skips non-mesh inputs, so trigger unconditionally. Independent of the lazy- // assembly-convert path — most uploads never become assemblies but should- // still be optimised.- await trigger("model-optimize", {- modelUploadId: modelId,+ const result = await insertModelUpload(client, {companyId,- userId+ createdBy: userId,+ modelId,+ path: modelPath,+ name,+ size,+ itemId: optional(formData.get("itemId")),+ jobId: optional(formData.get("jobId")),+ salesRfqLineId: optional(formData.get("salesRfqLineId")),+ quoteLineId: optional(formData.get("quoteLineId")),+ salesOrderLineId: optional(formData.get("salesOrderLineId")),+ convert});+ if (result.error) {+ logger.error("Failed to record model upload", {+ companyId,+ modelId,+ error: result.error+ });+ throw new Error("Failed to record upload: " + result.error.message);+ }+return {success: true};diff --git a/apps/erp/app/routes/x+/items+/change-notice+/$id.approval.tsx b/apps/erp/app/routes/x+/items+/change-notice+/$id.approval.tsxindex d8bcb6897c..ea0c5a90e4 100644--- a/apps/erp/app/routes/x+/items+/change-notice+/$id.approval.tsx+++ b/apps/erp/app/routes/x+/items+/change-notice+/$id.approval.tsx@@ -17,7 +17,7 @@ import type { ActionFunctionArgs } from "react-router";import {changeNoticeStageEvent,notifyChangeNoticeTransition-} from "~/modules/items/items.server";+} from "~/modules/items";import { getDatabaseClient } from "~/services/database.server";import { path } from "~/utils/path";diff --git a/apps/erp/app/routes/x+/items+/change-notice+/$id.status.tsx b/apps/erp/app/routes/x+/items+/change-notice+/$id.status.tsxindex 8803e7a76a..3f8242ec8c 100644--- a/apps/erp/app/routes/x+/items+/change-notice+/$id.status.tsx+++ b/apps/erp/app/routes/x+/items+/change-notice+/$id.status.tsx@@ -4,40 +4,21 @@import { assertIsPost, error, success } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";-import { getCarbonServiceRole } from "@carbon/auth/client.server";import { flash } from "@carbon/auth/session.server";-import {- cancelPendingApprovals,- openApprovalRequests-} from "@carbon/ee/approvals/document.server";import { validationError, validator } from "@carbon/form";-import { trigger } from "@carbon/jobs";-import { getLogger } from "@carbon/logger";-import { NotificationEvent } from "@carbon/notifications";import { redirect } from "@carbon/utils";import type { ActionFunctionArgs } from "react-router";-import {- changeNoticeNotifyStages,- changeNoticeStatusValidator,- updateChangeNoticeStatus-} from "~/modules/items";-import {- applyChangeNotice,- changeNoticeStageEvent,- notifyChangeNoticeTransition-} from "~/modules/items/items.server";+import { changeNoticeStatusValidator } from "~/modules/items";+import { transitionChangeNotice } from "~/modules/items/items.server";import { getDatabaseClient } from "~/services/database.server";import { path, requestReferrer } from "~/utils/path";-const logger = getLogger("erp", "change-notice-status");-const approvalOutcomeFlash = {requested: success("Submitted for approval"),"already-pending": error(null,"This change notice is already waiting for approval"- ),- failed: error(null, "Failed to submit for approval")+ )};export async function action({ request, params }: ActionFunctionArgs) {@@ -60,144 +41,36 @@ export async function action({ request, params }: ActionFunctionArgs) {const { fromStatus, status: toStatus, assignee } = validation.data;- // An approval rule gates Engineering Complete → Implementation: submitting- // opens a request and leaves the status alone; approving it performs the- // transition (approveRequest). Without a rule the advance proceeds as usual.- const isGatedAdvance =- fromStatus === "Engineering Complete" && toStatus === "Implementation";- if (isGatedAdvance) {- // fromStatus comes from the form: a stale page must not open a request for- // a notice that is no longer at Engineering Complete.- const current = await client- .from("changeOrder")- .select("status")- .eq("id", id)- .eq("companyId", companyId)- .maybeSingle();- if (current.data?.status !== fromStatus) {- throw redirect(- requestReferrer(request) ?? path.to.changeNoticeDetails(id),- await flash(- request,- error(- current.error,- "The change notice was updated by someone else. Refresh and try again."- )- )- );- }-- const opened = await openApprovalRequests(getCarbonServiceRole(), {- documentType: "changeOrder",- documentIds: [id],- companyId,- userId- });-- if (opened.status === "opened" && opened.approverIds.length > 0) {- await trigger("notify", {- event: NotificationEvent.ApprovalRequested,- companyId,- documentId: id,- documentType: "changeOrder",- recipient: { type: "users", userIds: opened.approverIds },- from: userId- }).catch((e) =>- logger.error("Failed to notify change notice approvers", {- companyId,- changeNoticeId: id,- error: e- })- );- }-- if (opened.status !== "not-required") {- const outcome =- opened.status === "failed"- ? "failed"- : opened.requested.length > 0- ? "requested"- : "already-pending";- throw redirect(- requestReferrer(request) ?? path.to.changeNoticeDetails(id),- await flash(request, approvalOutcomeFlash[outcome])- );- }- }-- // Implementation → Done IS the apply: applyChangeNotice activates each affected- // item's CO-owned Draft make method and performs the final CAS flip to Done- // (G1/G2). All other transitions go through the plain guarded status writer.- if (toStatus === "Done") {- const applied = await applyChangeNotice(client, getDatabaseClient(), {- changeNoticeId: id,- userId,- companyId- });- if (applied.error || !applied.data) {- throw redirect(- requestReferrer(request) ?? path.to.changeNoticeDetails(id),- await flash(- request,- error(applied.error, "Failed to apply change notice")- )- );- }- } else {- const update = await updateChangeNoticeStatus(client, {- id,- companyId,- fromStatus,- toStatus,- assignee,- updatedBy: userId- });-- if (update.error || !update.data) {- throw redirect(- requestReferrer(request) ?? path.to.changeNoticeDetails(id),- await flash(- request,- error(update.error, "Failed to update change notice status")- )- );- }- }+ // The approval gate, the release on Done, approval withdrawal and stage+ // notifications all live in transitionChangeNotice, shared with the API.+ const result = await transitionChangeNotice(client, getDatabaseClient(), {+ id,+ companyId,+ userId,+ fromStatus,+ toStatus,+ assignee+ });- // Cancelling withdraws a pending request; so does a plain advance past the- // gate, which only happens when the rule was turned off after the request- // was opened.- if (toStatus === "Cancelled" || isGatedAdvance) {- const cancelled = await cancelPendingApprovals(getCarbonServiceRole(), {- documentType: "changeOrder",- documentIds: [id],- companyId,- userId- });- if (cancelled.error) {- logger.error("Failed to cancel change notice approval requests", {- companyId,- changeNoticeId: id,- error: cancelled.error- });- }+ const back = requestReferrer(request) ?? path.to.changeNoticeDetails(id);+ if (result.error) {+ throw redirect(+ back,+ await flash(+ request,+ error(result.error.cause ?? null, result.error.message)+ )+ );}-- // Notify the CO assignee + action-task assignees only on the stages that- // notify on entry (Start / Implementation / Done). Best-effort; never blocks- // the redirect.- if (changeNoticeNotifyStages.includes(toStatus)) {- await notifyChangeNoticeTransition({- client,- event: changeNoticeStageEvent[toStatus],- changeNoticeId: id,- companyId,- userId- });+ if (result.data.approval) {+ throw redirect(+ back,+ await flash(request, approvalOutcomeFlash[result.data.approval])+ );}throw redirect(- requestReferrer(request) ?? path.to.changeNoticeDetails(id),+ back,await flash(request, success("Updated change notice status")));}diff --git a/apps/erp/app/routes/x+/settings+/webhooks.secret.$id.tsx b/apps/erp/app/routes/x+/settings+/webhooks.secret.$id.tsxnew file mode 100644index 0000000000..a75755fcb7--- /dev/null+++ b/apps/erp/app/routes/x+/settings+/webhooks.secret.$id.tsx@@ -0,0 +1,92 @@+// 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 { assertIsPost } from "@carbon/auth";+import { requirePermissions } from "@carbon/auth/auth.server";+import { EntitlementError } from "@carbon/ee/entitlements.server";+import {+ revealWebhookSigningSecret,+ rotateWebhookSigningSecret+} from "@carbon/ee/webhooks.server";+import { getLogger } from "@carbon/logger";+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";+import { data } from "react-router";+import { getDatabaseClient } from "~/services/database.server";++const logger = getLogger("erp", "webhook-signing-secret");++export type WebhookSigningSecretResponse =+ | { secret: string; error: null }+ | { secret: null; error: string };++// A credential: never cached, and only for people who can change settings.+const noStore = { headers: { "Cache-Control": "no-store" } };++async function respond(+ run: () => Promise<+ { data: string; error: null } | { data: null; error: { message: string } }+ >,+ context: { companyId: string; webhookId: string }+) {+ try {+ const result = await run();+ if (result.error) {+ logger.error("Failed to read a webhook signing secret", {+ ...context,+ error: result.error+ });+ return data<WebhookSigningSecretResponse>(+ { secret: null, error: result.error.message },+ noStore+ );+ }+ return data<WebhookSigningSecretResponse>(+ { secret: result.data, error: null },+ noStore+ );+ } catch (err) {+ if (err instanceof EntitlementError) {+ return data<WebhookSigningSecretResponse>(+ { secret: null, error: "Webhooks are not included in your plan" },+ noStore+ );+ }+ throw err;+ }+}++export async function loader({ request, params }: LoaderFunctionArgs) {+ const { client, companyId } = await requirePermissions(request, {+ update: "settings"+ });+ const webhookId = params.id;+ if (!webhookId) throw new Error("Could not find id");++ return respond(+ () =>+ revealWebhookSigningSecret(client, getDatabaseClient(), {+ companyId,+ webhookId+ }),+ { companyId, webhookId }+ );+}++export async function action({ request, params }: ActionFunctionArgs) {+ assertIsPost(request);+ const { client, companyId } = await requirePermissions(request, {+ update: "settings"+ });+ const webhookId = params.id;+ if (!webhookId) throw new Error("Could not find id");++ return respond(+ () =>+ rotateWebhookSigningSecret(client, getDatabaseClient(), {+ companyId,+ webhookId+ }),+ { companyId, webhookId }+ );+}diff --git a/apps/erp/app/utils/path.ts b/apps/erp/app/utils/path.tsindex 9f6974c767..e7aa05d90c 100644--- a/apps/erp/app/utils/path.ts+++ b/apps/erp/app/utils/path.ts@@ -2627,6 +2627,8 @@ export const path = {generatePath(`${x}/warehouse-transfer/${id}/status`),warehouseTransfers: `${x}/inventory/warehouse-transfers`,webhook: (id: string) => generatePath(`${x}/settings/webhooks/${id}`),+ webhookSigningSecret: (id: string) =>+ generatePath(`${x}/settings/webhooks/secret/${id}`),webhooks: `${x}/settings/webhooks`,workCenter: (id: string) =>generatePath(`${x}/resources/work-centers/${id}`),diff --git a/docs/content/docs/building/api-keys.mdx b/docs/content/docs/building/api-keys.mdxindex f8049748dd..b8431708e2 100644--- a/docs/content/docs/building/api-keys.mdx+++ b/docs/content/docs/building/api-keys.mdx@@ -53,7 +53,7 @@ Data API writes bypass the service layer and do not recalculate derived values s## Keys versus webhooks-An **API key** authorizes requests to Carbon. A **[webhook](/docs/building/webhooks)** notifies your service when a subscribed record changes. They are independent: webhook payloads are not signed with an API key. A typical integration uses the webhook as a change notification, then fetches the current record with an API key.+An **API key** authorizes requests to Carbon. A **[webhook](/docs/building/webhooks)** notifies your service when a subscribed record changes. They are independent: a webhook is signed with its own signing secret, never with an API key. A typical integration uses the webhook as a change notification, then fetches the current record with an API key.<Cards><Card title="Webhooks" href="/docs/building/webhooks">diff --git a/docs/content/docs/building/webhooks.mdx b/docs/content/docs/building/webhooks.mdxindex 965448e2d8..a4e8c6b728 100644--- a/docs/content/docs/building/webhooks.mdx+++ b/docs/content/docs/building/webhooks.mdx@@ -17,7 +17,7 @@ Each webhook subscribes to one table. The following tables support subscriptions| Invoicing | `salesInvoice`, `purchaseInvoice` || Production | `job` || Inventory | `receipt` |-| Items | `item` |+| Items | `item`, `makeMethod`, `methodMaterial`, `methodOperation`, `modelUpload`, `changeOrder`, `changeOrderAffectedItem` || Users | `employee` |Select at least one trigger operation: **insert**, **update**, or **delete**.@@ -37,7 +37,9 @@ Carbon sends a JSON body to the configured URL. `type` identifies the operation,}```-`old` appears only for updates. For deletes, `record` contains the last state of the deleted row. Carbon sets `Content-Type: application/json`, then applies any headers in the delivery configuration.+`old` appears only for updates. For deletes, `record` contains the last state of the deleted row. Carbon sets `Content-Type: application/json` and a `Carbon-Signature` header (see [Verifying deliveries](#verifying-deliveries)).++A bill of material or routing change arrives as a change to `methodMaterial` or `methodOperation`, with the `makeMethodId` of the version it belongs to. A version's status (Draft, Active, Archived) is on `makeMethod`. A change notice's release is an update of `changeOrder` from `Implementation` to `Done`.`eventId` identifies one change. It remains stable across delivery retries and differs for each new change, including repeated updates to the same record. Use it as the idempotency key.@@ -50,6 +52,7 @@ Create and manage webhooks under **Settings → Webhooks**. A webhook has:- **URL:** where the `POST` is sent; must be a valid URL.- **Triggers:** any of insert, update, delete (at least one).- **Active:** webhooks are on by default; switch off to pause delivery.+- **Signing secret:** reveal or roll it from the webhook's edit drawer (see below).Carbon tracks success and error counts and the latest timestamp for each outcome.@@ -64,8 +67,51 @@ Delivery is **at least once**. If the endpoint does not return a success statusThe success and error counters record one outcome per change, not per attempt, so a retried-then-delivered event counts once as a success.-<Callout type="warn">-Carbon does **not** sign webhook payloads and sends no shared-secret or signature header. Use HTTPS and include an unguessable token in the URL path or query. Reject requests without the token.+## Verifying deliveries++Each webhook has its own **signing secret** (`whsec_…`). Every delivery carries a `Carbon-Signature` header. With the secret `whsec_example`, a body of `{}` sent at `1760000000` is signed:++```+Carbon-Signature: t=1760000000,v1=703d2abadc91281113b98bbc26dd6ec6ebd63072172c44b3635b575b1f1313f1+```++`t` is the time of the attempt in Unix seconds. `v1` is the hex HMAC-SHA256 of `` `${t}.${body}` ``, keyed by the whole secret string, where `body` is the raw request body. To verify a delivery:++1. Read the raw body before you parse it. Parsing and re-serialising JSON changes the bytes.+2. Compute the HMAC and compare it with `v1` in constant time.+3. Reject a `t` more than five minutes from your clock, so a captured request cannot be replayed. Each retry is signed again with a new `t`.++```ts+import { createHmac, timingSafeEqual } from "node:crypto";++export function verifyCarbonSignature(+ rawBody: string,+ header: string,+ secret: string,+ toleranceSeconds = 300+) {+ const parts = Object.fromEntries(+ header.split(",").map((part) => part.split("=", 2) as [string, string])+ );+ const timestamp = Number(parts.t);+ if (!Number.isFinite(timestamp)) return false;+ if (Math.abs(Date.now() / 1000 - timestamp) > toleranceSeconds) return false;++ const expected = createHmac("sha256", secret)+ .update(`${timestamp}.${rawBody}`)+ .digest("hex");+ const received = parts.v1 ?? "";+ return (+ received.length === expected.length &&+ timingSafeEqual(Buffer.from(received), Buffer.from(expected))+ );+}+```++Reveal the secret in the webhook's edit drawer under **Settings → Webhooks**. **Roll secret** replaces it, and the next delivery is signed with the new one, so update your endpoint at the same time. Revealing or rolling the secret requires permission to update settings.++<Callout type="info">+A delivery tells you a record changed. Treat its body as a notification, and fetch the record with an [API key](/docs/building/api-keys) before you act on it.</Callout>## Relateddiff --git a/packages/checks/src/conformance/baseline.json b/packages/checks/src/conformance/baseline.jsonindex 9462b45e2a..0da955d0c8 100644--- a/packages/checks/src/conformance/baseline.json+++ b/packages/checks/src/conformance/baseline.json@@ -544,6 +544,7 @@"no-raw-rounding::packages/ee/src/slack/lib/messages.ts::text: `Updated by <@${update.updatedBy}> at <!date^${Math.floor(","no-raw-rounding::packages/files/src/common.ts::return `${gb.toFixed(2)} GB`;","no-raw-rounding::packages/files/src/common.ts::return `${mb.toFixed(2)} MB`;",+ "no-raw-rounding::packages/jobs/src/inngest/functions/events/webhook.ts::const timestamp = Math.floor(Date.now() / 1000);","no-raw-rounding::packages/jobs/src/inngest/functions/integrations/accounting-reconciliation.ts::Math.round(amount * 100)","no-raw-rounding::packages/jobs/src/inngest/functions/integrations/accounting-reconciliation.ts::const cents = Math.round(","no-raw-rounding::packages/jobs/src/inngest/functions/integrations/accounting-sync-operations.ts::const cents = Math.round(amount * 100);",diff --git a/packages/database/src/event-system/attachments.ts b/packages/database/src/event-system/attachments.tsindex c0b75cf42d..8e0ea0bdb6 100644--- a/packages/database/src/event-system/attachments.ts+++ b/packages/database/src/event-system/attachments.ts@@ -215,6 +215,7 @@ export const attachments = {maintenanceDispatchEvent: { events: true },maintenanceSchedule: { events: true },maintenanceScheduleItem: { events: true },+ makeMethod: { events: true },material: { statement: ["broadcast_table_changes"] },materialForm: { statement: ["broadcast_table_changes"] },materialSubstance: { statement: ["broadcast_table_changes"] },@@ -224,7 +225,11 @@ export const attachments = {before: ["sync_check_method_material_self_reference"],events: true},- modelUpload: { statement: ["broadcast_table_changes", "log_table_changes"] },+ methodOperation: { events: true },+ modelUpload: {+ events: true,+ statement: ["broadcast_table_changes", "log_table_changes"]+ },nonConformance: {after: ["sync_advance_document_sequence"],events: true,diff --git a/packages/database/src/event-system/handlers/sync_webhook_subscription.sql b/packages/database/src/event-system/handlers/sync_webhook_subscription.sqlindex 56ab99f6d8..ac2b64755a 100644--- a/packages/database/src/event-system/handlers/sync_webhook_subscription.sql+++ b/packages/database/src/event-system/handlers/sync_webhook_subscription.sql@@ -11,6 +11,7 @@ BEGINPERFORM delete_event_system_subscriptions_by_name(p_old->>'companyId', 'webhook-' || (p_old->>'id'));+ PERFORM delete_webhook_signing_secret(p_old->>'companyId', p_old->>'id');RETURN;END IF;diff --git a/packages/database/src/swagger-docs-schema.ts b/packages/database/src/swagger-docs-schema.tsindex a86568f28d..e658ea689c 100644--- a/packages/database/src/swagger-docs-schema.ts+++ b/packages/database/src/swagger-docs-schema.ts@@ -106538,6 +106538,45 @@ export default {tags: ["(rpc) users_with_verified_mfa"]}},+ "/rpc/rotate_webhook_signing_secret": {+ post: {+ parameters: [+ {+ in: "body",+ name: "args",+ required: true,+ schema: {+ properties: {+ p_company_id: {+ format: "text",+ type: "string"+ },+ p_webhook_id: {+ format: "text",+ type: "string"+ }+ },+ required: ["p_company_id", "p_webhook_id"],+ type: "object"+ }+ },+ {+ $ref: "#/parameters/preferParams"+ }+ ],+ produces: [+ "application/json",+ "application/vnd.pgrst.object+json;nulls=stripped",+ "application/vnd.pgrst.object+json"+ ],+ responses: {+ "200": {+ description: "OK"+ }+ },+ tags: ["(rpc) rotate_webhook_signing_secret"]+ }+ },"/rpc/get_companies_with_employee_role": {get: {produces: [@@ -109409,6 +109448,45 @@ export default {tags: ["(rpc) get_active_job_operations_by_location"]}},+ "/rpc/get_webhook_signing_secret": {+ post: {+ parameters: [+ {+ in: "body",+ name: "args",+ required: true,+ schema: {+ properties: {+ p_company_id: {+ format: "text",+ type: "string"+ },+ p_webhook_id: {+ format: "text",+ type: "string"+ }+ },+ required: ["p_company_id", "p_webhook_id"],+ type: "object"+ }+ },+ {+ $ref: "#/parameters/preferParams"+ }+ ],+ produces: [+ "application/json",+ "application/vnd.pgrst.object+json;nulls=stripped",+ "application/vnd.pgrst.object+json"+ ],+ responses: {+ "200": {+ description: "OK"+ }+ },+ tags: ["(rpc) get_webhook_signing_secret"]+ }+ },"/rpc/populate_company_search_index": {post: {parameters: [@@ -113975,6 +114053,45 @@ export default {tags: ["(rpc) sync_archive_other_procedures"]}},+ "/rpc/delete_webhook_signing_secret": {+ post: {+ parameters: [+ {+ in: "body",+ name: "args",+ required: true,+ schema: {+ properties: {+ p_company_id: {+ format: "text",+ type: "string"+ },+ p_webhook_id: {+ format: "text",+ type: "string"+ }+ },+ required: ["p_company_id", "p_webhook_id"],+ type: "object"+ }+ },+ {+ $ref: "#/parameters/preferParams"+ }+ ],+ produces: [+ "application/json",+ "application/vnd.pgrst.object+json;nulls=stripped",+ "application/vnd.pgrst.object+json"+ ],+ responses: {+ "200": {+ description: "OK"+ }+ },+ tags: ["(rpc) delete_webhook_signing_secret"]+ }+ },"/rpc/get_material_naming_details": {get: {parameters: [diff --git a/packages/database/src/types.ts b/packages/database/src/types.tsindex dd29609670..bb206ae6ef 100644--- a/packages/database/src/types.ts+++ b/packages/database/src/types.ts@@ -91911,6 +91911,10 @@ export type Database = {Args: { p_company_id: string; p_cutoff_date: string }Returns: number}+ delete_webhook_signing_secret: {+ Args: { p_company_id: string; p_webhook_id: string }+ Returns: undefined+ }drop_audit_log_table: {Args: { p_company_id: string }Returns: undefined@@ -94102,6 +94106,10 @@ export type Database = {userCount: number}[]}+ get_webhook_signing_secret: {+ Args: { p_company_id: string; p_webhook_id: string }+ Returns: string+ }getConsolidationRates: {Args: {p_company_group_id: string@@ -94380,6 +94388,10 @@ export type Database = {Args: { p_item_id: string; p_receipt_id: string }Returns: string}+ rotate_webhook_signing_secret: {+ Args: { p_company_id: string; p_webhook_id: string }+ Returns: string+ }save_inspection_document_atomic: {Args: {p_balloons?: Jsondiff --git a/packages/database/supabase/migrations/20261016231742_structural-steel-and-wood-materials.sql b/packages/database/supabase/migrations/20261016231742_structural-steel-and-wood-materials.sqlnew file mode 100644index 0000000000..32c9506886--- /dev/null+++ b/packages/database/supabase/migrations/20261016231742_structural-steel-and-wood-materials.sql@@ -0,0 +1,166 @@+-- Structural steel and wood for fabricators (trailers, frames, weldments).+-- Adds what the seed leaves out: W- and S-beam sizes, structural (HSS) tube walls,+-- structural steel grades, and wood as a substance with a lumber shape. Names follow+-- the seeded style ('C3 x 4.1', '1" x 2" x .049"') so generated material ids stay+-- consistent. All rows are system-wide (companyId NULL).++-- Structural steel grades+INSERT INTO "materialGrade" ("id", "materialSubstanceId", "name", "companyId") VALUES+ ('steel-a992', 'steel', 'A992', null),+ ('steel-a500-gr-b', 'steel', 'A500 Gr B', null),+ ('steel-a500-gr-c', 'steel', 'A500 Gr C', null),+ ('steel-a572-gr-50', 'steel', 'A572 Gr 50', null),+ ('steel-a1011-cs', 'steel', 'A1011 CS', null),+ ('steel-a1011-ss-gr-50', 'steel', 'A1011 SS Gr 50', null),+ ('steel-a513', 'steel', 'A513', null);++INSERT INTO "materialDimension" ("id", "materialFormId", "name", "isMetric", "companyId") VALUES+ -- W-beams (wide flange): depth x weight per foot+ ('wbeam-w4-x-13', 'wbeam', 'W4 x 13', false, null),+ ('wbeam-w5-x-16', 'wbeam', 'W5 x 16', false, null),+ ('wbeam-w5-x-19', 'wbeam', 'W5 x 19', false, null),+ ('wbeam-w6-x-9', 'wbeam', 'W6 x 9', false, null),+ ('wbeam-w6-x-12', 'wbeam', 'W6 x 12', false, null),+ ('wbeam-w6-x-15', 'wbeam', 'W6 x 15', false, null),+ ('wbeam-w6-x-16', 'wbeam', 'W6 x 16', false, null),+ ('wbeam-w6-x-20', 'wbeam', 'W6 x 20', false, null),+ ('wbeam-w6-x-25', 'wbeam', 'W6 x 25', false, null),+ ('wbeam-w8-x-10', 'wbeam', 'W8 x 10', false, null),+ ('wbeam-w8-x-13', 'wbeam', 'W8 x 13', false, null),+ ('wbeam-w8-x-15', 'wbeam', 'W8 x 15', false, null),+ ('wbeam-w8-x-18', 'wbeam', 'W8 x 18', false, null),+ ('wbeam-w8-x-21', 'wbeam', 'W8 x 21', false, null),+ ('wbeam-w8-x-24', 'wbeam', 'W8 x 24', false, null),+ ('wbeam-w8-x-28', 'wbeam', 'W8 x 28', false, null),+ ('wbeam-w8-x-31', 'wbeam', 'W8 x 31', false, null),+ ('wbeam-w8-x-35', 'wbeam', 'W8 x 35', false, null),+ ('wbeam-w8-x-40', 'wbeam', 'W8 x 40', false, null),+ ('wbeam-w10-x-12', 'wbeam', 'W10 x 12', false, null),+ ('wbeam-w10-x-15', 'wbeam', 'W10 x 15', false, null),+ ('wbeam-w10-x-17', 'wbeam', 'W10 x 17', false, null),+ ('wbeam-w10-x-19', 'wbeam', 'W10 x 19', false, null),+ ('wbeam-w10-x-22', 'wbeam', 'W10 x 22', false, null),+ ('wbeam-w10-x-26', 'wbeam', 'W10 x 26', false, null),+ ('wbeam-w10-x-30', 'wbeam', 'W10 x 30', false, null),+ ('wbeam-w10-x-33', 'wbeam', 'W10 x 33', false, null),+ ('wbeam-w12-x-14', 'wbeam', 'W12 x 14', false, null),+ ('wbeam-w12-x-16', 'wbeam', 'W12 x 16', false, null),+ ('wbeam-w12-x-19', 'wbeam', 'W12 x 19', false, null),+ ('wbeam-w12-x-22', 'wbeam', 'W12 x 22', false, null),+ ('wbeam-w12-x-26', 'wbeam', 'W12 x 26', false, null),+ ('wbeam-w12-x-30', 'wbeam', 'W12 x 30', false, null),+ ('wbeam-w12-x-35', 'wbeam', 'W12 x 35', false, null),+ ('wbeam-w12-x-40', 'wbeam', 'W12 x 40', false, null),+ ('wbeam-w14-x-22', 'wbeam', 'W14 x 22', false, null),+ ('wbeam-w14-x-26', 'wbeam', 'W14 x 26', false, null),+ ('wbeam-w14-x-30', 'wbeam', 'W14 x 30', false, null),+ ('wbeam-w14-x-34', 'wbeam', 'W14 x 34', false, null),+ ('wbeam-w16-x-26', 'wbeam', 'W16 x 26', false, null),+ ('wbeam-w16-x-31', 'wbeam', 'W16 x 31', false, null),+ -- S-beams (American standard)+ ('sbeam-s3-x-5-7', 'sbeam', 'S3 x 5.7', false, null),+ ('sbeam-s3-x-7-5', 'sbeam', 'S3 x 7.5', false, null),+ ('sbeam-s4-x-7-7', 'sbeam', 'S4 x 7.7', false, null),+ ('sbeam-s4-x-9-5', 'sbeam', 'S4 x 9.5', false, null),+ ('sbeam-s5-x-10', 'sbeam', 'S5 x 10', false, null),+ ('sbeam-s6-x-12-5', 'sbeam', 'S6 x 12.5', false, null),+ ('sbeam-s6-x-17-25', 'sbeam', 'S6 x 17.25', false, null),+ ('sbeam-s8-x-18-4', 'sbeam', 'S8 x 18.4', false, null),+ ('sbeam-s8-x-23', 'sbeam', 'S8 x 23', false, null),+ ('sbeam-s10-x-25-4', 'sbeam', 'S10 x 25.4', false, null),+ ('sbeam-s10-x-35', 'sbeam', 'S10 x 35', false, null),+ ('sbeam-s12-x-31-8', 'sbeam', 'S12 x 31.8', false, null),+ ('sbeam-s12-x-35', 'sbeam', 'S12 x 35', false, null),+ -- Structural rectangular tube (HSS): nominal 1/8, 3/16, 1/4 walls+ ('recttube-1x2x-125', 'recttube', '1" x 2" x .125"', false, null),+ ('recttube-1x3x-125', 'recttube', '1" x 3" x .125"', false, null),+ ('recttube-1-5x2x-125', 'recttube', '1.5" x 2" x .125"', false, null),+ ('recttube-1-5x2x-188', 'recttube', '1.5" x 2" x .188"', false, null),+ ('recttube-1-5x2-5x-125', 'recttube', '1.5" x 2.5" x .125"', false, null),+ ('recttube-1-5x2-5x-188', 'recttube', '1.5" x 2.5" x .188"', false, null),+ ('recttube-1-5x3x-125', 'recttube', '1.5" x 3" x .125"', false, null),+ ('recttube-1-5x3x-188', 'recttube', '1.5" x 3" x .188"', false, null),+ ('recttube-2x3x-125', 'recttube', '2" x 3" x .125"', false, null),+ ('recttube-2x3x-188', 'recttube', '2" x 3" x .188"', false, null),+ ('recttube-2x3x-250', 'recttube', '2" x 3" x .250"', false, null),+ ('recttube-2x4x-125', 'recttube', '2" x 4" x .125"', false, null),+ ('recttube-2x4x-188', 'recttube', '2" x 4" x .188"', false, null),+ ('recttube-2x4x-250', 'recttube', '2" x 4" x .250"', false, null),+ ('recttube-2x5x-188', 'recttube', '2" x 5" x .188"', false, null),+ ('recttube-2x5x-250', 'recttube', '2" x 5" x .250"', false, null),+ ('recttube-2x6x-188', 'recttube', '2" x 6" x .188"', false, null),+ ('recttube-2x6x-250', 'recttube', '2" x 6" x .250"', false, null),+ ('recttube-3x4x-125', 'recttube', '3" x 4" x .125"', false, null),+ ('recttube-3x4x-188', 'recttube', '3" x 4" x .188"', false, null),+ ('recttube-3x4x-250', 'recttube', '3" x 4" x .250"', false, null),+ ('recttube-3x5x-188', 'recttube', '3" x 5" x .188"', false, null),+ ('recttube-3x5x-250', 'recttube', '3" x 5" x .250"', false, null),+ ('recttube-3x6x-188', 'recttube', '3" x 6" x .188"', false, null),+ ('recttube-3x6x-250', 'recttube', '3" x 6" x .250"', false, null),+ ('recttube-4x6x-188', 'recttube', '4" x 6" x .188"', false, null),+ ('recttube-4x6x-250', 'recttube', '4" x 6" x .250"', false, null),+ ('recttube-4x8x-250', 'recttube', '4" x 8" x .250"', false, null),+ -- Structural square tube (HSS)+ ('squaretube-1x-125', 'squaretube', '1" x .125"', false, null),+ ('squaretube-1-5x-125', 'squaretube', '1.5" x .125"', false, null),+ ('squaretube-1-5x-188', 'squaretube', '1.5" x .188"', false, null),+ ('squaretube-2x-125', 'squaretube', '2" x .125"', false, null),+ ('squaretube-2x-188', 'squaretube', '2" x .188"', false, null),+ ('squaretube-2x-250', 'squaretube', '2" x .250"', false, null),+ ('squaretube-2-5x-125', 'squaretube', '2.5" x .125"', false, null),+ ('squaretube-2-5x-188', 'squaretube', '2.5" x .188"', false, null),+ ('squaretube-2-5x-250', 'squaretube', '2.5" x .250"', false, null),+ ('squaretube-3x-125', 'squaretube', '3" x .125"', false, null),+ ('squaretube-3x-188', 'squaretube', '3" x .188"', false, null),+ ('squaretube-3x-250', 'squaretube', '3" x .250"', false, null),+ ('squaretube-4x-188', 'squaretube', '4" x .188"', false, null),+ ('squaretube-4x-250', 'squaretube', '4" x .250"', false, null),+ ('squaretube-5x-250', 'squaretube', '5" x .250"', false, null),+ ('squaretube-6x-250', 'squaretube', '6" x .250"', false, null),+ -- Round bar for pins+ ('roundbar-1-75', 'roundbar', '1.75"', false, null),+ ('roundbar-2-25', 'roundbar', '2.25"', false, null);++-- Wood: a substance and a lumber shape+INSERT INTO "materialSubstance" ("id", "name", "code", "createdBy") VALUES+ ('wood', 'Wood', 'WOOD', 'system');++INSERT INTO "materialForm" ("id", "name", "code", "createdBy") VALUES+ ('lumber', 'Lumber', 'LUMBER', 'system');++-- Lumber in nominal sizes, as it is ordered+INSERT INTO "materialDimension" ("id", "materialFormId", "name", "isMetric", "companyId") VALUES+ ('lumber-1x4', 'lumber', '1" x 4"', false, null),+ ('lumber-1x6', 'lumber', '1" x 6"', false, null),+ ('lumber-1x8', 'lumber', '1" x 8"', false, null),+ ('lumber-1x10', 'lumber', '1" x 10"', false, null),+ ('lumber-1x12', 'lumber', '1" x 12"', false, null),+ ('lumber-2x4', 'lumber', '2" x 4"', false, null),+ ('lumber-2x6', 'lumber', '2" x 6"', false, null),+ ('lumber-2x8', 'lumber', '2" x 8"', false, null),+ ('lumber-2x10', 'lumber', '2" x 10"', false, null),+ ('lumber-2x12', 'lumber', '2" x 12"', false, null),+ ('lumber-4x4', 'lumber', '4" x 4"', false, null),+ ('lumber-4x6', 'lumber', '4" x 6"', false, null),+ ('lumber-6x6', 'lumber', '6" x 6"', false, null);++-- Species and grade+INSERT INTO "materialGrade" ("id", "materialSubstanceId", "name", "companyId") VALUES+ ('wood-syp-no1', 'wood', 'SYP #1', null),+ ('wood-syp-no2', 'wood', 'SYP #2', null),+ ('wood-df-no2', 'wood', 'DF #2', null),+ ('wood-spf-no2', 'wood', 'SPF #2', null),+ ('wood-red-oak', 'wood', 'Red Oak', null),+ ('wood-white-oak', 'wood', 'White Oak', null),+ ('wood-apitong', 'wood', 'Apitong', null);++-- Treatment+INSERT INTO "materialType" ("id", "name", "code", "materialSubstanceId", "materialFormId", "companyId") VALUES+ ('pressure-treated-wood-lumber', 'Pressure Treated', 'PT', 'wood', 'lumber', null),+ ('kiln-dried-wood-lumber', 'Kiln Dried', 'KD', 'wood', 'lumber', null),+ ('green-wood-lumber', 'Green', 'GR', 'wood', 'lumber', null);++-- Surfacing+INSERT INTO "materialFinish" ("id", "name", "materialSubstanceId", "companyId") VALUES+ ('s4s-wood', 'S4S', 'wood', null),+ ('rough-sawn-wood', 'Rough Sawn', 'wood', null);diff --git a/packages/database/supabase/migrations/20261017030257_webhook-method-and-model-tables.sql b/packages/database/supabase/migrations/20261017030257_webhook-method-and-model-tables.sqlnew file mode 100644index 0000000000..6e0b23fb09--- /dev/null+++ b/packages/database/supabase/migrations/20261017030257_webhook-method-and-model-tables.sql@@ -0,0 +1,13 @@+-- Webhooks for make methods, their materials and operations, CAD models and change+-- notices, so an integration that pushes a BOM or a model hears when someone edits+-- it, and when a change notice releases. makeMethod, methodOperation and+-- modelUpload get their event triggers from the generated migration that follows;+-- the others already emit events.+INSERT INTO "webhookTable" ("table", "module", "name") VALUES+ ('makeMethod', 'Items', 'Make Method'),+ ('methodMaterial', 'Items', 'Method Material'),+ ('methodOperation', 'Items', 'Method Operation'),+ ('modelUpload', 'Items', 'Model Upload'),+ ('changeOrder', 'Items', 'Change Notice'),+ ('changeOrderAffectedItem', 'Items', 'Change Notice Item')+ON CONFLICT ("table") DO NOTHING;diff --git a/packages/database/supabase/migrations/20261017030352_webhook-signing-secrets.sql b/packages/database/supabase/migrations/20261017030352_webhook-signing-secrets.sqlnew file mode 100644index 0000000000..8e9c31c1e0--- /dev/null+++ b/packages/database/supabase/migrations/20261017030352_webhook-signing-secrets.sql@@ -0,0 +1,93 @@+-- Each webhook signs its deliveries with its own secret, kept in Supabase Vault+-- like integration secrets (20260817122916). The secret is created on first use —+-- the first delivery, or the first time someone reveals it in Settings — so+-- existing webhooks are signed from their next delivery on.+--+-- Secrets are named 'webhook:<companyId>:<webhookId>'. Reading and rolling are+-- service-role only; the delivery job and the settings route call them over a+-- direct (Kysely) connection.++CREATE OR REPLACE FUNCTION get_webhook_signing_secret(p_company_id text, p_webhook_id text)+RETURNS text LANGUAGE plpgsql SECURITY DEFINER SET search_path = public, vault, extensions AS $$+DECLARE+ v_name text := 'webhook:' || p_company_id || ':' || p_webhook_id;+ v_secret text;+BEGIN+ IF current_setting('role', true) IN ('anon', 'authenticated') THEN+ RAISE EXCEPTION 'get_webhook_signing_secret is service role only'+ USING ERRCODE = 'insufficient_privilege';+ END IF;++ IF NOT EXISTS (+ SELECT 1 FROM "webhook" WHERE "id" = p_webhook_id AND "companyId" = p_company_id+ ) THEN+ RETURN NULL;+ END IF;++ SELECT decrypted_secret INTO v_secret FROM vault.decrypted_secrets WHERE name = v_name;+ IF v_secret IS NOT NULL THEN+ RETURN v_secret;+ END IF;++ v_secret := 'whsec_' || encode(extensions.gen_random_bytes(32), 'hex');+ BEGIN+ PERFORM vault.create_secret(v_secret, v_name, 'Carbon webhook signing secret');+ EXCEPTION WHEN unique_violation THEN+ -- A concurrent delivery created it first; use that one.+ SELECT decrypted_secret INTO v_secret FROM vault.decrypted_secrets WHERE name = v_name;+ END;+ RETURN v_secret;+END;+$$;++CREATE OR REPLACE FUNCTION rotate_webhook_signing_secret(p_company_id text, p_webhook_id text)+RETURNS text LANGUAGE plpgsql SECURITY DEFINER SET search_path = public, vault, extensions AS $$+DECLARE+ v_name text := 'webhook:' || p_company_id || ':' || p_webhook_id;+ v_id uuid;+ v_secret text;+BEGIN+ IF current_setting('role', true) IN ('anon', 'authenticated') THEN+ RAISE EXCEPTION 'rotate_webhook_signing_secret is service role only'+ USING ERRCODE = 'insufficient_privilege';+ END IF;++ IF NOT EXISTS (+ SELECT 1 FROM "webhook" WHERE "id" = p_webhook_id AND "companyId" = p_company_id+ ) THEN+ RETURN NULL;+ END IF;++ v_secret := 'whsec_' || encode(extensions.gen_random_bytes(32), 'hex');+ SELECT id INTO v_id FROM vault.secrets WHERE name = v_name;+ IF v_id IS NULL THEN+ PERFORM vault.create_secret(v_secret, v_name, 'Carbon webhook signing secret');+ ELSE+ -- Vault restricts direct UPDATE on vault.secrets; use the supported function.+ PERFORM vault.update_secret(v_id, v_secret);+ END IF;+ RETURN v_secret;+END;+$$;++-- Called by sync_webhook_subscription when a webhook row is deleted, including a+-- company delete's cascade. SECURITY INVOKER: from the SECURITY DEFINER+-- interceptor dispatcher it runs as the owner; called through the API it runs as+-- the caller, who cannot read the vault. Removes the secret only once its webhook+-- is gone.+CREATE OR REPLACE FUNCTION delete_webhook_signing_secret(p_company_id text, p_webhook_id text)+RETURNS void LANGUAGE plpgsql SECURITY INVOKER SET search_path = public, vault AS $$+BEGIN+ IF EXISTS (+ SELECT 1 FROM "webhook" WHERE "id" = p_webhook_id AND "companyId" = p_company_id+ ) THEN+ RETURN;+ END IF;+ DELETE FROM vault.secrets WHERE name = 'webhook:' || p_company_id || ':' || p_webhook_id;+END;+$$;++-- Restricted by the guards above, never by REVOKE EXECUTE: on this Postgres image+-- an API role calling a function it lacks EXECUTE on crashes the backend.++NOTIFY pgrst, 'reload schema';diff --git a/packages/database/supabase/migrations/20261017030423_webhook-method-and-model-events.sql b/packages/database/supabase/migrations/20261017030423_webhook-method-and-model-events.sqlnew file mode 100644index 0000000000..b5b35713b5--- /dev/null+++ b/packages/database/supabase/migrations/20261017030423_webhook-method-and-model-events.sql@@ -0,0 +1,55 @@+-- Generated by `pnpm --filter @carbon/database authz migration` from packages/database/src/authz. Do not edit.++-- Ships these rules to databases where `authz sync` does not run after migrations yet.++CREATE OR REPLACE FUNCTION public.sync_webhook_subscription(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public'+AS $function$+DECLARE+ v_ops TEXT[];+ v_name TEXT;+BEGIN+ IF p_operation = 'DELETE' THEN+ PERFORM delete_event_system_subscriptions_by_name(+ p_old->>'companyId', 'webhook-' || (p_old->>'id')+ );+ PERFORM delete_webhook_signing_secret(p_old->>'companyId', p_old->>'id');+ RETURN;+ END IF;++ v_name := 'webhook-' || (p_new->>'id');++ -- Clear first: `table` is editable and uniqueness is (companyId, name, table),+ -- so an upsert would strand the old row and fire the webhook twice.+ PERFORM delete_event_system_subscriptions_by_name(p_new->>'companyId', v_name);++ v_ops := ARRAY[]::TEXT[];+ IF (p_new->>'onInsert')::BOOLEAN THEN v_ops := array_append(v_ops, 'INSERT'); END IF;+ IF (p_new->>'onUpdate')::BOOLEAN THEN v_ops := array_append(v_ops, 'UPDATE'); END IF;+ IF (p_new->>'onDelete')::BOOLEAN THEN v_ops := array_append(v_ops, 'DELETE'); END IF;++ IF array_length(v_ops, 1) IS NULL THEN+ RETURN;+ END IF;++ PERFORM create_event_system_subscription(+ v_name,+ p_new->>'table',+ p_new->>'companyId',+ v_ops,+ 'WEBHOOK',+ jsonb_build_object('url', p_new->>'url', 'webhookId', p_new->>'id'),+ '{}'::jsonb,+ COALESCE((p_new->>'active')::BOOLEAN, false)+ );+END;+$function$;++-- event triggers (packages/database/src/event-system/attachments.ts)+SET lock_timeout = '5s';+SELECT set_event_triggers('makeMethod', ARRAY[]::text[], ARRAY[]::text[], true, ARRAY[]::text[]);+SELECT set_event_triggers('methodOperation', ARRAY[]::text[], ARRAY[]::text[], true, ARRAY[]::text[]);+SELECT set_event_triggers('modelUpload', ARRAY[]::text[], ARRAY[]::text[], true, ARRAY['broadcast_table_changes', 'log_table_changes']::text[]);+RESET lock_timeout;diff --git a/packages/ee/src/webhooks.server.ts b/packages/ee/src/webhooks.server.tsindex 80710b3720..7b685daebd 100644--- a/packages/ee/src/webhooks.server.ts+++ b/packages/ee/src/webhooks.server.ts@@ -3,8 +3,10 @@// (packages/ee/LICENSE). Not AGPL. Running, modifying, or copying it beyond those terms requires a commercial license.import type { Database } from "@carbon/database";+import type { Kysely, KyselyDatabase } from "@carbon/database/client";import { sanitize } from "@carbon/utils";import type { SupabaseClient } from "@supabase/supabase-js";+import { sql } from "kysely";import { requireEntitlement } from "./entitlements.server";/**@@ -102,3 +104,75 @@ export async function deactivateWebhooks(.update({ active: false }).eq("companyId", companyId);}++/**+ * A webhook's signing secret (`whsec_…`), created on first use and kept in+ * Supabase Vault. Null when the webhook does not exist in the company. Runtime:+ * the delivery job signs with it, so this is not gated (delivery is). The vault+ * functions refuse API roles, so `db` is the direct connection.+ */+export async function getWebhookSigningSecret(+ db: Kysely<KyselyDatabase>,+ companyId: string,+ webhookId: string+): Promise<string | null> {+ const { rows } = await sql<{ secret: string | null }>`+ SELECT get_webhook_signing_secret(${companyId}, ${webhookId}) AS secret+ `.execute(db);+ return rows[0]?.secret ?? null;+}++// The secret functions run over the direct connection, outside RLS: reading the+// webhook through the caller's client is what proves they may see it.+async function requireVisibleWebhook(+ client: SupabaseClient<Database>,+ companyId: string,+ webhookId: string+) {+ const webhook = await client+ .from("webhook")+ .select("id")+ .eq("id", webhookId)+ .eq("companyId", companyId)+ .maybeSingle();+ if (webhook.error) return webhook.error;+ if (!webhook.data) return { message: "Webhook not found" };+ return null;+}++export async function revealWebhookSigningSecret(+ client: SupabaseClient<Database>,+ db: Kysely<KyselyDatabase>,+ { companyId, webhookId }: { companyId: string; webhookId: string }+): Promise<+ { data: string; error: null } | { data: null; error: { message: string } }+> {+ await requireEntitlement(client, companyId, "WEBHOOKS");+ const notVisible = await requireVisibleWebhook(client, companyId, webhookId);+ if (notVisible) return { data: null, error: notVisible };+ const secret = await getWebhookSigningSecret(db, companyId, webhookId);+ if (!secret) return { data: null, error: { message: "Webhook not found" } };+ return { data: secret, error: null };+}++/**+ * Replace a webhook's signing secret. Deliveries are signed with the new secret+ * at once, so the receiving endpoint must be updated with it.+ */+export async function rotateWebhookSigningSecret(+ client: SupabaseClient<Database>,+ db: Kysely<KyselyDatabase>,+ { companyId, webhookId }: { companyId: string; webhookId: string }+): Promise<+ { data: string; error: null } | { data: null; error: { message: string } }+> {+ await requireEntitlement(client, companyId, "WEBHOOKS");+ const notVisible = await requireVisibleWebhook(client, companyId, webhookId);+ if (notVisible) return { data: null, error: notVisible };+ const { rows } = await sql<{ secret: string | null }>`+ SELECT rotate_webhook_signing_secret(${companyId}, ${webhookId}) AS secret+ `.execute(db);+ const secret = rows[0]?.secret;+ if (!secret) return { data: null, error: { message: "Webhook not found" } };+ return { data: secret, error: null };+}diff --git a/packages/jobs/manifests/schema.json b/packages/jobs/manifests/schema.jsonindex 4c9e64cf18..fad9043033 100644--- a/packages/jobs/manifests/schema.json+++ b/packages/jobs/manifests/schema.json@@ -1,11 +1,11 @@{"kind": "carbon-company-backup","version": 1,- "schemaVersion": "20261016163158",+ "schemaVersion": "20261017030423","sourceCompanyId": "schema-baseline","sourceCompanyGroupId": null,"sourceCompanyName": null,- "exportedAt": "2026-10-17T02:16:43.251Z",+ "exportedAt": "2026-10-17T04:44:57.424Z","exportedBy": "schema-baseline","label": "schema baseline","includeStorage": "none",diff --git a/packages/jobs/src/inngest/functions/events/webhook-body.test.ts b/packages/jobs/src/inngest/functions/events/webhook-body.test.tsindex 8cd29bea1d..6662ca31dc 100644--- a/packages/jobs/src/inngest/functions/events/webhook-body.test.ts+++ b/packages/jobs/src/inngest/functions/events/webhook-body.test.ts@@ -2,8 +2,9 @@// 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 { createHmac } from "node:crypto";import { describe, expect, it } from "vitest";-import { toWebhookBody } from "./webhook-body.ts";+import { signWebhookBody, toWebhookBody } from "./webhook-body.ts";// PUBLIC contract — these cases mirror the deleted `webhook` edge function// (git history: packages/database/supabase/functions/webhook/index.ts), which@@ -151,3 +152,32 @@ describe("toWebhookBody", () => {expect(attempt().eventId).toBe("77");});});++// PUBLIC contract — the verification sample in docs/building/webhooks.mdx.+describe("signWebhookBody", () => {+ const secret = "whsec_test";+ const body = JSON.stringify({ type: "INSERT", record: { id: "c1" } });++ it('signs "<t>.<body>" with HMAC-SHA256 keyed by the whole secret', () => {+ const expected = createHmac("sha256", secret)+ .update(`1760000000.${body}`)+ .digest("hex");+ expect(signWebhookBody(secret, body, 1760000000)).toBe(+ `t=1760000000,v1=${expected}`+ );+ });++ it("pins a known answer", () => {+ // Computed outside Node (Python's hmac), so a consumer in any language agrees.+ expect(signWebhookBody("whsec_abc", "{}", 1)).toBe(+ "t=1,v1=07301c55760783275ad3b893a15abe1d07b70c8e96b12a204061b23840f0b05b"+ );+ });++ it("changes with the body, the timestamp and the secret", () => {+ const base = signWebhookBody(secret, body, 1);+ expect(signWebhookBody(secret, `${body} `, 1)).not.toBe(base);+ expect(signWebhookBody(secret, body, 2)).not.toBe(base);+ expect(signWebhookBody("whsec_other", body, 1)).not.toBe(base);+ });+});diff --git a/packages/jobs/src/inngest/functions/events/webhook-body.ts b/packages/jobs/src/inngest/functions/events/webhook-body.tsindex 34c28a8921..24853154e1 100644--- a/packages/jobs/src/inngest/functions/events/webhook-body.ts+++ b/packages/jobs/src/inngest/functions/events/webhook-body.ts@@ -2,6 +2,7 @@// 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 { createHmac } from "node:crypto";import { z } from "zod";// Separate from webhook.ts so the contract below is testable — the handler@@ -76,3 +77,27 @@ export function toWebhookBody(eventId};}++/**+ * The header carrying a delivery's signature. PUBLIC contract — see+ * docs/content/docs/building/webhooks.mdx.+ */+export const WEBHOOK_SIGNATURE_HEADER = "Carbon-Signature";++/**+ * Sign a delivery: `t=<unix seconds>,v1=<hex HMAC-SHA256>`, where the HMAC is+ * keyed by the webhook's signing secret (the whole `whsec_…` string) and runs+ * over `${t}.${body}`, the exact bytes sent. The scheme Carbon itself verifies+ * for Paperless Parts. A consumer recomputes it from the raw request body and+ * rejects an old `t` to stop replays.+ */+export function signWebhookBody(+ secret: string,+ body: string,+ timestamp: number+): string {+ const signature = createHmac("sha256", secret)+ .update(`${timestamp}.${body}`)+ .digest("hex");+ return `t=${timestamp},v1=${signature}`;+}diff --git a/packages/jobs/src/inngest/functions/events/webhook.ts b/packages/jobs/src/inngest/functions/events/webhook.tsindex d0b36f3304..05312f17fb 100644--- a/packages/jobs/src/inngest/functions/events/webhook.ts+++ b/packages/jobs/src/inngest/functions/events/webhook.ts@@ -4,9 +4,16 @@import { getCarbonServiceRole } from "@carbon/auth/client.server";import { companyHasFeature } from "@carbon/ee/plan.server";+import { getWebhookSigningSecret } from "@carbon/ee/webhooks.server";import axios from "axios";+import { getJobDatabaseClient } from "../../../db.ts";import { inngest } from "../../client.ts";-import { toWebhookBody, webhookPayloadSchema } from "./webhook-body.ts";+import {+ signWebhookBody,+ toWebhookBody,+ WEBHOOK_SIGNATURE_HEADER,+ webhookPayloadSchema+} from "./webhook-body.ts";const RETRIES = 3;// A documented part of the webhook contract (docs: building/webhooks).@@ -53,18 +60,38 @@ export const webhookFunction = inngest.createFunction(}await step.run("send-webhook", async () => {- // Never log payload.url — the docs tell customers to treat the URL itself- // as the secret (an unguessable token in the path or query), since Carbon- // does not sign webhooks. webhookId identifies it without leaking that.+ // Never log payload.url or the secret — a URL may still carry a token of+ // its own. webhookId identifies the webhook without leaking either.logger.info(`Firing ${body.type} webhook ${webhookId ?? "<unknown>"} for ${payload.data.table}`);+ // Serialised once: the signature covers these exact bytes, and the+ // receiver verifies the raw body it is sent. Signed per attempt, so a+ // retry carries a fresh timestamp.+ const raw = JSON.stringify(body);+ const secret = webhookId+ ? await getWebhookSigningSecret(+ getJobDatabaseClient(),+ payload.companyId,+ webhookId+ )+ : null;+ if (!secret) {+ // The subscription outlived its webhook row; nothing to deliver for.+ logger.warn(+ `No signing secret for webhook ${webhookId ?? "<unknown>"}; skipping delivery`+ );+ return;+ }+ const timestamp = Math.floor(Date.now() / 1000);+try {- await axios.post(payload.url, body, {+ await axios.post(payload.url, raw, {headers: {"Content-Type": "application/json",- ...payload.config.headers+ ...payload.config.headers,+ [WEBHOOK_SIGNATURE_HEADER]: signWebhookBody(secret, raw, timestamp)},timeout: WEBHOOK_TIMEOUT_MS});diff --git a/packages/locale/locales/de/erp.po b/packages/locale/locales/de/erp.poindex 4323bc5721..dc0251bdf2 100644--- a/packages/locale/locales/de/erp.po+++ b/packages/locale/locales/de/erp.po@@ -5900,6 +5900,9 @@ msgstr "Dienstleistungsnummer kopieren"msgid "Copy service unique identifier"msgstr "Eindeutige Kennung der Dienstleistung kopieren"+msgid "Copy signing secret"+msgstr "Signierungsgeheimnis kopieren"+msgid "Copy supplier quote unique identifier"msgstr "Eindeutige Kennung des Lieferantenangebots kopieren"@@ -7550,6 +7553,9 @@ msgstr "Geliefert"msgid "Delivered on"msgstr "Geliefert am"+msgid "Deliveries are signed with the new secret at once. Update your endpoint with it."+msgstr "Auslieferungen werden sofort mit dem neuen Geheimnis signiert. Aktualisieren Sie Ihren Endpunkt damit."+msgid "Delivery Date"msgstr "Liefertermin"@@ -9214,6 +9220,9 @@ msgstr "Alle unternehmensbezogenen Datensätze. Zugangsdaten, Integrations-Tokenmsgid "Every condition must match"msgstr "Jede Bedingung muss erfüllt sein"+msgid "Every delivery carries a Carbon-Signature header signed with this secret. Verify it to know a request came from Carbon."+msgstr "Jede Auslieferung enthält einen Carbon-Signature-Header, der mit diesem Geheimnis signiert ist. Überprüfen Sie ihn, um sicherzustellen, dass die Anfrage von Carbon stammt."+msgid "Every in-scope test passes in your configured system, with your data."msgstr "Jeder Test im Umfang wird in Ihrem konfigurierten System mit Ihren Daten bestanden."@@ -9839,6 +9848,12 @@ msgstr "Fehler beim Ändern der Bildgröße: {errorMessage}"msgid "Failed to retrieve CSV column data."msgstr "Fehler beim Abrufen der CSV-Spaltendaten."+msgid "Failed to reveal the secret"+msgstr "Fehler beim Anzeigen des Geheimnisses"++msgid "Failed to roll the secret"+msgstr "Fehler beim Erneuern des Geheimnisses"+msgid "Failed to save configuration rule"msgstr "Fehler beim Speichern der Konfigurationsregel"@@ -18920,6 +18935,9 @@ msgstr "Rev {revision}"msgid "Rev {revisionId}"msgstr "Änderung {revisionId}"+msgid "Reveal"+msgstr "Anzeigen"+msgid "Reveal account number"msgstr "Kontonummer anzeigen"@@ -19186,6 +19204,12 @@ msgstr "Rollen und Verantwortlichkeiten"msgid "Roles that set default permissions for new employees"msgstr "Rollen, die Standardberechtigungen für neue Mitarbeiter festlegen"+msgid "Roll secret"+msgstr "Geheimnis erneuern"++msgid "Rolled the signing secret"+msgstr "Signierungsgeheimnis erneuert"+msgid "Room to grow without bolting on more tools"msgstr "Platz zum Wachsen ohne zusätzliche Tools"@@ -20796,6 +20820,9 @@ msgstr "Die Anmeldung erfordert auch einen Einmalcode aus Ihrer Authentifizierunmsgid "Signing in will no longer require a code. Enter the current 6-digit code from your authenticator app to confirm."msgstr "Die Anmeldung erfordert keinen Code mehr. Geben Sie den aktuellen 6-stelligen Code aus Ihrer Authentifikator-App ein, um zu bestätigen."+msgid "Signing secret"+msgstr "Signierungsgeheimnis"+msgid "Simultaneous"msgstr "Simultan"diff --git a/packages/locale/locales/en/erp.po b/packages/locale/locales/en/erp.poindex ab7e7dc02e..d9cfd45957 100644--- a/packages/locale/locales/en/erp.po+++ b/packages/locale/locales/en/erp.po@@ -5900,6 +5900,9 @@ msgstr "Copy service number"msgid "Copy service unique identifier"msgstr "Copy service unique identifier"+msgid "Copy signing secret"+msgstr "Copy signing secret"+msgid "Copy supplier quote unique identifier"msgstr "Copy supplier quote unique identifier"@@ -7550,6 +7553,9 @@ msgstr "Delivered"msgid "Delivered on"msgstr "Delivered on"+msgid "Deliveries are signed with the new secret at once. Update your endpoint with it."+msgstr "Deliveries are signed with the new secret at once. Update your endpoint with it."+msgid "Delivery Date"msgstr "Delivery Date"@@ -9214,6 +9220,9 @@ msgstr "Every company-scoped record. Credentials, integration tokens and webhookmsgid "Every condition must match"msgstr "Every condition must match"+msgid "Every delivery carries a Carbon-Signature header signed with this secret. Verify it to know a request came from Carbon."+msgstr "Every delivery carries a Carbon-Signature header signed with this secret. Verify it to know a request came from Carbon."+msgid "Every in-scope test passes in your configured system, with your data."msgstr "Every in-scope test passes in your configured system, with your data."@@ -9839,6 +9848,12 @@ msgstr "Failed to resize image: {errorMessage}"msgid "Failed to retrieve CSV column data."msgstr "Failed to retrieve CSV column data."+msgid "Failed to reveal the secret"+msgstr "Failed to reveal the secret"++msgid "Failed to roll the secret"+msgstr "Failed to roll the secret"+msgid "Failed to save configuration rule"msgstr "Failed to save configuration rule"@@ -18920,6 +18935,9 @@ msgstr "Rev {revision}"msgid "Rev {revisionId}"msgstr "Rev {revisionId}"+msgid "Reveal"+msgstr "Reveal"+msgid "Reveal account number"msgstr "Reveal account number"@@ -19186,6 +19204,12 @@ msgstr "Roles and Responsibilities"msgid "Roles that set default permissions for new employees"msgstr "Roles that set default permissions for new employees"+msgid "Roll secret"+msgstr "Roll secret"++msgid "Rolled the signing secret"+msgstr "Rolled the signing secret"+msgid "Room to grow without bolting on more tools"msgstr "Room to grow without bolting on more tools"@@ -20796,6 +20820,9 @@ msgstr "Signing in also requires a one-time code from your authenticator app"msgid "Signing in will no longer require a code. Enter the current 6-digit code from your authenticator app to confirm."msgstr "Signing in will no longer require a code. Enter the current 6-digit code from your authenticator app to confirm."+msgid "Signing secret"+msgstr "Signing secret"+msgid "Simultaneous"msgstr "Simultaneous"diff --git a/packages/locale/locales/es/erp.po b/packages/locale/locales/es/erp.poindex 0269c25dfd..6e8c206874 100644--- a/packages/locale/locales/es/erp.po+++ b/packages/locale/locales/es/erp.po@@ -5900,6 +5900,9 @@ msgstr "Copiar número de servicio"msgid "Copy service unique identifier"msgstr "Copiar identificador único del servicio"+msgid "Copy signing secret"+msgstr "Copiar secreto de firma"+msgid "Copy supplier quote unique identifier"msgstr "Copiar identificador único de cotización del proveedor"@@ -7550,6 +7553,9 @@ msgstr "Entregado"msgid "Delivered on"msgstr "Entregado el"+msgid "Deliveries are signed with the new secret at once. Update your endpoint with it."+msgstr "Las entregas se firman con el nuevo secreto inmediatamente. Actualiza tu punto final con él."+msgid "Delivery Date"msgstr "Fecha de Entrega"@@ -9214,6 +9220,9 @@ msgstr "Todos los registros de la empresa. Las credenciales, los tokens de integmsgid "Every condition must match"msgstr "Todas las condiciones deben coincidir"+msgid "Every delivery carries a Carbon-Signature header signed with this secret. Verify it to know a request came from Carbon."+msgstr "Cada entrega lleva un encabezado Carbon-Signature firmado con este secreto. Verifica que provino de Carbon."+msgid "Every in-scope test passes in your configured system, with your data."msgstr "Todas las pruebas dentro del alcance se aprueban en su sistema configurado, con sus datos."@@ -9839,6 +9848,12 @@ msgstr "Error al redimensionar la imagen: {errorMessage}"msgid "Failed to retrieve CSV column data."msgstr "Error al recuperar los datos de columna del CSV."+msgid "Failed to reveal the secret"+msgstr "No se pudo revelar el secreto"++msgid "Failed to roll the secret"+msgstr "No se pudo cambiar el secreto"+msgid "Failed to save configuration rule"msgstr "Error al guardar la regla de configuración"@@ -18920,6 +18935,9 @@ msgstr "Rev {revision}"msgid "Rev {revisionId}"msgstr "Rev. {revisionId}"+msgid "Reveal"+msgstr "Revelar"+msgid "Reveal account number"msgstr "Revelar número de cuenta"@@ -19186,6 +19204,12 @@ msgstr "Roles y Responsabilidades"msgid "Roles that set default permissions for new employees"msgstr "Roles que establecen permisos predeterminados para nuevos empleados"+msgid "Roll secret"+msgstr "Cambiar secreto"++msgid "Rolled the signing secret"+msgstr "Se cambió el secreto de firma"+msgid "Room to grow without bolting on more tools"msgstr "Espacio para crecer sin añadir más herramientas"@@ -20796,6 +20820,9 @@ msgstr "Iniciar sesión también requiere un código de un solo uso de tu aplicamsgid "Signing in will no longer require a code. Enter the current 6-digit code from your authenticator app to confirm."msgstr "Iniciar sesión ya no requerirá un código. Ingrese el código de 6 dígitos actual de su aplicación de autenticación para confirmar."+msgid "Signing secret"+msgstr "Secreto de firma"+msgid "Simultaneous"msgstr "Simultáneo"diff --git a/packages/locale/locales/fr/erp.po b/packages/locale/locales/fr/erp.poindex 58a2015987..4dd7134bbc 100644--- a/packages/locale/locales/fr/erp.po+++ b/packages/locale/locales/fr/erp.po@@ -5900,6 +5900,9 @@ msgstr "Copier le numéro de service"msgid "Copy service unique identifier"msgstr "Copier l'identifiant unique du service"+msgid "Copy signing secret"+msgstr "Copier la clé de signature"+msgid "Copy supplier quote unique identifier"msgstr "Copier l'identifiant unique du devis fournisseur"@@ -7550,6 +7553,9 @@ msgstr "Livré"msgid "Delivered on"msgstr "Livré le"+msgid "Deliveries are signed with the new secret at once. Update your endpoint with it."+msgstr "Les livraisons sont signées avec la nouvelle clé immédiatement. Mettez à jour votre endpoint avec cette clé."+msgid "Delivery Date"msgstr "Date de livraison"@@ -9214,6 +9220,9 @@ msgstr "Tous les enregistrements de l'entreprise. Les identifiants, jetons d'intmsgid "Every condition must match"msgstr "Chaque condition doit correspondre"+msgid "Every delivery carries a Carbon-Signature header signed with this secret. Verify it to know a request came from Carbon."+msgstr "Chaque livraison contient un en-tête Carbon-Signature signé avec ce secret. Vérifiez-le pour confirmer qu'une requête provient de Carbon."+msgid "Every in-scope test passes in your configured system, with your data."msgstr "Tous les tests dans le périmètre réussissent dans votre système configuré, avec vos données."@@ -9839,6 +9848,12 @@ msgstr "Échec du redimensionnement de l'image : {errorMessage}"msgid "Failed to retrieve CSV column data."msgstr "Impossible de récupérer les données de colonne CSV."+msgid "Failed to reveal the secret"+msgstr "Impossible de révéler la clé"++msgid "Failed to roll the secret"+msgstr "Impossible de renouveler la clé"+msgid "Failed to save configuration rule"msgstr "Échec de l'enregistrement de la règle de configuration"@@ -18920,6 +18935,9 @@ msgstr "Rév {revision}"msgid "Rev {revisionId}"msgstr "Rév {revisionId}"+msgid "Reveal"+msgstr "Révéler"+msgid "Reveal account number"msgstr "Afficher le numéro de compte"@@ -19186,6 +19204,12 @@ msgstr "Rôles et responsabilités"msgid "Roles that set default permissions for new employees"msgstr "Rôles qui définissent les autorisations par défaut pour les nouveaux employés"+msgid "Roll secret"+msgstr "Renouveler la clé"++msgid "Rolled the signing secret"+msgstr "Clé de signature renouvelée"+msgid "Room to grow without bolting on more tools"msgstr "Espace pour croître sans ajouter d'autres outils"@@ -20796,6 +20820,9 @@ msgstr "La connexion nécessite également un code à usage unique de votre applmsgid "Signing in will no longer require a code. Enter the current 6-digit code from your authenticator app to confirm."msgstr "La connexion ne nécessitera plus de code. Entrez le code à 6 chiffres actuel de votre application d'authentification pour confirmer."+msgid "Signing secret"+msgstr "Clé de signature"+msgid "Simultaneous"msgstr "Simultané"diff --git a/packages/locale/locales/hi/erp.po b/packages/locale/locales/hi/erp.poindex b7cbe1f6ce..a92e8e1d6d 100644--- a/packages/locale/locales/hi/erp.po+++ b/packages/locale/locales/hi/erp.po@@ -5900,6 +5900,9 @@ msgstr "सेवा संख्या कॉपी करें"msgid "Copy service unique identifier"msgstr "सेवा अनन्य पहचानकर्ता कॉपी करें"+msgid "Copy signing secret"+msgstr "हस्ताक्षर रहस्य की प्रतिलिपि बनाएं"+msgid "Copy supplier quote unique identifier"msgstr "आपूर्तिकर्ता कोटेशन की विशिष्ट पहचान नकल करें"@@ -7550,6 +7553,9 @@ msgstr "डिलीवर किया गया"msgid "Delivered on"msgstr "को डिलीवर किया गया"+msgid "Deliveries are signed with the new secret at once. Update your endpoint with it."+msgstr "डिलीवरीज़ नए रहस्य के साथ तुरंत हस्ताक्षरित की जाती हैं। अपना एंडपॉइंट इससे अपडेट करें।"+msgid "Delivery Date"msgstr "डिलीवरी तिथि"@@ -9214,6 +9220,9 @@ msgstr "हर कंपनी-स्कोप्ड रिकॉर्ड।msgid "Every condition must match"msgstr "हर शर्त मेल खानी चाहिए"+msgid "Every delivery carries a Carbon-Signature header signed with this secret. Verify it to know a request came from Carbon."+msgstr "प्रत्येक डिलीवरी इस रहस्य के साथ हस्ताक्षरित एक Carbon-Signature हेडर ले जाती है। यह सत्यापित करें कि अनुरोध Carbon से आया है।"+msgid "Every in-scope test passes in your configured system, with your data."msgstr "आपकी कॉन्फ़िगर की गई सिस्टम में, आपके डेटा के साथ, हर स्कोप में आने वाला टेस्ट पास होता है।"@@ -9839,6 +9848,12 @@ msgstr "छवि को पुनः आकार देने में विmsgid "Failed to retrieve CSV column data."msgstr "CSV कॉलम डेटा प्राप्त करने में विफल।"+msgid "Failed to reveal the secret"+msgstr "रहस्य को प्रकट करने में विफल"++msgid "Failed to roll the secret"+msgstr "रहस्य को रोल करने में विफल"+msgid "Failed to save configuration rule"msgstr "कॉन्फ़िगरेशन नियम सहेजने में विफल"@@ -18920,6 +18935,9 @@ msgstr "Rev {revision}"msgid "Rev {revisionId}"msgstr "संस्करण {revisionId}"+msgid "Reveal"+msgstr "प्रकट करें"+msgid "Reveal account number"msgstr "खाता संख्या दिखाएँ"@@ -19186,6 +19204,12 @@ msgstr "भूमिकाएं और जिम्मेदारियां"msgid "Roles that set default permissions for new employees"msgstr "नई कर्मचारियों के लिए डिफ़ॉल्ट अनुमतियां सेट करने वाली भूमिकाएं"+msgid "Roll secret"+msgstr "रहस्य को रोल करें"++msgid "Rolled the signing secret"+msgstr "हस्ताक्षर रहस्य को रोल कर दिया"+msgid "Room to grow without bolting on more tools"msgstr "बिना अतिरिक्त उपकरण जोड़े बढ़ने की गुंजाइश"@@ -20796,6 +20820,9 @@ msgstr "साइन इन करने के लिए आपके प्रmsgid "Signing in will no longer require a code. Enter the current 6-digit code from your authenticator app to confirm."msgstr "साइन इन करने के लिए अब कोड की आवश्यकता नहीं होगी। पुष्टि करने के लिए अपने ऑथेंटिकेटर ऐप से वर्तमान 6-अंकीय कोड दर्ज करें।"+msgid "Signing secret"+msgstr "हस्ताक्षर रहस्य"+msgid "Simultaneous"msgstr "समवर्ती"diff --git a/packages/locale/locales/it/erp.po b/packages/locale/locales/it/erp.poindex 3fbed6555e..8fbe83c73b 100644--- a/packages/locale/locales/it/erp.po+++ b/packages/locale/locales/it/erp.po@@ -5900,6 +5900,9 @@ msgstr "Copia numero servizio"msgid "Copy service unique identifier"msgstr "Copia identificatore univoco del servizio"+msgid "Copy signing secret"+msgstr "Copia chiave di firma"+msgid "Copy supplier quote unique identifier"msgstr "Copia identificatore univoco offerta del fornitore"@@ -7550,6 +7553,9 @@ msgstr "Consegnato"msgid "Delivered on"msgstr "Consegnato il"+msgid "Deliveries are signed with the new secret at once. Update your endpoint with it."+msgstr "Le consegne vengono firmate con la nuova chiave immediatamente. Aggiorna il tuo endpoint con essa."+msgid "Delivery Date"msgstr "Data di consegna"@@ -9214,6 +9220,9 @@ msgstr "Tutti i record dell'azienda. Credenziali, token di integrazione e webhoomsgid "Every condition must match"msgstr "Ogni condizione deve corrispondere"+msgid "Every delivery carries a Carbon-Signature header signed with this secret. Verify it to know a request came from Carbon."+msgstr "Ogni consegna contiene un'intestazione Carbon-Signature firmata con questa chiave. Verificala per assicurarti che la consegna provenga da Carbon."+msgid "Every in-scope test passes in your configured system, with your data."msgstr "Ogni test nell'ambito passa nel tuo sistema configurato, con i tuoi dati."@@ -9839,6 +9848,12 @@ msgstr "Impossibile ridimensionare l'immagine: {errorMessage}"msgid "Failed to retrieve CSV column data."msgstr "Impossibile recuperare i dati delle colonne CSV."+msgid "Failed to reveal the secret"+msgstr "Impossibile rivelare la chiave"++msgid "Failed to roll the secret"+msgstr "Impossibile rigenerare la chiave"+msgid "Failed to save configuration rule"msgstr "Impossibile salvare la regola di configurazione"@@ -18920,6 +18935,9 @@ msgstr "Rev {revision}"msgid "Rev {revisionId}"msgstr "Riv {revisionId}"+msgid "Reveal"+msgstr "Rivela"+msgid "Reveal account number"msgstr "Rivela numero di conto"@@ -19186,6 +19204,12 @@ msgstr "Ruoli e Responsabilità"msgid "Roles that set default permissions for new employees"msgstr "Ruoli che impostano le autorizzazioni predefinite per i nuovi dipendenti"+msgid "Roll secret"+msgstr "Rigenera la chiave"++msgid "Rolled the signing secret"+msgstr "Chiave di firma rigenerata"+msgid "Room to grow without bolting on more tools"msgstr "Spazio per crescere senza aggiungere altri strumenti"@@ -20796,6 +20820,9 @@ msgstr "L'accesso richiede anche un codice monouso dalla tua app autenticatore"msgid "Signing in will no longer require a code. Enter the current 6-digit code from your authenticator app to confirm."msgstr "L'accesso non richiederà più un codice. Inserisci il codice a 6 cifre attuale dall'app autenticatore per confermare."+msgid "Signing secret"+msgstr "Chiave di firma"+msgid "Simultaneous"msgstr "Simultanea"diff --git a/packages/locale/locales/ja/erp.po b/packages/locale/locales/ja/erp.poindex 1e9469f03e..a1e619001d 100644--- a/packages/locale/locales/ja/erp.po+++ b/packages/locale/locales/ja/erp.po@@ -5900,6 +5900,9 @@ msgstr "サービス番号をコピー"msgid "Copy service unique identifier"msgstr "サービスの一意な識別子をコピー"+msgid "Copy signing secret"+msgstr "署名シークレットをコピー"+msgid "Copy supplier quote unique identifier"msgstr "仕入先見積の一意識別子をコピー"@@ -7550,6 +7553,9 @@ msgstr "配送済"msgid "Delivered on"msgstr "配送日"+msgid "Deliveries are signed with the new secret at once. Update your endpoint with it."+msgstr "配信は新しいシークレットで直ちに署名されます。エンドポイントを更新してください。"+msgid "Delivery Date"msgstr "納期"@@ -9214,6 +9220,9 @@ msgstr "会社に属するすべてのレコード。認証情報、連携トーmsgid "Every condition must match"msgstr "すべての条件が一致する必要があります"+msgid "Every delivery carries a Carbon-Signature header signed with this secret. Verify it to know a request came from Carbon."+msgstr "すべての配信にはこのシークレットで署名されたCarbon-Signatureヘッダーが含まれます。Carbonからのリクエストであることを検証してください。"+msgid "Every in-scope test passes in your configured system, with your data."msgstr "スコープ内のすべてのテストが、設定されたシステムで、あなたのデータを使用して合格します。"@@ -9839,6 +9848,12 @@ msgstr "画像のリサイズに失敗しました: {errorMessage}"msgid "Failed to retrieve CSV column data."msgstr "CSVの列データの取得に失敗しました。"+msgid "Failed to reveal the secret"+msgstr "シークレットの表示に失敗しました"++msgid "Failed to roll the secret"+msgstr "シークレットのロールに失敗しました"+msgid "Failed to save configuration rule"msgstr "設定ルールの保存に失敗しました"@@ -18920,6 +18935,9 @@ msgstr "Rev {revision}"msgid "Rev {revisionId}"msgstr "改版 {revisionId}"+msgid "Reveal"+msgstr "表示"+msgid "Reveal account number"msgstr "銀行口座番号を表示"@@ -19186,6 +19204,12 @@ msgstr "役割と責任"msgid "Roles that set default permissions for new employees"msgstr "新しい従業員のデフォルト権限を設定するロール"+msgid "Roll secret"+msgstr "シークレットをロール"++msgid "Rolled the signing secret"+msgstr "署名シークレットをロールしました"+msgid "Room to grow without bolting on more tools"msgstr "さらに多くのツールを追加することなく成長する余地"@@ -20796,6 +20820,9 @@ msgstr "サインインには認証アプリからのワンタイムコードもmsgid "Signing in will no longer require a code. Enter the current 6-digit code from your authenticator app to confirm."msgstr "サインインにはコードが不要になります。確認するために、認証器アプリの現在の6桁のコードを入力します。"+msgid "Signing secret"+msgstr "署名シークレット"+msgid "Simultaneous"msgstr "同時"diff --git a/packages/locale/locales/ko/erp.po b/packages/locale/locales/ko/erp.poindex 78dacc09d5..e12db3c891 100644--- a/packages/locale/locales/ko/erp.po+++ b/packages/locale/locales/ko/erp.po@@ -5900,6 +5900,9 @@ msgstr "서비스 번호 복사"msgid "Copy service unique identifier"msgstr "서비스 고유 식별자 복사"+msgid "Copy signing secret"+msgstr "서명 비밀키 복사"+msgid "Copy supplier quote unique identifier"msgstr "공급업체 견적 고유 식별자 복사"@@ -7550,6 +7553,9 @@ msgstr "배송됨"msgid "Delivered on"msgstr "배송일"+msgid "Deliveries are signed with the new secret at once. Update your endpoint with it."+msgstr "전달이 즉시 새 비밀키로 서명됩니다. 엔드포인트를 업데이트하세요."+msgid "Delivery Date"msgstr "납기일"@@ -9214,6 +9220,9 @@ msgstr "모든 회사 범위의 레코드. 자격증명, 연동 토큰 및 웹msgid "Every condition must match"msgstr "모든 조건이 일치해야 함"+msgid "Every delivery carries a Carbon-Signature header signed with this secret. Verify it to know a request came from Carbon."+msgstr "모든 전달은 이 비밀키로 서명된 Carbon-Signature 헤더를 포함합니다. 이를 검증하여 요청이 Carbon에서 온 것을 확인할 수 있습니다."+msgid "Every in-scope test passes in your configured system, with your data."msgstr "설정한 시스템에서 귀사의 데이터로 범위 내 모든 테스트를 통과합니다."@@ -9839,6 +9848,12 @@ msgstr "이미지 크기를 조정하지 못했습니다: {errorMessage}"msgid "Failed to retrieve CSV column data."msgstr "CSV 열 데이터를 가져오지 못했습니다."+msgid "Failed to reveal the secret"+msgstr "비밀키 표시에 실패했습니다"++msgid "Failed to roll the secret"+msgstr "비밀키 갱신에 실패했습니다"+msgid "Failed to save configuration rule"msgstr "설정 규칙을 저장하지 못했습니다"@@ -18920,6 +18935,9 @@ msgstr "Rev {revision}"msgid "Rev {revisionId}"msgstr "개정 {revisionId}"+msgid "Reveal"+msgstr "표시"+msgid "Reveal account number"msgstr "계좌번호 표시"@@ -19186,6 +19204,12 @@ msgstr "역할 및 책임"msgid "Roles that set default permissions for new employees"msgstr "신규 직원의 기본 권한을 설정하는 역할"+msgid "Roll secret"+msgstr "비밀키 갱신"++msgid "Rolled the signing secret"+msgstr "서명 비밀키를 갱신했습니다"+msgid "Room to grow without bolting on more tools"msgstr "추가 도구 없이도 성장할 수 있는 여유"@@ -20796,6 +20820,9 @@ msgstr "로그인에는 인증자 앱의 일회용 코드도 필요합니다"msgid "Signing in will no longer require a code. Enter the current 6-digit code from your authenticator app to confirm."msgstr "로그인할 때 더 이상 코드가 필요하지 않습니다. 확인하려면 인증 앱의 현재 6자리 코드를 입력하세요."+msgid "Signing secret"+msgstr "서명 비밀키"+msgid "Simultaneous"msgstr "동시"diff --git a/packages/locale/locales/pl/erp.po b/packages/locale/locales/pl/erp.poindex e63d6319cf..50b0e5b238 100644--- a/packages/locale/locales/pl/erp.po+++ b/packages/locale/locales/pl/erp.po@@ -5900,6 +5900,9 @@ msgstr "Skopiuj numer usługi"msgid "Copy service unique identifier"msgstr "Skopiuj unikalny identyfikator usługi"+msgid "Copy signing secret"+msgstr "Skopiuj tajny klucz podpisywania"+msgid "Copy supplier quote unique identifier"msgstr "Skopiuj unikalny identyfikator oferty dostawcy"@@ -7550,6 +7553,9 @@ msgstr "Dostarczona"msgid "Delivered on"msgstr "Dostarczono dnia"+msgid "Deliveries are signed with the new secret at once. Update your endpoint with it."+msgstr "Dostawy są podpisywane nowym tajnym kluczem natychmiast. Aktualizuj swój punkt końcowy za jego pomocą."+msgid "Delivery Date"msgstr "Data dostawy"@@ -9214,6 +9220,9 @@ msgstr "Wszystkie rekordy firmy. Dane uwierzytelniające, tokeny integracji i wemsgid "Every condition must match"msgstr "Każdy warunek musi się zgadzać"+msgid "Every delivery carries a Carbon-Signature header signed with this secret. Verify it to know a request came from Carbon."+msgstr "Każda dostawa zawiera nagłówek Carbon-Signature podpisany tym tajnym kluczem. Zweryfikuj go, aby wiedzieć, że żądanie pochodzi z Carbon."+msgid "Every in-scope test passes in your configured system, with your data."msgstr "Każdy test w zakresie przechodzi w Twoim skonfigurowanym systemie, z Twoimi danymi."@@ -9839,6 +9848,12 @@ msgstr "Nie udało się zmienić rozmiaru obrazu: {errorMessage}"msgid "Failed to retrieve CSV column data."msgstr "Nie udało się pobrać danych kolumn CSV."+msgid "Failed to reveal the secret"+msgstr "Nie udało się ujawnić tajnego klucza"++msgid "Failed to roll the secret"+msgstr "Nie udało się obrócić tajnego klucza"+msgid "Failed to save configuration rule"msgstr "Nie udało się zapisać reguły konfiguracji"@@ -18920,6 +18935,9 @@ msgstr "Wer. {revision}"msgid "Rev {revisionId}"msgstr "Rev {revisionId}"+msgid "Reveal"+msgstr "Ujawnij"+msgid "Reveal account number"msgstr "Odsłoń numer konta"@@ -19186,6 +19204,12 @@ msgstr "Role i odpowiedzialności"msgid "Roles that set default permissions for new employees"msgstr "Role, które ustawiają domyślne uprawnienia dla nowych pracowników"+msgid "Roll secret"+msgstr "Obróć tajny klucz"++msgid "Rolled the signing secret"+msgstr "Obrócono tajny klucz podpisywania"+msgid "Room to grow without bolting on more tools"msgstr "Miejsce do wzrostu bez dodawania kolejnych narzędzi"@@ -20796,6 +20820,9 @@ msgstr "Logowanie wymaga również kodu jednorazowego z aplikacji authenticator"msgid "Signing in will no longer require a code. Enter the current 6-digit code from your authenticator app to confirm."msgstr "Logowanie nie będzie już wymagać kodu. Wpisz bieżący 6-cyfrowy kod z aplikacji Authenticator, aby potwierdzić."+msgid "Signing secret"+msgstr "Tajny klucz podpisywania"+msgid "Simultaneous"msgstr "Jednocześnie"diff --git a/packages/locale/locales/pt/erp.po b/packages/locale/locales/pt/erp.poindex ba8f1c4f86..88f59b86e8 100644--- a/packages/locale/locales/pt/erp.po+++ b/packages/locale/locales/pt/erp.po@@ -5900,6 +5900,9 @@ msgstr "Copiar número do serviço"msgid "Copy service unique identifier"msgstr "Copiar identificador exclusivo do serviço"+msgid "Copy signing secret"+msgstr "Copiar chave de assinatura"+msgid "Copy supplier quote unique identifier"msgstr "Copiar identificador único da cotação do fornecedor"@@ -7550,6 +7553,9 @@ msgstr "Entregue"msgid "Delivered on"msgstr "Entregue em"+msgid "Deliveries are signed with the new secret at once. Update your endpoint with it."+msgstr "As entregas são assinadas com a nova chave imediatamente. Atualize seu endpoint com ela."+msgid "Delivery Date"msgstr "Data de Entrega"@@ -9214,6 +9220,9 @@ msgstr "Todos os registros da empresa. Credenciais, tokens de integração e webmsgid "Every condition must match"msgstr "Todas as condições devem corresponder"+msgid "Every delivery carries a Carbon-Signature header signed with this secret. Verify it to know a request came from Carbon."+msgstr "Toda entrega carrega um cabeçalho Carbon-Signature assinado com esta chave. Verifique-o para confirmar que a requisição veio de Carbon."+msgid "Every in-scope test passes in your configured system, with your data."msgstr "Todos os testes no escopo passam no seu sistema configurado, com seus dados."@@ -9839,6 +9848,12 @@ msgstr "Falha ao redimensionar imagem: {errorMessage}"msgid "Failed to retrieve CSV column data."msgstr "Falha ao recuperar dados de coluna CSV."+msgid "Failed to reveal the secret"+msgstr "Falha ao revelar a chave"++msgid "Failed to roll the secret"+msgstr "Falha ao renovar a chave"+msgid "Failed to save configuration rule"msgstr "Falha ao salvar regra de configuração"@@ -18920,6 +18935,9 @@ msgstr "Rev {revision}"msgid "Rev {revisionId}"msgstr "Rev {revisionId}"+msgid "Reveal"+msgstr "Revelar"+msgid "Reveal account number"msgstr "Revelar número da conta"@@ -19186,6 +19204,12 @@ msgstr "Funções e Responsabilidades"msgid "Roles that set default permissions for new employees"msgstr "Funções que definem permissões padrão para novos funcionários"+msgid "Roll secret"+msgstr "Renovar chave"++msgid "Rolled the signing secret"+msgstr "Chave de assinatura renovada"+msgid "Room to grow without bolting on more tools"msgstr "Espaço para crescer sem adicionar mais ferramentas"@@ -20796,6 +20820,9 @@ msgstr "Entrar também requer um código único do seu aplicativo autenticador"msgid "Signing in will no longer require a code. Enter the current 6-digit code from your authenticator app to confirm."msgstr "Iniciar sessão deixará de exigir um código. Introduza o código de 6 dígitos atual da sua aplicação autenticadora para confirmar."+msgid "Signing secret"+msgstr "Chave de assinatura"+msgid "Simultaneous"msgstr "Simultâneo"diff --git a/packages/locale/locales/ru/erp.po b/packages/locale/locales/ru/erp.poindex 86705d71d3..992375bdc3 100644--- a/packages/locale/locales/ru/erp.po+++ b/packages/locale/locales/ru/erp.po@@ -5900,6 +5900,9 @@ msgstr "Копировать номер услуги"msgid "Copy service unique identifier"msgstr "Копировать уникальный идентификатор услуги"+msgid "Copy signing secret"+msgstr "Скопировать подписывающий секрет"+msgid "Copy supplier quote unique identifier"msgstr "Скопировать уникальный идентификатор предложения поставщика"@@ -7550,6 +7553,9 @@ msgstr "Доставлено"msgid "Delivered on"msgstr "Доставлено"+msgid "Deliveries are signed with the new secret at once. Update your endpoint with it."+msgstr "Доставки подписаны новым секретом сразу же. Обновите конечную точку этим секретом."+msgid "Delivery Date"msgstr "Дата поставки"@@ -9214,6 +9220,9 @@ msgstr "Все записи компании. Учётные данные, тоmsgid "Every condition must match"msgstr "Каждое условие должно совпадать"+msgid "Every delivery carries a Carbon-Signature header signed with this secret. Verify it to know a request came from Carbon."+msgstr "Каждая доставка содержит заголовок Carbon-Signature, подписанный этим секретом. Проверьте его, чтобы узнать, что запрос поступил от Carbon."+msgid "Every in-scope test passes in your configured system, with your data."msgstr "Все тесты в области действия проходят в вашей настроенной системе с вашими данными."@@ -9839,6 +9848,12 @@ msgstr "Не удалось изменить размер изображенияmsgid "Failed to retrieve CSV column data."msgstr "Не удалось получить данные столбцов CSV."+msgid "Failed to reveal the secret"+msgstr "Не удалось показать секрет"++msgid "Failed to roll the secret"+msgstr "Не удалось обновить секрет"+msgid "Failed to save configuration rule"msgstr "Ошибка при сохранении правила конфигурации"@@ -18920,6 +18935,9 @@ msgstr "Ред. {revision}"msgid "Rev {revisionId}"msgstr "Ревизия {revisionId}"+msgid "Reveal"+msgstr "Показать"+msgid "Reveal account number"msgstr "Раскрыть номер счета"@@ -19186,6 +19204,12 @@ msgstr "Роли и ответственность"msgid "Roles that set default permissions for new employees"msgstr "Роли, устанавливающие права доступа по умолчанию для новых сотрудников"+msgid "Roll secret"+msgstr "Обновить секрет"++msgid "Rolled the signing secret"+msgstr "Подписывающий секрет обновлен"+msgid "Room to grow without bolting on more tools"msgstr "Место для роста без добавления новых инструментов"@@ -20796,6 +20820,9 @@ msgstr "При входе также требуется одноразовыйmsgid "Signing in will no longer require a code. Enter the current 6-digit code from your authenticator app to confirm."msgstr "Вход больше не будет требовать кода. Введите текущий 6-значный код из приложения-аутентификатора для подтверждения."+msgid "Signing secret"+msgstr "Подписывающий секрет"+msgid "Simultaneous"msgstr "Одновременный"diff --git a/packages/locale/locales/tr/erp.po b/packages/locale/locales/tr/erp.poindex 06c3c16ac5..f1199106fc 100644--- a/packages/locale/locales/tr/erp.po+++ b/packages/locale/locales/tr/erp.po@@ -5900,6 +5900,9 @@ msgstr "Hizmet numarasını kopyala"msgid "Copy service unique identifier"msgstr "Hizmet benzersiz tanımlayıcısını kopyala"+msgid "Copy signing secret"+msgstr "İmza sırrını kopyala"+msgid "Copy supplier quote unique identifier"msgstr "Tedarikçi teklifi benzersiz tanıtıcısını kopyala"@@ -7550,6 +7553,9 @@ msgstr "Teslim Edildi"msgid "Delivered on"msgstr "Teslim Tarihi"+msgid "Deliveries are signed with the new secret at once. Update your endpoint with it."+msgstr "Teslimatlar yeni sır ile hemen imzalanır. Uç noktanızı bununla güncelleyin."+msgid "Delivery Date"msgstr "Teslimat Tarihi"@@ -9214,6 +9220,9 @@ msgstr "Şirket kapsamındaki tüm kayıtlar. Kimlik bilgileri, entegrasyon belimsgid "Every condition must match"msgstr "Her koşul eşleşmelidir"+msgid "Every delivery carries a Carbon-Signature header signed with this secret. Verify it to know a request came from Carbon."+msgstr "Her teslimat bu sır ile imzalanmış bir Carbon-Signature başlığı taşır. Carbon'dan geldiğini bilmek için bunu doğrulayın."+msgid "Every in-scope test passes in your configured system, with your data."msgstr "Kapsamdaki her test, yapılandırılmış sisteminizde, verilerinizle geçer."@@ -9839,6 +9848,12 @@ msgstr "Görüntü yeniden boyutlandırılamadı: {errorMessage}"msgid "Failed to retrieve CSV column data."msgstr "CSV sütun verileri alınamadı."+msgid "Failed to reveal the secret"+msgstr "Sır gösterilmesi başarısız oldu"++msgid "Failed to roll the secret"+msgstr "Sır döndürülmesi başarısız oldu"+msgid "Failed to save configuration rule"msgstr "Yapılandırma kuralını kaydetme başarısız oldu"@@ -18920,6 +18935,9 @@ msgstr "Sürüm {revision}"msgid "Rev {revisionId}"msgstr "Rev {revisionId}"+msgid "Reveal"+msgstr "Göster"+msgid "Reveal account number"msgstr "Hesap numarasını göster"@@ -19186,6 +19204,12 @@ msgstr "Roller ve Sorumluluklar"msgid "Roles that set default permissions for new employees"msgstr "Yeni çalışanlar için varsayılan izinleri ayarlayan roller"+msgid "Roll secret"+msgstr "Sırrı Döndür"++msgid "Rolled the signing secret"+msgstr "İmza sırrı döndürüldü"+msgid "Room to grow without bolting on more tools"msgstr "Daha fazla araç eklemeden büyüme için yer"@@ -20796,6 +20820,9 @@ msgstr "Oturum açma ayrıca doğrulayıcı uygulamanızdan bir kerelik kod geremsgid "Signing in will no longer require a code. Enter the current 6-digit code from your authenticator app to confirm."msgstr "Oturum açma artık kod gerektirmez. Onaylamak için kimlik doğrulayıcı uygulamanızdan mevcut 6 haneli kodu girin."+msgid "Signing secret"+msgstr "İmza sırrı"+msgid "Simultaneous"msgstr "Eşzamanlı"diff --git a/packages/locale/locales/zh/erp.po b/packages/locale/locales/zh/erp.poindex 8a373ff3cb..8d7cbe6098 100644--- a/packages/locale/locales/zh/erp.po+++ b/packages/locale/locales/zh/erp.po@@ -5900,6 +5900,9 @@ msgstr "复制服务编号"msgid "Copy service unique identifier"msgstr "复制服务唯一标识符"+msgid "Copy signing secret"+msgstr "复制签名密钥"+msgid "Copy supplier quote unique identifier"msgstr "复制供应商报价唯一标识符"@@ -7550,6 +7553,9 @@ msgstr "已交付"msgid "Delivered on"msgstr "交付于"+msgid "Deliveries are signed with the new secret at once. Update your endpoint with it."+msgstr "投递将立即使用新密钥进行签名。请使用此密钥配置您的端点。"+msgid "Delivery Date"msgstr "交货日期"@@ -9214,6 +9220,9 @@ msgstr "公司范围内的所有记录。凭据、集成令牌和 Webhook 永不msgid "Every condition must match"msgstr "每个条件都必须匹配"+msgid "Every delivery carries a Carbon-Signature header signed with this secret. Verify it to know a request came from Carbon."+msgstr "每个投递都携带使用此密钥签名的 Carbon-Signature 标头。验证该标头以确认请求来自 Carbon。"+msgid "Every in-scope test passes in your configured system, with your data."msgstr "您配置的系统中的每项范围内测试都通过了您的数据。"@@ -9839,6 +9848,12 @@ msgstr "调整图像大小失败:{errorMessage}"msgid "Failed to retrieve CSV column data."msgstr "未能检索 CSV 列数据。"+msgid "Failed to reveal the secret"+msgstr "无法显示该密钥"++msgid "Failed to roll the secret"+msgstr "无法轮换该密钥"+msgid "Failed to save configuration rule"msgstr "保存配置规则失败"@@ -18920,6 +18935,9 @@ msgstr "修订版 {revision}"msgid "Rev {revisionId}"msgstr "修订 {revisionId}"+msgid "Reveal"+msgstr "显示"+msgid "Reveal account number"msgstr "显示账户号码"@@ -19186,6 +19204,12 @@ msgstr "角色和职责"msgid "Roles that set default permissions for new employees"msgstr "为新员工设置默认权限的角色"+msgid "Roll secret"+msgstr "轮换密钥"++msgid "Rolled the signing secret"+msgstr "已轮换签名密钥"+msgid "Room to grow without bolting on more tools"msgstr "无需添加更多工具即可扩展"@@ -20796,6 +20820,9 @@ msgstr "登录还需要来自您的身份验证器应用的一次性代码"msgid "Signing in will no longer require a code. Enter the current 6-digit code from your authenticator app to confirm."msgstr "登录将不再需要代码。输入您的身份验证器应用中的当前 6 位数字代码以确认。"+msgid "Signing secret"+msgstr "签名密钥"+msgid "Simultaneous"msgstr "同时"diff --git a/packages/server-functions/src/get-method/configuration-rules.test.ts b/packages/server-functions/src/get-method/configuration-rules.test.tsnew file mode 100644index 0000000000..c7cfd5a13b--- /dev/null+++ b/packages/server-functions/src/get-method/configuration-rules.test.ts@@ -0,0 +1,49 @@+// 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 { remapRuleField, ruleFieldReferences } from "./configuration-rules";++// A version copy: method m1 → m2, material a → b, operation x → y.+const idMap = new Map([+ ["m1", "m2"],+ ["a", "b"],+ ["x", "y"]+]);++describe("remapRuleField", () => {+ it("re-keys a line field rule onto the copied line", () => {+ expect(remapRuleField("quantity:a", idMap)).toBe("quantity:b");+ expect(remapRuleField("laborTime:x", idMap)).toBe("laborTime:y");+ });++ it("re-keys the root list rule onto the new method", () => {+ expect(remapRuleField("billOfMaterial:m1:undefined", idMap)).toBe(+ "billOfMaterial:m2:undefined"+ );+ });++ it("re-keys a sub-assembly list rule by its line, keeping the child's method", () => {+ // The child item's method is not copied; the line that uses it is.+ expect(remapRuleField("billOfProcess:child:a", idMap)).toBe(+ "billOfProcess:child:b"+ );+ });++ it("leaves rules of rows that were not copied", () => {+ expect(remapRuleField("quantity:other", idMap)).toBeNull();+ expect(remapRuleField("billOfMaterial:child:other", idMap)).toBeNull();+ });+});++describe("ruleFieldReferences", () => {+ it("finds the rules of replaced rows by any id in the field", () => {+ const replaced = new Set(["old-line"]);+ expect(ruleFieldReferences("quantity:old-line", replaced)).toBe(true);+ expect(ruleFieldReferences("billOfMaterial:child:old-line", replaced)).toBe(+ true+ );+ expect(ruleFieldReferences("quantity:kept-line", replaced)).toBe(false);+ });+});diff --git a/packages/server-functions/src/get-method/configuration-rules.ts b/packages/server-functions/src/get-method/configuration-rules.tsnew file mode 100644index 0000000000..dc3ceb5c03--- /dev/null+++ b/packages/server-functions/src/get-method/configuration-rules.ts@@ -0,0 +1,21 @@+// 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.++// Configuration rule fields name the rows they configure, joined by ":":+// `<column>:<lineId>` for a method line or operation field, and+// `billOfMaterial|billOfProcess:<makeMethodId>:<lineId | "undefined">` for a+// node's list. Copying a method gives every row a new id, so its rules are+// re-keyed through a map of old id → new id.++/** Whether a rule field names any of `ids`. */+export function ruleFieldReferences(field: string, ids: Set<string>) {+ return field.split(":").some((part) => ids.has(part));+}++/** The field re-keyed onto the copied rows, or null when it names none of them. */+export function remapRuleField(field: string, idMap: Map<string, string>) {+ const parts = field.split(":");+ if (!parts.some((part) => idMap.has(part))) return null;+ return parts.map((part) => idMap.get(part) ?? part).join(":");+}diff --git a/packages/server-functions/src/get-method/index.ts b/packages/server-functions/src/get-method/index.tsindex 28e00bc9c7..a642d3b5ea 100644--- a/packages/server-functions/src/get-method/index.ts+++ b/packages/server-functions/src/get-method/index.ts@@ -53,6 +53,7 @@ import { defineServerFn } from "../define-server-fn";import { NotFoundError } from "../errors";import { chunked } from "../import-csv/chunks";import { getStorageUnitId } from "../lib/storage-units";+import { remapRuleField, ruleFieldReferences } from "./configuration-rules";import { importTypeScript } from "./sandbox";const logger = getLogger("server-functions", "get-method");@@ -94,6 +95,78 @@ const normalizeOperationType = (value: unknown) =>// inserted step ids — a bulk insert preserves order, so insertedStepIds[i] ↔ sourceSteps[i].// Guarded: a no-op when there are no slides, so it can never break step copying.// See .ai/specs/2026-07-14-mes-execution-views.md §4.+// A method copy re-keys the rules of the copied rows onto their new ids (`idMap`:+// source line, operation and method ids → target ids; see configuration-rules.ts),+// and drops the target's rules for the rows it replaced. Otherwise a new version's+// lines carry no rules and the old rules point at deleted rows.+async function copyConfigurationRules(+ trx: Transaction<KyselyDatabase>,+ args: {+ sourceItemId: string;+ targetItemId: string;+ replacedIds: string[];+ idMap: Map<string, string>;+ companyId: string;+ userId: string;+ }+) {+ const { sourceItemId, targetItemId, idMap, companyId, userId } = args;+ const replaced = new Set(args.replacedIds);++ if (replaced.size > 0) {+ const targetRules = await trx+ .selectFrom("configurationRule")+ .select("field")+ .where("itemId", "=", targetItemId)+ .where("companyId", "=", companyId)+ .execute();+ const stale = targetRules+ .map((rule) => rule.field)+ .filter((field) => ruleFieldReferences(field, replaced));+ if (stale.length > 0) {+ await trx+ .deleteFrom("configurationRule")+ .where("itemId", "=", targetItemId)+ .where("companyId", "=", companyId)+ .where("field", "in", stale)+ .execute();+ }+ }++ if (idMap.size === 0) return;+ const sourceRules = await trx+ .selectFrom("configurationRule")+ .select(["field", "code"])+ .where("itemId", "=", sourceItemId)+ .where("companyId", "=", companyId)+ .execute();+ const copies = sourceRules.flatMap((rule) => {+ const field = remapRuleField(rule.field, idMap);+ return field+ ? [+ {+ itemId: targetItemId,+ field,+ code: rule.code,+ companyId,+ updatedBy: userId+ }+ ]+ : [];+ });+ if (copies.length === 0) return;+ await trx+ .insertInto("configurationRule")+ .values(copies)+ .onConflict((oc) =>+ oc.columns(["itemId", "field"]).doUpdateSet((eb) => ({+ code: eb.ref("excluded.code"),+ updatedBy: eb.ref("excluded.updatedBy")+ }))+ )+ .execute();+}+async function copyStepSlides(trx: Transaction<KyselyDatabase>,sourceSteps: Array<{ id?: string | null }>,@@ -358,28 +431,9 @@ const getMethod = defineServerFn({: Promise.resolve()]);- // Copy materials from source to target, dropping any zero-quantity- // BOM lines.- const materialsToCopy = (- (sourceMaterials.data ??- []) as Database["public"]["Tables"]["methodMaterial"]["Row"][]- ).filter((material) => !isZeroQuantity(material.quantity));- if (parts.billOfMaterial && materialsToCopy.length > 0) {- await trx- .insertInto("methodMaterial")- .values(- materialsToCopy.map((material) => ({- ...material,- productionQuantity: undefined,- id: undefined, // Let the database generate a new ID- makeMethodId: targetMakeMethod.data.id!,- createdBy: userId- }))- )- .execute();- }-- // Copy operations from source to target+ // Operations first, so each copied BOM line can point at the copied+ // operation that consumes it, not at the source method's operation.+ const operationIdMap = new Map<string, string>();if (parts.billOfProcess &&sourceOperations.data &&@@ -410,6 +464,10 @@ const getMethod = defineServerFn({).returning(["id"]).execute();+ sourceOperations.data.forEach((operation, index) => {+ const id = operationIds[index]?.id;+ if (operation.id && id) operationIdMap.set(operation.id, id);+ });for await (const [index,@@ -498,6 +556,31 @@ const getMethod = defineServerFn({}}}+ // Copy materials from source to target, dropping any zero-quantity+ // BOM lines.+ const materialsToCopy = (+ (sourceMaterials.data ??+ []) as Database["public"]["Tables"]["methodMaterial"]["Row"][]+ ).filter((material) => !isZeroQuantity(material.quantity));+ if (parts.billOfMaterial && materialsToCopy.length > 0) {+ await trx+ .insertInto("methodMaterial")+ .values(+ materialsToCopy.map((material) => ({+ ...material,+ productionQuantity: undefined,+ id: undefined, // Let the database generate a new ID+ makeMethodId: targetMakeMethod.data.id!,+ // Without the bill of process the source's operations were not+ // copied, so no operation on the target is known to consume it.+ methodOperationId: material.methodOperationId+ ? (operationIdMap.get(material.methodOperationId) ?? null)+ : null,+ createdBy: userId+ }))+ )+ .execute();+ }});break;@@ -5247,6 +5330,24 @@ const getMethod = defineServerFn({}await db.transaction().execute(async (trx) => {+ // The lines about to be replaced, whose configuration rules go with them.+ const [targetMaterialIds, targetOperationIds] = await Promise.all([+ trx+ .selectFrom("methodMaterial")+ .select("id")+ .where("makeMethodId", "=", targetMakeMethod.data.id)+ .where("companyId", "=", companyId)+ .execute()+ .then((rows) => rows.map((row) => row.id)),+ trx+ .selectFrom("methodOperation")+ .select("id")+ .where("makeMethodId", "=", targetMakeMethod.data.id)+ .where("companyId", "=", companyId)+ .execute()+ .then((rows) => rows.map((row) => row.id))+ ]);+// Delete existing materials and operations from target methodawait Promise.all([parts.billOfMaterial@@ -5265,28 +5366,9 @@ const getMethod = defineServerFn({: Promise.resolve()]);- // Copy materials from source to target, dropping any zero-quantity- // BOM lines.- const materialsToCopy = (- (sourceMaterials.data ??- []) as Database["public"]["Tables"]["methodMaterial"]["Row"][]- ).filter((material) => !isZeroQuantity(material.quantity));- if (parts.billOfMaterial && materialsToCopy.length > 0) {- await trx- .insertInto("methodMaterial")- .values(- materialsToCopy.map((material) => ({- ...material,- productionQuantity: undefined,- id: undefined, // Let the database generate a new ID- makeMethodId: targetMakeMethod.data.id,- createdBy: userId- }))- )- .execute();- }-- // Copy operations from source to target+ // Operations first, so each copied BOM line can point at the copied+ // operation that consumes it, not at the source method's operation.+ const operationIdMap = new Map<string, string>();if (parts.billOfProcess &&sourceOperations.data &&@@ -5317,6 +5399,10 @@ const getMethod = defineServerFn({).returning(["id"]).execute();+ sourceOperations.data.forEach((operation, index) => {+ const id = operationIds[index]?.id;+ if (operation.id && id) operationIdMap.set(operation.id, id);+ });for await (const [index,@@ -5405,6 +5491,55 @@ const getMethod = defineServerFn({}}}+ // Copy materials from source to target, dropping any zero-quantity+ // BOM lines.+ const materialsToCopy = (+ (sourceMaterials.data ??+ []) as Database["public"]["Tables"]["methodMaterial"]["Row"][]+ ).filter((material) => !isZeroQuantity(material.quantity));+ const materialIdMap = new Map<string, string>();+ if (parts.billOfMaterial && materialsToCopy.length > 0) {+ const materialIds = await trx+ .insertInto("methodMaterial")+ .values(+ materialsToCopy.map((material) => ({+ ...material,+ productionQuantity: undefined,+ id: undefined, // Let the database generate a new ID+ makeMethodId: targetMakeMethod.data.id,+ // Without the bill of process the source's operations were not+ // copied, so no operation on the target is known to consume it.+ methodOperationId: material.methodOperationId+ ? (operationIdMap.get(material.methodOperationId) ?? null)+ : null,+ createdBy: userId+ }))+ )+ .returning(["id"])+ .execute();+ materialsToCopy.forEach((material, index) => {+ const id = materialIds[index]?.id;+ if (id) materialIdMap.set(material.id, id);+ });+ }++ // Configuration rules are keyed by method line and operation ids:+ // follow the copied lines, and drop the rules of the lines replaced.+ await copyConfigurationRules(trx, {+ sourceItemId: sourceMakeMethod.data.itemId,+ targetItemId: targetMakeMethod.data.itemId,+ replacedIds: [+ ...(parts.billOfMaterial ? targetMaterialIds : []),+ ...(parts.billOfProcess ? targetOperationIds : [])+ ],+ idMap: new Map([+ [sourceMakeMethod.data.id, targetMakeMethod.data.id],+ ...materialIdMap,+ ...operationIdMap+ ]),+ companyId,+ userId+ });});break;}