Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

Feat/workflow improvements (#1440)

Anshul sharma388e06d52f21
diff --git a/.ai/plans/2026-08-19-workflow-improvements-round-2.md b/.ai/plans/2026-08-19-workflow-improvements-round-2.md
new file mode 100644
index 0000000000..0a163288ad
--- /dev/null
+++ b/.ai/plans/2026-08-19-workflow-improvements-round-2.md
@@ -0,0 +1,2411 @@
+# Workflow improvements, round 2 — implementation plan
+
+**Spec / source:** `.ai/specs/2026-08-19-workflow-improvements-round-2.md`
+**Research:** `.ai/research/2026-08-19-workflow-improvements-round-2.md`
+**Branch:** `feat/workflow-improvements`
+
+> Read the spec first. Every design decision (D-1…D-16) referenced below is defined there.
+> Do NOT commit anything unless the user explicitly asks.
+
+## Progress
+
+- [x] Task 1: Quieter canvas grid and bezier edges
+- [x] Task 2: Relabel the notify action's `role` input to "Group"
+- [x] Task 3: Restrict the group and person pickers to employee groups
+- [x] Task 4: Split the builder store's read-only flag into `isVersionLocked` + `canEdit`
+- [x] Task 5: Wire the two flags through the provider and the route
+- [x] Task 6: Gate the canvas and builder controls on the new flags
+- [x] Task 7: Teach the shared value/field components an `isReadOnly` prop
+- [x] Task 8: Disable every control in the six node config forms
+- [x] Task 9: Build `WorkflowLockAlert` and mount it above the canvas
+- [x] Task 10: Add the positions-only writer (service + route + path)
+- [x] Task 11: Split autosave so a locked version saves positions only
+- [x] Task 12: Let a whole record render as text
+- [x] Task 13: Add `linkify` to the catalog and set it on the notify message
+- [x] Task 14: Render an entity part as a markdown link when a `linkFor` is supplied
+- [x] Task 15: Supply `linkFor` from the engine
+- [x] Task 16: Add `renderInlineLinks` to `@carbon/notifications`
+- [x] Task 17: Render inline links in the notification email
+- [x] Task 18: Render the message body and its links in the in-app bell
+- [x] Task 19: Build the per-company catalog overlay module
+- [x] Task 20: Accept the overlay in the catalog facade and resolve custom-field events
+- [x] Task 21: Derive custom-field event ids in the matcher
+- [x] Task 22: Add the `workflow_merge_custom_fields` RPC
+- [x] Task 23: Write custom fields from the update action
+- [x] Task 24: Load the company's custom fields in the engine
+- [x] Task 25: Move the builder from a catalog singleton to a per-company catalog hook
+- [x] Task 26: Offer custom-field triggers in the event picker
+- [x] Task 27: Extend the trigger-event drift invariant
+- [x] Task 28: Sync AGENTS.md and rules
+- [~] Task 29: End-to-end verification — static gates PASS; browser walk of the 30 acceptance criteria NOT run (needs the user)
+
+## Blocked — needs a decision before Task 17
+
+`packages/documents` does NOT depend on `@carbon/notifications` (verified: its `dependencies`
+are `@carbon/env`, `@carbon/react`, `@carbon/utils`, `@react-email/*`, …). Task 17 step 2's
+escape hatch therefore fires. Three options, none of which should be picked by guess:
+
+1. **Add `@carbon/notifications` to `packages/documents` dependencies.** Smallest diff. It is a
+ private workspace package of pure enums and helpers with no I/O, so the coupling is cheap —
+ but `NotificationEmail.tsx` currently keeps a LOCAL copy of `NotificationDetail` precisely so
+ the email package need not depend on it, and that comment says the avoidance is deliberate.
+2. **Move `renderInlineLinks` into `@carbon/utils`**, which `documents` already depends on.
+ `@carbon/notifications` would need `@carbon/utils` added instead (it currently depends on
+ nothing at runtime), so it trades one new edge for another.
+3. **Pre-split in `packages/jobs`**: widen the `NotificationDetail` shape to carry optional
+ segments, so the email renders data rather than parsing a string. Cleanest layering, widest
+ blast radius — `NotificationDetail` is consumed by email, Slack text and `payload.details`.
+
+Task 18 (the in-app bell) is unaffected — `apps/erp` may import `@carbon/notifications` today.
+
+## Dependencies
+
+- Tasks 1, 2, 3 are independent of everything and of each other.
+- Task 4 → 5 → 6; Task 7 → 8; Tasks 9, 10 independent of 4–8; Task 11 needs 4 and 10.
+- Task 12 → 13 → 14 → 15; Task 16 → 17 and 16 → 18.
+- Task 19 → 20 → {21, 24, 25}; Task 22 → 23; Task 24 needs 20 and 22-free; Task 25 → 26.
+- Task 27 needs 19. Task 28 needs everything. Task 29 is last.
+- Parallelisable groups: {1,2,3}, {4…11}, {12…18}, {19…27} touch disjoint files except
+ `packages/workflows/src/catalog/actions.ts` (Tasks 2 and 13 — do Task 2 first) and
+ `packages/workflows/src/catalog/catalog.ts` (Tasks 14 and 20 — do Task 14 first).
+
+---
+
+## Task 1: Quieter canvas grid and bezier edges
+
+**Depends on:** none
+**Files:**
+- Modify: `apps/erp/app/modules/workflows/ui/Builder/WorkflowBuilder.tsx` — `<Background>` props
+- Modify: `apps/erp/app/modules/workflows/ui/Builder/edges/WorkflowEdge.tsx` — path function
+- Modify: `apps/erp/app/modules/workflows/ui/Builder/edges/workflow-edge.css` — add the dot-colour override
+
+**Steps:**
+
+1. In `WorkflowBuilder.tsx`, replace the single `<Background>` line (currently
+ `<Background variant={BackgroundVariant.Dots} gap={16} />`) with:
+ ```tsx
+ <Background variant={BackgroundVariant.Dots} gap={24} size={1} />
+ ```
+2. In `edges/workflow-edge.css`, append a light/dark override for xyflow's dot colour.
+ This file is already loaded as a route-level stylesheet by `routes/x+/workflow+/$id.tsx`
+ (`export const links`), so it is the right home. Append:
+ ```css
+ /* xyflow ships an opaque default; the grid must sit under the content, not compete
+ with it. Scoped to the pane so no other canvas in the app is affected. */
+ .react-flow__pane {
+ --xy-background-pattern-dots-color: hsl(var(--muted-foreground) / 0.25);
+ }
+ ```
+ If `.react-flow__pane` turns out not to be an ancestor of the rendered
+ `<svg class="react-flow__background">` (inspect in the browser), move the declaration to
+ `.react-flow` instead. If neither works, STOP and report — do not hard-code a hex colour.
+3. In `edges/WorkflowEdge.tsx` line 4, change the import from `getSmoothStepPath` to
+ `getBezierPath`:
+ ```tsx
+ import { EdgeLabelRenderer, getBezierPath, useStore } from "@xyflow/react";
+ ```
+4. In the same file, replace the geometry call (currently lines 40-48) with:
+ ```tsx
+ const [edgePath, labelX, labelY] = getBezierPath({
+ sourceX,
+ sourceY,
+ sourcePosition,
+ targetX,
+ targetY,
+ targetPosition
+ });
+ ```
+ `getBezierPath` takes no `borderRadius` — drop it. It returns the same
+ `[path, labelX, labelY]` tuple, so the disconnect button below is unaffected.
+5. Change NOTHING else in `WorkflowEdge.tsx`. The `strokeDasharray="8 4"`, the
+ `strokeOpacity` dimming and `className="workflow-edge-animated"` all stay (D-15).
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=erp
+# Expected: no errors
+pnpm exec biome check apps/erp/app/modules/workflows/ui/Builder
+# Expected: no error-severity findings in the three touched files
+```
+
+**Out of scope:** `modules/production/ui/Jobs/JobDag.tsx`, `apps/mes/app/components/JobDag/JobDag.tsx`,
+`inventory/ui/Traceability/TraceabilityGraph.tsx` — other canvases, not part of this ask.
+
+---
+
+## Task 2: Relabel the notify action's `role` input to "Group"
+
+**Depends on:** none
+**Files:**
+- Modify: `packages/workflows/src/catalog/actions.ts` — one label string
+- Regenerated: `packages/workflows/src/catalog/{events,actions,labels,help}.generated.ts`
+- Regenerated: `packages/locale/locales/*/erp.po`
+
+**Steps:**
+
+1. In `packages/workflows/src/catalog/actions.ts`, inside the `notify` entry, change line 145
+ from:
+ ```ts
+ role: { type: t.entity("group"), required: false, label: "role" },
+ ```
+ to:
+ ```ts
+ // The stored input key stays `role` — renaming it would need a v4 definition
+ // format migration for a label change (D-9). The value is already a group id.
+ role: { type: t.entity("group"), required: false, label: "group" },
+ ```
+2. Do NOT touch `requireOneOf: [["user", "role"]]` (line 174), `notify.ts`, or `notify.test.ts`.
+3. Regenerate the catalog and format it:
+ ```bash
+ pnpm run generate:workflow-catalog
+ pnpm exec biome check --write packages/workflows/src/catalog/
+ ```
+ Confirm `packages/workflows/src/catalog/labels.generated.ts` now reads
+ `"action.notify.input.role": msg\`Group\`` (the key keeps `role`; only the message changes).
+4. Refresh the translation catalogs:
+ ```bash
+ pnpm run lingui:extract && pnpm run lingui:clean
+ ```
+ `lingui:extract` on this branch produces a large diff across every locale. That is expected
+ (see `.ai/lessons.md`); commit whatever it writes when the user asks for a commit.
+
+**Verify:**
+```bash
+pnpm run check:workflow-catalog
+# Expected: "check-workflow-catalog: ok — … actions, … operations" and exit 0
+pnpm --filter @carbon/workflows test
+# Expected: all tests pass
+```
+
+**Out of scope:** the input key `role`, `requireOneOf`, the runtime `notify.ts`, and any
+definition-format migration. Label only.
+
+---
+
+## Task 3: Restrict the group and person pickers to employee groups
+
+**Depends on:** none
+**Files:**
+- Modify: `apps/erp/app/modules/workflows/ui/Builder/fields/recordPickers.tsx` — two components
+
+**Steps:**
+
+1. In `recordPickers.tsx`, add `type="employee"` to `UserPicker`'s `<UserSelect>`:
+ ```tsx
+ const UserPicker = ({ value, onChange, isDisabled }: RecordPickerProps) => (
+ <UserSelect
+ value={value}
+ usersOnly
+ // "employee" is defined negatively by get_user_select_groups: not customer- and
+ // not supplier-flagged. Ad-hoc company groups stay listed (D-10).
+ type="employee"
+ isMulti={false}
+ insideCanvas
+ disabled={isDisabled}
+ onChange={(items) => handleUserChange(items, onChange)}
+ />
+ );
+ ```
+2. Add the same `type="employee"` to `GroupPicker`'s `<UserSelect>`, keeping every other prop.
+3. Confirm `UserSelect` accepts it: `apps/erp/app/components/Selectors/UserSelect/types.ts`
+ declares `type?: "employee" | "supplier" | "customer"`. If that prop is gone, STOP and report.
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=erp
+# Expected: no errors
+```
+Manual (during Task 29): open a notify action, open the Group field, confirm no customer or
+supplier group appears and a hand-made company group still does.
+
+**Out of scope:** `validate.ts` (it checks the entity type, not the group flags — existing
+definitions pointing at a customer or supplier group must keep working), the RPC, and every
+other `UserSelect` call site in the app.
+
+---
+
+## Task 4: Split the builder store's read-only flag into `isVersionLocked` + `canEdit`
+
+**Depends on:** none
+**Files:**
+- Modify: `apps/erp/app/modules/workflows/ui/Builder/store.ts`
+
+**Why two flags:** a live version still allows dragging; a missing `workflows_update`
+permission does not (D-14). Movement follows permission, not the lock (D-12).
+
+**Steps:**
+
+1. In `BuilderState` (currently line 54), replace `isReadOnly: boolean;` with:
+ ```ts
+ /** This version is the promoted one. Behaviour edits are refused; positions are not. */
+ isVersionLocked: boolean;
+ /** The user holds workflows_update. */
+ canEdit: boolean;
+ /** Behaviour edits: config, nodes, edges, expand state. */
+ canChangeDefinition: boolean;
+ /** Layout only. Follows permission, NOT the lock — see D-12. */
+ canMoveNodes: boolean;
+ ```
+2. Change the factory signature (currently line 111) to take the two source flags and derive
+ the two answers once:
+ ```ts
+ export function createBuilderStore(initial: {
+ nodes: BuilderNode[];
+ edges: BuilderEdge[];
+ isVersionLocked: boolean;
+ canEdit: boolean;
+ isOwner: boolean;
+ }) {
+ const canChangeDefinition = initial.canEdit && !initial.isVersionLocked;
+ const canMoveNodes = initial.canEdit;
+ return createStore<BuilderState>((set, get) => ({
+ ```
+ and in the initial-values block (currently lines 118-130) replace
+ `isReadOnly: initial.isReadOnly,` with:
+ ```ts
+ isVersionLocked: initial.isVersionLocked,
+ canEdit: initial.canEdit,
+ canChangeDefinition,
+ canMoveNodes,
+ ```
+3. Rewrite `onNodesChange` (currently lines 132-153) so layout changes pass on a locked
+ version but structural ones never do:
+ ```ts
+ onNodesChange: (changes) => {
+ const { canChangeDefinition, canMoveNodes, nodes } = get();
+
+ // Position, size and selection carry no behaviour, so they follow permission
+ // rather than the version lock — a live workflow can still be tidied and read.
+ const isLayout = (c: NodeChange<BuilderNode>) =>
+ c.type === "position" || c.type === "dimensions" || c.type === "select";
+
+ let incoming = changes;
+ if (!canChangeDefinition) {
+ if (!canMoveNodes) return;
+ incoming = changes.filter(isLayout);
+ if (!incoming.length) return;
+ }
+
+ // Protect the last trigger — deletion is allowed only when another remains.
+ const isRemove = (
+ c: NodeChange<BuilderNode>
+ ): c is { type: "remove"; id: string } => c.type === "remove";
+ const triggerIds = new Set(
+ nodes.filter((n) => n.type === "trigger").map((n) => n.id)
+ );
+ const triggerRemoveCount = incoming
+ .filter(isRemove)
+ .filter((c) => triggerIds.has(c.id)).length;
+ const allowed =
+ triggerRemoveCount >= triggerIds.size
+ ? incoming.filter((c) => !(isRemove(c) && triggerIds.has(c.id)))
+ : incoming;
+ if (!allowed.length) return;
+
+ set({ nodes: applyNodeChanges(allowed, nodes) });
+ },
+ ```
+4. In `onEdgesChange`, `onConnect`, and `addNode`, replace the existing
+ `const { isReadOnly, … } = get(); if (isReadOnly) return;` guard with
+ `const { canChangeDefinition, … } = get(); if (!canChangeDefinition) return;`.
+5. Change `arrangeNodes` (currently lines 294-298) and `setNodePositions` (300-308) to guard on
+ `canMoveNodes` instead of `isReadOnly`:
+ ```ts
+ arrangeNodes: () => {
+ const { nodes, edges, canMoveNodes, setNodePositions } = get();
+ if (!canMoveNodes) return;
+ setNodePositions(layoutPositions(nodes, edges));
+ },
+
+ setNodePositions: (positions) => {
+ const { canMoveNodes, nodes } = get();
+ if (!canMoveNodes) return;
+ set({
+ nodes: nodes.map((n) =>
+ positions[n.id] ? { ...n, position: positions[n.id] } : n
+ )
+ });
+ },
+ ```
+6. **This is the reported bug.** Add the missing guard to the five ungated mutators. Each gets
+ the same first line. `updateNodeData` is the one every node config form funnels through:
+ ```ts
+ updateNodeData: (id, patch) => {
+ // The single gate every node config form goes through. Without it a live version's
+ // trigger could be switched to Schedule, and — autosave being off — the edit
+ // silently evaporated on reload with no toast.
+ if (!get().canChangeDefinition) return;
+ set(({ nodes }) => ({
+ nodes: nodes.map((n) =>
+ n.id === id ? { ...n, data: { ...n.data, ...patch } } : n
+ )
+ }));
+ },
+ ```
+ Apply the same `if (!get().canChangeDefinition) return;` opener to `renameNode`,
+ `setNodeExpanded`, `setAllNodesExpanded` and `removeNode`, converting each from a
+ concise-body arrow to a block body where needed. `expanded` is part of the persisted
+ definition (`graph.ts` `fromReactFlow`), which is why expand/collapse counts as a
+ behaviour edit.
+7. Leave every other member of the store untouched.
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=erp
+# Expected: errors ONLY of the form "Property 'isReadOnly' does not exist on type 'BuilderState'"
+# in the consumer files Tasks 5-8 fix. Record that list; it is the work-list for those tasks.
+```
+
+**Out of scope:** any consumer of `isReadOnly` outside `store.ts` — Tasks 5-8 own those.
+
+---
+
+## Task 5: Wire the two flags through the provider and the route
+
+**Depends on:** Task 4
+**Files:**
+- Modify: `apps/erp/app/modules/workflows/ui/Builder/context.tsx` — provider props
+- Modify: `apps/erp/app/routes/x+/workflow+/$id.tsx` — compute and pass both flags
+
+**Steps:**
+
+1. In `context.tsx`, change `WorkflowBuilderProviderProps` from `isReadOnly: boolean;` to:
+ ```ts
+ isVersionLocked: boolean;
+ canEdit: boolean;
+ ```
+ Nothing else changes — the provider already spreads `props` straight into
+ `createBuilderStore(props)`.
+2. In `routes/x+/workflow+/$id.tsx`, the loader already returns `isReadOnly: versionId ===
+ workflow.activeVersionId`, i.e. "this is the live version". Rename that loader field to
+ `isVersionLocked` in **all three** return shapes (the no-versions branch ~line 100, the
+ unreadable-version branch ~line 120, and the success branch ~line 135). The first two
+ currently return `isReadOnly: true`; they become `isVersionLocked: true`.
+3. In the component (currently lines 159-163), replace the destructure alias and the derived
+ flag with:
+ ```tsx
+ isVersionLocked
+ } = useLoaderData<typeof loader>();
+
+ const canEdit = permissions.can("update", "workflows");
+ const isOwner = workflow.ownerId === userId;
+ ```
+ Delete the old `const isReadOnly = isLiveVersion || !permissions.can(...)` line.
+4. Update the provider mount (currently lines 181-189). The `key` must cover both flags,
+ because the store is created once in a ref and never updated after mount:
+ ```tsx
+ <WorkflowBuilderProvider
+ key={`${versionId}:${isVersionLocked}:${canEdit}:${isOwner}`}
+ nodes={nodes}
+ edges={edges}
+ isVersionLocked={isVersionLocked}
+ canEdit={canEdit}
+ isOwner={isOwner}
+ >
+ ```
+5. Fix any other reference to the removed `isReadOnly` in this file that the typecheck reports.
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=erp
+# Expected: no errors in context.tsx or routes/x+/workflow+/$id.tsx
+# (errors may remain in WorkflowBuilder.tsx / BuilderControls.tsx / node + form files — Tasks 6-8)
+```
+
+**Out of scope:** `shouldRevalidate` (Task 10 adds `/positions` to it).
+
+---
+
+## Task 6: Gate the canvas and builder controls on the new flags
+
+**Depends on:** Task 5
+**Files:**
+- Modify: `apps/erp/app/modules/workflows/ui/Builder/WorkflowBuilder.tsx`
+- Modify: `apps/erp/app/modules/workflows/ui/Builder/BuilderControls.tsx`
+- Modify: `apps/erp/app/modules/workflows/ui/Builder/nodes/WorkflowNodeCard.tsx`
+- Modify: `apps/erp/app/modules/workflows/ui/Builder/edges/WorkflowEdge.tsx`
+
+**Steps:**
+
+1. `WorkflowBuilder.tsx` — replace the single `isReadOnly` selector with two:
+ ```tsx
+ const canChangeDefinition = useBuilderStore((s) => s.canChangeDefinition);
+ const canMoveNodes = useBuilderStore((s) => s.canMoveNodes);
+ ```
+ Then, on the `<ReactFlow>` block (currently lines 136-171):
+ - `nodesDraggable={canMoveNodes}` (was `!isReadOnly`)
+ - `nodesConnectable={canChangeDefinition}` (was `!isReadOnly`)
+ - `deleteKeyCode={canChangeDefinition ? ["Delete"] : null}`
+ And on the surrounding wrapper: the drop handler (~lines 82, 92), the palette gate
+ (~lines 114, 125) and `onKeyDownCapture` all become `canChangeDefinition` /
+ `!canChangeDefinition` — a person who may not change the definition must not drop new
+ nodes onto a live version.
+2. `BuilderControls.tsx` — replace `const isReadOnly = useBuilderStore((s) => s.isReadOnly);`
+ with both selectors, then:
+ - auto-arrange button (~line 90): `isDisabled={!canMoveNodes}` (was `isDisabled={isReadOnly}`)
+ - expand/collapse-all button (~line 96): add `isDisabled={!canChangeDefinition}`. It is
+ currently ungated, and `expanded` is persisted.
+3. `nodes/WorkflowNodeCard.tsx` — line 66 currently reads
+ `const isReadOnly = useBuilderStore((state) => state.isReadOnly);`. Replace with:
+ ```tsx
+ const canChangeDefinition = useBuilderStore((state) => state.canChangeDefinition);
+ const isReadOnly = !canChangeDefinition;
+ ```
+ Keeping the local name `isReadOnly` means the rest of the file (the `InlineNodeName`
+ `isReadOnly` prop at line 130, and the expand/delete gates at lines 175-207) needs no edit.
+ The test-run button (lines 149-172) stays ungated — running a workflow does not modify it.
+4. `edges/WorkflowEdge.tsx` line 28 — same substitution:
+ ```tsx
+ const canChangeDefinition = useBuilderStore((s) => s.canChangeDefinition);
+ const isReadOnly = !canChangeDefinition;
+ ```
+ so the disconnect button (line 63) stays hidden on a live version.
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=erp
+# Expected: no errors in these four files
+```
+
+**Out of scope:** the six node config forms and the shared field components — Tasks 7 and 8.
+
+---
+
+## Task 7: Teach the shared value/field components an `isReadOnly` prop
+
+**Depends on:** none (do before Task 8)
+**Files:**
+- Modify: `packages/react/src/VariableText/VariableText.tsx` — add `isReadOnly`
+- Modify: `packages/react/src/Input.tsx` — fix the prop-order bug
+- Modify: `apps/erp/app/modules/workflows/ui/Builder/fields/types.ts` — `ValueFieldProps`
+- Modify: `.../fields/ValueField.tsx`, `.../fields/LiteralControl.tsx`,
+ `.../fields/InlineValueEditor.tsx`, `.../fields/PairsField.tsx`,
+ `.../fields/TemplateField.tsx`, `.../fields/VariableChip.tsx`,
+ `.../fields/VariablePickControl.tsx`
+- Modify: `.../config/ClauseRow.tsx`, `.../config/CombinatorToggle.tsx`
+
+**Prop-name reference — verified against each component's own definition. Using the wrong
+one silently does nothing:**
+
+| Component | Prop |
+|---|---|
+| `Button`, `IconButton`, `Input`, `NumberField`, `NumberInput`, `DatePicker`, `RECORD_PICKERS[*]` | `isDisabled` |
+| `Combobox`, `CreatableCombobox` | `isReadOnly` |
+| `Select` / `SelectTrigger`, `ToggleGroup` / `ToggleGroupItem`, `Switch`, `CommandInput`, `CommandItem`, raw `<button>`, `OperatorCombobox` | `disabled` |
+
+**Steps:**
+
+1. **Fix the `Input` bug first.** `packages/react/src/Input.tsx` applies
+ `disabled={isDisabled}` *after* `{...props}` (~lines 215-221), so a bare `disabled` passed
+ by a caller is silently overwritten with `false`. Change the spread order so an explicit
+ `disabled` prop survives:
+ ```tsx
+ disabled={isDisabled ?? props.disabled}
+ ```
+ placed after the spread. Add the comment: `// Explicit disabled must survive the spread; it was being overwritten.`
+ Then grep for callers that rely on the old (broken) behaviour:
+ ```bash
+ grep -rn "<Input" packages/ apps/ --include=*.tsx | grep -w "disabled"
+ ```
+ If a caller passes `disabled` expecting it to be ignored, STOP and report — do not guess.
+2. `packages/react/src/VariableText/VariableText.tsx` — add to `VariableTextProps`:
+ ```ts
+ /** Renders the same value but refuses edits. The Tiptap shell stays, so the
+ * read-only rendition matches the editable one exactly. */
+ isReadOnly?: boolean;
+ ```
+ Pass it to the Tiptap editor as `editable: !isReadOnly` in the `useEditor` options, and add
+ `isReadOnly` to that hook's dependency array if it has one. Setting `suggestionChar` to
+ `undefined` is NOT enough — it only kills the token menu, not typing.
+3. `fields/types.ts` — add one optional flag to `ValueFieldProps` (shared by `ValueField`,
+ `PairsField` and `TemplateField`, so this covers all three):
+ ```ts
+ /** The version is published: show the value, refuse every edit. */
+ isReadOnly?: boolean;
+ ```
+4. `fields/InlineValueEditor.tsx` — add `isReadOnly?: boolean;` to its `Props`, pass
+ `isReadOnly` through to `<VariableText>`, and short-circuit the two handlers that can dirty
+ the definition without a keystroke: `onFocusCapture` (~line 99, calls
+ `publishVariableMenuData`) and `onBlurCapture` (~lines 104-112, calls `onChange` with a
+ trimmed value). Both become no-ops when `isReadOnly`.
+5. `fields/ValueField.tsx` — accept `isReadOnly` and thread it to `<InlineValueEditor>` (~49),
+ `<VariablePickControl>` (~88), `<VariableChip>` (~92) and `<LiteralControl>` (~105); force
+ the `<VariableMenuPopover>` (~79) closed (`open={isReadOnly ? false : open}`).
+6. `fields/LiteralControl.tsx` — add `isReadOnly?: boolean;` to `LiteralControlProps`, make the
+ `{` handler (~lines 64-69, `braceOpens`) a no-op when set, and disable each branch with the
+ prop from the table above:
+ - `<Select>` ~83 and `<SelectTrigger>` ~84 → `disabled`
+ - `<Input>` ~105 → `isDisabled`
+ - `<NumberField>` ~124 → `isDisabled` (steppers inherit)
+ - `<Switch>` ~152 → `disabled`
+ - `<DatePicker>` ~162 → `isDisabled`
+ - `<Picker>` from `RECORD_PICKERS[type.of]` ~181 → `isDisabled`
+ - the fallback `<Input … disabled />` ~189-195 → change `disabled` to `isDisabled`
+7. `fields/PairsField.tsx` — thread `isReadOnly` to `<Input>` ~65 (`isDisabled`),
+ `<InlineValueEditor>` ~76, the remove `<IconButton>` ~85 (`isDisabled`) and the
+ "Add header" `<Button>` ~101 (`isDisabled`).
+8. `fields/TemplateField.tsx` — thread `isReadOnly` to its single `<InlineValueEditor>` (~28).
+9. `fields/VariablePickControl.tsx` — add `isReadOnly?: boolean;`; suppress the outer
+ `<div onClick={onOpen}>` (~30) handler and add `disabled` to the raw `<button>` (~38).
+10. `fields/VariableChip.tsx` — add `isReadOnly?: boolean;` and `disabled` on both raw
+ `<button>`s (~49 reopen menu, ~56 clear value).
+11. `config/CombinatorToggle.tsx` — add `isReadOnly?: boolean;` to its `Props` and pass
+ `disabled={isReadOnly}` to `<ToggleGroup>` (~11) and both `<ToggleGroupItem>`s (~19, ~25).
+12. `config/ClauseRow.tsx` — add `isReadOnly?: boolean;` to `ClauseRowProps`, then:
+ - `<Combobox>` ~141 → `isReadOnly={isReadOnly}` (it takes `isReadOnly`, NOT `isDisabled`)
+ - `<ValueField>` ~166 and ~213 → `isReadOnly={isReadOnly}`
+ - `<OperatorCombobox>` ~199 → `disabled={!leftType || isReadOnly}` (it already has a
+ `disabled={!leftType}`)
+ - remove `<IconButton>` ~242 → `isDisabled={!canRemove || isReadOnly}`
+ The `memo` wrapper at the bottom stays; a boolean prop is memo-safe.
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=erp
+pnpm exec turbo run typecheck --filter=@carbon/react
+# Expected: no errors
+pnpm --filter @carbon/react test
+# Expected: all tests pass (or "no test files")
+```
+
+**Out of scope:** the six node config forms (Task 8). Do not change any component's default
+behaviour — `isReadOnly` is optional and defaults to editable everywhere.
+
+---
+
+## Task 8: Disable every control in the six node config forms
+
+**Depends on:** Tasks 4, 6, 7
+**Files:**
+- Modify: `apps/erp/app/modules/workflows/ui/Builder/config/forms/index.ts` — `NodeFormProps`
+- Modify: `.../nodes/WorkflowNodeCard.tsx` — pass the flag to `<Form>`
+- Modify: `.../config/forms/{TriggerForm,ConditionForm,ActionForm,EntityForm,LookupForm,FilterForm}.tsx`
+
+**Steps:**
+
+1. `config/forms/index.ts` — add the flag to both the generic and the erased form type:
+ ```ts
+ export type NodeFormProps<K extends WorkflowNodeType = WorkflowNodeType> = {
+ node: …;
+ issues?: WorkflowIssue[];
+ /** The version is published: render every control disabled rather than inert. */
+ isReadOnly?: boolean;
+ };
+
+ export type AnyNodeForm = ComponentType<{
+ node: BuilderNode;
+ issues?: WorkflowIssue[];
+ isReadOnly?: boolean;
+ }>;
+ ```
+2. `nodes/WorkflowNodeCard.tsx` ~line 228 — pass it:
+ ```tsx
+ <Form key={id} node={builderNode} issues={nodeIssues} isReadOnly={isReadOnly} />
+ ```
+ (`isReadOnly` is already in scope from Task 6.)
+3. Work through the checklist below file by file. Every entry must end up disabled. Use the
+ prop-name table from Task 7 — a raw `<button>` takes native `disabled`; `Select`,
+ `SelectTrigger`, `ToggleGroup`, `ToggleGroupItem`, `Switch`, `CommandInput` and
+ `CommandItem` take `disabled`; `Button` and `IconButton` take `isDisabled`; `Combobox`
+ takes `isReadOnly`. Where a local sub-component has no such prop, add
+ `isReadOnly?: boolean` to its props type and thread it.
+
+ **TriggerForm.tsx** — add `isReadOnly` to the local `EventPickerProps` (~84-90) and
+ `ScheduleEditorProps` (~187-190), then:
+ raw `<button>` ~107 (event-picker trigger), `CommandInput` ~126, `CommandItem` ~137 and
+ ~159, `Select`+`SelectTrigger` ~204/208 (frequency), raw `<button>` ~235 (weekday toggle,
+ one per abbreviation), `Select`+`SelectTrigger` ~269/275 (day of month), ~298/302 (hour),
+ ~314/318 (minute), ~337/338 (timezone), **raw `<button>` ~431 ("Event") and ~443
+ ("Schedule") — this pair is the reported bug**, `<EventPicker>` ~465, `<ToggleGroup>` ~479
+ and its three `<ToggleGroupItem>`s ~487/493/499, `<ScheduleEditor>` ~517.
+
+ **ConditionForm.tsx** — add `isReadOnly` to `SortableClauseItem`'s props (~43-56), then:
+ raw `<button>` ~89 (drag grip) **and** pass `disabled: isReadOnly` into the
+ `useSortable({ id: sortId })` call ~80 so dragging is inert, `<ClauseRow>` ~102,
+ `<CombinatorToggle>` ~115, `<Button>` ~231 ("Add clause"), `<IconButton>` ~246
+ ("Remove path"), `<SortableClauseItem>` ~296, `<Button>` ~331 ("Add path"), `<Button>`
+ ~343 ("Add otherwise").
+
+ **ActionForm.tsx** — add `isReadOnly` to `ActionPicker`'s props (~93-98) and
+ `NotifyAboutField`'s props (~182-187), then: raw `<button>` ~126 (action-picker trigger),
+ `CommandInput` ~144, `CommandItem` ~153, `Select`+`SelectTrigger` ~227/228,
+ `<ValueField>` ~240, and inside `renderInput` (~354-418, a closure that can read
+ `isReadOnly` straight from props) `<PairsField>` ~370, `<TemplateField>` ~387,
+ `<ValueField>` ~404; `<ActionPicker>` ~443, raw `<button>` ~461 (the `requireOneOf` group
+ switch, one per member), `<NotifyAboutField>` ~500.
+
+ **EntityForm.tsx** — add `isReadOnly` to `OperationPicker`'s props (~35-39), then:
+ raw `<button>` ~62, `CommandInput` ~81, `CommandItem` ~92, `<OperationPicker>` ~166,
+ `<ValueField>` ~189.
+
+ **LookupForm.tsx** — `<Combobox>` ~120 (`isReadOnly`), raw `<button>` ~137 ("Just one"),
+ ~149 ("Every match"), `<ClauseRow>` ~170, raw `<button>` ~184 ("Add match").
+
+ **FilterForm.tsx** — raw `<button>` ~106 (source picker trigger), `CommandInput` ~127,
+ `CommandItem` ~134, raw `<button>` ~153 ("Clear"), `<CombinatorToggle>` ~174 and ~194,
+ `<ClauseRow>` ~182, `<Button>` ~203 ("Add rule").
+
+4. Line numbers will drift as you edit. After finishing a file, grep it to prove nothing was
+ missed:
+ ```bash
+ grep -n "<button\|<Button\|<IconButton\|<Select\|<Switch\|<ToggleGroup\|<Combobox\|<Command\|<ValueField\|<ClauseRow\|<CombinatorToggle\|<PairsField\|<TemplateField\|<Input\|<NumberField\|<DatePicker" \
+ apps/erp/app/modules/workflows/ui/Builder/config/forms/<File>.tsx
+ ```
+ Every hit must carry a disabling prop wired to `isReadOnly`, or be a nested render of a
+ component that already received it.
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=erp
+# Expected: no errors
+pnpm exec biome check apps/erp/app/modules/workflows
+# Expected: no error-severity findings
+```
+Acceptance criteria 18 and 19 are checked by hand in Task 29.
+
+**Out of scope:** hiding controls. They stay visible and become disabled — a live version must
+read as "this is what it does", not as an empty panel.
+
+---
+
+## Task 9: Build `WorkflowLockAlert` and mount it above the canvas
+
+**Depends on:** Task 5
+**Files:**
+- Create: `apps/erp/app/modules/workflows/ui/WorkflowLockAlert.tsx`
+- Modify: `apps/erp/app/routes/x+/workflow+/$id.tsx` — mount it
+- Copy from (precedent): `apps/erp/app/modules/items/ui/Item/ReleaseLockAlert.tsx`
+
+**Steps:**
+
+1. Create the component, matching the precedent's conventions exactly: default export, arrow
+ function, `Alert variant="warning"` + `LuTriangleAlert` from `react-icons/lu`, `<Trans>`
+ from `@lingui/react/macro` (NOT `useLingui`), optional `className`.
+ ```tsx
+ import { Alert, AlertDescription, AlertTitle, Button } from "@carbon/react";
+ import { Trans } from "@lingui/react/macro";
+ import { LuTriangleAlert } from "react-icons/lu";
+ import { Link } from "react-router";
+ import { path } from "~/utils/path";
+
+ type WorkflowLockAlertProps = {
+ workflowId: string;
+ /** The user holds workflows_update. Telling someone without it to "create a new
+ * version" would be wrong, so the two cases get different copy. */
+ canEdit: boolean;
+ className?: string;
+ };
+
+ const WorkflowLockAlert = ({
+ workflowId,
+ canEdit,
+ className
+ }: WorkflowLockAlertProps) => (
+ <Alert variant="warning" className={className}>
+ <LuTriangleAlert />
+ <AlertTitle>
+ <Trans>This version is live</Trans>
+ </AlertTitle>
+ <AlertDescription>
+ {canEdit ? (
+ <Trans>
+ This version is live. Create a new version to make changes. You can still
+ move steps around to tidy the layout.
+ </Trans>
+ ) : (
+ <Trans>
+ This version is live and you do not have permission to change workflows.
+ </Trans>
+ )}
+ </AlertDescription>
+ {canEdit && (
+ <Button asChild variant="secondary" size="sm" className="mt-2 w-fit">
+ <Link to={path.to.workflowVersionNew(workflowId)}>
+ <Trans>New version</Trans>
+ </Link>
+ </Button>
+ )}
+ </Alert>
+ );
+
+ export default WorkflowLockAlert;
+ ```
+ The description's first sentence deliberately matches `LOCKED_VERSION_MESSAGE` in
+ `apps/erp/app/modules/workflows/workflows.server.ts` — the banner and the server's 409 must
+ say the same thing.
+2. Confirm `path.to.workflowVersionNew(id)` exists in `apps/erp/app/utils/path.ts` (it does) and
+ that `x+/workflow+/$id.version.new.tsx` accepts a GET-navigable link. If that route is
+ POST-only, wrap the button in a `<Form method="post" action={…}>` instead of a `<Link>`
+ rather than inventing a new route.
+3. Mount it in `routes/x+/workflow+/$id.tsx`, between `<BuilderHeader>` and the
+ `<div className="relative flex flex-1 overflow-hidden">`:
+ ```tsx
+ {isVersionLocked && (
+ <WorkflowLockAlert
+ workflowId={workflow.id}
+ canEdit={canEdit}
+ className="mx-4 mt-3"
+ />
+ )}
+ ```
+4. Delete the stale line in `apps/erp/app/modules/workflows/AGENTS.md` (line 55) that already
+ claims this file exists, replacing it with the real inventory:
+ ```
+ ├── WorkflowsTable.tsx, WorkflowForm.tsx, WorkflowLockAlert.tsx, WorkflowActiveSwitch.tsx, WorkflowsUpgradeOverlay.tsx
+ ```
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=erp
+# Expected: no errors
+ls apps/erp/app/modules/workflows/ui/WorkflowLockAlert.tsx
+# Expected: the path prints
+```
+
+**Out of scope:** the 14px lock glyph in `BuilderHeader.tsx` and the `Live` badge in
+`WorkflowVersionStatus.tsx` — both stay; the banner is additive.
+
+---
+
+## Task 10: Add the positions-only writer (service + route + path)
+
+**Depends on:** none
+**Files:**
+- Modify: `apps/erp/app/modules/workflows/workflows.models.ts` — a validator
+- Modify: `apps/erp/app/modules/workflows/workflows.service.ts` — `updateWorkflowNodePositions`
+- Create: `apps/erp/app/routes/x+/workflow+/$id.positions.tsx`
+- Modify: `apps/erp/app/utils/path.ts` — `workflowPositions`
+- Modify: `apps/erp/app/routes/x+/workflow+/$id.tsx` — `shouldRevalidate`
+- Copy from (precedent): `apps/erp/app/routes/x+/workflow+/$id.canvas.tsx` (the deliberately
+ unlocked writer) and `$id.save.tsx` (the locked one)
+
+**Why a second route:** `/save` is correctly locked server-side and must stay locked. A narrow
+endpoint that ignores unknown node ids and never touches `edges` or `data` cannot change
+behaviour even when called by hand (D-13).
+
+**Steps:**
+
+1. Add a validator alongside `workflowDefinitionSaveValidator` in `workflows.models.ts`:
+ ```ts
+ export const workflowNodePositionsValidator = z.object({
+ versionId: zfd.text(z.string()),
+ // A JSON string, same shape as the save route's `nodes`/`edges` fields.
+ positions: zfd.text(z.string())
+ });
+ ```
+ Export it from the module barrel `apps/erp/app/modules/workflows/index.ts` if that barrel
+ lists validators explicitly.
+2. Add the service function to `workflows.service.ts`, next to `updateWorkflowCanvasState`:
+ ```ts
+ /**
+ * The ONE writer allowed on a live version. It reads the version's nodes and re-writes
+ * only `position`, only for node ids that already exist. `edges`, `data`, `expanded`,
+ * `name` and `type` are never touched and an unknown id is ignored, so the endpoint is
+ * incapable of changing behaviour even when called by hand (D-13).
+ *
+ * No audit bump, for the same reason as updateWorkflowCanvasState: tidying a layout is
+ * not an edit, and stamping `updatedAt` would reorder the list on every drag.
+ */
+ export async function updateWorkflowNodePositions(
+ client: SupabaseClient<Database>,
+ {
+ versionId,
+ companyId,
+ positions
+ }: {
+ versionId: string;
+ companyId: string;
+ positions: Record<string, { x: number; y: number }>;
+ }
+ ) {
+ const version = await client
+ .from("workflowVersion")
+ .select("nodes")
+ .eq("id", versionId)
+ .eq("companyId", companyId)
+ .maybeSingle();
+
+ if (version.error) return { data: null, error: version.error };
+ if (!version.data) return { data: null, error: { message: "Version not found" } };
+
+ const nodes = version.data.nodes;
+ if (!Array.isArray(nodes)) {
+ return { data: null, error: { message: "Version has no nodes" } };
+ }
+
+ const next = nodes.map((node) => {
+ const id = (node as { id?: unknown })?.id;
+ const position = typeof id === "string" ? positions[id] : undefined;
+ return position === undefined
+ ? node
+ : { ...(node as object), position: { x: position.x, y: position.y } };
+ });
+
+ return client
+ .from("workflowVersion")
+ .update({ nodes: next as unknown as Json })
+ .eq("id", versionId)
+ .eq("companyId", companyId);
+ }
+ ```
+3. Create `apps/erp/app/routes/x+/workflow+/$id.positions.tsx`, modelled on `$id.canvas.tsx`.
+ It requires `workflows_update` and deliberately does NOT call `checkWorkflowVersionLock`:
+ ```tsx
+ import { assertIsPost } from "@carbon/auth";
+ import { requirePermissions } from "@carbon/auth/auth.server";
+ import { requirePlan } from "@carbon/ee/plan.server";
+ import { validationError, validator } from "@carbon/form";
+ import type { ActionFunctionArgs } from "react-router";
+ import { data } from "react-router";
+ import {
+ updateWorkflowNodePositions,
+ workflowNodePositionsValidator
+ } from "~/modules/workflows";
+ import { path } from "~/utils/path";
+
+ // Node positions carry no behaviour, so the live-version lock does not apply here —
+ // you may tidy a published workflow's layout. The service applies positions only, to
+ // node ids that already exist, so this route cannot change what a workflow does.
+ export async function action({ request }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, companyId } = await requirePermissions(request, {
+ update: "workflows"
+ });
+ await requirePlan({
+ request,
+ client,
+ companyId,
+ feature: "WORKFLOWS",
+ redirectTo: path.to.workflows
+ });
+
+ const validation = await validator(workflowNodePositionsValidator).validate(
+ await request.formData()
+ );
+ if (validation.error) return validationError(validation.error);
+
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(validation.data.positions);
+ } catch {
+ return data({ ok: false, error: "Malformed positions" }, { status: 400 });
+ }
+
+ const shape = z
+ .record(z.string(), z.object({ x: z.number(), y: z.number() }))
+ .safeParse(parsed);
+ if (!shape.success) {
+ return data({ ok: false, error: "Malformed positions" }, { status: 400 });
+ }
+
+ const update = await updateWorkflowNodePositions(client, {
+ versionId: validation.data.versionId,
+ companyId,
+ positions: shape.data
+ });
+
+ if (update.error) {
+ return data({ ok: false, error: update.error.message }, { status: 500 });
+ }
+
+ return data({ ok: true });
+ }
+ ```
+ Import `z` from `"zod"`. Note `$id.save.tsx` also takes `versionId` from the body rather
+ than `params`, which is why this route does too.
+4. Add the path helper to `apps/erp/app/utils/path.ts`, alphabetically between `workflowNew`
+ and `workflowPublish`:
+ ```ts
+ workflowPositions: (id: string) =>
+ generatePath(`${x}/workflow/${id}/positions`),
+ ```
+5. In `routes/x+/workflow+/$id.tsx`, extend `shouldRevalidate` so a positions save does not
+ re-run the loader and remount the store:
+ ```ts
+ return (
+ !formAction?.includes("/save") &&
+ !formAction?.includes("/canvas") &&
+ !formAction?.includes("/positions")
+ );
+ ```
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=erp
+# Expected: no errors
+grep -n "workflowPositions" apps/erp/app/utils/path.ts
+# Expected: one hit
+```
+Acceptance criteria 23 and 24 are exercised by hand in Task 29.
+
+**Out of scope:** `updateWorkflowDefinition`, `checkWorkflowVersionLock`, and `$id.save.tsx` —
+the save route must keep returning 409 on a live version.
+
+---
+
+## Task 11: Split autosave so a locked version saves positions only
+
+**Depends on:** Tasks 4, 10
+**Files:**
+- Modify: `apps/erp/app/modules/workflows/ui/Builder/Autosave.tsx`
+
+**Steps:**
+
+1. Replace the `isReadOnly` subscription with the two flags the store now exposes:
+ ```tsx
+ const isVersionLocked = useBuilderStore((s) => s.isVersionLocked);
+ const canMoveNodes = useBuilderStore((s) => s.canMoveNodes);
+ const canChangeDefinition = useBuilderStore((s) => s.canChangeDefinition);
+ ```
+ (Use whichever hook this file already uses to read store state; keep the existing
+ `useBuilderStoreApi()` for the un-subscribed reads inside the effect.)
+2. In the save effect, replace the `if (isReadOnly) return;` bail with:
+ ```tsx
+ if (!canChangeDefinition && !(isVersionLocked && canMoveNodes)) return;
+ ```
+3. Inside the debounce tick, branch on which endpoint to post to. Keep the same 1s debounce and
+ the same `submittedRef` / baseline-diff machinery:
+ ```tsx
+ const state = store.getState();
+ const definition = fromReactFlow(state.nodes, state.edges);
+ const submitted = JSON.stringify(definition);
+ if (submitted === state.baseline) return;
+
+ const formData = new FormData();
+ formData.append("versionId", versionId);
+
+ if (canChangeDefinition) {
+ formData.append("nodes", JSON.stringify(definition.nodes));
+ formData.append("edges", JSON.stringify(definition.edges));
+ formData.append("formatVersion", String(definition.formatVersion));
+ } else {
+ // A live version: positions are the only thing the server will accept, and the
+ // only thing the store let the user change.
+ const positions = Object.fromEntries(
+ definition.nodes.map((n) => [n.id, { x: n.position.x, y: n.position.y }])
+ );
+ formData.append("positions", JSON.stringify(positions));
+ }
+
+ submittedRef.current = submitted;
+ state.setSaveState("saving");
+ submit(formData, {
+ method: "post",
+ action: canChangeDefinition
+ ? path.to.workflowSave(workflowId)
+ : path.to.workflowPositions(workflowId)
+ });
+ ```
+ Keep `fromReactFlow` as the snapshot source for the baseline diff, so a locked version's
+ baseline still rebaselines correctly on success and a drag is the only thing that can make
+ the two differ (every other mutator is gated in the store).
+4. Add `isVersionLocked`, `canMoveNodes` and `canChangeDefinition` to the effect's dependency
+ array in place of `isReadOnly`.
+5. Leave the completion effect (`rebaseline` on `ok`, `toast.error` otherwise) exactly as is.
+ It now actually fires on a locked version, which is the point — a refused save must say so.
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=erp
+# Expected: no errors
+grep -rn "isReadOnly" apps/erp/app/modules/workflows/ui/Builder/
+# Expected: hits only in files where it is a LOCAL const derived from canChangeDefinition,
+# or a prop name on a shared field component. No hit reading `state.isReadOnly`.
+```
+Acceptance criteria 21, 22 and 25 are checked by hand in Task 29.
+
+**Out of scope:** the canvas-state (viewport) autosave, which has its own route and stays as is.
+
+---
+
+## Task 12: Let a whole record render as text
+
+**Depends on:** none
+**Files:**
+- Modify: `packages/workflows/src/definition/types.ts` — `rendersAsText`
+- Modify: `packages/workflows/src/definition/types.test.ts` — extend
+- Modify: `packages/workflows/src/definition/validate.test.ts` — extend
+
+**Steps:**
+
+1. Replace `rendersAsText` (currently lines 77-85) with:
+ ```ts
+ /**
+ * Whether a value of this type has a reading inside a sentence. A record does: it
+ * prints as its readable id (renderValue falls back to `readableId ?? name ?? id`),
+ * which is exactly what someone means by "…for SO000123". A LIST of records does not —
+ * a run of ids in a sentence has no good reading (D-8).
+ */
+ export function rendersAsText(type: ValueType): boolean {
+ return type.kind !== "list" || type.of.kind !== "entity";
+ }
+ ```
+2. Extend `definition/types.test.ts` with cases proving `rendersAsText` is now `true` for
+ `t.entity("salesOrder")`, still `true` for every primitive, and still `false` for
+ `t.list({ kind: "entity", of: "salesOrder" })`.
+3. Extend `definition/validate.test.ts`: the existing `TYPE_MISMATCH` test that asserts a
+ record in a template is rejected must be changed to assert it is now ACCEPTED, and a new
+ test added asserting a **list of records** in a template is still rejected with
+ `TYPE_MISMATCH`. Find them by searching the file for `TYPE_MISMATCH` and
+ `Pick one of its properties`.
+4. This widens the rule for every template field including webhook bodies — that is intended
+ (they render as the readable id, criterion 17). Do not add a notify-only special case.
+
+**Verify:**
+```bash
+pnpm --filter @carbon/workflows test
+# Expected: all tests pass, including the new entity/list-of-entity cases
+```
+
+**Out of scope:** `renderValue` (it already knows how to print an entity) and the builder's
+`variableMenu.ts` (its `textOnly` filter calls `rendersAsText`, so it follows automatically).
+
+---
+
+## Task 13: Add `linkify` to the catalog and set it on the notify message
+
+**Depends on:** Task 2 (same file)
+**Files:**
+- Modify: `packages/workflows/src/definition/catalog.ts` — `CatalogInput`
+- Modify: `packages/workflows/src/catalog/build.ts` — `BuiltActionInput` + the copy-through
+- Modify: `packages/workflows/src/catalog/actions.ts` — `ActionInputLike` + the notify message
+- Regenerated: `packages/workflows/src/catalog/actions.generated.ts`
+
+**Why a declared flag:** the resolver must not linkify every template, or a webhook body would
+ship markdown (criterion 17). The catalog is the only place that knows which input is prose a
+human reads.
+
+**Steps:**
+
+1. `definition/catalog.ts` — add to `CatalogInput`, after `template`:
+ ```ts
+ /** This input is prose a person reads, so a record dropped into it renders as a
+ * link when the caller supplies one. Webhook bodies deliberately do not set this. */
+ linkify?: boolean;
+ ```
+2. `catalog/build.ts` — add the identical field to `BuiltActionInput` (after `template`), and
+ add one line to the hand-written copy-through loop (currently ~line 615), keeping the
+ established `...(spec.x ? { x: true } : {})` idiom:
+ ```ts
+ ...(spec.template ? { template: true } : {}),
+ ...(spec.linkify ? { linkify: true } : {}),
+ ```
+3. `catalog/actions.ts` — add to `ActionInputLike` (after `template?: boolean;`):
+ ```ts
+ /** Prose a person reads: a record dropped in renders as a link. Not for webhook bodies. */
+ linkify?: boolean;
+ ```
+ Then set it on the notify action's `message` input only — NOT on `subject` (an email subject
+ line renders markdown literally):
+ ```ts
+ message: {
+ type: t.string,
+ required: false,
+ label: "message",
+ template: true,
+ linkify: true
+ },
+ ```
+4. Regenerate:
+ ```bash
+ pnpm run generate:workflow-catalog
+ pnpm exec biome check --write packages/workflows/src/catalog/
+ ```
+ Confirm `actions.generated.ts`'s `notify.inputs.message` now carries `"linkify": true` and
+ `webhook.inputs.body` does not.
+
+**Verify:**
+```bash
+pnpm run check:workflow-catalog
+# Expected: exit 0, "check-workflow-catalog: ok"
+pnpm --filter @carbon/workflows test
+# Expected: all tests pass
+```
+
+**Out of scope:** the generated `<entity>.update` action family — none of its inputs is prose.
+
+---
+
+## Task 14: Render an entity part as a markdown link when a `linkFor` is supplied
+
+**Depends on:** Tasks 12, 13
+**Files:**
+- Modify: `packages/workflows/src/runtime/types.ts` — `RuntimeContext.linkFor`
+- Modify: `packages/workflows/src/runtime/resolve.ts` — `renderTemplate` options
+- Modify: `packages/workflows/src/runtime/action.ts` — pass the option for `linkify` inputs
+- Modify: `packages/workflows/src/runtime/template.test.ts` — extend
+- Modify: `packages/workflows/src/runtime/action.test.ts` — extend
+
+**Design constraint:** `packages/workflows` has four runtime deps and targets the browser at
+ES2019. It must NOT construct a URL or import `@carbon/env` — it calls a callback the engine
+supplies (Task 15).
+
+**Steps:**
+
+1. `runtime/types.ts` — add to `RuntimeContext`, after `record`:
+ ```ts
+ /** Turns a record into an absolute URL, for the inputs the catalog marks `linkify`.
+ * Supplied by the engine, which may read ERP_URL; this package never builds a URL. */
+ linkFor?: (of: string, id: string) => string | null;
+ ```
+2. `runtime/resolve.ts` — give `renderTemplate` an optional third argument and use it only for
+ entity parts:
+ ```ts
+ /** An unresolvable part fails the whole template; a blank would be a silent lie. */
+ export async function renderTemplate(
+ template: Template,
+ ctx: RuntimeContext,
+ options?: { linkFor?: (of: string, id: string) => string | null }
+ ): Promise<Resolution> {
+ const pieces: string[] = [];
+ for (const part of template.parts) {
+ if (part.kind === "text") {
+ pieces.push(part.text);
+ continue;
+ }
+ const resolved =
+ part.kind === "item"
+ ? await resolveItem(part, ctx)
+ : await resolveRef(part, ctx);
+ if (!resolved.ok) return resolved;
+ pieces.push(renderPart(resolved.value, options?.linkFor));
+ }
+ return { ok: true, value: primitiveValue("string", pieces.join("")) };
+ }
+
+ /** A record in prose reads as its id, and becomes a markdown link when the caller
+ * knows where it lives. Every other value renders exactly as before. */
+ function renderPart(
+ value: RuntimeValue,
+ linkFor?: (of: string, id: string) => string | null
+ ): string {
+ const text = renderValue(value);
+ if (linkFor === undefined || value.kind !== "entity" || text === "") return text;
+ const href = linkFor(value.of, value.id);
+ return href === null ? text : `[${text}](${href})`;
+ }
+ ```
+ `resolveValue`'s own `renderTemplate(value, ctx)` call passes no options, so every existing
+ caller renders exactly as today.
+3. `runtime/action.ts` — resolve a `linkify` input through `renderTemplate` with the callback.
+ Replace the input loop's body (currently lines 22-31):
+ ```ts
+ for (const [name, value] of Object.entries(node.data.inputs)) {
+ // Only a catalog-declared prose input linkifies, and only when the engine
+ // supplied a resolver — a webhook body must stay plain text.
+ const linkify =
+ action.inputs[name]?.linkify === true && value.kind === "template";
+ const resolved = linkify
+ ? await renderTemplate(value, ctx, { linkFor: ctx.linkFor })
+ : await resolveValue(value, ctx);
+ if (!resolved.ok) return { status: "Skipped", reason: resolved.reason };
+ inputs[name] =
+ ctx.item !== undefined && resolved.value.kind === "list"
+ ? ctx.item
+ : resolved.value;
+ ctx.record?.(name, inputs[name]);
+ }
+ ```
+ and extend the import at line 6 to `import { renderTemplate, resolveValue } from "./resolve";`.
+4. `runtime/template.test.ts` — add cases: an entity part with no `linkFor` renders its
+ `readableId` unchanged; with a `linkFor` returning a URL it renders
+ `[SO000123](https://example.test/…)`; with a `linkFor` returning `null` it renders the plain
+ id; a null entity value renders `""` and is never wrapped.
+5. `runtime/action.test.ts` — add a case proving an input WITHOUT `linkify` is untouched even
+ when `ctx.linkFor` is present (the webhook-body guarantee, criterion 17).
+
+**Verify:**
+```bash
+pnpm --filter @carbon/workflows test
+# Expected: all tests pass, including the new template and action cases
+pnpm exec turbo run typecheck --filter=@carbon/workflows
+# Expected: no errors
+```
+
+**Out of scope:** URL construction, `@carbon/env`, and `renderValue` (unchanged — the wrapping
+happens in `renderPart`, so every non-template caller is untouched).
+
+---
+
+## Task 15: Supply `linkFor` from the engine
+
+**Depends on:** Task 14
+**Files:**
+- Modify: `packages/jobs/src/workflows/engine/execute.ts` — `contextFor`
+
+**Steps:**
+
+1. Find `contextFor` in `execute.ts` (~lines 125-140), where the `RuntimeContext` is assembled.
+ Add a `linkFor` to the returned context:
+ ```ts
+ // The one place a workflow value becomes a URL. `/api/link` performs the company
+ // switch before redirecting, so a recipient in another active company still lands
+ // on the right record; an entity with no page returns null and renders as plain text.
+ linkFor: (of: string, id: string) =>
+ buildNotificationLink(NotificationEvent.Workflow, id, payload.companyId, of as never),
+ ```
+ importing `buildNotificationLink` from
+ `../../inngest/functions/notifications/content` and `NotificationEvent` from
+ `@carbon/notifications`. Use the same `documentType` cast the notify action already uses
+ (`notify.ts` casts the catalog entity name to `ApprovalDocumentType` with the comment that
+ the column is TEXT and the resolver reads the workflow entity name) — mirror that cast
+ rather than inventing a new one.
+2. `/api/link` resolves `documentType` through `getRecordPath`, whose `RECORD_ROUTES` map has
+ 19 keys. An entity outside that map lands on the dashboard rather than 404ing, which is the
+ existing behaviour for the notification row itself — acceptable, and the link text is still
+ the readable id.
+3. If `contextFor` does not have `payload` in scope, thread `companyId` in from its caller
+ rather than reading a module-level value.
+
+**Verify:**
+```bash
+pnpm --filter @carbon/jobs typecheck
+# Expected: no errors (note: this package uses `tsc --noEmit`, not tsgo)
+pnpm --filter @carbon/jobs test
+# Expected: all tests pass
+```
+
+**Out of scope:** Slack (not a workflow destination) and the `aboutId`/`aboutType` inputs,
+which already make the whole notification row clickable and are unchanged.
+
+---
+
+## Task 16: Add `renderInlineLinks` to `@carbon/notifications`
+
+**Depends on:** none
+**Files:**
+- Modify: `packages/notifications/src/index.ts` — add the helper
+- Create: `packages/notifications/src/index.test.ts`
+- Modify: `packages/notifications/package.json` — add a `test` script
+
+**This is a security boundary, not a formatting nicety.** The body is customer-authored text.
+If the matcher accepted any URL, a workflow author could inject an arbitrary destination into a
+notification the recipient trusts (D-11).
+
+**Steps:**
+
+1. Append to `packages/notifications/src/index.ts`:
+ ```ts
+ export type InlineLinkSegment =
+ | { text: string }
+ | { text: string; href: string };
+
+ // Deliberately strict: `[label](url)` where url is an absolute https URL on the
+ // supplied origin. A relative path, another host, or a javascript: URL is left as
+ // literal text — the body is customer-authored and must not be able to choose where
+ // a trusted notification points.
+ const INLINE_LINK = /\[([^\]\n]+)\]\((https:\/\/[^\s()]+)\)/g;
+
+ export function renderInlineLinks(
+ text: string,
+ origin: string
+ ): InlineLinkSegment[] {
+ const segments: InlineLinkSegment[] = [];
+ let index = 0;
+
+ let allowed: URL;
+ try {
+ allowed = new URL(origin);
+ } catch {
+ return text === "" ? [] : [{ text }];
+ }
+
+ INLINE_LINK.lastIndex = 0;
+ for (const match of text.matchAll(INLINE_LINK)) {
+ const [whole, label, href] = match;
+ if (label === undefined || href === undefined) continue;
+
+ let parsed: URL;
+ try {
+ parsed = new URL(href);
+ } catch {
+ continue;
+ }
+ if (parsed.protocol !== "https:" || parsed.origin !== allowed.origin) continue;
+
+ const start = match.index ?? 0;
+ if (start > index) segments.push({ text: text.slice(index, start) });
+ segments.push({ text: label, href: parsed.toString() });
+ index = start + whole.length;
+ }
+
+ if (index < text.length) segments.push({ text: text.slice(index) });
+ return segments;
+ }
+ ```
+2. Create `packages/notifications/src/index.test.ts` (this package has no tests yet, and
+ `@carbon/config/vitest` sets `globals: false`, so import the helpers explicitly):
+ ```ts
+ import { describe, expect, it } from "vitest";
+ import { renderInlineLinks } from "./index";
+
+ const ORIGIN = "https://app.carbon.ms";
+
+ describe("renderInlineLinks", () => {
+ it("splits a link out of surrounding text", () => { … });
+ it("leaves a javascript: URL as literal text", () => { … }); // criterion 16
+ it("leaves another host as literal text", () => { … });
+ it("leaves a relative path as literal text", () => { … });
+ it("leaves plain text as one segment", () => { … });
+ it("handles two links in one body", () => { … });
+ it("returns [] for an empty string", () => { … });
+ });
+ ```
+ Fill in each assertion; do not leave a `…` in the committed file.
+3. Add the missing runner to `packages/notifications/package.json` scripts:
+ ```json
+ "test": "vitest run"
+ ```
+ and add `@carbon/config` + `vitest` to its `devDependencies` (catalog versions) plus a
+ one-line `vitest.config.ts` matching the other packages:
+ ```ts
+ export { default } from "@carbon/config/vitest";
+ ```
+ Run `pnpm install` afterwards.
+
+**Verify:**
+```bash
+pnpm --filter @carbon/notifications test
+# Expected: 7 tests pass
+pnpm --filter @carbon/notifications typecheck
+# Expected: no errors
+```
+
+**Out of scope:** any other markdown syntax. Bold, italics and lists stay literal text.
+
+---
+
+## Task 17: Render inline links in the notification email
+
+**Depends on:** Task 16
+**Files:**
+- Modify: `packages/documents/src/email/NotificationEmail.tsx` — the detail value cell
+- Modify: `packages/jobs/src/inngest/functions/notifications/notify.ts` — pass the origin
+
+**Steps:**
+
+1. `NotificationEmail.tsx` renders `{detail.value}` inside a `<Text>` in a right-aligned cell
+ (~lines 300-317). Replace the bare value with segments:
+ ```tsx
+ <Text className={…}>
+ {renderInlineLinks(detail.value, erpUrl).map((segment, i) =>
+ "href" in segment ? (
+ <Link key={i} href={segment.href} style={{ color: "#2563eb" }}>
+ {segment.text}
+ </Link>
+ ) : (
+ <span key={i}>{segment.text}</span>
+ )
+ )}
+ </Text>
+ ```
+ using `Link` from `@react-email/components` (check what this file already imports; if it has
+ no `Link`, add it from the same package the other components come from).
+2. `NotificationEmail.tsx` deliberately keeps a LOCAL copy of `NotificationDetail` so the email
+ package need not depend on `@carbon/notifications`. Do not break that: add an `erpUrl?:
+ string` prop to the component and, if `erpUrl` is absent, render `detail.value` exactly as
+ today. Import `renderInlineLinks` from `@carbon/notifications` only if that dependency
+ already exists; otherwise copy the helper's *call* into the jobs package instead — i.e. have
+ `notify.ts` pre-split the segments and pass `details` values through unchanged, and put the
+ segment rendering in the email. **Decide by checking `packages/documents/package.json`
+ first.** If neither route is clean, STOP and report rather than adding a new cross-package
+ dependency by guess.
+3. In `packages/jobs/src/inngest/functions/notifications/notify.ts`, pass `erpUrl={ERP_URL}`
+ wherever `NotificationEmail` is rendered.
+4. The Workflow body is the only detail whose value is long prose, and the cell is
+ `textAlign: "right"` with a `whiteSpace: "nowrap"` label. Leave the layout alone in this
+ task — criterion 15 only requires the link to work.
+
+**Verify:**
+```bash
+pnpm --filter @carbon/documents typecheck
+pnpm --filter @carbon/jobs typecheck
+# Expected: no errors
+pnpm --filter @carbon/documents test
+# Expected: all tests pass
+```
+
+**Out of scope:** redesigning the details table, and every non-Workflow notification event
+(they pass through the same code path unchanged because their values contain no `[…](…)`).
+
+---
+
+## Task 18: Render the message body and its links in the in-app bell
+
+**Depends on:** Task 16
+**Files:**
+- Modify: `apps/erp/app/components/Layout/Topbar/Notifications.tsx`
+
+**Today `payload.details` is written and never read** — a workflow author's message is
+invisible in-app, which would make the whole link feature look broken (spec §5.2c).
+
+**Steps:**
+
+1. `GenericNotification` (~lines 185-200) receives the row but not its `payload`. Thread the
+ body through: read `payload.details` where the row is unpacked (find where `description` is
+ taken off `payload`), take the entry whose `label === "Message"`, and pass it as a new
+ optional `body?: string` prop down to `Notification`.
+2. In the `Notification` component (~lines 121-183), render the body under the description:
+ ```tsx
+ <p className="text-sm">
+ {description} {byUser && <span>{t`by ${byUser}`}</span>}
+ </p>
+ {body && (
+ <p className="text-xs text-muted-foreground line-clamp-3">{…segments…}</p>
+ )}
+ ```
+3. **The row is currently one `<Link to={to}>` wrapping everything.** A nested `<a>` is invalid
+ HTML and browsers will unnest it, so the anchor inside the body would escape the row.
+ Restructure: drop the outer `<Link>`, keep the same markup inside a
+ `<div role="link" tabIndex={0}>` (or a plain div) whose `onClick` and `onKeyDown` (Enter and
+ Space) call `navigate(to)` then `onClose()`, and render the body's link segments as real
+ `<Link to={segment.href}>` elements with `e.stopPropagation()` on their click so they do not
+ also fire the row navigation. Keep the existing `hover:bg-secondary` row styling and the
+ sibling "Mark as read" `IconButton` exactly where they are.
+4. Segment the body with `renderInlineLinks(body, window.location.origin)` from
+ `@carbon/notifications`. The href produced by Task 15 is an absolute
+ `${ERP_URL}/api/link?…` URL, so on the ERP origin it matches and becomes a link; use
+ `<a href={…}>` (a full page load through `/api/link`, which performs the company switch)
+ rather than a client-side `<Link>` for those — criterion 14 explicitly requires the company
+ switch to work.
+5. Every other notification event renders through this same component. Verify by eye that a
+ non-Workflow notification (which has no `body`) is visually unchanged.
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=erp
+# Expected: no errors
+pnpm exec biome check apps/erp/app/components/Layout/Topbar/Notifications.tsx
+# Expected: no error-severity findings
+```
+Criterion 14 and 16 are checked by hand in Task 29. This component renders EVERY notification
+type — regression-check at least three different events in the bell during Task 29.
+
+**Out of scope:** the digest child-row payload shape (it carries no `details`), and the
+notification detail drawer if one exists elsewhere.
+
+---
+
+## Task 19: Build the per-company catalog overlay module
+
+**Depends on:** none
+**Files:**
+- Create: `packages/workflows/src/catalog/custom-fields.ts`
+- Create: `packages/workflows/src/catalog/custom-fields.test.ts`
+- Modify: `packages/workflows/src/catalog/index.ts` — export it
+
+**Why an overlay (D-2):** `events.generated.ts` is committed, global and drift-checked against
+a fresh build. Custom fields are per-company and runtime. They cannot be generated; an overlay
+merged at the two catalog construction sites is the smallest seam.
+
+**Steps:**
+
+1. Create `packages/workflows/src/catalog/custom-fields.ts`. Pure, no I/O, no DB import:
+ ```ts
+ import type { CatalogEvent, CatalogInput } from "../definition/catalog";
+ import { t, type ValueType } from "../definition/types";
+ import { REGISTRY_ENTRIES } from "./entities";
+
+ /** One path segment, not a two-hop drill: `walkPath` and the runtime `walk` stay
+ * single-step, and the nested differ never emits the bare `customFields` key (D-3). */
+ export const CUSTOM_FIELD_PREFIX = "customFields.";
+
+ /** Custom fields attach to the item SUBTYPES (part, material, tool, …) while the
+ * catalog triggers on the shared `item` table. Merging them needs a collision rule
+ * and is its own change (D-7). */
+ const EXCLUDED_ENTITIES = new Set(["item"]);
+
+ /** The shape the ERP already loads, from `customField` / the `customFieldTables` view. */
+ export type CustomFieldDef = {
+ table: string;
+ /** The key inside the JSONB blob — an id, never the name. */
+ id: string;
+ name: string;
+ dataTypeId: number;
+ listOptions: string[] | null;
+ active: boolean;
+ };
+
+ export type CatalogOverlay = {
+ /** entity -> property path -> type */
+ properties: Record<string, Record<string, ValueType>>;
+ /** label key -> the customer's field name, verbatim and untranslated */
+ labels: Record<string, string>;
+ /** entity -> property path -> allowed values */
+ enums: Record<string, Record<string, readonly string[]>>;
+ /** action id -> input name -> spec, for the `<entity>.update` family */
+ actionInputs: Record<string, Record<string, CatalogInput>>;
+ };
+
+ export const EMPTY_OVERLAY: CatalogOverlay = {
+ properties: {},
+ labels: {},
+ enums: {},
+ actionInputs: {}
+ };
+
+ /** table -> registry entity name. Built once; the registry is committed data. */
+ export const ENTITY_BY_TABLE: Record<string, string> = Object.fromEntries(
+ Object.entries(REGISTRY_ENTRIES).map(([name, entry]) => [entry.table, name])
+ );
+
+ /** The ONE place DataType (apps/erp/app/modules/shared/types.ts) maps to a ValueType.
+ * A File field is exposed as the stored path — comparable and printable, but not a
+ * link and not a record to drill into (D-16). */
+ function valueTypeFor(dataTypeId: number): ValueType | undefined {
+ switch (dataTypeId) {
+ case 1: return t.boolean; // Boolean
+ case 2: return t.date; // Date
+ case 3: return t.string; // List — choices come from listOptions
+ case 4: return t.number; // Numeric
+ case 5: return t.string; // Text
+ case 6: return t.entity("user");
+ case 7: return t.entity("customer");
+ case 8: return t.entity("supplier");
+ case 9: return t.string; // File — the stored path
+ default: return undefined;
+ }
+ }
+
+ export function buildCatalogOverlay(defs: CustomFieldDef[]): CatalogOverlay {
+ const overlay: CatalogOverlay = {
+ properties: {},
+ labels: {},
+ enums: {},
+ actionInputs: {}
+ };
+
+ for (const def of defs) {
+ if (!def.active) continue;
+ const entity = ENTITY_BY_TABLE[def.table];
+ if (entity === undefined || EXCLUDED_ENTITIES.has(entity)) continue;
+ const type = valueTypeFor(def.dataTypeId);
+ if (type === undefined) continue;
+
+ const property = `${CUSTOM_FIELD_PREFIX}${def.id}`;
+ const choices =
+ def.dataTypeId === 3 && def.listOptions && def.listOptions.length > 0
+ ? def.listOptions
+ : undefined;
+
+ (overlay.properties[entity] ??= {})[property] = type;
+ overlay.labels[`entity.${entity}.${property}`] = def.name;
+ if (choices) (overlay.enums[entity] ??= {})[property] = choices;
+
+ // Writable through the generated update action, when the entity has one.
+ const actionId = `${entity}.update`;
+ (overlay.actionInputs[actionId] ??= {})[property] = {
+ type,
+ required: false,
+ ...(choices ? { choices } : {})
+ };
+ overlay.labels[`action.${actionId}.input.${property}`] = def.name;
+ }
+
+ return overlay;
+ }
+
+ /** `<entity>.customFields.<fieldId>.changed`. Deliberately parallel to the generated
+ * `<entity>.<column>.changed`. */
+ const CUSTOM_FIELD_EVENT =
+ /^([A-Za-z][A-Za-z0-9]*)\.customFields\.([^.]+)\.changed$/;
+
+ export function customFieldEventId(entity: string, fieldId: string): string {
+ return `${entity}.${CUSTOM_FIELD_PREFIX}${fieldId}.changed`;
+ }
+
+ /**
+ * Parses a custom-field event id into a synthetic CatalogEvent. WORKFLOW_EVENTS stays a
+ * closed, committed, drift-checked record — a per-company id cannot live there, so the
+ * id is PARSED rather than looked up (D-4). Company-blind by design: whether the field
+ * actually exists is decided by the workflowTriggerEvent join, not here.
+ */
+ export function resolveCustomFieldEvent(id: string): CatalogEvent | undefined {
+ const match = CUSTOM_FIELD_EVENT.exec(id);
+ if (match === null) return undefined;
+ const [, entity, fieldId] = match;
+ if (entity === undefined || fieldId === undefined) return undefined;
+ if (EXCLUDED_ENTITIES.has(entity)) return undefined;
+ const entry = REGISTRY_ENTRIES[entity];
+ // Reference-only entities have no `watch` and therefore no change events at all.
+ if (entry === undefined || entry.watch === undefined) return undefined;
+
+ return {
+ id,
+ outputs: {
+ record: t.entity(entity),
+ before: t.entity(entity),
+ after: t.entity(entity)
+ },
+ permission: entry.permission,
+ match: {
+ table: entry.table,
+ operation: "UPDATE",
+ field: `${CUSTOM_FIELD_PREFIX}${fieldId}`
+ }
+ };
+ }
+ ```
+2. Export the module from `packages/workflows/src/catalog/index.ts`:
+ ```ts
+ export type { CatalogOverlay, CustomFieldDef } from "./custom-fields";
+ export {
+ buildCatalogOverlay,
+ CUSTOM_FIELD_PREFIX,
+ customFieldEventId,
+ EMPTY_OVERLAY,
+ ENTITY_BY_TABLE,
+ resolveCustomFieldEvent
+ } from "./custom-fields";
+ ```
+ `src/index.ts` line 1 is `export * from "./catalog";`, so this reaches the public barrel.
+3. Create `custom-fields.test.ts` covering: each DataType maps to the right ValueType; an
+ inactive field is dropped; a field on `item` is dropped; a field on a table not in the
+ registry is dropped; a List field puts its options in `enums` AND on the action input; the
+ property key is exactly `customFields.<id>`; `resolveCustomFieldEvent` parses a valid id,
+ rejects `item.customFields.x.changed`, rejects a reference-only entity
+ (`user.customFields.x.changed`), rejects a malformed id, and returns a `match.field` of
+ `customFields.<id>`; `customFieldEventId` round-trips through `resolveCustomFieldEvent`.
+ Import `{ describe, expect, it } from "vitest"` explicitly — the shared config sets
+ `globals: false`.
+
+**Verify:**
+```bash
+pnpm --filter @carbon/workflows test
+# Expected: all tests pass, including the new custom-fields suite
+pnpm exec turbo run typecheck --filter=@carbon/workflows
+# Expected: no errors
+```
+
+**Out of scope:** `build.ts`'s `DROPPED_COLUMNS` — `customFields` stays out of the generated
+property map; the overlay is the only path in.
+
+---
+
+## Task 20: Accept the overlay in the catalog facade and resolve custom-field events
+
+**Depends on:** Tasks 14, 19
+**Files:**
+- Modify: `packages/workflows/src/definition/catalog.ts` — `WorkflowCatalog` gains two lookups
+- Modify: `packages/workflows/src/catalog/catalog.ts` — merge the overlay
+- Modify: `packages/workflows/src/sync.ts` — resolve rather than index
+- Modify: `packages/workflows/src/catalog/catalog.test.ts` and `src/sync.test.ts` — extend
+
+**Steps:**
+
+1. `definition/catalog.ts` — add to the `WorkflowCatalog` interface:
+ ```ts
+ /** The customer's own name for a property, when it is a custom field. */
+ getPropertyLabel(entity: string, property: string): string | undefined;
+ /** The customer's own name for an action input, when it is a custom field. */
+ getInputLabel(actionId: string, input: string): string | undefined;
+ ```
+ `createFixtureCatalog` in the same file must gain both (returning `undefined`) or every
+ test that builds one fails to compile.
+2. `packages/workflows/src/catalog/catalog.ts` — add the module-level resolver and take the
+ overlay:
+ ```ts
+ /** The single event lookup: the committed catalog first, then the parsed custom-field
+ * pattern. Every consumer goes through here, so `WORKFLOW_EVENTS` stays closed (D-4). */
+ export function getCatalogEvent(id: string): CatalogEvent | undefined {
+ return EVENTS.get(id) ?? resolveCustomFieldEvent(id);
+ }
+
+ export function createWorkflowCatalog(
+ overlay: CatalogOverlay = EMPTY_OVERLAY
+ ): WorkflowCatalog {
+ return {
+ getEvent: getCatalogEvent,
+ getEntity: (name) => {
+ const base = ENTITIES.get(name);
+ const extra = overlay.properties[name];
+ if (base === undefined || extra === undefined) return base;
+ // Generated first, overlay second: a real column always wins, so a customer
+ // cannot shadow one.
+ return { ...base, properties: { ...base.properties, ...extra } };
+ },
+ getAction: (id) => {
+ const base = ACTIONS.get(id);
+ const extra = overlay.actionInputs[id];
+ if (base === undefined || extra === undefined) return base;
+ return { ...base, inputs: { ...base.inputs, ...extra } };
+ },
+ getOperation: (id) => OPERATIONS.get(id),
+ getEnum: (entity, property) =>
+ ENUMS.get(entity)?.[property] ?? overlay.enums[entity]?.[property],
+ getPropertyLabel: (entity, property) =>
+ overlay.labels[`entity.${entity}.${property}`],
+ getInputLabel: (actionId, input) =>
+ overlay.labels[`action.${actionId}.input.${input}`]
+ };
+ }
+ ```
+ Import `CatalogOverlay`, `EMPTY_OVERLAY` and `resolveCustomFieldEvent` from
+ `./custom-fields`. Every existing call site passes no argument and is unaffected.
+3. `packages/workflows/src/sync.ts` — `deriveWorkflowSubscriptions` currently reads
+ `WORKFLOW_EVENTS[eventId]?.match` (line 59). Change the import at line 4 to
+ `import { getCatalogEvent } from "./catalog";` and line 59 to:
+ ```ts
+ const match = getCatalogEvent(eventId)?.match;
+ ```
+ This is what makes publishing a custom-field trigger create the right
+ `eventSystemSubscription` (criterion 2).
+4. Extend `catalog.test.ts`: `getEvent("salesOrder.customFields.cf_x.changed")` returns a
+ synthetic event with `match.field === "customFields.cf_x"`; an overlay property appears on
+ `getEntity`; an overlay property does NOT override a generated column of the same key; an
+ overlay enum is returned by `getEnum`; `getAction("salesOrder.update")` includes the overlay
+ input; `getPropertyLabel` returns the customer's name.
+5. Extend `sync.test.ts`: `deriveWorkflowSubscriptions(["salesOrder.customFields.cf_x.changed"])`
+ returns `[{ table: "salesOrder", operations: ["UPDATE"] }]`, and an id for `item` returns `[]`.
+
+**Verify:**
+```bash
+pnpm --filter @carbon/workflows test
+# Expected: all tests pass
+pnpm exec turbo run typecheck --filter=@carbon/workflows
+pnpm exec turbo run typecheck --filter=@carbon/jobs
+pnpm exec turbo run typecheck --filter=erp
+# Expected: no errors — every existing createWorkflowCatalog() call still compiles
+```
+
+**Out of scope:** `event-ids.ts` (Task 21) and the builder (Task 25).
+
+---
+
+## Task 21: Derive custom-field event ids in the matcher
+
+**Depends on:** Task 20
+**Files:**
+- Modify: `packages/jobs/src/workflows/event-ids.ts`
+- Modify: `packages/jobs/src/workflows/event-ids.test.ts` — extend
+
+**The matcher stays company-blind (D-5).** `computeNestedDiff` already emits
+`customFields.<id>` keys, so the id is derived from the data and the existing
+`workflowTriggerEvent` join does the filtering it already does. No company lookup is added to
+the hot path.
+
+**Steps:**
+
+1. Import the helpers and build a table→entity index once at module scope, beside `INDEX`:
+ ```ts
+ import { ENTITY_BY_TABLE, customFieldEventId, createWorkflowCatalog } from "@carbon/workflows";
+
+ const CATALOG = createWorkflowCatalog();
+ ```
+2. In `computeEventIds`, after the existing watched-column loop (currently lines 53-57), append
+ the custom-field pass:
+ ```ts
+ const ids: string[] = [];
+ for (const [field, id] of entry.changed) {
+ if (field in diff) ids.push(id);
+ }
+
+ // A custom field's event id is derived from the diff key, not looked up: the id is
+ // per company, the catalog is not. resolveCustomFieldEvent decides whether the
+ // entity may carry one at all (item is excluded), so the rule lives in one place.
+ const entity = ENTITY_BY_TABLE[input.table];
+ if (entity !== undefined) {
+ for (const key of Object.keys(diff)) {
+ const fieldId = key.startsWith("customFields.")
+ ? key.slice("customFields.".length)
+ : undefined;
+ if (fieldId === undefined || fieldId === "") continue;
+ const id = customFieldEventId(entity, fieldId);
+ if (CATALOG.getEvent(id) !== undefined) ids.push(id);
+ }
+ }
+
+ return ids;
+ ```
+ Custom-field ids are appended AFTER the generated `.changed` ids, which keeps the existing
+ "one run per workflow per announcement, first event id wins" rule producing the same winner
+ as today for any workflow subscribed to both.
+3. Extend `event-ids.test.ts`: an UPDATE whose diff contains `customFields.cf_x` on
+ `salesOrder` yields `["salesOrder.customFields.cf_x.changed"]`; the same on `item` yields
+ `[]`; a bare `customFields` key (which the nested differ never emits) yields `[]`; an update
+ touching both a watched column and a custom field yields both ids with the column's id
+ first; an unwatched table still yields `[]`.
+
+**Verify:**
+```bash
+pnpm --filter @carbon/jobs exec vitest run src/workflows/event-ids.test.ts
+# Expected: all tests pass
+pnpm --filter @carbon/jobs typecheck
+# Expected: no errors
+```
+
+**Out of scope:** `computeNestedDiff` in `inngest/functions/events/diff.ts` — it already emits
+the right keys and must not change.
+
+---
+
+## Task 22: Add the `workflow_merge_custom_fields` RPC
+
+**Depends on:** none
+**Files:**
+- Create: a new migration under `packages/database/supabase/migrations/`
+- Regenerated: `packages/database/src/types.ts` (never hand-edited)
+
+**Why an RPC (D-6):** a read-modify-write on the JSONB blob through the Supabase client races a
+concurrent human edit and would erase the other fields. `||` merges server-side in one
+statement.
+
+**Steps:**
+
+1. Create the migration:
+ ```bash
+ pnpm db:migrate:new workflow-merge-custom-fields
+ ```
+2. Fill it in, following the house style (a `--` rationale block, `SECURITY INVOKER`,
+ `SET search_path = public`, `GRANT EXECUTE … TO authenticated` on its own final line):
+ ```sql
+ -- A workflow may set one custom field without erasing the others. Reading the blob,
+ -- merging in app code and writing it back races a concurrent human edit and silently
+ -- drops their change, so the merge happens server-side in one statement.
+ --
+ -- SECURITY INVOKER: the workflow runs as its owner and RLS on the target table is the
+ -- authorization gate, exactly as it is for the ordinary column update beside it.
+ -- p_table is validated against "customFieldTable" — the existing global allowlist —
+ -- before it is ever interpolated into the dynamic statement.
+ CREATE OR REPLACE FUNCTION workflow_merge_custom_fields (
+ p_table TEXT,
+ p_id TEXT,
+ p_company_id TEXT,
+ p_values JSONB
+ )
+ RETURNS VOID
+ LANGUAGE "plpgsql"
+ SECURITY INVOKER
+ SET search_path = public
+ AS $$
+ BEGIN
+ IF NOT EXISTS (SELECT 1 FROM "customFieldTable" WHERE "table" = p_table) THEN
+ RAISE EXCEPTION 'Unknown custom field table: %', p_table;
+ END IF;
+
+ IF p_values IS NULL OR jsonb_typeof(p_values) <> 'object' THEN
+ RAISE EXCEPTION 'p_values must be a JSON object';
+ END IF;
+
+ EXECUTE format(
+ 'UPDATE %I SET "customFields" = COALESCE("customFields", ''{}''::jsonb) || $1 '
+ 'WHERE "id" = $2 AND "companyId" = $3',
+ p_table
+ ) USING p_values, p_id, p_company_id;
+ END;
+ $$;
+
+ GRANT EXECUTE ON FUNCTION workflow_merge_custom_fields(TEXT, TEXT, TEXT, JSONB) TO authenticated;
+ ```
+3. Apply it and regenerate the types — **in this order**, before any typecheck that depends on
+ the new RPC:
+ ```bash
+ pnpm db:migrate
+ pnpm run generate:types
+ ```
+ If the local database is not running, STOP and ask the user to start it — never rebuild the
+ database to test a change.
+4. Confirm the RPC now appears in the generated types:
+ ```bash
+ grep -n "workflow_merge_custom_fields" packages/database/src/types.ts
+ # Expected: at least one hit under Functions
+ ```
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=@carbon/database
+# Expected: no errors
+```
+
+**Out of scope:** any schema change to `customField` or `customFieldTable`, and RLS policy
+edits. Both stay exactly as they are.
+
+---
+
+## Task 23: Write custom fields from the update action
+
+**Depends on:** Tasks 19, 22
+**Files:**
+- Modify: `packages/jobs/src/workflows/actions/update.ts`
+- Create: `packages/jobs/src/workflows/actions/update.test.ts` (if absent; otherwise extend)
+
+**Steps:**
+
+1. In `runUpdateAction`, split custom-field inputs out of the ordinary column loop. Replace the
+ `fields` accumulation loop (currently ~lines 78-96) so keys beginning with the prefix land in
+ a second bucket, while all the existing validation still runs on them:
+ ```ts
+ const fields: Record<string, unknown> = {};
+ const customFields: Record<string, unknown> = {};
+
+ for (const [column, value] of Object.entries(inputs)) {
+ if (column === entity) continue;
+ const spec = action.inputs[column];
+ const raw = toPlainValue(value);
+
+ if (raw === undefined) continue;
+ if (raw === null && spec?.notNull) continue;
+
+ if (
+ raw !== null &&
+ spec?.choices !== undefined &&
+ !spec.choices.includes(String(raw))
+ ) {
+ return { ok: false, error: `"${String(raw)}" is not a valid ${column}.` };
+ }
+
+ if (column.startsWith(CUSTOM_FIELD_PREFIX)) {
+ // The ERP's form layer writes every custom field as a FormData string, so the
+ // blob holds strings whatever the declared type. `fromColumn` coerces back by
+ // the DECLARED type on read, so writing a string here round-trips exactly.
+ customFields[column.slice(CUSTOM_FIELD_PREFIX.length)] =
+ raw === null ? null : String(raw);
+ continue;
+ }
+
+ fields[column] = raw;
+ }
+ ```
+ Import `CUSTOM_FIELD_PREFIX` from `@carbon/workflows`.
+2. The tenancy loop that follows must cover custom fields too — a User/Customer/Supplier custom
+ field is an entity-typed value and must be proved to belong to this company. Run the same
+ loop over `Object.entries(customFields)`, looking the spec up under the prefixed key:
+ ```ts
+ for (const [fieldId, raw] of Object.entries(customFields)) {
+ if (raw === null) continue;
+ const spec = action.inputs[`${CUSTOM_FIELD_PREFIX}${fieldId}`];
+ const scope =
+ spec?.type.kind === "entity"
+ ? REGISTRY_ENTRIES[spec.type.of]?.table
+ : spec?.scopeTable;
+ if (scope === undefined) continue;
+
+ const belongs = await existsInCompany({
+ client,
+ table: scope,
+ id: String(raw),
+ companyId
+ });
+ if (!belongs) {
+ return { ok: false, error: `The value you chose is not in this company.` };
+ }
+ }
+ ```
+3. Issue the merge as a separate statement AFTER the ordinary update, and only when there is
+ something to write. Both live inside the same durable step, whose at-most-once claim already
+ covers a partial failure:
+ ```ts
+ if (Object.keys(customFields).length > 0) {
+ // One statement, server-side `||` merge: setting one field must not erase the
+ // others, and a read-modify-write here would race a concurrent human edit (D-6).
+ const merged = await client.rpc("workflow_merge_custom_fields", {
+ p_table: table,
+ p_id: target.id,
+ p_company_id: companyId,
+ p_values: customFields
+ });
+ if (merged.error) return { ok: false, error: merged.error.message };
+ }
+ ```
+ Place it after the existing `.update(...)` call and before the success return. If
+ `fields` is empty, skip the ordinary update entirely rather than writing a bare
+ `updatedBy`/`updatedAt` — decide by `Object.keys(fields).length > 0`.
+4. Update the success summary so the count includes both:
+ ```ts
+ summary: `Updated ${Object.keys(fields).length + Object.keys(customFields).length} field(s).`
+ ```
+5. Add tests for: a custom field write leaves the other keys in the blob intact (criterion 8);
+ a List custom field set outside its `listOptions` fails with a reason and writes nothing
+ (criterion 9); a User custom field pointing at another company's user is refused; an
+ update setting both a real column and a custom field issues both statements. Mock the
+ Supabase client the way the neighbouring `notify.test.ts` does.
+
+**Verify:**
+```bash
+pnpm --filter @carbon/jobs test
+pnpm --filter @carbon/jobs typecheck
+# Expected: all tests pass, no errors
+```
+
+**Out of scope:** creating custom fields, deleting them, and the `create` action family.
+
+---
+
+## Task 24: Load the company's custom fields in the engine
+
+**Depends on:** Tasks 19, 20
+**Files:**
+- Modify: `packages/jobs/src/workflows/engine/execute.ts`
+
+**Steps:**
+
+1. `executeWorkflowRun` currently builds the catalog on its second line
+ (`const catalog = createWorkflowCatalog();`) — before the `"load"` step. `catalog` is not
+ read until after `loaded` is settled (`walkWorkflow`, the `"permissions"` step,
+ `triggerOutputs`), so it can safely move down.
+2. Delete that line. After the `if (loaded.settled !== null) return …` early exit, add a new
+ durable step that reads the company's definitions through the **owner-scoped** client — the
+ same client every other business read uses, so a field the owner may not see does not reach
+ the workflow:
+ ```ts
+ // Read as the owner, like every other business read: `customField` is company-scoped
+ // and RLS-covered. Its own step so a transient read failure retries without redoing
+ // the run claim above.
+ const customFields = await step.run("custom-fields", async () => {
+ const client = await getOwnerClient(payload.ownerId, payload.runId);
+ const { data, error } = await client
+ .from("customField")
+ .select("table, id, name, dataTypeId, listOptions, active")
+ .eq("companyId", payload.companyId)
+ .eq("active", true);
+ // A company with no custom fields, and a refused read, are the same answer here:
+ // the workflow runs against the shipped catalog alone.
+ return error || !data ? [] : data;
+ });
+
+ const catalog = createWorkflowCatalog(
+ buildCatalogOverlay(customFields as CustomFieldDef[])
+ );
+ ```
+ Import `buildCatalogOverlay` and the `CustomFieldDef` type from `@carbon/workflows`.
+3. Everything downstream works unchanged: `resolve.ts`'s `entity.properties[segment]` gate now
+ finds the property, `fromColumn` coerces by the declared `ValueType`, and `compare.ts` is
+ untouched. A value that cannot be coerced resolves to nothing, which the engine already
+ treats as "skip with a reason", never an error.
+4. Confirm `getOwnerClient` is already imported in this file (it is, used by `contextFor` and
+ the `"permissions"` step). If `payload.ownerId` is not in scope at that point, STOP and
+ report rather than reaching for a privileged client.
+
+**Verify:**
+```bash
+pnpm --filter @carbon/jobs typecheck
+pnpm --filter @carbon/jobs test
+# Expected: no errors, all tests pass
+```
+
+**Out of scope:** `loader.ts` — it already does `select("*")`, so the JSONB blob is already in
+memory. Nothing there changes.
+
+---
+
+## Task 25: Move the builder from a catalog singleton to a per-company catalog hook
+
+**Depends on:** Task 20
+**Files:**
+- Modify: `apps/erp/app/hooks/useCustomFieldsSchema.tsx` — surface `active`
+- Modify: `apps/erp/app/modules/workflows/ui/Builder/catalog.ts` — replace the singleton
+- Modify: the seven files that import the `catalog` value (list below)
+
+**Risk being managed:** `catalog.ts` currently exports a module-level singleton. Deleting that
+export makes every missed call site a COMPILE ERROR rather than a silently field-less picker —
+that is deliberate; do not keep a compatibility export.
+
+**Steps:**
+
+1. `apps/erp/app/hooks/useCustomFieldsSchema.tsx` — the `customFieldTables` view already emits
+ `active` in its `fields` JSON, but `fieldValidator` omits it and zod strips unknown keys.
+ Add it so the overlay can filter:
+ ```ts
+ active: z.boolean().nullish().transform((v) => v ?? true),
+ ```
+ placed alphabetically in the object. Nothing else in that file changes; every existing
+ consumer only gains a key.
+2. Rewrite `ui/Builder/catalog.ts`. Delete `export const catalog = createWorkflowCatalog();`
+ and add:
+ ```ts
+ /** The company's catalog: shipped entries plus this company's custom fields (D-2).
+ * There is deliberately no module singleton — a call site that forgets the hook is a
+ * compile error, not a picker that quietly lists no custom fields. */
+ export function useWorkflowCatalog(): WorkflowCatalog {
+ const schemas = useCustomFieldsSchema();
+ return useMemo(() => {
+ const defs = Object.entries(schemas).flatMap(([table, fields]) =>
+ (fields ?? []).map((field) => ({
+ table,
+ id: field.id,
+ name: field.name,
+ dataTypeId: field.dataTypeId,
+ listOptions: field.listOptions,
+ active: field.active
+ }))
+ );
+ return createWorkflowCatalog(buildCatalogOverlay(defs));
+ }, [schemas]);
+ }
+ ```
+ importing `buildCatalogOverlay`, `createWorkflowCatalog` and the `WorkflowCatalog` type from
+ `@carbon/workflows`, `useCustomFieldsSchema` from `~/hooks`, and `useMemo` from `react`.
+ Keep `useWorkflowLabel`, `workflowFieldHelp` and the `./labelKeys` re-exports exactly as they
+ are.
+3. Update the seven files that import the `catalog` VALUE, replacing
+ `import { catalog } from "../catalog"` (path varies) with the hook and a
+ `const catalog = useWorkflowCatalog();` at the top of the component or hook body:
+ - `ui/Builder/LiveValidation.tsx`
+ - `ui/Builder/useDefinition.ts`
+ - `ui/Builder/config/ClauseRow.tsx`
+ - `ui/Builder/config/forms/ActionForm.tsx`
+ - `ui/Builder/config/forms/EntityForm.tsx`
+ - `ui/Builder/fields/useVariableMenuData.ts`
+ - `ui/Builder/TestRun/TestRunDialog.tsx`
+ All seven are React components or hooks, so the hook is legal in each. Where `catalog` is
+ read inside a `useMemo`, add it to that memo's dependency array. The other nine importers
+ take only `useWorkflowLabel` / label-key helpers and need no change.
+4. `ClauseRow.tsx`'s `columnOptions` memo currently labels a column with
+ `label(propertyLabelKey(entity, col), col)`. Change the fallback so a custom field shows the
+ customer's own name rather than the raw id:
+ ```ts
+ label(propertyLabelKey(entity, col), catalog.getPropertyLabel(entity, col) ?? col)
+ ```
+ and add `catalog` to that memo's deps. Do the same wherever `ActionForm.tsx` labels an
+ action input, using `catalog.getInputLabel(actionId, name) ?? name` as the fallback.
+ Custom field names are customer data and are deliberately never translated.
+5. Verify nothing still reaches for the deleted singleton:
+ ```bash
+ grep -rn "from \"[./]*catalog\"" apps/erp/app/modules/workflows | grep -w catalog
+ # Expected: no hit importing a bare `catalog` binding
+ ```
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=erp
+# Expected: no errors. If TS2589 ("Type instantiation is excessively deep") appears in an
+# unrelated file, that is the known erp instantiation-budget problem (.ai/lessons.md) —
+# re-run with `pnpm --filter erp exec tsgo --noEmit` to bypass a stale turbo cache before
+# treating it as real.
+pnpm --filter erp exec vitest run app/modules/workflows
+# Expected: existing workflow tests pass
+```
+
+**Out of scope:** the nine files that import only `useWorkflowLabel` or the label-key helpers.
+
+---
+
+## Task 26: Offer custom-field triggers in the event picker
+
+**Depends on:** Task 25
+**Files:**
+- Modify: `apps/erp/app/modules/workflows/ui/Builder/config/forms/TriggerForm.tsx`
+
+**Steps:**
+
+1. `TriggerForm.tsx`'s event grouping memo (~lines 374-393) currently splits
+ `Object.keys(WORKFLOW_EVENTS)` by `id.split(".")[0]`. Extend it to append this company's
+ custom-field event ids per entity, from the catalog hook added in Task 25:
+ ```tsx
+ const catalog = useWorkflowCatalog();
+ const customFields = useCustomFieldsSchema();
+ ```
+ Build the extra ids with `customFieldEventId(entity, field.id)` from `@carbon/workflows`,
+ keeping only those for which `catalog.getEvent(id) !== undefined` — that single call
+ enforces the `item` exclusion and the reference-only-entity rule in one place, so the rule
+ never gets restated here.
+2. Append the custom-field ids AFTER the generated ones within each entity group, so the
+ shipped triggers stay at the top of a familiar list.
+3. In the `CommandItem` for a custom-field event, render the field's own name as the label
+ (`catalog.getPropertyLabel(entity, "customFields." + fieldId)`) plus a muted "Custom field"
+ qualifier, so a custom field called `Priority` is distinguishable from a shipped column of
+ the same name. Copy the existing item's markup; do not invent a new row shape.
+4. Items are excluded (D-7). When the user picks the Item group and it has custom fields
+ defined in the ERP that are not offered here, say so plainly rather than showing nothing
+ unusual — add a single muted line under the Item group:
+ `<Trans>Custom fields are not available for items yet.</Trans>`. Render it only for the
+ `item` group.
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=erp
+# Expected: no errors
+pnpm exec biome check apps/erp/app/modules/workflows/ui/Builder/config/forms/TriggerForm.tsx
+# Expected: no error-severity findings
+```
+Criteria 1 and 12 are checked by hand in Task 29.
+
+**Out of scope:** the condition/filter/lookup pickers — they read `catalog.getEntity().properties`
+and pick up the overlay automatically once Task 25 lands.
+
+---
+
+## Task 27: Extend the trigger-event drift invariant
+
+**Depends on:** Tasks 19, 20
+**Files:**
+- Modify: `packages/checks/src/invariants/workflow-trigger-event-drift.sql`
+- Modify: `packages/checks/src/scripts/check-workflow-events.ts`
+
+**Steps:**
+
+1. `check-workflow-events.ts` filters on `catalog.getEvent(row.eventId) === undefined`. After
+ Task 20 that already accepts a well-formed custom-field id, which is a *pattern* check, not
+ an existence check. Strengthen it: for a row whose id matches the custom-field pattern, also
+ require that a `customField` row with that id exists for that company and that its `table`
+ matches the entity. Add to the SQL query a `LEFT JOIN` is not possible (the id is embedded
+ in a string), so do it in a second query:
+ ```ts
+ const { rows: fields } = await client.query<{ id: string; table: string; companyId: string }>(
+ `SELECT "id", "table", "companyId" FROM "customField"`
+ );
+ const known = new Set(fields.map((f) => `${f.companyId}:${f.table}:${f.id}`));
+ ```
+ then, for each subscription whose id parses as a custom-field event, resolve the entity's
+ table via `REGISTRY_ENTRIES` and check membership. Report a distinct message:
+ `subscribes to custom field "<id>", which no longer exists in this company` — that catches a
+ trigger left behind after a custom field is deleted, which a bare pattern allow would not
+ (criterion 11).
+2. Leave `workflow-trigger-event-drift.sql` alone unless it hard-codes a list of known event
+ ids. Read it first: it compares `workflowTriggerEvent` rows against the ids on the active
+ version's trigger nodes and never consults the catalog, so a custom-field id flows through
+ it correctly with no change. If that reading is wrong, STOP and report.
+3. Note in a comment at the top of `check-workflow-events.ts` that neither check runs in CI
+ (no job has DB credentials, per `packages/checks/AGENTS.md`) — they are operator tools.
+
+**Verify:**
+```bash
+pnpm --filter @carbon/checks typecheck
+# Expected: no errors
+pnpm --filter @carbon/checks test
+# Expected: all tests pass
+```
+Running the check itself needs a live database:
+```bash
+DATABASE_URL=<local> pnpm --filter @carbon/checks workflow-events
+# Expected: "PASS workflow-events (N subscription(s) all resolve)"
+```
+Skip that command if the database is not running; do not start or rebuild it.
+
+**Out of scope:** automatically cleaning up an orphaned `workflowTriggerEvent` row. The check
+surfaces it; deleting it is deliberately not in scope.
+
+---
+
+## Task 28: Sync AGENTS.md and rules
+
+**Depends on:** Tasks 1–27
+**Files:**
+- Modify: `apps/erp/app/modules/workflows/AGENTS.md`
+- Modify: `packages/workflows/AGENTS.md`
+- Modify: `packages/jobs/AGENTS.md`
+- Modify: `.claude/rules/workflow-event-catalog.md`
+- Modify: `.claude/rules/workflow-engine.md`
+- Modify: `.claude/rules/workflow-matcher.md`
+- Modify: `.claude/rules/workflow-actions.md`
+- Modify: `.ai/specs/2026-08-19-workflow-improvements-round-2.md` — changelog + status
+- Modify: `.ai/plans/automation/pending-changes.md` — mark round 2 done
+
+**Steps:**
+
+1. `apps/erp/app/modules/workflows/AGENTS.md`:
+ - Line 55's file list is already fixed by Task 9. Confirm it now names
+ `WorkflowLockAlert.tsx`, `WorkflowActiveSwitch.tsx` and `WorkflowsUpgradeOverlay.tsx`.
+ - Line ~11 (the canvas-state paragraph) and line ~69 (the lock paragraph) must both mention
+ the new `$id.positions.tsx` route, `updateWorkflowNodePositions`, and that it is
+ deliberately NOT gated by `checkWorkflowVersionLock`.
+ - Add the `shouldRevalidate` exclusion for `/positions`.
+ - Document the store's two flags (`canChangeDefinition` vs `canMoveNodes`) and that
+ movement follows permission, not the lock.
+2. `packages/workflows/AGENTS.md` — document `custom-fields.ts`: the overlay, the one-segment
+ `customFields.<id>` path, the DataType→ValueType map living in exactly one place, and that
+ `WORKFLOW_EVENTS` stays closed with custom-field ids resolved by `getCatalogEvent`.
+ Also record the new `CatalogInput.linkify` flag and `RuntimeContext.linkFor`.
+3. `packages/jobs/AGENTS.md` — two stale lines to fix while here: it claims `update.ts` "also
+ exports `toPlainValue`" (it lives in `actions/values.ts`), and the same claim appears in
+ `.claude/rules/workflow-actions.md`. Fix both, and add the custom-field merge RPC to the
+ update-action description.
+4. `.claude/rules/workflow-event-catalog.md` — it says "6 reference-only" entities; the code has
+ 7 (it omits `nonConformanceType`). Fix that count, and add the custom-field event id shape.
+5. `.claude/rules/workflow-matcher.md` — record that `computeEventIds` derives custom-field ids
+ from the diff key and stays company-blind.
+6. `.claude/rules/workflow-engine.md` — record the `custom-fields` step and the per-run overlay.
+7. Update the spec's Status from `Draft — awaiting review` to `Implemented`, and append a
+ changelog entry dated the day the work lands noting anything that diverged from the design.
+ If nothing diverged, say so explicitly.
+8. In `.ai/plans/automation/pending-changes.md`, mark the `## 8–15. Round 2 (2026-08-19)` block
+ as done with a pointer to this plan file.
+
+**Verify:**
+```bash
+grep -rn "toPlainValue" packages/jobs/AGENTS.md .claude/rules/workflow-actions.md
+# Expected: no line claiming it is exported from update.ts
+grep -n "WorkflowLockAlert" apps/erp/app/modules/workflows/AGENTS.md
+# Expected: one hit, and the file exists
+```
+
+**Out of scope:** `docs/content/**` (the customer-facing docs site). If the user wants a docs
+page for custom fields in workflows, that is a separate ask — flag it, do not write it.
+
+---
+
+## Task 29: End-to-end verification
+
+**Depends on:** Tasks 1–28
+**Files:** none — this task only runs commands and exercises the UI.
+
+**Steps:**
+
+1. Full static gate, scoped (a whole-repo `turbo run typecheck` OOMs — never run it):
+ ```bash
+ pnpm exec turbo run typecheck --filter=@carbon/workflows
+ pnpm exec turbo run typecheck --filter=@carbon/jobs
+ pnpm exec turbo run typecheck --filter=@carbon/notifications
+ pnpm exec turbo run typecheck --filter=@carbon/documents
+ pnpm exec turbo run typecheck --filter=@carbon/react
+ pnpm exec turbo run typecheck --filter=@carbon/checks
+ pnpm exec turbo run typecheck --filter=erp
+ # Expected: no errors anywhere
+ ```
+2. Tests and the catalog gates:
+ ```bash
+ pnpm --filter @carbon/workflows test
+ pnpm --filter @carbon/jobs test
+ pnpm --filter @carbon/notifications test
+ pnpm --filter erp exec vitest run app/modules/workflows
+ pnpm run check:workflow-catalog
+ # Expected: all pass; check-workflow-catalog exits 0
+ ```
+3. Lint — its own CI gate. Fix only error-severity findings; leave the pre-existing warnings:
+ ```bash
+ pnpm exec biome check
+ # Expected: zero errors (warnings unchanged from the branch baseline)
+ ```
+4. Ask the user before browser work, then walk the 30 acceptance criteria in the spec's §7.
+ The ones no command can prove:
+ - **1, 12** — a Text custom field on Sales Order appears in the trigger picker labelled as a
+ custom field; the Item group says custom fields are not available yet.
+ - **2, 3** — publish it, then check `workflowTriggerEvent` and `eventSystemSubscription`
+ rows, edit the field on a sales order and confirm exactly one `workflowRun`; edit an
+ unrelated column and confirm none.
+ - **4, 5, 6** — a condition on the field evaluates correctly and the step's `detail` records
+ the clause; a List field offers exactly its options; a Numeric field compares with `>`.
+ - **7, 8, 9, 10** — the field prints in a message; an Update action setting it leaves the
+ other keys in the blob intact (read the row before and after); an out-of-range List value
+ fails the step and writes nothing; company B's fields are invisible in company A.
+ - **11** — deactivate the field: it leaves the pickers, the published workflow still parses,
+ and `pnpm --filter @carbon/checks workflow-events` reports it.
+ - **13, 14, 15, 16, 17** — the variable menu offers the whole Sales Order record; the in-app
+ bell shows subject AND body with a working link (including the company switch); the email
+ shows the same; `[click](javascript:alert(1))` renders as literal text with no anchor; the
+ same record in a webhook body renders as a bare readable id with no markdown.
+ - **18, 19, 20** — on a live version the trigger's Schedule button does nothing and is
+ visibly disabled and a reload shows it unchanged; every input in all six node types is
+ disabled; the banner appears with a "New version" button, and a user without
+ `workflows_update` sees the other copy with no button.
+ - **21, 22, 25** — drag a node and reload; run auto-arrange and reload; branch a new version
+ and confirm the tidied positions carried over.
+ - **23, 24** — hand-craft a POST to `/x/workflow/$id/positions` carrying a changed `data`
+ payload and a new node id: only existing nodes' positions change. A POST to
+ `/x/workflow/$id/save` on a live version still returns 409.
+ - **26, 27, 28** — the notify action's second recipient field reads "Group" and lists no
+ customer or supplier group while a hand-made company group is still there; the person
+ field lists employees only; a workflow already pointing at a supplier group still runs and
+ still displays that group's name.
+ - **29, 30** — the grid is quieter at 24px in both light and dark themes; connectors are
+ single continuous curves with the marching-ants dashes still running and the disconnect
+ button still on the line.
+ - Regression: open the notification bell and check at least three non-Workflow notification
+ types still render and navigate correctly (Task 18 restructured that row for everyone).
+5. Report results honestly. If a criterion fails, say which one and paste the output — do not
+ mark the plan complete.
+6. Do NOT commit. Stop here and report; the user commits on their own say-so.
+
+**Verify:** the commands above, plus a written pass/fail against each of the 30 criteria.
+
+**Out of scope:** rebuilding the database, deploying, and opening a PR.
diff --git a/.ai/plans/automation/pending-changes.md b/.ai/plans/automation/pending-changes.md
index d0ee88d832..d60a4c0b27 100644
--- a/.ai/plans/automation/pending-changes.md
+++ b/.ai/plans/automation/pending-changes.md
@@ -65,4 +65,17 @@ Currently nodes are colored differently per type. Change to:
---
+## 8–15. Round 2 (2026-08-19)
+
+Custom fields in workflows (trigger + read + write), linking a record inside a message,
+strict read-only on the live version with node rearranging still allowed, "Role" → "Group"
+limited to employee groups, minimal grid, curved edges.
+
+Designed in `.ai/specs/2026-08-19-workflow-improvements-round-2.md`
+(research: `.ai/research/2026-08-19-workflow-improvements-round-2.md`).
+**Implemented** — plan and per-task record in
+`.ai/plans/2026-08-19-workflow-improvements-round-2.md`.
+
+---
+
<!-- Add more changes below as the user describes them -->
diff --git a/.ai/research/2026-08-19-workflow-improvements-round-2.md b/.ai/research/2026-08-19-workflow-improvements-round-2.md
new file mode 100644
index 0000000000..b09c552c5b
--- /dev/null
+++ b/.ai/research/2026-08-19-workflow-improvements-round-2.md
@@ -0,0 +1,376 @@
+# Research — Workflow improvements (round 2)
+
+Codebase research backing `.ai/specs/2026-08-19-workflow-improvements-round-2.md`.
+Grounded against the branch `feat/workflow-improvements` as of 2026-08-19. No external
+research: every item is internal/mechanical to Carbon's own workflow subsystem, with one
+in-repo precedent (storage rules) noted below.
+
+---
+
+## 1. Custom fields in triggers
+
+### How the catalog produces an entity's field list
+
+- Hand-written inputs: `packages/workflows/src/catalog/{entities,moments,actions,operations}.ts`
+- Generator: `scripts/generate-workflow-catalog.ts` → `packages/workflows/src/catalog/build.ts`
+ (`buildCatalog`, pure) → committed `events.generated.ts` / `actions.generated.ts` /
+ `labels.generated.ts`.
+- Field lists come from `packages/database/src/swagger-docs-schema.ts`, injected as an
+ argument. `entityProperties` at `build.ts:436-450`.
+- **The hard gate:** `build.ts:122-129`
+ ```ts
+ const DROPPED_COLUMNS = new Set(["companyId","customFields","embedding","updatedAt","updatedBy"]);
+ ```
+ Asserted by `catalog.test.ts:181` and `build.test.ts:328`. A watched/writable column
+ inside `DROPPED_COLUMNS` is a hard build error (`build.ts:272-276`, `303-307`).
+- Runtime facade: `catalog/catalog.ts` `createWorkflowCatalog()`. The builder holds a
+ **module-level singleton**: `apps/erp/app/modules/workflows/ui/Builder/catalog.ts:8`.
+- Picker gates: `ui/Builder/config/ClauseRow.tsx:105-129` (condition/filter/lookup rows) and
+ `ui/Builder/fields/variableMenu.ts` (`expand()`, `MAX_PATH = 2`).
+- Resolver gate: `packages/workflows/src/runtime/resolve.ts:134-137` —
+ `entity.properties[segment] === undefined` → `A ${entity} has no "${segment}"`.
+
+### How Carbon's custom fields work
+
+- `customFieldTable` (global catalog of eligible tables) and `customField` (per-company
+ definitions) — `packages/database/supabase/migrations/20240311021818_custom-fields.sql`.
+ `customField` columns: `id`, `name`, `sortOrder`, `table`, `dataTypeId`, `listOptions TEXT[]`,
+ `active`, `companyId`, `required` (`20260505120000_custom-field-required.sql`), `tags`.
+ Unique `(table, name, companyId)`.
+- View `customFieldTables` — one row per (table × company) with a `fields` JSON array.
+- Values: one `customFields JSONB` column per core table; **keys inside the blob are
+ customField ids**, not names. `setCustomFields`/`getCustomFields` at
+ `apps/erp/app/utils/form.ts:9-60`; rendering `apps/erp/app/components/Form/CustomFormFields.tsx`.
+- Definitions reach the client once per session: `apps/erp/app/routes/x+/_layout.tsx:177`
+ → `getCustomFieldsSchemas` (`modules/shared/shared.server.ts:54`, Redis-cached) → loader key
+ `customFields` → `apps/erp/app/hooks/useCustomFieldsSchema.tsx`.
+- `DataType` enum (`apps/erp/app/modules/shared/types.ts:85-95`): Boolean=1, Date=2, List=3,
+ Numeric=4, Text=5, User=6, Customer=7, Supplier=8, File=9.
+
+### What already works with no change
+
+- **Reads.** `packages/jobs/src/workflows/engine/loader.ts:39` is `select("*")`, and trigger
+ payload rows come straight off the event queue — the JSONB blob is *already in memory*.
+ Only the catalog and the resolver refuse it.
+- **The matcher.** `computeNestedDiff` (`packages/jobs/src/inngest/functions/events/diff.ts:157-190`)
+ already emits keys like `customFields.<fieldId>`, and `computeEventIds`
+ (`packages/jobs/src/workflows/event-ids.ts:53-56`) matches `field in diff`. So
+ `match: { table, operation: "UPDATE", field: "customFields.<id>" }` would fire today with
+ **no matcher change**.
+ Caveat: because objects are diffed nested, the bare key `customFields` never appears — a
+ watch on the whole column would never match.
+
+### What blocks it
+
+1. The catalog is **build-time and global**; custom fields are **runtime and per-company**.
+ They cannot be generated into `events.generated.ts`.
+2. `WORKFLOW_EVENTS` is a static committed record consulted by `deriveWorkflowSubscriptions`
+ (`packages/workflows/src/sync.ts:53`), `event-ids.ts`'s module-level `INDEX`, and the
+ `workflow-trigger-event-drift` deploy check in `packages/checks` — all four assume a
+ **closed, committed event id set**.
+3. Labels: `WORKFLOW_LABELS` is a static generated `msg` table keyed `entity.<name>.<column>`.
+ A per-company field has no key; `useWorkflowLabel(key, fallback)`'s fallback would have to
+ carry the customField `name`.
+4. Values are untyped JSON. `fromColumn` (`packages/workflows/src/runtime/values.ts`) coerces
+ by the catalog's declared `ValueType`, so a `DataType → ValueType` map is needed
+ (List → string + `choices` from `listOptions`; User/Customer/Supplier → `t.entity(...)`).
+5. **Entity mismatch:** 9 of the 10 triggerable entities are in `customFieldTable`
+ (purchaseOrder, salesOrder, job, receipt, shipment, quote, supplier, customer,
+ nonConformance). `item` is **not** — the catalog registers `table: "item"`
+ (`entities.ts:125`) while custom fields attach to the subtypes `part`, `material`, `tool`,
+ `consumable`, `fixture`.
+
+### In-repo precedent
+
+Storage rules (the other feature sharing `Operator` from `@carbon/utils`) already support
+custom fields via a dynamic path escape hatch: `packages/utils/src/field-registry.ts:318-334`
+(`getFieldDef` synthesizes a `FieldDef` for any `item.customFields.*` path), generic dotted
+resolver `packages/utils/src/storage-rules.ts:178-190`. Their picker
+(`FieldCombobox.tsx`) does **not** enumerate per-company fields — the user types the path — so
+it is a data-model precedent, not a UX one.
+
+---
+
+## 2. Linking a SO/PO in a message
+
+### There is no "message node"
+
+Messaging is the `notify` **action** inside the generic `action` node. Declared at
+`packages/workflows/src/catalog/actions.ts:140-172`:
+
+| Input | Type | Notes |
+|---|---|---|
+| `user` | `entity("user")` | optional |
+| `role` | `entity("group")` | optional; `requireOneOf: [["user","role"]]` |
+| `subject` | `string` **required**, `template: true` | |
+| `message` | `string` optional, `template: true` | the body |
+| `aboutId` | `string` optional | linked record's id |
+| `aboutType` | `string` optional | catalog entity name |
+
+`aboutId`/`aboutType` already have a hand-written field: `NotifyAboutField` in
+`ActionForm.tsx:186-249` (its own comment says "The only hand-written field… Not a pattern.").
+
+### Templates are structured, not `{{ }}`
+
+Typing `{` opens a menu (`fields/InlineValueEditor.tsx:22`); what is stored is a structured
+part `{kind:"text"|"ref"|"item"}` (`definition/types.ts:139-153`). Editor is Tiptap:
+`packages/react/src/VariableText/VariableText.tsx` + `VariableChip.tsx` — text + chips only.
+Chip encoding: `fields/tokenId.ts`. Editor↔value: `fields/valueParts.ts`.
+
+Resolver: `packages/workflows/src/runtime/resolve.ts` — `resolveValue:17`, `renderTemplate:43`
+(any unresolvable part fails the whole template), `renderValue:29` (an entity prints
+`row.readableId ?? row.name ?? id`).
+
+**Nothing renders as a URL today.** And `rendersAsText` (`definition/types.ts:82`) returns
+**false** for `entity` / `list<entity>`, enforced in the validator's `checkTemplateParts`
+(`definition/validate.ts`, `TYPE_MISMATCH`) and the builder's `textOnly` filter
+(`variableMenu.ts:99`, `:161`) — so today a customer cannot even drop a whole record into a
+message; only its scalar properties.
+
+### How Carbon deep-links a record
+
+- `apps/erp/app/utils/entity.ts` — `RECORD_ROUTES:14` keyed by **workflow catalog entity name**
+ (`salesOrder`, `purchaseOrder`, `job`, `quote`, `nonConformance`→`path.to.issue`, …);
+ `getRecordPath(entity, id):61`; `getEntityPath(entityId):71` from an id prefix
+ (`ENTITY_BY_ID_PREFIX:38` — `so`→salesOrder, `po`→purchaseOrder).
+- Absolute links for email/Slack: `buildNotificationLink(event, documentId, companyId, documentType)`
+ → `${ERP_URL}/api/link?event=…&documentId=…&companyId=…&documentType=…`
+ (`packages/jobs/src/inngest/functions/notifications/content.ts:19-27`). Resolver route
+ `apps/erp/app/routes/api+/link.ts`; the `NotificationEvent.Workflow` case (`:83`) calls
+ `getRecordPath(documentType, documentId)`. `/api/link` also performs the **company switch**
+ before redirecting.
+
+### Delivery
+
+`packages/jobs/src/workflows/actions/notify.ts` → `trigger("notify", …)` with
+`event: NotificationEvent.Workflow`, `title: subject`, `body: message`,
+`documentId: aboutId ?? runId`, `documentType: aboutType`.
+Destinations (`inngest/functions/notifications/notify.ts:188`): **InApp + Email** (no Slack).
+`content.ts:1188`: `description = title`, and the **body becomes a single detail row**
+`[{ label: "Message", value: body }]` (`NotificationDetail {label, value}`,
+`packages/notifications/src/index.ts:90`).
+
+**Known gap:** `details` is stored on `notification.payload`
+(`inngest/functions/notifications/notify.ts:501`) but is **never rendered in the ERP topbar**
+(`apps/erp/app/components/Layout/Topbar/Notifications.tsx`, Workflow case `:423-430`). Today
+the workflow message body is invisible in-app; only the subject shows. The whole row is one
+`<Link>`, so a nested anchor needs care.
+
+Email renders details as label/value rows: `packages/documents/src/email/NotificationEmail.tsx:269-310`,
+single CTA button `ctaUrl`.
+
+### The entity RuntimeValue is a complete link spec
+
+`packages/workflows/src/runtime/types.ts:21`:
+`{ kind: "entity"; of: string; id: string; row?: Record<string, unknown> }`.
+`of` is exactly the catalog entity name — the same key `RECORD_ROUTES` uses and the same value
+`aboutType` carries.
+
+**Constraint:** `packages/workflows` has four runtime deps only (`zod`, `@carbon/utils`,
+`@lingui/core`, `@internationalized/date`), targets browser + ES2019, and cannot import
+`~/utils/path` or `@carbon/env`. URL construction therefore belongs job-side in
+`packages/jobs/src/workflows/actions/notify.ts` (which may import `ERP_URL`), never in
+`runtime/resolve.ts`.
+
+---
+
+## 3. Version locking
+
+### There is no status enum — "live" is a pointer comparison
+
+`workflowVersion` has **no status column** (`20260810100100_workflows-foundation.sql:55`).
+`workflow.activeVersionId` (`:39`) is the pointer; `workflow.active` is a boolean kill switch;
+`workflow.canvasState` (`:41`) is viewport JSONB, **per workflow, not per version**.
+
+`getWorkflowLockFlags({versionId, activeVersionId})` →
+`{isLive, isVersionLocked}`, both just `versionId === activeVersionId`
+(`apps/erp/app/modules/workflows/workflows.server.ts:25-34`).
+`LOCKED_VERSION_MESSAGE` at `:22`.
+Publishing: `publishWorkflowVersion` `:99-152` (validate → set `activeVersionId` → `syncAndWake`).
+
+### How read-only propagates
+
+Computed in `apps/erp/app/routes/x+/workflow+/$id.tsx:144` (loader) and `:162`
+(`isLiveVersion || !permissions.can("update","workflows")`), passed to the provider at
+`:183-189` with `key={versionId:isReadOnly:isOwner}` so it is immutable per mount.
+Store field `ui/Builder/store.ts:54,114,125`; context `ui/Builder/context.tsx:44`.
+
+Guarded today: `onNodesChange` (`store.ts:133`), `onEdgesChange` (`:156`), `onConnect` (`:162`),
+`addNode` (`:183`), `arrangeNodes` (`:295`), `setNodePositions` (`:301`);
+`WorkflowBuilder.tsx` drop (`:82,92`), palette (`:114,125`),
+`nodesDraggable={false}`/`nodesConnectable={false}` (`:155-156`), `deleteKeyCode={null}` (`:160`);
+`BuilderControls.tsx:67,93`; `WorkflowNodeCard.tsx:66,175,179,191`;
+`edges/WorkflowEdge.tsx:28,63`; `config/InlineNodeName.tsx:9,50`;
+`Autosave.tsx:26,29` (autosave off entirely); `BuilderHeader.tsx:139,175-190` (lock icon).
+
+### The bug — the entire node-config layer is ungated
+
+`store.ts` `updateNodeData` (`:260-265`) has **no `isReadOnly` guard**, and
+`WorkflowNodeCard.tsx:123,226-230` renders the config form unconditionally. No form reads
+`isReadOnly`. So on a live version these are all interactive:
+
+- **Trigger mode Event↔Schedule** — `config/forms/TriggerForm.tsx:430-455`, plain buttons
+ calling `updateNodeData` (`:397`, `:405`). Also ungated: event picker (`:413-415,465-471`),
+ origin ToggleGroup (`:479-505`), whole `ScheduleEditor` (`:192-357` → `patchSchedule:418-421`).
+- `ActionForm.tsx:315,339,348`; `ConditionForm.tsx:133` (and `:124` `onEdgesChange`, which *is*
+ guarded — so a path delete desyncs data from edges); `FilterForm.tsx:68,75,79,85,91,176,196`;
+ `EntityForm.tsx:146,156`; `LookupForm.tsx:79,83,92,99,105`.
+- Also ungated in the store: `renameNode` (`:267`), `setNodeExpanded` (`:280`),
+ `setAllNodesExpanded` (`:287`), `removeNode` (`:310`). `BuilderControls.tsx`
+ expand/collapse-all is **not** disabled and `expanded` is part of the persisted definition.
+
+Net effect: the user changes the trigger to Schedule, the canvas shows it, nothing persists
+(autosave is off), and there is **no feedback** — the edit silently evaporates on reload.
+
+Deliberately allowed on a live version: workflow **rename** (name lives on `workflow`, not the
+version — `BuilderHeader.tsx:54-55`), **test run** (`WorkflowNodeCard.tsx:149-172`), and
+**viewport persistence** (`canPersistCanvasState`, `$id.canvas.tsx:14-15`).
+
+### Positions are part of the versioned definition
+
+`definition/schema.ts:36` — `position: {x, y}` on the node schema (`expanded` rides along too).
+Serialized by `ui/Builder/graph.ts:49-74` (`fromReactFlow`, `:62`), read back by
+`toBuilderNode:21-29`. Persisted by **autosave only** (`Autosave.tsx:28-54`, 1s debounce,
+diffs `JSON.stringify(fromReactFlow(...))` vs `state.baseline`) → POST `path.to.workflowSave`
+→ `routes/x+/workflow+/$id.save.tsx` → `updateWorkflowDefinition`
+(`workflows.service.ts:163`, the only caller).
+
+So a node move on a live version is a write to the live version's `nodes` JSONB. Allowing
+drag cannot be done by flipping `nodesDraggable` alone.
+
+### Server-side guard — exactly one route
+
+`checkWorkflowVersionLock` (`workflows.server.ts:41-61`) → `getWorkflowVersionOwnership`
+(`workflows.service.ts:410-421`); deliberately "unresolvable ⇒ unlocked" (`:46-49`).
+Only caller: `routes/x+/workflow+/$id.save.tsx:52-56` → `409`. Since `/save` is the only
+writer of `nodes`/`edges`, the definition is genuinely protected server-side.
+No DB-level guard: RLS on `workflowVersion` (migration `:238-259`) is the standard company +
+permission-claim policy set; no CHECK, no trigger.
+Client feedback on refusal: `Autosave.tsx:56-69` `toast.error` — but autosave never fires in
+read-only mode, so today a blocked edit produces no toast.
+
+### The prominent affordance that was specced but never built
+
+- Today: a 14px `LuLock` + tooltip (`BuilderHeader.tsx:175-190`) and a green `Live` badge shown
+ **only inside the version dropdown** (`ui/Builder/WorkflowVersionStatus.tsx`).
+- `.ai/specs/implemented/2026-07-31-workflows-builder-canvas.md:15-17,73,293-299,397,530`
+ specifies a `WorkflowLockAlert.tsx` that **was never built**.
+ `apps/erp/app/modules/workflows/AGENTS.md` also lists `ui/WorkflowLockAlert.tsx` — **stale doc**.
+- House pattern to copy: `apps/erp/app/modules/items/ui/Item/ReleaseLockAlert.tsx`
+ (`Alert variant="warning"` + `LuTriangleAlert`; also exports `getReleaseLockFlags`, which
+ `getWorkflowLockFlags` mirrors). Primitives: `packages/react/src/Alert.tsx`, `Badge.tsx`.
+- Mount points: between `<BuilderHeader>` and the canvas in `x+/workflow+/$id.tsx:191-197`,
+ and/or a React Flow `<Panel position="top-center">` (idiom in `BuilderControls.tsx`).
+
+---
+
+## 4. "Role" → "Group", employee groups only
+
+### The field is already a group entity
+
+`packages/workflows/src/catalog/actions.ts:145` —
+`role: { type: t.entity("group"), required: false, label: "role" }` on the `notify` action,
+alongside `user: t.entity("user")` (`:144`), `requireOneOf: [["user","role"]]` (`:174`).
+Generated mirror `actions.generated.ts:134,151`; label
+`labels.generated.ts:39` → `"action.notify.input.role": msg\`Role\``.
+Rendered by `ActionForm.tsx:359` and the `requireOneOf` block `:454-473`.
+Control: `LiteralControl.tsx:177` → `RECORD_PICKERS.group` → `GroupPicker` at
+`ui/Builder/fields/recordPickers.tsx:145-153` (registry `:174`).
+
+**Not** the `role` enum (`'customer'|'employee'|'supplier'` on `userToCompany`). The hardcoded
+`["Buyer","Manager","Admin"]` list is a **test fixture** (`definition/catalog.ts:191-196`).
+
+Stored shape: `{kind:"literal", type:{kind:"entity", of:"group"}, value:"<group.id>"}` under
+`node.data.inputs.role`. At runtime `packages/jobs/src/workflows/actions/notify.ts:8-32`
+merges `inputs.user` and `inputs.role` into one `groupIds` array (every user has an identity
+group whose id == their user id).
+
+### The groups model
+
+**One `group` table**, no type enum — five booleans (`packages/database/src/types.ts:15869-15906`):
+`isEmployeeTypeGroup`, `isCustomerTypeGroup`, `isCustomerOrgGroup`, `isSupplierTypeGroup`,
+`isSupplierOrgGroup`, plus `isIdentityGroup` (per-user singleton, always excluded from pickers).
+
+"Employee" is defined **negatively** —
+`packages/database/supabase/migrations/20260714045245_user-select-rpcs.sql:53-60`:
+```
+WHEN p_type = 'employee' THEN NOT (isCustomerOrgGroup OR isCustomerTypeGroup
+ OR isSupplierOrgGroup OR isSupplierTypeGroup)
+```
+
+Listing: `getUserSelectGroups` (`apps/erp/app/modules/users/users.service.ts:418`) wraps RPC
+`get_user_select_groups(p_company_id, p_type, p_search, p_limit, p_offset)`.
+Precedents: `routes/x+/settings+/approval-rules.tsx:33-34` (employee-only),
+`routes/x+/sales+/price-list.tsx:35-38` (customer-only).
+
+### The picker already supports the filter
+
+There is no `Form/Group.tsx`; the group picker is `UserSelect`
+(`apps/erp/app/components/Selectors/UserSelect/`), whose props include
+`type?: "employee" | "supplier" | "customer"` (`types.ts:59`) →
+`useUserSelect.ts:130,141-142` → `path.to.api.userSelectGroups(type, …)` → the RPC's `p_type`.
+
+**The gap:** `GroupPicker` (`recordPickers.tsx:145-153`) passes **no `type`**, so `p_type` is
+NULL → the RPC's `ELSE TRUE` returns **every** non-identity group, including customer and
+supplier ones. The sibling `UserPicker` (`:132-141`) passes `usersOnly` but also no `type`, so
+the person picker has the same leak.
+
+### Migration cost
+
+- **Relabel + filter only: zero data migration.** Change `label: "role"` → `"group"` at
+ `actions.ts:145`, run `pnpm generate:workflow-catalog`, then `pnpm lingui:extract`.
+ Stored key stays `inputs.role`; the value is already a group id.
+ Existing definitions pointing at a customer/supplier group keep working (`validate.ts` checks
+ only the type, not the flags) — they just can't be re-picked.
+- **Renaming the input key `role` → `group` requires a v4 format migration.**
+ `CURRENT_DEFINITION_FORMAT_VERSION = 3` (`definition/schema.ts:11`); migrator
+ `migrateDefinition(raw, from)` (`definition/normalize.ts:48-93`; v1→v2 lookup match rules,
+ v2→v3 `title`→`name`), driven by `readWorkflowVersion` (`:103+`). Also in scope:
+ `requireOneOf` (`actions.ts:174`), `notify.ts:28`, `notify.test.ts:57`.
+
+---
+
+## 5. Canvas visuals
+
+- **`@xyflow/react` 12.10.2** (React Flow v12) — `apps/erp/package.json:70`.
+- Canvas: `ui/Builder/WorkflowBuilder.tsx`, `<ReactFlow>` at `:136-171`.
+ `minZoom={0.25} maxZoom={2}` (`:148-149`), `onlyRenderVisibleElements` (`:161`),
+ `defaultEdgeOptions={{type:"workflow"}}` (`:162`), `proOptions={{hideAttribution:true}}` (`:147`).
+ Layout is left→right dagre (`layout.ts:43`, `rankdir:"LR"`); handles `Position.Left`
+ (`NodeCard.tsx:116`) / `Position.Right` (`OutputHandle.tsx:120`).
+- **Grid:** `WorkflowBuilder.tsx:166` —
+ `<Background variant={BackgroundVariant.Dots} gap={16} />`. `size` and `color` are **not**
+ set, so xyflow defaults apply (`size=1`, CSS var `--xy-background-pattern-dots-color`).
+ Knobs: `BackgroundVariant.Lines`/`Cross`, larger `gap`, smaller `size`, a muted `color`, or a
+ second `<Background id>` layer for major/minor grid.
+- **Edge:** one custom component, `ui/Builder/edges/WorkflowEdge.tsx`
+ (`edgeTypes = { workflow: WorkflowEdge }` at `:101`).
+ - Geometry `:40-48` — `getSmoothStepPath({..., borderRadius: 12})` (orthogonal with rounded
+ corners, **not** a bezier). "Smoother" = raise `borderRadius`, or swap to `getBezierPath`
+ / `getSimpleBezierPath` — one import + one call site.
+ - Stroke `:52-62`, inline on a hand-rolled `<path>` (no `<BaseEdge>`, no `style` prop):
+ `stroke="hsl(var(--primary))"`, `strokeWidth={highlighted ? 2.5 : 1.75}`,
+ `strokeLinecap="round"`, `strokeDasharray="8 4"`, `strokeOpacity` dimming to `0.28`,
+ `className="workflow-edge-animated"` → `edges/workflow-edge.css`
+ (`edge-flow`, `stroke-dashoffset 24 → 0`, 1.2s linear infinite).
+ - `EdgeLabelRenderer` block `:63-94` renders the two-click disconnect button.
+- Stylesheets are **route-level `<link>`s**, not global imports:
+ `routes/x+/workflow+/$id.tsx:14` (`@xyflow/react/dist/style.css?url`), `:32`
+ (`workflow-edge.css?url`), wired via `export const links` at `:42`. There are **no**
+ `.react-flow__*` / `--xy-*` overrides anywhere in the app.
+- Other canvases in the repo (precedent, all separate): `modules/production/ui/Jobs/JobDag.tsx:203`
+ and `apps/mes/app/components/JobDag/JobDag.tsx:218` (`<Background gap={20} size={1} />`);
+ tree views in accounting/settings/people; `inventory/ui/Traceability/TraceabilityGraph.tsx:647`.
+
+---
+
+## Relevant lessons already recorded
+
+`.ai/lessons.md`:
+- "Never hand-measure React Flow handle positions; and never `stopPropagation` inside a node" —
+ use `nodrag`, call `useUpdateNodeInternals` on handle/size change.
+- "A dropdown that lives inside an editor popup must own its keys on the document" —
+ `VariableTreeMenu.tsx`.
+- Workflow definition parsing must go through `migrateDefinition`, never the current schema
+ directly.
+- `packages/workflows` targets ES2019 (no BigInt literals, no `node:crypto`).
diff --git a/.ai/specs/2026-08-19-workflow-improvements-round-2.md b/.ai/specs/2026-08-19-workflow-improvements-round-2.md
new file mode 100644
index 0000000000..668bc57ca2
--- /dev/null
+++ b/.ai/specs/2026-08-19-workflow-improvements-round-2.md
@@ -0,0 +1,547 @@
+# Spec — Workflow improvements, round 2
+
+**Status:** Implemented (pending browser verification)
+**Date:** 2026-08-19
+**Branch:** `feat/workflow-improvements`
+**Research:** [`.ai/research/2026-08-19-workflow-improvements-round-2.md`](../research/2026-08-19-workflow-improvements-round-2.md)
+**Prior art:** `.ai/specs/2026-07-30-workflows-{engine,matcher,event-catalog}.md`,
+`.ai/specs/implemented/2026-07-31-workflows-builder-canvas.md`,
+`.ai/plans/automation/pending-changes.md` (items 1–7, shipped)
+
+---
+
+## 1. Summary
+
+Eight customer-raised changes to the Workflows feature, in three groups:
+
+1. **Custom fields become first-class in workflows** — trigger on one changing, read one in
+ conditions/filters/messages, and write one from an Update action.
+2. **A message can link to the record it is about** — dropping a Sales Order or Purchase Order
+ into a notification body produces a clickable link, in email and in the in-app bell.
+3. **The published version is genuinely read-only, and says so** — a prominent banner, every
+ node control visibly disabled, the trigger-mode bug closed, but node *positions* stay
+ editable so a live workflow can still be tidied and read.
+
+Plus three small ones: the notify action's "Role" field becomes "Group" and lists employee
+groups only (the person picker gets the same treatment), the canvas grid becomes quieter, and
+connectors become true curves.
+
+## 2. Problem
+
+- **Custom fields are invisible to workflows.** Every customer models something Carbon does not
+ ship a column for. Today a workflow cannot notice one changing, cannot compare one, cannot
+ print one, and cannot set one — so any rule that depends on customer-specific data is
+ unbuildable. The data is already in memory at run time (`loader.ts` reads `select("*")`) and
+ the matcher already emits `customFields.<id>` diff keys; only the catalog refuses them.
+- **A notification cannot point at its record.** `notify` already carries `aboutId`/`aboutType`
+ so the whole notification row is clickable, but the *body* is plain text with no way to say
+ "…for SO000123" as a link. Worse, the body is never rendered in the in-app bell at all
+ (`notification.payload.details` is written and then dropped by `Notifications.tsx`), so a
+ workflow author writing a message sees it vanish in-app.
+- **The live version is only half locked, and the half that isn't is silent.** `updateNodeData`
+ has no read-only guard, so every node config form is fully interactive on a published version
+ — the reported case is switching the trigger from Event to Schedule. Because autosave is
+ disabled in read-only mode, the change is neither saved nor refused: it silently evaporates on
+ reload, with no toast and no explanation. The only lock signal is a 14px lock glyph.
+- **You cannot tidy a live workflow.** `onNodesChange` drops *all* changes including drags, so a
+ published workflow is frozen in whatever layout it had — unreadable graphs stay unreadable.
+- **The "Role" picker lists customers and suppliers.** `GroupPicker` passes no `type`, so the RPC
+ returns every non-identity group. A workflow can be pointed at a supplier org group by
+ accident. The sibling person picker has the identical leak.
+- Canvas grid and connectors read louder than the content.
+
+## 3. Goals
+
+- Custom fields usable as trigger, as readable value, and as writable value, scoped per company.
+- A record dropped into a message renders as a clickable link in email and in-app.
+- The workflow message body is visible in the in-app bell.
+- No edit of any kind to a published version's behaviour is possible from the UI or by a
+ hand-rolled request; node positions are the single deliberate exception.
+- The read-only state is unmissable before the user tries to edit, not after.
+- The notify action's group and person pickers list employees only.
+- Quieter grid, curved connectors.
+
+## 4. Non-goals
+
+- **Items do not get custom fields in v1.** Carbon attaches item custom fields to the subtypes
+ (`part`, `material`, `tool`, `consumable`, `fixture`); the workflow catalog triggers on the
+ shared `item` table. Merging them needs a collision rule and is its own change. The nine other
+ triggerable entities are covered.
+- **No `File` custom fields as entity values.** A `File` custom field (DataType 9) is exposed as
+ a plain string path — comparable and printable, but not a link and not an entity to drill into.
+- No change to the workflow permission model, the run-history schema, or retention.
+- No rich text in messages. The body stays a single string; the only structure added is an
+ inline link.
+- No format-version bump. The stored `role` input key is not renamed (see D-9).
+- Renaming/reshaping any existing catalog event id. Custom-field event ids are new and additive.
+
+## 5. Design
+
+### 5.1 Custom fields — a per-company catalog overlay
+
+The catalog is built at **build time and is global**; custom fields are **runtime and
+per-company**. They therefore cannot be generated into `events.generated.ts`. Instead the
+catalog gains an optional overlay that is merged in per company at the two places a catalog is
+constructed: the builder (client) and the engine (server).
+
+#### New module — `packages/workflows/src/catalog/custom-fields.ts`
+
+Pure, no I/O, no DB import. Its input is the shape the ERP already loads.
+
+```ts
+export type CustomFieldDef = {
+ table: string; // customField."table"
+ id: string; // customField.id — the key inside the JSONB blob
+ name: string; // the customer's label
+ dataTypeId: number; // DataType enum
+ listOptions: string[] | null;
+ active: boolean;
+};
+
+export type CatalogOverlay = {
+ properties: Record<string, Record<string, ValueType>>; // entity -> path -> type
+ labels: Record<string, string>; // "entity.customFields.<id>" -> name
+ enums: Record<string, string[]>; // same key -> listOptions
+};
+
+export function buildCatalogOverlay(defs: CustomFieldDef[]): CatalogOverlay;
+```
+
+- The property **path is one segment**, the literal string `customFields.<fieldId>`. It is not
+ a two-hop drill. This keeps `walkPath` (`definition/catalog.ts:82-96`) and `resolve.ts`'s
+ `walk` single-step: read `row.customFields?.[fieldId]`. It also means the bare key
+ `customFields` never becomes a property, which matches the differ (nested diffs never emit
+ the bare key).
+- Only `active` fields are included, and only for tables in `WORKFLOW_ENTITY_REGISTRY` **minus
+ `item`** (non-goal).
+
+**DataType → ValueType map** (the one place this mapping lives):
+
+| DataType | ValueType | Notes |
+|---|---|---|
+| Boolean (1) | `t.boolean` | |
+| Date (2) | `t.date` | |
+| List (3) | `t.string` + `enums[key] = listOptions` | drives the right-hand side of a clause |
+| Numeric (4) | `t.number` | |
+| Text (5) | `t.string` | |
+| User (6) | `t.entity("user")` | drillable — `user` is a reference entity in the registry |
+| Customer (7) | `t.entity("customer")` | |
+| Supplier (8) | `t.entity("supplier")` | |
+| File (9) | `t.string` | the stored path; not linkable (non-goal) |
+
+#### Catalog facade
+
+`createWorkflowCatalog(overlay?: CatalogOverlay)` (`catalog/catalog.ts`). `getEntity` merges
+`properties` (generated first, overlay second — a generated column always wins, so a customer
+cannot shadow a real column), `getEnum` falls through to `overlay.enums`, and a new
+`getPropertyLabel(entity, path)` returns the overlay label when there is one.
+
+`build.ts`'s `DROPPED_COLUMNS` is **unchanged** — `customFields` stays out of the generated
+property map. The overlay is the only path in.
+
+#### Trigger events — parsed, not looked up
+
+New event id shape: `<entity>.customFields.<fieldId>.changed` — e.g.
+`salesOrder.customFields.cf_a1b2c3.changed`. Deliberately parallel to the generated
+`<entity>.<column>.changed`.
+
+`WORKFLOW_EVENTS` stays a closed committed record. Every consumer that currently does
+`WORKFLOW_EVENTS[id]` moves to a new **`resolveEvent(id): CatalogEvent | null`** exported from
+`catalog/catalog.ts`, which returns the static entry when there is one and otherwise parses the
+custom-field pattern into a synthetic `CatalogEvent`:
+
+```
+match: { table: <entity's table>, operation: "UPDATE", field: `customFields.${fieldId}` }
+permission: copied from the entity's registry entry
+outputs: record | before | after (identical to a generated .changed event)
+```
+
+Consumers to switch: `sync.ts` `deriveWorkflowSubscriptions:59`, and anywhere the builder reads
+an event by id.
+
+**The matcher needs no per-company knowledge.** `computeNestedDiff` already emits
+`customFields.<id>` keys, so `event-ids.ts` gains one extra pass in `computeEventIds`: for each
+diff key matching `^customFields\.(.+)$` on a table that is in `INDEX`, emit
+`` `${entity}.customFields.${fieldId}.changed` ``. The id is *derived from the data*, and the
+existing `workflowTriggerEvent` join then filters to the workflows that actually subscribed. No
+company lookup is added to the hot path.
+
+Ordering: custom-field ids are appended after the generated `.changed` ids (which are emitted in
+catalog order). The "one run per workflow per announcement, first event id wins" rule is
+unchanged; a workflow subscribed to both a real column and a custom field on the same update
+still gets exactly one run.
+
+**Drift check.** `workflow-trigger-event-drift` (`packages/checks`) currently asserts every
+`workflowTriggerEvent.eventId` is a known catalog id. It gains a second branch: an id matching
+the custom-field pattern is valid when a `customField` row with that id exists for that company
+and its `table` matches the entity. That is a stronger check than a bare pattern allow — it
+catches a trigger left behind after a custom field is deleted.
+
+#### Reading a custom field at run time
+
+`engine/execute.ts`'s existing `"load"` step gains one read: the company's active `customField`
+rows (through the **owner-scoped client**, like every other business read — `customField` is
+company-scoped and RLS-covered). It builds the overlay once per run and constructs the catalog
+with it. Everything downstream — `resolve.ts:134`'s `entity.properties[segment]` gate,
+`values.ts`'s `fromColumn` coercion, `compare.ts` — works unchanged, because the property is
+now simply declared.
+
+`fromColumn` receives the value straight out of the JSONB blob. Custom-field values are stored
+as strings by the ERP's form layer regardless of type, so coercion is by the **declared**
+`ValueType`, not by the JS runtime type — this is exactly what `fromColumn` already does for
+columns. A value that cannot be coerced resolves to nothing, which the engine already treats as
+"skip with a reason", never an error.
+
+#### Writing a custom field
+
+The `<entity>.update` action's input list gains the company's custom fields, from the same
+overlay. Two things `update.ts` must do differently:
+
+1. **Never clobber the blob.** A workflow setting one field must not erase the others, and a
+ read-modify-write through the Supabase client races with a concurrent human edit. New RPC,
+ invoker-rights so RLS still applies:
+
+ ```sql
+ workflow_merge_custom_fields(p_table text, p_id text, p_company_id text, p_values jsonb)
+ -- UPDATE <table> SET "customFields" = COALESCE("customFields", '{}'::jsonb) || p_values
+ -- WHERE id = p_id AND "companyId" = p_company_id
+ ```
+
+ `p_table` is validated against `customFieldTable` inside the function (an allowlist that
+ already exists) — it is never interpolated from caller-supplied text without that check.
+2. **Validate by declared type.** `update.ts` already rejects a value outside a column's enum
+ and already proves every entity-typed value belongs to this company. Both extend to custom
+ fields unchanged: List options are the enum, and User/Customer/Supplier custom fields go
+ through the same tenancy check.
+
+The write is a separate statement from the row's ordinary column update, so an update node that
+sets both writes twice. That is acceptable — both are inside the same durable step and the
+step's at-most-once claim already covers a partial failure.
+
+#### Builder
+
+`ui/Builder/catalog.ts`'s module-level singleton becomes a **provider**: the route already has
+the company's definitions via `useCustomFieldsSchema()` (loaded once per session in
+`x+/_layout.tsx`), so the builder builds the overlay client-side and puts the catalog on context.
+`ClauseRow.tsx`, `variableMenu.ts`, `ActionForm.tsx` and `TriggerForm.tsx`'s `EventPicker` read
+it from there.
+
+**Labels.** `WORKFLOW_LABELS` is a static generated `msg` table and cannot hold a per-company
+name. The overlay supplies plain strings; `useWorkflowLabel(key, fallback)`'s existing fallback
+path carries the custom field's `name` verbatim. Custom field names are customer data and are
+deliberately not translated.
+
+In the event picker, custom-field events are grouped under their entity like any other, with a
+"Custom field" qualifier so `Priority` (a custom field) is distinguishable from a shipped column
+of the same name.
+
+### 5.2 Linking a record in a message
+
+Three parts.
+
+**(a) A record may be dropped into a template.** `rendersAsText` (`definition/types.ts:82`)
+currently returns false for `entity` and `list<entity>`, which is why the variable menu hides
+whole records in message fields. It starts returning true for `entity` (not for
+`list<entity>` — a list of records in a sentence has no good reading). `renderValue` already
+knows what to print for an entity: `row.readableId ?? row.name ?? id`. This is one rule change,
+not a notify-only special case, so the validator's `checkTemplateParts` and the builder's
+`textOnly` filter both follow automatically.
+
+**(b) The notify action linkifies entity parts.** `renderTemplate` gains an optional
+`ctx.linkFor?: (of: string, id: string) => string | null`. When supplied, an entity part renders
+as a markdown link `[SO000123](https://…)`; when absent (webhook bodies, condition operands,
+every other caller) it renders exactly as today. `packages/workflows` still constructs no URL
+and imports nothing new — the callback is supplied by
+`packages/jobs/src/workflows/actions/notify.ts`, which may import `ERP_URL` and already knows
+`companyId`. The URL is the existing `buildNotificationLink` form
+(`${ERP_URL}/api/link?event=workflow&documentId=…&companyId=…&documentType=<of>`), so the
+company switch and the `RECORD_ROUTES` lookup are the ones already in production.
+
+**(c) Renderers understand inline links.** One shared helper in `packages/notifications`:
+
+```ts
+renderInlineLinks(text: string): Array<{ text: string } | { text: string; href: string }>
+```
+
+It matches **only** `[label](url)` where `url` is an absolute `https://` URL on the ERP origin.
+Anything else — a user typing `[x](javascript:...)`, a relative path, another host — is left as
+literal text. This is a security boundary, not a formatting nicety: the body is customer-authored
+and must not be able to inject an arbitrary destination.
+
+Consumed by:
+- `packages/documents/src/email/NotificationEmail.tsx` — detail values render the segments,
+ anchors for the linked ones.
+- `apps/erp/app/components/Layout/Topbar/Notifications.tsx` — **and this is where the body starts
+ being rendered at all.** Today `payload.details` is written and never read. The Workflow row
+ gains the body beneath the subject. The whole row is currently one `<Link>`; a nested anchor is
+ invalid HTML, so the row's outer `<Link>` is replaced with a click handler on the row plus real
+ anchors inline (the pattern the rest of the dropdown can keep using).
+
+Slack is not a Workflow destination today and is out of scope.
+
+### 5.3 The published version
+
+#### (a) Strictly no behaviour edits
+
+`store.ts` gains the `isReadOnly` guard on the mutators that lack it: `updateNodeData` (:260),
+`renameNode` (:267), `setNodeExpanded` (:280), `setAllNodesExpanded` (:287), `removeNode` (:310).
+`updateNodeData` is the one every config form funnels through, so that single guard closes the
+trigger-mode bug and every sibling instance of it at once.
+
+`BuilderControls.tsx`'s expand/collapse-all is disabled in read-only mode (`expanded` is part of
+the persisted definition).
+
+#### (b) Visibly disabled, not silently inert
+
+`NodeFormProps` (`ui/Builder/config/forms/index.ts`) gains `isReadOnly`;
+`WorkflowNodeCard.tsx:226` already has the flag in scope and passes it down. All six forms
+(`TriggerForm`, `ConditionForm`, `ActionForm`, `EntityForm`, `LookupForm`, `FilterForm`) render
+their controls `disabled`. The Event/Schedule toggle in `TriggerForm.tsx:430-455` is the headline
+case: it becomes two disabled buttons showing the current mode rather than two live ones.
+
+#### (c) A prominent lock affordance
+
+Build `apps/erp/app/modules/workflows/ui/WorkflowLockAlert.tsx` — the component the canvas spec
+called for and that was never built (and that `modules/workflows/AGENTS.md` already, wrongly,
+lists as existing; that stale line gets fixed in the same change).
+
+Copy `apps/erp/app/modules/items/ui/Item/ReleaseLockAlert.tsx`: `Alert variant="warning"` +
+`LuTriangleAlert`, title "This version is live", description
+`LOCKED_VERSION_MESSAGE` ("This version is live. Create a new version to make changes."), and a
+"New version" button for anyone holding `workflows_update`. Mounted between `<BuilderHeader>` and
+the canvas in `routes/x+/workflow+/$id.tsx:191-197`.
+
+The no-permission case gets its own copy — a person who simply lacks `workflows_update` should
+not be told to create a new version.
+
+#### (d) Rearranging stays allowed
+
+Read-only splits into two reasons, because they want different behaviour:
+
+| | live version | no `workflows_update` |
+|---|---|---|
+| behaviour edits | blocked | blocked |
+| node drag | **allowed** | blocked |
+| auto-arrange | **allowed** | blocked |
+
+So the store's single `isReadOnly` becomes `{ isVersionLocked, canEdit }` with a derived
+`canMoveNodes = isVersionLocked ? canEdit : canEdit`, i.e. movement follows permission, not the
+lock. Concretely:
+
+- `onNodesChange` lets `position` / `dimensions` / `select` changes through whenever
+ `canMoveNodes`, and keeps dropping `remove` and everything else.
+- `WorkflowBuilder.tsx:155` `nodesDraggable={canMoveNodes}`.
+- `arrangeNodes` / `setNodePositions` guard on `canMoveNodes`.
+
+**Persistence.** Positions live in the versioned definition (`schema.ts:36`) and `/save` is
+correctly locked server-side, so a second, narrower writer is needed:
+
+- Route `apps/erp/app/routes/x+/workflow+/$id.positions.tsx` — requires `workflows_update`,
+ does **not** call `checkWorkflowVersionLock`.
+- Service `updateWorkflowNodePositions(client, { versionId, companyId, positions })` — reads the
+ version's `nodes`, and for each incoming `{ id, position }` applies the position **only** if
+ that node id already exists. Unknown ids are ignored, `edges` is never touched, and no other
+ key of any node is written. The endpoint is therefore incapable of changing behaviour even if
+ called by hand.
+- `Autosave.tsx` splits: when the version is locked it diffs positions only and posts to
+ `/positions`; otherwise it behaves exactly as today. Same 1s debounce.
+- A refusal from either endpoint raises the existing `toast.error` path — which today never
+ fires on a locked version because autosave is switched off entirely.
+
+Nothing else about a live version becomes writable. `workflow.canvasState` (viewport) keeps its
+existing deliberately-unlocked route.
+
+### 5.4 Group and person pickers
+
+- `packages/workflows/src/catalog/actions.ts:145` — `label: "role"` → `label: "group"`, then
+ `pnpm run generate:workflow-catalog` and `pnpm run lingui:extract && pnpm run lingui:clean`.
+ The **stored input key stays `role`** (D-9), so no definition migration and no change to
+ `requireOneOf`, `notify.ts` or its test.
+- `ui/Builder/fields/recordPickers.tsx` — `GroupPicker` (:145-153) and `UserPicker` (:132-141)
+ both pass `type="employee"` to `<UserSelect>`, which routes to
+ `get_user_select_groups(p_type => 'employee')`, i.e. *not customer- and not supplier-flagged*.
+ That is the RPC's existing definition and matches the ask exactly: ad-hoc groups a company
+ created by hand stay available; customer and supplier org/type groups disappear.
+- Existing definitions pointing at a customer or supplier group keep working (validation checks
+ the type, not the flags). They simply cannot be re-picked from the list. This is deliberate —
+ silently breaking a live workflow to enforce a new picker rule would be worse.
+
+### 5.5 Canvas visuals
+
+- `WorkflowBuilder.tsx:166` — `<Background variant={BackgroundVariant.Dots} gap={24} size={1} />`,
+ plus a `--xy-background-pattern-dots-color` override with light and dark values in the
+ route-level stylesheet. Today no `--xy-*` override exists anywhere in the app, so the dot
+ colour is whatever xyflow ships; that is why it reads loud.
+- `edges/WorkflowEdge.tsx:40-48` — `getSmoothStepPath` → `getBezierPath`. One import, one call
+ site; `labelX`/`labelY` come back from the same call so the disconnect button is unaffected.
+ Stroke, dash pattern and the marching-ants animation are **unchanged** (explicitly kept).
+
+## 6. Design Decisions
+
+| # | Decision | Rationale |
+|---|---|---|
+| D-1 | Custom fields reach workflows as trigger **and** read **and** write | User's call. The engine already has the data; a trigger you cannot read or act on is half a feature. |
+| D-2 | Per-company **overlay** on the catalog, not generated entries | The catalog is build-time and global (`events.generated.ts` is committed and drift-checked); custom fields are runtime and per-company. Generation is impossible; an overlay merged at the two construction sites is the smallest seam. |
+| D-3 | The property path is one segment, `customFields.<fieldId>` | Keeps `walkPath` and `resolve.ts`'s `walk` single-step, and matches the differ, which never emits the bare `customFields` key. |
+| D-4 | Event ids are **parsed** (`resolveEvent`), not added to `WORKFLOW_EVENTS` | `WORKFLOW_EVENTS` is committed, generated and drift-checked against a fresh build; a per-company id cannot live there. Parsing keeps one closed generated file and one open pattern. |
+| D-5 | `computeEventIds` derives the id from the diff key, so the matcher stays company-blind | The nested differ already emits `customFields.<id>`; no per-company lookup is added to the hot path, and the `workflowTriggerEvent` join does the filtering it already does. |
+| D-6 | Writes go through a `workflow_merge_custom_fields` RPC with `||` merge | A read-modify-write on the JSONB blob through the Supabase client races a concurrent human edit and would erase other fields. Invoker-rights keeps RLS. `p_table` is checked against the existing `customFieldTable` allowlist. |
+| D-7 | Items are excluded | User's call. Item custom fields attach to `part`/`material`/`tool`/…; the catalog triggers on the shared `item` table. Merging needs a collision rule and is its own change. |
+| D-8 | `rendersAsText` starts allowing `entity` (not `list<entity>`) | One general rule beats a notify-only special case; `renderValue` already knows how to print an entity. A list of records in a sentence has no good reading. |
+| D-9 | The notify input key stays `role`; only its label becomes "Group" | Renaming the key needs a v4 definition format migration (`normalize.ts` `migrateDefinition`) plus changes to `requireOneOf`, `notify.ts` and its test, for zero user-visible gain. The stored value is already a group id. |
+| D-10 | "Employee" means *not customer- and not supplier-flagged* | That is the existing `get_user_select_groups(p_type => 'employee')` definition (`20260714045245_user-select-rpcs.sql:53-60`) and matches the ask's wording ("not customers or suppliers"). Ad-hoc company groups stay pickable. |
+| D-11 | Links are markdown `[label](url)`, linkified only for https URLs on the ERP origin | The body is one string with no structured channel. Restricting the pattern to our own origin is what stops customer-authored text from injecting an arbitrary destination. |
+| D-12 | Movement follows **permission**, not the version lock | The ask. Positions carry no behaviour, and run history orders steps topologically (`topologicalNodeOrder`), never by position — so tidying a live version changes nothing a reader depends on, and the layout carries over when the next version is branched. |
+| D-13 | A separate `/positions` route that can only write positions | `/save` is correctly locked server-side and must stay locked. A narrow endpoint that ignores unknown node ids and never touches `edges` or `data` is incapable of changing behaviour even when called by hand. |
+| D-14 | Read-only splits into `isVersionLocked` vs `canEdit` | The two reasons want different behaviour (a locked version still allows dragging; missing permission does not) and different copy (telling someone without permission to "create a new version" is wrong). |
+| D-15 | Connectors become true beziers; dashes and animation stay | User's call on both. `getBezierPath` returns the same `labelX`/`labelY`, so the disconnect button is unaffected. |
+| D-16 | `File` custom fields are exposed as plain strings | The stored value is a path; treating it as an entity would imply a drill-through and a link that do not exist. |
+
+## 7. Acceptance criteria
+
+**Custom fields**
+
+1. With a Text custom field "Rush Reason" on Sales Order, the trigger picker offers
+ "Sales Order's Rush Reason changes" under Sales Order, labelled as a custom field.
+2. Publishing that workflow writes one `workflowTriggerEvent` row with
+ `eventId = 'salesOrder.customFields.<id>.changed'` and one `workflow-salesOrder`
+ `eventSystemSubscription` with `UPDATE` in its operations.
+3. Editing that field on a sales order queues exactly one `workflowRun`; editing an unrelated
+ column queues none.
+4. In a condition, `record.Rush Reason contains "expedite"` evaluates true for the value
+ "Customer expedite" and false for "standard", and the step's `detail` records the clause.
+5. A List custom field's condition offers exactly its `listOptions` as right-hand choices.
+6. A Numeric custom field compares with `>` correctly (the declared type drives coercion, not
+ the JS type of the stored JSON value).
+7. Dropping a custom field into a notification body prints its value.
+8. An Update action that sets one custom field leaves every other key in that record's
+ `customFields` blob untouched, verified by reading the row before and after.
+9. An Update action setting a List custom field to a value outside `listOptions` fails the step
+ with a reason, and writes nothing.
+10. A workflow in company A cannot see or trigger on company B's custom fields.
+11. Deactivating a custom field removes it from the pickers; an already-published workflow
+ referencing it still parses, and the drift check reports it.
+12. Item triggers show no custom fields, and the builder says why rather than showing an empty
+ group.
+
+**Message links**
+
+13. In a notify action's Message field, the variable menu offers the whole Sales Order record
+ (not only its individual fields).
+14. The resulting in-app notification shows the subject **and** the body, and the body's record
+ reference is a working link to that sales order — including the company switch when the
+ recipient's active company differs.
+15. The emailed notification shows the same body with the same working link.
+16. A body containing the literal text `[click](javascript:alert(1))` renders as literal text,
+ with no anchor.
+17. The same record dropped into a **webhook** body renders as its readable id with no URL and
+ no markdown.
+
+**Published version**
+
+18. On a live version, clicking Schedule in the trigger node does nothing and the control is
+ visibly disabled; reloading shows the trigger unchanged.
+19. On a live version, every input in every node's config is disabled — verified for all six
+ node types.
+20. On a live version, a warning banner above the canvas states the version is live and offers
+ "New version"; a user without `workflows_update` sees a different message with no button.
+21. On a live version, dragging a node moves it, and the new position survives a reload.
+22. On a live version, auto-arrange runs and its layout survives a reload.
+23. A hand-crafted POST to `/x/workflow/$id/positions` carrying a changed `data` payload or a new
+ node id changes nothing but the positions of already-existing nodes.
+24. A hand-crafted POST to `/x/workflow/$id/save` on a live version still returns 409.
+25. Branching a new version from a live one carries over the tidied positions.
+
+**Pickers and visuals**
+
+26. The notify action's second recipient field is labelled "Group", and its list contains no
+ customer or supplier groups; a company's hand-made group is still listed.
+27. The person field on the same action lists employees only.
+28. A workflow already pointing at a supplier group continues to run and to display that group's
+ name.
+29. The canvas grid is dots at 24px spacing with an explicit low-contrast colour that is legible
+ in both light and dark themes.
+30. Connectors render as single continuous curves; the dashed marching-ants animation still runs
+ and the disconnect button still sits on the line.
+
+## 8. Open questions — resolved
+
+- [x] **How far should custom fields reach into workflows?** — **Answer:** trigger **and** read
+ everywhere (conditions, filters, messages), via a per-company catalog overlay. The engine
+ already carries the data; a trigger whose value cannot be read is half a feature.
+- [x] **Should workflows also be able to write a custom field?** — **Answer:** yes. Initially
+ scoped out as read+trigger only; the user explicitly extended it to writing. Handled via
+ the `workflow_merge_custom_fields` RPC so one field's write cannot clobber the blob, with
+ validation reusing the existing enum and tenancy checks (D-6).
+- [x] **What about Items, whose custom fields live on the subtypes?** — **Answer:** leave Items
+ out for now; the other nine triggerable entities are covered and the builder says so
+ plainly rather than showing an empty list (D-7).
+- [x] **What should a record link look like in a message?** — **Answer:** the record itself
+ becomes insertable and renders as its readable id, clickable, in email and in-app (D-8,
+ D-11). A raw-URL property was rejected as uglier to read.
+- [x] **Fix the in-app bell dropping the message body?** — **Answer:** yes — otherwise the link
+ exists only in email and the feature looks broken in-app.
+- [x] **Where do node positions for a live version get saved?** — **Answer:** into the live
+ version, positions only, through a narrow endpoint that rejects everything else (D-12,
+ D-13). Chosen over a separate layout store so tidying carries over when the next version
+ is branched.
+- [x] **How strongly should the read-only state be shown?** — **Answer:** a warning banner above
+ the canvas **and** every node control visibly disabled. The silent-evaporation behaviour is
+ the actual reported bug.
+- [x] **Should the person picker get the same employee filter as the group picker?** —
+ **Answer:** yes; it is the identical leak and inconsistency between two adjacent fields
+ would be worse.
+- [x] **Grid style?** — **Answer:** fainter dots, wider apart (24px), with an explicit
+ low-contrast colour for both themes.
+- [x] **Edge style?** — **Answer:** true curves. The user noted React Flow already ships a
+ curvier edge type by default — that is `getBezierPath`, versus the `getSmoothStepPath`
+ currently in use (D-15).
+- [x] **Keep the dashed marching-ants animation?** — **Answer:** yes, keep it as-is.
+
+## 9. Risks
+
+- **Catalog construction moves from a module singleton to a provider.** `ui/Builder/catalog.ts`
+ is imported directly in several files; every one must move to the context or it will silently
+ see a catalog with no custom fields. Grep is the mitigation, plus the fact that a missed site
+ shows up immediately as a missing property in the picker.
+- **`rendersAsText` allowing `entity` widens more than messages.** It is read by the validator
+ and by the variable menu, so records become droppable into every template field including
+ webhook bodies. That is intended (they render as the readable id), but it is a behaviour change
+ to a shared rule and needs the validator's tests extended.
+- **Custom-field ids leak into stored trigger rows.** Deleting a custom field leaves a
+ `workflowTriggerEvent` row that can never fire again. The extended drift check surfaces it;
+ cleaning it up automatically is deliberately not in scope.
+- **The notification row's nested-anchor change** touches a component outside the workflows
+ module that every notification type renders through. Regression surface is the whole bell.
+- `packages/erp` is chronically near TypeScript's instantiation budget (`.ai/lessons.md`); the
+ new catalog context type is new type surface in a widely-imported file.
+
+## 10. Changelog
+
+- **2026-08-19** — Initial spec. Eleven open questions resolved with the user before writing
+ (§8); the custom-fields scope was extended from read+trigger to include writing during that
+ interview.
+- **2026-08-19** — Implemented. Plan: `.ai/plans/2026-08-19-workflow-improvements-round-2.md`.
+ Four deviations from the design, all decided during execution and all narrower than the spec:
+ 1. **§5.2c / email links.** `packages/documents` did not depend on `@carbon/notifications`,
+ and its local `NotificationDetail` copy carried a comment saying that avoidance was
+ deliberate. The user chose to add the dependency rather than duplicate the parser — the
+ link matcher is a security boundary and must be the same code in both renderers.
+ 2. **§5.2c / the bell row.** The outer `<Link>` is dropped only for rows that actually have a
+ body. A `role="link"` div loses cmd-click, open-in-new-tab and the status-bar URL, so every
+ other notification type keeps its real anchor and is byte-for-byte unchanged. The body
+ reader is also gated on `NotificationEvent.Workflow`, because `JobOperationMessage` writes
+ a `{label:"Message"}` detail whose text its description already embeds.
+ 3. **§5.3c / the banner button.** The new-version route is POST-only and takes
+ `copyFromVersionId`, so the button submits a fetcher rather than linking, and it is gated on
+ `workflows_create` (the permission that route actually requires) rather than
+ `workflows_update`.
+ 4. **§5.1 / writing.** A custom field's value is written as a string, matching what the ERP's
+ own form layer stores; `fromColumn` coerces back by the DECLARED type on read, so the
+ round-trip is exact. The ordinary column update is skipped entirely when a step sets only
+ custom fields, rather than writing a bare `updatedBy`/`updatedAt`.
+
+ Also fixed in passing, both pre-existing: `packages/react`'s `Input` applied
+ `disabled={isDisabled}` AFTER the props spread, silently overriding any caller-supplied
+ `disabled` (two Linear/Jira search boxes were affected); and `@carbon/notifications` had no
+ test runner at all.
diff --git a/.ai/specs/2026-08-20-notify-channels.md b/.ai/specs/2026-08-20-notify-channels.md
new file mode 100644
index 0000000000..85b65e27d7
--- /dev/null
+++ b/.ai/specs/2026-08-20-notify-channels.md
@@ -0,0 +1,72 @@
+# Notify action — per-node channel picker
+
+## Problem
+
+The workflow `notify` action always delivers on whatever the notify job's default
+map says for `NotificationEvent.Workflow` — in-app plus email, never Slack. The
+author has no say, and Slack is unreachable from a workflow even for companies
+that have connected it.
+
+## Outcome
+
+A "Notification type" field on the notify node: a multi-select over In-app,
+Email and Slack. The chosen channels ride to the notify job as `destinations`,
+which the job already accepts.
+
+## Decisions
+
+- **In-app is locked on.** `notify.ts` force-adds `NotificationDestination.InApp`
+ to every notification so the topbar reflects everything; that is a platform-wide
+ contract, not a workflow one. The option renders checked and disabled with
+ "Always sent" underneath, which is the truth rather than a switch that does
+ nothing.
+- **The field is optional, not required.** With in-app locked on, "required"
+ could only ever be satisfied trivially — and a required input would block
+ publish on notify nodes saved before this field existed, in a picker where
+ the author cannot tick the one channel that is actually on. `defaultValue`
+ seeds `["inApp", "email"]` on every new node instead, so the field is filled
+ in practice and an absent value keeps today's behaviour.
+- **Unavailable channels are disabled with a reason.** Email needs a Business or
+ Partner plan; Slack needs the company's Slack integration active. The job skips
+ a channel it cannot use silently — the author has to be told at build time or
+ never.
+- **The catalog flag is generic.** `multiple: true` on a catalog input means "a
+ set of `choices`", typed `t.list(t.string)`. Nothing about it is notify-specific;
+ only the option titles and availability are.
+
+## Shape
+
+Catalog (`packages/workflows`):
+
+- `ActionInputLike` / `BuiltActionInput` / `CatalogInput` gain `multiple?: boolean`,
+ and `defaultValue` widens to `string | readonly string[]`.
+- `notify` gains `channels: { type: t.list(t.string), choices: ["inApp","email","slack"],
+ multiple: true, defaultValue: ["inApp","email"], required: false }`.
+- `checkInputs` validates every member of a list literal against `choices`
+ (today it only checks single strings).
+- `validateCatalogInputs` refuses a `multiple` input that is not a list of strings
+ with `choices`, and checks an array `defaultValue` member by member.
+
+Builder (`apps/erp`):
+
+- `MultiChoiceField` — a fourth field component, dispatched in `ActionForm`
+ alongside `pairs` and `template`. Renders `ChoiceSelect multiple`.
+- `multiChoice.ts` — the pure value round-trip (`readChoices` / `writeChoices`),
+ unit-tested; an emptied set stores as absent, matching `pairsRows.ts`.
+- `choiceOptions.tsx` — resolves `choices` to titles/descriptions/disabled. Reads
+ availability from `useIntegrations().has("slack")` and
+ `usePlanGate({ feature: "EMAIL_NOTIFICATIONS" })`, both of which read the `/x`
+ layout's route data — no loader change.
+
+Runtime (`packages/jobs`):
+
+- `runNotifyAction` reads `inputs.channels`, keeps the values that are real
+ `NotificationDestination`s, and passes them as `destinations`. Empty or absent
+ omits the field, so the job's default map still applies.
+
+## Not doing
+
+- Letting the author switch off in-app. That would change delivery for every
+ notification type in the product, not just workflows.
+- Warning at run time when a channel was skipped. The job's silence is
+ pre-existing; the build-time disable is the fix that reaches the author.
diff --git a/.claude/rules/workflow-actions.md b/.claude/rules/workflow-actions.md
index ec22a0b7e4..99c720e13a 100644
--- a/.claude/rules/workflow-actions.md
+++ b/.claude/rules/workflow-actions.md
@@ -199,6 +199,34 @@ rendered — nothing here reads a template. When the customer named no record, t
**run** stands in as the notification's subject (`documentId: aboutId ?? runId`).
`trigger` only queues, so the summary claims recipients, never delivery.
+### Channels
+
+`channels` is a multi-select catalog input — `t.list(t.string)` with
+`choices: ["inApp", "email", "slack"]` and `defaultValue: ["inApp", "email"]`.
+The executor keeps only the names that are real `NotificationDestination`s and
+passes them as `destinations`; an empty or absent value **omits the field**, so
+the notify job falls back to its default map for `NotificationEvent.Workflow`
+(in-app plus email) — which is what a node saved before this input existed means.
+
+Three things about it are load-bearing:
+
+- **In-app cannot be switched off.** `notify.ts` force-adds
+ `NotificationDestination.InApp` to every notification so the bell menu reflects
+ everything, product-wide. The builder therefore shows it ticked and disabled
+ rather than offering a switch that does nothing.
+- **The input is optional, not required**, precisely because in-app is locked on:
+ requiring it could only ever be satisfied trivially, and it would block publish
+ on notify nodes saved before the field existed in a picker where the author
+ cannot tick the one channel that is actually on.
+- **Availability is a build-time concern.** Email needs `EMAIL_NOTIFICATIONS`
+ (Business/Partner) and Slack needs the company's Slack integration active; the
+ job skips a channel it cannot use with a `console.warn` at most. The builder
+ disables the option and says why (`fields/choiceOptions.tsx`) — that is the only
+ place the author ever finds out. "Unavailable" only blocks ADDING a channel; one
+ already stored (the seeded `email` default on a company with no plan for it) stays
+ removable, or the author is looking at a channel they cannot clear. Only a `LOCKED`
+ choice is frozen. `fields/multiChoice.ts` `choiceState` owns that distinction.
+
## The webhook action
`actions/webhook.ts`. Four inputs, `url` and `method` required:
@@ -297,8 +325,8 @@ matcher's subscription reconciler is already careful never to touch a company's
`GONE` ("This step is no longer available.") means the catalog no longer has it,
`NO_DISPATCH` means the dispatcher was never injected, `UNKNOWN_RESULT` means a
`call` action declares no `record` output to hand back.
-- `toPlainValue` lives in `update.ts` and is imported by `create.ts` so both
- convert identically. Don't fork it.
+- `toPlainValue` lives in `actions/values.ts` and is imported by BOTH `update.ts` and
+ `create.ts` so they convert identically. Don't fork it.
- `update.ts` and `search.ts` both cast the client to an untyped `SupabaseClient`
before `.from(table)`. The table is only known at run time, and typing it costs a
~350-way instantiation `apps/erp` cannot afford.
diff --git a/.claude/rules/workflow-engine.md b/.claude/rules/workflow-engine.md
index 4402b722d2..0c1ea13a46 100644
--- a/.claude/rules/workflow-engine.md
+++ b/.claude/rules/workflow-engine.md
@@ -183,3 +183,35 @@ becomes visible — `Ran 100 of 150; 50 were not used.` The node's outputs are a
list of each successful item's primary output, in item order. A failed item does
not stop the graph but does mark the **run** Failed, so a partial batch never
shows a customer a green tick.
+
+## Per-run additions (round 2)
+
+- **`custom-fields` step.** `executeWorkflowRun` now runs one extra durable step between
+ `"load"` and `"permissions"`, reading the company's active `customField` rows through the
+ **owner's** client and building a `CatalogOverlay` from them. The catalog is constructed from
+ that overlay, so a custom field is simply a declared property everywhere downstream —
+ `resolve.ts`'s `entity.properties[segment]` gate, `values.ts`'s `fromColumn` coercion and
+ `compare.ts` all work unchanged. A refused read and a company with no custom fields are the
+ same answer: the run proceeds against the shipped catalog alone. Step ids are therefore
+ `"load"`, `"custom-fields"`, `"permissions"`, `` `node:${nodeId}` ``, `"finish"`.
+- **`ctx.linkFor`.** `contextFor` supplies an optional `(of, id) => string | null` that turns a
+ record into the existing `${ERP_URL}/api/link?...` URL. `renderTemplate` uses it ONLY for
+ inputs the catalog marks `linkify` (today: the notify action's `message`), wrapping an entity
+ part as `[name](url)`. A webhook body has no `linkify`, so it still renders a bare
+ name with no markdown. `packages/workflows` constructs no URL — it calls the callback.
+- **How a record NAMES itself in prose.** `entityText` in `runtime/resolve.ts` reads the columns
+ `CatalogEntity.display` lists, best first, and falls back to the raw id only when none of them
+ is readable. `display` is REQUIRED on every registry entry and comes from the hand-written
+ registry at run time (`catalog.ts`, the same route as `descriptions`) — the generator never
+ sees it, so adding an entity needs no catalog regeneration but does need a display column, or
+ it will not compile. It mirrors `fkDisplayRegistry` in `@carbon/database`, which cannot be
+ imported here: it is a runtime value and this package is bundled for the browser. Most entity
+ values carry no `row` — a moment output, a created record and a foreign key all arrive as a
+ bare id — so `entityText` loads one through `ctx.loader` (owner-scoped, cached per run).
+ `renderPart` handles a single entity only: `rendersAsText` refuses a LIST of records as a
+ template part, so one can never reach it. The synchronous `renderValue` cannot reach the
+ catalog or the loader and so reads an entity off its inline row alone — it is not, and must
+ not become, a second way to name a record.
+- **Slack.** `renderSlackMrkdwn` in `packages/notifications/src/index.ts` re-spells the message's
+ `[name](url)` as Slack's `<url|name>`, beside the `renderInlineLinks` matcher it delegates to
+ and the in-app and email renditions that share it. Without it Slack shows markdown verbatim.
diff --git a/.claude/rules/workflow-event-catalog.md b/.claude/rules/workflow-event-catalog.md
index 7f601ee522..115d44da55 100644
--- a/.claude/rules/workflow-event-catalog.md
+++ b/.claude/rules/workflow-event-catalog.md
@@ -33,9 +33,9 @@ packages/workflows/src/catalog/labels.generated.ts COMMITTED one msg`` per ev
```
Today: 10 triggerable entities with 77 watched columns → 97 record events, plus 9 moments
-= **106 events**, plus property maps for 16 entities (the 10 triggerable ones and 6
-reference-only: `user`, `group`, `jobOperation`, `salesInvoice`, `purchaseInvoice`,
-`location`), plus **16 actions** and **15 operations**.
+= **106 events**, plus property maps for 17 entities (the 10 triggerable ones and 7
+reference-only: `user`, `group`, `jobOperation`, `nonConformanceType`, `salesInvoice`,
+`purchaseInvoice`, `location`), plus **16 actions** and **15 operations**.
To add an entity, a moment, an action or an operation, edit the one hand-written file
and run:
@@ -245,3 +245,32 @@ the `workflow-trigger-event-drift` SQL invariant and
event id in the separate generated file, which also holds action and operation labels.
- A hand-written action id that collides with a generated `<entity>.update` is a build error,
not a silent overwrite.
+
+## Custom fields — the per-company overlay
+
+The catalog is build-time and global; a company's custom fields are runtime and per company,
+so they cannot be generated into `events.generated.ts`. Instead `catalog/custom-fields.ts`
+builds a `CatalogOverlay` from the company's `customField` rows, and
+`createWorkflowCatalog(overlay)` merges it — **generated first, overlay second**, so a real
+column always wins and a customer cannot shadow one.
+
+- The property path is ONE segment: the literal string `customFields.<fieldId>`, keyed by the
+ field's **id**, which is the key inside the JSONB blob. That keeps `walkPath` and the runtime
+ `walk` single-step, and matches the differ, which never emits the bare `customFields` key.
+- `custom-fields.ts` holds the ONLY `DataType → ValueType` map. List → `string` plus `choices`
+ from `listOptions`; User/Customer/Supplier → `t.entity(...)`; File → the stored path as a
+ string, not a link.
+- Trigger ids are `<entity>.customFields.<fieldId>.changed` and are **parsed, not looked up**:
+ `WORKFLOW_EVENTS` stays a closed, committed, drift-checked record. `getCatalogEvent(id)` is
+ the single lookup — the static map first, then `resolveCustomFieldEvent`. Every consumer goes
+ through it, including `sync.ts`'s `deriveWorkflowSubscriptions`.
+- `item` is excluded: its custom fields attach to the subtypes (`part`, `material`, `tool`, …)
+ while the catalog triggers on the shared `item` table. Reference-only entities are excluded
+ too — no `watch` block means no change events at all.
+- The matcher stays **company-blind**: `computeEventIds` derives the id from the
+ `customFields.<id>` diff key the nested differ already emits, and the existing
+ `workflowTriggerEvent` join does the filtering. No company lookup enters the hot path.
+- Writes go through the `workflow_merge_custom_fields` RPC (SECURITY INVOKER, `p_table`
+ validated against `customFieldTable`) so setting one field cannot erase the others.
+- The engine builds the overlay once per run in the `custom-fields` durable step, reading
+ `customField` through the **owner's** client like every other business read.
diff --git a/.claude/rules/workflow-matcher.md b/.claude/rules/workflow-matcher.md
index c5f014b3ec..3d6b41635d 100644
--- a/.claude/rules/workflow-matcher.md
+++ b/.claude/rules/workflow-matcher.md
@@ -164,3 +164,17 @@ Kysely bypasses RLS. **The caller authorizes first** — phase 7's activation ro
account's concurrency, not a per-`companyId`/per-`workflowId` cap. See `workflow-engine.md`.
- Deploy-time drift checks live with `packages/checks`: the `workflow-trigger-event-drift`
SQL invariant and `pnpm --filter @carbon/checks workflow-events`.
+
+## Custom-field trigger ids
+
+`computeEventIds` emits `<entity>.customFields.<fieldId>.changed` for every
+`customFields.<id>` key in the diff, on any table that maps to a triggerable entity. The id is
+**derived from the data, never looked up** — it is per company and the catalog is not — so the
+matcher stays company-blind and no company lookup enters the hot path. `catalog.getEvent(id)`
+is what decides whether the entity may carry one at all (`item` and reference-only entities
+cannot), so that rule lives in exactly one place. Custom-field ids are appended AFTER the
+generated `.changed` ids, keeping "first event id wins" picking the same winner as before for a
+workflow subscribed to both a column and a field on the same update.
+
+`deriveWorkflowSubscriptions` resolves through `getCatalogEvent` rather than indexing
+`WORKFLOW_EVENTS`, which is what gives a custom-field trigger its `UPDATE` subscription.
diff --git a/apps/erp/app/components/Layout/Topbar/Notifications.tsx b/apps/erp/app/components/Layout/Topbar/Notifications.tsx
index 18ed014df6..3f1ab64462 100644
--- a/apps/erp/app/components/Layout/Topbar/Notifications.tsx
+++ b/apps/erp/app/components/Layout/Topbar/Notifications.tsx
@@ -1,5 +1,5 @@
"use client";
-import { NotificationEvent } from "@carbon/notifications";
+import { NotificationEvent, renderInlineLinks } from "@carbon/notifications";
import {
Badge,
Button,
@@ -46,7 +46,7 @@ import {
RiProgress4Line,
RiProgress8Line
} from "react-icons/ri";
-import { Link, useFetcher } from "react-router";
+import { Link, useFetcher, useNavigate } from "react-router";
import { DateTime } from "~/components";
import { useNotifications, useUser } from "~/hooks";
import type { ApprovalDocumentType } from "~/modules/shared";
@@ -65,6 +65,24 @@ type OutstandingTraining = {
currentPeriod: string | null;
};
+// `payload.details` is written by the notify job but is not on the topbar
+// Notification type, which only declares the keys this menu always reads.
+function getNotificationBody(
+ payload: NotificationRecord["payload"],
+ event: NotificationEvent
+): string | undefined {
+ // Workflow is the only event whose body is authored text rather than a
+ // restatement of the description — every other event would render twice.
+ if (event !== NotificationEvent.Workflow) return undefined;
+ const details = (payload as { details?: { label: string; value: string }[] })
+ .details;
+ if (!Array.isArray(details)) return undefined;
+ const message = details.find((detail) => detail?.label === "Message")?.value;
+ return typeof message === "string" && message.length > 0
+ ? message
+ : undefined;
+}
+
function EmptyState({ description }: { description: string }) {
return (
<div className="h-[460px] flex items-center justify-center flex-col gap-y-4">
@@ -122,6 +140,7 @@ function Notification({
icon,
to,
description,
+ body,
createdAt,
markMessageAsRead,
from,
@@ -130,6 +149,7 @@ function Notification({
icon: React.ReactNode;
to: string;
description: string;
+ body?: string;
createdAt: string;
from?: string;
markMessageAsRead?: () => void;
@@ -138,6 +158,7 @@ function Notification({
const { id: userId } = useUser();
const { t } = useLingui();
const [people] = usePeople();
+ const navigate = useNavigate();
let byUser = "";
if (from) {
if (from === userId) {
@@ -146,27 +167,84 @@ function Notification({
byUser = people.find((p) => p.id === from)?.name ?? "";
}
}
- return (
- <div className="flex items-between justify-between gap-x-4 px-3 py-3 hover:bg-secondary">
- <Link
- className="flex items-between justify-between gap-x-4 "
- onClick={() => onClose()}
- to={to}
- >
- <div>
- <div className="h-9 w-9 flex items-center justify-center gap-y-0 border rounded-full">
- {icon}
- </div>
+
+ const segments = body
+ ? renderInlineLinks(
+ body,
+ typeof window === "undefined" ? "" : window.location.origin
+ )
+ : null;
+
+ const content = (
+ <>
+ <div>
+ <div className="h-9 w-9 flex items-center justify-center gap-y-0 border rounded-full">
+ {icon}
</div>
- <div>
- <p className="text-sm">
- {description} {byUser && <span>{t`by ${byUser}`}</span>}
+ </div>
+ <div>
+ <p className="text-sm">
+ {description} {byUser && <span>{t`by ${byUser}`}</span>}
+ </p>
+ {segments && segments.length > 0 && (
+ <p className="text-xs text-muted-foreground line-clamp-3">
+ {segments.map((segment, index) =>
+ "href" in segment ? (
+ <a
+ key={`${index}:${segment.text}`}
+ href={segment.href}
+ className="underline underline-offset-2 hover:text-foreground"
+ // `/api/link` switches the active company server-side before
+ // redirecting, so this must be a full page load.
+ onClick={(e) => e.stopPropagation()}
+ >
+ {segment.text}
+ </a>
+ ) : (
+ <span key={`${index}:${segment.text}`}>{segment.text}</span>
+ )
+ )}
</p>
- <span className="text-xs text-muted-foreground">
- <DateTime value={createdAt} variant="relative" />
- </span>
+ )}
+ <span className="text-xs text-muted-foreground">
+ <DateTime value={createdAt} variant="relative" />
+ </span>
+ </div>
+ </>
+ );
+
+ return (
+ <div className="flex items-between justify-between gap-x-4 px-3 py-3 hover:bg-secondary">
+ {segments ? (
+ // A body can contain anchors, and an <a> inside an <a> is invalid HTML —
+ // browsers unnest it, which would pull the link out of the row.
+ <div
+ role="link"
+ tabIndex={0}
+ className="flex items-between justify-between gap-x-4 cursor-pointer"
+ onClick={() => {
+ onClose();
+ navigate(to);
+ }}
+ onKeyDown={(e) => {
+ if (e.target !== e.currentTarget) return;
+ if (e.key !== "Enter" && e.key !== " ") return;
+ e.preventDefault();
+ onClose();
+ navigate(to);
+ }}
+ >
+ {content}
</div>
- </Link>
+ ) : (
+ <Link
+ className="flex items-between justify-between gap-x-4 "
+ onClick={() => onClose()}
+ to={to}
+ >
+ {content}
+ </Link>
+ )}
{markMessageAsRead && (
<div>
<IconButton
@@ -191,6 +269,7 @@ function GenericNotification({
id: string;
createdAt: string;
description: string;
+ body?: string;
event: NotificationEvent;
from?: string;
documentType?: ApprovalDocumentType;
@@ -682,6 +761,7 @@ const Notifications = () => {
id={notification.payload.documentId as string}
createdAt={notification.createdAt}
description={notification.payload.description as string}
+ body={getNotificationBody(notification.payload, event)}
event={event}
from={notification.payload.from as string | undefined}
documentType={
@@ -769,6 +849,7 @@ const Notifications = () => {
id={notification.payload.documentId as string}
createdAt={notification.createdAt}
description={notification.payload.description as string}
+ body={getNotificationBody(notification.payload, event)}
event={event}
from={notification.payload.from as string | undefined}
documentType={
diff --git a/apps/erp/app/hooks/useCustomFieldsSchema.tsx b/apps/erp/app/hooks/useCustomFieldsSchema.tsx
index d056f29705..4bd477b47f 100644
--- a/apps/erp/app/hooks/useCustomFieldsSchema.tsx
+++ b/apps/erp/app/hooks/useCustomFieldsSchema.tsx
@@ -29,6 +29,11 @@ export function useCustomFieldsSchema() {
const fieldValidator = z
.array(
z.object({
+ // Absent on older rows; the view emits it, and zod would otherwise strip it.
+ active: z
+ .boolean()
+ .nullish()
+ .transform((v) => v ?? true),
dataTypeId: z.number(),
id: z.string(),
listOptions: z.array(z.string()).nullable(),
diff --git a/apps/erp/app/modules/workflows/AGENTS.md b/apps/erp/app/modules/workflows/AGENTS.md
index 235e2a31f2..08d560f932 100644
--- a/apps/erp/app/modules/workflows/AGENTS.md
+++ b/apps/erp/app/modules/workflows/AGENTS.md
@@ -8,7 +8,7 @@ The definition schema, validator, catalogs, matcher and engine all live outside
- **Workflow** — the `workflow` row. Carries `ownerId`, `active` (the on/off kill switch), and `activeVersionId` (the promoted version pointer). The pointer and the boolean are separate columns on purpose: turning a workflow off and back on restores whichever version was promoted.
- **Version** — a `workflowVersion` row holding `nodes`, `edges` and `formatVersion`. Numbered, never named.
-- **Canvas state** — `workflow.canvasState` JSONB: `{ x, y, zoom, panOnScroll }`. Per workflow (not per user, not per version), written by `$id.canvas.tsx` through `updateWorkflowCanvasState`, restored as `defaultViewport`. Node collapse is NOT here — `expanded` lives on each node in the definition and rides the autosave. Both `/save` and `/canvas` are excluded from `shouldRevalidate`; revalidating on a canvas write would snap the viewport back to where it was on load.
+- **Canvas state** — `workflow.canvasState` JSONB: `{ x, y, zoom, panOnScroll }`. Per workflow (not per user, not per version), written by `$id.canvas.tsx` through `updateWorkflowCanvasState`, restored as `defaultViewport`. Node collapse is NOT here — `expanded` lives on each node in the definition and rides the autosave. `/save`, `/canvas` and `/positions` are all excluded from `shouldRevalidate`; revalidating on a canvas write would snap the viewport back to where it was on load, and revalidating on a positions write would remount the builder store mid-drag.
- **Definition** — `{ formatVersion, nodes, edges }`, validated by `workflowDefinitionSchema` from `@carbon/workflows`. `CURRENT_DEFINITION_FORMAT_VERSION` is **3**; the SQL column default is a stale **1**, so the app always writes the constant explicitly.
- **Publish** — validate → set `activeVersionId` → set `active` → `syncWorkflowTriggers` → wake the scheduler. One route does all five; splitting them leaves a workflow that looks active and never fires.
- **The live version is read-only.** Editing a live workflow means creating a new version, the same rule released item revisions follow.
@@ -17,7 +17,7 @@ The definition schema, validator, catalogs, matcher and engine all live outside
### Always
- MUST read a version through `readWorkflowVersion(row)` from `@carbon/workflows` — the only legal read path. On `{ ok: false }` render the failure and **do not mount the canvas**; a blank canvas would let an autosave overwrite a definition nobody could see.
-- MUST call `checkWorkflowVersionLock` in every mutating route. The live-version lock is enforced server-side, not only in the UI.
+- MUST call `checkWorkflowVersionLock` in every mutating route. The live-version lock is enforced server-side, not only in the UI. The ONE deliberate exception is `$id.positions.tsx` — node positions carry no behaviour, and `updateWorkflowNodePositions` writes only `position`, only onto node ids that already exist, so that route cannot change what a workflow does even when called by hand.
- MUST write `formatVersion: CURRENT_DEFINITION_FORMAT_VERSION` on every definition write.
- MUST scope every query by `companyId`.
- MUST build version insert/update objects with every key explicitly present — PostgREST writes `NULL` for a present-but-`undefined` key, which would null `nodes`/`edges` past their `'[]'` defaults.
@@ -52,7 +52,8 @@ modules/workflows/
├── types.ts # BuilderNode / BuilderEdge React Flow aliases
├── index.ts # barrel (does NOT export workflows.server)
└── ui/
- ├── WorkflowsTable.tsx, WorkflowForm.tsx, WorkflowLockAlert.tsx
+ ├── WorkflowsTable.tsx, WorkflowForm.tsx, WorkflowLockAlert.tsx,
+ │ WorkflowActiveSwitch.tsx, WorkflowsUpgradeOverlay.tsx
├── useWorkflowsSubmodules.tsx
└── Builder/ # canvas, store, node cards, palette, versions, issues
```
@@ -67,13 +68,15 @@ Routes split in two trees: `x+/workflows+/` (list, create, rename, delete, with
- `insertWorkflowVersion` / `updateWorkflowDefinition` / `deleteWorkflowVersion`
- `updateWorkflowOwner` — takes the session user, never a submitted id
- `getWorkflowLockFlags` / `checkWorkflowVersionLock` (server) — the live-version lock
+- `updateWorkflowNodePositions` (service) — the positions-only writer behind `$id.positions.tsx`
- `publishWorkflowVersion` / `setWorkflowActive` (server) — both call `syncWorkflowTriggers`, which uses Kysely and **bypasses RLS**; the route's `requirePermissions` is the only authorization gate
## Builder Notes
- One zustand store per builder instance, vanilla `createStore` in a ref behind a context — the `DocumentTemplateEditor` idiom. React Flow keeps viewport and interaction state.
- **No undo.** Deliberate; recovery is via versions.
-- Autosave is a 1s debounce posting to `$id.save.tsx`. The route exports `shouldRevalidate` returning false for `/save` — without it every autosave re-seeds the canvas from server state mid-edit.
+- Autosave is a 1s debounce with two modes. An editable version posts the whole definition to `$id.save.tsx`; a LIVE version posts positions only, to `$id.positions.tsx`. The route exports `shouldRevalidate` returning false for both — without it every autosave re-seeds the canvas from server state mid-edit.
+- The builder store has TWO read-only reasons, not one: `canChangeDefinition` (`canEdit && !isVersionLocked`) gates config, nodes, edges and `expanded`; `canMoveNodes` (`canEdit` alone) gates dragging and auto-arrange. Movement follows PERMISSION, not the lock, so a published workflow can still be tidied. Every store mutator is gated on one of them — `updateNodeData` in particular, since every node config form funnels through it.
- **A draft saves half-filled; only publishing demands completeness.** `clauseSchema.right` and `lookupMatchSchema.value` are optional and `lookupMatchSchema.field` may be `""`, so a node the user is still filling in round-trips through `workflowDefinitionSchema` (and therefore `readWorkflowVersion`) instead of failing autosave. `validateDefinition`'s config layer is what reports each gap as `INCOMPLETE_CONFIG` and blocks publish. Never re-tighten those three fields to make a runtime path simpler — the runtime skips with a reason (`compare.ts`, `lookup.ts`) precisely so it does not have to. When `/save` does return `ok: false`, `Autosave.tsx` raises the server's `error` string as a toast and the route logs the zod issues.
- Drawn loops are blocked at connection time by `isValidConnection` + `wouldCreateCycle`. The validator's `CYCLE` check stays as the backstop.
- Converging edges are allowed: the engine is a first-arrival OR-join by design.
@@ -89,13 +92,14 @@ Routes split in two trees: `x+/workflows+/` (list, create, rename, delete, with
- `fields/control.ts` `pickControl` is the single ordered decision for which control a value renders in — `inline` (the `{` editor), `chip` (an already-picked reference) or `literal` (everything `LiteralControl` dispatches). Order matters: `choices` must disqualify the free-text rule or every enum column loses its dropdown. Add a case there, never an `if` in `ValueField`.
- `fields/Field.tsx` owns the label / required marker / issue shell. No control re-implements it.
-- Three controls, dispatched in `config/forms/ActionForm.tsx` in this order: `PairsField` when the catalog input sets `pairs`, `TemplateField` when it sets `template`, `ValueField` otherwise. Only the last consults `pickControl`. `TemplateField` is the prose editor — it takes line breaks (`multiline`, `minRows={4}`) so a JSON payload reads the way it is written; `VariableText` encodes a break as a paragraph and a `"\n"` in the stored text, so newlines survive the round trip.
+- Four controls, dispatched in `config/forms/ActionForm.tsx` in this order: `PairsField` when the catalog input sets `pairs`, `MultiChoiceField` when `isMultiSelect(input)` (`choices` on a `t.list` of text — derived, never a declared flag, so it cannot disagree with the type), `TemplateField` when it sets `template`, `ValueField` otherwise. Only the last consults `pickControl`. `TemplateField` is the prose editor — it takes line breaks (`multiline`, `minRows={4}`) so a JSON payload reads the way it is written; `VariableText` encodes a break as a paragraph and a `"\n"` in the stored text, so newlines survive the round trip.
- `fields/pairsRows.ts` holds `PairsField`'s row maths and is macro-free by the same rule as `variableMenu.ts` — the component pulls in the glossary, which vitest cannot compile. Rows are keyed by position, an emptied set is stored as absent, and per-row errors arrive as `rowIssuesForField(issues, …)` reading `<field>.entries.<n>` (`partIssuesForField` reads `<field>.parts.<n>`; a variable inside a row nests both).
+- `fields/multiChoice.ts` holds `MultiChoiceField`'s value round-trip and is macro-free for the same reason as `pairsRows.ts`. Picks are stored in the order the choices are OFFERED, not clicked (two authors ticking the same channels must produce the same definition, or autosave churns), and an emptied set stores as absent. `fields/choiceOptions.tsx` is where a choice gets its title, its description and whether it is available — the notify job skips a channel the company has no plan or integration for in SILENCE, so build time is the only place the author can be told. `choiceState` owns what renders ticked and what the author may not touch, and the two are NOT the same: a choice in `LOCKED` (`inApp`) is ticked and frozen because the platform sends it regardless, while an UNAVAILABLE choice can only never be ADDED — one already stored stays removable, or a node seeded with a channel the company has no plan for is a dead end.
- `CatalogInput.defaultValue` is seeded into `inputs` by `ActionForm` when the action is picked — nothing reads it at run time, so a required input with a default still reports `MISSING_INPUT` on a node saved before the default existed.
- `showWhen` is enforced in **two** places in `ActionForm`: the visible-input list and an early return inside `renderInput`, because a `requireOneOf` member renders through a path the list never touches. Closing a gate clears the gated input's value in the same `updateNodeData` call.
- **`{…}` is display only.** A reference is stored as `{ kind: "ref", nodeId, output, path }` and binds to the node **id**; the braces and the label are a rendering of it, so a rename never touches storage. `fields/tokenId.ts` is the only encoder/decoder and `fields/valueParts.ts` the only converter — a token label must come from `refLabel` so an inserted chip and a stored chip read identically (a mismatch trips the editor's remount check and steals focus mid-keystroke).
- Serialization rule in `valueParts.ts`: plain text stays a `literal`, a lone variable stays a bare `ref`, only mixed content becomes a `template`. Templates are legal only where a string is expected (`packages/workflows/src/definition/nodes.ts`).
-- Every field reaches variables through the same `{` trigger. `fields/VariableTreeMenu.tsx` is the only menu; it is hosted by `fields/InlineVariableMenu.tsx` (inside the ProseMirror suggestion popup) and `fields/VariableMenuPopover.tsx` (a Radix popover, for controls you cannot type a brace into — those render `fields/VariableAffordance.tsx` inside their own border). `fields/menuNav.ts` is the single keyboard implementation and is unit-tested apart from both hosts, so a key can never behave differently in one of them. `VariableTreeMenu` binds it to a **document-level capture-phase `keydown`** rather than taking keys from its host: delegating through the ProseMirror suggestion plugin (or the popover's search input) is the thing that kept breaking. Focus deliberately stays in the field so search-as-you-type keeps working; the highlighted row is `aria-selected`, not focused. The listener no-ops when the menu's own root is detached or invisible — the editor popup is *hidden*, not unmounted, on dismissal, and a menu nobody can see must not eat arrow keys. Escape is never claimed; it belongs to whichever popup is wrapping the menu.
+- Every field reaches variables through the same `{` trigger. `fields/VariableTreeMenu.tsx` is the only menu; it is hosted by `fields/InlineVariableMenu.tsx` (inside the ProseMirror suggestion popup) and `fields/VariableMenuPopover.tsx` (a Radix popover, for controls you cannot type a brace into — those render `fields/VariablePickControl.tsx` inside their own border). `fields/menuNav.ts` is the single keyboard implementation and is unit-tested apart from both hosts, so a key can never behave differently in one of them. `VariableTreeMenu` binds it to a **document-level capture-phase `keydown`** rather than taking keys from its host: delegating through the ProseMirror suggestion plugin (or the popover's search input) is the thing that kept breaking. Focus deliberately stays in the field so search-as-you-type keeps working; the highlighted row is `aria-selected`, not focused. The listener no-ops when the menu's own root is detached or invisible — the editor popup is *hidden*, not unmounted, on dismissal, and a menu nobody can see must not eat arrow keys. Escape is never claimed; it belongs to whichever popup is wrapping the menu.
- The tiptap popup mounts outside the React tree, so it can reach neither context nor a store hook. `fields/menuBridge.ts` bridges it with one module-level slot. Do not replace this with context — context does not reach a `ReactRenderer` subtree. The slot is published **on focus** (`onFocusCapture` in `InlineValueEditor`), never on mount: every value field mounts an editor, so a mount-time publish hands the slot to whichever one rendered last, and its unmount then blanks the menu for all of them. `retractVariableMenuData` only clears the slot if the caller still holds it.
- `VariableMenuPopover` uses `PopoverAnchor`, not `PopoverTrigger` — the control it wraps contains a Select and text inputs, and a trigger toggles the menu on every click that lands in any of them. `open` is therefore driven only by the field, so the menu's data must be built from an effect on `open`, not from `onOpenChange` (which never fires for a `{}`-button or typed-brace open).
- `fields/variableMenu.ts` exports both shapes: `variableTree` (browse, one level at a time) and `variableMenuItems` (the flat search index). Search matches the full `Step › output › property` breadcrumb, so it must keep coming from the flat list, not from the tree.
diff --git a/apps/erp/app/modules/workflows/ui/Builder/Autosave.tsx b/apps/erp/app/modules/workflows/ui/Builder/Autosave.tsx
index 86b13b51de..b706503cbc 100644
--- a/apps/erp/app/modules/workflows/ui/Builder/Autosave.tsx
+++ b/apps/erp/app/modules/workflows/ui/Builder/Autosave.tsx
@@ -7,7 +7,11 @@ import { fromReactFlow } from "./graph";
const DEBOUNCE_MS = 1000;
-/** Debounced autosave. Safe because the version being edited is never the live one. */
+/**
+ * Debounced autosave, in two modes. An editable version posts the whole definition to
+ * `/save`. A LIVE version posts positions only, to `/positions` — the store lets nothing
+ * else through, and `/save` would refuse it with a 409 anyway.
+ */
export function Autosave({
workflowId,
versionId
@@ -23,10 +27,13 @@ export function Autosave({
const nodes = useBuilderStore((state) => state.nodes);
const edges = useBuilderStore((state) => state.edges);
- const isReadOnly = useBuilderStore((state) => state.isReadOnly);
+ const canChangeDefinition = useBuilderStore(
+ (state) => state.canChangeDefinition
+ );
+ const canMoveNodes = useBuilderStore((state) => state.canMoveNodes);
useEffect(() => {
- if (isReadOnly) return;
+ if (!canChangeDefinition && !canMoveNodes) return;
const timer = setTimeout(() => {
const state = store.getState();
@@ -36,22 +43,50 @@ export function Autosave({
const formData = new FormData();
formData.append("versionId", versionId);
- formData.append("nodes", JSON.stringify(definition.nodes));
- formData.append("edges", JSON.stringify(definition.edges));
- formData.append("formatVersion", String(definition.formatVersion));
+
+ if (canChangeDefinition) {
+ formData.append("nodes", JSON.stringify(definition.nodes));
+ formData.append("edges", JSON.stringify(definition.edges));
+ formData.append("formatVersion", String(definition.formatVersion));
+ } else {
+ // Live version: a drag is the only thing the store let through, so positions
+ // are the only thing worth sending — and the only thing the server accepts.
+ formData.append(
+ "positions",
+ JSON.stringify(
+ Object.fromEntries(
+ definition.nodes.map((node) => [
+ node.id,
+ { x: node.position.x, y: node.position.y }
+ ])
+ )
+ )
+ );
+ }
submittedRef.current = submitted;
state.setSaveState("saving");
submit(formData, {
method: "post",
- action: path.to.workflowSave(workflowId)
+ action: canChangeDefinition
+ ? path.to.workflowSave(workflowId)
+ : path.to.workflowPositions(workflowId)
});
}, DEBOUNCE_MS);
return () => clearTimeout(timer);
// `fetcher` is deliberately not a dependency — its identity changes on every
// state tick, which would restart the debounce forever.
- }, [nodes, edges, isReadOnly, store, versionId, workflowId, submit]);
+ }, [
+ nodes,
+ edges,
+ canChangeDefinition,
+ canMoveNodes,
+ store,
+ versionId,
+ workflowId,
+ submit
+ ]);
useEffect(() => {
const submitted = submittedRef.current;
diff --git a/apps/erp/app/modules/workflows/ui/Builder/BuilderControls.tsx b/apps/erp/app/modules/workflows/ui/Builder/BuilderControls.tsx
index 1e7acf879e..8d62726a08 100644
--- a/apps/erp/app/modules/workflows/ui/Builder/BuilderControls.tsx
+++ b/apps/erp/app/modules/workflows/ui/Builder/BuilderControls.tsx
@@ -64,7 +64,8 @@ export function BuilderControls({ panOnScroll, onTogglePanOnScroll }: Props) {
const allExpanded = useBuilderStore((s) =>
s.nodes.every((n) => n.expanded !== false)
);
- const isReadOnly = useBuilderStore((s) => s.isReadOnly);
+ const canChangeDefinition = useBuilderStore((s) => s.canChangeDefinition);
+ const canMoveNodes = useBuilderStore((s) => s.canMoveNodes);
return (
// One Panel owns the whole bottom-right overlay. The minimap is a Panel of its
@@ -90,7 +91,7 @@ export function BuilderControls({ panOnScroll, onTogglePanOnScroll }: Props) {
<ControlButton
aria-label={t`Auto arrange`}
icon={<LuNetwork />}
- isDisabled={isReadOnly}
+ isDisabled={!canMoveNodes}
onClick={autoArrange}
/>
<ControlButton
@@ -98,6 +99,8 @@ export function BuilderControls({ panOnScroll, onTogglePanOnScroll }: Props) {
icon={allExpanded ? <LuMinimize2 /> : <LuMaximize2 />}
aria-pressed={!allExpanded}
className={cn(!allExpanded && "bg-muted")}
+ // `expanded` is part of the persisted definition, so this is an edit.
+ isDisabled={!canChangeDefinition}
onClick={() => expandAll(!allExpanded)}
/>
<div className="mx-0.5 h-4 w-px bg-border" />
diff --git a/apps/erp/app/modules/workflows/ui/Builder/BuilderHeader.tsx b/apps/erp/app/modules/workflows/ui/Builder/BuilderHeader.tsx
index cf4e054b0b..d0d6cd78e9 100644
--- a/apps/erp/app/modules/workflows/ui/Builder/BuilderHeader.tsx
+++ b/apps/erp/app/modules/workflows/ui/Builder/BuilderHeader.tsx
@@ -136,7 +136,11 @@ export function BuilderHeader({
const { t } = useLingui();
const permissions = usePermissions();
const store = useBuilderStoreApi();
- const isReadOnly = useBuilderStore((state) => state.isReadOnly);
+ // The lock glyph means "this is the live version"; the tooltip below distinguishes
+ // that from simply lacking permission.
+ const isVersionLocked = useBuilderStore((state) => state.isVersionLocked);
+ const canEdit = useBuilderStore((state) => state.canEdit);
+ const isReadOnly = isVersionLocked || !canEdit;
const publishFetcher = useFetcher<{
ok?: boolean;
diff --git a/apps/erp/app/modules/workflows/ui/Builder/LiveValidation.tsx b/apps/erp/app/modules/workflows/ui/Builder/LiveValidation.tsx
index cd0e497800..9b15207fe8 100644
--- a/apps/erp/app/modules/workflows/ui/Builder/LiveValidation.tsx
+++ b/apps/erp/app/modules/workflows/ui/Builder/LiveValidation.tsx
@@ -1,6 +1,6 @@
import { referenceIssues } from "@carbon/workflows";
import { useEffect } from "react";
-import { catalog } from "./catalog";
+import { useWorkflowCatalog } from "./catalog";
import { useBuilderStore, useBuilderStoreApi } from "./context";
import { fromReactFlow } from "./graph";
import { batchPlansFor } from "./useDefinition";
@@ -15,6 +15,7 @@ const DEBOUNCE_MS = 250;
*/
export function LiveValidation() {
const store = useBuilderStoreApi();
+ const catalog = useWorkflowCatalog();
const nodes = useBuilderStore((state) => state.nodes);
const edges = useBuilderStore((state) => state.edges);
@@ -25,11 +26,11 @@ export function LiveValidation() {
const definition = fromReactFlow(nodes, edges);
const state = store.getState();
state.setLiveIssues(referenceIssues(definition, catalog));
- state.setBatchPlans(batchPlansFor(definition));
+ state.setBatchPlans(batchPlansFor(definition, catalog));
}, DEBOUNCE_MS);
return () => clearTimeout(timer);
- }, [nodes, edges, store]);
+ }, [nodes, edges, store, catalog]);
return null;
}
diff --git a/apps/erp/app/modules/workflows/ui/Builder/TestRun/TestRunDialog.tsx b/apps/erp/app/modules/workflows/ui/Builder/TestRun/TestRunDialog.tsx
index 662e65afc7..4b04c18510 100644
--- a/apps/erp/app/modules/workflows/ui/Builder/TestRun/TestRunDialog.tsx
+++ b/apps/erp/app/modules/workflows/ui/Builder/TestRun/TestRunDialog.tsx
@@ -17,7 +17,7 @@ import { Trans, useLingui } from "@lingui/react/macro";
import { useCallback, useEffect, useMemo, useState } from "react";
import { useFetcher } from "react-router";
import { path } from "~/utils/path";
-import { catalog, useWorkflowLabel } from "../catalog";
+import { useWorkflowCatalog, useWorkflowEventLabel } from "../catalog";
import { useBuilderStore, useBuilderStoreApi } from "../context";
import { humanizeField } from "../nodes/meta";
import type { TestRunResult } from "../store";
@@ -115,7 +115,8 @@ function Dialog({
onRun: (formData: FormData) => void;
}) {
const { t } = useLingui();
- const label = useWorkflowLabel();
+ const eventLabel = useWorkflowEventLabel();
+ const catalog = useWorkflowCatalog();
const closeTestRun = useBuilderStore((s) => s.closeTestRun);
const definition = useDefinition();
@@ -202,7 +203,7 @@ function Dialog({
value={eventId}
options={events.map((id) => ({
value: id,
- label: label(id)
+ label: eventLabel(id)
}))}
onChange={(next) => {
setEventId(next);
diff --git a/apps/erp/app/modules/workflows/ui/Builder/WorkflowBuilder.tsx b/apps/erp/app/modules/workflows/ui/Builder/WorkflowBuilder.tsx
index 53843fd6d6..90863e6b48 100644
--- a/apps/erp/app/modules/workflows/ui/Builder/WorkflowBuilder.tsx
+++ b/apps/erp/app/modules/workflows/ui/Builder/WorkflowBuilder.tsx
@@ -55,7 +55,11 @@ export function WorkflowBuilder({
const nodes = useBuilderStore((state) => state.nodes);
const edges = useBuilderStore((state) => state.edges);
- const isReadOnly = useBuilderStore((state) => state.isReadOnly);
+ const canChangeDefinition = useBuilderStore(
+ (state) => state.canChangeDefinition
+ );
+ const canMoveNodes = useBuilderStore((state) => state.canMoveNodes);
+ const isReadOnly = !canChangeDefinition;
const showResults = useBuilderStore(
(state) => state.testRunStatus === "running" || state.testRunResult !== null
);
@@ -154,7 +158,7 @@ export function WorkflowBuilder({
? { defaultViewport: initialViewport }
: { fitView: true })}
onMoveEnd={onMoveEnd}
- nodesDraggable={!isReadOnly}
+ nodesDraggable={canMoveNodes}
nodesConnectable={!isReadOnly}
elementsSelectable
// Delete only. Backspace is too easy to hit by accident, and there
@@ -165,7 +169,7 @@ export function WorkflowBuilder({
panOnScroll={panOnScroll}
zoomOnScroll={!panOnScroll}
>
- <Background variant={BackgroundVariant.Dots} gap={16} />
+ <Background variant={BackgroundVariant.Dots} gap={24} size={1} />
<BuilderControls
panOnScroll={panOnScroll}
onTogglePanOnScroll={togglePanOnScroll}
diff --git a/apps/erp/app/modules/workflows/ui/Builder/catalog.ts b/apps/erp/app/modules/workflows/ui/Builder/catalog.ts
index a45b146d64..d3c22ef7c9 100644
--- a/apps/erp/app/modules/workflows/ui/Builder/catalog.ts
+++ b/apps/erp/app/modules/workflows/ui/Builder/catalog.ts
@@ -1,11 +1,37 @@
import type { TermId } from "@carbon/glossary";
-import { createWorkflowCatalog } from "@carbon/workflows";
+import type { WorkflowCatalog } from "@carbon/workflows";
+import {
+ buildCatalogOverlay,
+ CUSTOM_FIELD_PREFIX,
+ createWorkflowCatalog,
+ parseCustomFieldEventId
+} from "@carbon/workflows";
import { WORKFLOW_FIELD_HELP } from "@carbon/workflows/help";
import { WORKFLOW_LABELS } from "@carbon/workflows/labels";
import { useLingui } from "@lingui/react";
+import { useLingui as useLinguiMacro } from "@lingui/react/macro";
+import { useMemo } from "react";
+import { useCustomFieldsSchema } from "~/hooks/useCustomFieldsSchema";
-/** One instance for the whole builder; the catalog is immutable committed data. */
-export const catalog = createWorkflowCatalog();
+/** The company's catalog: shipped entries plus this company's custom fields.
+ * There is deliberately no module singleton — a call site that forgets the hook is a
+ * compile error, not a picker that quietly lists no custom fields. */
+export function useWorkflowCatalog(): WorkflowCatalog {
+ const schemas = useCustomFieldsSchema();
+ return useMemo(() => {
+ const defs = Object.entries(schemas).flatMap(([table, fields]) =>
+ (fields ?? []).map((field) => ({
+ table,
+ id: field.id,
+ name: field.name,
+ dataTypeId: field.dataTypeId,
+ listOptions: field.listOptions,
+ active: field.active
+ }))
+ );
+ return createWorkflowCatalog(buildCatalogOverlay(defs));
+ }, [schemas]);
+}
/** Translates a catalog label key; falls back to the key's last segment when absent. */
export function useWorkflowLabel(): (key: string, fallback?: string) => string {
@@ -19,6 +45,42 @@ export function useWorkflowLabel(): (key: string, fallback?: string) => string {
};
}
+/** Names a trigger event. A custom field has no shipped label, so the sentence is built
+ * here from the customer's own field name — one resolver, so the picker, the node card
+ * and the run list can never name the same trigger three ways. */
+export function useWorkflowEventLabel(): (
+ id: string,
+ fallback?: string
+) => string {
+ const label = useWorkflowLabel();
+ const catalog = useWorkflowCatalog();
+ const { t } = useLinguiMacro();
+
+ return (id: string, fallback?: string) => {
+ const custom = parseCustomFieldEventId(id);
+ if (custom === undefined) return label(id, fallback);
+ const name =
+ catalog.getPropertyLabel(custom.entity, custom.property) ??
+ custom.property.slice(CUSTOM_FIELD_PREFIX.length);
+ return t`When ${name} changes`;
+ };
+}
+
+/** Custom-field property path -> the customer's own field name. A field id is unique, so
+ * one map names a path segment without resolving what type it hangs off. */
+export function useCustomFieldLabels(): Record<string, string> {
+ const schemas = useCustomFieldsSchema();
+ return useMemo(() => {
+ const labels: Record<string, string> = {};
+ for (const fields of Object.values(schemas)) {
+ for (const field of fields ?? []) {
+ labels[`${CUSTOM_FIELD_PREFIX}${field.id}`] = field.name;
+ }
+ }
+ return labels;
+ }, [schemas]);
+}
+
/** Glossary term for a catalog input key, or undefined when the field has no help. */
export function workflowFieldHelp(key: string): TermId | undefined {
return WORKFLOW_FIELD_HELP[key];
diff --git a/apps/erp/app/modules/workflows/ui/Builder/config/ClauseRow.tsx b/apps/erp/app/modules/workflows/ui/Builder/config/ClauseRow.tsx
index 45d155720c..d3384c3d80 100644
--- a/apps/erp/app/modules/workflows/ui/Builder/config/ClauseRow.tsx
+++ b/apps/erp/app/modules/workflows/ui/Builder/config/ClauseRow.tsx
@@ -7,7 +7,11 @@ import type React from "react";
import { memo, useEffect, useMemo } from "react";
import { LuX } from "react-icons/lu";
import OperatorCombobox from "~/modules/storage-rules/ui/OperatorCombobox";
-import { catalog, propertyLabelKey, useWorkflowLabel } from "../catalog";
+import {
+ propertyLabelKey,
+ useWorkflowCatalog,
+ useWorkflowLabel
+} from "../catalog";
import { Field } from "../fields/Field";
import type { FieldContext } from "../fields/types";
import { ValueField } from "../fields/ValueField";
@@ -51,6 +55,8 @@ type ClauseRowProps = {
/** Validator field path for this row, e.g. `clauses.0` or `paths.<id>.clauses.0`. */
fieldPath: string;
issues?: WorkflowIssue[];
+ /** The version is published: show the value, refuse every edit. */
+ isReadOnly?: boolean;
};
function ClauseRowImpl({
@@ -64,10 +70,12 @@ function ClauseRowImpl({
entity,
grip,
fieldPath,
- issues
+ issues,
+ isReadOnly
}: ClauseRowProps) {
const { t } = useLingui();
const label = useWorkflowLabel();
+ const catalog = useWorkflowCatalog();
const typeOfValue = useValueTypeResolver(context.nodeId);
// Derive the left operand's type for operator selection
@@ -85,7 +93,7 @@ function ClauseRowImpl({
// "value" mode: a literal carries its own type, but a picked variable is a
// reference and has to be resolved against the graph.
return clause.left ? typeOfValue(clause.left) : undefined;
- }, [leftMode, clause.left, entity, typeOfValue]);
+ }, [leftMode, clause.left, entity, typeOfValue, catalog]);
const availableOps = useMemo<readonly Operator[]>(
() => (leftType ? operatorsForType(leftType) : []),
@@ -107,11 +115,15 @@ function ClauseRowImpl({
if (leftMode !== "column" || !entity) return [];
return Object.entries(catalog.getEntity(entity)?.properties ?? {}).map(
([col]) => ({
- label: label(propertyLabelKey(entity, col), col),
+ // A custom field has no translated key — fall back to the customer's own name.
+ label: label(
+ propertyLabelKey(entity, col),
+ catalog.getPropertyLabel(entity, col) ?? col
+ ),
value: col
})
);
- }, [leftMode, entity, label]);
+ }, [leftMode, entity, label, catalog]);
const currentColumn =
leftMode === "column" &&
@@ -126,7 +138,7 @@ function ClauseRowImpl({
leftMode === "column" && entity && currentColumn
? catalog.getEnum(entity, currentColumn)
: undefined,
- [leftMode, entity, currentColumn]
+ [leftMode, entity, currentColumn, catalog]
);
return (
@@ -143,6 +155,7 @@ function ClauseRowImpl({
placeholder={t`Pick a property`}
value={currentColumn}
options={columnOptions}
+ isReadOnly={isReadOnly}
onChange={(col) => {
const colType = entity
? catalog.getEntity(entity)?.properties[col]
@@ -192,6 +205,7 @@ function ClauseRowImpl({
`${fieldPath}.left`,
`${fieldPath}.field`
)}
+ isReadOnly={isReadOnly}
/>
)}
@@ -205,7 +219,7 @@ function ClauseRowImpl({
})
}
available={Array.from(availableOps)}
- disabled={!leftType}
+ disabled={!leftType || isReadOnly}
/>
</Field>
@@ -228,6 +242,7 @@ function ClauseRowImpl({
`${fieldPath}.right`,
`${fieldPath}.value`
)}
+ isReadOnly={isReadOnly}
/>
) : (
<Field label={t`Value`}>
@@ -245,7 +260,7 @@ function ClauseRowImpl({
variant="ghost"
size="sm"
onClick={() => onRemove(index)}
- isDisabled={!canRemove}
+ isDisabled={!canRemove || isReadOnly}
className={cn(
"shrink-0",
!canRemove && "opacity-0 pointer-events-none"
diff --git a/apps/erp/app/modules/workflows/ui/Builder/config/CombinatorToggle.tsx b/apps/erp/app/modules/workflows/ui/Builder/config/CombinatorToggle.tsx
index b32eccf34a..4fae9ed763 100644
--- a/apps/erp/app/modules/workflows/ui/Builder/config/CombinatorToggle.tsx
+++ b/apps/erp/app/modules/workflows/ui/Builder/config/CombinatorToggle.tsx
@@ -4,9 +4,11 @@ import { Trans } from "@lingui/react/macro";
type Props = {
value: "and" | "or";
onChange: (v: "and" | "or") => void;
+ /** The version is published: show the value, refuse every edit. */
+ isReadOnly?: boolean;
};
-export function CombinatorToggle({ value, onChange }: Props) {
+export function CombinatorToggle({ value, onChange, isReadOnly }: Props) {
return (
<ToggleGroup
type="single"
@@ -14,16 +16,19 @@ export function CombinatorToggle({ value, onChange }: Props) {
onValueChange={(v) => {
if (v === "and" || v === "or") onChange(v);
}}
+ disabled={isReadOnly}
className={cn("nodrag nopan gap-0 rounded-md border text-[10px]")}
>
<ToggleGroupItem
value="and"
+ disabled={isReadOnly}
className="h-5 rounded-l-md rounded-r-none border-r px-1.5 text-[10px] data-[state=on]:bg-primary data-[state=on]:text-primary-foreground"
>
<Trans>AND</Trans>
</ToggleGroupItem>
<ToggleGroupItem
value="or"
+ disabled={isReadOnly}
className="h-5 rounded-l-none rounded-r-md px-1.5 text-[10px] data-[state=on]:bg-primary data-[state=on]:text-primary-foreground"
>
<Trans>OR</Trans>
diff --git a/apps/erp/app/modules/workflows/ui/Builder/config/forms/ActionForm.tsx b/apps/erp/app/modules/workflows/ui/Builder/config/forms/ActionForm.tsx
index 01b9ef07bd..7d08929673 100644
--- a/apps/erp/app/modules/workflows/ui/Builder/config/forms/ActionForm.tsx
+++ b/apps/erp/app/modules/workflows/ui/Builder/config/forms/ActionForm.tsx
@@ -15,8 +15,9 @@ import {
SelectTrigger,
SelectValue
} from "@carbon/react";
-import type { ValueOrRef, ValueType } from "@carbon/workflows";
+import type { ValueOrRef, ValueType, WorkflowCatalog } from "@carbon/workflows";
import {
+ isMultiSelect,
MAX_LIST_ITEMS,
WORKFLOW_ACTION_CATALOG,
WORKFLOW_ENTITY_REGISTRY
@@ -26,12 +27,14 @@ import { useMemo, useState } from "react";
import { LuCheck, LuChevronsUpDown, LuListOrdered } from "react-icons/lu";
import {
actionInputLabelKey,
- catalog,
entityLabelKey,
+ useWorkflowCatalog,
useWorkflowLabel,
workflowFieldHelp
} from "../../catalog";
import { useBuilderStore } from "../../context";
+import { lockedChoices, useChoiceOptions } from "../../fields/choiceOptions";
+import { MultiChoiceField } from "../../fields/MultiChoiceField";
import { PairsField } from "../../fields/PairsField";
import { TemplateField } from "../../fields/TemplateField";
import { ValueField } from "../../fields/ValueField";
@@ -62,7 +65,10 @@ function isGateOpen(gate: Gate, inputs: Record<string, ValueOrRef>): boolean {
return gate.equals.includes(target.value);
}
-function seededInputs(actionId: string): Record<string, ValueOrRef> {
+function seededInputs(
+ actionId: string,
+ catalog: WorkflowCatalog
+): Record<string, ValueOrRef> {
const seeded: Record<string, ValueOrRef> = {};
const def = catalog.getAction(actionId);
for (const [name, input] of Object.entries(def?.inputs ?? {})) {
@@ -95,13 +101,15 @@ type ActionPickerProps = {
onSelect: (id: string) => void;
upstreamEntities: Set<string>;
label: (key: string) => string;
+ isReadOnly?: boolean;
};
function ActionPicker({
selected,
onSelect,
upstreamEntities,
- label
+ label,
+ isReadOnly
}: ActionPickerProps) {
const { t } = useLingui();
const [open, setOpen] = useState(false);
@@ -124,6 +132,7 @@ function ActionPicker({
<PopoverTrigger asChild>
<button
type="button"
+ disabled={isReadOnly}
className="flex w-full items-center justify-between rounded-md border bg-background px-3 py-2 text-sm hover:bg-muted/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
>
<span
@@ -141,7 +150,10 @@ function ActionPicker({
onTouchMove={(e) => e.stopPropagation()}
>
<Command>
- <CommandInput placeholder={t`Search actions…`} />
+ <CommandInput
+ placeholder={t`Search actions…`}
+ disabled={isReadOnly}
+ />
<CommandList className="max-h-64 overflow-auto scrollbar-thin scrollbar-track-transparent scrollbar-thumb-accent">
<CommandEmpty>
<Trans>No actions found.</Trans>
@@ -153,6 +165,7 @@ function ActionPicker({
<CommandItem
key={id}
value={`${id} ${label(id)}`}
+ disabled={isReadOnly}
onSelect={() => {
onSelect(id);
setOpen(false);
@@ -184,6 +197,7 @@ type NotifyAboutFieldProps = {
inputs: Record<string, ValueOrRef>;
onInputChange: (name: string, value: ValueOrRef | undefined) => void;
inLoop: boolean;
+ isReadOnly?: boolean;
};
/** The only hand-written field: notify names its subject in two loose strings because
@@ -192,7 +206,8 @@ function NotifyAboutField({
nodeId,
inputs,
onInputChange,
- inLoop
+ inLoop,
+ isReadOnly
}: NotifyAboutFieldProps) {
const { t } = useLingui();
const label = useWorkflowLabel();
@@ -224,8 +239,12 @@ function NotifyAboutField({
<label className="text-sm font-medium text-foreground">
<Trans>About</Trans>
</label>
- <Select value={aboutType ?? ""} onValueChange={handleTypeChange}>
- <SelectTrigger className="w-full">
+ <Select
+ value={aboutType ?? ""}
+ onValueChange={handleTypeChange}
+ disabled={isReadOnly}
+ >
+ <SelectTrigger className="w-full" disabled={isReadOnly}>
<SelectValue placeholder={t`Pick a record type…`} />
</SelectTrigger>
<SelectContent>
@@ -243,6 +262,7 @@ function NotifyAboutField({
value={aboutId}
onChange={(v) => onInputChange("aboutId", v)}
context={{ nodeId, inLoop }}
+ isReadOnly={isReadOnly}
/>
)}
</div>
@@ -251,13 +271,27 @@ function NotifyAboutField({
// ── ActionForm ────────────────────────────────────────────────────────────────
-export function ActionForm({ node, issues }: NodeFormProps<"action">) {
+export function ActionForm({
+ node,
+ issues,
+ isReadOnly
+}: NodeFormProps<"action">) {
const updateNodeData = useBuilderStore((s) => s.updateNodeData);
const label = useWorkflowLabel();
+ const catalog = useWorkflowCatalog();
+ const choiceOptions = useChoiceOptions();
const { action: actionId, inputs } = node.data;
const actionDef = actionId ? catalog.getAction(actionId) : undefined;
+
+ // A custom-field input has no translated key — fall back to the customer's own name.
+ const inputLabel = (name: string) =>
+ label(
+ actionInputLabelKey(actionId, name),
+ catalog.getInputLabel(actionId, name) ?? name
+ );
+
const batch = useActionBatchPlan(node.id, actionId, inputs);
const isBatch = batch.kind === "repeats";
@@ -291,19 +325,11 @@ export function ActionForm({ node, issues }: NodeFormProps<"action">) {
return init;
});
- // Hidden inputs — members of requireOneOf groups that aren't active
- const hiddenInputs = useMemo(() => {
- const hidden = new Set<string>();
- for (let i = 0; i < requireOneOf.length; i++) {
- const group = requireOneOf[i];
- if (!group) continue;
- const active = groupSelections[i];
- for (const name of group) {
- if (name !== active) hidden.add(name);
- }
- }
- return hidden;
- }, [requireOneOf, groupSelections]);
+ // Each group's own block renders its active member, so the ordinary Inputs list skips them all.
+ const groupOwnedInputs = useMemo(
+ () => new Set((actionDef?.requireOneOf ?? []).flat()),
+ [actionDef]
+ );
// The about inputs are handled by NotifyAboutField, skip them in the normal loop
const isNotify = actionId === "notify";
@@ -312,7 +338,7 @@ export function ActionForm({ node, issues }: NodeFormProps<"action">) {
// ── event handlers ──────────────────────────────────────────────────────────
function handleActionSelect(id: string) {
- updateNodeData(node.id, { action: id, inputs: seededInputs(id) });
+ updateNodeData(node.id, { action: id, inputs: seededInputs(id, catalog) });
// Reset group selections for the new action
const newDef = catalog.getAction(id);
const newGroups = newDef?.requireOneOf ?? [];
@@ -356,7 +382,7 @@ export function ActionForm({ node, issues }: NodeFormProps<"action">) {
if (!inputDef) return null;
// Also guarded in the list below; a requireOneOf member reaches here without it.
if (!isGateOpen(inputDef.showWhen, inputs)) return null;
- const inputLabel = label(actionInputLabelKey(actionId, name), name);
+ const fieldLabel = inputLabel(name);
const inputHelp = workflowFieldHelp(actionInputLabelKey(actionId, name));
const fieldContext = {
nodeId: node.id,
@@ -370,7 +396,7 @@ export function ActionForm({ node, issues }: NodeFormProps<"action">) {
return (
<PairsField
key={name}
- label={inputLabel}
+ label={fieldLabel}
helpTermId={inputHelp}
type={inputDef.type}
required={inputDef.required}
@@ -379,6 +405,25 @@ export function ActionForm({ node, issues }: NodeFormProps<"action">) {
context={fieldContext}
issue={fieldIssue}
partIssues={rowIssuesForField(issues, name, `inputs.${name}`)}
+ isReadOnly={isReadOnly}
+ />
+ );
+ }
+
+ if (isMultiSelect(inputDef)) {
+ return (
+ <MultiChoiceField
+ key={name}
+ label={fieldLabel}
+ helpTermId={inputHelp}
+ type={inputDef.type}
+ required={inputDef.required}
+ options={choiceOptions(inputDef.choices)}
+ locked={lockedChoices(inputDef.choices)}
+ value={inputs[name]}
+ onChange={(v) => handleInputChange(name, v)}
+ issue={fieldIssue}
+ isReadOnly={isReadOnly}
/>
);
}
@@ -387,7 +432,7 @@ export function ActionForm({ node, issues }: NodeFormProps<"action">) {
return (
<TemplateField
key={name}
- label={inputLabel}
+ label={fieldLabel}
helpTermId={inputHelp}
type={inputDef.type}
required={inputDef.required}
@@ -396,6 +441,7 @@ export function ActionForm({ node, issues }: NodeFormProps<"action">) {
context={fieldContext}
issue={fieldIssue}
partIssues={fieldParts}
+ isReadOnly={isReadOnly}
/>
);
}
@@ -403,7 +449,7 @@ export function ActionForm({ node, issues }: NodeFormProps<"action">) {
return (
<ValueField
key={name}
- label={inputLabel}
+ label={fieldLabel}
helpTermId={inputHelp}
type={inputDef.type}
required={inputDef.required}
@@ -413,23 +459,38 @@ export function ActionForm({ node, issues }: NodeFormProps<"action">) {
context={fieldContext}
issue={fieldIssue}
partIssues={fieldParts}
+ isReadOnly={isReadOnly}
/>
);
}
+ /** Rendered directly under the action picker rather than with the rest: a multi-select
+ * qualifies the action itself (how a notification is delivered), so it belongs beside
+ * the action, not below the recipient and the message. */
+ const modeInputNames = useMemo(() => {
+ if (!actionDef) return [];
+ return Object.entries(actionDef.inputs)
+ .filter(([name, inputDef]) => {
+ if (groupOwnedInputs.has(name) || skipInputs.has(name)) return false;
+ return isMultiSelect(inputDef);
+ })
+ .map(([name]) => name);
+ }, [actionDef, groupOwnedInputs, skipInputs]);
+
// Sort inputs: required first, then optional (preserving catalog order within each)
const visibleInputNames = useMemo(() => {
if (!actionDef) return [];
const required: string[] = [];
const optional: string[] = [];
for (const [name, inputDef] of Object.entries(actionDef.inputs)) {
- if (hiddenInputs.has(name) || skipInputs.has(name)) continue;
+ if (groupOwnedInputs.has(name) || skipInputs.has(name)) continue;
+ if (modeInputNames.includes(name)) continue;
if (!isGateOpen(inputDef.showWhen, inputs)) continue;
if (inputDef.required) required.push(name);
else optional.push(name);
}
return [...required, ...optional];
- }, [actionDef, hiddenInputs, skipInputs, inputs]);
+ }, [actionDef, groupOwnedInputs, skipInputs, modeInputNames, inputs]);
// ── render ──────────────────────────────────────────────────────────────────
@@ -445,11 +506,18 @@ export function ActionForm({ node, issues }: NodeFormProps<"action">) {
onSelect={handleActionSelect}
upstreamEntities={upstreamEntities}
label={label}
+ isReadOnly={isReadOnly}
/>
</div>
{actionDef && (
<>
+ {modeInputNames.length > 0 && (
+ <div className="space-y-3">
+ {modeInputNames.map((name) => renderInput(name))}
+ </div>
+ )}
+
{/* requireOneOf group selectors */}
{requireOneOf.map((group, i) => (
<div key={i} className="space-y-1">
@@ -461,6 +529,7 @@ export function ActionForm({ node, issues }: NodeFormProps<"action">) {
<button
key={name}
type="button"
+ disabled={isReadOnly}
className={cn(
"flex-1 px-3 py-2 text-sm transition-colors",
groupSelections[i] === name
@@ -470,7 +539,7 @@ export function ActionForm({ node, issues }: NodeFormProps<"action">) {
)}
onClick={() => handleGroupSwitch(i, name)}
>
- {label(actionInputLabelKey(actionId, name), name)}
+ {inputLabel(name)}
</button>
))}
</div>
@@ -502,6 +571,7 @@ export function ActionForm({ node, issues }: NodeFormProps<"action">) {
inputs={inputs}
onInputChange={handleInputChange}
inLoop={isBatch}
+ isReadOnly={isReadOnly}
/>
</div>
)}
@@ -513,13 +583,8 @@ export function ActionForm({ node, issues }: NodeFormProps<"action">) {
<LuListOrdered className="mt-0.5 h-4 w-4 shrink-0 text-muted-foreground" />
<p className="text-muted-foreground">
<Trans>
- A list is wired into{" "}
- {label(
- actionInputLabelKey(actionId, batch.input),
- batch.input
- )}
- , so this step runs once for each item in it — up to{" "}
- {MAX_LIST_ITEMS}.
+ A list is wired into {inputLabel(batch.input)}, so this step
+ runs once for each item in it — up to {MAX_LIST_ITEMS}.
</Trans>
</p>
</div>
@@ -530,18 +595,9 @@ export function ActionForm({ node, issues }: NodeFormProps<"action">) {
<LuListOrdered className="mt-0.5 h-4 w-4 shrink-0 text-destructive" />
<p className="text-destructive">
<Trans>
- Lists are wired into both{" "}
- {label(
- actionInputLabelKey(actionId, batch.first),
- batch.first
- )}{" "}
- and{" "}
- {label(
- actionInputLabelKey(actionId, batch.second),
- batch.second
- )}
- , so this step cannot tell which one to repeat over. Leave a
- list on only one of them.
+ Lists are wired into both {inputLabel(batch.first)} and{" "}
+ {inputLabel(batch.second)}, so this step cannot tell which one
+ to repeat over. Leave a list on only one of them.
</Trans>
</p>
</div>
diff --git a/apps/erp/app/modules/workflows/ui/Builder/config/forms/ComputeForm.tsx b/apps/erp/app/modules/workflows/ui/Builder/config/forms/ComputeForm.tsx
index 163cc27d22..6dc05b099c 100644
--- a/apps/erp/app/modules/workflows/ui/Builder/config/forms/ComputeForm.tsx
+++ b/apps/erp/app/modules/workflows/ui/Builder/config/forms/ComputeForm.tsx
@@ -16,10 +16,10 @@ import { Trans, useLingui } from "@lingui/react/macro";
import { useMemo, useState } from "react";
import { LuCheck, LuChevronsUpDown, LuListOrdered } from "react-icons/lu";
import {
- catalog,
describeValueType,
entityLabelKey,
operationInputLabelKey,
+ useWorkflowCatalog,
useWorkflowLabel,
workflowFieldHelp
} from "../../catalog";
@@ -36,9 +36,15 @@ type OperationPickerProps = {
selected: string;
onSelect: (id: string) => void;
label: (key: string, fallback?: string) => string;
+ isReadOnly?: boolean;
};
-function OperationPicker({ selected, onSelect, label }: OperationPickerProps) {
+function OperationPicker({
+ selected,
+ onSelect,
+ label,
+ isReadOnly
+}: OperationPickerProps) {
const { t } = useLingui();
const [open, setOpen] = useState(false);
@@ -61,6 +67,7 @@ function OperationPicker({ selected, onSelect, label }: OperationPickerProps) {
<PopoverTrigger asChild>
<button
type="button"
+ disabled={isReadOnly}
className="flex w-full items-center justify-between rounded-md border bg-background px-3 py-2 text-sm hover:bg-muted/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
>
<span
@@ -78,7 +85,10 @@ function OperationPicker({ selected, onSelect, label }: OperationPickerProps) {
onTouchMove={(e) => e.stopPropagation()}
>
<Command>
- <CommandInput placeholder={t`Search operations…`} />
+ <CommandInput
+ placeholder={t`Search operations…`}
+ disabled={isReadOnly}
+ />
<CommandList className="max-h-64 overflow-auto scrollbar-thin scrollbar-track-transparent scrollbar-thumb-accent">
<CommandEmpty>
<Trans>No operations found.</Trans>
@@ -92,6 +102,7 @@ function OperationPicker({ selected, onSelect, label }: OperationPickerProps) {
<CommandItem
key={id}
value={`${id} ${label(id)}`}
+ disabled={isReadOnly}
onSelect={() => {
onSelect(id);
setOpen(false);
@@ -117,9 +128,14 @@ function OperationPicker({ selected, onSelect, label }: OperationPickerProps) {
// ── ComputeForm ───────────────────────────────────────────────────────────────
-export function ComputeForm({ node, issues }: NodeFormProps<"compute">) {
+export function ComputeForm({
+ node,
+ issues,
+ isReadOnly
+}: NodeFormProps<"compute">) {
const updateNodeData = useBuilderStore((s) => s.updateNodeData);
const label = useWorkflowLabel();
+ const catalog = useWorkflowCatalog();
const { operation: operationId, inputs } = node.data;
@@ -167,6 +183,7 @@ export function ComputeForm({ node, issues }: NodeFormProps<"compute">) {
selected={operationId}
onSelect={handleOperationSelect}
label={label}
+ isReadOnly={isReadOnly}
/>
</div>
@@ -198,6 +215,7 @@ export function ComputeForm({ node, issues }: NodeFormProps<"compute">) {
context={{ nodeId: node.id, inLoop: false }}
issue={issueForField(issues, name, `inputs.${name}`)}
partIssues={partIssuesForField(issues, name, `inputs.${name}`)}
+ isReadOnly={isReadOnly}
/>
);
})}
diff --git a/apps/erp/app/modules/workflows/ui/Builder/config/forms/ConditionForm.tsx b/apps/erp/app/modules/workflows/ui/Builder/config/forms/ConditionForm.tsx
index 8d5eaa88ee..302c0f7ea9 100644
--- a/apps/erp/app/modules/workflows/ui/Builder/config/forms/ConditionForm.tsx
+++ b/apps/erp/app/modules/workflows/ui/Builder/config/forms/ConditionForm.tsx
@@ -53,6 +53,7 @@ type SortableClauseItemProps = {
onCombinatorChange: (v: "and" | "or") => void;
fieldPath: string;
issues?: WorkflowIssue[];
+ isReadOnly?: boolean;
};
function SortableClauseItem({
@@ -67,7 +68,8 @@ function SortableClauseItem({
isLast,
onCombinatorChange,
fieldPath,
- issues
+ issues,
+ isReadOnly
}: SortableClauseItemProps) {
const { t } = useLingui();
const {
@@ -77,7 +79,7 @@ function SortableClauseItem({
transform,
transition,
isDragging
- } = useSortable({ id: sortId });
+ } = useSortable({ id: sortId, disabled: isReadOnly });
const style = {
transform: CSS.Transform.toString(transform),
@@ -89,6 +91,7 @@ function SortableClauseItem({
<button
type="button"
aria-label={t`Drag to reorder`}
+ disabled={isReadOnly}
className="nodrag nopan flex h-8 w-5 shrink-0 cursor-grab items-center justify-center text-muted-foreground active:cursor-grabbing"
{...attributes}
{...listeners}
@@ -109,17 +112,26 @@ function SortableClauseItem({
grip={grip}
fieldPath={fieldPath}
issues={issues}
+ isReadOnly={isReadOnly}
/>
{!isLast && (
<div className="flex justify-center py-3">
- <CombinatorToggle value={combinator} onChange={onCombinatorChange} />
+ <CombinatorToggle
+ value={combinator}
+ onChange={onCombinatorChange}
+ isReadOnly={isReadOnly}
+ />
</div>
)}
</div>
);
}
-export function ConditionForm({ node, issues }: NodeFormProps<"condition">) {
+export function ConditionForm({
+ node,
+ issues,
+ isReadOnly
+}: NodeFormProps<"condition">) {
const updateNodeData = useBuilderStore((s) => s.updateNodeData);
const onEdgesChange = useBuilderStore((s) => s.onEdgesChange);
const edges = useBuilderStore((s) => s.edges);
@@ -238,6 +250,7 @@ export function ConditionForm({ node, issues }: NodeFormProps<"condition">) {
clauses: [...path.clauses, newClause()]
})
}
+ isDisabled={isReadOnly}
>
<Trans>Add clause</Trans>
</Button>
@@ -249,6 +262,7 @@ export function ConditionForm({ node, issues }: NodeFormProps<"condition">) {
variant="ghost"
size="sm"
onClick={() => removePath(path.id)}
+ isDisabled={isReadOnly}
/>
)}
</div>
@@ -311,6 +325,7 @@ export function ConditionForm({ node, issues }: NodeFormProps<"condition">) {
}
fieldPath={`paths.${path.id}.clauses.${i}`}
issues={issues}
+ isReadOnly={isReadOnly}
/>
))}
</SortableContext>
@@ -335,6 +350,7 @@ export function ConditionForm({ node, issues }: NodeFormProps<"condition">) {
leftIcon={<LuPlus />}
className="w-full"
onClick={addElseIf}
+ isDisabled={isReadOnly}
>
<Trans>Add path</Trans>
</Button>
@@ -347,6 +363,7 @@ export function ConditionForm({ node, issues }: NodeFormProps<"condition">) {
leftIcon={<LuPlus />}
className="w-full"
onClick={addElse}
+ isDisabled={isReadOnly}
>
<Trans>Add otherwise</Trans>
</Button>
diff --git a/apps/erp/app/modules/workflows/ui/Builder/config/forms/FilterForm.tsx b/apps/erp/app/modules/workflows/ui/Builder/config/forms/FilterForm.tsx
index 69f07de420..b3e04f3daf 100644
--- a/apps/erp/app/modules/workflows/ui/Builder/config/forms/FilterForm.tsx
+++ b/apps/erp/app/modules/workflows/ui/Builder/config/forms/FilterForm.tsx
@@ -38,7 +38,11 @@ const newClause = (): Clause => ({
}
});
-export function FilterForm({ node, issues }: NodeFormProps<"filter">) {
+export function FilterForm({
+ node,
+ issues,
+ isReadOnly
+}: NodeFormProps<"filter">) {
const updateNodeData = useBuilderStore((s) => s.updateNodeData);
const { t } = useLingui();
@@ -105,6 +109,7 @@ export function FilterForm({ node, issues }: NodeFormProps<"filter">) {
<PopoverTrigger asChild>
<button
type="button"
+ disabled={isReadOnly}
className="flex w-full items-center justify-between rounded-md border bg-background px-3 py-2 text-sm hover:bg-muted/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
>
<span
@@ -124,7 +129,10 @@ export function FilterForm({ node, issues }: NodeFormProps<"filter">) {
onTouchMove={(e) => e.stopPropagation()}
>
<Command>
- <CommandInput placeholder={t`Search list variables…`} />
+ <CommandInput
+ placeholder={t`Search list variables…`}
+ disabled={isReadOnly}
+ />
<CommandList className="max-h-64 overflow-y-auto">
<CommandEmpty>
<Trans>No list variables available upstream.</Trans>
@@ -134,6 +142,7 @@ export function FilterForm({ node, issues }: NodeFormProps<"filter">) {
<CommandItem
key={`${v.nodeId}:${v.output}`}
value={`${v.nodeName} ${v.output} ${describeValueType(v.type)}`}
+ disabled={isReadOnly}
onSelect={() => handleSourceSelect(v.nodeId, v.output)}
className="flex flex-col items-start gap-0.5 px-3 py-2"
>
@@ -154,6 +163,7 @@ export function FilterForm({ node, issues }: NodeFormProps<"filter">) {
type="button"
className="text-xs text-muted-foreground hover:text-foreground underline underline-offset-2"
onClick={handleClearSource}
+ disabled={isReadOnly}
>
<Trans>Clear</Trans>
</button>
@@ -174,6 +184,7 @@ export function FilterForm({ node, issues }: NodeFormProps<"filter">) {
<CombinatorToggle
value={combinator}
onChange={(v) => updateNodeData(node.id, { combinator: v })}
+ isReadOnly={isReadOnly}
/>
</div>
@@ -188,12 +199,14 @@ export function FilterForm({ node, issues }: NodeFormProps<"filter">) {
context={context}
fieldPath={`clauses.${i}`}
issues={issues}
+ isReadOnly={isReadOnly}
/>
{i < clauses.length - 1 && (
<div className="flex justify-center py-1">
<CombinatorToggle
value={combinator}
onChange={(v) => updateNodeData(node.id, { combinator: v })}
+ isReadOnly={isReadOnly}
/>
</div>
)}
@@ -206,6 +219,7 @@ export function FilterForm({ node, issues }: NodeFormProps<"filter">) {
size="sm"
leftIcon={<LuPlus />}
onClick={handleAddClause}
+ isDisabled={isReadOnly}
>
<Trans>Add rule</Trans>
</Button>
diff --git a/apps/erp/app/modules/workflows/ui/Builder/config/forms/LookupForm.tsx b/apps/erp/app/modules/workflows/ui/Builder/config/forms/LookupForm.tsx
index 06556c4169..ef55ca042f 100644
--- a/apps/erp/app/modules/workflows/ui/Builder/config/forms/LookupForm.tsx
+++ b/apps/erp/app/modules/workflows/ui/Builder/config/forms/LookupForm.tsx
@@ -41,7 +41,11 @@ function clauseToMatch(c: Clause): WorkingMatch {
};
}
-export function LookupForm({ node, issues }: NodeFormProps<"lookup">) {
+export function LookupForm({
+ node,
+ issues,
+ isReadOnly
+}: NodeFormProps<"lookup">) {
const updateNodeData = useBuilderStore((s) => s.updateNodeData);
const label = useWorkflowLabel();
const { t } = useLingui();
@@ -123,6 +127,7 @@ export function LookupForm({ node, issues }: NodeFormProps<"lookup">) {
options={entityOptions}
onChange={handleEntityChange}
placeholder={t`Pick a record type…`}
+ isReadOnly={isReadOnly}
/>
</div>
@@ -143,11 +148,13 @@ export function LookupForm({ node, issues }: NodeFormProps<"lookup">) {
: "bg-background text-foreground hover:bg-muted"
)}
onClick={() => handleReturnsChange("one")}
+ disabled={isReadOnly}
>
<Trans>Just one</Trans>
</button>
<button
type="button"
+ disabled={isReadOnly}
className={cn(
"flex-1 border-l px-3 py-2 text-sm transition-colors",
returns === "list"
@@ -179,10 +186,12 @@ export function LookupForm({ node, issues }: NodeFormProps<"lookup">) {
entity={entity}
fieldPath={`match.${idx}`}
issues={issues}
+ isReadOnly={isReadOnly}
/>
))}
<button
type="button"
+ disabled={isReadOnly}
className="flex items-center gap-1.5 text-sm text-muted-foreground hover:text-foreground"
onClick={handleAddMatch}
>
diff --git a/apps/erp/app/modules/workflows/ui/Builder/config/forms/TriggerForm.tsx b/apps/erp/app/modules/workflows/ui/Builder/config/forms/TriggerForm.tsx
index 026d1a5ae1..655ac1bf15 100644
--- a/apps/erp/app/modules/workflows/ui/Builder/config/forms/TriggerForm.tsx
+++ b/apps/erp/app/modules/workflows/ui/Builder/config/forms/TriggerForm.tsx
@@ -21,12 +21,23 @@ import {
} from "@carbon/react";
import { getTimezones } from "@carbon/utils";
import type { Origin, Schedule } from "@carbon/workflows";
-import { WORKFLOW_ENTITY_REGISTRY, WORKFLOW_EVENTS } from "@carbon/workflows";
+import {
+ customFieldEventId,
+ ENTITY_BY_TABLE,
+ WORKFLOW_ENTITY_REGISTRY,
+ WORKFLOW_EVENTS
+} from "@carbon/workflows";
import { getLocalTimeZone } from "@internationalized/date";
import { Trans, useLingui } from "@lingui/react/macro";
import { useMemo, useState } from "react";
import { LuCheck, LuChevronsUpDown } from "react-icons/lu";
-import { entityLabelKey, useWorkflowLabel } from "../../catalog";
+import { useCustomFieldsSchema } from "~/hooks/useCustomFieldsSchema";
+import {
+ entityLabelKey,
+ useWorkflowCatalog,
+ useWorkflowEventLabel,
+ useWorkflowLabel
+} from "../../catalog";
import { useBuilderStore } from "../../context";
import { FormStack, Section } from "../layout";
import type { NodeFormProps } from "./index";
@@ -86,7 +97,12 @@ type EventPickerProps = {
onSelect: (id: string) => void;
entityGroups: EntityGroup[];
momentIds: string[];
+ /** The company's custom-field event ids — the badge is the only thing that needs to
+ * tell them apart; their labels come from `eventLabel` like every other event's. */
+ customIds: Set<string>;
label: (key: string) => string;
+ eventLabel: (id: string) => string;
+ isReadOnly?: boolean;
};
function EventPicker({
@@ -94,18 +110,22 @@ function EventPicker({
onSelect,
entityGroups,
momentIds,
- label
+ customIds,
+ label,
+ eventLabel,
+ isReadOnly
}: EventPickerProps) {
const { t } = useLingui();
const [open, setOpen] = useState(false);
- const summary = selected ? label(selected) : t`Select an event…`;
+ const summary = selected ? eventLabel(selected) : t`Select an event…`;
return (
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
<button
type="button"
+ disabled={isReadOnly}
className="flex w-full items-center justify-between rounded-md border bg-background px-3 py-2 text-sm hover:bg-muted/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
>
<span
@@ -123,7 +143,7 @@ function EventPicker({
onTouchMove={(e) => e.stopPropagation()}
>
<Command>
- <CommandInput placeholder={t`Search events…`} />
+ <CommandInput placeholder={t`Search events…`} disabled={isReadOnly} />
<CommandList className="max-h-64 overflow-auto scrollbar-thin scrollbar-track-transparent scrollbar-thumb-accent">
<CommandEmpty>
<Trans>No events found.</Trans>
@@ -138,7 +158,8 @@ function EventPicker({
key={id}
// Search runs on `value`, so the visible label has to be in it —
// the id alone is never what someone types, and never translated.
- value={`${id} ${label(id)}`}
+ value={`${id} ${eventLabel(id)}`}
+ disabled={isReadOnly}
onSelect={() => {
onSelect(id);
setOpen(false);
@@ -150,9 +171,24 @@ function EventPicker({
selected === id ? "opacity-100" : "opacity-0"
)}
/>
- {label(id)}
+ <span className="truncate">
+ {eventLabel(id)}
+ {/* A custom field can share a name with a shipped column. */}
+ {customIds.has(id) && (
+ <span className="ml-2 text-xs text-muted-foreground">
+ <Trans>Custom field</Trans>
+ </span>
+ )}
+ </span>
</CommandItem>
))}
+ {entity === "item" && (
+ <p className="px-2 py-1.5 text-xs text-muted-foreground">
+ <Trans>
+ Custom fields are not available for items yet.
+ </Trans>
+ </p>
+ )}
</CommandGroup>
))}
{momentIds.length > 0 && (
@@ -161,6 +197,7 @@ function EventPicker({
<CommandItem
key={id}
value={`${id} ${label(id)}`}
+ disabled={isReadOnly}
onSelect={() => {
onSelect(id);
setOpen(false);
@@ -189,9 +226,14 @@ function EventPicker({
type ScheduleEditorProps = {
schedule: Schedule;
onChange: (patch: Partial<Schedule>) => void;
+ isReadOnly?: boolean;
};
-function ScheduleEditor({ schedule, onChange }: ScheduleEditorProps) {
+function ScheduleEditor({
+ schedule,
+ onChange,
+ isReadOnly
+}: ScheduleEditorProps) {
const { t } = useLingui();
const tz = resolveTimezone(schedule.tz);
@@ -206,8 +248,9 @@ function ScheduleEditor({ schedule, onChange }: ScheduleEditorProps) {
<Select
value={schedule.freq}
onValueChange={(v) => onChange({ freq: v as Schedule["freq"] })}
+ disabled={isReadOnly}
>
- <SelectTrigger className="w-full">
+ <SelectTrigger className="w-full" disabled={isReadOnly}>
<SelectValue />
</SelectTrigger>
<SelectContent>
@@ -239,6 +282,7 @@ function ScheduleEditor({ schedule, onChange }: ScheduleEditorProps) {
type="button"
aria-pressed={active}
aria-label={day}
+ disabled={isReadOnly}
className={cn(
"h-8 w-8 rounded-md text-xs font-medium transition-colors",
active
@@ -273,8 +317,9 @@ function ScheduleEditor({ schedule, onChange }: ScheduleEditorProps) {
onValueChange={(v) =>
onChange({ day: v === "last" ? "last" : Number(v) })
}
+ disabled={isReadOnly}
>
- <SelectTrigger className="w-full">
+ <SelectTrigger className="w-full" disabled={isReadOnly}>
<SelectValue />
</SelectTrigger>
<SelectContent>
@@ -300,8 +345,9 @@ function ScheduleEditor({ schedule, onChange }: ScheduleEditorProps) {
<Select
value={String(schedule.hour)}
onValueChange={(v) => onChange({ hour: Number(v) })}
+ disabled={isReadOnly}
>
- <SelectTrigger className="flex-1">
+ <SelectTrigger className="flex-1" disabled={isReadOnly}>
<SelectValue />
</SelectTrigger>
<SelectContent>
@@ -316,8 +362,9 @@ function ScheduleEditor({ schedule, onChange }: ScheduleEditorProps) {
<Select
value={String(schedule.minute)}
onValueChange={(v) => onChange({ minute: Number(v) })}
+ disabled={isReadOnly}
>
- <SelectTrigger className="flex-1">
+ <SelectTrigger className="flex-1" disabled={isReadOnly}>
<SelectValue />
</SelectTrigger>
<SelectContent>
@@ -336,8 +383,12 @@ function ScheduleEditor({ schedule, onChange }: ScheduleEditorProps) {
<Section>
<Trans>Timezone</Trans>
</Section>
- <Select value={tz} onValueChange={(v) => onChange({ tz: v })}>
- <SelectTrigger className="w-full">
+ <Select
+ value={tz}
+ onValueChange={(v) => onChange({ tz: v })}
+ disabled={isReadOnly}
+ >
+ <SelectTrigger className="w-full" disabled={isReadOnly}>
<SelectValue />
</SelectTrigger>
<SelectContent>
@@ -360,9 +411,12 @@ function ScheduleEditor({ schedule, onChange }: ScheduleEditorProps) {
// ─── TriggerForm ─────────────────────────────────────────────────────────────
-export function TriggerForm({ node }: NodeFormProps<"trigger">) {
+export function TriggerForm({ node, isReadOnly }: NodeFormProps<"trigger">) {
const updateNodeData = useBuilderStore((s) => s.updateNodeData);
const label = useWorkflowLabel();
+ const eventLabel = useWorkflowEventLabel();
+ const catalog = useWorkflowCatalog();
+ const customFields = useCustomFieldsSchema();
const { events, origin, schedule } = node.data;
const isScheduleMode = !!schedule;
@@ -373,6 +427,30 @@ export function TriggerForm({ node }: NodeFormProps<"trigger">) {
[]
);
+ // This company's custom-field triggers. `catalog.getEvent` is the single gate — it
+ // owns the item exclusion and the reference-only-entity rule, so neither is restated.
+ const customIds = useMemo(() => {
+ const ids: Record<string, string[]> = {};
+
+ for (const [table, fields] of Object.entries(customFields)) {
+ const entity = ENTITY_BY_TABLE[table];
+ if (entity === undefined) continue;
+ for (const field of fields ?? []) {
+ if (!field.active) continue;
+ const id = customFieldEventId(entity, field.id);
+ if (catalog.getEvent(id) === undefined) continue;
+ (ids[entity] ??= []).push(id);
+ }
+ }
+
+ return ids;
+ }, [customFields, catalog]);
+
+ const customIdSet = useMemo(
+ () => new Set(Object.values(customIds).flat()),
+ [customIds]
+ );
+
const { entityGroups, momentIds } = useMemo(() => {
const groupMap: Record<string, string[]> = {};
const moments: string[] = [];
@@ -387,12 +465,17 @@ export function TriggerForm({ node }: NodeFormProps<"trigger">) {
}
}
+ // Custom fields go after the shipped triggers, so a familiar list stays familiar.
+ for (const [entity, ids] of Object.entries(customIds)) {
+ (groupMap[entity] ??= []).push(...ids);
+ }
+
const entityGroups: EntityGroup[] = Object.entries(groupMap).map(
([entity, ids]) => ({ entity, ids })
);
return { entityGroups, momentIds: moments };
- }, [registryEntities]);
+ }, [registryEntities, customIds]);
// Mode switching
function switchToEvents() {
@@ -439,11 +522,13 @@ export function TriggerForm({ node }: NodeFormProps<"trigger">) {
: "bg-background text-foreground hover:bg-muted"
)}
onClick={switchToEvents}
+ disabled={isReadOnly}
>
<Trans>Event</Trans>
</button>
<button
type="button"
+ disabled={isReadOnly}
className={cn(
"flex-1 border-l px-3 py-2 text-sm transition-colors",
isScheduleMode
@@ -469,7 +554,10 @@ export function TriggerForm({ node }: NodeFormProps<"trigger">) {
onSelect={selectEvent}
entityGroups={entityGroups}
momentIds={momentIds}
+ customIds={customIdSet}
label={label}
+ eventLabel={eventLabel}
+ isReadOnly={isReadOnly}
/>
</div>
@@ -491,22 +579,26 @@ export function TriggerForm({ node }: NodeFormProps<"trigger">) {
onValueChange={(v) => {
if (v) updateNodeData(node.id, { origin: v as Origin });
}}
+ disabled={isReadOnly}
className="justify-start"
>
<ToggleGroupItem
value={"Person" satisfies Origin}
+ disabled={isReadOnly}
className="text-xs"
>
<Trans>Everything else</Trans>
</ToggleGroupItem>
<ToggleGroupItem
value={"Automation" satisfies Origin}
+ disabled={isReadOnly}
className="text-xs"
>
<Trans>Workflows</Trans>
</ToggleGroupItem>
<ToggleGroupItem
value={"Both" satisfies Origin}
+ disabled={isReadOnly}
className="text-xs"
>
<Trans>Both</Trans>
@@ -517,7 +609,11 @@ export function TriggerForm({ node }: NodeFormProps<"trigger">) {
) : (
<>
{schedule && (
- <ScheduleEditor schedule={schedule} onChange={patchSchedule} />
+ <ScheduleEditor
+ schedule={schedule}
+ onChange={patchSchedule}
+ isReadOnly={isReadOnly}
+ />
)}
</>
)}
diff --git a/apps/erp/app/modules/workflows/ui/Builder/config/forms/index.ts b/apps/erp/app/modules/workflows/ui/Builder/config/forms/index.ts
index b849eb4ccf..d5080d8e37 100644
--- a/apps/erp/app/modules/workflows/ui/Builder/config/forms/index.ts
+++ b/apps/erp/app/modules/workflows/ui/Builder/config/forms/index.ts
@@ -21,6 +21,8 @@ export type NodeFormProps<K extends WorkflowNodeType = WorkflowNodeType> = {
};
/** Issues for this node, so forms can highlight the affected field. */
issues?: WorkflowIssue[];
+ /** The version is published: render every control disabled rather than inert. */
+ isReadOnly?: boolean;
};
/** Spelled out: a missing kind is a TS2741, not a blank panel. */
@@ -39,4 +41,5 @@ export const NODE_FORMS: {
export type AnyNodeForm = ComponentType<{
node: BuilderNode;
issues?: WorkflowIssue[];
+ isReadOnly?: boolean;
}>;
diff --git a/apps/erp/app/modules/workflows/ui/Builder/context.tsx b/apps/erp/app/modules/workflows/ui/Builder/context.tsx
index 5373ce733a..87cb8a4084 100644
--- a/apps/erp/app/modules/workflows/ui/Builder/context.tsx
+++ b/apps/erp/app/modules/workflows/ui/Builder/context.tsx
@@ -41,7 +41,8 @@ export function useBuilderStoreApi(): StoreApi<BuilderState> {
type WorkflowBuilderProviderProps = {
nodes: BuilderNode[];
edges: BuilderEdge[];
- isReadOnly: boolean;
+ isVersionLocked: boolean;
+ canEdit: boolean;
isOwner: boolean;
};
diff --git a/apps/erp/app/modules/workflows/ui/Builder/edges/WorkflowEdge.tsx b/apps/erp/app/modules/workflows/ui/Builder/edges/WorkflowEdge.tsx
index 45a6743694..18a144cea8 100644
--- a/apps/erp/app/modules/workflows/ui/Builder/edges/WorkflowEdge.tsx
+++ b/apps/erp/app/modules/workflows/ui/Builder/edges/WorkflowEdge.tsx
@@ -1,7 +1,7 @@
import { cn, IconButton } from "@carbon/react";
import { useLingui } from "@lingui/react/macro";
import type { EdgeProps } from "@xyflow/react";
-import { EdgeLabelRenderer, getSmoothStepPath, useStore } from "@xyflow/react";
+import { EdgeLabelRenderer, getBezierPath, useStore } from "@xyflow/react";
import { memo, useEffect, useState } from "react";
import { LuX } from "react-icons/lu";
import { useBuilderStore } from "../context";
@@ -25,7 +25,8 @@ function WorkflowEdgeImpl({
const anySelected = useStore((s) => s.nodes.some((n) => n.selected));
const highlighted = selected || isNodeSelected;
- const isReadOnly = useBuilderStore((s) => s.isReadOnly);
+ const canChangeDefinition = useBuilderStore((s) => s.canChangeDefinition);
+ const isReadOnly = !canChangeDefinition;
const onEdgesChange = useBuilderStore((s) => s.onEdgesChange);
const [armed, setArmed] = useState(false);
@@ -37,14 +38,13 @@ function WorkflowEdgeImpl({
return () => clearTimeout(timer);
}, [armed]);
- const [edgePath, labelX, labelY] = getSmoothStepPath({
+ const [edgePath, labelX, labelY] = getBezierPath({
sourceX,
sourceY,
sourcePosition,
targetX,
targetY,
- targetPosition,
- borderRadius: 12
+ targetPosition
});
return (
diff --git a/apps/erp/app/modules/workflows/ui/Builder/edges/workflow-edge.css b/apps/erp/app/modules/workflows/ui/Builder/edges/workflow-edge.css
index e1d9ca47f6..16d8c56ab9 100644
--- a/apps/erp/app/modules/workflows/ui/Builder/edges/workflow-edge.css
+++ b/apps/erp/app/modules/workflows/ui/Builder/edges/workflow-edge.css
@@ -5,3 +5,8 @@
.workflow-edge-animated {
animation: edge-flow 1.2s linear infinite;
}
+
+/* xyflow's default dot colour competes with the content. Scoped to this canvas. */
+.react-flow {
+ --xy-background-pattern-dots-color: hsl(var(--muted-foreground) / 0.25);
+}
diff --git a/apps/erp/app/modules/workflows/ui/Builder/fields/InlineValueEditor.tsx b/apps/erp/app/modules/workflows/ui/Builder/fields/InlineValueEditor.tsx
index ab5f96ef02..d85c66c90b 100644
--- a/apps/erp/app/modules/workflows/ui/Builder/fields/InlineValueEditor.tsx
+++ b/apps/erp/app/modules/workflows/ui/Builder/fields/InlineValueEditor.tsx
@@ -6,6 +6,7 @@ import {
import type { ValueOrRef, ValueType } from "@carbon/workflows";
import { useLingui } from "@lingui/react/macro";
import { useCallback, useEffect, useRef } from "react";
+import { useCustomFieldLabels } from "../catalog";
import { useBuilderStoreApi } from "../context";
import { InlineVariableMenu } from "./InlineVariableMenu";
import { publishVariableMenuData, retractVariableMenuData } from "./menuBridge";
@@ -48,6 +49,8 @@ type Props = {
/** Fires as focus enters and leaves. Lets the field hold back advice about a value
* the user is still in the middle of typing. */
onFocusChange?: (focused: boolean) => void;
+ /** The version is published: show the value, refuse every edit. */
+ isReadOnly?: boolean;
};
export function InlineValueEditor({
@@ -63,9 +66,12 @@ export function InlineValueEditor({
maxRows,
minRows,
multiline,
- onFocusChange
+ onFocusChange,
+ isReadOnly = false
}: Props) {
const { t } = useLingui();
+ // A custom field's path segment is its id; only this map knows what to call it.
+ const segmentLabels = useCustomFieldLabels();
const store = useBuilderStoreApi();
const getMenuData = useVariableMenuData(context, accepts, textOnly);
@@ -97,12 +103,14 @@ export function InlineValueEditor({
<div
className="min-w-0 flex-1"
onFocusCapture={() => {
+ if (isReadOnly) return;
publishVariableMenuData(getData);
onFocusChange?.(true);
}}
onBlurCapture={() => {
+ if (isReadOnly) return;
onFocusChange?.(false);
- const parts = toEditorParts(value, nodeName);
+ const parts = toEditorParts(value, nodeName, undefined, segmentLabels);
const trimmed = withoutTrailingSpace(parts);
// Same array back means nothing to trim; writing anyway dirties the workflow
// on every focus change.
@@ -112,7 +120,7 @@ export function InlineValueEditor({
}}
>
<VariableText
- value={toEditorParts(value, nodeName, partIssues)}
+ value={toEditorParts(value, nodeName, partIssues, segmentLabels)}
onChange={(next: VariableTextPart[]) =>
onChange(fromEditorParts(next, { collapseSingleRef }))
}
@@ -124,6 +132,7 @@ export function InlineValueEditor({
renderTokenLabel={leafOfLabel}
maxRows={maxRows}
minRows={minRows}
+ isReadOnly={isReadOnly}
className={cn("w-full", hasIssue && "border-destructive")}
/>
</div>
diff --git a/apps/erp/app/modules/workflows/ui/Builder/fields/InlineVariableMenu.tsx b/apps/erp/app/modules/workflows/ui/Builder/fields/InlineVariableMenu.tsx
index 20c032edcf..a5756b7097 100644
--- a/apps/erp/app/modules/workflows/ui/Builder/fields/InlineVariableMenu.tsx
+++ b/apps/erp/app/modules/workflows/ui/Builder/fields/InlineVariableMenu.tsx
@@ -2,7 +2,13 @@ import type {
VariableTextMenuHandle,
VariableTextMenuProps
} from "@carbon/react/VariableText";
-import { forwardRef, useImperativeHandle } from "react";
+import {
+ forwardRef,
+ useEffect,
+ useImperativeHandle,
+ useRef,
+ useState
+} from "react";
import { readVariableMenuData } from "./menuBridge";
import { VariableTreeMenu } from "./VariableTreeMenu";
@@ -11,20 +17,53 @@ import { VariableTreeMenu } from "./VariableTreeMenu";
export const InlineVariableMenu = forwardRef<
VariableTextMenuHandle,
VariableTextMenuProps
->(function InlineVariableMenu(props, ref) {
+>(function InlineVariableMenu({ editor, range, query, command }, ref) {
// The menu claims its keys on the document, so there is nothing left to hand back —
// and declining here lets the suggestion plugin close its own popup on Escape.
useImperativeHandle(ref, () => ({ onKeyDown: () => false }));
const { tree, flat, emptyReason } = readVariableMenuData();
+ // The menu searches on its own box, seeded with whatever was typed after the `{`. The
+ // editor keeps matching as it always did, so anything typed back in the field wins —
+ // this only fires when `query` actually changes, which it cannot while the box has focus.
+ const [search, setSearch] = useState(query);
+ useEffect(() => setSearch(query), [query]);
+
+ /** Picking puts the caret back in the editor, which blurs the search box mid-insert.
+ * Without this latch that blur reads as leaving, and the dismissal below deletes the
+ * range the token is being written into — the pick closes the menu and inserts nothing. */
+ const picking = useRef(false);
+
+ /** Closing without picking has to take the `{` with it: the popup is driven by that
+ * match, so leaving the character behind would leave the menu open over a field the
+ * user has already moved on from. `focus` hands the caret back to where they typed it. */
+ const dismiss = (focus: boolean) => {
+ const chain = editor.chain();
+ (focus ? chain.focus() : chain).deleteRange(range).run();
+ };
+
return (
<VariableTreeMenu
tree={tree}
flat={flat}
emptyReason={emptyReason}
- query={props.query}
- onSelect={(item) => props.command(item)}
+ query={search}
+ onQueryChange={setSearch}
+ onEscape={() => dismiss(true)}
+ onSearchBlur={(next) => {
+ if (picking.current) return;
+ // Focus going back into the field is the user carrying on typing there, not
+ // leaving: the same menu keeps matching on what the field itself holds.
+ if (next !== null && editor.view.dom.contains(next)) return;
+ // A click on nothing focusable leaves the page with no caret at all — that is the
+ // one case the field has to be handed it back.
+ dismiss(next === null);
+ }}
+ onSelect={(item) => {
+ picking.current = true;
+ command(item);
+ }}
// Backspace has to delete the `{` the user just typed.
backspacePops={false}
/>
diff --git a/apps/erp/app/modules/workflows/ui/Builder/fields/LiteralControl.tsx b/apps/erp/app/modules/workflows/ui/Builder/fields/LiteralControl.tsx
index 897f2e0f46..19424fa372 100644
--- a/apps/erp/app/modules/workflows/ui/Builder/fields/LiteralControl.tsx
+++ b/apps/erp/app/modules/workflows/ui/Builder/fields/LiteralControl.tsx
@@ -40,6 +40,8 @@ type LiteralControlProps = {
/** Opens the variable menu. Every control here has two modes, and `{` is the one
* way into the second. */
onRequestVariable: () => void;
+ /** The version is published: show the value, refuse every edit. */
+ isReadOnly?: boolean;
};
export function LiteralControl({
@@ -47,7 +49,8 @@ export function LiteralControl({
choices,
value,
onChange,
- onRequestVariable
+ onRequestVariable,
+ isReadOnly = false
}: LiteralControlProps) {
const { t } = useLingui();
@@ -62,6 +65,7 @@ export function LiteralControl({
// A `{` opens the menu rather than landing in the buffer. On the shell rather than
// each input, so a dropdown and a switch answer the key the same way a text box does.
const braceOpens = (e: KeyboardEvent) => {
+ if (isReadOnly) return;
if (e.key === "{") {
e.preventDefault();
onRequestVariable();
@@ -80,8 +84,12 @@ export function LiteralControl({
if (choices && choices.length > 0) {
const strValue = typeof value === "string" ? value : "";
return shell(
- <Select value={strValue} onValueChange={(v) => emit(v || undefined)}>
- <SelectTrigger>
+ <Select
+ value={strValue}
+ onValueChange={(v) => emit(v || undefined)}
+ disabled={isReadOnly}
+ >
+ <SelectTrigger disabled={isReadOnly}>
<SelectValue className="truncate" placeholder={t`Select…`} />
</SelectTrigger>
<SelectContent>
@@ -109,6 +117,7 @@ export function LiteralControl({
value={strValue}
onChange={(e) => emit(e.target.value)}
placeholder={t`Enter text…`}
+ isDisabled={isReadOnly}
/>
);
}
@@ -127,6 +136,7 @@ export function LiteralControl({
emit(typeof n === "number" && !Number.isNaN(n) ? n : undefined)
}
aria-label={t`Number`}
+ isDisabled={isReadOnly}
>
<NumberInputGroup className="relative">
<NumberInput
@@ -153,6 +163,7 @@ export function LiteralControl({
checked={boolValue}
onCheckedChange={(checked) => emit(checked)}
aria-label={t`Toggle`}
+ disabled={isReadOnly}
/>
);
}
@@ -163,6 +174,7 @@ export function LiteralControl({
value={asCalendarDate(value)}
onChange={(date) => emit(date?.toString() ?? undefined)}
aria-label={t`Date`}
+ isDisabled={isReadOnly}
/>
);
}
@@ -178,7 +190,11 @@ export function LiteralControl({
if (Picker) {
const strValue = typeof value === "string" ? value : undefined;
return shell(
- <Picker value={strValue} onChange={(id) => emit(id ?? undefined)} />
+ <Picker
+ value={strValue}
+ onChange={(id) => emit(id ?? undefined)}
+ isDisabled={isReadOnly}
+ />
);
}
}
@@ -191,7 +207,7 @@ export function LiteralControl({
type="text"
className="truncate"
placeholder={t`Pick a value from an earlier step`}
- disabled
+ isDisabled
/>
);
}
diff --git a/apps/erp/app/modules/workflows/ui/Builder/fields/MultiChoiceField.tsx b/apps/erp/app/modules/workflows/ui/Builder/fields/MultiChoiceField.tsx
new file mode 100644
index 0000000000..e76b05a1fd
--- /dev/null
+++ b/apps/erp/app/modules/workflows/ui/Builder/fields/MultiChoiceField.tsx
@@ -0,0 +1,70 @@
+import type { TermId } from "@carbon/glossary";
+import { ChoiceSelect, type ChoiceSelectOption } from "@carbon/react";
+import type { ValueOrRef, ValueType } from "@carbon/workflows";
+import { useLingui } from "@lingui/react/macro";
+import { Field } from "./Field";
+import { choiceState, writeChoices } from "./multiChoice";
+
+export type MultiChoiceFieldProps = {
+ label: string;
+ type: ValueType;
+ required?: boolean;
+ helpTermId?: TermId;
+ /** Titles, descriptions and per-option availability, in the order to offer them. */
+ options: ChoiceSelectOption[];
+ /** Always ticked and never togglable, whatever is stored — a channel the platform
+ * sends regardless. Not written on mount, so an untouched node stays untouched. */
+ locked?: readonly string[];
+ value: ValueOrRef | undefined;
+ onChange: (next: ValueOrRef | undefined) => void;
+ issue?: string;
+ isReadOnly?: boolean;
+};
+
+/**
+ * A set of fixed choices, for a catalog input declared `multiple`. Deliberately not a
+ * `ValueField` control: there is no variable to bind here, so the `{` affordance every
+ * other control carries would offer something this field cannot accept.
+ */
+export function MultiChoiceField({
+ label,
+ type,
+ required,
+ helpTermId,
+ options,
+ locked,
+ value,
+ onChange,
+ issue,
+ isReadOnly
+}: MultiChoiceFieldProps) {
+ const { t } = useLingui();
+ const choices = options.map((option) => option.value);
+ const { shown, frozen } = choiceState(options, value, locked);
+ const rendered = options.map((option) => ({
+ ...option,
+ disabled: frozen.includes(option.value)
+ }));
+
+ return (
+ <Field
+ label={label}
+ required={required}
+ helpTermId={helpTermId}
+ issue={issue}
+ >
+ <div className="min-w-0 flex-1">
+ <ChoiceSelect
+ multiple
+ aria-label={label}
+ options={rendered}
+ value={shown}
+ onChange={(next) => onChange(writeChoices(next, choices, type))}
+ placeholder={t`Select…`}
+ disabled={isReadOnly}
+ className="w-full"
+ />
+ </div>
+ </Field>
+ );
+}
diff --git a/apps/erp/app/modules/workflows/ui/Builder/fields/PairsField.tsx b/apps/erp/app/modules/workflows/ui/Builder/fields/PairsField.tsx
index 6ef19e5511..6624d4cc61 100644
--- a/apps/erp/app/modules/workflows/ui/Builder/fields/PairsField.tsx
+++ b/apps/erp/app/modules/workflows/ui/Builder/fields/PairsField.tsx
@@ -25,7 +25,8 @@ export function PairsField({
onChange,
context,
issue,
- partIssues
+ partIssues,
+ isReadOnly
}: ValueFieldProps) {
const { t } = useLingui();
const entries = entriesOf(value);
@@ -72,6 +73,7 @@ export function PairsField({
placeholder={t`Name`}
value={entry.name}
onChange={(e) => handleName(index, e.target.value)}
+ isDisabled={isReadOnly}
/>
<InlineValueEditor
textOnly
@@ -81,6 +83,7 @@ export function PairsField({
context={context}
placeholder={t`Value`}
hasIssue={!!rowIssue}
+ isReadOnly={isReadOnly}
/>
<IconButton
icon={<LuX />}
@@ -89,6 +92,7 @@ export function PairsField({
size="sm"
className="shrink-0"
onClick={() => handleRemove(index)}
+ isDisabled={isReadOnly}
/>
</div>
{rowIssue && (
@@ -104,6 +108,7 @@ export function PairsField({
size="sm"
leftIcon={<LuPlus />}
onClick={handleAdd}
+ isDisabled={isReadOnly}
>
<Trans>Add header</Trans>
</Button>
diff --git a/apps/erp/app/modules/workflows/ui/Builder/fields/TemplateField.tsx b/apps/erp/app/modules/workflows/ui/Builder/fields/TemplateField.tsx
index 0740cea5d4..44e3be9720 100644
--- a/apps/erp/app/modules/workflows/ui/Builder/fields/TemplateField.tsx
+++ b/apps/erp/app/modules/workflows/ui/Builder/fields/TemplateField.tsx
@@ -12,7 +12,8 @@ export function TemplateField({
onChange,
context,
issue,
- partIssues
+ partIssues,
+ isReadOnly
}: ValueFieldProps) {
return (
<Field
@@ -35,6 +36,7 @@ export function TemplateField({
multiline
minRows={4}
maxRows={12}
+ isReadOnly={isReadOnly}
/>
</Field>
);
diff --git a/apps/erp/app/modules/workflows/ui/Builder/fields/ValueField.tsx b/apps/erp/app/modules/workflows/ui/Builder/fields/ValueField.tsx
index 785d1e1b8e..d40cfe0097 100644
--- a/apps/erp/app/modules/workflows/ui/Builder/fields/ValueField.tsx
+++ b/apps/erp/app/modules/workflows/ui/Builder/fields/ValueField.tsx
@@ -1,4 +1,5 @@
import { useState } from "react";
+import { useCustomFieldLabels } from "../catalog";
import { useBuilderStoreApi } from "../context";
import { pickControl } from "./control";
import { Field } from "./Field";
@@ -22,9 +23,11 @@ export function ValueField({
context,
placeholder,
issue,
- partIssues
+ partIssues,
+ isReadOnly
}: ValueFieldProps) {
const store = useBuilderStoreApi();
+ const segmentLabels = useCustomFieldLabels();
const [pickerOpen, setPickerOpen] = useState(false);
const control = pickControl(type, value, choices);
const acceptsFilter = pickAccepts(type, accepts);
@@ -54,6 +57,7 @@ export function ValueField({
context={context}
placeholder={placeholder}
hasIssue={!!issue}
+ isReadOnly={isReadOnly}
// A lone variable is stored bare, so the field's own message is about it.
partIssues={
value?.kind === "template"
@@ -80,7 +84,7 @@ export function ValueField({
accepts={acceptsFilter}
context={context}
onChange={onChange}
- open={pickerOpen}
+ open={isReadOnly ? false : pickerOpen}
onOpenChange={setPickerOpen}
>
<div className="flex min-w-0 flex-1 items-center">
@@ -88,13 +92,16 @@ export function ValueField({
<VariablePickControl
placeholder={placeholder}
hasIssue={!!issue}
+ isReadOnly={isReadOnly}
onOpen={() => setPickerOpen(true)}
chip={
control === "chip" && ref ? (
<VariableChip
variable={ref}
nodeTitle={nodeTitle}
+ segmentLabels={segmentLabels}
invalid={issue}
+ isReadOnly={isReadOnly}
onRemove={() => onChange(undefined)}
onReopen={() => setPickerOpen(true)}
/>
@@ -117,6 +124,7 @@ export function ValueField({
}
onChange={onChange}
onRequestVariable={() => setPickerOpen(true)}
+ isReadOnly={isReadOnly}
/>
)}
</div>
diff --git a/apps/erp/app/modules/workflows/ui/Builder/fields/VariableChip.tsx b/apps/erp/app/modules/workflows/ui/Builder/fields/VariableChip.tsx
index 47b9c1024d..8f75485a4f 100644
--- a/apps/erp/app/modules/workflows/ui/Builder/fields/VariableChip.tsx
+++ b/apps/erp/app/modules/workflows/ui/Builder/fields/VariableChip.tsx
@@ -3,7 +3,7 @@ import { VARIABLE_TEXT_CHIP_CLASS } from "@carbon/react/VariableText";
import type { ItemRef, VariableRef } from "@carbon/workflows";
import { useLingui } from "@lingui/react/macro";
import { LuX } from "react-icons/lu";
-import { refLabel, refLeafLabel } from "./tokenId";
+import { namedPath, refLabel, refLeafLabel } from "./tokenId";
type Props = {
variable: VariableRef | ItemRef;
@@ -14,6 +14,10 @@ type Props = {
invalid?: string;
onRemove: () => void;
onReopen: () => void;
+ /** The version is published: show the value, refuse every edit. */
+ isReadOnly?: boolean;
+ /** Path segment -> what the customer calls it. A custom field's segment is an id. */
+ segmentLabels?: Record<string, string>;
};
const BROKEN_CHIP_CLASS =
@@ -27,7 +31,9 @@ export function VariableChip({
typeName,
invalid,
onRemove,
- onReopen
+ onReopen,
+ isReadOnly = false,
+ segmentLabels
}: Props) {
const { t } = useLingui();
// The step is gone, so there is no name left to show — the chip has to say so itself.
@@ -35,9 +41,11 @@ export function VariableChip({
const removed = refVal.kind === "ref" && nodeTitle === undefined;
const broken = removed || invalid !== undefined;
+ const path = namedPath(refVal.path, segmentLabels);
+
const label = removed
? t`Step removed — pick a new value`
- : `{${refLeafLabel(refVal)}}`;
+ : `{${refLeafLabel(refVal, path)}}`;
const chip = (
<span
@@ -49,6 +57,7 @@ export function VariableChip({
<button
type="button"
onClick={onReopen}
+ disabled={isReadOnly}
className="min-w-0 overflow-hidden text-ellipsis whitespace-nowrap"
>
{label}
@@ -61,6 +70,7 @@ export function VariableChip({
event.stopPropagation();
onRemove();
}}
+ disabled={isReadOnly}
className="shrink-0 rounded-full opacity-60 transition-opacity hover:opacity-100"
>
<LuX className="size-3" />
@@ -72,14 +82,14 @@ export function VariableChip({
// The chip shows the value's own name; the full `Step › output › property` path is the
// tooltip, because a narrow clause cell cannot fit it.
- const path = typeName
- ? `${refLabel(refVal, nodeTitle)} › ${typeName}`
- : refLabel(refVal, nodeTitle);
+ const fullPath = typeName
+ ? `${refLabel(refVal, nodeTitle, path)} › ${typeName}`
+ : refLabel(refVal, nodeTitle, path);
return (
<Tooltip>
<TooltipTrigger asChild>{chip}</TooltipTrigger>
- <TooltipContent>{invalid ?? path}</TooltipContent>
+ <TooltipContent>{invalid ?? fullPath}</TooltipContent>
</Tooltip>
);
}
diff --git a/apps/erp/app/modules/workflows/ui/Builder/fields/VariablePickControl.tsx b/apps/erp/app/modules/workflows/ui/Builder/fields/VariablePickControl.tsx
index 5738418b69..a3b91573b4 100644
--- a/apps/erp/app/modules/workflows/ui/Builder/fields/VariablePickControl.tsx
+++ b/apps/erp/app/modules/workflows/ui/Builder/fields/VariablePickControl.tsx
@@ -15,13 +15,16 @@ export function VariablePickControl({
placeholder,
hasIssue,
onOpen,
- chip
+ chip,
+ isReadOnly = false
}: {
placeholder?: string;
hasIssue?: boolean;
onOpen: () => void;
/** The chosen variable, drawn inside the box. Absent means nothing is chosen yet. */
chip?: ReactNode;
+ /** The version is published: show the value, refuse every edit. */
+ isReadOnly?: boolean;
}) {
const { t } = useLingui();
@@ -29,7 +32,7 @@ export function VariablePickControl({
// The whole box opens the menu, chip or not — clicking a select's own text is how
// anyone expects to reopen it. The chip's clear button stops the click itself.
<div
- onClick={onOpen}
+ onClick={isReadOnly ? undefined : onOpen}
className={cn(
"flex h-10 w-full min-w-0 flex-1 cursor-pointer items-center justify-between gap-2 whitespace-nowrap rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-xs transition-[color,box-shadow] focus-within:border-ring focus-within:ring-[3px] focus-within:ring-ring/50",
hasIssue && "border-destructive"
@@ -39,6 +42,7 @@ export function VariablePickControl({
<button
type="button"
onClick={onOpen}
+ disabled={isReadOnly}
className="min-w-0 flex-1 truncate text-left text-muted-foreground outline-none"
>
{placeholder ?? t`Pick a variable…`}
diff --git a/apps/erp/app/modules/workflows/ui/Builder/fields/VariableTreeMenu.tsx b/apps/erp/app/modules/workflows/ui/Builder/fields/VariableTreeMenu.tsx
index 571a675b43..690b3fe797 100644
--- a/apps/erp/app/modules/workflows/ui/Builder/fields/VariableTreeMenu.tsx
+++ b/apps/erp/app/modules/workflows/ui/Builder/fields/VariableTreeMenu.tsx
@@ -3,7 +3,13 @@ import { useLingui } from "@lingui/react/macro";
import { useVirtualizer } from "@tanstack/react-virtual";
import { useEffect, useMemo, useRef, useState } from "react";
import { LuArrowLeft, LuChevronRight, LuInfo } from "react-icons/lu";
-import { INITIAL_NAV, type NavState, navigate, rowsAt } from "./menuNav";
+import {
+ INITIAL_NAV,
+ itemsUnder,
+ type NavState,
+ navigate,
+ rowsAt
+} from "./menuNav";
import type { VariableMenuItem, VariableTreeNode } from "./variableMenu";
const ITEM_HEIGHT = 44;
@@ -20,17 +26,30 @@ export type VariableTreeMenuProps = {
/** Shown instead of the generic empty text when the tree is empty because the
* field only accepts one type. */
emptyReason?: string;
+ /** Renders a search box inside the menu. It is deliberately NOT focused on open —
+ * the caret stays in the field the user is writing in until they click into it.
+ * Omit where the host already owns one — the popover puts its field above this. */
+ onQueryChange?: (query: string) => void;
+ /** Escape typed in that search box. The editor host cannot hear it any other way:
+ * its own Escape handler only fires while the field, not the menu, has focus. */
+ onEscape?: () => void;
+ /** Focus left the search box for something outside the menu, with wherever it went.
+ * Only the host knows whether that ends the picker or is the field taking focus back. */
+ onSearchBlur?: (next: Element | null) => void;
};
-/** One level of the variable tree at a time, with search that cuts across every level.
- * Every key is decided by `menuNav.ts`, so both hosts behave identically. */
+/** One level of the variable tree at a time, with search across every level below the
+ * open one. Every key is decided by `menuNav.ts`, so both hosts behave identically. */
export function VariableTreeMenu({
tree,
flat,
query,
onSelect,
backspacePops,
- emptyReason
+ emptyReason,
+ onQueryChange,
+ onEscape,
+ onSearchBlur
}: VariableTreeMenuProps) {
const { t } = useLingui();
const [nav, setNav] = useState<NavState>(INITIAL_NAV);
@@ -40,21 +59,32 @@ export function VariableTreeMenu({
const needle = query.trim().toLowerCase();
const searching = needle.length > 0;
- // Search abandons the tree: matches come from every level, each row keeping the full
- // `Step › output › property` label so the source is still obvious.
+ // Whatever is open is what gets searched: the flat index at the root, that record's
+ // own fields once drilled in. `flat` rather than `itemsUnder(tree, [])` at the root so
+ // a host that indexes more than the tree shows (the loop item) keeps searching it.
+ const scope = useMemo(
+ () => (nav.path.length === 0 ? flat : itemsUnder(tree, nav.path)),
+ [flat, tree, nav.path]
+ );
+
+ // Search abandons the tree: it matches every level in scope, on the whole breadcrumb,
+ // but each row shows only the variable's own name with the path underneath it.
const searchRows = useMemo<VariableTreeNode[]>(
() =>
searching
- ? flat
+ ? scope
.filter((i) => i.label.toLowerCase().includes(needle))
.map((i) => ({
key: i.id,
- label: i.label,
- helper: i.helper,
+ label: i.leaf ?? i.label,
+ // The path, not the type: one field name can appear under several records,
+ // and with only the name shown those rows are indistinguishable.
+ helper: i.label,
+ fullPath: i.label,
item: i
}))
: [],
- [searching, needle, flat]
+ [searching, needle, scope]
);
// `nav.path` survives a search so clearing the query returns to the open level.
@@ -132,7 +162,25 @@ export function VariableTreeMenu({
ref={rootRef}
className="min-w-[280px] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md"
>
- {!searching && nav.path.length > 0 && (
+ {onQueryChange && (
+ <input
+ className="h-10 w-full border-b border-border bg-transparent px-3 text-sm outline-none placeholder:text-muted-foreground"
+ placeholder={t`Search variables…`}
+ value={query}
+ onChange={(event) => onQueryChange(event.target.value)}
+ onKeyDown={(event) => {
+ if (event.key !== "Escape") return;
+ event.preventDefault();
+ onEscape?.();
+ }}
+ // A row refuses focus on mousedown, so a blur here is always the menu being
+ // left — never a click inside it.
+ onBlur={(event) => onSearchBlur?.(event.relatedTarget)}
+ />
+ )}
+
+ {/* Shown while searching too — it is what the search is scoped to. */}
+ {nav.path.length > 0 && (
<button
type="button"
className="flex w-full items-center gap-1.5 border-b border-border px-3 py-2 text-xs text-muted-foreground hover:text-foreground"
@@ -183,6 +231,9 @@ export function VariableTreeMenu({
role="option"
aria-selected={selected}
disabled={!usable}
+ // The path on hover, as the native tooltip rather than a floating one:
+ // a hoverable popup over the list eats the click that picks the row.
+ title={row.fullPath}
className={cn(
"absolute left-0 top-0 flex w-full items-center gap-2 px-3 text-left text-sm",
// Reads as the focused row even though focus stays in the field.
@@ -194,6 +245,9 @@ export function VariableTreeMenu({
height: `${ITEM_HEIGHT}px`,
transform: `translateY(${virtualRow.start}px)`
}}
+ // Never take focus: drilling into a row has to leave the caret where the
+ // user is typing, whether that is the search box or the field itself.
+ onMouseDown={(event) => event.preventDefault()}
// Click and Enter go through the same reducer so they cannot diverge.
onClick={() => {
setNav((n) => ({ ...n, index: virtualRow.index }));
@@ -215,7 +269,7 @@ export function VariableTreeMenu({
}
>
<span className="flex min-w-0 flex-1 flex-col">
- <span className="flex items-center gap-1 leading-tight">
+ <span className="flex min-w-0 items-center gap-1 leading-tight">
<span className="truncate">{row.label}</span>
{row.description && (
<Tooltip>
diff --git a/apps/erp/app/modules/workflows/ui/Builder/fields/choiceOptions.tsx b/apps/erp/app/modules/workflows/ui/Builder/fields/choiceOptions.tsx
new file mode 100644
index 0000000000..a22ee06bdd
--- /dev/null
+++ b/apps/erp/app/modules/workflows/ui/Builder/fields/choiceOptions.tsx
@@ -0,0 +1,66 @@
+import type { ChoiceSelectOption } from "@carbon/react";
+import { useLingui } from "@lingui/react/macro";
+import { LuBell, LuMail, LuSlack } from "react-icons/lu";
+import { useIntegrations } from "~/hooks/useIntegrations";
+import { usePlanGate } from "~/hooks/usePlanGate";
+
+/** Choices the platform delivers whatever the node says — the notify job force-adds the
+ * in-app row to every notification, so it is shown ticked and cannot be unticked. */
+const LOCKED = new Set(["inApp"]);
+
+export function lockedChoices(choices: readonly string[]): string[] {
+ return choices.filter((choice) => LOCKED.has(choice));
+}
+
+export type ChoiceOptionResolver = (
+ choices: readonly string[]
+) => ChoiceSelectOption[];
+
+/**
+ * Builds the options for a `multiple` catalog input. Today that is only the notify
+ * action's channels, and the whole point of the descriptions is that the notify job
+ * skips a channel the company cannot use in SILENCE — the author has to be told here
+ * or they never find out at all.
+ */
+export function useChoiceOptions(): ChoiceOptionResolver {
+ const { t } = useLingui();
+ const slackConnected = useIntegrations().has("slack");
+ const emailGated = usePlanGate({ feature: "EMAIL_NOTIFICATIONS" }).isGated;
+
+ return (choices) =>
+ choices.map((value) => {
+ switch (value) {
+ case "inApp":
+ return {
+ value,
+ title: t`In-app`,
+ description: t`Always sent — every notification shows in the bell menu.`,
+ icon: <LuBell />,
+ disabled: true
+ };
+ case "email":
+ return {
+ value,
+ title: t`Email`,
+ description: emailGated
+ ? t`Needs a Business or Partner plan.`
+ : t`Sent to each recipient who has email notifications turned on.`,
+ icon: <LuMail />,
+ disabled: emailGated
+ };
+ case "slack":
+ return {
+ value,
+ title: t`Slack`,
+ description: slackConnected
+ ? t`Direct message to each recipient in your Slack workspace.`
+ : t`Connect Slack under Settings → Integrations first.`,
+ icon: <LuSlack />,
+ disabled: !slackConnected
+ };
+ // A new multi-select input with no wording of its own still renders.
+ default:
+ return { value, title: value };
+ }
+ });
+}
diff --git a/apps/erp/app/modules/workflows/ui/Builder/fields/menuNav.test.ts b/apps/erp/app/modules/workflows/ui/Builder/fields/menuNav.test.ts
index 9041fc810a..61a31e3d11 100644
--- a/apps/erp/app/modules/workflows/ui/Builder/fields/menuNav.test.ts
+++ b/apps/erp/app/modules/workflows/ui/Builder/fields/menuNav.test.ts
@@ -1,5 +1,11 @@
import { describe, expect, it } from "vitest";
-import { INITIAL_NAV, type NavState, navigate, rowsAt } from "./menuNav";
+import {
+ INITIAL_NAV,
+ itemsUnder,
+ type NavState,
+ navigate,
+ rowsAt
+} from "./menuNav";
import type { VariableTreeNode } from "./variableMenu";
const item = (id: string) => ({ id, label: id });
@@ -34,6 +40,25 @@ const stateOf = (result: ReturnType<typeof navigate>) => {
return result.state;
};
+describe("itemsUnder", () => {
+ it("collects every item in the tree at the root", () => {
+ expect(itemsUnder(tree, []).map((i) => i.id)).toEqual([
+ "record",
+ "name",
+ "email",
+ "count",
+ "inner"
+ ]);
+ });
+
+ it("collects only what is under the open level", () => {
+ expect(itemsUnder(tree, ["record"]).map((i) => i.id)).toEqual([
+ "name",
+ "email"
+ ]);
+ });
+});
+
describe("rowsAt", () => {
it("returns the root for an empty path", () => {
expect(rowsAt(tree, []).map((r) => r.key)).toEqual([
diff --git a/apps/erp/app/modules/workflows/ui/Builder/fields/menuNav.ts b/apps/erp/app/modules/workflows/ui/Builder/fields/menuNav.ts
index 3669a5b8b9..5a6947e00c 100644
--- a/apps/erp/app/modules/workflows/ui/Builder/fields/menuNav.ts
+++ b/apps/erp/app/modules/workflows/ui/Builder/fields/menuNav.ts
@@ -34,6 +34,24 @@ export function rowsAt(
return rows;
}
+/** Every selectable item at or below `path`, in tree order. Search runs on this, so
+ * drilling into a record searches that record instead of every step in the workflow —
+ * the same field name usually exists under several of them. */
+export function itemsUnder(
+ tree: VariableTreeNode[],
+ path: string[]
+): VariableMenuItem[] {
+ const items: VariableMenuItem[] = [];
+ const walk = (nodes: VariableTreeNode[]) => {
+ for (const node of nodes) {
+ if (node.item) items.push(node.item);
+ if (node.children?.length) walk(node.children);
+ }
+ };
+ walk(rowsAt(tree, path));
+ return items;
+}
+
type NavOptions = {
/** True in the popover host, where Backspace on an empty query pops a level.
* False in the editor host, where Backspace must delete the `{`. */
diff --git a/apps/erp/app/modules/workflows/ui/Builder/fields/multiChoice.test.ts b/apps/erp/app/modules/workflows/ui/Builder/fields/multiChoice.test.ts
new file mode 100644
index 0000000000..d5ebaa80ba
--- /dev/null
+++ b/apps/erp/app/modules/workflows/ui/Builder/fields/multiChoice.test.ts
@@ -0,0 +1,97 @@
+import type { ValueType } from "@carbon/workflows";
+import { describe, expect, it } from "vitest";
+import { choiceState, readChoices, writeChoices } from "./multiChoice";
+
+const CHOICES = ["inApp", "email", "slack"] as const;
+const TYPE: ValueType = {
+ kind: "list",
+ of: { kind: "primitive", of: "string" }
+};
+
+describe("readChoices", () => {
+ it("reads the members of a literal list", () => {
+ expect(
+ readChoices(
+ { kind: "literal", type: TYPE, value: ["inApp", "slack"] },
+ CHOICES
+ )
+ ).toEqual(["inApp", "slack"]);
+ });
+
+ it("drops members that are no longer offered", () => {
+ expect(
+ readChoices(
+ { kind: "literal", type: TYPE, value: ["email", "carrier-pigeon"] },
+ CHOICES
+ )
+ ).toEqual(["email"]);
+ });
+
+ it("reads nothing from an absent or non-literal value", () => {
+ expect(readChoices(undefined, CHOICES)).toEqual([]);
+ expect(
+ readChoices(
+ { kind: "ref", nodeId: "n", output: "record", path: [] },
+ CHOICES
+ )
+ ).toEqual([]);
+ expect(
+ readChoices({ kind: "literal", type: TYPE, value: "email" }, CHOICES)
+ ).toEqual([]);
+ });
+});
+
+describe("choiceState", () => {
+ const OPTIONS = [
+ { value: "inApp" },
+ { value: "email", disabled: true },
+ { value: "slack" }
+ ];
+ const stored = (...names: string[]) =>
+ ({ kind: "literal", type: TYPE, value: names }) as const;
+
+ it("ticks a locked choice on a node that stores nothing", () => {
+ expect(choiceState(OPTIONS, undefined, ["inApp"])).toEqual({
+ shown: ["inApp"],
+ frozen: ["inApp", "email"]
+ });
+ });
+
+ it("leaves an unavailable choice removable once it is stored", () => {
+ // The seeded default puts email on a node whose company has no plan for it. Freezing
+ // it there would leave the author looking at a channel they cannot clear.
+ expect(choiceState(OPTIONS, stored("inApp", "email"), ["inApp"])).toEqual({
+ shown: ["inApp", "email"],
+ frozen: ["inApp"]
+ });
+ });
+
+ it("shows the ticks in the order the choices are offered", () => {
+ expect(choiceState(OPTIONS, stored("slack", "inApp")).shown).toEqual([
+ "inApp",
+ "slack"
+ ]);
+ });
+});
+
+describe("writeChoices", () => {
+ it("stores the picks in the order they are offered", () => {
+ expect(writeChoices(["slack", "inApp"], CHOICES, TYPE)).toEqual({
+ kind: "literal",
+ type: TYPE,
+ value: ["inApp", "slack"]
+ });
+ });
+
+ it("stores an emptied set as absent", () => {
+ expect(writeChoices([], CHOICES, TYPE)).toBeUndefined();
+ });
+
+ it("ignores a pick that is not one of the choices", () => {
+ expect(writeChoices(["email", "sms"], CHOICES, TYPE)).toEqual({
+ kind: "literal",
+ type: TYPE,
+ value: ["email"]
+ });
+ });
+});
diff --git a/apps/erp/app/modules/workflows/ui/Builder/fields/multiChoice.ts b/apps/erp/app/modules/workflows/ui/Builder/fields/multiChoice.ts
new file mode 100644
index 0000000000..686525460d
--- /dev/null
+++ b/apps/erp/app/modules/workflows/ui/Builder/fields/multiChoice.ts
@@ -0,0 +1,70 @@
+import type { ValueOrRef, ValueType } from "@carbon/workflows";
+
+// The value round-trip for a multi-select input, with no React and no macro, so the
+// part that decides what gets STORED can be unit-tested.
+
+/**
+ * The choices a stored value holds. Anything that is not a literal list of the offered
+ * strings reads as nothing picked: a variable-bound or hand-edited value must not have
+ * its members half-rendered as ticks.
+ */
+export function readChoices(
+ value: ValueOrRef | undefined,
+ choices: readonly string[]
+): string[] {
+ if (value?.kind !== "literal") return [];
+ if (!Array.isArray(value.value)) return [];
+ return value.value.filter(
+ (entry): entry is string =>
+ typeof entry === "string" && choices.includes(entry)
+ );
+}
+
+/**
+ * What renders as ticked, and which options the author may not touch.
+ *
+ * `locked` is a choice the platform sends regardless (in-app): always ticked, never
+ * togglable. An UNAVAILABLE choice — one the company has no plan or integration for — is
+ * a different statement and must not be frozen the same way: it can never be added, but
+ * one that is already stored has to stay removable, or a node seeded with a channel the
+ * company cannot use is a dead end the author can see and not clear.
+ */
+export function choiceState(
+ options: readonly { value: string; disabled?: boolean }[],
+ value: ValueOrRef | undefined,
+ locked: readonly string[] = []
+): { shown: string[]; frozen: string[] } {
+ const stored = readChoices(
+ value,
+ options.map((option) => option.value)
+ );
+ const shown = options
+ .filter(
+ (option) => locked.includes(option.value) || stored.includes(option.value)
+ )
+ .map((option) => option.value);
+ const frozen = options
+ .filter(
+ (option) =>
+ locked.includes(option.value) ||
+ (option.disabled === true && !shown.includes(option.value))
+ )
+ .map((option) => option.value);
+ return { shown, frozen };
+}
+
+/**
+ * What to store for a set of picks. Ordered by the options rather than by the clicks —
+ * `ChoiceSelect` already does this, but two authors ticking the same channels must
+ * produce the same definition or autosave churns, and that is too load-bearing to
+ * leave to a caller. An emptied set stores as absent, like `pairsRows.ts`.
+ */
+export function writeChoices(
+ picked: readonly string[],
+ choices: readonly string[],
+ type: ValueType
+): ValueOrRef | undefined {
+ const ordered = choices.filter((choice) => picked.includes(choice));
+ if (ordered.length === 0) return undefined;
+ return { kind: "literal", type, value: ordered };
+}
diff --git a/apps/erp/app/modules/workflows/ui/Builder/fields/recordPickers.tsx b/apps/erp/app/modules/workflows/ui/Builder/fields/recordPickers.tsx
index f320d557f9..cfc594316f 100644
--- a/apps/erp/app/modules/workflows/ui/Builder/fields/recordPickers.tsx
+++ b/apps/erp/app/modules/workflows/ui/Builder/fields/recordPickers.tsx
@@ -135,6 +135,9 @@ const UserPicker = ({ value, onChange, isDisabled }: RecordPickerProps) => (
<UserSelect
value={value}
usersOnly
+ // "employee" is defined negatively by get_user_select_groups: not customer- and
+ // not supplier-flagged. Ad-hoc company groups stay listed.
+ type="employee"
isMulti={false}
insideCanvas
disabled={isDisabled}
@@ -147,6 +150,7 @@ const UserPicker = ({ value, onChange, isDisabled }: RecordPickerProps) => (
const GroupPicker = ({ value, onChange, isDisabled }: RecordPickerProps) => (
<UserSelect
value={value}
+ type="employee"
isMulti={false}
insideCanvas
disabled={isDisabled}
diff --git a/apps/erp/app/modules/workflows/ui/Builder/fields/tokenId.ts b/apps/erp/app/modules/workflows/ui/Builder/fields/tokenId.ts
index 1ee97e655b..1d069329d4 100644
--- a/apps/erp/app/modules/workflows/ui/Builder/fields/tokenId.ts
+++ b/apps/erp/app/modules/workflows/ui/Builder/fields/tokenId.ts
@@ -54,18 +54,35 @@ export function decodeTokenId(id: string): RefPart | undefined {
return undefined;
}
-/** `Step › output › property` — display only, so it follows a rename. */
-export function refLabel(ref: RefPart, nodeName?: string): string {
- if (ref.kind === "item") return ["Current item", ...ref.path].join(" › ");
+/** Path segments as the customer sees them. Only the segments the map names are replaced,
+ * so a shipped column keeps reading as itself. */
+export function namedPath(
+ path: string[],
+ segmentLabels?: Record<string, string>
+): string[] {
+ if (segmentLabels === undefined) return path;
+ return path.map((segment) => segmentLabels[segment] ?? segment);
+}
+
+/** `Step › output › property` — display only, so it follows a rename. `pathLabels` names
+ * the path segments as the customer sees them; the raw column names are the fallback. */
+export function refLabel(
+ ref: RefPart,
+ nodeName?: string,
+ pathLabels?: string[]
+): string {
+ const path = pathLabels ?? ref.path;
+ if (ref.kind === "item") return ["Current item", ...path].join(" › ");
// Only a real name is titled; the id fallback is not a slug.
const step = nodeName === undefined ? ref.nodeId : nodeNameLabel(nodeName);
- return [step, outputLabel(ref.output), ...ref.path].join(" › ");
+ return [step, outputLabel(ref.output), ...path].join(" › ");
}
/** Just the last segment — what a chip shows when the full path will not fit. `refLabel`
* stays the tooltip and the search text, so this is a short form, not a second source. */
-export function refLeafLabel(ref: RefPart): string {
- const last = ref.path[ref.path.length - 1];
+export function refLeafLabel(ref: RefPart, pathLabels?: string[]): string {
+ const path = pathLabels ?? ref.path;
+ const last = path[path.length - 1];
if (last !== undefined) return last;
return ref.kind === "item" ? "Current item" : outputLabel(ref.output);
}
diff --git a/apps/erp/app/modules/workflows/ui/Builder/fields/types.ts b/apps/erp/app/modules/workflows/ui/Builder/fields/types.ts
index d275d48fc4..54d6c6aee6 100644
--- a/apps/erp/app/modules/workflows/ui/Builder/fields/types.ts
+++ b/apps/erp/app/modules/workflows/ui/Builder/fields/types.ts
@@ -32,4 +32,6 @@ export type ValueFieldProps = {
/** Per-variable messages, keyed by the variable's position in the value. Only the
* broken one goes red; a sentence's other variables are left alone. */
partIssues?: Record<number, string>;
+ /** The version is published: show the value, refuse every edit. */
+ isReadOnly?: boolean;
};
diff --git a/apps/erp/app/modules/workflows/ui/Builder/fields/useVariableMenuData.ts b/apps/erp/app/modules/workflows/ui/Builder/fields/useVariableMenuData.ts
index d79a17328c..c3fcffdb4c 100644
--- a/apps/erp/app/modules/workflows/ui/Builder/fields/useVariableMenuData.ts
+++ b/apps/erp/app/modules/workflows/ui/Builder/fields/useVariableMenuData.ts
@@ -1,6 +1,6 @@
import type { ValueType } from "@carbon/workflows";
import { useCallback, useRef } from "react";
-import { catalog, useWorkflowLabel } from "../catalog";
+import { useWorkflowCatalog, useWorkflowLabel } from "../catalog";
import { describeVariable } from "../labelKeys";
import { useVariablesGetter } from "../useDefinition";
import type { VariableMenuData } from "./menuBridge";
@@ -15,6 +15,7 @@ export function useVariableMenuData(
textOnly?: boolean
): () => VariableMenuData {
const getVariables = useVariablesGetter(context.nodeId);
+ const catalog = useWorkflowCatalog();
// `useWorkflowLabel` returns a fresh closure each render; read it through a ref so
// the getter identity stays stable for callers that memoise on it.
@@ -39,5 +40,12 @@ export function useVariableMenuData(
? `No earlier step produces ${describeVariable(accepts, true, opts.labelFor)}.`
: undefined
};
- }, [getVariables, accepts, textOnly, context.inLoop, context.batching]);
+ }, [
+ getVariables,
+ accepts,
+ textOnly,
+ context.inLoop,
+ context.batching,
+ catalog
+ ]);
}
diff --git a/apps/erp/app/modules/workflows/ui/Builder/fields/valueParts.ts b/apps/erp/app/modules/workflows/ui/Builder/fields/valueParts.ts
index a843c8f583..a2272bb900 100644
--- a/apps/erp/app/modules/workflows/ui/Builder/fields/valueParts.ts
+++ b/apps/erp/app/modules/workflows/ui/Builder/fields/valueParts.ts
@@ -1,13 +1,15 @@
import type { VariableTextPart } from "@carbon/react/VariableText";
import type { TemplatePart, ValueOrRef } from "@carbon/workflows";
-import { decodeTokenId, encodeTokenId, refLabel } from "./tokenId";
+import { decodeTokenId, encodeTokenId, namedPath, refLabel } from "./tokenId";
/** What the editor shows for a stored value. Labels are resolved here and nowhere else. */
export function toEditorParts(
value: ValueOrRef | undefined,
nodeName: (id: string) => string | undefined,
/** Keyed by position in a template's parts; a bare reference is position 0. */
- partIssues?: Record<number, string>
+ partIssues?: Record<number, string>,
+ /** Path segment -> what the customer calls it. A custom field's segment is an id. */
+ segmentLabels?: Record<string, string>
): VariableTextPart[] {
const token = (part: TemplatePart, index: number): VariableTextPart => {
if (part.kind === "text") return { kind: "text", text: part.text };
@@ -16,7 +18,8 @@ export function toEditorParts(
id: encodeTokenId(part),
label: refLabel(
part,
- part.kind === "ref" ? nodeName(part.nodeId) : undefined
+ part.kind === "ref" ? nodeName(part.nodeId) : undefined,
+ namedPath(part.path, segmentLabels)
),
invalid: partIssues?.[index] !== undefined
};
diff --git a/apps/erp/app/modules/workflows/ui/Builder/fields/variableMenu.test.ts b/apps/erp/app/modules/workflows/ui/Builder/fields/variableMenu.test.ts
index 635a28b16d..c2e7e3aeef 100644
--- a/apps/erp/app/modules/workflows/ui/Builder/fields/variableMenu.test.ts
+++ b/apps/erp/app/modules/workflows/ui/Builder/fields/variableMenu.test.ts
@@ -235,18 +235,18 @@ describe("variableTree", () => {
).toBe(false);
});
- it("hides the record itself from a text field but keeps its properties", () => {
+ // A record prints as its readable id, so a text field offers it alongside its
+ // properties. A LIST of records still has no reading in a sentence.
+ it("offers the record itself in a text field, and its properties", () => {
const [record] =
variableTree([variable], catalog, { textOnly: true })[0].children ?? [];
- expect(record.item).toBeUndefined();
+ expect(record.item).toBeDefined();
expect(record.children?.length).toBeGreaterThan(0);
expect(
variableMenuItems([variable], catalog, { textOnly: true }).map((item) =>
decodeTokenId(item.id)
)
- ).not.toContainEqual(
- expect.objectContaining({ output: "record", path: [] })
- );
+ ).toContainEqual(expect.objectContaining({ output: "record", path: [] }));
});
it("labels properties through the resolver, not the raw column name", () => {
diff --git a/apps/erp/app/modules/workflows/ui/Builder/fields/variableMenu.ts b/apps/erp/app/modules/workflows/ui/Builder/fields/variableMenu.ts
index b35e796fa3..3394b97db5 100644
--- a/apps/erp/app/modules/workflows/ui/Builder/fields/variableMenu.ts
+++ b/apps/erp/app/modules/workflows/ui/Builder/fields/variableMenu.ts
@@ -11,12 +11,16 @@ import {
outputLabel,
propertyLabelKey
} from "../labelKeys";
-import { encodeTokenId, refLabel } from "./tokenId";
+import { encodeTokenId, refLabel, refLeafLabel } from "./tokenId";
export type VariableMenuItem = {
id: string;
label: string;
helper?: string;
+ /** Just the variable's own name. Search rows title themselves with this and show
+ * `label` underneath — a full breadcrumb in a narrow menu truncates away the one
+ * word the user typed. */
+ leaf?: string;
};
/** One row in the drill-down menu. `item` means selectable, `children` means drillable,
@@ -27,6 +31,9 @@ export type VariableTreeNode = {
helper?: string;
/** Plain-English explanation of what this field holds, shown as a tooltip. */
description?: string;
+ /** `Step › output › property`, shown on hover. Only search rows set it: they are
+ * the only rows the tree's own breadcrumb does not already place. */
+ fullPath?: string;
item?: VariableMenuItem;
children?: VariableTreeNode[];
};
@@ -77,6 +84,22 @@ function withoutDuplicateOutputs(
);
}
+/**
+ * What one property is called. The shipped translation first, then the catalog's own
+ * label — a custom field lives only there — and the raw column name last.
+ */
+function propertyLabel(
+ catalog: WorkflowCatalog,
+ labelFor: (key: string, fallback: string) => string,
+ entity: string,
+ property: string
+): string {
+ return labelFor(
+ propertyLabelKey(entity, property),
+ catalog.getPropertyLabel(entity, property) ?? property
+ );
+}
+
/**
* Flattens the variable list into menu entries, expanding entity properties up to
* `MAX_PATH` hops. Labels come from `refLabel`, the same function that renders an
@@ -100,7 +123,7 @@ export function variableMenuItems(
(!accepts || canAssign(type, accepts, { batching }));
for (const variable of withoutDuplicateOutputs(variables)) {
- const add = (path: string[], type: ValueType) => {
+ const add = (path: string[], labels: string[], type: ValueType) => {
if (!fits(type)) return;
const ref: VariableRef = {
kind: "ref",
@@ -110,12 +133,15 @@ export function variableMenuItems(
};
items.push({
id: encodeTokenId(ref),
- label: refLabel(ref, variable.nodeName),
+ // Named as the tree names them: search matches what the customer can see, which
+ // for a custom field is the only name they have ever been shown.
+ label: refLabel(ref, variable.nodeName, labels),
+ leaf: refLeafLabel(ref, labels),
helper: describeVariable(type, variable.guaranteed, labelFor)
});
};
- const expand = (type: ValueType, path: string[]) => {
+ const expand = (type: ValueType, path: string[], labels: string[]) => {
if (path.length >= MAX_PATH || type.kind !== "entity") return;
const entity = catalog.getEntity(type.of);
if (!entity) return;
@@ -123,13 +149,17 @@ export function variableMenuItems(
entity.properties
)) {
const nextPath = [...path, property];
- add(nextPath, propertyType);
- expand(propertyType, nextPath);
+ const nextLabels = [
+ ...labels,
+ propertyLabel(catalog, labelFor, type.of, property)
+ ];
+ add(nextPath, nextLabels, propertyType);
+ expand(propertyType, nextPath, nextLabels);
}
};
- add([], variable.type);
- expand(variable.type, []);
+ add([], [], variable.type);
+ expand(variable.type, [], []);
}
if (inLoop) {
@@ -137,6 +167,7 @@ export function variableMenuItems(
items.push({
id: encodeTokenId(ref),
label: refLabel(ref),
+ leaf: refLeafLabel(ref),
helper: "the item in the current loop"
});
}
@@ -168,6 +199,7 @@ export function variableTree(
variable: AvailableVariable,
type: ValueType,
path: string[],
+ pathLabels: string[],
label: string,
description?: string
): VariableTreeNode | null {
@@ -187,7 +219,10 @@ export function variableTree(
item: compatible
? {
id: encodeTokenId(ref),
- label: refLabel(ref, variable.nodeName),
+ label: refLabel(ref, variable.nodeName, pathLabels),
+ // The row's own label IS the leaf, so a search scoped to this level names
+ // its hits exactly as the level it drilled out of did.
+ leaf: label,
helper
}
: undefined
@@ -197,16 +232,23 @@ export function variableTree(
const entity = catalog.getEntity(type.of);
const children = entity
? Object.entries(entity.properties)
- .map(([property, propertyType]) =>
+ .map(([property, propertyType]) => {
// Property labels are catalog-driven; the raw column name is the fallback.
- build(
+ const propertyName = propertyLabel(
+ catalog,
+ labelFor,
+ type.of,
+ property
+ );
+ return build(
variable,
propertyType,
[...path, property],
- labelFor(propertyLabelKey(type.of, property), property),
+ [...pathLabels, propertyName],
+ propertyName,
entity.descriptions?.[property]
- )
- )
+ );
+ })
.filter((child): child is VariableTreeNode => child !== null)
: [];
if (children.length) node.children = children;
@@ -235,6 +277,7 @@ export function variableTree(
variable,
variable.type,
[],
+ [],
outputLabel(variable.output)
);
if (output) step.children!.push(output);
@@ -255,6 +298,7 @@ export function variableTree(
item: {
id: encodeTokenId(ref),
label: refLabel(ref),
+ leaf: refLeafLabel(ref),
helper: "the item in the current loop"
}
});
diff --git a/apps/erp/app/modules/workflows/ui/Builder/nodes/WorkflowNodeCard.tsx b/apps/erp/app/modules/workflows/ui/Builder/nodes/WorkflowNodeCard.tsx
index 1fc83dd756..9e157fab7b 100644
--- a/apps/erp/app/modules/workflows/ui/Builder/nodes/WorkflowNodeCard.tsx
+++ b/apps/erp/app/modules/workflows/ui/Builder/nodes/WorkflowNodeCard.tsx
@@ -7,7 +7,6 @@ import {
} from "@carbon/react";
import type { WorkflowNodeType } from "@carbon/workflows";
import { FAILURE_HANDLE } from "@carbon/workflows";
-import { WORKFLOW_LABELS } from "@carbon/workflows/labels";
import { Trans, useLingui } from "@lingui/react/macro";
import type { NodeProps } from "@xyflow/react";
import { useConnection } from "@xyflow/react";
@@ -20,6 +19,7 @@ import {
LuTriangleAlert,
LuX
} from "react-icons/lu";
+import { useWorkflowEventLabel } from "../catalog";
import type { AnyNodeForm } from "../config/forms/index";
import { NODE_FORMS } from "../config/forms/index";
import { InlineNodeName } from "../config/InlineNodeName";
@@ -46,7 +46,8 @@ import { NODE_KIND_META } from "./meta";
// Every node kind renders through this one component; what differs between kinds
// is data in `NODE_KIND_META`, not code.
function WorkflowNodeCardImpl({ id, type, data, selected }: NodeProps) {
- const { i18n, t } = useLingui();
+ const { t } = useLingui();
+ const eventLabel = useWorkflowEventLabel();
const node = asWorkflowNode(id, type as WorkflowNodeType, data);
const meta = NODE_KIND_META[node.type];
@@ -63,7 +64,10 @@ function WorkflowNodeCardImpl({ id, type, data, selected }: NodeProps) {
const isConnected = useBuilderStore(selectIsConnected(id));
const cardIssues = isConnected ? nodeIssues : [];
- const isReadOnly = useBuilderStore((state) => state.isReadOnly);
+ const canChangeDefinition = useBuilderStore(
+ (state) => state.canChangeDefinition
+ );
+ const isReadOnly = !canChangeDefinition;
const isOwner = useBuilderStore((state) => state.isOwner);
const openTestRun = useBuilderStore((state) => state.openTestRun);
@@ -106,10 +110,9 @@ function WorkflowNodeCardImpl({ id, type, data, selected }: NodeProps) {
}, [armed]);
const catalogId = meta.catalogId?.(node);
- const label = catalogId
- ? (WORKFLOW_LABELS[catalogId] && i18n._(WORKFLOW_LABELS[catalogId])) ||
- catalogId
- : undefined;
+ // Through the resolver, not `WORKFLOW_LABELS` directly: a custom-field trigger has no
+ // shipped label and would otherwise render its raw id on the card.
+ const label = catalogId ? eventLabel(catalogId, catalogId) : undefined;
const summary = label ?? meta.summary?.(node);
@@ -225,7 +228,12 @@ function WorkflowNodeCardImpl({ id, type, data, selected }: NodeProps) {
>
{builderNode && (
<div className="space-y-3">
- <Form key={id} node={builderNode} issues={nodeIssues} />
+ <Form
+ key={id}
+ node={builderNode}
+ issues={nodeIssues}
+ isReadOnly={isReadOnly}
+ />
</div>
)}
{hasFailureHandle && !hasFailureEdge && (
diff --git a/apps/erp/app/modules/workflows/ui/Builder/store.test.ts b/apps/erp/app/modules/workflows/ui/Builder/store.test.ts
index 9e15d54cbb..dacbfda57f 100644
--- a/apps/erp/app/modules/workflows/ui/Builder/store.test.ts
+++ b/apps/erp/app/modules/workflows/ui/Builder/store.test.ts
@@ -7,7 +7,8 @@ const store = () =>
createBuilderStore({
nodes: [createNode("trigger", { x: 0, y: 0 })] as unknown as BuilderNode[],
edges: [],
- isReadOnly: false,
+ isVersionLocked: false,
+ canEdit: true,
isOwner: true
});
diff --git a/apps/erp/app/modules/workflows/ui/Builder/store.ts b/apps/erp/app/modules/workflows/ui/Builder/store.ts
index fb25d327f6..424eca4668 100644
--- a/apps/erp/app/modules/workflows/ui/Builder/store.ts
+++ b/apps/erp/app/modules/workflows/ui/Builder/store.ts
@@ -51,7 +51,14 @@ export type BuilderState = {
* alongside `liveIssues`, and absent for a step that runs once. */
batchPlans: Record<string, BatchPlan>;
saveState: SaveState;
- isReadOnly: boolean;
+ /** This version is the promoted one. Behaviour edits are refused; positions are not. */
+ isVersionLocked: boolean;
+ /** The viewer holds workflows_update. */
+ canEdit: boolean;
+ /** Config, nodes, edges and expand state — everything that changes what it does. */
+ canChangeDefinition: boolean;
+ /** Layout only. Follows permission, NOT the lock: tidying a live version is allowed. */
+ canMoveNodes: boolean;
/** The viewer owns this workflow, so they may fire a test run. */
isOwner: boolean;
/** The trigger node whose test-run dialog is open, or null. */
@@ -111,9 +118,13 @@ export const snapshot = (nodes: BuilderNode[], edges: BuilderEdge[]) =>
export function createBuilderStore(initial: {
nodes: BuilderNode[];
edges: BuilderEdge[];
- isReadOnly: boolean;
+ isVersionLocked: boolean;
+ canEdit: boolean;
isOwner: boolean;
}) {
+ const canChangeDefinition = initial.canEdit && !initial.isVersionLocked;
+ const canMoveNodes = initial.canEdit;
+
return createStore<BuilderState>((set, get) => ({
nodes: initial.nodes,
edges: initial.edges,
@@ -122,7 +133,10 @@ export function createBuilderStore(initial: {
liveIssues: [],
batchPlans: {},
saveState: "idle",
- isReadOnly: initial.isReadOnly,
+ isVersionLocked: initial.isVersionLocked,
+ canEdit: initial.canEdit,
+ canChangeDefinition,
+ canMoveNodes,
isOwner: initial.isOwner,
testRunFor: null,
testRunStatus: "idle",
@@ -130,8 +144,19 @@ export function createBuilderStore(initial: {
baseline: snapshot(initial.nodes, initial.edges),
onNodesChange: (changes) => {
- const { isReadOnly, nodes } = get();
- if (isReadOnly) return;
+ const { canChangeDefinition, canMoveNodes, nodes } = get();
+
+ // Position, size and selection carry no behaviour, so they follow permission
+ // rather than the version lock — a live workflow can still be tidied and read.
+ const isLayout = (c: NodeChange<BuilderNode>) =>
+ c.type === "position" || c.type === "dimensions" || c.type === "select";
+
+ let incoming = changes;
+ if (!canChangeDefinition) {
+ if (!canMoveNodes) return;
+ incoming = changes.filter(isLayout);
+ if (!incoming.length) return;
+ }
// Protect the last trigger — deletion is allowed only when another remains.
const isRemove = (
@@ -140,27 +165,27 @@ export function createBuilderStore(initial: {
const triggerIds = new Set(
nodes.filter((n) => n.type === "trigger").map((n) => n.id)
);
- const triggerRemoveCount = changes
+ const triggerRemoveCount = incoming
.filter(isRemove)
.filter((c) => triggerIds.has(c.id)).length;
const allowed =
triggerRemoveCount >= triggerIds.size
- ? changes.filter((c) => !(isRemove(c) && triggerIds.has(c.id)))
- : changes;
+ ? incoming.filter((c) => !(isRemove(c) && triggerIds.has(c.id)))
+ : incoming;
if (!allowed.length) return;
set({ nodes: applyNodeChanges(allowed, nodes) });
},
onEdgesChange: (changes) => {
- const { isReadOnly, edges } = get();
- if (isReadOnly) return;
+ const { canChangeDefinition, edges } = get();
+ if (!canChangeDefinition) return;
set({ edges: applyEdgeChanges(changes, edges) });
},
onConnect: (connection) => {
- const { isReadOnly, nodes, edges } = get();
- if (isReadOnly) return;
+ const { canChangeDefinition, nodes, edges } = get();
+ if (!canChangeDefinition) return;
if (!canConnect(nodes, edges, connection)) return;
set({
@@ -180,8 +205,8 @@ export function createBuilderStore(initial: {
// unconnected. Without one (a palette click) it lands below the selection and
// is wired from that node's first unused handle.
addNode: (type, position) => {
- const { isReadOnly, nodes, edges, selectedNodeId } = get();
- if (isReadOnly) return;
+ const { canChangeDefinition, nodes, edges, selectedNodeId } = get();
+ if (!canChangeDefinition) return;
const takenNames = new Set(nodes.map((n) => n.name));
const from = position
@@ -257,14 +282,20 @@ export function createBuilderStore(initial: {
// in flight must stay dirty or the next autosave skips them.
rebaseline: (saved) => set({ baseline: saved }),
- updateNodeData: (id, patch) =>
+ // The single gate every node config form funnels through. Without it a live
+ // version's trigger could be switched to Schedule and — autosave being off — the
+ // edit silently evaporated on reload, with no toast and no explanation.
+ updateNodeData: (id, patch) => {
+ if (!get().canChangeDefinition) return;
set(({ nodes }) => ({
nodes: nodes.map((n) =>
n.id === id ? { ...n, data: { ...n.data, ...patch } } : n
)
- })),
+ }));
+ },
- renameNode: (id, name) =>
+ renameNode: (id, name) => {
+ if (!get().canChangeDefinition) return;
set(({ nodes }) => {
const slug = slugifyNodeName(name);
if (slug === "") return {};
@@ -275,9 +306,13 @@ export function createBuilderStore(initial: {
return {
nodes: nodes.map((n) => (n.id === id ? { ...n, name: unique } : n))
};
- }),
+ });
+ },
+ // `expanded` rides along in the persisted definition, so collapsing a card is a
+ // behaviour edit as far as the save route is concerned.
setNodeExpanded: (id, expanded) => {
+ if (!get().canChangeDefinition) return;
set(({ nodes }) => ({
nodes: nodes.map((n) => (n.id === id ? { ...n, expanded } : n))
}));
@@ -285,6 +320,7 @@ export function createBuilderStore(initial: {
},
setAllNodesExpanded: (expanded) => {
+ if (!get().canChangeDefinition) return;
set(({ nodes }) => ({
nodes: nodes.map((n) => ({ ...n, expanded }))
}));
@@ -292,14 +328,14 @@ export function createBuilderStore(initial: {
},
arrangeNodes: () => {
- const { nodes, edges, isReadOnly, setNodePositions } = get();
- if (isReadOnly) return;
+ const { nodes, edges, canMoveNodes, setNodePositions } = get();
+ if (!canMoveNodes) return;
setNodePositions(layoutPositions(nodes, edges));
},
setNodePositions: (positions) => {
- const { isReadOnly, nodes } = get();
- if (isReadOnly) return;
+ const { canMoveNodes, nodes } = get();
+ if (!canMoveNodes) return;
set({
nodes: nodes.map((n) =>
positions[n.id] ? { ...n, position: positions[n.id] } : n
@@ -308,7 +344,8 @@ export function createBuilderStore(initial: {
},
removeNode: (id) => {
- const { nodes, edges, selectedNodeId } = get();
+ const { canChangeDefinition, nodes, edges, selectedNodeId } = get();
+ if (!canChangeDefinition) return;
const node = nodes.find((n) => n.id === id);
if (!node) return;
if (
diff --git a/apps/erp/app/modules/workflows/ui/Builder/useDefinition.ts b/apps/erp/app/modules/workflows/ui/Builder/useDefinition.ts
index 9370a96179..c233cf66f5 100644
--- a/apps/erp/app/modules/workflows/ui/Builder/useDefinition.ts
+++ b/apps/erp/app/modules/workflows/ui/Builder/useDefinition.ts
@@ -3,6 +3,7 @@ import type {
BatchPlan,
ValueOrRef,
ValueType,
+ WorkflowCatalog,
WorkflowDefinition
} from "@carbon/workflows";
import {
@@ -12,7 +13,7 @@ import {
variablesFromHandle
} from "@carbon/workflows";
import { useCallback, useMemo } from "react";
-import { catalog } from "./catalog";
+import { useWorkflowCatalog } from "./catalog";
import { useBuilderStoreApi, useBuilderStoreShallow } from "./context";
import { fromReactFlow } from "./graph";
@@ -28,9 +29,10 @@ export function useDefinition(): WorkflowDefinition {
/** Variables visible to one node. A picker is mounted per input, so this must stay memoised. */
export function useAvailableVariables(nodeId: string) {
const definition = useDefinition();
+ const catalog = useWorkflowCatalog();
return useMemo(
() => availableVariables(definition, nodeId, catalog),
- [definition, nodeId]
+ [definition, nodeId, catalog]
);
}
@@ -41,20 +43,22 @@ export function useValueTypeResolver(
nodeId: string
): (value: ValueOrRef) => ValueType | undefined {
const definition = useDefinition();
+ const catalog = useWorkflowCatalog();
return useMemo(() => {
const { context } = createContext(definition, catalog);
return (value: ValueOrRef) => context.typeOf(value, nodeId);
- }, [definition, nodeId]);
+ }, [definition, nodeId, catalog]);
}
/** The same list, computed on demand. Subscribing re-renders every field on every
* drag frame; a menu only needs the list at the moment it opens. */
export function useVariablesGetter(nodeId: string): () => AvailableVariable[] {
const store = useBuilderStoreApi();
+ const catalog = useWorkflowCatalog();
return useCallback(() => {
const { nodes, edges } = store.getState();
return availableVariables(fromReactFlow(nodes, edges), nodeId, catalog);
- }, [store, nodeId]);
+ }, [store, nodeId, catalog]);
}
/**
@@ -63,7 +67,8 @@ export function useVariablesGetter(nodeId: string): () => AvailableVariable[] {
* definition would rebuild it on every drag frame, once per card.
*/
export function batchPlansFor(
- definition: WorkflowDefinition
+ definition: WorkflowDefinition,
+ catalog: WorkflowCatalog
): Record<string, BatchPlan> {
const { context } = createContext(definition, catalog);
const plans: Record<string, BatchPlan> = {};
@@ -90,6 +95,7 @@ export function useActionBatchPlan(
inputs: Record<string, ValueOrRef>
): BatchPlan {
const typeOf = useValueTypeResolver(nodeId);
+ const catalog = useWorkflowCatalog();
return useMemo(() => {
const action = actionId ? catalog.getAction(actionId) : undefined;
if (action === undefined) return { kind: "none" };
@@ -97,7 +103,7 @@ export function useActionBatchPlan(
const supplied = inputs[name];
return supplied === undefined ? undefined : typeOf(supplied);
});
- }, [actionId, inputs, typeOf]);
+ }, [actionId, inputs, typeOf, catalog]);
}
/** The name of the compute operation input that is wired to a list, or undefined when
@@ -108,6 +114,7 @@ export function useComputeBatchInput(
inputs: Record<string, ValueOrRef>
): string | undefined {
const typeOf = useValueTypeResolver(nodeId);
+ const catalog = useWorkflowCatalog();
return useMemo(() => {
const operation = operationId
? catalog.getOperation(operationId)
@@ -121,7 +128,7 @@ export function useComputeBatchInput(
if (type?.kind === "list") return name;
}
return undefined;
- }, [operationId, inputs, typeOf]);
+ }, [operationId, inputs, typeOf, catalog]);
}
export type HandlePreview = {
@@ -136,6 +143,7 @@ export function useHandlePreviewGetter(
handleId: string
): () => HandlePreview {
const store = useBuilderStoreApi();
+ const catalog = useWorkflowCatalog();
return useCallback(() => {
const { nodes, edges } = store.getState();
const definition = fromReactFlow(nodes, edges);
@@ -147,5 +155,5 @@ export function useHandlePreviewGetter(
variables: variablesFromHandle(definition, nodeId, handleId, catalog),
routesOnly: outputs !== undefined && Object.keys(outputs).length === 0
};
- }, [store, nodeId, handleId]);
+ }, [store, nodeId, handleId, catalog]);
}
diff --git a/apps/erp/app/modules/workflows/ui/Runs/WorkflowRunDetail.tsx b/apps/erp/app/modules/workflows/ui/Runs/WorkflowRunDetail.tsx
index 4a7ba75df1..fc2d15101f 100644
--- a/apps/erp/app/modules/workflows/ui/Runs/WorkflowRunDetail.tsx
+++ b/apps/erp/app/modules/workflows/ui/Runs/WorkflowRunDetail.tsx
@@ -11,7 +11,7 @@ import type {
WorkflowRunDetail as WorkflowRunDetailType,
WorkflowRunStep
} from "../../workflows.service";
-import { useWorkflowLabel } from "../Builder/catalog";
+import { useWorkflowEventLabel, useWorkflowLabel } from "../Builder/catalog";
import { EntityRecordLink } from "./EntityRecordLink";
import { RunLiveUpdates } from "./RunLiveUpdates";
import { RunStatus, TestRunBadge } from "./RunStatus";
@@ -97,7 +97,10 @@ export function WorkflowRunDetail({
(run.workflow as { name?: string } | null)?.name ?? run.workflowId;
const label = useWorkflowLabel();
- const eventLabel = run.eventId ? label(run.eventId, run.eventId) : null;
+ const triggerLabel = useWorkflowEventLabel();
+ const eventLabel = run.eventId
+ ? triggerLabel(run.eventId, run.eventId)
+ : null;
const isInFlight = run.status === "Queued" || run.status === "Running";
const compacted = run.compactedAt !== null;
diff --git a/apps/erp/app/modules/workflows/ui/Runs/WorkflowRunsTable.tsx b/apps/erp/app/modules/workflows/ui/Runs/WorkflowRunsTable.tsx
index ccf9b3fe86..5793925815 100644
--- a/apps/erp/app/modules/workflows/ui/Runs/WorkflowRunsTable.tsx
+++ b/apps/erp/app/modules/workflows/ui/Runs/WorkflowRunsTable.tsx
@@ -2,7 +2,7 @@ import { HStack } from "@carbon/react";
import { formatDateTime, formatDurationMilliseconds } from "@carbon/utils";
import { useLingui } from "@lingui/react/macro";
import type { ColumnDef } from "@tanstack/react-table";
-import { memo, useMemo } from "react";
+import { memo, useMemo, useRef } from "react";
import {
LuCalendar,
LuClock,
@@ -15,7 +15,7 @@ import { EmployeeAvatar, Hyperlink, Table } from "~/components";
import { useUser } from "~/hooks";
import { path } from "~/utils/path";
import type { WorkflowRun } from "../../workflows.service";
-import { labelText } from "../Builder/nodes/meta";
+import { useWorkflowEventLabel } from "../Builder/catalog";
import { EntityRecordLink } from "./EntityRecordLink";
import { RunsLiveUpdates } from "./RunLiveUpdates";
import { RunStatus, TestRunBadge } from "./RunStatus";
@@ -28,6 +28,11 @@ type WorkflowRunsTableProps = {
const WorkflowRunsTable = memo(({ data, count }: WorkflowRunsTableProps) => {
const { t } = useLingui();
const { company } = useUser();
+ // A fresh closure each render, so the columns memo reads it through a ref rather than
+ // rebuilding every column on every render.
+ const eventLabel = useWorkflowEventLabel();
+ const eventLabelRef = useRef(eventLabel);
+ eventLabelRef.current = eventLabel;
const hasInFlight = data.some(
(row) => row.status === "Queued" || row.status === "Running"
@@ -70,7 +75,7 @@ const WorkflowRunsTable = memo(({ data, count }: WorkflowRunsTableProps) => {
cell: ({ row }) => {
const eventId = row.original.eventId;
if (!eventId) return "—";
- return labelText(eventId) ?? eventId;
+ return eventLabelRef.current(eventId, eventId);
},
meta: { icon: <LuZap /> }
},
diff --git a/apps/erp/app/modules/workflows/ui/WorkflowLockAlert.tsx b/apps/erp/app/modules/workflows/ui/WorkflowLockAlert.tsx
new file mode 100644
index 0000000000..a9fc650361
--- /dev/null
+++ b/apps/erp/app/modules/workflows/ui/WorkflowLockAlert.tsx
@@ -0,0 +1,75 @@
+import { Alert, AlertDescription, AlertTitle, Button } from "@carbon/react";
+import { Trans } from "@lingui/react/macro";
+import { LuTriangleAlert } from "react-icons/lu";
+import { useFetcher } from "react-router";
+import { path } from "~/utils/path";
+
+type WorkflowLockAlertProps = {
+ workflowId: string;
+ /** Branched from, when the reader makes a new version. */
+ versionId: string;
+ /** The reader may create a version. Telling someone without that permission to
+ * "create a new version" would be wrong, so the two cases get different copy. */
+ canCreateVersion: boolean;
+ className?: string;
+};
+
+/**
+ * Shown above the canvas whenever the open version is the live one. The 14px lock glyph
+ * in the header is not enough: without this, an edit on a published version is refused
+ * silently and the author only finds out when it vanishes on reload.
+ */
+const WorkflowLockAlert = ({
+ workflowId,
+ versionId,
+ canCreateVersion,
+ className
+}: WorkflowLockAlertProps) => {
+ const fetcher = useFetcher();
+
+ // The new-version route is POST-only and copies the version you are looking at,
+ // so this submits rather than linking.
+ const newVersion = () => {
+ const formData = new FormData();
+ formData.set("copyFromVersionId", versionId);
+ fetcher.submit(formData, {
+ method: "post",
+ action: path.to.workflowVersionNew(workflowId)
+ });
+ };
+
+ return (
+ <Alert variant="warning" className={className}>
+ <LuTriangleAlert />
+ <AlertTitle>
+ <Trans>This version is live</Trans>
+ </AlertTitle>
+ <AlertDescription>
+ {canCreateVersion ? (
+ <Trans>
+ This version is live. Create a new version to make changes. You can
+ still move steps around to tidy the layout.
+ </Trans>
+ ) : (
+ <Trans>
+ This version is live, so it cannot be changed. You can still move
+ steps around to tidy the layout.
+ </Trans>
+ )}
+ </AlertDescription>
+ {canCreateVersion && (
+ <Button
+ variant="secondary"
+ size="sm"
+ className="mt-2 w-fit"
+ isDisabled={fetcher.state !== "idle"}
+ onClick={newVersion}
+ >
+ <Trans>New version</Trans>
+ </Button>
+ )}
+ </Alert>
+ );
+};
+
+export default WorkflowLockAlert;
diff --git a/apps/erp/app/modules/workflows/workflows.models.ts b/apps/erp/app/modules/workflows/workflows.models.ts
index add5f1ee0c..b3e7ba8d2d 100644
--- a/apps/erp/app/modules/workflows/workflows.models.ts
+++ b/apps/erp/app/modules/workflows/workflows.models.ts
@@ -14,6 +14,12 @@ export const workflowDefinitionSaveValidator = z.object({
formatVersion: zfd.numeric(z.number().int())
});
+/** Layout only. The one payload a live version accepts — see `$id.positions.tsx`. */
+export const workflowNodePositionsValidator = z.object({
+ versionId: z.string().min(1, { message: "Version is required" }),
+ positions: z.string().min(1)
+});
+
export const workflowTestRunValidator = z.object({
/** The version the run is recorded against. The canvas can be a step ahead of it
* — autosave is a second behind — but it is what a reader can open afterwards. */
diff --git a/apps/erp/app/modules/workflows/workflows.service.ts b/apps/erp/app/modules/workflows/workflows.service.ts
index c68e8d43b5..a709cd2eba 100644
--- a/apps/erp/app/modules/workflows/workflows.service.ts
+++ b/apps/erp/app/modules/workflows/workflows.service.ts
@@ -184,6 +184,59 @@ export async function updateWorkflowDefinition(
.eq("companyId", definition.companyId);
}
+/**
+ * The one writer allowed on a live version. It reads the version's nodes and re-writes
+ * only `position`, only for node ids that already exist — `edges`, `data`, `expanded`,
+ * `name` and `type` are never touched, and an unknown id is ignored. The endpoint is
+ * therefore incapable of changing behaviour even when called by hand.
+ *
+ * No audit bump, for the same reason as the canvas state below: tidying a layout is not
+ * an edit, and stamping `updatedAt` would reorder the list on every drag.
+ */
+export async function updateWorkflowNodePositions(
+ client: SupabaseClient<Database>,
+ {
+ versionId,
+ workflowId,
+ companyId,
+ positions
+ }: {
+ versionId: string;
+ workflowId: string;
+ companyId: string;
+ positions: Record<string, { x: number; y: number }>;
+ }
+) {
+ // Scoped to the workflow in the URL as well as the version in the body, so the two
+ // cannot disagree — otherwise the path segment is decorative.
+ const version = await client
+ .from("workflowVersion")
+ .select("nodes")
+ .eq("id", versionId)
+ .eq("workflowId", workflowId)
+ .eq("companyId", companyId)
+ .maybeSingle();
+
+ if (version.error) return { data: null, error: version.error };
+ if (!version.data || !Array.isArray(version.data.nodes)) {
+ return { data: null, error: { message: "Version not found" } };
+ }
+
+ const nodes = (version.data.nodes as unknown[]).map((node) => {
+ const id = (node as { id?: unknown })?.id;
+ const position = typeof id === "string" ? positions[id] : undefined;
+ return position === undefined
+ ? node
+ : { ...(node as object), position: { x: position.x, y: position.y } };
+ });
+
+ return client
+ .from("workflowVersion")
+ .update({ nodes: nodes as unknown as Json })
+ .eq("id", versionId)
+ .eq("companyId", companyId);
+}
+
// No audit bump: panning the canvas is not an edit to the workflow, and stamping
// `updatedAt` here would reorder the list on every scroll.
export async function updateWorkflowCanvasState(
diff --git a/apps/erp/app/routes/onboarding+/_layout.tsx b/apps/erp/app/routes/onboarding+/_layout.tsx
index 853d650c2d..0482dde938 100644
--- a/apps/erp/app/routes/onboarding+/_layout.tsx
+++ b/apps/erp/app/routes/onboarding+/_layout.tsx
@@ -75,8 +75,12 @@ export default function OnboardingLayout() {
<TooltipProvider>
<div className="relative h-screen w-screen">
<MeshGradientBackground />
- <div className="relative z-10 flex h-full w-full items-center justify-center p-4">
- <Outlet />
+ {/* The scroll container is the wrapper, not the centering flex — a step
+ taller than the window would otherwise be clipped at both ends. */}
+ <div className="absolute inset-0 z-10 overflow-y-auto">
+ <div className="flex min-h-full w-full items-center justify-center p-4">
+ <Outlet />
+ </div>
</div>
</div>
</TooltipProvider>
diff --git a/apps/erp/app/routes/x+/workflow+/$id.positions.tsx b/apps/erp/app/routes/x+/workflow+/$id.positions.tsx
new file mode 100644
index 0000000000..707b6b102f
--- /dev/null
+++ b/apps/erp/app/routes/x+/workflow+/$id.positions.tsx
@@ -0,0 +1,70 @@
+import { assertIsPost } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { requirePlan } from "@carbon/ee/plan.server";
+import { validationError, validator } from "@carbon/form";
+import type { ActionFunctionArgs } from "react-router";
+import { data } from "react-router";
+import { z } from "zod";
+import {
+ updateWorkflowNodePositions,
+ workflowNodePositionsValidator
+} from "~/modules/workflows";
+import { path } from "~/utils/path";
+
+const positionsSchema = z.record(
+ z.string(),
+ z.object({ x: z.number(), y: z.number() })
+);
+
+// Node positions carry no behaviour, so the live-version lock deliberately does not
+// apply here — a published workflow may still be tidied. The service writes positions
+// only, and only onto node ids that already exist, so this route cannot change what a
+// workflow does even when called by hand. `/save` stays locked.
+export async function action({ params, request }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { id } = params;
+ if (!id) throw new Error("Could not find id");
+ const { client, companyId } = await requirePermissions(request, {
+ update: "workflows"
+ });
+ await requirePlan({
+ request,
+ client,
+ companyId,
+ feature: "WORKFLOWS",
+ redirectTo: path.to.workflows
+ });
+
+ const validation = await validator(workflowNodePositionsValidator).validate(
+ await request.formData()
+ );
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(validation.data.positions);
+ } catch {
+ return data({ ok: false, error: "Malformed positions" }, { status: 400 });
+ }
+
+ const positions = positionsSchema.safeParse(parsed);
+ if (!positions.success) {
+ return data({ ok: false, error: "Malformed positions" }, { status: 400 });
+ }
+
+ const update = await updateWorkflowNodePositions(client, {
+ versionId: validation.data.versionId,
+ workflowId: id,
+ companyId,
+ positions: positions.data
+ });
+
+ if (update.error) {
+ return data({ ok: false, error: update.error.message }, { status: 500 });
+ }
+
+ return data({ ok: true });
+}
diff --git a/apps/erp/app/routes/x+/workflow+/$id.tsx b/apps/erp/app/routes/x+/workflow+/$id.tsx
index dd0a8e5408..8fca76645b 100644
--- a/apps/erp/app/routes/x+/workflow+/$id.tsx
+++ b/apps/erp/app/routes/x+/workflow+/$id.tsx
@@ -35,6 +35,7 @@ import { IssuesPanel } from "~/modules/workflows/ui/Builder/IssuesPanel";
import { LiveValidation } from "~/modules/workflows/ui/Builder/LiveValidation";
import { TestRunDialog } from "~/modules/workflows/ui/Builder/TestRun/TestRunDialog";
import { WorkflowBuilder } from "~/modules/workflows/ui/Builder/WorkflowBuilder";
+import WorkflowLockAlert from "~/modules/workflows/ui/WorkflowLockAlert";
import type { Handle } from "~/utils/handle";
import { detailBreadcrumb } from "~/utils/handle";
import { path } from "~/utils/path";
@@ -55,7 +56,11 @@ export const handle: Handle = {
// Neither write may revalidate the loader: a save would re-seed the canvas mid-edit
// and lose the selection, a canvas write would snap the viewport back.
export function shouldRevalidate({ formAction }: ShouldRevalidateFunctionArgs) {
- return !formAction?.includes("/save") && !formAction?.includes("/canvas");
+ return (
+ !formAction?.includes("/save") &&
+ !formAction?.includes("/canvas") &&
+ !formAction?.includes("/positions")
+ );
}
export async function loader({ request, params }: LoaderFunctionArgs) {
@@ -107,7 +112,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
definition: null,
failure: "no-versions" as const,
message: "This workflow has no versions.",
- isReadOnly: true
+ isVersionLocked: true
};
}
@@ -128,7 +133,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
definition: null,
failure: read.failure,
message: read.message,
- isReadOnly: true
+ isVersionLocked: true
};
}
@@ -141,7 +146,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
definition: read.definition,
failure: null,
message: null,
- isReadOnly: versionId === workflow.activeVersionId
+ isVersionLocked: versionId === workflow.activeVersionId
};
}
@@ -156,10 +161,12 @@ export default function WorkflowBuilderRoute() {
versionId,
definition,
message,
- isReadOnly: isLiveVersion
+ isVersionLocked
} = useLoaderData<typeof loader>();
- const isReadOnly = isLiveVersion || !permissions.can("update", "workflows");
+ // Two reasons, two behaviours: a locked version still allows dragging, a missing
+ // permission does not — and the two want different copy in the banner.
+ const canEdit = permissions.can("update", "workflows");
const isOwner = workflow.ownerId === userId;
if (!definition || !versionId) {
@@ -181,10 +188,11 @@ export default function WorkflowBuilderRoute() {
return (
<ReactFlowProvider>
<WorkflowBuilderProvider
- key={`${versionId}:${isReadOnly}:${isOwner}`}
+ key={`${versionId}:${isVersionLocked}:${canEdit}:${isOwner}`}
nodes={nodes}
edges={edges}
- isReadOnly={isReadOnly}
+ isVersionLocked={isVersionLocked}
+ canEdit={canEdit}
isOwner={isOwner}
>
<div className="flex h-[calc(100dvh-49px)] w-full flex-col">
@@ -194,6 +202,14 @@ export default function WorkflowBuilderRoute() {
versionId={versionId}
onIssues={issuesDisclosure.onOpen}
/>
+ {isVersionLocked && (
+ <WorkflowLockAlert
+ workflowId={workflow.id}
+ versionId={versionId}
+ canCreateVersion={permissions.can("create", "workflows")}
+ className="mx-4 mt-3"
+ />
+ )}
<div className="relative flex flex-1 overflow-hidden">
<WorkflowBuilder
workflowId={workflow.id}
diff --git a/apps/erp/app/utils/path.ts b/apps/erp/app/utils/path.ts
index c5239719ec..ba39cd67ca 100644
--- a/apps/erp/app/utils/path.ts
+++ b/apps/erp/app/utils/path.ts
@@ -2173,6 +2173,8 @@ export const path = {
workflowCanvas: (id: string) => generatePath(`${x}/workflow/${id}/canvas`),
workflowDelete: (id: string) => generatePath(`${x}/workflows/delete/${id}`),
workflowNew: `${x}/workflows/new`,
+ workflowPositions: (id: string) =>
+ generatePath(`${x}/workflow/${id}/positions`),
workflowPublish: (id: string) =>
generatePath(`${x}/workflow/${id}/publish`),
workflowRename: (id: string) => generatePath(`${x}/workflows/${id}/rename`),
diff --git a/packages/checks/src/scripts/check-workflow-events.ts b/packages/checks/src/scripts/check-workflow-events.ts
index a40ff8163f..373ba93e6f 100644
--- a/packages/checks/src/scripts/check-workflow-events.ts
+++ b/packages/checks/src/scripts/check-workflow-events.ts
@@ -1,10 +1,20 @@
/**
- * Every event id a live workflow subscribes to must still exist in the generated
- * catalog. Needs a live database: `pnpm --filter @carbon/checks workflow-events`.
+ * Every event id a live workflow subscribes to must still resolve. Needs a live database:
+ * `pnpm --filter @carbon/checks workflow-events`. Does NOT run in CI — no job in
+ * .github/workflows has database credentials. Run it by hand after a catalog change.
+ *
+ * Two shapes of drift:
+ * - a shipped id the catalog no longer has (a rename left it behind);
+ * - a custom-field id whose `customField` row is gone. That one the catalog cannot
+ * catch on its own — it PARSES those ids rather than looking them up, deliberately,
+ * so that it stays company-blind. The existence check therefore lives here.
*/
-import { createWorkflowCatalog } from "@carbon/workflows";
+import { createWorkflowCatalog, REGISTRY_ENTRIES } from "@carbon/workflows";
import { Client } from "pg";
+const CUSTOM_FIELD_EVENT =
+ /^([A-Za-z][A-Za-z0-9]*)\.customFields\.([^.]+)\.changed$/;
+
async function main() {
const connectionString =
process.env.DATABASE_URL ?? process.env.SUPABASE_DB_URL;
@@ -33,22 +43,51 @@ async function main() {
ORDER BY t."eventId"`
);
- const unknown = rows.filter(
- (row) => catalog.getEvent(row.eventId) === undefined
+ // `${companyId}:${table}:${fieldId}` for every custom field that still exists.
+ const { rows: fields } = await client.query<{
+ id: string;
+ table: string;
+ companyId: string;
+ }>(`SELECT "id", "table", "companyId" FROM "customField"`);
+ const known = new Set(
+ fields.map((f) => `${f.companyId}:${f.table}:${f.id}`)
);
- for (const row of unknown) {
- console.log(
- `FAIL workflow ${row.workflowId} (company ${row.companyId}) subscribes to "${row.eventId}", which is not in the catalog.`
- );
+ const failures: string[] = [];
+
+ for (const row of rows) {
+ if (catalog.getEvent(row.eventId) === undefined) {
+ failures.push(
+ `FAIL workflow ${row.workflowId} (company ${row.companyId}) subscribes to "${row.eventId}", which is not in the catalog.`
+ );
+ continue;
+ }
+
+ // The catalog only proves the id is well formed and names a triggerable entity.
+ // Whether the field itself still exists is company data, so it is checked here —
+ // this is what surfaces a trigger left behind by a deleted custom field.
+ const match = CUSTOM_FIELD_EVENT.exec(row.eventId);
+ if (match === null) continue;
+ const [, entity, fieldId] = match;
+ const table =
+ entity === undefined ? undefined : REGISTRY_ENTRIES[entity]?.table;
+ if (table === undefined || fieldId === undefined) continue;
+
+ if (!known.has(`${row.companyId}:${table}:${fieldId}`)) {
+ failures.push(
+ `FAIL workflow ${row.workflowId} (company ${row.companyId}) subscribes to custom field "${fieldId}" on ${table}, which no longer exists in this company.`
+ );
+ }
}
- if (unknown.length === 0) {
+ for (const line of failures) console.log(line);
+
+ if (failures.length === 0) {
console.log(
`PASS workflow-events (${rows.length} subscription(s) all resolve)`
);
}
- process.exit(unknown.length > 0 ? 1 : 0);
+ process.exit(failures.length > 0 ? 1 : 0);
} finally {
await client.end();
}
diff --git a/packages/database/src/swagger-docs-schema.ts b/packages/database/src/swagger-docs-schema.ts
index b53c0f571f..2cf1e419c3 100644
--- a/packages/database/src/swagger-docs-schema.ts
+++ b/packages/database/src/swagger-docs-schema.ts
@@ -88815,6 +88815,52 @@ export default {
tags: ["(rpc) sync_edit_document_transaction"]
}
},
+ "/rpc/workflow_merge_custom_fields": {
+ post: {
+ parameters: [
+ {
+ in: "body",
+ name: "args",
+ required: true,
+ schema: {
+ properties: {
+ p_company_id: {
+ format: "text",
+ type: "string"
+ },
+ p_id: {
+ format: "text",
+ type: "string"
+ },
+ p_table: {
+ format: "text",
+ type: "string"
+ },
+ p_values: {
+ format: "jsonb"
+ }
+ },
+ required: ["p_table", "p_id", "p_company_id", "p_values"],
+ 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) workflow_merge_custom_fields"]
+ }
+ },
"/rpc/get_jobs_by_date_range": {
post: {
parameters: [
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index 580bbf3f15..35876a3d6c 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -66860,14 +66860,14 @@ export type Database = {
},
{
foreignKeyName: "partner_id_fkey"
- columns: ["supplierLocationId"]
+ columns: ["id"]
isOneToOne: false
referencedRelation: "supplierLocation"
referencedColumns: ["id"]
},
{
foreignKeyName: "partner_id_fkey"
- columns: ["id"]
+ columns: ["supplierLocationId"]
isOneToOne: false
referencedRelation: "supplierLocation"
referencedColumns: ["id"]
@@ -72493,14 +72493,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["paymentCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["paymentCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -78498,6 +78498,15 @@ export type Database = {
}
uuid_generate_v4: { Args: never; Returns: string }
uuid_to_base58: { Args: { _uuid: string }; Returns: string }
+ workflow_merge_custom_fields: {
+ Args: {
+ p_company_id: string
+ p_id: string
+ p_table: string
+ p_values: Json
+ }
+ Returns: undefined
+ }
xid: { Args: { _at?: string }; Returns: unknown }
xid_counter: { Args: { _xid: unknown }; Returns: number }
xid_decode: { Args: { _xid: unknown }; Returns: number[] }
diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.ts
index 580bbf3f15..35876a3d6c 100644
--- a/packages/database/supabase/functions/lib/types.ts
+++ b/packages/database/supabase/functions/lib/types.ts
@@ -66860,14 +66860,14 @@ export type Database = {
},
{
foreignKeyName: "partner_id_fkey"
- columns: ["supplierLocationId"]
+ columns: ["id"]
isOneToOne: false
referencedRelation: "supplierLocation"
referencedColumns: ["id"]
},
{
foreignKeyName: "partner_id_fkey"
- columns: ["id"]
+ columns: ["supplierLocationId"]
isOneToOne: false
referencedRelation: "supplierLocation"
referencedColumns: ["id"]
@@ -72493,14 +72493,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["paymentCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["paymentCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -78498,6 +78498,15 @@ export type Database = {
}
uuid_generate_v4: { Args: never; Returns: string }
uuid_to_base58: { Args: { _uuid: string }; Returns: string }
+ workflow_merge_custom_fields: {
+ Args: {
+ p_company_id: string
+ p_id: string
+ p_table: string
+ p_values: Json
+ }
+ Returns: undefined
+ }
xid: { Args: { _at?: string }; Returns: unknown }
xid_counter: { Args: { _xid: unknown }; Returns: number }
xid_decode: { Args: { _xid: unknown }; Returns: number[] }
diff --git a/packages/database/supabase/migrations/20260819105102_workflow-merge-custom-fields.sql b/packages/database/supabase/migrations/20260819105102_workflow-merge-custom-fields.sql
new file mode 100644
index 0000000000..6a7ec01233
--- /dev/null
+++ b/packages/database/supabase/migrations/20260819105102_workflow-merge-custom-fields.sql
@@ -0,0 +1,38 @@
+-- A workflow may now set a custom field. Setting one must not erase the others, and
+-- reading the blob, merging in app code and writing it back races a concurrent human
+-- edit — the person's change is silently dropped. So the merge happens server-side, in
+-- one statement, with jsonb `||`.
+--
+-- SECURITY INVOKER: a workflow acts as its owner, and RLS on the target table is the
+-- authorization gate, exactly as it is for the ordinary column update issued beside this
+-- one. p_table is validated against "customFieldTable" — the global allowlist that
+-- already exists — before it is ever interpolated into the dynamic statement.
+CREATE OR REPLACE FUNCTION workflow_merge_custom_fields (
+ p_table TEXT,
+ p_id TEXT,
+ p_company_id TEXT,
+ p_values JSONB
+)
+RETURNS VOID
+LANGUAGE "plpgsql"
+SECURITY INVOKER
+SET search_path = public
+AS $$
+BEGIN
+ IF NOT EXISTS (SELECT 1 FROM "customFieldTable" WHERE "table" = p_table) THEN
+ RAISE EXCEPTION 'Unknown custom field table: %', p_table;
+ END IF;
+
+ IF p_values IS NULL OR jsonb_typeof(p_values) <> 'object' THEN
+ RAISE EXCEPTION 'p_values must be a JSON object';
+ END IF;
+
+ EXECUTE format(
+ 'UPDATE %I SET "customFields" = COALESCE("customFields", ''{}''::jsonb) || $1 '
+ 'WHERE "id" = $2 AND "companyId" = $3',
+ p_table
+ ) USING p_values, p_id, p_company_id;
+END;
+$$;
+
+GRANT EXECUTE ON FUNCTION workflow_merge_custom_fields(TEXT, TEXT, TEXT, JSONB) TO authenticated;
diff --git a/packages/documents/package.json b/packages/documents/package.json
index f4ed79a432..f785d81057 100644
--- a/packages/documents/package.json
+++ b/packages/documents/package.json
@@ -3,6 +3,7 @@
"dependencies": {
"@bwip-js/node": "4.9.0",
"@carbon/env": "workspace:*",
+ "@carbon/notifications": "workspace:*",
"@carbon/react": "workspace:*",
"@carbon/utils": "workspace:*",
"@hookform/resolvers": "3.10.0",
diff --git a/packages/documents/src/email/NotificationEmail.tsx b/packages/documents/src/email/NotificationEmail.tsx
index e82ad5c952..d8b7d29a9f 100644
--- a/packages/documents/src/email/NotificationEmail.tsx
+++ b/packages/documents/src/email/NotificationEmail.tsx
@@ -1,3 +1,4 @@
+import { renderInlineLinks } from "@carbon/notifications";
import {
Body,
Button,
@@ -12,8 +13,9 @@ import {
import { Logo } from "./components/Logo";
import { EmailThemeProvider, getEmailThemeClasses } from "./components/Theme";
-// Structurally compatible with `NotificationDetail` from `@carbon/notifications`
-// (kept local so the email package needn't depend on the notifications package).
+// Structurally compatible with `NotificationDetail` from `@carbon/notifications`,
+// which this file now also imports `renderInlineLinks` from — the parser must be the
+// same one the in-app bell uses, or a link that works in one place fails in the other.
interface NotificationDetail {
label: string;
value: string;
@@ -31,6 +33,10 @@ interface Props {
ctaLabel?: string;
ctaUrl?: string;
details?: NotificationDetail[];
+ // The ERP origin. A `[label](url)` in a detail value is rendered as a real anchor
+ // only when the url is an https url on THIS origin; without it every value stays
+ // literal text, which is the safe default for a customer-authored body.
+ erpUrl?: string;
// When set, renders the "Manage notification settings" footer.
settingsUrl?: string;
}
@@ -193,6 +199,7 @@ export const NotificationEmail = ({
ctaLabel = "View details",
ctaUrl,
details,
+ erpUrl,
settingsUrl
}: Props) => {
const themeClasses = getEmailThemeClasses();
@@ -311,7 +318,26 @@ export const NotificationEmail = ({
<Text
className={`text-[13px] leading-[20px] m-0 font-medium ${themeClasses.text}`}
>
- {detail.value}
+ {erpUrl
+ ? renderInlineLinks(detail.value, erpUrl).map(
+ (segment, i) =>
+ "href" in segment ? (
+ <Link
+ // Segments have no stable id; the value is
+ // re-rendered whole or not at all.
+ // biome-ignore lint/suspicious/noArrayIndexKey: no stable id
+ key={i}
+ href={segment.href}
+ style={{ color: "#2563eb" }}
+ >
+ {segment.text}
+ </Link>
+ ) : (
+ // biome-ignore lint/suspicious/noArrayIndexKey: no stable id
+ <span key={i}>{segment.text}</span>
+ )
+ )
+ : detail.value}
</Text>
</td>
</tr>
diff --git a/packages/glossary/src/terms.ts b/packages/glossary/src/terms.ts
index 50874eebc2..5bae9c73a7 100644
--- a/packages/glossary/src/terms.ts
+++ b/packages/glossary/src/terms.ts
@@ -1998,6 +1998,10 @@ export const terms = {
term: msg`About (notification)`,
definition: msg`The record a workflow notification points at, named as an id plus its kind; leave it empty and the notification links to the workflow run itself.`
},
+ "workflow-notify-channels": {
+ term: msg`Notification Type`,
+ definition: msg`Where a workflow notification is delivered — in-app is always sent, while email needs a Business or Partner plan and Slack needs your Slack workspace connected.`
+ },
"workflow-webhook-url": {
term: msg`Webhook URL`,
definition: msg`The https address a workflow's webhook step posts to — plain http, redirects, and hosts resolving to private or link-local addresses are refused, and the call gives up after ten seconds.`
diff --git a/packages/jobs/AGENTS.md b/packages/jobs/AGENTS.md
index bd5013a14d..0fd110176b 100644
--- a/packages/jobs/AGENTS.md
+++ b/packages/jobs/AGENTS.md
@@ -127,7 +127,7 @@ Routing is off the catalog's `getActionRoute(id)`, never off the shape of an id.
| `services.ts` | `createWorkflowServices` — routes an action id to `notify`, `webhook`, the update path or the create path; the only export the engine uses |
| `dispatcher.ts` | The `setWorkflowDispatch` seam (below) |
| `create.ts` | `runCreateAction` — creates through the ERP's own `upsert*` service function via the dispatcher, so sequence numbers, defaults and required-field logic are the app's; digs the new row's id out of the returned envelope |
-| `update.ts` | `runUpdateAction` — writes the catalog's allowlisted columns on one record. Checks the target and **every entity-typed value** exists in this company before writing, and rejects a value outside a column's enum. Also exports `toPlainValue` |
+| `update.ts` | `runUpdateAction` — writes the catalog's allowlisted columns on one record. Checks the target and **every entity-typed value** exists in this company before writing, and rejects a value outside a column's enum. A custom field is written separately, through the `workflow_merge_custom_fields` RPC, so setting one cannot erase the others |
| `notify.ts` | `runNotifyAction` — one `trigger("notify", …)` with `NotificationEvent.Workflow`. A role IS a group and every user has an identity group whose id is their user id, so both recipient inputs collapse to `groupIds` |
| `search.ts` | `runSearch` — one Lookup node's search, translated to PostgREST filters that mean exactly what `runtime/compare.ts` says (`contains`/`startsWith`/`endsWith` → `ilike`). Reads `MAX_LIST_ITEMS + 1` so an over-cap list is detectable |
| `operations.ts` | `runOperation` — the 15 read-only computations, one `COMPUTATIONS` entry per catalog operation id. An id with no implementation refuses rather than falls through; a throw becomes a failed node, never a thrown walk |
diff --git a/packages/jobs/src/inngest/functions/notifications/content.ts b/packages/jobs/src/inngest/functions/notifications/content.ts
index ed498bb837..4ac45bb80b 100644
--- a/packages/jobs/src/inngest/functions/notifications/content.ts
+++ b/packages/jobs/src/inngest/functions/notifications/content.ts
@@ -1311,6 +1311,9 @@ export function getNotificationEmailComponent(args: {
ctaLabel: args.ctaLabel,
ctaUrl: args.ctaUrl,
details: args.content.details,
+ // Only a link on our own origin is rendered as an anchor; anything else in a
+ // customer-authored body stays literal text.
+ erpUrl: ERP_URL,
heading: args.heading,
message: args.content.description,
preview: args.heading,
diff --git a/packages/jobs/src/inngest/functions/notifications/notify.ts b/packages/jobs/src/inngest/functions/notifications/notify.ts
index e545f9c476..40f659b35f 100644
--- a/packages/jobs/src/inngest/functions/notifications/notify.ts
+++ b/packages/jobs/src/inngest/functions/notifications/notify.ts
@@ -9,12 +9,14 @@ import { getSlackUserIdByCarbonId } from "@carbon/ee/slack.server";
import { ERP_URL } from "@carbon/env";
import type { Events } from "@carbon/lib/events";
import {
+ escapeSlackText,
getNotificationEmailCtaLabel,
getNotificationEmailHeading,
getNotificationTopic,
isRecurringNotificationEvent,
NotificationDestination,
- NotificationEvent
+ NotificationEvent,
+ renderSlackMrkdwn
} from "@carbon/notifications";
import { datetime } from "@carbon/utils";
import { render } from "@react-email/components";
@@ -26,16 +28,6 @@ import {
getNotificationEmailComponent
} from "./content";
-// Slack mrkdwn requires &, <, > escaped in text; inside a <url|label> a
-// literal "|" would also terminate the label, so it's swapped for a lookalike.
-function escapeSlackText(value: string): string {
- return value
- .replace(/&/g, "&amp;")
- .replace(/</g, "&lt;")
- .replace(/>/g, "&gt;")
- .replace(/\|/g, "¦");
-}
-
async function getCompanyIntegrations(
client: ReturnType<typeof getCarbonServiceRole>,
companyId: string
@@ -686,6 +678,12 @@ export const notifyFunction = inngest.createFunction(
payload.companyId,
payload.documentType
);
+ const slackDetailLines = details
+ .map(
+ (detail) =>
+ `${escapeSlackText(detail.label)}: ${renderSlackMrkdwn(detail.value, ERP_URL)}`
+ )
+ .join("\n");
// Digest: one mrkdwn-linked line per document (items are the
// actions, no footer link). Otherwise: detail rows + footer link.
const text = digestItems
@@ -699,7 +697,7 @@ export const notifyFunction = inngest.createFunction(
})
].join("\n")
: `${description}${
- detailLines ? `\n${detailLines}` : ""
+ slackDetailLines ? `\n${slackDetailLines}` : ""
}\n<${ctaUrl}|View in Carbon>`;
const slackUserIds = await Promise.all(
diff --git a/packages/jobs/src/workflows/actions/notify.test.ts b/packages/jobs/src/workflows/actions/notify.test.ts
index 62eb51a899..22d955e714 100644
--- a/packages/jobs/src/workflows/actions/notify.test.ts
+++ b/packages/jobs/src/workflows/actions/notify.test.ts
@@ -1,6 +1,9 @@
-import { NotificationEvent } from "@carbon/notifications";
+import {
+ NotificationDestination,
+ NotificationEvent
+} from "@carbon/notifications";
import type { RuntimeValue } from "@carbon/workflows";
-import { entityValue, primitiveValue } from "@carbon/workflows";
+import { entityValue, listValue, primitiveValue } from "@carbon/workflows";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { runNotifyAction } from "./notify";
@@ -79,6 +82,45 @@ describe("runNotifyAction", () => {
expect(triggerMock).not.toHaveBeenCalled();
});
+ const channels = (...names: string[]) =>
+ listValue(
+ { kind: "primitive", of: "string" },
+ names.map((name) => primitiveValue("string", name))
+ ).value;
+
+ it("passes the chosen channels through as destinations", async () => {
+ await run({
+ user: entityValue("user", "usr_1"),
+ subject,
+ channels: channels("inApp", "slack")
+ });
+
+ expect(triggerMock).toHaveBeenCalledWith(
+ "notify",
+ expect.objectContaining({
+ destinations: [
+ NotificationDestination.InApp,
+ NotificationDestination.Slack
+ ]
+ })
+ );
+ });
+
+ // An absent field is the job's "use the default map for this event", which is what a
+ // node saved before the input existed still means.
+ it("omits destinations when no channel is chosen or none is recognised", async () => {
+ await run({ user: entityValue("user", "usr_1"), subject });
+ expect(triggerMock.mock.calls[0]?.[1]).not.toHaveProperty("destinations");
+
+ triggerMock.mockClear();
+ await run({
+ user: entityValue("user", "usr_1"),
+ subject,
+ channels: channels("carrier-pigeon")
+ });
+ expect(triggerMock.mock.calls[0]?.[1]).not.toHaveProperty("destinations");
+ });
+
it("falls back to the run id as the document when no record is named", async () => {
await run({ user: entityValue("user", "usr_1"), subject });
expect(triggerMock).toHaveBeenCalledWith(
diff --git a/packages/jobs/src/workflows/actions/notify.ts b/packages/jobs/src/workflows/actions/notify.ts
index 1bc72aa4ff..4ec1fc110a 100644
--- a/packages/jobs/src/workflows/actions/notify.ts
+++ b/packages/jobs/src/workflows/actions/notify.ts
@@ -1,10 +1,15 @@
import type { Database } from "@carbon/database";
import { trigger } from "@carbon/lib/trigger";
-import { NotificationEvent } from "@carbon/notifications";
+import {
+ NotificationDestination,
+ NotificationEvent
+} from "@carbon/notifications";
import type { ActionOutcome, RuntimeValue } from "@carbon/workflows";
type ApprovalDocumentType = Database["public"]["Enums"]["approvalDocumentType"];
+const DESTINATIONS = new Set<string>(Object.values(NotificationDestination));
+
function entityId(value: RuntimeValue | undefined): string | undefined {
return value?.kind === "entity" && value.id ? value.id : undefined;
}
@@ -15,6 +20,21 @@ function text(value: RuntimeValue | undefined): string | undefined {
return rendered === "" ? undefined : rendered;
}
+/**
+ * The channels the customer ticked, or undefined to leave the notify job on its default
+ * map for this event. A name the job would not recognise is dropped rather than passed
+ * on — an unknown destination is silently ignored there, so it would read as delivered.
+ */
+function channels(
+ value: RuntimeValue | undefined
+): NotificationDestination[] | undefined {
+ if (value?.kind !== "list") return undefined;
+ const picked = value.items
+ .map((item) => (item.kind === "primitive" ? String(item.value) : ""))
+ .filter((name) => DESTINATIONS.has(name)) as NotificationDestination[];
+ return picked.length > 0 ? [...new Set(picked)] : undefined;
+}
+
/** `subject` and `message` arrive already rendered, so nothing here reads a template. */
export async function runNotifyAction(params: {
companyId: string;
@@ -34,10 +54,14 @@ export async function runNotifyAction(params: {
const aboutId = text(inputs.aboutId);
const aboutType = text(inputs.aboutType);
+ const destinations = channels(inputs.channels);
await trigger("notify", {
body: text(inputs.message),
companyId,
+ // Omitted rather than empty: the job reads an absent field as "use the default map",
+ // which is what a node saved before this input existed still means.
+ ...(destinations ? { destinations } : {}),
// The run stands in as the subject when the customer named no record.
documentId: aboutId ?? runId,
// The payload type is the approval enum; the column is TEXT and the link
diff --git a/packages/jobs/src/workflows/actions/update.ts b/packages/jobs/src/workflows/actions/update.ts
index c806cdc19e..3df94917c0 100644
--- a/packages/jobs/src/workflows/actions/update.ts
+++ b/packages/jobs/src/workflows/actions/update.ts
@@ -3,6 +3,7 @@ import { datetime } from "@carbon/utils";
import {
type ActionOutcome,
type CatalogAction,
+ CUSTOM_FIELD_PREFIX,
entityValue,
REGISTRY_ENTRIES,
type RuntimeValue
@@ -74,6 +75,8 @@ export async function runUpdateAction(params: {
if (!found) return { ok: false, error: `That ${entity} could not be read.` };
const fields: Record<string, unknown> = {};
+ // Keyed by custom field id — the key inside the JSONB blob, not the prefixed input name.
+ const customFields: Record<string, unknown> = {};
for (const [column, value] of Object.entries(inputs)) {
if (column === entity) continue;
@@ -93,12 +96,30 @@ export async function runUpdateAction(params: {
return { ok: false, error: `"${String(raw)}" is not a valid ${column}.` };
}
+ if (column.startsWith(CUSTOM_FIELD_PREFIX)) {
+ // The ERP's form layer writes every custom field as a FormData string, so the
+ // blob holds strings whatever the declared type. `fromColumn` coerces back by
+ // the DECLARED type on read, so a string here round-trips exactly.
+ customFields[column.slice(CUSTOM_FIELD_PREFIX.length)] =
+ raw === null ? null : String(raw);
+ continue;
+ }
+
fields[column] = raw;
}
// The tenancy guarantee: a reference must belong to this company, whatever
// supplied it. Skipping it would let a workflow point at another tenant's row.
- for (const [column, raw] of Object.entries(fields)) {
+ // A User/Customer/Supplier custom field is a reference like any other.
+ const references: [string, unknown][] = [
+ ...Object.entries(fields),
+ ...Object.entries(customFields).map(
+ ([fieldId, raw]) =>
+ [`${CUSTOM_FIELD_PREFIX}${fieldId}`, raw] as [string, unknown]
+ )
+ ];
+
+ for (const [column, raw] of references) {
if (raw === null) continue;
const spec = action.inputs[column];
const scope =
@@ -121,21 +142,38 @@ export async function runUpdateAction(params: {
}
}
- const { error } = await client
- .from(table)
- .update({
- ...fields,
- updatedBy: ownerId,
- updatedAt: datetime.timestamp()
- })
- .eq("id", target.id)
- .eq("companyId", companyId);
+ if (Object.keys(fields).length > 0) {
+ const { error } = await client
+ .from(table)
+ .update({
+ ...fields,
+ updatedBy: ownerId,
+ updatedAt: datetime.timestamp()
+ })
+ .eq("id", target.id)
+ .eq("companyId", companyId);
+
+ if (error) return { ok: false, error: error.message };
+ }
- if (error) return { ok: false, error: error.message };
+ if (Object.keys(customFields).length > 0) {
+ // One statement, server-side `||` merge: setting one field must not erase the
+ // others, and a read-modify-write here would race a concurrent human edit.
+ const { error } = await client.rpc("workflow_merge_custom_fields", {
+ p_table: table,
+ p_id: target.id,
+ p_company_id: companyId,
+ p_values: customFields
+ });
+
+ if (error) return { ok: false, error: error.message };
+ }
return {
ok: true,
outputs: { record: entityValue(entity, target.id) },
- summary: `Updated ${Object.keys(fields).length} field(s).`
+ summary: `Updated ${
+ Object.keys(fields).length + Object.keys(customFields).length
+ } field(s).`
};
}
diff --git a/packages/jobs/src/workflows/engine/batch.test.ts b/packages/jobs/src/workflows/engine/batch.test.ts
index 02440b0ed3..b7eb31a30a 100644
--- a/packages/jobs/src/workflows/engine/batch.test.ts
+++ b/packages/jobs/src/workflows/engine/batch.test.ts
@@ -21,11 +21,28 @@ vi.mock("./ledger", () => ({
failInterruptedSteps: vi.fn(async () => 0)
}));
vi.mock("./owner", () => ({
- getOwnerClient: vi.fn(async () => ({})),
+ // The engine reads the company custom fields through this client; a bare {} has no
+ // `.from`, so the stub answers that one query with an empty list.
+ getOwnerClient: vi.fn(async () => ({
+ from: () => ({
+ select: () => ({
+ eq: () => ({ eq: async () => ({ data: [], error: null }) })
+ })
+ })
+ })),
readOwnerPermissions: vi.fn(async () => ({})),
hasPermission: () => true
}));
vi.mock("../actions", () => ({ createWorkflowServices: vi.fn() }));
+// The real module pulls in the email templates and @carbon/env; the engine only wants a URL.
+vi.mock("../../inngest/functions/notifications/content", () => ({
+ buildNotificationLink: (
+ event: string,
+ documentId: string,
+ companyId: string
+ ) =>
+ `https://erp.test/api/link?event=${event}&documentId=${documentId}&companyId=${companyId}`
+}));
const { executeWorkflowRun } = await import("./execute");
const { loadRunContext } = await import("./log");
@@ -192,6 +209,7 @@ describe("batch mode", () => {
expect(ids).toEqual([
"load",
+ "custom-fields",
"permissions",
// The trigger is recorded before the walk starts at its successors.
"node:t1",
@@ -212,6 +230,7 @@ describe("batch mode", () => {
expect(ids).toEqual([
"load",
+ "custom-fields",
"permissions",
"node:t1",
"node:look",
diff --git a/packages/jobs/src/workflows/engine/end-to-end.test.ts b/packages/jobs/src/workflows/engine/end-to-end.test.ts
index d42f129834..b4d1242853 100644
--- a/packages/jobs/src/workflows/engine/end-to-end.test.ts
+++ b/packages/jobs/src/workflows/engine/end-to-end.test.ts
@@ -24,11 +24,28 @@ vi.mock("./ledger", () => ({
failInterruptedSteps: vi.fn(async () => 0)
}));
vi.mock("./owner", () => ({
- getOwnerClient: vi.fn(async () => ({})),
+ // The engine reads the company custom fields through this client; a bare {} has no
+ // `.from`, so the stub answers that one query with an empty list.
+ getOwnerClient: vi.fn(async () => ({
+ from: () => ({
+ select: () => ({
+ eq: () => ({ eq: async () => ({ data: [], error: null }) })
+ })
+ })
+ })),
readOwnerPermissions: vi.fn(async () => ({})),
hasPermission: () => true
}));
vi.mock("../actions", () => ({ createWorkflowServices: vi.fn() }));
+// The real module pulls in the email templates and @carbon/env; the engine only wants a URL.
+vi.mock("../../inngest/functions/notifications/content", () => ({
+ buildNotificationLink: (
+ event: string,
+ documentId: string,
+ companyId: string
+ ) =>
+ `https://erp.test/api/link?event=${event}&documentId=${documentId}&companyId=${companyId}`
+}));
const { executeWorkflowRun } = await import("./execute");
const { loadRunContext } = await import("./log");
diff --git a/packages/jobs/src/workflows/engine/execute.test.ts b/packages/jobs/src/workflows/engine/execute.test.ts
index 284f55606c..68435e2bf6 100644
--- a/packages/jobs/src/workflows/engine/execute.test.ts
+++ b/packages/jobs/src/workflows/engine/execute.test.ts
@@ -18,11 +18,28 @@ vi.mock("./ledger", () => ({
failInterruptedSteps: vi.fn(async () => 0)
}));
vi.mock("./owner", () => ({
- getOwnerClient: vi.fn(async () => ({})),
+ // The engine reads the company custom fields through this client; a bare {} has no
+ // `.from`, so the stub answers that one query with an empty list.
+ getOwnerClient: vi.fn(async () => ({
+ from: () => ({
+ select: () => ({
+ eq: () => ({ eq: async () => ({ data: [], error: null }) })
+ })
+ })
+ })),
readOwnerPermissions: vi.fn(async () => ({})),
hasPermission: vi.fn(() => true)
}));
vi.mock("../actions", () => ({ createWorkflowServices: vi.fn() }));
+// The real module pulls in the email templates and @carbon/env; the engine only wants a URL.
+vi.mock("../../inngest/functions/notifications/content", () => ({
+ buildNotificationLink: (
+ event: string,
+ documentId: string,
+ companyId: string
+ ) =>
+ `https://erp.test/api/link?event=${event}&documentId=${documentId}&companyId=${companyId}`
+}));
const { executeWorkflowRun } = await import("./execute");
const { loadRunContext, claimRun, finishRun } = await import("./log");
@@ -151,7 +168,7 @@ describe("the owner's permissions", () => {
await executeWorkflowRun({ payload, step, logger });
- expect(ids).toEqual(["load", "permissions"]);
+ expect(ids).toEqual(["load", "custom-fields", "permissions"]);
expect(vi.mocked(finishRun).mock.calls.at(-1)?.[1]).toMatchObject({
status: "Failed",
error: "The owner of this workflow no longer has access to Purchasing."
diff --git a/packages/jobs/src/workflows/engine/execute.ts b/packages/jobs/src/workflows/engine/execute.ts
index 9e83769974..59e75f59b4 100644
--- a/packages/jobs/src/workflows/engine/execute.ts
+++ b/packages/jobs/src/workflows/engine/execute.ts
@@ -1,6 +1,9 @@
+import { NotificationEvent } from "@carbon/notifications";
import { datetime } from "@carbon/utils";
import {
batchCandidates,
+ buildCatalogOverlay,
+ type CustomFieldDef,
createWorkflowCatalog,
executorFor,
FAILURE_HANDLE,
@@ -20,6 +23,7 @@ import {
} from "@carbon/workflows";
import { NonRetriableError } from "inngest";
import { getJobDatabaseClient, type JobDatabase } from "../../db";
+import { buildNotificationLink } from "../../inngest/functions/notifications/content";
import { createWorkflowServices } from "../actions";
import {
claimStep,
@@ -129,6 +133,18 @@ async function contextFor(args: NodeArgs): Promise<RuntimeContext> {
catalog,
loader: createEntityLoader({ client, companyId: payload.companyId, cache }),
outputs: args.outputs,
+ // The one place a workflow value becomes a URL. `/api/link` performs the company
+ // switch before redirecting, so a recipient whose active company differs still
+ // lands on the right record. Only inputs the catalog marks `linkify` use this.
+ linkFor: (of: string, id: string) =>
+ buildNotificationLink(
+ NotificationEvent.Workflow,
+ id,
+ payload.companyId,
+ // The column is TEXT and the link resolver reads the workflow entity name;
+ // the payload type is the approval enum, so the cast mirrors notify.ts.
+ of as Parameters<typeof buildNotificationLink>[3]
+ ),
...(args.item === undefined ? {} : { item: args.item }),
...(args.record === undefined ? {} : { record: args.record }),
services: createWorkflowServices({
@@ -349,7 +365,6 @@ export async function executeWorkflowRun(params: {
logger: EngineLogger;
}): Promise<{ runId: string; status: string; steps: number }> {
const { payload, step, logger } = params;
- const catalog = createWorkflowCatalog();
const loaded = await step.run("load", async () => {
const db = getJobDatabaseClient();
@@ -403,6 +418,28 @@ export async function executeWorkflowRun(params: {
const { definition, startedAt, companyGroupId } = loaded;
+ // The catalog is build-time and global; custom fields are runtime and per company, so
+ // they arrive as an overlay merged in here. Read as the OWNER, like every other business
+ // read — a field the owner may not see must not reach the workflow. Its own step so a
+ // transient read failure retries without redoing the run claim above.
+ const customFields = await step.run("custom-fields", async () => {
+ const client = await getOwnerClient(payload.ownerId, payload.runId);
+ const { data, error } = await client
+ .from("customField")
+ .select("table, id, name, dataTypeId, listOptions, active")
+ .eq("companyId", payload.companyId)
+ .eq("active", true);
+ // A refused read is an empty set under RLS, not an error, so an error here is transient
+ // and worth the retry — swallowing it would silently run against the shipped catalog.
+ if (error)
+ throw new Error(`Could not read custom fields: ${error.message}`);
+ return data ?? [];
+ });
+
+ const catalog = createWorkflowCatalog(
+ buildCatalogOverlay(customFields as CustomFieldDef[])
+ );
+
const ledger = createDatabaseLedger(getJobDatabaseClient(), {
runId: payload.runId,
companyId: payload.companyId
diff --git a/packages/jobs/src/workflows/engine/manual.test.ts b/packages/jobs/src/workflows/engine/manual.test.ts
index 009ba4ed0b..28f6992579 100644
--- a/packages/jobs/src/workflows/engine/manual.test.ts
+++ b/packages/jobs/src/workflows/engine/manual.test.ts
@@ -60,11 +60,28 @@ const getJobDatabaseClient = vi.fn(() => ({
}));
vi.mock("../../db", () => ({ getJobDatabaseClient }));
vi.mock("./owner", () => ({
- getOwnerClient: vi.fn(async () => ({})),
+ // The engine reads the company custom fields through this client; a bare {} has no
+ // `.from`, so the stub answers that one query with an empty list.
+ getOwnerClient: vi.fn(async () => ({
+ from: () => ({
+ select: () => ({
+ eq: () => ({ eq: async () => ({ data: [], error: null }) })
+ })
+ })
+ })),
readOwnerPermissions: vi.fn(async () => ({})),
hasPermission: vi.fn(() => true)
}));
vi.mock("../actions", () => ({ createWorkflowServices: vi.fn() }));
+// The real module pulls in the email templates and @carbon/env; the engine only wants a URL.
+vi.mock("../../inngest/functions/notifications/content", () => ({
+ buildNotificationLink: (
+ event: string,
+ documentId: string,
+ companyId: string
+ ) =>
+ `https://erp.test/api/link?event=${event}&documentId=${documentId}&companyId=${companyId}`
+}));
const { executeManualWorkflowRun } = await import("./manual");
const { createWorkflowServices } = await import("../actions");
diff --git a/packages/jobs/src/workflows/event-ids.test.ts b/packages/jobs/src/workflows/event-ids.test.ts
index 9bdd3b02bb..84d40c06f2 100644
--- a/packages/jobs/src/workflows/event-ids.test.ts
+++ b/packages/jobs/src/workflows/event-ids.test.ts
@@ -85,3 +85,59 @@ describe("computeEventIds", () => {
).toEqual([]);
});
});
+
+describe("custom-field events", () => {
+ const update = (
+ table: string,
+ oldFields: Record<string, unknown> | undefined,
+ newFields: Record<string, unknown> | undefined
+ ) =>
+ computeEventIds({
+ table,
+ operation: "UPDATE",
+ old: { ...base, customFields: oldFields },
+ new: { ...base, customFields: newFields }
+ });
+
+ it("derives the id from the diff key", () => {
+ expect(update("purchaseOrder", { cf_1: "a" }, { cf_1: "b" })).toEqual([
+ "purchaseOrder.customFields.cf_1.changed"
+ ]);
+ });
+
+ it("emits nothing for an untouched custom field", () => {
+ expect(update("purchaseOrder", { cf_1: "a" }, { cf_1: "a" })).toEqual([]);
+ });
+
+ it("emits one id per changed field", () => {
+ expect(
+ update(
+ "purchaseOrder",
+ { cf_1: "a", cf_2: "x" },
+ { cf_1: "b", cf_2: "y" }
+ )
+ ).toEqual([
+ "purchaseOrder.customFields.cf_1.changed",
+ "purchaseOrder.customFields.cf_2.changed"
+ ]);
+ });
+
+ // Item custom fields live on the subtypes; the catalog triggers on `item`.
+ it("emits nothing for item", () => {
+ expect(update("item", { cf_1: "a" }, { cf_1: "b" })).toEqual([]);
+ });
+
+ it("puts the watched column's id first when both changed", () => {
+ expect(
+ computeEventIds({
+ table: "purchaseOrder",
+ operation: "UPDATE",
+ old: { ...base, status: "Draft", customFields: { cf_1: "a" } },
+ new: { ...base, status: "Planned", customFields: { cf_1: "b" } }
+ })
+ ).toEqual([
+ "purchaseOrder.status.changed",
+ "purchaseOrder.customFields.cf_1.changed"
+ ]);
+ });
+});
diff --git a/packages/jobs/src/workflows/event-ids.ts b/packages/jobs/src/workflows/event-ids.ts
index f4fa9eafa3..45ec20f377 100644
--- a/packages/jobs/src/workflows/event-ids.ts
+++ b/packages/jobs/src/workflows/event-ids.ts
@@ -1,6 +1,15 @@
-import { WORKFLOW_EVENTS } from "@carbon/workflows";
+import {
+ CUSTOM_FIELD_PREFIX,
+ createWorkflowCatalog,
+ customFieldEventId,
+ ENTITY_BY_TABLE,
+ WORKFLOW_EVENTS
+} from "@carbon/workflows";
import { computeDiff } from "../inngest/functions/events/diff";
+// A facade over module-load maps; building it once here keeps the hot path allocation-free.
+const CATALOG = createWorkflowCatalog();
+
type TableIndex = {
created?: string;
deleted?: string;
@@ -54,5 +63,24 @@ export function computeEventIds(input: {
for (const [field, id] of entry.changed) {
if (field in diff) ids.push(id);
}
+
+ // A custom field's event id is DERIVED from the diff key, never looked up: the id is
+ // per company and the catalog is not, so no company lookup enters the hot path. The
+ // existing workflowTriggerEvent join does the filtering it already did.
+ //
+ // Appended after the generated ids, so "one run per workflow per announcement, first
+ // id wins" picks the same winner it does today for a workflow watching both.
+ const entity = ENTITY_BY_TABLE[input.table];
+ if (entity !== undefined) {
+ for (const key of Object.keys(diff)) {
+ if (!key.startsWith(CUSTOM_FIELD_PREFIX)) continue;
+ const fieldId = key.slice(CUSTOM_FIELD_PREFIX.length);
+ if (fieldId === "") continue;
+ const id = customFieldEventId(entity, fieldId);
+ // The one place the item exclusion and the reference-only rule are decided.
+ if (CATALOG.getEvent(id) !== undefined) ids.push(id);
+ }
+ }
+
return ids;
}
diff --git a/packages/locale/locales/de/erp.po b/packages/locale/locales/de/erp.po
index e7595b8cc9..ac2f341770 100644
--- a/packages/locale/locales/de/erp.po
+++ b/packages/locale/locales/de/erp.po
@@ -456,7 +456,7 @@ msgstr "Der Status eines Auftrags ändert sich"
msgid "A list is wired into {0}, so this step runs once for each item and returns a list of results."
msgstr "Eine Liste ist mit {0} verbunden, sodass dieser Schritt einmal für jedes Element ausgeführt wird und eine Liste von Ergebnissen zurückgibt."
-#. placeholder {0}: label( actionInputLabelKey(actionId, batch.input), batch.input )
+#. placeholder {0}: inputLabel(batch.input)
msgid "A list is wired into {0}, so this step runs once for each item in it — up to {MAX_LIST_ITEMS}."
msgstr "Eine Liste ist mit {0} verbunden, sodass dieser Schritt für jedes Element darin einmal ausgeführt wird – bis zu {MAX_LIST_ITEMS}."
@@ -1372,6 +1372,9 @@ msgstr "Alpha"
msgid "Always"
msgstr "Immer"
+msgid "Always sent — every notification shows in the bell menu."
+msgstr "Immer versendet — jede Benachrichtigung wird im Glockenmenü angezeigt."
+
msgid "Always taken"
msgstr "Immer genommen"
@@ -3399,6 +3402,9 @@ msgstr "Jira-Problem verbinden"
msgid "Connect Linear issue"
msgstr "Linear-Problem verbinden"
+msgid "Connect Slack under Settings → Integrations first."
+msgstr "Verbinden Sie Slack zuerst unter Einstellungen → Integrationen."
+
msgid "Connect the Otherwise handle to a node to run when no condition matches."
msgstr "Verbinden Sie das Otherwise-Handle mit einem Knoten, um auszuführen, wenn keine Bedingung erfüllt ist."
@@ -4190,6 +4196,9 @@ msgstr "Benutzerdefiniertes Feld"
msgid "Custom Fields"
msgstr "Benutzerdefinierte Felder"
+msgid "Custom fields are not available for items yet."
+msgstr "Benutzerdefinierte Felder sind für Artikel noch nicht verfügbar."
+
msgid "Custom SOW · we manage"
msgstr "Benutzerdefiniertes SOW · wir verwalten"
@@ -5095,6 +5104,9 @@ msgstr "Abmessungen"
msgid "Direct"
msgstr "Direkt"
+msgid "Direct message to each recipient in your Slack workspace."
+msgstr "Direktnachricht an jeden Empfänger in Ihrem Slack-Arbeitsbereich."
+
msgid "Direction"
msgstr "Richtung"
@@ -7586,6 +7598,9 @@ msgstr "Nur auf Lager"
msgid "In the loop together"
msgstr "Im Prozess dabei"
+msgid "In-app"
+msgstr "In-App"
+
msgid "In-app notifications are always delivered. Choose which topics also reach you by email or Slack."
msgstr "In-App-Benachrichtigungen werden immer zugestellt. Wählen Sie, welche Themen Sie auch per E-Mail oder Slack erreichen."
@@ -8475,8 +8490,8 @@ msgstr "Listenoptionen"
msgid "List Parameters"
msgstr "Listenparameter"
-#. placeholder {0}: label( actionInputLabelKey(actionId, batch.first), batch.first )
-#. placeholder {1}: label( actionInputLabelKey(actionId, batch.second), batch.second )
+#. placeholder {0}: inputLabel(batch.first)
+#. placeholder {1}: inputLabel(batch.second)
msgid "Lists are wired into both {0} and {1}, so this step cannot tell which one to repeat over. Leave a list on only one of them."
msgstr "Listen sind an beide {0} und {1} angebunden, daher kann dieser Schritt nicht erkennen, welche wiederholt werden soll. Behalten Sie eine Liste nur auf einer von ihnen."
@@ -9267,6 +9282,9 @@ msgstr "Benötigt bis"
msgid "Need the right columns?"
msgstr "Benötigen Sie die richtigen Spalten?"
+msgid "Needs a Business or Partner plan."
+msgstr "Benötigt einen Business- oder Partner-Plan."
+
msgid "Needs fixing"
msgstr "Muss behoben werden"
@@ -9573,6 +9591,9 @@ msgstr "Neue Transferzeile"
msgid "New Unit of Measure"
msgstr "Neue Maßeinheit"
+msgid "New version"
+msgstr "Neue Version"
+
msgid "New Version"
msgstr "Neue Version"
@@ -10142,6 +10163,12 @@ msgstr "Noch nichts. Ein Schritt bietet Werte erst nach der Konfiguration an."
msgid "Notification"
msgstr "Benachrichtigung"
+msgid "Notification type"
+msgstr "Benachrichtigungstyp"
+
+msgid "Notification Type"
+msgstr "Benachrichtigungstyp"
+
msgid "Notifications"
msgstr "Benachrichtigungen"
@@ -13334,6 +13361,9 @@ msgstr "Sendet dieses Dokument zur Genehmigung, bevor es aktiv werden kann."
msgid "Sent complete date"
msgstr "Versanddatum abgeschlossen"
+msgid "Sent to each recipient who has email notifications turned on."
+msgstr "Versendet an jeden Empfänger, der E-Mail-Benachrichtigungen aktiviert hat."
+
msgid "Sequences"
msgstr "Sequenzen"
@@ -15546,9 +15576,18 @@ msgstr "Diese Version gehört zur Änderungsmitteilung <0>{0}</0>. Bearbeiten Si
msgid "This version cannot be opened"
msgstr "Diese Version kann nicht geöffnet werden"
+msgid "This version is live"
+msgstr "Diese Version ist live"
+
+msgid "This version is live, so it cannot be changed. You can still move steps around to tidy the layout."
+msgstr "Diese Version ist live und kann nicht geändert werden. Sie können die Schritte immer noch verschieben, um das Layout zu ordnen."
+
msgid "This version is live. Create a new version to edit."
msgstr "Diese Version ist aktiv. Erstellen Sie eine neue Version zum Bearbeiten."
+msgid "This version is live. Create a new version to make changes. You can still move steps around to tidy the layout."
+msgstr "Diese Version ist live. Erstellen Sie eine neue Version, um Änderungen vorzunehmen. Sie können die Schritte immer noch verschieben, um das Layout zu ordnen."
+
msgid "This version's definition could not be read."
msgstr "Die Definition dieser Version konnte nicht gelesen werden."
@@ -16935,6 +16974,9 @@ msgstr "Was ist nicht im Umfang enthalten"
msgid "When"
msgstr "Wann"
+msgid "When {name} changes"
+msgstr "Wenn sich {name} ändert"
+
msgid "When a finished product's shelf life is set to Calculated, pick which consumed inputs feed the calculation."
msgstr "Wenn die Haltbarkeit eines Fertigprodukts auf „Berechnet\" eingestellt ist, wählen Sie aus, welche verbrauchten Eingaben die Berechnung speisen."
@@ -17031,6 +17073,9 @@ msgstr "Wann Sie sich zur Lieferung verpflichtet haben; Planung behandelt dies a
msgid "When your fiscal and tax years start"
msgstr "Wenn Ihr Geschäftsjahr und Steuerjahr beginnen"
+msgid "Where a workflow notification is delivered — in-app is always sent, while email needs a Business or Partner plan and Slack needs your Slack workspace connected."
+msgstr "Wohin eine Workflow-Benachrichtigung versendet wird – in-app wird immer versendet, während E-Mail einen Business- oder Partner-Plan benötigt und Slack Ihren Slack-Arbeitsbereich erfordert."
+
msgid "Where an operation runs; carries labor and quoting rates, with overhead the difference between them."
msgstr "Wo ein Betrieb läuft; trägt Arbeits- und Angebotstarife, mit Overhead dem Unterschied zwischen ihnen."
diff --git a/packages/locale/locales/en/erp.po b/packages/locale/locales/en/erp.po
index 2a36c8807b..0c5837cc97 100644
--- a/packages/locale/locales/en/erp.po
+++ b/packages/locale/locales/en/erp.po
@@ -456,7 +456,7 @@ msgstr "A job's status changes"
msgid "A list is wired into {0}, so this step runs once for each item and returns a list of results."
msgstr "A list is wired into {0}, so this step runs once for each item and returns a list of results."
-#. placeholder {0}: label( actionInputLabelKey(actionId, batch.input), batch.input )
+#. placeholder {0}: inputLabel(batch.input)
msgid "A list is wired into {0}, so this step runs once for each item in it — up to {MAX_LIST_ITEMS}."
msgstr "A list is wired into {0}, so this step runs once for each item in it — up to {MAX_LIST_ITEMS}."
@@ -1372,6 +1372,9 @@ msgstr "Alpha"
msgid "Always"
msgstr "Always"
+msgid "Always sent — every notification shows in the bell menu."
+msgstr "Always sent — every notification shows in the bell menu."
+
msgid "Always taken"
msgstr "Always taken"
@@ -3399,6 +3402,9 @@ msgstr "Connect Jira issue"
msgid "Connect Linear issue"
msgstr "Connect Linear issue"
+msgid "Connect Slack under Settings → Integrations first."
+msgstr "Connect Slack under Settings → Integrations first."
+
msgid "Connect the Otherwise handle to a node to run when no condition matches."
msgstr "Connect the Otherwise handle to a node to run when no condition matches."
@@ -4190,6 +4196,9 @@ msgstr "Custom Field"
msgid "Custom Fields"
msgstr "Custom Fields"
+msgid "Custom fields are not available for items yet."
+msgstr "Custom fields are not available for items yet."
+
msgid "Custom SOW · we manage"
msgstr "Custom SOW · we manage"
@@ -5095,6 +5104,9 @@ msgstr "Dimensions"
msgid "Direct"
msgstr "Direct"
+msgid "Direct message to each recipient in your Slack workspace."
+msgstr "Direct message to each recipient in your Slack workspace."
+
msgid "Direction"
msgstr "Direction"
@@ -7586,6 +7598,9 @@ msgstr "In stock only"
msgid "In the loop together"
msgstr "In the loop together"
+msgid "In-app"
+msgstr "In-app"
+
msgid "In-app notifications are always delivered. Choose which topics also reach you by email or Slack."
msgstr "In-app notifications are always delivered. Choose which topics also reach you by email or Slack."
@@ -8475,8 +8490,8 @@ msgstr "List Options"
msgid "List Parameters"
msgstr "List Parameters"
-#. placeholder {0}: label( actionInputLabelKey(actionId, batch.first), batch.first )
-#. placeholder {1}: label( actionInputLabelKey(actionId, batch.second), batch.second )
+#. placeholder {0}: inputLabel(batch.first)
+#. placeholder {1}: inputLabel(batch.second)
msgid "Lists are wired into both {0} and {1}, so this step cannot tell which one to repeat over. Leave a list on only one of them."
msgstr "Lists are wired into both {0} and {1}, so this step cannot tell which one to repeat over. Leave a list on only one of them."
@@ -9267,6 +9282,9 @@ msgstr "Need by"
msgid "Need the right columns?"
msgstr "Need the right columns?"
+msgid "Needs a Business or Partner plan."
+msgstr "Needs a Business or Partner plan."
+
msgid "Needs fixing"
msgstr "Needs fixing"
@@ -9573,6 +9591,9 @@ msgstr "New Transfer Line"
msgid "New Unit of Measure"
msgstr "New Unit of Measure"
+msgid "New version"
+msgstr "New version"
+
msgid "New Version"
msgstr "New Version"
@@ -10142,6 +10163,12 @@ msgstr "Nothing yet. A step only offers values once it is configured."
msgid "Notification"
msgstr "Notification"
+msgid "Notification type"
+msgstr "Notification type"
+
+msgid "Notification Type"
+msgstr "Notification Type"
+
msgid "Notifications"
msgstr "Notifications"
@@ -13334,6 +13361,9 @@ msgstr "Sends this document for approval before it can go active."
msgid "Sent complete date"
msgstr "Sent complete date"
+msgid "Sent to each recipient who has email notifications turned on."
+msgstr "Sent to each recipient who has email notifications turned on."
+
msgid "Sequences"
msgstr "Sequences"
@@ -15546,9 +15576,18 @@ msgstr "This version belongs to change notice <0>{0}</0>. Edit it there."
msgid "This version cannot be opened"
msgstr "This version cannot be opened"
+msgid "This version is live"
+msgstr "This version is live"
+
+msgid "This version is live, so it cannot be changed. You can still move steps around to tidy the layout."
+msgstr "This version is live, so it cannot be changed. You can still move steps around to tidy the layout."
+
msgid "This version is live. Create a new version to edit."
msgstr "This version is live. Create a new version to edit."
+msgid "This version is live. Create a new version to make changes. You can still move steps around to tidy the layout."
+msgstr "This version is live. Create a new version to make changes. You can still move steps around to tidy the layout."
+
msgid "This version's definition could not be read."
msgstr "This version's definition could not be read."
@@ -16935,6 +16974,9 @@ msgstr "What's out of scope"
msgid "When"
msgstr "When"
+msgid "When {name} changes"
+msgstr "When {name} changes"
+
msgid "When a finished product's shelf life is set to Calculated, pick which consumed inputs feed the calculation."
msgstr "When a finished product's shelf life is set to Calculated, pick which consumed inputs feed the calculation."
@@ -17031,6 +17073,9 @@ msgstr "When you committed to deliver; planning treats this as the demand-due-da
msgid "When your fiscal and tax years start"
msgstr "When your fiscal and tax years start"
+msgid "Where a workflow notification is delivered — in-app is always sent, while email needs a Business or Partner plan and Slack needs your Slack workspace connected."
+msgstr "Where a workflow notification is delivered — in-app is always sent, while email needs a Business or Partner plan and Slack needs your Slack workspace connected."
+
msgid "Where an operation runs; carries labor and quoting rates, with overhead the difference between them."
msgstr "Where an operation runs; carries labor and quoting rates, with overhead the difference between them."
diff --git a/packages/locale/locales/es/erp.po b/packages/locale/locales/es/erp.po
index 7b3e8db80c..340c1df279 100644
--- a/packages/locale/locales/es/erp.po
+++ b/packages/locale/locales/es/erp.po
@@ -456,7 +456,7 @@ msgstr "El estado de un trabajo cambia"
msgid "A list is wired into {0}, so this step runs once for each item and returns a list of results."
msgstr "Una lista está conectada a {0}, por lo que este paso se ejecuta una vez para cada elemento y devuelve una lista de resultados."
-#. placeholder {0}: label( actionInputLabelKey(actionId, batch.input), batch.input )
+#. placeholder {0}: inputLabel(batch.input)
msgid "A list is wired into {0}, so this step runs once for each item in it — up to {MAX_LIST_ITEMS}."
msgstr "Una lista está conectada a {0}, por lo que este paso se ejecuta una vez para cada elemento — hasta {MAX_LIST_ITEMS}."
@@ -1372,6 +1372,9 @@ msgstr "Alfa"
msgid "Always"
msgstr "Siempre"
+msgid "Always sent — every notification shows in the bell menu."
+msgstr "Siempre enviado — cada notificación se muestra en el menú de campanilla."
+
msgid "Always taken"
msgstr "Siempre se toma"
@@ -3399,6 +3402,9 @@ msgstr "Conectar problema de Jira"
msgid "Connect Linear issue"
msgstr "Conectar problema de Linear"
+msgid "Connect Slack under Settings → Integrations first."
+msgstr "Conecta Slack en Configuración → Integraciones primero."
+
msgid "Connect the Otherwise handle to a node to run when no condition matches."
msgstr "Conecta el manejador Otherwise a un nodo para ejecutarlo cuando ninguna condición coincida."
@@ -4190,6 +4196,9 @@ msgstr "Campo Personalizado"
msgid "Custom Fields"
msgstr "Campos Personalizados"
+msgid "Custom fields are not available for items yet."
+msgstr "Los campos personalizados aún no están disponibles para artículos."
+
msgid "Custom SOW · we manage"
msgstr "SOW personalizado · nosotros gestionamos"
@@ -5095,6 +5104,9 @@ msgstr "Dimensiones"
msgid "Direct"
msgstr "Directo"
+msgid "Direct message to each recipient in your Slack workspace."
+msgstr "Mensaje directo a cada destinatario en tu espacio de trabajo de Slack."
+
msgid "Direction"
msgstr "Dirección"
@@ -7586,6 +7598,9 @@ msgstr "Solo en stock"
msgid "In the loop together"
msgstr "En el ciclo juntos"
+msgid "In-app"
+msgstr "En la aplicación"
+
msgid "In-app notifications are always delivered. Choose which topics also reach you by email or Slack."
msgstr "Las notificaciones en la aplicación siempre se entregan. Elija qué temas también le llegan por correo electrónico o Slack."
@@ -8475,8 +8490,8 @@ msgstr "Opciones de lista"
msgid "List Parameters"
msgstr "Parámetros de Lista"
-#. placeholder {0}: label( actionInputLabelKey(actionId, batch.first), batch.first )
-#. placeholder {1}: label( actionInputLabelKey(actionId, batch.second), batch.second )
+#. placeholder {0}: inputLabel(batch.first)
+#. placeholder {1}: inputLabel(batch.second)
msgid "Lists are wired into both {0} and {1}, so this step cannot tell which one to repeat over. Leave a list on only one of them."
msgstr "Las listas están conectadas tanto a {0} como a {1}, por lo que este paso no puede determinar cuál repetir. Mantén una lista solo en una de ellas."
@@ -9267,6 +9282,9 @@ msgstr "Necesario por"
msgid "Need the right columns?"
msgstr "¿Necesitas las columnas correctas?"
+msgid "Needs a Business or Partner plan."
+msgstr "Requiere un plan Business o Partner."
+
msgid "Needs fixing"
msgstr "Necesita reparación"
@@ -9573,6 +9591,9 @@ msgstr "Nueva Línea de Transferencia"
msgid "New Unit of Measure"
msgstr "Nueva Unidad de Medida"
+msgid "New version"
+msgstr "Nueva versión"
+
msgid "New Version"
msgstr "Nueva Versión"
@@ -10142,6 +10163,12 @@ msgstr "Aún no hay nada. Un paso solo ofrece valores una vez que está configur
msgid "Notification"
msgstr "Notificación"
+msgid "Notification type"
+msgstr "Tipo de notificación"
+
+msgid "Notification Type"
+msgstr "Tipo de Notificación"
+
msgid "Notifications"
msgstr "Notificaciones"
@@ -13334,6 +13361,9 @@ msgstr "Envía este documento para aprobación antes de que pueda activarse."
msgid "Sent complete date"
msgstr "Fecha de envío completado"
+msgid "Sent to each recipient who has email notifications turned on."
+msgstr "Enviado a cada destinatario que tiene las notificaciones por correo electrónico activadas."
+
msgid "Sequences"
msgstr "Secuencias"
@@ -15546,9 +15576,18 @@ msgstr "Esta versión pertenece al aviso de cambio <0>{0}</0>. Edítala allí."
msgid "This version cannot be opened"
msgstr "Esta versión no se puede abrir"
+msgid "This version is live"
+msgstr "Esta versión está en vivo"
+
+msgid "This version is live, so it cannot be changed. You can still move steps around to tidy the layout."
+msgstr "Esta versión está en vivo, por lo que no se puede cambiar. Aún puedes mover los pasos para ordenar el diseño."
+
msgid "This version is live. Create a new version to edit."
msgstr "Esta versión está activa. Crea una nueva versión para editar."
+msgid "This version is live. Create a new version to make changes. You can still move steps around to tidy the layout."
+msgstr "Esta versión está en vivo. Crea una nueva versión para hacer cambios. Aún puedes mover los pasos para ordenar el diseño."
+
msgid "This version's definition could not be read."
msgstr "La definición de esta versión no se pudo leer."
@@ -16935,6 +16974,9 @@ msgstr "Qué está fuera del alcance"
msgid "When"
msgstr "Cuándo"
+msgid "When {name} changes"
+msgstr "Cuando {name} cambia"
+
msgid "When a finished product's shelf life is set to Calculated, pick which consumed inputs feed the calculation."
msgstr "Cuando la vida útil de un producto terminado se establece en Calculada, elige qué insumos consumidos alimentan el cálculo."
@@ -17031,6 +17073,9 @@ msgstr "Cuándo se comprometió a entregar; la planificación trata esto como la
msgid "When your fiscal and tax years start"
msgstr "Cuándo comienzan sus años fiscales y tributarios"
+msgid "Where a workflow notification is delivered — in-app is always sent, while email needs a Business or Partner plan and Slack needs your Slack workspace connected."
+msgstr "Dónde se entrega una notificación de flujo de trabajo — en la aplicación siempre se envía, mientras que el correo electrónico requiere un plan Business o Partner y Slack requiere que tu espacio de trabajo de Slack esté conectado."
+
msgid "Where an operation runs; carries labor and quoting rates, with overhead the difference between them."
msgstr "Dónde se ejecuta una operación; lleva tasas de trabajo y cotización, con gastos generales la diferencia entre ellas."
diff --git a/packages/locale/locales/fr/erp.po b/packages/locale/locales/fr/erp.po
index 7ef12b19b4..e11cad84be 100644
--- a/packages/locale/locales/fr/erp.po
+++ b/packages/locale/locales/fr/erp.po
@@ -456,7 +456,7 @@ msgstr "Le statut d'un travail change"
msgid "A list is wired into {0}, so this step runs once for each item and returns a list of results."
msgstr "Une liste est connectée à {0}, donc cette étape s'exécute une fois pour chaque élément et retourne une liste de résultats."
-#. placeholder {0}: label( actionInputLabelKey(actionId, batch.input), batch.input )
+#. placeholder {0}: inputLabel(batch.input)
msgid "A list is wired into {0}, so this step runs once for each item in it — up to {MAX_LIST_ITEMS}."
msgstr "Une liste est connectée à {0}, donc cette étape s'exécute une fois pour chaque élément — jusqu'à {MAX_LIST_ITEMS}."
@@ -1372,6 +1372,9 @@ msgstr "Alpha"
msgid "Always"
msgstr "Toujours"
+msgid "Always sent — every notification shows in the bell menu."
+msgstr "Toujours envoyé — chaque notification apparaît dans le menu de notifications."
+
msgid "Always taken"
msgstr "Toujours pris"
@@ -3399,6 +3402,9 @@ msgstr "Connecter un problème Jira"
msgid "Connect Linear issue"
msgstr "Connecter un problème Linear"
+msgid "Connect Slack under Settings → Integrations first."
+msgstr "Connectez d'abord Slack sous Paramètres → Intégrations."
+
msgid "Connect the Otherwise handle to a node to run when no condition matches."
msgstr "Connectez la poignée Sinon à un nœud à exécuter quand aucune condition ne correspond."
@@ -4190,6 +4196,9 @@ msgstr "Champ personnalisé"
msgid "Custom Fields"
msgstr "Champs personnalisés"
+msgid "Custom fields are not available for items yet."
+msgstr "Les champs personnalisés ne sont pas encore disponibles pour les articles."
+
msgid "Custom SOW · we manage"
msgstr "SOW personnalisé · nous gérons"
@@ -5095,6 +5104,9 @@ msgstr "Dimensions"
msgid "Direct"
msgstr "Direct"
+msgid "Direct message to each recipient in your Slack workspace."
+msgstr "Message direct à chaque destinataire dans votre espace de travail Slack."
+
msgid "Direction"
msgstr "Direction"
@@ -7586,6 +7598,9 @@ msgstr "En stock uniquement"
msgid "In the loop together"
msgstr "Dans la boucle ensemble"
+msgid "In-app"
+msgstr "In-app"
+
msgid "In-app notifications are always delivered. Choose which topics also reach you by email or Slack."
msgstr "Les notifications dans l'application sont toujours livrées. Choisissez les sujets qui vous parviennent également par e-mail ou Slack."
@@ -8475,8 +8490,8 @@ msgstr "Options de liste"
msgid "List Parameters"
msgstr "Paramètres de liste"
-#. placeholder {0}: label( actionInputLabelKey(actionId, batch.first), batch.first )
-#. placeholder {1}: label( actionInputLabelKey(actionId, batch.second), batch.second )
+#. placeholder {0}: inputLabel(batch.first)
+#. placeholder {1}: inputLabel(batch.second)
msgid "Lists are wired into both {0} and {1}, so this step cannot tell which one to repeat over. Leave a list on only one of them."
msgstr "Les listes sont connectées à la fois à {0} et {1}, donc cette étape ne peut pas savoir sur laquelle répéter. Laissez une liste sur une seule d'entre elles."
@@ -9267,6 +9282,9 @@ msgstr "Requis le"
msgid "Need the right columns?"
msgstr "Besoin des bonnes colonnes ?"
+msgid "Needs a Business or Partner plan."
+msgstr "Nécessite un plan Business ou Partner."
+
msgid "Needs fixing"
msgstr "Doit être réparé"
@@ -9573,6 +9591,9 @@ msgstr "Nouvelle Ligne de Transfert"
msgid "New Unit of Measure"
msgstr "Nouvelle Unité de Mesure"
+msgid "New version"
+msgstr "Nouvelle version"
+
msgid "New Version"
msgstr "Nouvelle Version"
@@ -10142,6 +10163,12 @@ msgstr "Rien pour le moment. Une étape n'offre des valeurs qu'une fois configur
msgid "Notification"
msgstr "Notification"
+msgid "Notification type"
+msgstr "Type de notification"
+
+msgid "Notification Type"
+msgstr "Type de notification"
+
msgid "Notifications"
msgstr "Notifications"
@@ -13334,6 +13361,9 @@ msgstr "Envoie ce document pour approbation avant qu'il ne puisse devenir actif.
msgid "Sent complete date"
msgstr "Date d'envoi complète"
+msgid "Sent to each recipient who has email notifications turned on."
+msgstr "Envoyé à chaque destinataire qui a activé les notifications par email."
+
msgid "Sequences"
msgstr "Séquences"
@@ -15546,9 +15576,18 @@ msgstr "Cette version appartient au change notice <0>{0}</0>. Modifiez-le là."
msgid "This version cannot be opened"
msgstr "Cette version ne peut pas être ouverte"
+msgid "This version is live"
+msgstr "Cette version est en direct"
+
+msgid "This version is live, so it cannot be changed. You can still move steps around to tidy the layout."
+msgstr "Cette version est en direct, elle ne peut donc pas être modifiée. Vous pouvez toujours déplacer les étapes pour organiser la mise en page."
+
msgid "This version is live. Create a new version to edit."
msgstr "Cette version est en direct. Créez une nouvelle version pour modifier."
+msgid "This version is live. Create a new version to make changes. You can still move steps around to tidy the layout."
+msgstr "Cette version est en direct. Créez une nouvelle version pour apporter des modifications. Vous pouvez toujours déplacer les étapes pour organiser la mise en page."
+
msgid "This version's definition could not be read."
msgstr "La définition de cette version n'a pas pu être lue."
@@ -16935,6 +16974,9 @@ msgstr "Ce qui n'est pas dans le périmètre"
msgid "When"
msgstr "Quand"
+msgid "When {name} changes"
+msgstr "Quand {name} change"
+
msgid "When a finished product's shelf life is set to Calculated, pick which consumed inputs feed the calculation."
msgstr "Lorsque la durée de vie d'un produit fini est définie sur Calculée, choisissez les entrées consommées qui alimentent le calcul."
@@ -17031,6 +17073,9 @@ msgstr "Quand vous vous êtes engagé à livrer ; la planification traite ceci c
msgid "When your fiscal and tax years start"
msgstr "Quand commencent vos exercices fiscal et fiscal"
+msgid "Where a workflow notification is delivered — in-app is always sent, while email needs a Business or Partner plan and Slack needs your Slack workspace connected."
+msgstr "Où une notification de workflow est livrée — in-app est toujours envoyé, tandis que l'email nécessite un plan Business ou Partner et Slack nécessite que votre espace de travail Slack soit connecté."
+
msgid "Where an operation runs; carries labor and quoting rates, with overhead the difference between them."
msgstr "Où un opération s'exécute ; porte les taux de travail et de devis, avec frais généraux la différence entre eux."
diff --git a/packages/locale/locales/hi/erp.po b/packages/locale/locales/hi/erp.po
index 195bda0475..0fd91cfa43 100644
--- a/packages/locale/locales/hi/erp.po
+++ b/packages/locale/locales/hi/erp.po
@@ -456,7 +456,7 @@ msgstr "किसी नौकरी की स्थिति में पर
msgid "A list is wired into {0}, so this step runs once for each item and returns a list of results."
msgstr "एक सूची {0} में जुड़ी हुई है, इसलिए यह चरण प्रत्येक आइटम के लिए एक बार चलता है और परिणामों की एक सूची लौटाता है।"
-#. placeholder {0}: label( actionInputLabelKey(actionId, batch.input), batch.input )
+#. placeholder {0}: inputLabel(batch.input)
msgid "A list is wired into {0}, so this step runs once for each item in it — up to {MAX_LIST_ITEMS}."
msgstr "एक सूची {0} में जुड़ी हुई है, इसलिए यह चरण इसमें प्रत्येक आइटम के लिए एक बार चलता है — {MAX_LIST_ITEMS} तक।"
@@ -1372,6 +1372,9 @@ msgstr "अल्फा"
msgid "Always"
msgstr "हमेशा"
+msgid "Always sent — every notification shows in the bell menu."
+msgstr "हमेशा भेजा जाता है — हर सूचना घंटी मेनू में दिखाई देती है।"
+
msgid "Always taken"
msgstr "हमेशा लिया जाता है"
@@ -3399,6 +3402,9 @@ msgstr "Jira समस्या से कनेक्ट करें"
msgid "Connect Linear issue"
msgstr "Linear समस्या से कनेक्ट करें"
+msgid "Connect Slack under Settings → Integrations first."
+msgstr "पहले सेटिंग्स → इंटीग्रेशन के तहत Slack को जोड़ें।"
+
msgid "Connect the Otherwise handle to a node to run when no condition matches."
msgstr "कोई शर्त मेल नहीं खाने पर चलाने के लिए हैंडल को एक नोड से कनेक्ट करें।"
@@ -4190,6 +4196,9 @@ msgstr "कस्टम फील्ड"
msgid "Custom Fields"
msgstr "कस्टम फील्ड्स"
+msgid "Custom fields are not available for items yet."
+msgstr "कस्टम फील्ड अभी आइटम के लिए उपलब्ध नहीं हैं।"
+
msgid "Custom SOW · we manage"
msgstr "कस्टम SOW · हम प्रबंधित करते हैं"
@@ -5095,6 +5104,9 @@ msgstr "आयाम"
msgid "Direct"
msgstr "सीधा"
+msgid "Direct message to each recipient in your Slack workspace."
+msgstr "आपके Slack वर्कस्पेस में प्रत्येक प्राप्तकर्ता को सीधा संदेश।"
+
msgid "Direction"
msgstr "दिशा"
@@ -7586,6 +7598,9 @@ msgstr "केवल स्टॉक में"
msgid "In the loop together"
msgstr "एक साथ लूप में"
+msgid "In-app"
+msgstr "ऐप में"
+
msgid "In-app notifications are always delivered. Choose which topics also reach you by email or Slack."
msgstr "इन-ऐप नोटिफिकेशन हमेशा डिलीवर किए जाते हैं। चुनें कि कौन से विषय आपको ईमेल या Slack के माध्यम से भी पहुंचते हैं।"
@@ -8475,8 +8490,8 @@ msgstr "सूची विकल्प"
msgid "List Parameters"
msgstr "सूची पैरामीटर"
-#. placeholder {0}: label( actionInputLabelKey(actionId, batch.first), batch.first )
-#. placeholder {1}: label( actionInputLabelKey(actionId, batch.second), batch.second )
+#. placeholder {0}: inputLabel(batch.first)
+#. placeholder {1}: inputLabel(batch.second)
msgid "Lists are wired into both {0} and {1}, so this step cannot tell which one to repeat over. Leave a list on only one of them."
msgstr "सूचियां दोनों {0} और {1} में वायर्ड हैं, इसलिए यह चरण नहीं बता सकता कि किस पर दोहराना है। एक सूची को केवल एक पर छोड़ें।"
@@ -9267,6 +9282,9 @@ msgstr "आवश्यकता की तारीख"
msgid "Need the right columns?"
msgstr "क्या आपको सही कॉलम चाहिए?"
+msgid "Needs a Business or Partner plan."
+msgstr "एक बिजनेस या पार्टनर प्लान की आवश्यकता है।"
+
msgid "Needs fixing"
msgstr "मरम्मत की आवश्यकता है"
@@ -9573,6 +9591,9 @@ msgstr "नई ट्रांसफर लाइन"
msgid "New Unit of Measure"
msgstr "नई माप की इकाई"
+msgid "New version"
+msgstr "नया संस्करण"
+
msgid "New Version"
msgstr "नया संस्करण"
@@ -10142,6 +10163,12 @@ msgstr "अभी कुछ नहीं। एक स्टेप केवल
msgid "Notification"
msgstr "सूचना"
+msgid "Notification type"
+msgstr "सूचना प्रकार"
+
+msgid "Notification Type"
+msgstr "सूचना प्रकार"
+
msgid "Notifications"
msgstr "सूचनाएं"
@@ -13334,6 +13361,9 @@ msgstr "यह दस्तावेज़ सक्रिय होने स
msgid "Sent complete date"
msgstr "भेजे गए पूर्ण दिनांक"
+msgid "Sent to each recipient who has email notifications turned on."
+msgstr "प्रत्येक प्राप्तकर्ता को भेजा जाता है जिसके पास ईमेल सूचनाएं चालू हैं।"
+
msgid "Sequences"
msgstr "अनुक्रम"
@@ -15546,9 +15576,18 @@ msgstr "यह संस्करण परिवर्तन सूचना <0
msgid "This version cannot be opened"
msgstr "यह version खोला नहीं जा सकता"
+msgid "This version is live"
+msgstr "यह संस्करण लाइव है"
+
+msgid "This version is live, so it cannot be changed. You can still move steps around to tidy the layout."
+msgstr "यह संस्करण लाइव है, इसलिए इसे बदला नहीं जा सकता। आप अभी भी लेआउट को सुव्यवस्थित करने के लिए चरणों को स्थानांतरित कर सकते हैं।"
+
msgid "This version is live. Create a new version to edit."
msgstr "यह version live है। संपादित करने के लिए एक नया version बनाएं।"
+msgid "This version is live. Create a new version to make changes. You can still move steps around to tidy the layout."
+msgstr "यह संस्करण लाइव है। परिवर्तन करने के लिए एक नया संस्करण बनाएं। आप अभी भी लेआउट को सुव्यवस्थित करने के लिए चरणों को स्थानांतरित कर सकते हैं।"
+
msgid "This version's definition could not be read."
msgstr "इस version की परिभाषा को पढ़ा नहीं जा सका।"
@@ -16935,6 +16974,9 @@ msgstr "स्कोप से बाहर क्या है"
msgid "When"
msgstr "कब"
+msgid "When {name} changes"
+msgstr "जब {name} परिवर्तन होता है"
+
msgid "When a finished product's shelf life is set to Calculated, pick which consumed inputs feed the calculation."
msgstr "जब किसी तैयार उत्पाद का शेल्फ जीवन Calculated पर सेट किया जाता है, तो चुनें कि कौन से उपभोग किए गए इनपुट गणना को खिलाते हैं।"
@@ -17031,6 +17073,9 @@ msgstr "जब आप डिलीवरी के लिए प्रतिब
msgid "When your fiscal and tax years start"
msgstr "जब आपका वित्तीय और कर वर्ष शुरू होता है"
+msgid "Where a workflow notification is delivered — in-app is always sent, while email needs a Business or Partner plan and Slack needs your Slack workspace connected."
+msgstr "वह जगह जहां वर्कफ़्लो सूचना दी जाती है — ऐप में हमेशा भेजा जाता है, जबकि ईमेल को एक बिजनेस या पार्टनर प्लान की आवश्यकता है और Slack को आपके Slack वर्कस्पेस को जोड़ने की आवश्यकता है।"
+
msgid "Where an operation runs; carries labor and quoting rates, with overhead the difference between them."
msgstr "जहां एक ऑपरेशन चलता है; श्रम और उद्धरण दरें ले जाता है, ओवरहेड उनके बीच अंतर के साथ।"
diff --git a/packages/locale/locales/it/erp.po b/packages/locale/locales/it/erp.po
index be9ee8b501..b1a11c66ed 100644
--- a/packages/locale/locales/it/erp.po
+++ b/packages/locale/locales/it/erp.po
@@ -456,7 +456,7 @@ msgstr "Lo stato del lavoro cambia"
msgid "A list is wired into {0}, so this step runs once for each item and returns a list of results."
msgstr "Un elenco è collegato a {0}, quindi questo passaggio viene eseguito una volta per ogni elemento e restituisce un elenco di risultati."
-#. placeholder {0}: label( actionInputLabelKey(actionId, batch.input), batch.input )
+#. placeholder {0}: inputLabel(batch.input)
msgid "A list is wired into {0}, so this step runs once for each item in it — up to {MAX_LIST_ITEMS}."
msgstr "Un elenco è collegato a {0}, quindi questo passaggio viene eseguito una volta per ogni elemento in esso — fino a {MAX_LIST_ITEMS}."
@@ -1372,6 +1372,9 @@ msgstr "Alpha"
msgid "Always"
msgstr "Sempre"
+msgid "Always sent — every notification shows in the bell menu."
+msgstr "Sempre inviato — ogni notifica appare nel menu campanello."
+
msgid "Always taken"
msgstr "Sempre preso"
@@ -3399,6 +3402,9 @@ msgstr "Connetti problema Jira"
msgid "Connect Linear issue"
msgstr "Connetti problema Linear"
+msgid "Connect Slack under Settings → Integrations first."
+msgstr "Connetti Slack in Impostazioni → Integrazioni prima."
+
msgid "Connect the Otherwise handle to a node to run when no condition matches."
msgstr "Connetti il gestore Otherwise a un nodo per eseguire quando nessuna condizione corrisponde."
@@ -4190,6 +4196,9 @@ msgstr "Campo Personalizzato"
msgid "Custom Fields"
msgstr "Campi Personalizzati"
+msgid "Custom fields are not available for items yet."
+msgstr "I campi personalizzati non sono ancora disponibili per gli articoli."
+
msgid "Custom SOW · we manage"
msgstr "Custom SOW · gestiamo noi"
@@ -5095,6 +5104,9 @@ msgstr "Dimensioni"
msgid "Direct"
msgstr "Diretto"
+msgid "Direct message to each recipient in your Slack workspace."
+msgstr "Messaggio diretto a ogni destinatario nel tuo spazio di lavoro Slack."
+
msgid "Direction"
msgstr "Direzione"
@@ -7586,6 +7598,9 @@ msgstr "Solo in giacenza"
msgid "In the loop together"
msgstr "Nel giro insieme"
+msgid "In-app"
+msgstr "In-app"
+
msgid "In-app notifications are always delivered. Choose which topics also reach you by email or Slack."
msgstr "Le notifiche in-app vengono sempre consegnate. Scegli quali argomenti vuoi ricevere anche per e-mail o Slack."
@@ -8475,8 +8490,8 @@ msgstr "Opzioni Elenco"
msgid "List Parameters"
msgstr "Parametri Elenco"
-#. placeholder {0}: label( actionInputLabelKey(actionId, batch.first), batch.first )
-#. placeholder {1}: label( actionInputLabelKey(actionId, batch.second), batch.second )
+#. placeholder {0}: inputLabel(batch.first)
+#. placeholder {1}: inputLabel(batch.second)
msgid "Lists are wired into both {0} and {1}, so this step cannot tell which one to repeat over. Leave a list on only one of them."
msgstr "Gli elenchi sono collegati sia a {0} che a {1}, quindi questo passaggio non può dire quale ripetere. Lascia un elenco su uno solo di essi."
@@ -9267,6 +9282,9 @@ msgstr "Necessario entro"
msgid "Need the right columns?"
msgstr "Hai bisogno delle colonne giuste?"
+msgid "Needs a Business or Partner plan."
+msgstr "Richiede un piano Business o Partner."
+
msgid "Needs fixing"
msgstr "Necessita correzione"
@@ -9573,6 +9591,9 @@ msgstr "Nuova Riga di Trasferimento"
msgid "New Unit of Measure"
msgstr "Nuova Unità di Misura"
+msgid "New version"
+msgstr "Nuova versione"
+
msgid "New Version"
msgstr "Nuova Versione"
@@ -10142,6 +10163,12 @@ msgstr "Non c'è ancora nulla. Un passaggio offre valori solo dopo essere stato
msgid "Notification"
msgstr "Notifica"
+msgid "Notification type"
+msgstr "Tipo di notifica"
+
+msgid "Notification Type"
+msgstr "Tipo di notifica"
+
msgid "Notifications"
msgstr "Notifiche"
@@ -13334,6 +13361,9 @@ msgstr "Invia questo documento per l'approvazione prima che possa diventare atti
msgid "Sent complete date"
msgstr "Data di completamento inviata"
+msgid "Sent to each recipient who has email notifications turned on."
+msgstr "Inviato a ogni destinatario che ha le notifiche email attivate."
+
msgid "Sequences"
msgstr "Sequenze"
@@ -15546,9 +15576,18 @@ msgstr "Questa versione appartiene all'avviso di modifica <0>{0}</0>. Modificalo
msgid "This version cannot be opened"
msgstr "Questa versione non può essere aperta"
+msgid "This version is live"
+msgstr "Questa versione è in diretta"
+
+msgid "This version is live, so it cannot be changed. You can still move steps around to tidy the layout."
+msgstr "Questa versione è in diretta, quindi non può essere modificata. Puoi ancora spostare i passaggi per pulire il layout."
+
msgid "This version is live. Create a new version to edit."
msgstr "Questa versione è in tempo reale. Crea una nuova versione per modificare."
+msgid "This version is live. Create a new version to make changes. You can still move steps around to tidy the layout."
+msgstr "Questa versione è in diretta. Crea una nuova versione per apportare modifiche. Puoi ancora spostare i passaggi per pulire il layout."
+
msgid "This version's definition could not be read."
msgstr "La definizione di questa versione non potrebbe essere letta."
@@ -16935,6 +16974,9 @@ msgstr "Cosa non rientra nell'ambito"
msgid "When"
msgstr "Quando"
+msgid "When {name} changes"
+msgstr "Quando {name} cambia"
+
msgid "When a finished product's shelf life is set to Calculated, pick which consumed inputs feed the calculation."
msgstr "Quando la durata di conservazione di un prodotto finito è impostata su Calcolata, scegli quali input consumati alimentano il calcolo."
@@ -17031,6 +17073,9 @@ msgstr "Quando vi siete impegnati a consegnare; la pianificazione tratta questo
msgid "When your fiscal and tax years start"
msgstr "Quando iniziano i tuoi anni fiscali e fiscali"
+msgid "Where a workflow notification is delivered — in-app is always sent, while email needs a Business or Partner plan and Slack needs your Slack workspace connected."
+msgstr "Dove viene consegnata una notifica del flusso di lavoro — in-app viene sempre inviato, mentre email richiede un piano Business o Partner e Slack necessita del tuo spazio di lavoro Slack connesso."
+
msgid "Where an operation runs; carries labor and quoting rates, with overhead the difference between them."
msgstr "Dove un'operazione viene eseguita; porta tassi di manodopera e di quotazione, con spese generali la differenza tra di esse."
diff --git a/packages/locale/locales/ja/erp.po b/packages/locale/locales/ja/erp.po
index bdc733f6a0..3e29a65399 100644
--- a/packages/locale/locales/ja/erp.po
+++ b/packages/locale/locales/ja/erp.po
@@ -456,7 +456,7 @@ msgstr "ジョブのステータスが変更されました"
msgid "A list is wired into {0}, so this step runs once for each item and returns a list of results."
msgstr "リストが{0}に接続されているため、このステップは各項目ごとに1回実行され、結果のリストを返します。"
-#. placeholder {0}: label( actionInputLabelKey(actionId, batch.input), batch.input )
+#. placeholder {0}: inputLabel(batch.input)
msgid "A list is wired into {0}, so this step runs once for each item in it — up to {MAX_LIST_ITEMS}."
msgstr "リストが{0}に接続されているため、このステップはその中の各項目ごとに1回実行されます。最大{MAX_LIST_ITEMS}個です。"
@@ -1372,6 +1372,9 @@ msgstr "アルファ"
msgid "Always"
msgstr "常に"
+msgid "Always sent — every notification shows in the bell menu."
+msgstr "常に送信 — すべての通知がベルメニューに表示されます。"
+
msgid "Always taken"
msgstr "常に取得"
@@ -3399,6 +3402,9 @@ msgstr "Jira課題に接続"
msgid "Connect Linear issue"
msgstr "Linear イシューを接続"
+msgid "Connect Slack under Settings → Integrations first."
+msgstr "最初に設定 → 統合でSlackを接続してください。"
+
msgid "Connect the Otherwise handle to a node to run when no condition matches."
msgstr "条件に一致しないときに実行するノードにOtherwiseハンドルを接続します。"
@@ -4190,6 +4196,9 @@ msgstr "カスタムフィールド"
msgid "Custom Fields"
msgstr "カスタムフィールド"
+msgid "Custom fields are not available for items yet."
+msgstr "カスタムフィールドはまだアイテムで利用できません。"
+
msgid "Custom SOW · we manage"
msgstr "カスタムSOW · 当社が管理"
@@ -5095,6 +5104,9 @@ msgstr "寸法"
msgid "Direct"
msgstr "直接"
+msgid "Direct message to each recipient in your Slack workspace."
+msgstr "Slackワークスペース内の各受信者への直接メッセージ。"
+
msgid "Direction"
msgstr "方向"
@@ -7586,6 +7598,9 @@ msgstr "在庫のみ"
msgid "In the loop together"
msgstr "一緒にループの中にいる"
+msgid "In-app"
+msgstr "アプリ内"
+
msgid "In-app notifications are always delivered. Choose which topics also reach you by email or Slack."
msgstr "アプリ内通知は常に配信されます。どのトピックがメールまたはSlackでも届くかを選択してください。"
@@ -8475,8 +8490,8 @@ msgstr "リストオプション"
msgid "List Parameters"
msgstr "リストパラメータ"
-#. placeholder {0}: label( actionInputLabelKey(actionId, batch.first), batch.first )
-#. placeholder {1}: label( actionInputLabelKey(actionId, batch.second), batch.second )
+#. placeholder {0}: inputLabel(batch.first)
+#. placeholder {1}: inputLabel(batch.second)
msgid "Lists are wired into both {0} and {1}, so this step cannot tell which one to repeat over. Leave a list on only one of them."
msgstr "リストが{0}と{1}の両方に接続されています。そのため、このステップはどちらを繰り返すべきかを判断できません。リストはそのうちの1つにのみ残してください。"
@@ -9267,6 +9282,9 @@ msgstr "必要日"
msgid "Need the right columns?"
msgstr "正しい列が必要ですか?"
+msgid "Needs a Business or Partner plan."
+msgstr "ビジネスプランまたはパートナープランが必要です。"
+
msgid "Needs fixing"
msgstr "修理が必要です"
@@ -9573,6 +9591,9 @@ msgstr "新しい転送ライン"
msgid "New Unit of Measure"
msgstr "新しい測定単位"
+msgid "New version"
+msgstr "新しいバージョン"
+
msgid "New Version"
msgstr "新しいバージョン"
@@ -10142,6 +10163,12 @@ msgstr "まだ何もありません。ステップは構成されると値を提
msgid "Notification"
msgstr "通知"
+msgid "Notification type"
+msgstr "通知タイプ"
+
+msgid "Notification Type"
+msgstr "通知タイプ"
+
msgid "Notifications"
msgstr "通知"
@@ -13334,6 +13361,9 @@ msgstr "このドキュメントを承認のために送信してから、アク
msgid "Sent complete date"
msgstr "送信完了日"
+msgid "Sent to each recipient who has email notifications turned on."
+msgstr "メール通知がオンになっている各受信者に送信されます。"
+
msgid "Sequences"
msgstr "シーケンス"
@@ -15546,9 +15576,18 @@ msgstr "このバージョンは変更通知<0>{0}</0>に属しています。
msgid "This version cannot be opened"
msgstr "このバージョンは開くことができません"
+msgid "This version is live"
+msgstr "このバージョンはライブです"
+
+msgid "This version is live, so it cannot be changed. You can still move steps around to tidy the layout."
+msgstr "このバージョンはライブなので変更できません。レイアウトを整えるためにステップを移動することができます。"
+
msgid "This version is live. Create a new version to edit."
msgstr "このバージョンはライブです。編集するには新しいバージョンを作成してください。"
+msgid "This version is live. Create a new version to make changes. You can still move steps around to tidy the layout."
+msgstr "このバージョンはライブです。変更を加えるには新しいバージョンを作成してください。レイアウトを整えるためにステップを移動することができます。"
+
msgid "This version's definition could not be read."
msgstr "このバージョンの定義を読み取ることができませんでした。"
@@ -16935,6 +16974,9 @@ msgstr "スコープ外の内容"
msgid "When"
msgstr "いつ"
+msgid "When {name} changes"
+msgstr "{name}が変更されるとき"
+
msgid "When a finished product's shelf life is set to Calculated, pick which consumed inputs feed the calculation."
msgstr "完成品の賞味期限が「計算」に設定されている場合、計算に使用される消費入力を選択します。"
@@ -17031,6 +17073,9 @@ msgstr "あなたが配送を約束したいつ。計画はこれをフルフィ
msgid "When your fiscal and tax years start"
msgstr "会計年度および税務年度の開始時期"
+msgid "Where a workflow notification is delivered — in-app is always sent, while email needs a Business or Partner plan and Slack needs your Slack workspace connected."
+msgstr "ワークフロー通知が配信される場所 — アプリ内は常に送信されますが、メールはビジネスプランまたはパートナープランが必要で、Slackはワークスペースが接続されている必要があります。"
+
msgid "Where an operation runs; carries labor and quoting rates, with overhead the difference between them."
msgstr "操作が実行される場所。労働と見積もりレート、オーバーヘッドはそれらの違いです。"
diff --git a/packages/locale/locales/ko/erp.po b/packages/locale/locales/ko/erp.po
index 3ddd7287e8..51732d6b6c 100644
--- a/packages/locale/locales/ko/erp.po
+++ b/packages/locale/locales/ko/erp.po
@@ -456,7 +456,7 @@ msgstr "작업의 상태가 변경됨"
msgid "A list is wired into {0}, so this step runs once for each item and returns a list of results."
msgstr "목록이 {0}에 연결되어 있으므로 이 단계는 각 항목마다 한 번씩 실행되고 결과 목록을 반환합니다."
-#. placeholder {0}: label( actionInputLabelKey(actionId, batch.input), batch.input )
+#. placeholder {0}: inputLabel(batch.input)
msgid "A list is wired into {0}, so this step runs once for each item in it — up to {MAX_LIST_ITEMS}."
msgstr "목록이 {0}에 연결되어 있으므로 이 단계는 그 안의 각 항목마다 한 번씩 실행됩니다 — 최대 {MAX_LIST_ITEMS}개까지."
@@ -1372,6 +1372,9 @@ msgstr "알파"
msgid "Always"
msgstr "항상"
+msgid "Always sent — every notification shows in the bell menu."
+msgstr "항상 전송됨 — 모든 알림이 벨 메뉴에 표시됩니다."
+
msgid "Always taken"
msgstr "항상 사용됨"
@@ -3399,6 +3402,9 @@ msgstr "Jira 이슈 연결"
msgid "Connect Linear issue"
msgstr "Linear 이슈 연결"
+msgid "Connect Slack under Settings → Integrations first."
+msgstr "먼저 설정 → 통합 아래에서 Slack을 연결하세요."
+
msgid "Connect the Otherwise handle to a node to run when no condition matches."
msgstr "조건이 일치하지 않을 때 실행할 노드에 Otherwise 핸들을 연결합니다."
@@ -4190,6 +4196,9 @@ msgstr "사용자 정의 필드"
msgid "Custom Fields"
msgstr "사용자 정의 필드"
+msgid "Custom fields are not available for items yet."
+msgstr "사용자 정의 필드는 아직 항목에 사용할 수 없습니다."
+
msgid "Custom SOW · we manage"
msgstr "맞춤 SOW · 저희가 관리"
@@ -5095,6 +5104,9 @@ msgstr "치수"
msgid "Direct"
msgstr "직접"
+msgid "Direct message to each recipient in your Slack workspace."
+msgstr "Slack 작업 공간의 각 수신자에게 직접 메시지를 보냅니다."
+
msgid "Direction"
msgstr "방향"
@@ -7586,6 +7598,9 @@ msgstr "재고만"
msgid "In the loop together"
msgstr "함께 정보 공유하기"
+msgid "In-app"
+msgstr "인앱"
+
msgid "In-app notifications are always delivered. Choose which topics also reach you by email or Slack."
msgstr "인앱 알림은 항상 전달됩니다. 이메일 또는 Slack으로도 전달받을 주제를 선택하세요."
@@ -8475,8 +8490,8 @@ msgstr "목록 옵션"
msgid "List Parameters"
msgstr "목록 파라미터"
-#. placeholder {0}: label( actionInputLabelKey(actionId, batch.first), batch.first )
-#. placeholder {1}: label( actionInputLabelKey(actionId, batch.second), batch.second )
+#. placeholder {0}: inputLabel(batch.first)
+#. placeholder {1}: inputLabel(batch.second)
msgid "Lists are wired into both {0} and {1}, so this step cannot tell which one to repeat over. Leave a list on only one of them."
msgstr "{0}과 {1} 모두에 목록이 연결되어 있어서 이 단계에서 어느 것을 반복할지 알 수 없습니다. 목록을 하나에만 남기세요."
@@ -9267,6 +9282,9 @@ msgstr "필요일"
msgid "Need the right columns?"
msgstr "적절한 열이 필요하신가요?"
+msgid "Needs a Business or Partner plan."
+msgstr "Business 또는 Partner 요금제가 필요합니다."
+
msgid "Needs fixing"
msgstr "수정 필요"
@@ -9573,6 +9591,9 @@ msgstr "새 이동 라인"
msgid "New Unit of Measure"
msgstr "새 측정 단위"
+msgid "New version"
+msgstr "새 버전"
+
msgid "New Version"
msgstr "새 버전"
@@ -10142,6 +10163,12 @@ msgstr "아직 없습니다. 단계는 구성된 후에만 값을 제공합니
msgid "Notification"
msgstr "알림"
+msgid "Notification type"
+msgstr "알림 유형"
+
+msgid "Notification Type"
+msgstr "알림 유형"
+
msgid "Notifications"
msgstr "알림"
@@ -13334,6 +13361,9 @@ msgstr "이 문서를 활성화하기 전에 승인을 위해 전송합니다."
msgid "Sent complete date"
msgstr "발송 완료 날짜"
+msgid "Sent to each recipient who has email notifications turned on."
+msgstr "이메일 알림이 켜져 있는 각 수신자에게 전송됩니다."
+
msgid "Sequences"
msgstr "시퀀스"
@@ -15546,9 +15576,18 @@ msgstr "이 버전은 변경 공지 <0>{0}</0>에 속합니다. 거기서 편집
msgid "This version cannot be opened"
msgstr "이 버전을 열 수 없습니다."
+msgid "This version is live"
+msgstr "이 버전은 활성화되어 있습니다"
+
+msgid "This version is live, so it cannot be changed. You can still move steps around to tidy the layout."
+msgstr "이 버전은 활성화되어 있어서 변경할 수 없습니다. 여전히 단계를 이동하여 레이아웃을 정리할 수 있습니다."
+
msgid "This version is live. Create a new version to edit."
msgstr "이 버전은 활성입니다. 편집할 새 버전을 만드십시오."
+msgid "This version is live. Create a new version to make changes. You can still move steps around to tidy the layout."
+msgstr "이 버전은 활성화되어 있습니다. 변경하려면 새 버전을 만드세요. 여전히 단계를 이동하여 레이아웃을 정리할 수 있습니다."
+
msgid "This version's definition could not be read."
msgstr "이 버전의 정의를 읽을 수 없습니다."
@@ -16935,6 +16974,9 @@ msgstr "범위에서 제외되는 것"
msgid "When"
msgstr "시점"
+msgid "When {name} changes"
+msgstr "{name}이(가) 변경될 때"
+
msgid "When a finished product's shelf life is set to Calculated, pick which consumed inputs feed the calculation."
msgstr "완제품의 유효기간이 계산됨으로 설정된 경우, 계산에 반영할 소비 투입물을 선택하세요."
@@ -17031,6 +17073,9 @@ msgstr "귀사가 납품하기로 약속한 시점으로, 계획에서는 이를
msgid "When your fiscal and tax years start"
msgstr "회계연도 및 세무연도가 시작되는 시기"
+msgid "Where a workflow notification is delivered — in-app is always sent, while email needs a Business or Partner plan and Slack needs your Slack workspace connected."
+msgstr "워크플로우 알림이 전송되는 위치 — 인앱은 항상 전송되며, 이메일은 Business 또는 Partner 요금제가 필요하고 Slack은 Slack 작업 공간이 연결되어야 합니다."
+
msgid "Where an operation runs; carries labor and quoting rates, with overhead the difference between them."
msgstr "공정작업이 실행되는 곳으로, 노무 및 견적 요율을 가지며 두 요율의 차이가 간접비입니다."
diff --git a/packages/locale/locales/pl/erp.po b/packages/locale/locales/pl/erp.po
index 62f6054e51..a12b4e105e 100644
--- a/packages/locale/locales/pl/erp.po
+++ b/packages/locale/locales/pl/erp.po
@@ -456,7 +456,7 @@ msgstr "Status zadania zmienia się"
msgid "A list is wired into {0}, so this step runs once for each item and returns a list of results."
msgstr "Lista jest podłączona do {0}, więc ten krok uruchamia się raz dla każdego elementu i zwraca listę wyników."
-#. placeholder {0}: label( actionInputLabelKey(actionId, batch.input), batch.input )
+#. placeholder {0}: inputLabel(batch.input)
msgid "A list is wired into {0}, so this step runs once for each item in it — up to {MAX_LIST_ITEMS}."
msgstr "Lista jest podłączona do {0}, więc ten krok uruchamia się raz dla każdego elementu w niej — do {MAX_LIST_ITEMS}."
@@ -1372,6 +1372,9 @@ msgstr "Alfa"
msgid "Always"
msgstr "Zawsze"
+msgid "Always sent — every notification shows in the bell menu."
+msgstr "Zawsze wysyłane — każde powiadomienie pojawia się w menu dzwonka."
+
msgid "Always taken"
msgstr "Zawsze podjęty"
@@ -3399,6 +3402,9 @@ msgstr "Połącz problem Jiry"
msgid "Connect Linear issue"
msgstr "Połącz problem Linear"
+msgid "Connect Slack under Settings → Integrations first."
+msgstr "Najpierw połącz Slack w Ustawienia → Integracje."
+
msgid "Connect the Otherwise handle to a node to run when no condition matches."
msgstr "Połącz uchwyt Otherwise z węzłem do uruchomienia, gdy żaden warunek się nie zmieni."
@@ -4190,6 +4196,9 @@ msgstr "Pole niestandardowe"
msgid "Custom Fields"
msgstr "Pola niestandardowe"
+msgid "Custom fields are not available for items yet."
+msgstr "Pola niestandardowe nie są jeszcze dostępne dla artykułów."
+
msgid "Custom SOW · we manage"
msgstr "Niestandardowy SOW · zarządzamy"
@@ -5095,6 +5104,9 @@ msgstr "Wymiary"
msgid "Direct"
msgstr "Bezpośredni"
+msgid "Direct message to each recipient in your Slack workspace."
+msgstr "Bezpośrednia wiadomość do każdego odbiorcy w Twojej przestrzeni roboczej Slack."
+
msgid "Direction"
msgstr "Kierunek"
@@ -7586,6 +7598,9 @@ msgstr "Tylko w magazynie"
msgid "In the loop together"
msgstr "W pętli razem"
+msgid "In-app"
+msgstr "W aplikacji"
+
msgid "In-app notifications are always delivered. Choose which topics also reach you by email or Slack."
msgstr "Powiadomienia w aplikacji są zawsze dostarczane. Wybierz, które tematy mają do Ciebie dotrzeć również pocztą e-mail lub Slack."
@@ -8475,8 +8490,8 @@ msgstr "Opcje listy"
msgid "List Parameters"
msgstr "Parametry listy"
-#. placeholder {0}: label( actionInputLabelKey(actionId, batch.first), batch.first )
-#. placeholder {1}: label( actionInputLabelKey(actionId, batch.second), batch.second )
+#. placeholder {0}: inputLabel(batch.first)
+#. placeholder {1}: inputLabel(batch.second)
msgid "Lists are wired into both {0} and {1}, so this step cannot tell which one to repeat over. Leave a list on only one of them."
msgstr "Listy są podłączone do obu {0} i {1}, więc ten krok nie może określić, którą z nich powtarzać. Pozostaw listę tylko w jednej z nich."
@@ -9267,6 +9282,9 @@ msgstr "Potrzebne do"
msgid "Need the right columns?"
msgstr "Potrzebujesz odpowiednich kolumn?"
+msgid "Needs a Business or Partner plan."
+msgstr "Wymaga planu Business lub Partner."
+
msgid "Needs fixing"
msgstr "Wymaga naprawy"
@@ -9573,6 +9591,9 @@ msgstr "Nowa linia transferu"
msgid "New Unit of Measure"
msgstr "Nowa jednostka miary"
+msgid "New version"
+msgstr "Nowa wersja"
+
msgid "New Version"
msgstr "Nowa wersja"
@@ -10142,6 +10163,12 @@ msgstr "Nic jeszcze. Krok oferuje wartości dopiero po skonfigurowaniu."
msgid "Notification"
msgstr "Powiadomienie"
+msgid "Notification type"
+msgstr "Typ powiadomienia"
+
+msgid "Notification Type"
+msgstr "Typ powiadomienia"
+
msgid "Notifications"
msgstr "Powiadomienia"
@@ -13334,6 +13361,9 @@ msgstr "Wysyła ten dokument do zatwierdzenia, zanim będzie mógł zostać akty
msgid "Sent complete date"
msgstr "Data wysłania ukończenia"
+msgid "Sent to each recipient who has email notifications turned on."
+msgstr "Wysłane do każdego odbiorcy, który ma włączone powiadomienia e-mail."
+
msgid "Sequences"
msgstr "Sekwencje"
@@ -15546,9 +15576,18 @@ msgstr "Ta wersja należy do zmiany powiadomienia <0>{0}</0>. Edytuj tam."
msgid "This version cannot be opened"
msgstr "Ta wersja nie może być otwarta"
+msgid "This version is live"
+msgstr "Ta wersja jest na żywo"
+
+msgid "This version is live, so it cannot be changed. You can still move steps around to tidy the layout."
+msgstr "Ta wersja jest na żywo, dlatego nie można jej zmienić. Możesz nadal przenosić kroki, aby uporządkować układ."
+
msgid "This version is live. Create a new version to edit."
msgstr "Ta wersja jest aktywna. Utwórz nową wersję do edycji."
+msgid "This version is live. Create a new version to make changes. You can still move steps around to tidy the layout."
+msgstr "Ta wersja jest na żywo. Utwórz nową wersję, aby wprowadzić zmiany. Możesz nadal przenosić kroki, aby uporządkować układ."
+
msgid "This version's definition could not be read."
msgstr "Definicję tej wersji nie można było odczytać."
@@ -16935,6 +16974,9 @@ msgstr "Co jest poza zakresem"
msgid "When"
msgstr "Kiedy"
+msgid "When {name} changes"
+msgstr "Gdy zmieni się {name}"
+
msgid "When a finished product's shelf life is set to Calculated, pick which consumed inputs feed the calculation."
msgstr "Gdy okres przydatności gotowego produktu jest ustawiony na Obliczony, wybierz, które zużyte materiały wejściowe zasilają obliczenie."
@@ -17031,6 +17073,9 @@ msgstr "Kiedy zobowiązałeś się do dostawy; planowanie traktuje to jako datę
msgid "When your fiscal and tax years start"
msgstr "Kiedy rozpoczynają się Twoje lata obrachunkowe i podatkowe"
+msgid "Where a workflow notification is delivered — in-app is always sent, while email needs a Business or Partner plan and Slack needs your Slack workspace connected."
+msgstr "Gdzie jest dostarczane powiadomienie przepływu pracy — w aplikacji jest zawsze wysyłane, podczas gdy wiadomość e-mail wymaga planu Business lub Partner, a Slack wymaga połączonej przestrzeni roboczej Slack."
+
msgid "Where an operation runs; carries labor and quoting rates, with overhead the difference between them."
msgstr "Gdzie operacja przebiega; nosi stawki pracy i notowań, z ogólnymi kosztem różnicę między nimi."
diff --git a/packages/locale/locales/pt/erp.po b/packages/locale/locales/pt/erp.po
index 18cd40864c..0351ef6176 100644
--- a/packages/locale/locales/pt/erp.po
+++ b/packages/locale/locales/pt/erp.po
@@ -456,7 +456,7 @@ msgstr "O status de um trabalho muda"
msgid "A list is wired into {0}, so this step runs once for each item and returns a list of results."
msgstr "Uma lista é conectada a {0}, portanto, esta etapa é executada uma vez para cada item e retorna uma lista de resultados."
-#. placeholder {0}: label( actionInputLabelKey(actionId, batch.input), batch.input )
+#. placeholder {0}: inputLabel(batch.input)
msgid "A list is wired into {0}, so this step runs once for each item in it — up to {MAX_LIST_ITEMS}."
msgstr "Uma lista é conectada a {0}, portanto, esta etapa é executada uma vez para cada item nela — até {MAX_LIST_ITEMS}."
@@ -1372,6 +1372,9 @@ msgstr "Alfa"
msgid "Always"
msgstr "Sempre"
+msgid "Always sent — every notification shows in the bell menu."
+msgstr "Sempre enviado — todas as notificações aparecem no menu de sino."
+
msgid "Always taken"
msgstr "Sempre adotado"
@@ -3399,6 +3402,9 @@ msgstr "Conectar problema do Jira"
msgid "Connect Linear issue"
msgstr "Conectar problema do Linear"
+msgid "Connect Slack under Settings → Integrations first."
+msgstr "Conecte Slack em Configurações → Integrações primeiro."
+
msgid "Connect the Otherwise handle to a node to run when no condition matches."
msgstr "Conecte o manipulador Caso contrário a um nó para executar quando nenhuma condição corresponder."
@@ -4190,6 +4196,9 @@ msgstr "Campo Personalizado"
msgid "Custom Fields"
msgstr "Campos Personalizados"
+msgid "Custom fields are not available for items yet."
+msgstr "Os campos personalizados ainda não estão disponíveis para itens."
+
msgid "Custom SOW · we manage"
msgstr "SOW personalizado · gerenciamos"
@@ -5095,6 +5104,9 @@ msgstr "Dimensões"
msgid "Direct"
msgstr "Direto"
+msgid "Direct message to each recipient in your Slack workspace."
+msgstr "Mensagem direta para cada destinatário em seu espaço de trabalho do Slack."
+
msgid "Direction"
msgstr "Direção"
@@ -7586,6 +7598,9 @@ msgstr "Apenas em estoque"
msgid "In the loop together"
msgstr "No circuito juntos"
+msgid "In-app"
+msgstr "No aplicativo"
+
msgid "In-app notifications are always delivered. Choose which topics also reach you by email or Slack."
msgstr "As notificações no aplicativo são sempre entregues. Escolha quais tópicos também chegarão a você por email ou Slack."
@@ -8475,8 +8490,8 @@ msgstr "Opções de Lista"
msgid "List Parameters"
msgstr "Parâmetros de Lista"
-#. placeholder {0}: label( actionInputLabelKey(actionId, batch.first), batch.first )
-#. placeholder {1}: label( actionInputLabelKey(actionId, batch.second), batch.second )
+#. placeholder {0}: inputLabel(batch.first)
+#. placeholder {1}: inputLabel(batch.second)
msgid "Lists are wired into both {0} and {1}, so this step cannot tell which one to repeat over. Leave a list on only one of them."
msgstr "Listas estão conectadas em ambos {0} e {1}, então esta etapa não pode saber qual repetir. Deixe uma lista em apenas um deles."
@@ -9267,6 +9282,9 @@ msgstr "Necessário até"
msgid "Need the right columns?"
msgstr "Precisa das colunas certas?"
+msgid "Needs a Business or Partner plan."
+msgstr "Requer um plano Business ou Partner."
+
msgid "Needs fixing"
msgstr "Precisa de reparo"
@@ -9573,6 +9591,9 @@ msgstr "Nova Linha de Transferência"
msgid "New Unit of Measure"
msgstr "Nova Unidade de Medida"
+msgid "New version"
+msgstr "Nova versão"
+
msgid "New Version"
msgstr "Nova Versão"
@@ -10142,6 +10163,12 @@ msgstr "Nada ainda. Um passo só oferece valores uma vez que está configurado."
msgid "Notification"
msgstr "Notificação"
+msgid "Notification type"
+msgstr "Tipo de notificação"
+
+msgid "Notification Type"
+msgstr "Tipo de Notificação"
+
msgid "Notifications"
msgstr "Notificações"
@@ -13334,6 +13361,9 @@ msgstr "Envia este documento para aprovação antes de poder ficar ativo."
msgid "Sent complete date"
msgstr "Data de conclusão do envio"
+msgid "Sent to each recipient who has email notifications turned on."
+msgstr "Enviado a cada destinatário que tem notificações por e-mail ativadas."
+
msgid "Sequences"
msgstr "Sequências"
@@ -15546,9 +15576,18 @@ msgstr "Esta versão pertence ao aviso de alteração <0>{0}</0>. Edite-a lá."
msgid "This version cannot be opened"
msgstr "Esta versão não pode ser aberta"
+msgid "This version is live"
+msgstr "Esta versão está ativa"
+
+msgid "This version is live, so it cannot be changed. You can still move steps around to tidy the layout."
+msgstr "Esta versão está ativa, portanto não pode ser alterada. Você ainda pode mover as etapas para organizar o layout."
+
msgid "This version is live. Create a new version to edit."
msgstr "Esta versão está ativa. Crie uma nova versão para editar."
+msgid "This version is live. Create a new version to make changes. You can still move steps around to tidy the layout."
+msgstr "Esta versão está ativa. Crie uma nova versão para fazer alterações. Você ainda pode mover as etapas para organizar o layout."
+
msgid "This version's definition could not be read."
msgstr "A definição desta versão não pôde ser lida."
@@ -16935,6 +16974,9 @@ msgstr "O que está fora do escopo"
msgid "When"
msgstr "Quando"
+msgid "When {name} changes"
+msgstr "Quando {name} muda"
+
msgid "When a finished product's shelf life is set to Calculated, pick which consumed inputs feed the calculation."
msgstr "Quando a vida útil de um produto acabado é definida como Calculada, escolha quais entradas consumidas alimentam o cálculo."
@@ -17031,6 +17073,9 @@ msgstr "Quando você se comprometeu a entregar; o planejamento trata isso como a
msgid "When your fiscal and tax years start"
msgstr "Quando seus anos fiscais e de impostos começam"
+msgid "Where a workflow notification is delivered — in-app is always sent, while email needs a Business or Partner plan and Slack needs your Slack workspace connected."
+msgstr "Onde uma notificação de fluxo de trabalho é entregue — no aplicativo é sempre enviado, enquanto e-mail requer um plano Business ou Partner e Slack precisa de seu espaço de trabalho do Slack conectado."
+
msgid "Where an operation runs; carries labor and quoting rates, with overhead the difference between them."
msgstr "Onde uma operação é executada; leva as taxas de trabalho e cotação, com despesas gerais a diferença entre elas."
diff --git a/packages/locale/locales/ru/erp.po b/packages/locale/locales/ru/erp.po
index 707e82b314..f65e03d054 100644
--- a/packages/locale/locales/ru/erp.po
+++ b/packages/locale/locales/ru/erp.po
@@ -456,7 +456,7 @@ msgstr "Статус работы изменяется"
msgid "A list is wired into {0}, so this step runs once for each item and returns a list of results."
msgstr "Список подключен к {0}, поэтому этот шаг выполняется один раз для каждого элемента и возвращает список результатов."
-#. placeholder {0}: label( actionInputLabelKey(actionId, batch.input), batch.input )
+#. placeholder {0}: inputLabel(batch.input)
msgid "A list is wired into {0}, so this step runs once for each item in it — up to {MAX_LIST_ITEMS}."
msgstr "Список подключен к {0}, поэтому этот шаг выполняется один раз для каждого элемента в нем — до {MAX_LIST_ITEMS}."
@@ -1372,6 +1372,9 @@ msgstr "Альфа"
msgid "Always"
msgstr "Всегда"
+msgid "Always sent — every notification shows in the bell menu."
+msgstr "Всегда отправляется — каждое уведомление отображается в меню уведомлений."
+
msgid "Always taken"
msgstr "Всегда выбирается"
@@ -3399,6 +3402,9 @@ msgstr "Подключить проблему Jira"
msgid "Connect Linear issue"
msgstr "Подключить Linear issue"
+msgid "Connect Slack under Settings → Integrations first."
+msgstr "Сначала подключите Slack в разделе Настройки → Интеграции."
+
msgid "Connect the Otherwise handle to a node to run when no condition matches."
msgstr "Подключите обработчик Otherwise к узлу для запуска, когда ни одно условие не совпадает."
@@ -4190,6 +4196,9 @@ msgstr "Пользовательское поле"
msgid "Custom Fields"
msgstr "Пользовательские поля"
+msgid "Custom fields are not available for items yet."
+msgstr "Пользовательские поля пока недоступны для элементов."
+
msgid "Custom SOW · we manage"
msgstr "Пользовательское SOW · мы управляем"
@@ -5095,6 +5104,9 @@ msgstr "Размеры"
msgid "Direct"
msgstr "Прямой"
+msgid "Direct message to each recipient in your Slack workspace."
+msgstr "Прямое сообщение каждому получателю в вашем рабочем пространстве Slack."
+
msgid "Direction"
msgstr "Направление"
@@ -7586,6 +7598,9 @@ msgstr "Только в наличии"
msgid "In the loop together"
msgstr "В курсе дела вместе"
+msgid "In-app"
+msgstr "В приложении"
+
msgid "In-app notifications are always delivered. Choose which topics also reach you by email or Slack."
msgstr "Уведомления в приложении всегда доставляются. Выберите, какие темы также будут доходить до вас по электронной почте или Slack."
@@ -8475,8 +8490,8 @@ msgstr "Параметры списка"
msgid "List Parameters"
msgstr "Параметры списка"
-#. placeholder {0}: label( actionInputLabelKey(actionId, batch.first), batch.first )
-#. placeholder {1}: label( actionInputLabelKey(actionId, batch.second), batch.second )
+#. placeholder {0}: inputLabel(batch.first)
+#. placeholder {1}: inputLabel(batch.second)
msgid "Lists are wired into both {0} and {1}, so this step cannot tell which one to repeat over. Leave a list on only one of them."
msgstr "Списки привязаны к обоим {0} и {1}, поэтому этот шаг не может определить, какой из них повторить. Оставьте список только в одном из них."
@@ -9267,6 +9282,9 @@ msgstr "Требуется к"
msgid "Need the right columns?"
msgstr "Нужны правильные столбцы?"
+msgid "Needs a Business or Partner plan."
+msgstr "Требуется план Business или Partner."
+
msgid "Needs fixing"
msgstr "Требуется исправление"
@@ -9573,6 +9591,9 @@ msgstr "Новая строка передачи"
msgid "New Unit of Measure"
msgstr "Новая единица измерения"
+msgid "New version"
+msgstr "Новая версия"
+
msgid "New Version"
msgstr "Новая версия"
@@ -10142,6 +10163,12 @@ msgstr "Пока ничего. Шаг предоставляет значени
msgid "Notification"
msgstr "Уведомление"
+msgid "Notification type"
+msgstr "Тип уведомления"
+
+msgid "Notification Type"
+msgstr "Тип уведомления"
+
msgid "Notifications"
msgstr "Уведомления"
@@ -13334,6 +13361,9 @@ msgstr "Отправляет этот документ на утверждени
msgid "Sent complete date"
msgstr "Дата отправки выполнена"
+msgid "Sent to each recipient who has email notifications turned on."
+msgstr "Отправляется каждому получателю, у которого включены email-уведомления."
+
msgid "Sequences"
msgstr "Последовательности"
@@ -15546,9 +15576,18 @@ msgstr "Эта версия принадлежит уведомлению об
msgid "This version cannot be opened"
msgstr "Эта версия не может быть открыта"
+msgid "This version is live"
+msgstr "Эта версия активна"
+
+msgid "This version is live, so it cannot be changed. You can still move steps around to tidy the layout."
+msgstr "Эта версия активна, поэтому её нельзя изменить. Вы по-прежнему можете перемещать шаги для упорядочивания макета."
+
msgid "This version is live. Create a new version to edit."
msgstr "Эта версия активна. Создайте новую версию для редактирования."
+msgid "This version is live. Create a new version to make changes. You can still move steps around to tidy the layout."
+msgstr "Эта версия активна. Создайте новую версию для внесения изменений. Вы по-прежнему можете перемещать шаги для упорядочивания макета."
+
msgid "This version's definition could not be read."
msgstr "Определение этой версии не удалось прочитать."
@@ -16935,6 +16974,9 @@ msgstr "Что выходит за рамки"
msgid "When"
msgstr "Когда"
+msgid "When {name} changes"
+msgstr "Когда {name} изменяется"
+
msgid "When a finished product's shelf life is set to Calculated, pick which consumed inputs feed the calculation."
msgstr "Когда срок хранения готового продукта установлен на Рассчитанный, выберите, какие потребленные входные данные питают расчет."
@@ -17031,6 +17073,9 @@ msgstr "Когда вы обязались доставить; планиров
msgid "When your fiscal and tax years start"
msgstr "Когда начинаются ваши финансовый и налоговый годы"
+msgid "Where a workflow notification is delivered — in-app is always sent, while email needs a Business or Partner plan and Slack needs your Slack workspace connected."
+msgstr "Где доставляется уведомление рабочего процесса — в приложении всегда отправляется, email требует план Business или Partner, а Slack требует подключённого рабочего пространства Slack."
+
msgid "Where an operation runs; carries labor and quoting rates, with overhead the difference between them."
msgstr "Где работает операция; несет ставки труда и предложения, накладные расходы - разница между ними."
diff --git a/packages/locale/locales/tr/erp.po b/packages/locale/locales/tr/erp.po
index d088a009b5..982ccffc14 100644
--- a/packages/locale/locales/tr/erp.po
+++ b/packages/locale/locales/tr/erp.po
@@ -456,7 +456,7 @@ msgstr "Bir işin durumu değiştirildi"
msgid "A list is wired into {0}, so this step runs once for each item and returns a list of results."
msgstr "Bir liste {0} öğesine bağlandı, bu nedenle bu adım her öğe için bir kez çalışır ve sonuçların listesini döndürür."
-#. placeholder {0}: label( actionInputLabelKey(actionId, batch.input), batch.input )
+#. placeholder {0}: inputLabel(batch.input)
msgid "A list is wired into {0}, so this step runs once for each item in it — up to {MAX_LIST_ITEMS}."
msgstr "Bir liste {0} öğesine bağlandı, bu nedenle bu adım içindeki her öğe için bir kez çalışır — en fazla {MAX_LIST_ITEMS}."
@@ -1372,6 +1372,9 @@ msgstr "Alfa"
msgid "Always"
msgstr "Her zaman"
+msgid "Always sent — every notification shows in the bell menu."
+msgstr "Her zaman gönderilir — her bildirim çan menüsünde gösterilir."
+
msgid "Always taken"
msgstr "Her zaman alındı"
@@ -3399,6 +3402,9 @@ msgstr "Jira sorununu bağla"
msgid "Connect Linear issue"
msgstr "Linear sorununu bağla"
+msgid "Connect Slack under Settings → Integrations first."
+msgstr "Slack'i önce Ayarlar → İntegrasyonlar altında bağlayın."
+
msgid "Connect the Otherwise handle to a node to run when no condition matches."
msgstr "Hiçbir koşul eşleşmediğinde çalıştırılacak bir düğüme Aksi takdirde işlecini bağlayın."
@@ -4190,6 +4196,9 @@ msgstr "Özel Alan"
msgid "Custom Fields"
msgstr "Özel Alanlar"
+msgid "Custom fields are not available for items yet."
+msgstr "Özel alanlar henüz öğeler için kullanılabilir değildir."
+
msgid "Custom SOW · we manage"
msgstr "Özel SOW · biz yönetiriz"
@@ -5095,6 +5104,9 @@ msgstr "Boyutlar"
msgid "Direct"
msgstr "Doğrudan"
+msgid "Direct message to each recipient in your Slack workspace."
+msgstr "Slack çalışma alanınızdaki her alıcıya doğrudan mesaj."
+
msgid "Direction"
msgstr "Yön"
@@ -7586,6 +7598,9 @@ msgstr "Yalnızca stokta"
msgid "In the loop together"
msgstr "Birlikte döngüde"
+msgid "In-app"
+msgstr "Uygulama içi"
+
msgid "In-app notifications are always delivered. Choose which topics also reach you by email or Slack."
msgstr "Uygulama içi bildirimler her zaman iletilir. Hangi konuların e-posta veya Slack aracılığıyla sizi ulaştıracağını seçin."
@@ -8475,8 +8490,8 @@ msgstr "Liste Seçenekleri"
msgid "List Parameters"
msgstr "Liste Parametreleri"
-#. placeholder {0}: label( actionInputLabelKey(actionId, batch.first), batch.first )
-#. placeholder {1}: label( actionInputLabelKey(actionId, batch.second), batch.second )
+#. placeholder {0}: inputLabel(batch.first)
+#. placeholder {1}: inputLabel(batch.second)
msgid "Lists are wired into both {0} and {1}, so this step cannot tell which one to repeat over. Leave a list on only one of them."
msgstr "Listeler hem {0} hem de {1} öğelerine bağlıdır, bu nedenle bu adım hangisinin üzerinde tekrarlanacağını belirleyemez. Listeyi yalnızca birine bırakın."
@@ -9267,6 +9282,9 @@ msgstr "Gerektiğinde"
msgid "Need the right columns?"
msgstr "Doğru sütunlara ihtiyacınız var mı?"
+msgid "Needs a Business or Partner plan."
+msgstr "Business veya Partner planı gereklidir."
+
msgid "Needs fixing"
msgstr "Onarılması gerekir"
@@ -9573,6 +9591,9 @@ msgstr "Yeni Transfer Satırı"
msgid "New Unit of Measure"
msgstr "Yeni Bir Ölçü Birimi"
+msgid "New version"
+msgstr "Yeni versiyon"
+
msgid "New Version"
msgstr "Yeni Sürüm"
@@ -10142,6 +10163,12 @@ msgstr "Henüz hiçbir şey yok. Bir adım yalnızca yapılandırıldıktan sonr
msgid "Notification"
msgstr "Bildirim"
+msgid "Notification type"
+msgstr "Bildirim türü"
+
+msgid "Notification Type"
+msgstr "Bildirim Türü"
+
msgid "Notifications"
msgstr "Bildirimler"
@@ -13334,6 +13361,9 @@ msgstr "Bu belge aktif hale gelmeden önce onay için gönderilir."
msgid "Sent complete date"
msgstr "Gönderilen tamamlama tarihi"
+msgid "Sent to each recipient who has email notifications turned on."
+msgstr "E-posta bildirimleri açık olan her alıcıya gönderilir."
+
msgid "Sequences"
msgstr "Sıralamalar"
@@ -15546,9 +15576,18 @@ msgstr "Bu sürüm değişiklik bildirimi <0>{0}</0> ile ilgilidir. Orada düzen
msgid "This version cannot be opened"
msgstr "Bu sürüm açılamıyor"
+msgid "This version is live"
+msgstr "Bu versiyon yayında"
+
+msgid "This version is live, so it cannot be changed. You can still move steps around to tidy the layout."
+msgstr "Bu versiyon yayında olduğundan değiştirilemez. Düzeni düzenlemek için yine de adımları hareket ettirebilirsiniz."
+
msgid "This version is live. Create a new version to edit."
msgstr "Bu sürüm canlı. Düzenlemek için yeni bir sürüm oluşturun."
+msgid "This version is live. Create a new version to make changes. You can still move steps around to tidy the layout."
+msgstr "Bu versiyon yayında. Değişiklik yapmak için yeni bir versiyon oluşturun. Düzeni düzenlemek için yine de adımları hareket ettirebilirsiniz."
+
msgid "This version's definition could not be read."
msgstr "Bu sürümün tanımı okunamadı."
@@ -16935,6 +16974,9 @@ msgstr "Kapsam dışında neler var"
msgid "When"
msgstr "Ne zaman"
+msgid "When {name} changes"
+msgstr "Ne zaman {name} değişir"
+
msgid "When a finished product's shelf life is set to Calculated, pick which consumed inputs feed the calculation."
msgstr "Bir bitmiş ürünün raf ömrü Hesaplanan olarak ayarlandığında, hesaplamaya hangi tüketilen girdilerin dahil edileceğini seçin."
@@ -17031,6 +17073,9 @@ msgstr "Teslim etmeyi taahhüt ettiğiniz zaman; planlama bunu karşılama için
msgid "When your fiscal and tax years start"
msgstr "Mali ve vergi yıllarınız ne zaman başlar"
+msgid "Where a workflow notification is delivered — in-app is always sent, while email needs a Business or Partner plan and Slack needs your Slack workspace connected."
+msgstr "İş akışı bildiriminin nereye teslim edileceği — uygulama içi her zaman gönderilir, e-posta Business veya Partner planı gerektirir ve Slack, Slack çalışma alanınızın bağlı olması gerekir."
+
msgid "Where an operation runs; carries labor and quoting rates, with overhead the difference between them."
msgstr "Bir operasyonun nerede çalıştırıldığı; işçilik ve teklif oranlarını taşır, genel giderler aralarındaki fark."
diff --git a/packages/locale/locales/zh/erp.po b/packages/locale/locales/zh/erp.po
index aee194bfda..1a558149ee 100644
--- a/packages/locale/locales/zh/erp.po
+++ b/packages/locale/locales/zh/erp.po
@@ -456,7 +456,7 @@ msgstr "任务的状态已变更"
msgid "A list is wired into {0}, so this step runs once for each item and returns a list of results."
msgstr "列表被接入到 {0},所以此步骤为每个项目运行一次并返回结果列表。"
-#. placeholder {0}: label( actionInputLabelKey(actionId, batch.input), batch.input )
+#. placeholder {0}: inputLabel(batch.input)
msgid "A list is wired into {0}, so this step runs once for each item in it — up to {MAX_LIST_ITEMS}."
msgstr "列表被接入到 {0},所以此步骤为其中每个项目运行一次 — 最多 {MAX_LIST_ITEMS} 个。"
@@ -1372,6 +1372,9 @@ msgstr "Alpha"
msgid "Always"
msgstr "始终"
+msgid "Always sent — every notification shows in the bell menu."
+msgstr "始终发送 — 每个通知都显示在铃声菜单中。"
+
msgid "Always taken"
msgstr "始终采取"
@@ -3399,6 +3402,9 @@ msgstr "连接 Jira 问题"
msgid "Connect Linear issue"
msgstr "连接 Linear 问题"
+msgid "Connect Slack under Settings → Integrations first."
+msgstr "先在设置 → 集成中连接 Slack。"
+
msgid "Connect the Otherwise handle to a node to run when no condition matches."
msgstr "将 Otherwise 句柄连接到节点,以便在没有条件匹配时运行。"
@@ -4190,6 +4196,9 @@ msgstr "自定义字段"
msgid "Custom Fields"
msgstr "自定义字段"
+msgid "Custom fields are not available for items yet."
+msgstr "自定义字段尚不适用于项目。"
+
msgid "Custom SOW · we manage"
msgstr "自定义 SOW · 我们管理"
@@ -5095,6 +5104,9 @@ msgstr "尺寸"
msgid "Direct"
msgstr "直接"
+msgid "Direct message to each recipient in your Slack workspace."
+msgstr "在您的 Slack 工作区中直接消息给每个收件人。"
+
msgid "Direction"
msgstr "方向"
@@ -7586,6 +7598,9 @@ msgstr "仅库存"
msgid "In the loop together"
msgstr "一起保持沟通"
+msgid "In-app"
+msgstr "应用内"
+
msgid "In-app notifications are always delivered. Choose which topics also reach you by email or Slack."
msgstr "应用内通知始终会被传递。选择哪些主题也通过电子邮件或 Slack 发送给您。"
@@ -8475,8 +8490,8 @@ msgstr "列表选项"
msgid "List Parameters"
msgstr "列表参数"
-#. placeholder {0}: label( actionInputLabelKey(actionId, batch.first), batch.first )
-#. placeholder {1}: label( actionInputLabelKey(actionId, batch.second), batch.second )
+#. placeholder {0}: inputLabel(batch.first)
+#. placeholder {1}: inputLabel(batch.second)
msgid "Lists are wired into both {0} and {1}, so this step cannot tell which one to repeat over. Leave a list on only one of them."
msgstr "列表同时连接到{0}和{1},因此此步骤无法判断要在哪一个上重复。仅在其中一个上保留列表。"
@@ -9267,6 +9282,9 @@ msgstr "需要日期"
msgid "Need the right columns?"
msgstr "需要正确的列吗?"
+msgid "Needs a Business or Partner plan."
+msgstr "需要业务或合作伙伴计划。"
+
msgid "Needs fixing"
msgstr "需要修复"
@@ -9573,6 +9591,9 @@ msgstr "新转移行"
msgid "New Unit of Measure"
msgstr "新计量单位"
+msgid "New version"
+msgstr "新版本"
+
msgid "New Version"
msgstr "新版本"
@@ -10142,6 +10163,12 @@ msgstr "暂无内容。步骤配置后才会提供值。"
msgid "Notification"
msgstr "通知"
+msgid "Notification type"
+msgstr "通知类型"
+
+msgid "Notification Type"
+msgstr "通知类型"
+
msgid "Notifications"
msgstr "通知"
@@ -13334,6 +13361,9 @@ msgstr "在文档激活前将其发送以供批准。"
msgid "Sent complete date"
msgstr "发送完成日期"
+msgid "Sent to each recipient who has email notifications turned on."
+msgstr "发送给打开了电子邮件通知的每个收件人。"
+
msgid "Sequences"
msgstr "序列"
@@ -15546,9 +15576,18 @@ msgstr "此版本属于变更通知<0>{0}</0>。请在那里编辑。"
msgid "This version cannot be opened"
msgstr "无法打开此版本"
+msgid "This version is live"
+msgstr "此版本已上线"
+
+msgid "This version is live, so it cannot be changed. You can still move steps around to tidy the layout."
+msgstr "此版本已上线,因此无法更改。您仍然可以移动步骤来整理布局。"
+
msgid "This version is live. Create a new version to edit."
msgstr "此版本处于实时状态。创建新版本进行编辑。"
+msgid "This version is live. Create a new version to make changes. You can still move steps around to tidy the layout."
+msgstr "此版本已上线。创建新版本以进行更改。您仍然可以移动步骤来整理布局。"
+
msgid "This version's definition could not be read."
msgstr "无法读取此版本的定义。"
@@ -16935,6 +16974,9 @@ msgstr "超出范围的内容"
msgid "When"
msgstr "何时"
+msgid "When {name} changes"
+msgstr "当 {name} 更改时"
+
msgid "When a finished product's shelf life is set to Calculated, pick which consumed inputs feed the calculation."
msgstr "当成品的保质期设置为\"计算\"时,选择哪些消耗的投入物料用于计算。"
@@ -17031,6 +17073,9 @@ msgstr "当您承诺交货时;计划将其视为履行的需求到期日期。"
msgid "When your fiscal and tax years start"
msgstr "您的会计年度和税务年度的开始时间"
+msgid "Where a workflow notification is delivered — in-app is always sent, while email needs a Business or Partner plan and Slack needs your Slack workspace connected."
+msgstr "工作流通知的传送位置 — 应用内始终发送,电子邮件需要业务或合作伙伴计划,Slack 需要连接您的 Slack 工作区。"
+
msgid "Where an operation runs; carries labor and quoting rates, with overhead the difference between them."
msgstr "操作执行的位置。carries劳动和报价费率,开销是它们之间的差异。"
diff --git a/packages/notifications/AGENTS.md b/packages/notifications/AGENTS.md
index ac43df444c..ef31cc857d 100644
--- a/packages/notifications/AGENTS.md
+++ b/packages/notifications/AGENTS.md
@@ -28,6 +28,7 @@ pnpm --filter @carbon/notifications typecheck # tsgo --noEmit
## Key Patterns
- **Enums + pure mapping helpers, no I/O** — `NotificationEvent`, `NotificationTopic`, `NotificationDestination`; `getNotificationTopic`, email heading/CTA helpers, and `USER_FACING_NOTIFICATION_TOPICS` (display order for the account notification-settings page — when adding a `NotificationTopic`, add it here too or it won't appear on that page)
+- **Body rendering lives here, all three renditions together** — `renderInlineLinks` (the strict `[label](https://origin/…)` matcher; a security boundary, since a workflow's message body is customer-authored) plus `renderSlackMrkdwn` / `escapeSlackText` for the Slack rendition. The in-app topbar and `NotificationEmail.tsx` consume the segments directly. A fourth channel adds its rendition beside these, not in the fan-out job
- **`NotificationEvent.Workflow` is the payload-text kind** — every other event's content is read from its source document; this one carries `title` / `body` on the `carbon/notify` payload and reads nothing. Raised by the workflows notify action (`packages/jobs/src/workflows/actions/notify.ts`), topic `General`
- **inApp is always included** — regardless of caller-specified destinations
- **Single export**: `@carbon/notifications` barrel from `src/index.ts`
diff --git a/packages/notifications/package.json b/packages/notifications/package.json
index b867839a4b..0c38a4edfc 100644
--- a/packages/notifications/package.json
+++ b/packages/notifications/package.json
@@ -3,7 +3,8 @@
"@carbon/config": "workspace:*",
"@types/node": "20.19.39",
"sst": "catalog:",
- "typescript": "catalog:"
+ "typescript": "catalog:",
+ "vitest": "catalog:"
},
"exports": {
".": "./src/index.ts"
@@ -14,6 +15,7 @@
"clean": "rimraf .turbo node_modules dist",
"dev": "tsup --watch",
"lint": "biome lint --write ",
+ "test": "vitest run",
"typecheck": "tsgo --noEmit"
},
"sideEffects": false,
diff --git a/packages/notifications/src/index.test.ts b/packages/notifications/src/index.test.ts
new file mode 100644
index 0000000000..f57c8acda7
--- /dev/null
+++ b/packages/notifications/src/index.test.ts
@@ -0,0 +1,88 @@
+import { describe, expect, it } from "vitest";
+import { renderInlineLinks, renderSlackMrkdwn } from "./index";
+
+const ORIGIN = "https://app.carbon.ms";
+const HREF = `${ORIGIN}/api/link?event=workflow&documentId=so_1`;
+
+describe("renderInlineLinks", () => {
+ it("returns nothing for an empty string", () => {
+ expect(renderInlineLinks("", ORIGIN)).toEqual([]);
+ });
+
+ it("returns plain text as a single segment", () => {
+ expect(renderInlineLinks("Nothing to see", ORIGIN)).toEqual([
+ { text: "Nothing to see" }
+ ]);
+ });
+
+ it("splits a link out of the surrounding text", () => {
+ expect(
+ renderInlineLinks(`Check [SO000123](${HREF}) today`, ORIGIN)
+ ).toEqual([
+ { text: "Check " },
+ { text: "SO000123", href: HREF },
+ { text: " today" }
+ ]);
+ });
+
+ it("handles two links in one body", () => {
+ const body = `[A](${HREF}) and [B](${HREF})`;
+ expect(renderInlineLinks(body, ORIGIN)).toEqual([
+ { text: "A", href: HREF },
+ { text: " and " },
+ { text: "B", href: HREF }
+ ]);
+ });
+
+ // The reason this function exists: the body is customer-authored.
+ it("leaves a javascript: url as literal text", () => {
+ const body = "[click](javascript:alert(1))";
+ expect(renderInlineLinks(body, ORIGIN)).toEqual([{ text: body }]);
+ });
+
+ it("leaves another host as literal text", () => {
+ const body = "[click](https://evil.example/steal)";
+ expect(renderInlineLinks(body, ORIGIN)).toEqual([{ text: body }]);
+ });
+
+ it("leaves a plain http url as literal text", () => {
+ const body = "[click](http://app.carbon.ms/x)";
+ expect(renderInlineLinks(body, ORIGIN)).toEqual([{ text: body }]);
+ });
+
+ it("leaves a relative path as literal text", () => {
+ const body = "[click](/x/sales/orders)";
+ expect(renderInlineLinks(body, ORIGIN)).toEqual([{ text: body }]);
+ });
+
+ it("treats an unparseable origin as no origin at all", () => {
+ const body = `Check [SO000123](${HREF})`;
+ expect(renderInlineLinks(body, "")).toEqual([{ text: body }]);
+ });
+});
+
+describe("renderSlackMrkdwn", () => {
+ it("rewrites a Carbon link as Slack mrkdwn", () => {
+ expect(renderSlackMrkdwn(`Check [SO000123](${HREF})`, ORIGIN)).toBe(
+ `Check <${HREF}|SO000123>`
+ );
+ });
+
+ it("leaves a link on another host as literal text", () => {
+ const body = "[click](https://evil.example/steal)";
+ expect(renderSlackMrkdwn(body, ORIGIN)).toBe(
+ "[click](https://evil.example/steal)"
+ );
+ });
+
+ // `|` would terminate the label, and Slack reads bare `&`/`<`/`>` as markup.
+ it("escapes Slack's control characters in both a label and plain text", () => {
+ expect(renderSlackMrkdwn(`A & B <c> [x|y](${HREF})`, ORIGIN)).toBe(
+ `A &amp; B &lt;c&gt; <${HREF}|x¦y>`
+ );
+ });
+
+ it("returns an empty string for an empty message", () => {
+ expect(renderSlackMrkdwn("", ORIGIN)).toBe("");
+ });
+});
diff --git a/packages/notifications/src/index.ts b/packages/notifications/src/index.ts
index 433c9500dd..ca6f6be290 100644
--- a/packages/notifications/src/index.ts
+++ b/packages/notifications/src/index.ts
@@ -326,3 +326,81 @@ export function getNotificationTopicPhrase(
return `${count} unread ${plural}`;
}
}
+
+export type InlineLinkSegment =
+ | { text: string }
+ | { text: string; href: string };
+
+/**
+ * Deliberately strict: `[label](url)` where the url is an absolute https URL on the
+ * supplied origin. A relative path, another host, or a `javascript:` url is left as
+ * literal text.
+ *
+ * This is a security boundary, not a formatting nicety. A workflow's message body is
+ * customer-authored, so an unrestricted matcher would let its author choose where a
+ * notification the recipient trusts actually points.
+ */
+const INLINE_LINK = /\[([^\]\n]+)\]\((https:\/\/[^\s()]+)\)/g;
+
+export function renderInlineLinks(
+ text: string,
+ origin: string
+): InlineLinkSegment[] {
+ if (text === "") return [];
+
+ let allowed: URL;
+ try {
+ allowed = new URL(origin);
+ } catch {
+ return [{ text }];
+ }
+
+ const segments: InlineLinkSegment[] = [];
+ let index = 0;
+
+ for (const match of text.matchAll(INLINE_LINK)) {
+ const [whole, label, href] = match;
+ if (label === undefined || href === undefined) continue;
+
+ let parsed: URL;
+ try {
+ parsed = new URL(href);
+ } catch {
+ continue;
+ }
+ if (parsed.protocol !== "https:" || parsed.origin !== allowed.origin) {
+ continue;
+ }
+
+ const start = match.index ?? 0;
+ if (start > index) segments.push({ text: text.slice(index, start) });
+ segments.push({ text: label, href: parsed.toString() });
+ index = start + whole.length;
+ }
+
+ if (index < text.length) segments.push({ text: text.slice(index) });
+ return segments;
+}
+
+/** Slack mrkdwn requires `&`, `<` and `>` escaped in text; inside a `<url|label>` a literal
+ * `|` would also terminate the label, so it is swapped for a lookalike. */
+export function escapeSlackText(value: string): string {
+ return value
+ .replace(/&/g, "&amp;")
+ .replace(/</g, "&lt;")
+ .replace(/>/g, "&gt;")
+ .replace(/\|/g, "¦");
+}
+
+/** The Slack rendition of the same `[label](url)` the in-app and email renderers handle —
+ * Slack spells a link `<url|label>`, so the markdown would otherwise be shown verbatim.
+ * Goes through `renderInlineLinks`, so it inherits that matcher's origin restriction. */
+export function renderSlackMrkdwn(text: string, origin: string): string {
+ return renderInlineLinks(text, origin)
+ .map((segment) =>
+ "href" in segment
+ ? `<${segment.href}|${escapeSlackText(segment.text)}>`
+ : escapeSlackText(segment.text)
+ )
+ .join("");
+}
diff --git a/packages/notifications/vitest.config.ts b/packages/notifications/vitest.config.ts
new file mode 100644
index 0000000000..9a3c27eaed
--- /dev/null
+++ b/packages/notifications/vitest.config.ts
@@ -0,0 +1 @@
+export { default } from "@carbon/config/vitest";
diff --git a/packages/react/src/Input.tsx b/packages/react/src/Input.tsx
index b94d5c0020..ade5af47e1 100644
--- a/packages/react/src/Input.tsx
+++ b/packages/react/src/Input.tsx
@@ -192,7 +192,7 @@ const Input = forwardRef<HTMLInputElement, InputProps>(
isFirstChild = true,
isLastChild = true,
isInvalid = false,
- isDisabled = false,
+ isDisabled,
isReadOnly = false,
borderless = false,
type = "text",
@@ -201,6 +201,7 @@ const Input = forwardRef<HTMLInputElement, InputProps>(
ref
) => {
const isInputGroup = useContext(InputGroupContext) ?? false;
+ const disabled = isDisabled ?? props.disabled ?? false;
return (
<ReactAria.Input
@@ -212,13 +213,14 @@ const Input = forwardRef<HTMLInputElement, InputProps>(
isLastChild,
isInvalid,
isReadOnly,
- isDisabled,
+ isDisabled: disabled,
borderless
}),
className
)}
{...props}
- disabled={isDisabled}
+ // Explicit disabled must survive the spread; it was being overwritten.
+ disabled={disabled}
readOnly={isReadOnly}
ref={ref}
type={type}
diff --git a/packages/react/src/VariableText/VariableText.tsx b/packages/react/src/VariableText/VariableText.tsx
index d57a954a9a..b109473b12 100644
--- a/packages/react/src/VariableText/VariableText.tsx
+++ b/packages/react/src/VariableText/VariableText.tsx
@@ -12,7 +12,7 @@ import {
Placeholder,
StarterKit
} from "@carbon/tiptap";
-import type { RefObject } from "react";
+import type { CSSProperties, RefObject } from "react";
import {
forwardRef,
useEffect,
@@ -51,6 +51,9 @@ export type VariableTextProps = {
menuComponent?: MentionListComponent;
/** Shortens the text drawn inside a token chip. The stored label is untouched. */
renderTokenLabel?: (label: string) => string;
+ /** Renders the same value but refuses edits. The Tiptap shell stays, so the
+ * read-only rendition matches the editable one exactly. */
+ isReadOnly?: boolean;
};
export type VariableTextHandle = {
@@ -138,14 +141,15 @@ function contentKey(parts: VariableTextPart[]): string {
// A char no keyboard produces, so the menu stays dormant when no trigger is given.
const NO_TRIGGER = "\0";
-/** The editor shell, exported so a read-only rendition of the same value matches.
- * No `min-h-*`: the height range is computed from `minRows`/`maxRows` below.
- * `select-text` is load-bearing: React Flow puts `user-select: none` on every node,
- * and an inherited `none` stops a click placing the caret inside a contenteditable. */
+/** The editor shell, exported so a read-only rendition of the same value matches. It is
+ * chrome only — the padding and the height floor live on the contenteditable itself
+ * (`.variable-text-content`), so that element fills the box and a click anywhere in it
+ * places a caret. `select-text` is load-bearing: React Flow puts `user-select: none` on
+ * every node, and an inherited `none` stops a click placing the caret at all. */
export const VARIABLE_TEXT_SHELL_CLASS =
- "select-text cursor-text overflow-y-auto overscroll-contain break-words rounded-md border border-input bg-background px-3 py-2 text-sm";
+ "select-text cursor-text overflow-y-auto overscroll-contain break-words rounded-md border border-input bg-background text-sm";
-// A `text-sm` line box plus `py-2`, so one row is 2.5rem — the old fixed floor.
+// A `text-sm` line box plus the content's own padding, so one row is 2.5rem.
const ROW_REM = 1.25;
const PADDING_REM = 1.25;
const heightFor = (rows: number) => `${rows * ROW_REM + PADDING_REM}rem`;
@@ -166,7 +170,8 @@ export const VariableText = forwardRef<VariableTextHandle, VariableTextProps>(
maxRows = 5,
minRows = 1,
menuComponent,
- renderTokenLabel
+ renderTokenLabel,
+ isReadOnly = false
},
ref
) {
@@ -249,6 +254,11 @@ export const VariableText = forwardRef<VariableTextHandle, VariableTextProps>(
editor.commands.setContent(partsToDoc(valueRef.current), false);
}, [key]);
+ // The editor is created once, so a lock that arrives later has to be applied here.
+ useEffect(() => {
+ editorRef.current?.setEditable(!isReadOnly);
+ }, [isReadOnly]);
+
useImperativeHandle(ref, () => ({
insertToken: (token) => {
const editor = editorRef.current;
@@ -268,14 +278,18 @@ export const VariableText = forwardRef<VariableTextHandle, VariableTextProps>(
`style` passthrough, and the row range has to be an inline height. */}
<div
className={cn(VARIABLE_TEXT_SHELL_CLASS, className)}
- style={{
- minHeight: heightFor(minRows),
- maxHeight: heightFor(maxRows)
- }}
+ style={
+ {
+ minHeight: heightFor(minRows),
+ maxHeight: heightFor(maxRows),
+ "--variable-text-content-min-height": heightFor(minRows)
+ } as CSSProperties
+ }
>
<EditorContent
initialContent={initialContent}
extensions={extensions}
+ editable={!isReadOnly}
editorProps={{
handleKeyDown(_view, event) {
// Never swallow the popup's Enter: ProseMirror consults these props
@@ -285,7 +299,7 @@ export const VariableText = forwardRef<VariableTextHandle, VariableTextProps>(
return false;
},
attributes: {
- class: "focus:outline-none max-w-full"
+ class: "focus:outline-none max-w-full variable-text-content"
}
}}
onCreate={({ editor }) => {
diff --git a/packages/react/src/VariableText/variable-text.css b/packages/react/src/VariableText/variable-text.css
index 03a56fb172..5e5bf3163c 100644
--- a/packages/react/src/VariableText/variable-text.css
+++ b/packages/react/src/VariableText/variable-text.css
@@ -1,3 +1,12 @@
+/* The editable element owns the whole box — its height floor (set by the shell as a custom
+ property) and its padding — so a click anywhere in the field reaches ProseMirror and
+ places a caret. `border-box` is what keeps the padding inside that floor. */
+.variable-text-content {
+ box-sizing: border-box;
+ min-height: var(--variable-text-content-min-height, 0);
+ padding: 0.5rem 0.75rem;
+}
+
/* Tiptap's Placeholder extension only adds a class and a `data-placeholder` attribute —
the visible text is this rule. It ships with the component because the app stylesheet
that used to hold it (apps/erp/app/styles/prosemirror.css) is imported nowhere. */
diff --git a/packages/workflows/AGENTS.md b/packages/workflows/AGENTS.md
index 6799f393e4..528809d1ca 100644
--- a/packages/workflows/AGENTS.md
+++ b/packages/workflows/AGENTS.md
@@ -322,3 +322,33 @@ pnpm run check:workflow-catalog # the CI `catalog` job
Changing `Operator` in `@carbon/utils` also needs
`pnpm --filter @carbon/utils test` and `pnpm exec turbo run typecheck --filter=erp`.
+
+## Custom fields (round 2)
+
+`src/catalog/custom-fields.ts` is the per-company overlay. The catalog is build-time and
+global; custom fields are runtime and per company, so they are merged in rather than generated.
+
+- `buildCatalogOverlay(defs)` → `{ properties, labels, enums, actionInputs }`, keyed by the
+ ONE-segment property path `customFields.<fieldId>` (the field's id, which is the key inside
+ the JSONB blob). One segment keeps `walkPath` and the runtime `walk` single-step.
+- It holds the ONLY `DataType → ValueType` map. `item` and reference-only entities are excluded.
+- `createWorkflowCatalog(overlay?)` merges **generated first, overlay second** — a real column
+ always wins, and the shipped keys keep their order at the top of every picker.
+- `WorkflowCatalog` gained `getPropertyLabel(entity, property)` and
+ `getInputLabel(actionId, input)`. They return the customer's own field name, which is customer
+ data and is deliberately never translated.
+- `getCatalogEvent(id)` is the single event lookup: the committed map, then
+ `resolveCustomFieldEvent`, which PARSES `<entity>.customFields.<fieldId>.changed` into a
+ synthetic `CatalogEvent`. `WORKFLOW_EVENTS` stays closed and drift-checked. `sync.ts` uses it
+ too, which is what gives a custom-field trigger its `UPDATE` subscription.
+
+## `linkify` and `ctx.linkFor`
+
+`CatalogInput.linkify` marks an input as prose a person reads. `renderTemplate(template, ctx,
+{ linkFor })` wraps an entity part as `[readableId](url)`; `actionExecutor` passes the callback
+only for `linkify` inputs, so a webhook body still renders a bare readable id. This package
+constructs no URL — it is bundled for the browser with four runtime dependencies and cannot
+import `@carbon/env`; the engine supplies `ctx.linkFor`.
+
+`rendersAsText` now accepts a whole record (it prints as its readable id) and still refuses a
+LIST of records.
diff --git a/packages/workflows/src/catalog/actions.generated.ts b/packages/workflows/src/catalog/actions.generated.ts
index 9686fd2a6c..537a2fe112 100644
--- a/packages/workflows/src/catalog/actions.generated.ts
+++ b/packages/workflows/src/catalog/actions.generated.ts
@@ -132,6 +132,12 @@ export const WORKFLOW_ACTION_CATALOG: Record<string, BuiltAction> = {
inputs: {
user: { type: { kind: "entity", of: "user" }, required: false },
role: { type: { kind: "entity", of: "group" }, required: false },
+ channels: {
+ type: { kind: "list", of: { kind: "primitive", of: "string" } },
+ required: false,
+ choices: ["inApp", "email", "slack"],
+ defaultValue: ["inApp", "email"]
+ },
subject: {
type: { kind: "primitive", of: "string" },
required: true,
@@ -140,7 +146,8 @@ export const WORKFLOW_ACTION_CATALOG: Record<string, BuiltAction> = {
message: {
type: { kind: "primitive", of: "string" },
required: false,
- template: true
+ template: true,
+ linkify: true
},
aboutId: { type: { kind: "primitive", of: "string" }, required: false },
aboutType: { type: { kind: "primitive", of: "string" }, required: false }
diff --git a/packages/workflows/src/catalog/actions.ts b/packages/workflows/src/catalog/actions.ts
index e812ca8030..1cbbdd92d6 100644
--- a/packages/workflows/src/catalog/actions.ts
+++ b/packages/workflows/src/catalog/actions.ts
@@ -7,11 +7,14 @@ export interface ActionInputLike {
required: boolean;
label: string;
template?: boolean;
+ /** Prose a person reads: a record dropped in renders as a link. Not for webhook bodies,
+ * where a markdown link would ship to someone else's API as literal text. */
+ linkify?: boolean;
/** Allowed literal values. The generated side infers these from the database schema;
* a hand-written action is not a schema entity, so it must say so here. */
choices?: readonly string[];
/** What the builder seeds a new node with. Nothing reads it at run time. */
- defaultValue?: string;
+ defaultValue?: string | readonly string[];
/** The value is a set of name/value rows. */
pairs?: boolean;
/** Only shown, and only required, while `input` holds one of `equals`. */
@@ -142,18 +145,35 @@ export const WORKFLOW_ACTIONS = {
permission: { module: "users", action: "view" },
inputs: {
user: { type: t.entity("user"), required: false, label: "person" },
- role: { type: t.entity("group"), required: false, label: "role" },
+ // The stored key stays `role`; renaming it would need a v4 format migration for a
+ // label change, and the value is already a group id.
+ role: { type: t.entity("group"), required: false, label: "group" },
+ // In-app is always delivered whatever is stored here — the notify job adds it to
+ // every notification — so this is optional rather than required: a required field
+ // whose one guaranteed member cannot be ticked is a trap on older nodes.
+ channels: {
+ type: t.list({ kind: "primitive", of: "string" }),
+ required: false,
+ label: "notification type",
+ choices: ["inApp", "email", "slack"],
+ // What the action has always sent. An absent value means the same thing.
+ defaultValue: ["inApp", "email"],
+ help: "workflow-notify-channels"
+ },
subject: {
type: t.string,
required: true,
label: "subject",
template: true
},
+ // The body is prose someone reads, so a record dropped in becomes a link.
+ // Deliberately not the subject: an email subject renders markdown literally.
message: {
type: t.string,
required: false,
label: "message",
- template: true
+ template: true,
+ linkify: true
},
// The value model has no "any record" type, so the record is named in two parts.
aboutId: {
diff --git a/packages/workflows/src/catalog/build.test.ts b/packages/workflows/src/catalog/build.test.ts
index bca7d20a9b..4141d7a03e 100644
--- a/packages/workflows/src/catalog/build.test.ts
+++ b/packages/workflows/src/catalog/build.test.ts
@@ -1,5 +1,6 @@
import swaggerDocsSchema from "@carbon/database/swagger-docs-schema";
import { describe, expect, it } from "vitest";
+import type { ActionInputLike } from "./actions";
import { WORKFLOW_ACTIONS } from "./actions";
import type {
MomentDeclarationLike,
@@ -603,6 +604,93 @@ describe("validateCatalogInputs", () => {
expect(problems[0]).toMatch(/is a template but is not a string/);
});
+ // Malformed on purpose — the point of each case is a declaration the check must refuse.
+ const multi = (input: Record<string, unknown>) =>
+ validateCatalogInputs(
+ registry,
+ {},
+ {
+ "order.archive": {
+ label: "Archive an order",
+ permission: { module: "purchasing", action: "update" },
+ call: "purchasing_archiveOrder",
+ inputs: {
+ channels: input as unknown as ActionInputLike
+ },
+ outputs: {},
+ batchable: false
+ }
+ },
+ {},
+ schema
+ );
+
+ const LIST_OF_TEXT = {
+ kind: "list",
+ of: { kind: "primitive", of: "string" }
+ } as const;
+
+ it("accepts a well-formed multi-select", () => {
+ expect(
+ multi({
+ type: LIST_OF_TEXT,
+ required: false,
+ label: "channels",
+ choices: ["inApp", "email"],
+ defaultValue: ["inApp"]
+ })
+ ).toEqual([]);
+ });
+
+ it("rejects a fixed set of values on a list of anything but text", () => {
+ const problems = multi({
+ type: { kind: "list", of: { kind: "primitive", of: "number" } },
+ required: false,
+ label: "channels",
+ choices: ["inApp"]
+ });
+ expect(problems).toHaveLength(1);
+ expect(problems[0]).toMatch(/is not a list of text/);
+ });
+
+ it("rejects a default that is not one of a multi-select's values", () => {
+ const problems = multi({
+ type: LIST_OF_TEXT,
+ required: false,
+ label: "channels",
+ choices: ["inApp", "email"],
+ defaultValue: ["inApp", "carrier-pigeon"]
+ });
+ expect(problems).toHaveLength(1);
+ expect(problems[0]).toMatch(/"carrier-pigeon", which is not one/);
+ });
+
+ it("rejects a single default on a multi-select", () => {
+ const problems = multi({
+ type: LIST_OF_TEXT,
+ required: false,
+ label: "channels",
+ choices: ["inApp", "email"],
+ defaultValue: "inApp"
+ });
+ expect(problems).toHaveLength(1);
+ expect(problems[0]).toMatch(/defaults to one value but holds a set/);
+ });
+
+ it("rejects a set of defaults on an input that holds one value", () => {
+ const problems = multi({
+ type: { kind: "primitive", of: "string" },
+ required: false,
+ label: "channels",
+ choices: ["inApp", "email"],
+ defaultValue: ["inApp"]
+ });
+ expect(problems).toHaveLength(1);
+ expect(problems[0]).toMatch(
+ /defaults to a set of values but only holds one/
+ );
+ });
+
const gated = (
showWhen: { input: string; equals: readonly string[] },
methodChoices?: readonly string[]
@@ -680,9 +768,9 @@ describe("buildCatalog — the real hand-written inputs", () => {
expect(Object.keys(built.actions)).toHaveLength(16);
expect(Object.keys(built.operations)).toHaveLength(15);
// 106 events + 16 actions + 15 operations + 17 entity labels + 95 column labels
- // + 27 action input labels + 15 operation input labels
+ // + 28 action input labels + 15 operation input labels
// + 44 generated update-action input labels (10 record inputs + 34 writable columns)
- expect(Object.keys(built.labels)).toHaveLength(335);
+ expect(Object.keys(built.labels)).toHaveLength(336);
});
it("sets template: true on inputs marked as templates", () => {
diff --git a/packages/workflows/src/catalog/build.ts b/packages/workflows/src/catalog/build.ts
index 6b36d23144..1a36884785 100644
--- a/packages/workflows/src/catalog/build.ts
+++ b/packages/workflows/src/catalog/build.ts
@@ -1,5 +1,9 @@
import type { TermId } from "@carbon/glossary";
-import type { EventMatch, RequiredPermission } from "../definition/catalog";
+import {
+ type EventMatch,
+ isMultiSelect,
+ type RequiredPermission
+} from "../definition/catalog";
import { t, type ValueType } from "../definition/types";
import type { ActionDeclarationLike } from "./actions";
import type { OperationDeclarationLike } from "./operations";
@@ -53,6 +57,9 @@ export interface RegistryEntry {
/** Plain-English explanation per column, surfaced as a tooltip in the variable picker.
* Any column in the entity may have one; not restricted to watched or writable columns. */
describe?: Record<string, string>;
+ /** Columns that spell this record's name, best first. Read at run time by the catalog,
+ * not by the generator, so adding one needs no regeneration. */
+ display?: readonly string[];
}
export interface MomentDeclarationLike {
@@ -72,8 +79,11 @@ export interface BuiltActionInput {
required: boolean;
choices?: readonly string[];
/** What the builder seeds a new node with. Nothing reads it at run time. */
- defaultValue?: string;
+ defaultValue?: string | readonly string[];
template?: boolean;
+ /** Prose a person reads: a record dropped in renders as a link when the caller
+ * supplies a resolver. Not set on webhook bodies. */
+ linkify?: boolean;
/** Table a non-entity foreign key points at, so the update executor can scope the
* value to the company. Resolved here so a dropped fk note fails CI rather than
* silently disabling that check at run time. */
@@ -369,13 +379,38 @@ export function validateCatalogInputs(
) {
problems.push(`${id}.${input} is a template but is not a string.`);
}
+ // A fixed set of values on a list is what MAKES it a multi-select (`isMultiSelect`),
+ // so a list of anything else has no reading in the builder.
if (
- spec.defaultValue !== undefined &&
spec.choices !== undefined &&
- !spec.choices.includes(spec.defaultValue)
+ spec.type.kind === "list" &&
+ !(spec.type.of.kind === "primitive" && spec.type.of.of === "string")
) {
problems.push(
- `${id}.${input} defaults to "${spec.defaultValue}", which is not one of its values.`
+ `${id}.${input} offers a fixed set of values but is not a list of text.`
+ );
+ }
+ if (spec.defaultValue !== undefined && spec.choices !== undefined) {
+ // One default or a set of them — a multi-select seeds several at once.
+ const defaults =
+ typeof spec.defaultValue === "string"
+ ? [spec.defaultValue]
+ : spec.defaultValue;
+ for (const value of defaults) {
+ if (spec.choices.includes(value)) continue;
+ problems.push(
+ `${id}.${input} defaults to "${value}", which is not one of its values.`
+ );
+ }
+ }
+ if (Array.isArray(spec.defaultValue) && spec.type.kind !== "list") {
+ problems.push(
+ `${id}.${input} defaults to a set of values but only holds one.`
+ );
+ }
+ if (typeof spec.defaultValue === "string" && spec.type.kind === "list") {
+ problems.push(
+ `${id}.${input} defaults to one value but holds a set of them.`
);
}
const gate = spec.showWhen;
@@ -390,6 +425,11 @@ export function validateCatalogInputs(
problems.push(
`${id}.${input} is gated on "${gate.input}", which has no fixed set of values.`
);
+ } else if (isMultiSelect(target)) {
+ // The gate reads one literal string; a set has no single value to match.
+ problems.push(
+ `${id}.${input} is gated on "${gate.input}", which holds a set of values.`
+ );
} else {
for (const value of gate.equals) {
if (!target.choices.includes(value)) {
@@ -613,6 +653,7 @@ export function buildCatalog(
...(spec.choices ? { choices: spec.choices } : {}),
...(spec.defaultValue ? { defaultValue: spec.defaultValue } : {}),
...(spec.template ? { template: true } : {}),
+ ...(spec.linkify ? { linkify: true } : {}),
...(spec.pairs ? { pairs: true } : {}),
...(spec.showWhen ? { showWhen: spec.showWhen } : {})
};
diff --git a/packages/workflows/src/catalog/catalog.test.ts b/packages/workflows/src/catalog/catalog.test.ts
index 8831ef871e..494299358a 100644
--- a/packages/workflows/src/catalog/catalog.test.ts
+++ b/packages/workflows/src/catalog/catalog.test.ts
@@ -3,8 +3,10 @@ import {
type WorkflowDefinition,
workflowDefinitionSchema
} from "../definition/schema";
+import { t } from "../definition/types";
import { validateDefinition } from "../definition/validate";
import { createWorkflowCatalog, getActionRoute } from "./catalog";
+import { buildCatalogOverlay } from "./custom-fields";
const catalog = createWorkflowCatalog();
@@ -254,3 +256,84 @@ describe("validateDefinition against the real catalog", () => {
).toContain("MULTIPLE_TRIGGER_EVENTS");
});
});
+
+describe("the per-company overlay", () => {
+ const overlay = buildCatalogOverlay([
+ {
+ table: "salesOrder",
+ id: "cf_1",
+ name: "Rush Reason",
+ dataTypeId: 3,
+ listOptions: ["Low", "High"],
+ active: true
+ }
+ ]);
+
+ it("resolves a custom-field trigger through getEvent", () => {
+ const event = createWorkflowCatalog().getEvent(
+ "salesOrder.customFields.cf_1.changed"
+ );
+ expect(event?.match).toEqual({
+ table: "salesOrder",
+ operation: "UPDATE",
+ field: "customFields.cf_1"
+ });
+ });
+
+ it("adds the field to the entity's properties", () => {
+ const properties =
+ createWorkflowCatalog(overlay).getEntity("salesOrder")?.properties;
+ expect(properties?.["customFields.cf_1"]).toEqual(t.string);
+ // The shipped columns are still there.
+ expect(properties?.status).toBeDefined();
+ });
+
+ // A customer must not be able to shadow a real column.
+ it("lets a generated property win over an overlay one", () => {
+ const shadow = {
+ ...overlay,
+ properties: { salesOrder: { status: t.number } }
+ };
+ expect(
+ createWorkflowCatalog(shadow).getEntity("salesOrder")?.properties.status
+ ).toEqual(t.string);
+ });
+
+ it("returns the field's options from getEnum", () => {
+ expect(
+ createWorkflowCatalog(overlay).getEnum("salesOrder", "customFields.cf_1")
+ ).toEqual(["Low", "High"]);
+ });
+
+ it("adds the field to the entity's update action", () => {
+ const inputs =
+ createWorkflowCatalog(overlay).getAction("salesOrder.update")?.inputs;
+ expect(inputs?.["customFields.cf_1"]).toEqual({
+ type: t.string,
+ required: false,
+ choices: ["Low", "High"]
+ });
+ expect(inputs?.salesOrder).toBeDefined();
+ });
+
+ it("returns the customer's own name as the property label", () => {
+ const catalog = createWorkflowCatalog(overlay);
+ expect(catalog.getPropertyLabel("salesOrder", "customFields.cf_1")).toBe(
+ "Rush Reason"
+ );
+ expect(catalog.getPropertyLabel("salesOrder", "status")).toBeUndefined();
+ expect(
+ catalog.getInputLabel("salesOrder.update", "customFields.cf_1")
+ ).toBe("Rush Reason");
+ });
+
+ it("leaves a catalog built with no overlay untouched", () => {
+ const bare = createWorkflowCatalog();
+ expect(
+ bare.getEntity("salesOrder")?.properties["customFields.cf_1"]
+ ).toBeUndefined();
+ expect(
+ bare.getAction("salesOrder.update")?.inputs["customFields.cf_1"]
+ ).toBeUndefined();
+ });
+});
diff --git a/packages/workflows/src/catalog/catalog.ts b/packages/workflows/src/catalog/catalog.ts
index 5e87b9008a..d160def3ff 100644
--- a/packages/workflows/src/catalog/catalog.ts
+++ b/packages/workflows/src/catalog/catalog.ts
@@ -9,6 +9,11 @@ import {
WORKFLOW_ACTION_CATALOG,
WORKFLOW_OPERATION_CATALOG
} from "./actions.generated";
+import {
+ type CatalogOverlay,
+ EMPTY_OVERLAY,
+ resolveCustomFieldEvent
+} from "./custom-fields";
import { REGISTRY_ENTRIES } from "./entities";
import {
WORKFLOW_ENTITIES,
@@ -28,6 +33,7 @@ const ENTITIES: Map<string, CatalogEntity> = new Map(
if (entry?.permission !== undefined)
base.permission = { module: entry.permission, action: "view" };
if (entry?.describe !== undefined) base.descriptions = entry.describe;
+ if (entry?.display !== undefined) base.display = entry.display;
return [name, base];
})
);
@@ -50,14 +56,60 @@ const ENUMS: Map<string, Record<string, readonly string[]>> = new Map(
Object.entries(WORKFLOW_ENTITY_ENUMS)
);
-/** The one catalog every consumer reads: events, entities, actions and operations. */
-export function createWorkflowCatalog(): WorkflowCatalog {
+/**
+ * Shipped entries first, then the ones this company added — a generated key always wins,
+ * so a customer cannot shadow a real column, and the shipped ones keep their order at the
+ * top of every picker.
+ */
+function merge<T>(base: Record<string, T>, extra: Record<string, T>) {
+ const merged: Record<string, T> = { ...base };
+ for (const [key, value] of Object.entries(extra)) {
+ if (key in base) continue;
+ merged[key] = value;
+ }
+ return merged;
+}
+
+/**
+ * The single event lookup: the committed catalog first, then the parsed custom-field
+ * pattern. Every consumer goes through here, so `WORKFLOW_EVENTS` stays closed.
+ */
+export function getCatalogEvent(id: string): CatalogEvent | undefined {
+ return EVENTS.get(id) ?? resolveCustomFieldEvent(id);
+}
+
+/**
+ * The one catalog every consumer reads: events, entities, actions and operations.
+ *
+ * `overlay` carries a company's custom fields. It is merged generated-first so a real
+ * column always wins — a customer cannot shadow one.
+ */
+export function createWorkflowCatalog(
+ overlay: CatalogOverlay = EMPTY_OVERLAY
+): WorkflowCatalog {
return {
- getEvent: (id) => EVENTS.get(id),
- getEntity: (name) => ENTITIES.get(name),
- getAction: (id) => ACTIONS.get(id),
+ getEvent: getCatalogEvent,
+ getEntity: (name) => {
+ const base = ENTITIES.get(name);
+ const extra = overlay.properties[name];
+ if (base === undefined || extra === undefined) return base;
+ return { ...base, properties: merge(base.properties, extra) };
+ },
+ getAction: (id) => {
+ const base = ACTIONS.get(id);
+ const extra = overlay.actionInputs[id];
+ if (base === undefined || extra === undefined) return base;
+ return { ...base, inputs: merge(base.inputs, extra) };
+ },
getOperation: (id) => OPERATIONS.get(id),
- getEnum: (entity, property) => ENUMS.get(entity)?.[property]
+ getEnum: (entity, property) =>
+ ENUMS.get(entity)?.[property] ?? overlay.enums[entity]?.[property],
+ // Custom field names are customer data and are deliberately never translated, so
+ // they arrive as plain strings rather than through WORKFLOW_LABELS.
+ getPropertyLabel: (entity, property) =>
+ overlay.labels[`entity.${entity}.${property}`],
+ getInputLabel: (actionId, input) =>
+ overlay.labels[`action.${actionId}.input.${input}`]
};
}
diff --git a/packages/workflows/src/catalog/custom-fields.test.ts b/packages/workflows/src/catalog/custom-fields.test.ts
new file mode 100644
index 0000000000..0b3e3e0a36
--- /dev/null
+++ b/packages/workflows/src/catalog/custom-fields.test.ts
@@ -0,0 +1,157 @@
+import { describe, expect, it } from "vitest";
+import { t } from "../definition/types";
+import {
+ buildCatalogOverlay,
+ type CustomFieldDef,
+ customFieldEventId,
+ ENTITY_BY_TABLE,
+ resolveCustomFieldEvent
+} from "./custom-fields";
+
+const field = (over: Partial<CustomFieldDef> = {}): CustomFieldDef => ({
+ table: "salesOrder",
+ id: "cf_1",
+ name: "Rush Reason",
+ dataTypeId: 5,
+ listOptions: null,
+ active: true,
+ ...over
+});
+
+describe("buildCatalogOverlay", () => {
+ it("keys the property by id, one segment, under the entity name", () => {
+ const overlay = buildCatalogOverlay([field()]);
+ expect(overlay.properties.salesOrder).toEqual({
+ "customFields.cf_1": t.string
+ });
+ expect(overlay.labels["entity.salesOrder.customFields.cf_1"]).toBe(
+ "Rush Reason"
+ );
+ });
+
+ it("maps every DataType to its ValueType", () => {
+ const cases: [number, unknown][] = [
+ [1, t.boolean],
+ [2, t.date],
+ [3, t.string],
+ [4, t.number],
+ [5, t.string],
+ [6, t.entity("user")],
+ [7, t.entity("customer")],
+ [8, t.entity("supplier")],
+ // A File field is the stored path — printable, not a link.
+ [9, t.string]
+ ];
+ for (const [dataTypeId, expected] of cases) {
+ const overlay = buildCatalogOverlay([field({ dataTypeId })]);
+ expect(overlay.properties.salesOrder?.["customFields.cf_1"]).toEqual(
+ expected
+ );
+ }
+ });
+
+ it("drops an unknown DataType rather than guessing", () => {
+ expect(buildCatalogOverlay([field({ dataTypeId: 99 })]).properties).toEqual(
+ {}
+ );
+ });
+
+ it("drops an inactive field", () => {
+ expect(buildCatalogOverlay([field({ active: false })]).properties).toEqual(
+ {}
+ );
+ });
+
+ // Item custom fields live on part/material/tool/…; the catalog triggers on `item`.
+ it("drops item, which has no comparable custom fields yet", () => {
+ expect(buildCatalogOverlay([field({ table: "item" })]).properties).toEqual(
+ {}
+ );
+ });
+
+ it("drops a table that is not a registry entity", () => {
+ expect(
+ buildCatalogOverlay([field({ table: "notATable" })]).properties
+ ).toEqual({});
+ });
+
+ it("puts a List field's options in enums and on the action input", () => {
+ const overlay = buildCatalogOverlay([
+ field({ dataTypeId: 3, listOptions: ["Low", "High"] })
+ ]);
+ expect(overlay.enums.salesOrder?.["customFields.cf_1"]).toEqual([
+ "Low",
+ "High"
+ ]);
+ expect(
+ overlay.actionInputs["salesOrder.update"]?.["customFields.cf_1"]
+ ).toEqual({ type: t.string, required: false, choices: ["Low", "High"] });
+ });
+
+ it("makes a non-List field writable with no choices", () => {
+ const overlay = buildCatalogOverlay([field()]);
+ expect(
+ overlay.actionInputs["salesOrder.update"]?.["customFields.cf_1"]
+ ).toEqual({ type: t.string, required: false });
+ expect(
+ overlay.labels["action.salesOrder.update.input.customFields.cf_1"]
+ ).toBe("Rush Reason");
+ });
+
+ it("indexes every registry entity by its table", () => {
+ expect(ENTITY_BY_TABLE.salesOrder).toBe("salesOrder");
+ expect(ENTITY_BY_TABLE.nonConformance).toBe("nonConformance");
+ });
+});
+
+describe("resolveCustomFieldEvent", () => {
+ it("parses a well-formed id into a synthetic UPDATE event", () => {
+ const id = customFieldEventId("salesOrder", "cf_1");
+ expect(id).toBe("salesOrder.customFields.cf_1.changed");
+
+ const event = resolveCustomFieldEvent(id);
+ expect(event?.match).toEqual({
+ table: "salesOrder",
+ operation: "UPDATE",
+ field: "customFields.cf_1"
+ });
+ expect(event?.permission).toBe("sales");
+ expect(event?.outputs).toEqual({
+ record: t.entity("salesOrder"),
+ before: t.entity("salesOrder"),
+ after: t.entity("salesOrder")
+ });
+ });
+
+ it("refuses item", () => {
+ expect(
+ resolveCustomFieldEvent("item.customFields.cf_1.changed")
+ ).toBeUndefined();
+ });
+
+ // A reference-only entity has no `watch` block, so it has no change events at all.
+ it("refuses a reference-only entity", () => {
+ expect(
+ resolveCustomFieldEvent("user.customFields.cf_1.changed")
+ ).toBeUndefined();
+ });
+
+ it("refuses an unknown entity", () => {
+ expect(
+ resolveCustomFieldEvent("nope.customFields.cf_1.changed")
+ ).toBeUndefined();
+ });
+
+ it("refuses a generated column event and other malformed ids", () => {
+ for (const id of [
+ "salesOrder.status.changed",
+ "salesOrder.customFields.changed",
+ "salesOrder.customFields.cf_1.created",
+ "salesOrder.customFields.a.b.changed",
+ "customFields.cf_1.changed",
+ ""
+ ]) {
+ expect(resolveCustomFieldEvent(id)).toBeUndefined();
+ }
+ });
+});
diff --git a/packages/workflows/src/catalog/custom-fields.ts b/packages/workflows/src/catalog/custom-fields.ts
new file mode 100644
index 0000000000..68f40eb868
--- /dev/null
+++ b/packages/workflows/src/catalog/custom-fields.ts
@@ -0,0 +1,186 @@
+import type { CatalogEvent, CatalogInput } from "../definition/catalog";
+import { t, type ValueType } from "../definition/types";
+import { REGISTRY_ENTRIES } from "./entities";
+
+/**
+ * The property path is ONE segment — the literal string `customFields.<fieldId>` — not a
+ * two-hop drill. That keeps `walkPath` and the runtime `walk` single-step, and it matches
+ * the differ, which emits nested keys and so never produces the bare `customFields` key.
+ */
+export const CUSTOM_FIELD_PREFIX = "customFields.";
+
+/**
+ * Custom fields attach to the item SUBTYPES (`part`, `material`, `tool`, `consumable`,
+ * `fixture`) while the workflow catalog triggers on the shared `item` table. Merging them
+ * needs a collision rule and is its own change.
+ */
+const EXCLUDED_ENTITIES = new Set(["item"]);
+
+/** The shape the ERP already loads, from `customField` / the `customFieldTables` view. */
+export type CustomFieldDef = {
+ table: string;
+ /** The key inside the JSONB blob — an id, never the customer-visible name. */
+ id: string;
+ name: string;
+ dataTypeId: number;
+ listOptions: string[] | null;
+ active: boolean;
+};
+
+/**
+ * What a company adds to the shipped catalog. Merged in at the two places a catalog is
+ * built: the builder (client) and the engine (server). The catalog itself is build-time
+ * and global, so per-company fields cannot be generated into it.
+ */
+export type CatalogOverlay = {
+ /** entity -> property path -> type */
+ properties: Record<string, Record<string, ValueType>>;
+ /** label key -> the customer's own field name, verbatim and untranslated */
+ labels: Record<string, string>;
+ /** entity -> property path -> allowed values */
+ enums: Record<string, Record<string, readonly string[]>>;
+ /** action id -> input name -> spec, for the generated `<entity>.update` family */
+ actionInputs: Record<string, Record<string, CatalogInput>>;
+};
+
+export const EMPTY_OVERLAY: CatalogOverlay = {
+ properties: {},
+ labels: {},
+ enums: {},
+ actionInputs: {}
+};
+
+/** table -> registry entity name. Built once; the registry is committed data. */
+export const ENTITY_BY_TABLE: Record<string, string> = Object.fromEntries(
+ Object.entries(REGISTRY_ENTRIES).map(([name, entry]) => [entry.table, name])
+);
+
+/**
+ * The ONE place `DataType` (`apps/erp/app/modules/shared/types.ts`) maps to a `ValueType`.
+ * A File field is exposed as the stored path — comparable and printable, but not a link
+ * and not a record to drill into.
+ */
+function valueTypeFor(dataTypeId: number): ValueType | undefined {
+ switch (dataTypeId) {
+ case 1:
+ return t.boolean;
+ case 2:
+ return t.date;
+ // List: a string, whose allowed values come from `listOptions`.
+ case 3:
+ return t.string;
+ case 4:
+ return t.number;
+ case 5:
+ return t.string;
+ case 6:
+ return t.entity("user");
+ case 7:
+ return t.entity("customer");
+ case 8:
+ return t.entity("supplier");
+ // File: the stored path.
+ case 9:
+ return t.string;
+ default:
+ return undefined;
+ }
+}
+
+export function buildCatalogOverlay(defs: CustomFieldDef[]): CatalogOverlay {
+ const overlay: CatalogOverlay = {
+ properties: {},
+ labels: {},
+ enums: {},
+ actionInputs: {}
+ };
+
+ for (const def of defs) {
+ if (!def.active) continue;
+ const entity = ENTITY_BY_TABLE[def.table];
+ if (entity === undefined || EXCLUDED_ENTITIES.has(entity)) continue;
+ const type = valueTypeFor(def.dataTypeId);
+ if (type === undefined) continue;
+
+ const property = `${CUSTOM_FIELD_PREFIX}${def.id}`;
+ const choices =
+ def.dataTypeId === 3 && def.listOptions && def.listOptions.length > 0
+ ? def.listOptions
+ : undefined;
+
+ (overlay.properties[entity] ??= {})[property] = type;
+ overlay.labels[`entity.${entity}.${property}`] = def.name;
+ if (choices) (overlay.enums[entity] ??= {})[property] = choices;
+
+ // Writable through the generated update action. An entity with no `write` block
+ // has no `<entity>.update`, in which case `getAction` simply never finds a base to
+ // merge this onto.
+ const actionId = `${entity}.update`;
+ (overlay.actionInputs[actionId] ??= {})[property] = {
+ type,
+ required: false,
+ ...(choices ? { choices } : {})
+ };
+ overlay.labels[`action.${actionId}.input.${property}`] = def.name;
+ }
+
+ return overlay;
+}
+
+/** `<entity>.customFields.<fieldId>.changed`. */
+export function customFieldEventId(entity: string, fieldId: string): string {
+ return `${entity}.${CUSTOM_FIELD_PREFIX}${fieldId}.changed`;
+}
+
+const CUSTOM_FIELD_EVENT =
+ /^([A-Za-z][A-Za-z0-9]*)\.customFields\.([^.]+)\.changed$/;
+
+/** The entity and property path a custom-field trigger id names, or undefined when the id
+ * is a shipped event. The label a customer sees is keyed by that property. */
+export function parseCustomFieldEventId(
+ id: string
+): { entity: string; property: string } | undefined {
+ const match = CUSTOM_FIELD_EVENT.exec(id);
+ if (match === null) return undefined;
+
+ const [, entity, fieldId] = match;
+ if (entity === undefined || fieldId === undefined) return undefined;
+
+ return { entity, property: `${CUSTOM_FIELD_PREFIX}${fieldId}` };
+}
+
+/**
+ * Parses a custom-field event id into a synthetic `CatalogEvent`, deliberately parallel
+ * to the generated `<entity>.<column>.changed`.
+ *
+ * `WORKFLOW_EVENTS` stays a closed, committed, drift-checked record — a per-company id
+ * cannot live there — so the id is PARSED rather than looked up. Company-blind by design:
+ * whether the field actually exists for the company is decided by the
+ * `workflowTriggerEvent` join the matcher already does, not here.
+ */
+export function resolveCustomFieldEvent(id: string): CatalogEvent | undefined {
+ const parsed = parseCustomFieldEventId(id);
+ if (parsed === undefined) return undefined;
+
+ const { entity, property } = parsed;
+ if (EXCLUDED_ENTITIES.has(entity)) return undefined;
+
+ const entry = REGISTRY_ENTRIES[entity];
+ // A reference-only entity has no `watch` block and so no change events at all.
+ if (entry === undefined || entry.watch === undefined) return undefined;
+
+ return {
+ id,
+ outputs: {
+ record: t.entity(entity),
+ before: t.entity(entity),
+ after: t.entity(entity)
+ },
+ permission: entry.permission,
+ match: {
+ table: entry.table,
+ operation: "UPDATE",
+ field: property
+ }
+ };
+}
diff --git a/packages/workflows/src/catalog/entities.ts b/packages/workflows/src/catalog/entities.ts
index 5cf3faa26a..daaae2dfa1 100644
--- a/packages/workflows/src/catalog/entities.ts
+++ b/packages/workflows/src/catalog/entities.ts
@@ -5,13 +5,21 @@ import type {
WritableColumnLike
} from "./build";
-/** `watch`, `write`, and `describe` keys are bound to the entry's own table, so a renamed column fails to compile. */
+/** `watch`, `write`, `describe` and `display` keys are bound to the entry's own table, so a renamed column fails to compile. */
interface EntityEntry<T extends TableName>
- extends Omit<RegistryEntry, "table" | "watch" | "write" | "describe"> {
+ extends Omit<
+ RegistryEntry,
+ "table" | "watch" | "write" | "describe" | "display"
+ > {
table: T;
watch?: { [C in ColumnOf<T>]?: WatchedColumnLike };
write?: { [C in ColumnOf<T>]?: WritableColumnLike };
describe?: { [C in ColumnOf<T>]?: string };
+ /** Columns that spell this record's name, best first. Required, so a new entity cannot
+ * quietly render as a raw id in a customer's notification. Mirrors `fkDisplayRegistry` in
+ * `@carbon/database`, which cannot be imported here: it is a runtime value and this
+ * package is bundled for the browser. */
+ display: readonly ColumnOf<T>[];
}
/** Identity helper that infers `T` so `watch` keys get checked. */
@@ -21,6 +29,7 @@ export const WORKFLOW_ENTITY_REGISTRY = {
purchaseOrder: entity({
table: "purchaseOrder",
label: "Purchase order",
+ display: ["purchaseOrderId"],
help: "purchase-order",
permission: "purchasing",
watch: {
@@ -56,6 +65,7 @@ export const WORKFLOW_ENTITY_REGISTRY = {
salesOrder: entity({
table: "salesOrder",
label: "Sales order",
+ display: ["salesOrderId"],
help: "sales-order",
permission: "sales",
watch: {
@@ -91,6 +101,7 @@ export const WORKFLOW_ENTITY_REGISTRY = {
job: entity({
table: "job",
label: "Job",
+ display: ["jobId"],
help: "job",
permission: "production",
watch: {
@@ -124,6 +135,7 @@ export const WORKFLOW_ENTITY_REGISTRY = {
item: entity({
table: "item",
label: "Item",
+ display: ["readableId", "name"],
help: "item",
permission: "parts",
watch: {
@@ -155,6 +167,7 @@ export const WORKFLOW_ENTITY_REGISTRY = {
receipt: entity({
table: "receipt",
label: "Receipt",
+ display: ["receiptId"],
help: "receipt",
permission: "inventory",
watch: {
@@ -181,6 +194,7 @@ export const WORKFLOW_ENTITY_REGISTRY = {
shipment: entity({
table: "shipment",
label: "Shipment",
+ display: ["shipmentId"],
help: "shipment",
permission: "inventory",
watch: {
@@ -210,6 +224,7 @@ export const WORKFLOW_ENTITY_REGISTRY = {
quote: entity({
table: "quote",
label: "Quote",
+ display: ["quoteId"],
help: "quote",
permission: "sales",
watch: {
@@ -250,6 +265,7 @@ export const WORKFLOW_ENTITY_REGISTRY = {
supplier: entity({
table: "supplier",
label: "Supplier",
+ display: ["name"],
permission: "purchasing",
watch: {
supplierStatus: { label: "status" },
@@ -282,6 +298,7 @@ export const WORKFLOW_ENTITY_REGISTRY = {
customer: entity({
table: "customer",
label: "Customer",
+ display: ["name"],
permission: "sales",
watch: {
customerStatusId: { label: "status" },
@@ -314,6 +331,7 @@ export const WORKFLOW_ENTITY_REGISTRY = {
nonConformance: entity({
table: "nonConformance",
label: "Issue",
+ display: ["nonConformanceId"],
help: "nonconformance",
permission: "quality",
watch: {
@@ -352,37 +370,44 @@ export const WORKFLOW_ENTITY_REGISTRY = {
table: "user",
label: "User",
article: "A",
- permission: "users"
+ permission: "users",
+ display: ["fullName"]
}),
group: entity({
table: "group",
label: "Group",
- permission: "users"
+ permission: "users",
+ display: ["name"]
}),
jobOperation: entity({
table: "jobOperation",
label: "Job operation",
- permission: "production"
+ permission: "production",
+ display: ["description"]
}),
nonConformanceType: entity({
table: "nonConformanceType",
label: "Issue type",
- permission: "quality"
+ permission: "quality",
+ display: ["name"]
}),
salesInvoice: entity({
table: "salesInvoice",
label: "Sales invoice",
- permission: "invoicing"
+ permission: "invoicing",
+ display: ["invoiceId"]
}),
purchaseInvoice: entity({
table: "purchaseInvoice",
label: "Purchase invoice",
- permission: "invoicing"
+ permission: "invoicing",
+ display: ["invoiceId"]
}),
location: entity({
table: "location",
label: "Location",
- permission: "resources"
+ permission: "resources",
+ display: ["name"]
})
} as const;
diff --git a/packages/workflows/src/catalog/help.generated.ts b/packages/workflows/src/catalog/help.generated.ts
index 7b67fe7950..9dd345ff3e 100644
--- a/packages/workflows/src/catalog/help.generated.ts
+++ b/packages/workflows/src/catalog/help.generated.ts
@@ -22,6 +22,7 @@ export const WORKFLOW_FIELD_HELP: Record<string, TermId> = {
"action.nonConformance.update.input.nonConformanceTypeId": "issue-issue-type",
"action.notify.input.aboutId": "workflow-notify-about-record",
"action.notify.input.aboutType": "workflow-notify-about-record",
+ "action.notify.input.channels": "workflow-notify-channels",
"action.purchaseOrder.create.input.supplierReference":
"purchase-order-supplier-order-number",
"action.purchaseOrder.update.input.assignee": "assignee",
diff --git a/packages/workflows/src/catalog/index.ts b/packages/workflows/src/catalog/index.ts
index c657a67776..49af164aae 100644
--- a/packages/workflows/src/catalog/index.ts
+++ b/packages/workflows/src/catalog/index.ts
@@ -7,7 +7,21 @@ export {
WORKFLOW_ACTION_CATALOG,
WORKFLOW_OPERATION_CATALOG
} from "./actions.generated";
-export { createWorkflowCatalog, getActionRoute } from "./catalog";
+export {
+ createWorkflowCatalog,
+ getActionRoute,
+ getCatalogEvent
+} from "./catalog";
+export type { CatalogOverlay, CustomFieldDef } from "./custom-fields";
+export {
+ buildCatalogOverlay,
+ CUSTOM_FIELD_PREFIX,
+ customFieldEventId,
+ EMPTY_OVERLAY,
+ ENTITY_BY_TABLE,
+ parseCustomFieldEventId,
+ resolveCustomFieldEvent
+} from "./custom-fields";
export { REGISTRY_ENTRIES, WORKFLOW_ENTITY_REGISTRY } from "./entities";
// `labels.generated` is not re-exported: `msg` is a build-time macro, so only a
// Vite-built consumer may import it, via the `@carbon/workflows/labels` subpath.
diff --git a/packages/workflows/src/catalog/labels.generated.ts b/packages/workflows/src/catalog/labels.generated.ts
index 75fb393471..6576bcbd6e 100644
--- a/packages/workflows/src/catalog/labels.generated.ts
+++ b/packages/workflows/src/catalog/labels.generated.ts
@@ -35,8 +35,9 @@ export const WORKFLOW_LABELS: Record<string, MessageDescriptor> = {
"action.nonConformance.update.input.priority": msg`Priority`,
"action.notify.input.aboutId": msg`About`,
"action.notify.input.aboutType": msg`Kind of record`,
+ "action.notify.input.channels": msg`Notification type`,
"action.notify.input.message": msg`Message`,
- "action.notify.input.role": msg`Role`,
+ "action.notify.input.role": msg`Group`,
"action.notify.input.subject": msg`Subject`,
"action.notify.input.user": msg`Person`,
"action.purchaseOrder.create.input.orderDate": msg`Order date`,
diff --git a/packages/workflows/src/definition/catalog.ts b/packages/workflows/src/definition/catalog.ts
index 83d72caa8f..b967ccfe02 100644
--- a/packages/workflows/src/definition/catalog.ts
+++ b/packages/workflows/src/definition/catalog.ts
@@ -27,11 +27,14 @@ export interface CatalogInput {
required: boolean;
/** Allowed literal values, where the underlying column is an enum. */
choices?: readonly string[];
- /** What the builder seeds a new node with. Must be one of `choices` when both are set.
- * Stored like any other value — nothing reads it at run time. */
- defaultValue?: string;
+ /** What the builder seeds a new node with. Must be drawn from `choices` when both are
+ * set. Stored like any other value — nothing reads it at run time. */
+ defaultValue?: string | readonly string[];
/** Prose that may interleave text and variables; the builder renders a chip editor. */
template?: boolean;
+ /** This input is prose a person reads, so a record dropped into it renders as a link
+ * when the caller supplies a resolver. Webhook bodies deliberately do not set this. */
+ linkify?: boolean;
/** Table a non-entity foreign key points at, so the write can be scoped to the company. */
scopeTable?: string;
/** The column rejects null; an input resolving to nothing is skipped, not written. */
@@ -45,6 +48,23 @@ export interface CatalogInput {
showWhen?: { input: string; equals: readonly string[] };
}
+/**
+ * Whether an input holds a SET of its `choices` rather than one of them — the builder
+ * renders a multi-select and stores a list literal. Derived rather than declared: a fixed
+ * set of values on a list of text has no other reading, and a hand-set flag could only
+ * ever disagree with the type it describes.
+ */
+export function isMultiSelect<
+ T extends { type: ValueType; choices?: readonly string[] }
+>(input: T): input is T & { choices: readonly string[] } {
+ return (
+ input.choices !== undefined &&
+ input.type.kind === "list" &&
+ input.type.of.kind === "primitive" &&
+ input.type.of.of === "string"
+ );
+}
+
export interface CatalogAction {
id: string;
inputs: Record<string, CatalogInput>;
@@ -71,6 +91,8 @@ export interface CatalogEntity {
/** Plain-English per-column description, keyed by column name.
* Only present for columns the registry explicitly describes. */
descriptions?: Record<string, string>;
+ /** Columns that spell this record's name, best first — how it reads in prose. */
+ display?: readonly string[];
}
/** What the validator needs to look up, and nothing more. */
@@ -81,6 +103,10 @@ export interface WorkflowCatalog {
getEntity(name: string): CatalogEntity | undefined;
/** Allowed values for an entity's column, or undefined when it is not an enum. */
getEnum(entity: string, property: string): readonly string[] | undefined;
+ /** The customer's own name for a property, when it is a custom field. */
+ getPropertyLabel(entity: string, property: string): string | undefined;
+ /** The customer's own name for an action input, when it is a custom field. */
+ getInputLabel(actionId: string, input: string): string | undefined;
}
/** The type at the end of a property path, or undefined where it does not exist. */
@@ -120,7 +146,8 @@ const FIXTURE_ENTITIES: CatalogEntity[] = [
status: t.string,
assignee: t.entity("user")
},
- permission: { module: "purchasing", action: "view" }
+ permission: { module: "purchasing", action: "view" },
+ display: ["purchaseOrderId"]
},
{
name: "user",
@@ -192,6 +219,12 @@ const FIXTURE_ACTIONS: CatalogAction[] = [
type: t.string,
required: false,
choices: ["Buyer", "Manager", "Admin"]
+ },
+ channels: {
+ type: t.list({ kind: "primitive", of: "string" }),
+ required: false,
+ choices: ["inApp", "email", "slack"],
+ defaultValue: ["inApp"]
}
},
outputs: {},
@@ -272,6 +305,9 @@ export function createFixtureCatalog(
getEntity: (name) => entities.get(name),
getEnum: options.omitEnums
? () => undefined
- : (entity, property) => FIXTURE_ENUMS[entity]?.[property]
+ : (entity, property) => FIXTURE_ENUMS[entity]?.[property],
+ // The fixtures carry no custom fields, so nothing here has a customer-given name.
+ getPropertyLabel: () => undefined,
+ getInputLabel: () => undefined
};
}
diff --git a/packages/workflows/src/definition/nodes.ts b/packages/workflows/src/definition/nodes.ts
index dffe3302bd..d1ebe274b7 100644
--- a/packages/workflows/src/definition/nodes.ts
+++ b/packages/workflows/src/definition/nodes.ts
@@ -352,18 +352,22 @@ function checkInputs(
});
}
- if (
- declaration.choices !== undefined &&
- supplied.kind === "literal" &&
- typeof supplied.value === "string" &&
- !declaration.choices.includes(supplied.value)
- ) {
- issues.push({
- code: "INCOMPLETE_CONFIG",
- message: `"${supplied.value}" is not a valid ${name}.`,
- nodeId: node.id,
- field: `inputs.${name}`
- });
+ if (declaration.choices !== undefined && supplied.kind === "literal") {
+ // A multi-select stores a list, so every member has to be checked — a single
+ // string test would wave the whole array through unread.
+ const picked = Array.isArray(supplied.value)
+ ? supplied.value
+ : [supplied.value];
+ for (const value of picked) {
+ if (typeof value !== "string") continue;
+ if (declaration.choices.includes(value)) continue;
+ issues.push({
+ code: "INCOMPLETE_CONFIG",
+ message: `"${value}" is not a valid ${name}.`,
+ nodeId: node.id,
+ field: `inputs.${name}`
+ });
+ }
}
}
diff --git a/packages/workflows/src/definition/types.test.ts b/packages/workflows/src/definition/types.test.ts
index 2fc7e8fe83..64b3dedcb4 100644
--- a/packages/workflows/src/definition/types.test.ts
+++ b/packages/workflows/src/definition/types.test.ts
@@ -3,6 +3,7 @@ import { describe, expect, it } from "vitest";
import {
canAssign,
expectedClauseRightType,
+ rendersAsText,
t,
valueOrRefSchema,
WORKFLOW_OPERATORS
@@ -85,3 +86,30 @@ describe("pairs", () => {
).toBe(false);
});
});
+
+describe("rendersAsText", () => {
+ it("accepts every primitive", () => {
+ for (const type of [t.string, t.number, t.boolean, t.date]) {
+ expect(rendersAsText(type)).toBe(true);
+ }
+ });
+
+ // A record prints as its readable id, which is what "…for SO000123" means, and is
+ // what a notification body turns into a link.
+ it("accepts a record", () => {
+ expect(rendersAsText(t.entity("salesOrder"))).toBe(true);
+ });
+
+ it("accepts a list of primitives", () => {
+ expect(rendersAsText(t.list({ kind: "primitive", of: "string" }))).toBe(
+ true
+ );
+ });
+
+ // A run of ids in a sentence has no good reading.
+ it("refuses a list of records", () => {
+ expect(rendersAsText(t.list({ kind: "entity", of: "salesOrder" }))).toBe(
+ false
+ );
+ });
+});
diff --git a/packages/workflows/src/definition/types.ts b/packages/workflows/src/definition/types.ts
index 9c394f3366..3f15c4266b 100644
--- a/packages/workflows/src/definition/types.ts
+++ b/packages/workflows/src/definition/types.ts
@@ -75,12 +75,14 @@ export function expectedClauseRightType(
}
/**
- * Whether a value of this type has a reading inside a sentence. A record does not —
- * it would flatten to whichever column happened to look name-ish, or to its raw id.
- * The property the user meant is one hop further in.
+ * Whether a value of this type has a reading inside a sentence. A record does: it prints as
+ * the name its entity declares in `display` (`SO000123`), which is exactly what someone
+ * means by "…for SO000123" — and in a notification body it becomes the link to that record.
+ * A LIST of records does not: a run of ids in a sentence has no good reading, and the
+ * property the author meant is one hop further in. This is what lets `renderPart` assume an
+ * entity part is never a list.
*/
export function rendersAsText(type: ValueType): boolean {
- if (type.kind === "entity") return false;
return type.kind !== "list" || type.of.kind !== "entity";
}
diff --git a/packages/workflows/src/definition/validate.test.ts b/packages/workflows/src/definition/validate.test.ts
index 39a4b9f0cd..cd8c8dbe9f 100644
--- a/packages/workflows/src/definition/validate.test.ts
+++ b/packages/workflows/src/definition/validate.test.ts
@@ -475,7 +475,9 @@ describe("types", () => {
expect(codesFound).toContain("TYPE_MISMATCH");
});
- it("reports TYPE_MISMATCH for a record written into a sentence", () => {
+ // A whole record reads as its readable id, which is what "…for PO000123" means, and
+ // is what a notification body turns into a link. A LIST of records still does not.
+ it("accepts a record written into a sentence", () => {
const definition = define(
[
trigger(),
@@ -494,10 +496,7 @@ describe("types", () => {
],
[edge("e1", "trigger", "out", "a1")]
);
- const issues = validateDefinition(definition, catalog);
- expect(issues.map((i) => i.code)).toEqual(["TYPE_MISMATCH"]);
- // The part index, so the builder can redden that one token and not the field.
- expect(issues[0]?.field).toBe("title.parts.1");
+ expect(validateDefinition(definition, catalog)).toEqual([]);
});
it("accepts a property of that record in the same sentence", () => {
@@ -877,6 +876,54 @@ describe("configuration", () => {
expect(issues.filter((i) => i.code === "INCOMPLETE_CONFIG")).toEqual([]);
});
+ it("reports INCOMPLETE_CONFIG for a member of a multi-select that is not offered", () => {
+ const definition = define(
+ [
+ trigger(),
+ action("a1", {
+ action: "alertSomeone",
+ inputs: {
+ role: literal("string", "Manager"),
+ channels: {
+ kind: "literal",
+ type: { kind: "list", of: { kind: "primitive", of: "string" } },
+ value: ["inApp", "carrier-pigeon"]
+ }
+ }
+ })
+ ],
+ [edge("e1", "trigger", "out", "a1")]
+ );
+ const issues = validateDefinition(definition, catalog);
+ expect(
+ issues.filter(
+ (i) => i.code === "INCOMPLETE_CONFIG" && i.field === "inputs.channels"
+ )
+ ).toHaveLength(1);
+ });
+
+ it("accepts a multi-select whose members are all offered", () => {
+ const definition = define(
+ [
+ trigger(),
+ action("a1", {
+ action: "alertSomeone",
+ inputs: {
+ role: literal("string", "Manager"),
+ channels: {
+ kind: "literal",
+ type: { kind: "list", of: { kind: "primitive", of: "string" } },
+ value: ["inApp", "slack"]
+ }
+ }
+ })
+ ],
+ [edge("e1", "trigger", "out", "a1")]
+ );
+ const issues = validateDefinition(definition, catalog);
+ expect(issues.filter((i) => i.code === "INCOMPLETE_CONFIG")).toEqual([]);
+ });
+
it("does not check choices when the value is a ref", () => {
const definition = define(
[
@@ -1461,7 +1508,9 @@ describe("pairs and showWhen", () => {
expect(issues[0]?.field).toBe("headers.entries.0");
});
- it("refuses a whole record as a row's value", () => {
+ // A record in a header reads as its readable id, same as anywhere else in text —
+ // and a webhook body gets no `linkFor`, so it stays a bare id with no markdown.
+ it("accepts a whole record as a row's value", () => {
const issues = issuesFor({
url: literal("https://example.com"),
method: literal("GET"),
@@ -1480,9 +1529,7 @@ describe("pairs and showWhen", () => {
]
}
});
- expect(issues[0]?.code).toBe("TYPE_MISMATCH");
- expect(issues[0]?.field).toBe("headers.entries.0");
- expect(issues[0]?.message).toMatch(/into text/);
+ expect(issues).toEqual([]);
});
it("leaves an already-published webhook with only url and body alone", () => {
diff --git a/packages/workflows/src/index.ts b/packages/workflows/src/index.ts
index 9cb6c36f73..0b2b7700d0 100644
--- a/packages/workflows/src/index.ts
+++ b/packages/workflows/src/index.ts
@@ -13,7 +13,11 @@ export type {
RequiredPermission,
WorkflowCatalog
} from "./definition/catalog";
-export { createFixtureCatalog, walkPath } from "./definition/catalog";
+export {
+ createFixtureCatalog,
+ isMultiSelect,
+ walkPath
+} from "./definition/catalog";
export type { WorkflowIssue, WorkflowIssueCode } from "./definition/issues";
export { REFERENCE_ISSUE_CODES } from "./definition/issues";
export {
diff --git a/packages/workflows/src/runtime/action.test.ts b/packages/workflows/src/runtime/action.test.ts
index 9393d6c796..5ac461da28 100644
--- a/packages/workflows/src/runtime/action.test.ts
+++ b/packages/workflows/src/runtime/action.test.ts
@@ -173,3 +173,41 @@ describe("actionExecutor", () => {
});
});
});
+
+// The webhook-body guarantee: a markdown link shipped to someone else's API would be
+// literal text there, so only an input the catalog marks `linkify` may be wrapped.
+describe("actionExecutor and linkify", () => {
+ const orderRef = {
+ kind: "template" as const,
+ parts: [
+ { kind: "text" as const, text: "Check " },
+ { kind: "ref" as const, nodeId: "trigger", output: "record", path: [] }
+ ]
+ };
+
+ const withOrder = (runAction: WorkflowServices["runAction"]) =>
+ createRuntimeContext({
+ outputs: {
+ trigger: {
+ record: entityValue("purchaseOrder", "po_1", {
+ purchaseOrderId: "PO000123"
+ })
+ }
+ },
+ services: { runAction },
+ linkFor: (of: string, id: string) => `https://erp.test/${of}/${id}`
+ });
+
+ it("leaves an input without linkify plain, even with a resolver present", async () => {
+ let seen: Record<string, RuntimeValue> = {};
+ const ctx = withOrder(async (_id, inputs) => {
+ seen = inputs;
+ return { ok: true, outputs: {} };
+ });
+
+ // `createIssue.title` is a plain template input in the fixture catalog.
+ await actionExecutor.execute(node("createIssue", { title: orderRef }), ctx);
+
+ expect(seen.title).toEqual(primitiveValue("string", "Check PO000123"));
+ });
+});
diff --git a/packages/workflows/src/runtime/action.ts b/packages/workflows/src/runtime/action.ts
index 6de1c2d8a0..f4c93696c7 100644
--- a/packages/workflows/src/runtime/action.ts
+++ b/packages/workflows/src/runtime/action.ts
@@ -3,7 +3,7 @@ import {
FAILURE_HANDLE,
SUCCESS_HANDLE
} from "../definition/schema";
-import { resolveValue } from "./resolve";
+import { renderTemplate, resolveValue } from "./resolve";
import type { NodeExecutor, RuntimeValue } from "./types";
const GONE = "This step is no longer available.";
@@ -20,7 +20,12 @@ export const actionExecutor: NodeExecutor<ActionNode> = {
const inputs: Record<string, RuntimeValue> = {};
for (const [name, value] of Object.entries(node.data.inputs)) {
- const resolved = await resolveValue(value, ctx);
+ // Only a catalog-declared prose input linkifies, and only when the engine
+ // supplied a resolver — a webhook body must stay plain text.
+ const resolved =
+ action.inputs[name]?.linkify === true && value.kind === "template"
+ ? await renderTemplate(value, ctx, { linkFor: ctx.linkFor })
+ : await resolveValue(value, ctx);
if (!resolved.ok) return { status: "Skipped", reason: resolved.reason };
// In a batch the one list input stands for the item this turn is on.
inputs[name] =
diff --git a/packages/workflows/src/runtime/fixtures.ts b/packages/workflows/src/runtime/fixtures.ts
index e88d817726..8f2f46b3af 100644
--- a/packages/workflows/src/runtime/fixtures.ts
+++ b/packages/workflows/src/runtime/fixtures.ts
@@ -32,6 +32,8 @@ export function createRuntimeContext(
outputs?: Record<string, Record<string, RuntimeValue>>;
item?: RuntimeValue;
services?: Partial<WorkflowServices>;
+ /** Supplied by the engine in production; omit to render records as plain ids. */
+ linkFor?: (of: string, id: string) => string | null;
} = {}
): RuntimeContext {
return {
@@ -39,6 +41,7 @@ export function createRuntimeContext(
loader: createFakeLoader(options.rows ?? {}),
services: createFixtureServices(options.services),
outputs: options.outputs ?? {},
- item: options.item
+ item: options.item,
+ linkFor: options.linkFor
};
}
diff --git a/packages/workflows/src/runtime/resolve.ts b/packages/workflows/src/runtime/resolve.ts
index cc325518df..36d8093afa 100644
--- a/packages/workflows/src/runtime/resolve.ts
+++ b/packages/workflows/src/runtime/resolve.ts
@@ -25,25 +25,80 @@ export async function resolveValue(
return resolveRef(value, ctx);
}
+/** All a SYNCHRONOUS reading of a record can offer: no catalog to ask which column names it,
+ * no loader to fetch one. `entityText` is what names a record properly. */
+const INLINE_ENTITY_COLUMNS = ["readableId", "name"];
+
+/** The first of `columns` this row holds a non-blank value for. */
+function pickDisplay(
+ row: Record<string, unknown> | null | undefined,
+ columns: readonly string[]
+): string | undefined {
+ if (row === null || row === undefined) return undefined;
+ for (const column of columns) {
+ const raw = row[column];
+ if (raw === null || raw === undefined) continue;
+ const text = String(raw).trim();
+ if (text !== "") return text;
+ }
+ return undefined;
+}
+
/** How one resolved value reads inside a sentence. */
export function renderValue(value: RuntimeValue): string {
if (isNull(value)) return "";
if (value.kind === "list") return value.items.map(renderValue).join(", ");
- if (value.kind === "entity") {
- const readable = value.row?.readableId ?? value.row?.name;
- return readable === undefined || readable === null
- ? value.id
- : String(readable);
- }
+ if (value.kind === "entity")
+ return pickDisplay(value.row, INLINE_ENTITY_COLUMNS) ?? value.id;
// Rows have no reading as a sentence; nothing writes one into text.
if (value.kind === "pairs") return "";
return value.value === null ? "" : String(value.value);
}
+/** How a record READS: the name a person would recognise it by — `SO000123`, not `so_x8f2`.
+ * The row is fetched when the value carries no snapshot, which is most of them: a moment
+ * output, a created record and a foreign key all arrive as a bare id. Reads go through the
+ * loader, so they are the owner's and cached for the run; an unreadable one falls back to
+ * the id rather than failing a message over a label. */
+async function entityText(
+ value: Extract<RuntimeValue, { kind: "entity" }>,
+ ctx: RuntimeContext
+): Promise<string> {
+ const columns = ctx.catalog.getEntity(value.of)?.display ?? [];
+ return (
+ pickDisplay(value.row, columns) ??
+ pickDisplay(await ctx.loader.load(value.of, value.id), columns) ??
+ value.id
+ );
+}
+
+/**
+ * A record in prose reads as its name, and becomes a markdown link when the caller knows
+ * where it lives. Every other value renders exactly as `renderValue` does — a LIST of
+ * records never reaches here, because `rendersAsText` refuses one as a template part.
+ */
+async function renderPart(
+ value: RuntimeValue,
+ ctx: RuntimeContext,
+ linkFor?: (of: string, id: string) => string | null
+): Promise<string> {
+ if (value.kind !== "entity") return renderValue(value);
+ const text = await entityText(value, ctx);
+ if (linkFor === undefined || text === "") return text;
+ const href = linkFor(value.of, value.id);
+ if (href === null) return text;
+ // The link matcher's label cannot hold a `]` and honours no backslash escape, so a record
+ // named `PO](…)` would end the label early and pick the destination itself. Drop the
+ // brackets; a name that is nothing but brackets stays unlinked.
+ const label = text.replace(/[[\]]/g, "").trim();
+ return label === "" ? text : `[${label}](${href})`;
+}
+
/** An unresolvable part fails the whole template; a blank would be a silent lie. */
export async function renderTemplate(
template: Template,
- ctx: RuntimeContext
+ ctx: RuntimeContext,
+ options?: { linkFor?: (of: string, id: string) => string | null }
): Promise<Resolution> {
const pieces: string[] = [];
for (const part of template.parts) {
@@ -56,7 +111,7 @@ export async function renderTemplate(
? await resolveItem(part, ctx)
: await resolveRef(part, ctx);
if (!resolved.ok) return resolved;
- pieces.push(renderValue(resolved.value));
+ pieces.push(await renderPart(resolved.value, ctx, options?.linkFor));
}
return { ok: true, value: primitiveValue("string", pieces.join("")) };
}
diff --git a/packages/workflows/src/runtime/template.test.ts b/packages/workflows/src/runtime/template.test.ts
index 42bbd7d199..e3249a786c 100644
--- a/packages/workflows/src/runtime/template.test.ts
+++ b/packages/workflows/src/runtime/template.test.ts
@@ -61,7 +61,9 @@ describe("renderTemplate", () => {
const ctx = createRuntimeContext({
outputs: {
n1: {
- order: entityValue("purchaseOrder", "po1", { readableId: "PO-1042" })
+ order: entityValue("purchaseOrder", "po1", {
+ purchaseOrderId: "PO-1042"
+ })
}
}
});
@@ -85,6 +87,39 @@ describe("renderTemplate", () => {
});
});
+ // A moment output, a created record and a foreign key all arrive as a bare id.
+ it("loads a record that carries no row to name it", async () => {
+ const ctx = createRuntimeContext({
+ rows: { "purchaseOrder:po1": { purchaseOrderId: "PO000123" } },
+ outputs: { n1: { order: entityValue("purchaseOrder", "po1") } }
+ });
+ const result = await renderTemplate(template(ref("order")), ctx);
+
+ expect(result).toEqual({
+ ok: true,
+ value: primitiveValue("string", "PO000123")
+ });
+ });
+
+ it("names a record by its declared display column, not another readable one", async () => {
+ const ctx = createRuntimeContext({
+ outputs: {
+ n1: {
+ order: entityValue("purchaseOrder", "po1", {
+ purchaseOrderId: "PO000123",
+ name: "Widgets restock"
+ })
+ }
+ }
+ });
+ const result = await renderTemplate(template(ref("order")), ctx);
+
+ expect(result).toEqual({
+ ok: true,
+ value: primitiveValue("string", "PO000123")
+ });
+ });
+
it("fails the whole template when a part cannot be resolved", async () => {
const ctx = createRuntimeContext();
const result = await renderTemplate(
@@ -98,3 +133,106 @@ describe("renderTemplate", () => {
});
});
});
+
+describe("renderTemplate with a link resolver", () => {
+ const order = () =>
+ entityValue("purchaseOrder", "po_1", { purchaseOrderId: "PO000123" });
+
+ it("leaves a record as its readable id when no resolver is supplied", async () => {
+ const ctx = createRuntimeContext({
+ outputs: { n1: { record: order() } }
+ });
+ const result = await renderTemplate(
+ template(text("Check "), ref("record")),
+ ctx
+ );
+
+ expect(result).toEqual({
+ ok: true,
+ value: primitiveValue("string", "Check PO000123")
+ });
+ });
+
+ it("wraps a record in a markdown link when one is supplied", async () => {
+ const ctx = createRuntimeContext({
+ outputs: { n1: { record: order() } }
+ });
+ const result = await renderTemplate(
+ template(text("Check "), ref("record")),
+ ctx,
+ { linkFor: (of, id) => `https://erp.test/link?of=${of}&id=${id}` }
+ );
+
+ expect(result).toEqual({
+ ok: true,
+ value: primitiveValue(
+ "string",
+ "Check [PO000123](https://erp.test/link?of=purchaseOrder&id=po_1)"
+ )
+ });
+ });
+
+ // A record name is customer data: it must not be able to choose where the link points.
+ it("cannot break out of the link label", async () => {
+ const ctx = createRuntimeContext({
+ outputs: {
+ n1: {
+ record: entityValue("purchaseOrder", "po_1", {
+ purchaseOrderId: "PO](https://erp.test/x/admin)"
+ })
+ }
+ }
+ });
+ const result = await renderTemplate(template(ref("record")), ctx, {
+ linkFor: () => "https://erp.test/link"
+ });
+
+ expect(result).toEqual({
+ ok: true,
+ value: primitiveValue(
+ "string",
+ "[PO(https://erp.test/x/admin)](https://erp.test/link)"
+ )
+ });
+ });
+
+ // An entity with no page in the app: the id still reads, it just is not clickable.
+ it("falls back to the plain id when the resolver returns null", async () => {
+ const ctx = createRuntimeContext({
+ outputs: { n1: { record: order() } }
+ });
+ const result = await renderTemplate(template(ref("record")), ctx, {
+ linkFor: () => null
+ });
+
+ expect(result).toEqual({
+ ok: true,
+ value: primitiveValue("string", "PO000123")
+ });
+ });
+
+ it("never wraps a non-record part", async () => {
+ const ctx = createRuntimeContext({
+ outputs: { n1: { total: primitiveValue("number", 42) } }
+ });
+ const result = await renderTemplate(template(ref("total")), ctx, {
+ linkFor: () => "https://erp.test/x"
+ });
+
+ expect(result).toEqual({
+ ok: true,
+ value: primitiveValue("string", "42")
+ });
+ });
+
+ it("never wraps a null value", async () => {
+ const ctx = createRuntimeContext({
+ outputs: { n1: { record: nullValue() } }
+ });
+ const result = await renderTemplate(template(ref("record")), ctx, {
+ linkFor: () => "https://erp.test/x"
+ });
+
+ expect(result).toEqual({ ok: true, value: primitiveValue("string", "") });
+ });
+});
diff --git a/packages/workflows/src/runtime/types.ts b/packages/workflows/src/runtime/types.ts
index 54c1b82eb8..955846beba 100644
--- a/packages/workflows/src/runtime/types.ts
+++ b/packages/workflows/src/runtime/types.ts
@@ -83,6 +83,10 @@ export interface RuntimeContext {
/** Called as each input resolves, so a step can report the values it used even
* when the work it hands them to throws. The engine supplies it; tests may omit it. */
record?: (key: string, value: RuntimeValue) => void;
+ /** Turns a record into an absolute URL, for the inputs the catalog marks `linkify`.
+ * Supplied by the engine, which may read ERP_URL — this package never builds a URL,
+ * because it is bundled for the browser and has four runtime dependencies. */
+ linkFor?: (of: string, id: string) => string | null;
}
/** What a single clause resolved to. `null` values mean it could not be read. */
diff --git a/packages/workflows/src/sync.test.ts b/packages/workflows/src/sync.test.ts
index ae78906cb4..8604a58705 100644
--- a/packages/workflows/src/sync.test.ts
+++ b/packages/workflows/src/sync.test.ts
@@ -138,3 +138,26 @@ describe("deriveWorkflowSubscriptions", () => {
expect(deriveWorkflowSubscriptions(["not.a.real.event"])).toEqual([]);
});
});
+
+describe("deriveWorkflowSubscriptions with custom-field triggers", () => {
+ it("subscribes to UPDATE on the field's own table", () => {
+ expect(
+ deriveWorkflowSubscriptions(["salesOrder.customFields.cf_1.changed"])
+ ).toEqual([{ table: "salesOrder", operations: ["UPDATE"] }]);
+ });
+
+ it("folds a custom field in with a watched column on the same table", () => {
+ expect(
+ deriveWorkflowSubscriptions([
+ "salesOrder.created",
+ "salesOrder.customFields.cf_1.changed"
+ ])
+ ).toEqual([{ table: "salesOrder", operations: ["INSERT", "UPDATE"] }]);
+ });
+
+ it("ignores an id no catalog entry resolves", () => {
+ expect(
+ deriveWorkflowSubscriptions(["item.customFields.cf_1.changed"])
+ ).toEqual([]);
+ });
+});
diff --git a/packages/workflows/src/sync.ts b/packages/workflows/src/sync.ts
index 63870747a9..fe2f94b115 100644
--- a/packages/workflows/src/sync.ts
+++ b/packages/workflows/src/sync.ts
@@ -1,7 +1,7 @@
import type { KyselyDatabase } from "@carbon/database/client";
import type { Kysely, Transaction } from "kysely";
import { z } from "zod";
-import { WORKFLOW_EVENTS } from "./catalog";
+import { getCatalogEvent } from "./catalog";
import { nextRunAfter } from "./definition/schedule";
import { nodeSchema, type Origin } from "./definition/schema";
import type { Schedule } from "./definition/types";
@@ -56,7 +56,9 @@ export function deriveWorkflowSubscriptions(
): DesiredSubscription[] {
const byTable = new Map<string, Set<"INSERT" | "UPDATE" | "DELETE">>();
for (const eventId of eventIds) {
- const match = WORKFLOW_EVENTS[eventId]?.match;
+ // Resolved, not indexed: a custom-field trigger's id is per company and is parsed
+ // rather than looked up, and it still needs an UPDATE subscription on its table.
+ const match = getCatalogEvent(eventId)?.match;
if (!match || !("table" in match)) continue;
const ops = byTable.get(match.table) ?? new Set();
ops.add(match.operation);
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 6d3422e9b5..348b588439 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -703,7 +703,7 @@ importers:
'@react-router/remix-routes-option-adapter':
specifier: 'catalog:'
'@react-router/serve':
specifier: 'catalog:'
@@ -748,7 +748,7 @@ importers:
'@vercel/react-router':
specifier: 'catalog:'
'@visx/responsive':
specifier: 2.17.0
version: 2.17.0([email protected])
@@ -983,16 +983,16 @@ importers:
'@lingui/vite-plugin':
specifier: 'catalog:'
'@react-router/dev':
specifier: 'catalog:'
'@tailwindcss/typography':
specifier: 'catalog:'
version: 0.5.19([email protected])
'@tailwindcss/vite':
specifier: 'catalog:'
'@types/d3':
specifier: 7.4.3
version: 7.4.3
@@ -1052,13 +1052,13 @@ importers:
version: 5.8.3
vite:
specifier: 'catalog:'
vite-plugin-babel-macros:
specifier: 'catalog:'
vitest:
specifier: 'catalog:'
apps/mes:
dependencies:
@@ -2089,6 +2089,9 @@ importers:
'@carbon/env':
specifier: workspace:*
version: link:../env
+ '@carbon/notifications':
+ specifier: workspace:*
+ version: link:../notifications
'@carbon/react':
specifier: workspace:*
version: link:../react
@@ -2726,7 +2729,7 @@ importers:
version: 5.8.3
vitest:
specifier: 'catalog:'
packages/locale:
dependencies:
@@ -2807,6 +2810,9 @@ importers:
typescript:
specifier: 'catalog:'
version: 5.8.3
+ vitest:
+ specifier: 'catalog:'
packages/onboarding:
dependencies:
@@ -17157,7 +17163,7 @@ snapshots:
'@babel/traverse': 7.29.0
'@babel/types': 7.29.0
convert-source-map: 2.0.0
- debug: 4.4.3([email protected])
+ debug: 4.4.3([email protected])
gensync: 1.0.0-beta.2
json5: 2.2.3
semver: 7.7.4
@@ -17177,7 +17183,7 @@ snapshots:
'@babel/types': 7.29.0
'@jridgewell/remapping': 2.3.5
convert-source-map: 2.0.0
- debug: 4.4.3([email protected])
+ debug: 4.4.3([email protected])
gensync: 1.0.0-beta.2
json5: 2.2.3
semver: 7.7.4
@@ -17347,7 +17353,7 @@ snapshots:
'@babel/parser': 7.29.2
'@babel/template': 7.28.6
'@babel/types': 7.29.0
- debug: 4.4.3([email protected])
+ debug: 4.4.3([email protected])
globals: 11.12.0
transitivePeerDependencies:
- supports-color
@@ -17360,7 +17366,7 @@ snapshots:
'@babel/parser': 7.29.2
'@babel/template': 7.28.6
'@babel/types': 7.29.0
- debug: 4.4.3([email protected])
+ debug: 4.4.3([email protected])
transitivePeerDependencies:
- supports-color
@@ -18433,6 +18439,16 @@ snapshots:
transitivePeerDependencies:
- typescript
+ dependencies:
+ '@lingui/cli': 5.9.4([email protected])([email protected])
+ '@lingui/conf': 5.9.4([email protected])
+ transitivePeerDependencies:
+ - babel-plugin-macros
+ - supports-color
+ - typescript
+
dependencies:
'@lingui/cli': 5.9.4([email protected])([email protected])
@@ -18794,7 +18810,7 @@ snapshots:
dependencies:
'@oclif/core': 4.11.7
ansis: 3.17.0
- debug: 4.4.3([email protected])
+ debug: 4.4.3([email protected])
npm: 11.17.0
npm-package-arg: 11.0.3
npm-run-path: 5.3.0
@@ -22161,6 +22177,56 @@ snapshots:
- tsx
- yaml
+ dependencies:
+ '@babel/core': 7.29.0
+ '@babel/generator': 7.29.1
+ '@babel/parser': 7.29.2
+ '@babel/plugin-syntax-jsx': 7.28.6(@babel/[email protected])
+ '@babel/preset-typescript': 7.28.5(@babel/[email protected])
+ '@babel/traverse': 7.29.0
+ '@babel/types': 7.29.0
+ '@remix-run/node-fetch-server': 0.13.1
+ arg: 5.0.2
+ babel-dead-code-elimination: 1.0.12
+ chokidar: 4.0.3
+ dedent: 1.7.2([email protected])
+ es-module-lexer: 1.7.0
+ exit-hook: 2.2.1
+ isbot: 5.1.37
+ jsesc: 3.0.2
+ lodash: 4.17.21
+ p-map: 7.0.4
+ pathe: 1.1.2
+ picocolors: 1.1.1
+ pkg-types: 2.3.0
+ prettier: 3.8.1
+ react-refresh: 0.14.2
+ semver: 7.7.4
+ tinyglobby: 0.2.17
+ valibot: 1.3.1([email protected])
+ optionalDependencies:
+ typescript: 5.8.3
+ transitivePeerDependencies:
+ - '@types/node'
+ - babel-plugin-macros
+ - jiti
+ - less
+ - lightningcss
+ - sass
+ - sass-embedded
+ - stylus
+ - sugarss
+ - supports-color
+ - terser
+ - tsx
+ - yaml
+
dependencies:
'@babel/core': 7.29.0
@@ -22239,6 +22305,12 @@ snapshots:
optionalDependencies:
typescript: 5.8.3
+ dependencies:
+ optionalDependencies:
+ typescript: 5.8.3
+
dependencies:
@@ -23520,6 +23592,13 @@ snapshots:
postcss-selector-parser: 6.0.10
tailwindcss: 4.3.0
+ dependencies:
+ '@tailwindcss/node': 4.3.0
+ '@tailwindcss/oxide': 4.3.0
+ tailwindcss: 4.3.0
+
dependencies:
'@tailwindcss/node': 4.3.0
@@ -24387,6 +24466,16 @@ snapshots:
'@vercel/[email protected]': {}
+ dependencies:
+ '@vercel/static-config': 3.2.0
+ isbot: 5.1.37
+ react: 18.3.1
+ react-dom: 18.3.1([email protected])
+ ts-morph: 12.0.0
+
dependencies:
@@ -24501,14 +24590,6 @@ snapshots:
optionalDependencies:
- dependencies:
- '@vitest/spy': 4.1.6
- estree-walker: 3.0.3
- magic-string: 0.30.21
- optionalDependencies:
-
dependencies:
'@vitest/spy': 4.1.6
@@ -24533,6 +24614,14 @@ snapshots:
optionalDependencies:
+ dependencies:
+ '@vitest/spy': 4.1.6
+ estree-walker: 3.0.3
+ magic-string: 0.30.21
+ optionalDependencies:
+
dependencies:
'@vitest/spy': 4.1.6
@@ -25002,7 +25091,7 @@ snapshots:
dependencies:
bytes: 3.1.2
content-type: 1.0.5
- debug: 4.4.3([email protected])
+ debug: 4.4.3([email protected])
http-errors: 2.0.1
iconv-lite: 0.7.2
on-finished: 2.4.1
@@ -25883,7 +25972,7 @@ snapshots:
dependencies:
'@socket.io/component-emitter': 3.1.2
- debug: 4.4.3([email protected])
+ debug: 4.4.3([email protected])
engine.io-parser: 5.2.3
ws: 8.21.0
xmlhttprequest-ssl: 2.1.2
@@ -25903,7 +25992,7 @@ snapshots:
base64id: 2.0.0
cookie: 0.7.2
cors: 2.8.6
- debug: 4.4.3([email protected])
+ debug: 4.4.3([email protected])
engine.io-parser: 5.2.3
ws: 8.21.0
transitivePeerDependencies:
@@ -26318,7 +26407,7 @@ snapshots:
content-type: 1.0.5
cookie: 0.7.2
cookie-signature: 1.2.2
- debug: 4.4.3([email protected])
+ debug: 4.4.3([email protected])
depd: 2.0.0
encodeurl: 2.0.0
escape-html: 1.0.3
@@ -26447,7 +26536,7 @@ snapshots:
dependencies:
- debug: 4.4.3([email protected])
+ debug: 4.4.3([email protected])
encodeurl: 2.0.0
escape-html: 1.0.3
on-finished: 2.4.1
@@ -27013,14 +27102,14 @@ snapshots:
dependencies:
agent-base: 7.1.4
- debug: 4.4.3([email protected])
+ debug: 4.4.3([email protected])
transitivePeerDependencies:
- supports-color
dependencies:
agent-base: 9.0.0
- debug: 4.4.3([email protected])
+ debug: 4.4.3([email protected])
transitivePeerDependencies:
- supports-color
@@ -27133,7 +27222,7 @@ snapshots:
canonicalize: 1.0.8
chalk: 4.1.2
cross-fetch: 4.1.0([email protected])
- debug: 4.4.3([email protected])
+ debug: 4.4.3([email protected])
hash.js: 1.1.7
json-stringify-safe: 5.0.1
ms: 2.1.3
@@ -27171,7 +27260,7 @@ snapshots:
canonicalize: 1.0.8
chalk: 4.1.2
cross-fetch: 4.1.0([email protected])
- debug: 4.4.3([email protected])
+ debug: 4.4.3([email protected])
hash.js: 1.1.7
json-stringify-safe: 5.0.1
ms: 2.1.3
@@ -27233,7 +27322,7 @@ snapshots:
dependencies:
'@ioredis/commands': 1.5.1
cluster-key-slot: 1.1.2
- debug: 4.4.3([email protected])
+ debug: 4.4.3([email protected])
denque: 2.1.0
lodash.defaults: 4.2.0
lodash.isarguments: 3.1.0
@@ -28359,7 +28448,7 @@ snapshots:
dependencies:
'@types/debug': 4.1.13
- debug: 4.4.3([email protected])
+ debug: 4.4.3([email protected])
decode-named-character-reference: 1.3.0
devlop: 1.1.0
micromark-core-commonmark: 2.0.3
@@ -29943,7 +30032,7 @@ snapshots:
dependencies:
- debug: 4.4.3([email protected])
+ debug: 4.4.3([email protected])
module-details-from-path: 1.0.4
resolve: 1.22.11
transitivePeerDependencies:
@@ -29951,7 +30040,7 @@ snapshots:
dependencies:
- debug: 4.4.3([email protected])
+ debug: 4.4.3([email protected])
module-details-from-path: 1.0.4
transitivePeerDependencies:
- supports-color
@@ -30068,7 +30157,7 @@ snapshots:
dependencies:
- debug: 4.4.3([email protected])
+ debug: 4.4.3([email protected])
depd: 2.0.0
is-promise: 4.0.0
parseurl: 1.3.3
@@ -30176,7 +30265,7 @@ snapshots:
dependencies:
- debug: 4.4.3([email protected])
+ debug: 4.4.3([email protected])
encodeurl: 2.0.0
escape-html: 1.0.3
etag: 1.8.1
@@ -30383,7 +30472,7 @@ snapshots:
dependencies:
- debug: 4.4.3([email protected])
+ debug: 4.4.3([email protected])
ws: 8.21.0
transitivePeerDependencies:
- bufferutil
@@ -30404,7 +30493,7 @@ snapshots:
dependencies:
'@socket.io/component-emitter': 3.1.2
- debug: 4.4.3([email protected])
+ debug: 4.4.3([email protected])
transitivePeerDependencies:
- supports-color
@@ -30413,7 +30502,7 @@ snapshots:
accepts: 1.3.8
base64id: 2.0.0
cors: 2.8.6
- debug: 4.4.3([email protected])
+ debug: 4.4.3([email protected])
engine.io: 6.6.9
socket.io-adapter: 2.5.8
socket.io-parser: 4.2.6
@@ -30876,7 +30965,7 @@ snapshots:
dependencies:
callsites: 3.1.0
- debug: 4.4.3([email protected])
+ debug: 4.4.3([email protected])
is-observable: 2.1.0
observable-fns: 0.6.1
optionalDependencies:
@@ -31022,7 +31111,7 @@ snapshots:
cac: 6.7.14
chokidar: 4.0.3
consola: 3.4.2
- debug: 4.4.3([email protected])
+ debug: 4.4.3([email protected])
esbuild: 0.27.7
fix-dts-default-cjs-exports: 1.0.1
joycon: 3.1.1
@@ -31050,7 +31139,7 @@ snapshots:
cac: 6.7.14
chokidar: 4.0.3
consola: 3.4.2
- debug: 4.4.3([email protected])
+ debug: 4.4.3([email protected])
esbuild: 0.27.7
fix-dts-default-cjs-exports: 1.0.1
joycon: 3.1.1
@@ -31352,7 +31441,7 @@ snapshots:
dependencies:
cac: 6.7.14
- debug: 4.4.3([email protected])
+ debug: 4.4.3([email protected])
es-module-lexer: 1.7.0
pathe: 2.0.3
@@ -31373,7 +31462,7 @@ snapshots:
dependencies:
cac: 6.7.14
- debug: 4.4.3([email protected])
+ debug: 4.4.3([email protected])
es-module-lexer: 1.7.0
pathe: 2.0.3
@@ -31402,6 +31491,17 @@ snapshots:
transitivePeerDependencies:
- supports-color
+ dependencies:
+ '@babel/core': 7.29.0
+ '@babel/plugin-syntax-jsx': 7.28.6(@babel/[email protected])
+ '@babel/plugin-syntax-typescript': 7.28.6(@babel/[email protected])
+ '@types/babel__core': 7.20.5
+ babel-plugin-macros: 3.1.0
+ transitivePeerDependencies:
+ - supports-color
+
dependencies:
'@babel/core': 7.29.0
@@ -31464,7 +31564,7 @@ snapshots:
tsx: 4.21.0
yaml: 2.8.3
dependencies:
lightningcss: 1.32.0
picomatch: 4.0.4
@@ -31473,14 +31573,14 @@ snapshots:
tinyglobby: 0.2.17
optionalDependencies:
'@types/node': 20.19.39
- esbuild: 0.27.7
+ esbuild: 0.28.0
fsevents: 2.3.3
jiti: 2.7.0
terser: 5.48.0
tsx: 4.21.0
yaml: 2.8.3
dependencies:
lightningcss: 1.32.0
picomatch: 4.0.4
@@ -31488,7 +31588,7 @@ snapshots:
rolldown: 1.0.0-rc.17
tinyglobby: 0.2.17
optionalDependencies:
- '@types/node': 20.19.39
+ '@types/node': 22.19.7
esbuild: 0.28.0
fsevents: 2.3.3
jiti: 2.7.0
@@ -31496,7 +31596,7 @@ snapshots:
tsx: 4.21.0
yaml: 2.8.3
dependencies:
lightningcss: 1.32.0
picomatch: 4.0.4
@@ -31504,7 +31604,7 @@ snapshots:
rolldown: 1.0.0-rc.17
tinyglobby: 0.2.17
optionalDependencies:
- '@types/node': 22.19.7
+ '@types/node': 24.12.2
esbuild: 0.28.0
fsevents: 2.3.3
jiti: 2.7.0
@@ -31512,7 +31612,7 @@ snapshots:
tsx: 4.21.0
yaml: 2.8.3
dependencies:
lightningcss: 1.32.0
picomatch: 4.0.4
@@ -31520,8 +31620,8 @@ snapshots:
rolldown: 1.0.0-rc.17
tinyglobby: 0.2.17
optionalDependencies:
- '@types/node': 24.12.2
- esbuild: 0.28.0
+ '@types/node': 26.1.0
+ esbuild: 0.27.7
fsevents: 2.3.3
jiti: 2.7.0
terser: 5.48.0
@@ -31588,10 +31688,10 @@ snapshots:
transitivePeerDependencies:
- msw
dependencies:
'@vitest/expect': 4.1.6
'@vitest/pretty-format': 4.1.6
'@vitest/runner': 4.1.6
'@vitest/snapshot': 4.1.6
@@ -31608,7 +31708,7 @@ snapshots:
tinyexec: 1.2.4
tinyglobby: 0.2.17
tinyrainbow: 3.1.0
why-is-node-running: 2.3.0
optionalDependencies:
'@opentelemetry/api': 1.9.0
@@ -31616,10 +31716,10 @@ snapshots:
transitivePeerDependencies:
- msw
dependencies:
'@vitest/expect': 4.1.6
'@vitest/pretty-format': 4.1.6
'@vitest/runner': 4.1.6
'@vitest/snapshot': 4.1.6
@@ -31636,18 +31736,18 @@ snapshots:
tinyexec: 1.2.4
tinyglobby: 0.2.17
tinyrainbow: 3.1.0
why-is-node-running: 2.3.0
optionalDependencies:
'@opentelemetry/api': 1.9.0
- '@types/node': 20.19.39
+ '@types/node': 22.19.7
transitivePeerDependencies:
- msw
dependencies:
'@vitest/expect': 4.1.6
'@vitest/pretty-format': 4.1.6
'@vitest/runner': 4.1.6
'@vitest/snapshot': 4.1.6
@@ -31664,18 +31764,18 @@ snapshots:
tinyexec: 1.2.4
tinyglobby: 0.2.17
tinyrainbow: 3.1.0
why-is-node-running: 2.3.0
optionalDependencies:
'@opentelemetry/api': 1.9.0
- '@types/node': 22.19.7
+ '@types/node': 24.12.2
transitivePeerDependencies:
- msw
dependencies:
'@vitest/expect': 4.1.6
'@vitest/pretty-format': 4.1.6
'@vitest/runner': 4.1.6
'@vitest/snapshot': 4.1.6
@@ -31692,11 +31792,11 @@ snapshots:
tinyexec: 1.2.4
tinyglobby: 0.2.17
tinyrainbow: 3.1.0
why-is-node-running: 2.3.0
optionalDependencies:
'@opentelemetry/api': 1.9.0
- '@types/node': 24.12.2
+ '@types/node': 26.1.0
transitivePeerDependencies:
- msw