Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
item rules refactor and audit log changes (#813)
Sid03f1bf67017d
diff --git a/apps/erp/app/components/AuditLog/AuditLogDrawer.tsx b/apps/erp/app/components/AuditLog/AuditLogDrawer.tsxindex ed1d3c69f8..00fd3439e1 100644--- a/apps/erp/app/components/AuditLog/AuditLogDrawer.tsx+++ b/apps/erp/app/components/AuditLog/AuditLogDrawer.tsx@@ -1,4 +1,4 @@-import { getTableLabel } from "@carbon/database/audit.config";+import { auditConfig, getTableLabel } from "@carbon/database/audit.config";import type { AuditLogEntry } from "@carbon/database/audit.types";import {Badge,@@ -241,7 +241,12 @@ const AuditLogEntryCard = memo(({ entry }: AuditLogEntryCardProps) => {icon: null};- const diffKeys = entry.diff ? Object.keys(entry.diff) : [];+ // Belt-and-suspenders filter — backend strips skipFields too, but if a+ // legacy entry slipped through (or a new skipField was added since the+ // entry was written), keep the noise out of the rendered diff.+ const diffKeys = entry.diff+ ? Object.keys(entry.diff).filter((k) => !isSkippedDiffKey(k))+ : [];return (<div className="border bg-muted/40 rounded-lg p-4 w-full">@@ -305,6 +310,18 @@ const AuditLogEntryCard = memo(({ entry }: AuditLogEntryCardProps) => {AuditLogEntryCard.displayName = "AuditLogEntryCard";export { AuditLogEntryCard };+// Hide globally-skipped columns (and any nested suffix path) from the+// rendered diff. Mirrors the writer/reader filter so vector / metadata+// noise stays out of the UI even if it sneaks past the API layer.+function isSkippedDiffKey(key: string): boolean {+ const skip = auditConfig.skipFields as readonly string[];+ for (let i = 0; i < skip.length; i++) {+ const s = skip[i]!;+ if (key === s || key.endsWith(`.${s}`)) return true;+ }+ return false;+}+function formatValue(value: unknown): string {if (value === null) return "null";if (value === undefined) return "undefined";diff --git a/apps/erp/app/components/Form/StorageUnit.tsx b/apps/erp/app/components/Form/StorageUnit.tsxindex 1bab13092d..8a64be98c8 100644--- a/apps/erp/app/components/Form/StorageUnit.tsx+++ b/apps/erp/app/components/Form/StorageUnit.tsx@@ -1,102 +1,97 @@+// Compatibility shim: keeps the historical `<StorageUnit>` form API but+// renders the hierarchical drill-down picker (Location → tree) underneath.+// All existing callsites continue to work; new code should prefer+// `StorageUnitDrillSelectField` directly.+import type { ComboboxProps } from "@carbon/form";-import { CreatableCombobox } from "@carbon/form";-import { useDisclosure } from "@carbon/react";-import { useEffect, useMemo, useRef, useState } from "react";+import { forwardRef, useEffect, useMemo } from "react";import { useFetcher } from "react-router";import type { getStorageUnitsList } from "~/modules/inventory";-import StorageUnitForm from "~/modules/inventory/ui/StorageUnits/StorageUnitForm";import type { ListItem } from "~/types";import { path } from "~/utils/path";+import {+ StorageUnitDrillSelectField,+ type StorageUnitTreeRow+} from "./StorageUnitDrillSelect";type StorageUnitSelectProps = Omit<ComboboxProps,"options" | "onChange" | "inline"> & {locationId?: string;+ /** Kept for API compat; the drill picker doesn't display per-item qty. */itemId?: string;+ /** No-op in the drill picker — table inline preview no longer supported. */inline?: boolean;onChange?: (storageUnit: ListItem | null) => void;/**- * When set, the option list excludes the given storage unit and every one- * of its descendants. Used by StorageUnitForm's Parent select so a user- * cannot pick themselves or a child as the parent (which would create a- * cycle). The DB enforces the same invariant via- * storage_unit_enforce_no_cycle; this just keeps the UI honest.+ * Exclude the given storage unit and every one of its descendants — used+ * by `StorageUnitForm`'s Parent picker so a user cannot pick themselves or+ * a child (which would create a cycle). DB enforces the same invariant+ * via `storage_unit_enforce_no_cycle`.*/excludeDescendantsOf?: string;};-const StorageUnitPreview = (- value: string,- options: { value: string; label: string | JSX.Element }[]-) => {- const storageUnit = options.find((o) => o.value === value);- if (!storageUnit) return "Inventory";- return storageUnit.label;-};--const StorageUnit = (props: StorageUnitSelectProps) => {- const newStorageUnitModal = useDisclosure();- const [created, setCreated] = useState<string>("");- const triggerRef = useRef<HTMLButtonElement>(null);-- const { options: rawOptions, data } = useStorageUnits(- props.locationId,- props.itemId- );-- const excludedIds = useExcludedDescendantIds(props.excludeDescendantsOf);+const StorageUnit = forwardRef<HTMLDivElement, StorageUnitSelectProps>(+ (props, _ref) => {+ const {+ name,+ label,+ locationId,+ isReadOnly,+ isOptional,+ excludeDescendantsOf,+ onChange,+ ...rest+ } = props;++ // Field name is required to bind to the form. The original component+ // declared `name` via ComboboxProps (also required).+ if (!name) {+ console.warn("<StorageUnit /> requires a `name` prop.");+ return null;+ }- const options = useMemo(() => {- if (excludedIds.size === 0) return rawOptions;- return rawOptions.filter((option) => !excludedIds.has(option.value));- }, [rawOptions, excludedIds]);-- const onChange = (- newValue: { label: string | JSX.Element; value: string } | null- ) => {- const storageUnit =- data?.data?.find((s) => s.id === newValue?.value) ?? null;- props.onChange?.(storageUnit as ListItem | null);- };-- return (- <>- <CreatableCombobox- ref={triggerRef}- options={options}- {...props}- label={props?.label ?? "Storage Unit"}- inline={props.inline ? StorageUnitPreview : undefined}- onChange={onChange}- onCreateOption={(option) => {- newStorageUnitModal.onOpen();- setCreated(option);+ return (+ <StorageUnitDrillSelectField+ name={name}+ label={typeof label === "string" ? label : undefined}+ helperText={+ typeof rest.helperText === "string" ? rest.helperText : undefined+ }+ locationId={locationId}+ isReadOnly={isReadOnly}+ isOptional={isOptional}+ excludeDescendantsOf={excludeDescendantsOf}+ placeholder={+ typeof rest.placeholder === "string"+ ? rest.placeholder+ : "Select storage unit"+ }+ onChange={(row) => {+ if (!onChange) return;+ onChange(rowToListItem(row));}}/>+ );+ }+);+StorageUnit.displayName = "StorageUnit";- {newStorageUnitModal.isOpen && (- <StorageUnitForm- locationId={props.locationId!}- type="modal"- onClose={() => {- setCreated("");- newStorageUnitModal.onClose();- triggerRef.current?.click();- }}- initialValues={{- name: created,- locationId: props?.locationId ?? "",- storageTypeIds: []- }}- />- )}- </>- );+const rowToListItem = (row: StorageUnitTreeRow | null): ListItem | null => {+ if (!row) return null;+ return { id: row.id, name: row.name } as ListItem;};export default StorageUnit;+// ---------------------------------------------------------------------------+// useStorageUnits — kept exported because table cells / non-form callsites+// still pull the flat list (with optional per-item qty hints). The drill+// picker has its own tree fetch; this hook stays as the flat fallback.+// ---------------------------------------------------------------------------+export function useStorageUnits(locationId?: string, itemId?: string) {const storageUnitsFetcher =useFetcher<Awaited<ReturnType<typeof getStorageUnitsList>>>();@@ -107,7 +102,6 @@ export function useStorageUnits(locationId?: string, itemId?: string) {useEffect(() => {if (locationId) {if (itemId) {- // Load both storage units with quantities and all storage unitsstorageUnitsWithQuantitiesFetcher.load(path.to.api.storageUnitsWithQuantities(locationId, itemId));@@ -118,22 +112,18 @@ export function useStorageUnits(locationId?: string, itemId?: string) {const options = useMemo(() => {if (itemId && storageUnitsWithQuantitiesFetcher.data?.data) {- // Create a map of storage units with quantitiesconst storageUnitsWithQuantities =storageUnitsWithQuantitiesFetcher.data.data;const allStorageUnits = storageUnitsFetcher.data?.data ?? [];- // Create a set of storage unit IDs that have quantitiesconst storageUnitIdsWithQuantities = new Set(storageUnitsWithQuantities.map((s: any) => s.id));- // Filter out storage units that already have quantities from the all listconst storageUnitsWithoutQuantities = allStorageUnits.filter((storageUnit: any) => !storageUnitIdsWithQuantities.has(storageUnit.id));- // Combine the lists: storage units with quantities first, then othersconst combinedStorageUnits = [...storageUnitsWithQuantities.map((c: any) => ({value: c.id,@@ -149,7 +139,6 @@ export function useStorageUnits(locationId?: string, itemId?: string) {return combinedStorageUnits;}- // Fallback to original behaviorreturn (storageUnitsFetcher.data?.data?.map((c) => ({value: c.id,@@ -167,28 +156,3 @@ export function useStorageUnits(locationId?: string, itemId?: string) {return { options, data: storageUnitsFetcher.data };}--/**- * Fetches the set of storage-unit ids in the subtree rooted at `rootId`- * (rootId itself + all descendants). Returns an empty Set when rootId is- * undefined so the caller can always do `excludedIds.has(x)` safely.- */-function useExcludedDescendantIds(rootId?: string): Set<string> {- const descendantsFetcher = useFetcher<{ data: { id: string }[] }>();-- // biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migration- useEffect(() => {- if (rootId) {- descendantsFetcher.load(path.to.api.storageUnitDescendants(rootId));- }- }, [rootId]);-- return useMemo(() => {- if (!rootId) return new Set<string>();- const ids = new Set<string>([rootId]);- for (const row of descendantsFetcher.data?.data ?? []) {- if (row.id) ids.add(row.id);- }- return ids;- }, [rootId, descendantsFetcher.data]);-}diff --git a/apps/erp/app/components/Form/StorageUnitDrillSelect.tsx b/apps/erp/app/components/Form/StorageUnitDrillSelect.tsxindex 768a0d1d77..ea36ddfea1 100644--- a/apps/erp/app/components/Form/StorageUnitDrillSelect.tsx+++ b/apps/erp/app/components/Form/StorageUnitDrillSelect.tsx@@ -22,10 +22,11 @@ import {useDisclosure} from "@carbon/react";import { useCallback, useEffect, useMemo, useRef, useState } from "react";-import { LuX } from "react-icons/lu";+import { LuChevronDown, LuChevronRight, LuMapPin, LuX } from "react-icons/lu";import { useFetcher } from "react-router";import StorageUnitForm from "~/modules/inventory/ui/StorageUnits/StorageUnitForm";import { path } from "~/utils/path";+import { useLocations } from "./Location";export type StorageUnitTreeRow = {id: string;@@ -56,12 +57,18 @@ export function useStorageUnitsTree(locationId?: string | null) {type StorageUnitDrillSelectProps = {locationId: string | null | undefined;value: string | null | undefined;- onChange: (id: string) => void;+ onChange: (id: string, row?: StorageUnitTreeRow) => void;isReadOnly?: boolean;/** Show "+ New storage unit" footer. Defaults to `true`. */allowCreate?: boolean;placeholder?: string;className?: string;+ /**+ * Exclude the given unit and all its descendants from the tree. Used by+ * parent-pickers so a user can't pick themselves / a child (cycle). DB+ * also enforces via `storage_unit_enforce_no_cycle`.+ */+ excludeDescendantsOf?: string;};export function StorageUnitDrillSelect({@@ -71,9 +78,18 @@ export function StorageUnitDrillSelect({isReadOnly,allowCreate = true,placeholder = "Select",- className+ className,+ excludeDescendantsOf}: StorageUnitDrillSelectProps) {- const rows = useStorageUnitsTree(locationId);+ const allRows = useStorageUnitsTree(locationId);+ const excludedIds = useExcludedDescendantIds(excludeDescendantsOf);+ const rows = useMemo(+ () =>+ excludedIds.size === 0+ ? allRows+ : allRows.filter((r) => !excludedIds.has(r.id)),+ [allRows, excludedIds]+ );const newStorageUnitModal = useDisclosure();const [created, setCreated] = useState<string>("");const [open, setOpen] = useState(false);@@ -132,13 +148,30 @@ export function StorageUnitDrillSelect({const selectedRow = value ? byId.get(value) : undefined;const triggerLabel = selectedRow?.name ?? "";+ // Look up the current location's name for the breadcrumb root.+ const locations = useLocations();+ const locationLabel = useMemo(() => {+ const match = locations.find((l) => l.value === locationId);+ return match ? (typeof match.label === "string" ? match.label : "") : "";+ }, [locations, locationId]);++ // Open with the selected row's parent stack so the user sees the selected+ // unit highlighted in its sibling list on reopen.+ useEffect(() => {+ if (!open) return;+ if (!value) return;+ const row = byId.get(value);+ if (!row) return;+ setStack((row.ancestorPath ?? []).slice(0, -1));+ }, [open, value, byId]);+const reset = () => {setStack([]);setSearch("");};const select = (id: string) => {- onChange(id);+ onChange(id, id ? byId.get(id) : undefined);setOpen(false);reset();};@@ -160,54 +193,70 @@ export function StorageUnitDrillSelect({type="button"disabled={isReadOnly}className={cn(- "flex h-9 w-full items-center justify-between gap-2 rounded-md border border-input bg-transparent px-3 text-sm text-left",- "ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",+ "flex h-9 w-full items-center justify-between gap-2 rounded-md border border-input bg-transparent px-3 text-sm text-left shadow-xs transition-[color,box-shadow]",+ "outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50",isReadOnly && "opacity-60 cursor-not-allowed",!triggerLabel && "text-muted-foreground",className)}>- <span className="truncate">{triggerLabel || placeholder}</span>- {value && !isReadOnly ? (- <span- role="button"- tabIndex={-1}- onClick={(e) => {- e.stopPropagation();- onChange("");- }}- className="flex h-4 w-4 items-center justify-center rounded hover:bg-muted"- >- <LuX className="h-3 w-3" />- </span>- ) : null}+ <span className="min-w-0 flex-1 truncate">+ {triggerLabel || placeholder}+ </span>+ <span className="flex shrink-0 items-center gap-1">+ {value && !isReadOnly ? (+ <span+ role="button"+ tabIndex={-1}+ aria-label="Clear"+ onClick={(e) => {+ e.stopPropagation();+ onChange("");+ }}+ className="flex h-4 w-4 items-center justify-center rounded opacity-60 hover:bg-muted hover:opacity-100"+ >+ <LuX className="h-3 w-3" />+ </span>+ ) : null}+ <LuChevronDown className="h-4 w-4 opacity-50" />+ </span></button></PopoverTrigger>- <PopoverContent className="w-[280px] p-0" align="start">- <div className="flex flex-wrap items-center gap-1 border-b px-2 py-1.5">+ <PopoverContent+ align="start"+ sideOffset={4}+ collisionPadding={12}+ avoidCollisions+ className="w-auto min-w-[280px] max-w-[min(420px,calc(100vw-24px))] p-0"+ >+ {/* Breadcrumb — always visible. Root crumb = location, non-clickable+ (DrillSelect is single-location); subsequent crumbs are parent+ units (clickable to navigate up the tree). */}+ <div className="flex flex-wrap items-center gap-0.5 border-b px-2 py-1.5"><buttontype="button"onClick={() => setStack([])}className={cn(- "rounded px-1.5 py-0.5 text-xs hover:bg-muted",+ "flex items-center gap-1 rounded px-1.5 py-0.5 text-xs hover:bg-muted",stack.length === 0- ? "text-foreground font-medium"- : "text-muted-foreground"+ ? "font-medium text-foreground"+ : "text-muted-foreground hover:text-foreground")}>- All+ <LuMapPin className="h-3 w-3 opacity-70" />+ {locationLabel || "Location"}</button>{breadcrumb.map((row, i) => (- <span key={row.id} className="flex items-center gap-1">- <span className="text-muted-foreground text-xs">/</span>+ <span key={row.id} className="flex items-center gap-0.5">+ <LuChevronRight className="h-3 w-3 text-muted-foreground/60" /><buttontype="button"onClick={() => setStack(stack.slice(0, i + 1))}className={cn("rounded px-1.5 py-0.5 text-xs hover:bg-muted",i === breadcrumb.length - 1- ? "text-foreground font-medium"- : "text-muted-foreground"+ ? "font-medium text-foreground"+ : "text-muted-foreground hover:text-foreground")}>{row.name}@@ -215,54 +264,62 @@ export function StorageUnitDrillSelect({</span>))}</div>- <div className="border-b px-2 py-1.5">- <Input- autoFocus- value={search}- onChange={(e) => setSearch(e.target.value)}- placeholder="Search…"- className="h-7 text-sm"- />- </div>- <div className="max-h-[260px] overflow-y-auto py-1">++ {/* Search — flush, borderless. */}+ <Input+ autoFocus+ borderless+ value={search}+ onChange={(e) => setSearch(e.target.value)}+ placeholder="Search storage units…"+ className="h-9 rounded-none border-b border-border bg-transparent px-3 text-sm focus-visible:ring-0 focus-visible:ring-offset-0"+ />++ {/* List */}+ <ul role="list" className="max-h-[260px] overflow-y-auto py-1">{searchResults ? (searchResults.length === 0 ? (- <div className="px-3 py-6 text-center text-xs text-muted-foreground">+ <li className="px-3 py-6 text-center text-xs text-muted-foreground">No matches- </div>+ </li>) : (searchResults.map((row) => (- <button- key={row.id}- type="button"- onClick={() => select(row.id)}- className="flex w-full flex-col items-start px-3 py-1.5 text-left text-sm hover:bg-muted"- >- <span>{row.name}</span>- {renderPath(row) && (- <span className="text-xs text-muted-foreground">- {renderPath(row)}- </span>- )}- </button>+ <li key={row.id}>+ <button+ type="button"+ onClick={() => select(row.id)}+ className="flex w-full flex-col items-start gap-0.5 px-3 py-1.5 text-left hover:bg-muted"+ >+ <span className="text-sm">{row.name}</span>+ {renderPath(row) && (+ <span className="text-xs text-muted-foreground">+ {renderPath(row)}+ </span>+ )}+ </button>+ </li>)))) : currentChildren.length === 0 ? (- <div className="px-3 py-6 text-center text-xs text-muted-foreground">+ <li className="px-3 py-6 text-center text-xs text-muted-foreground">No storage units- </div>+ </li>) : (currentChildren.map((row) => {const hasChildren = (childrenOf.get(row.id) ?? []).length > 0;+ const isSelected = row.id === value;return (- <div+ <likey={row.id}className="flex items-stretch hover:bg-muted"><buttontype="button"onClick={() => select(row.id)}- className="flex-1 px-3 py-1.5 text-left text-sm"+ className={cn(+ "flex-1 truncate px-3 py-1.5 text-left text-sm",+ isSelected && "font-medium text-foreground"+ )}>{row.name}</button>@@ -273,32 +330,32 @@ export function StorageUnitDrillSelect({setStack([...stack, row.id]);setSearch("");}}- className="flex w-7 items-center justify-center border-l text-muted-foreground hover:text-foreground"+ className="flex w-7 shrink-0 items-center justify-center border-l text-muted-foreground hover:text-foreground"aria-label={`Open ${row.name}`}>- ›+ <LuChevronRight className="h-3.5 w-3.5" /></button>)}- </div>+ </li>);}))}- </div>+ </ul>+{allowCreate && (- <div className="border-t px-2 py-1.5">- <button- type="button"- onClick={() => {- setOpen(false);- reset();- newStorageUnitModal.onOpen();- setCreated(search);- }}- className="w-full rounded px-2 py-1 text-left text-xs text-muted-foreground hover:bg-muted"- >- + New storage unit{search ? `: "${search}"` : ""}- </button>- </div>+ <button+ type="button"+ onClick={() => {+ setOpen(false);+ reset();+ newStorageUnitModal.onOpen();+ setCreated(search);+ }}+ className="flex w-full items-center gap-1 border-t border-border px-3 py-2 text-left text-xs text-muted-foreground hover:bg-muted hover:text-foreground"+ >+ <span className="text-sm leading-none">+</span>+ New storage unit{search ? `: "${search}"` : ""}+ </button>)}</PopoverContent></Popover>@@ -322,6 +379,31 @@ export function StorageUnitDrillSelect({);}+// ---------------------------------------------------------------------------+// useExcludedDescendantIds — fetches the subtree under `rootId` so a+// parent-picker can exclude self + descendants (cycle prevention).+// ---------------------------------------------------------------------------++export function useExcludedDescendantIds(rootId?: string): Set<string> {+ const descendantsFetcher = useFetcher<{ data: { id: string }[] }>();++ // biome-ignore lint/correctness/useExhaustiveDependencies: fetcher identity changes every render+ useEffect(() => {+ if (rootId) {+ descendantsFetcher.load(path.to.api.storageUnitDescendants(rootId));+ }+ }, [rootId]);++ return useMemo(() => {+ if (!rootId) return new Set<string>();+ const ids = new Set<string>([rootId]);+ for (const row of descendantsFetcher.data?.data ?? []) {+ if (row.id) ids.add(row.id);+ }+ return ids;+ }, [rootId, descendantsFetcher.data]);+}+// ---------------------------------------------------------------------------// Form-aware variant — binds to `@carbon/form` via name + hidden input.// ---------------------------------------------------------------------------@@ -332,9 +414,17 @@ type StorageUnitDrillSelectFieldProps = {helperText?: string;locationId: string | null | undefined;isReadOnly?: boolean;+ isOptional?: boolean;allowCreate?: boolean;placeholder?: string;className?: string;+ excludeDescendantsOf?: string;+ /**+ * Callback fired after the form value updates. Receives the chosen row so+ * callers that need name/parent metadata don't have to re-fetch. `null` on+ * clear.+ */+ onChange?: (row: StorageUnitTreeRow | null) => void;};export function StorageUnitDrillSelectField({@@ -343,16 +433,23 @@ export function StorageUnitDrillSelectField({helperText,locationId,isReadOnly,+ isOptional,allowCreate,placeholder,- className+ className,+ excludeDescendantsOf,+ onChange}: StorageUnitDrillSelectFieldProps) {- const { error, getInputProps } = useField(name);+ const { error, getInputProps, isOptional: fieldIsOptional } = useField(name);const [value, setValue] = useControlField<string | undefined>(name);return (<FormControl isInvalid={!!error}>- {label && <FormLabel htmlFor={name}>{label}</FormLabel>}+ {label && (+ <FormLabel htmlFor={name} isOptional={isOptional ?? fieldIsOptional}>+ {label}+ </FormLabel>+ )}{/* Hidden input so the form serialises the chosen id on submit. */}<input{...getInputProps({ id: name, type: "hidden" })}@@ -362,11 +459,15 @@ export function StorageUnitDrillSelectField({<StorageUnitDrillSelectlocationId={locationId}value={value ?? null}- onChange={(next) => setValue(next || undefined)}+ onChange={(next, row) => {+ setValue(next || undefined);+ onChange?.(next ? (row ?? null) : null);+ }}isReadOnly={isReadOnly}allowCreate={allowCreate}placeholder={placeholder}className={className}+ excludeDescendantsOf={excludeDescendantsOf}/>{error ? (<FormErrorMessage>{error}</FormErrorMessage>diff --git a/apps/erp/app/modules/customRules/customRules.models.ts b/apps/erp/app/modules/customRules/customRules.models.tsnew file mode 100644index 0000000000..04691b0b0c--- /dev/null+++ b/apps/erp/app/modules/customRules/customRules.models.ts@@ -0,0 +1,107 @@+import {+ SURFACES_BY_TARGET_TYPE,+ TARGET_TYPES,+ TRANSACTION_SURFACES+} from "@carbon/utils";+import { z } from "zod";+import { zfd } from "zod-form-data";++export const customRuleSeverities = ["error", "warn"] as const;++export const customRuleOperators = [+ "eq",+ "neq",+ "in",+ "notIn",+ "isSet",+ "isNotSet",+ "gt",+ "lt"+] as const;++const customRuleConditionValueSchema = z.union([+ z.string(),+ z.number(),+ z.boolean(),+ z.array(z.union([z.string(), z.number(), z.boolean()])),+ z.null()+]);++const customRuleConditionSchema = z.object({+ field: z.string().min(1, { message: "Field is required" }),+ op: z.enum(customRuleOperators),+ value: customRuleConditionValueSchema.optional()+});++export const customRuleMatchKinds = ["all", "any", "none"] as const;++export const customRuleConditionAstSchema = z.object({+ kind: z.enum(customRuleMatchKinds),+ conditions: z+ .array(customRuleConditionSchema)+ .min(1, { message: "At least one condition is required" })+});++const customRuleConditionAstFormField = z.preprocess((raw) => {+ if (typeof raw !== "string") return raw;+ try {+ return JSON.parse(raw);+ } catch {+ return raw;+ }+}, customRuleConditionAstSchema);++export const customRuleValidator = z+ .object({+ id: zfd.text(z.string().optional()),+ name: z.string().min(1, { message: "Name is required" }).max(120),+ description: zfd.text(z.string().optional()),+ message: z.string().min(1, { message: "Message is required" }).max(500),+ severity: z.enum(customRuleSeverities),+ targetType: z.enum(TARGET_TYPES),+ appliesToAll: zfd.checkbox(),+ active: zfd.checkbox(),+ surfaces: zfd+ .repeatableOfType(z.enum(TRANSACTION_SURFACES))+ .refine((arr) => arr.length >= 1, {+ message: "Pick at least one surface"+ }),+ conditionAst: customRuleConditionAstFormField+ })+ .superRefine((val, ctx) => {+ // Reject any surface that isn't valid for the chosen targetType. Schema+ // enforcement only — DB has no CHECK; UI also filters the picker.+ const allowed = new Set<string>(SURFACES_BY_TARGET_TYPE[val.targetType]);+ for (let i = 0; i < val.surfaces.length; i++) {+ const s = val.surfaces[i]!;+ if (!allowed.has(s)) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ path: ["surfaces", i],+ message: `Surface "${s}" not valid for ${val.targetType} rules`+ });+ }+ }+ });++/**+ * Polymorphic assignment validator factory. The form's hidden field tells the+ * action which targetType is in play, then this validator picks the right+ * target-id key.+ */+export const customRuleAssignmentValidator = (+ targetType: "item" | "storageUnit" | "workCenter"+) => {+ const idKey =+ targetType === "item"+ ? "itemId"+ : targetType === "storageUnit"+ ? "storageUnitId"+ : "workCenterId";+ return z.object({+ [idKey]: z.string().min(1, { message: "Target ID is required" }),+ ruleId: z.string().min(1, { message: "Rule ID is required" })+ });+};++export const customRuleAcknowledgeValidator = zfd.checkbox();diff --git a/apps/erp/app/modules/customRules/customRules.service.ts b/apps/erp/app/modules/customRules/customRules.service.tsnew file mode 100644index 0000000000..3c7dbe3b40--- /dev/null+++ b/apps/erp/app/modules/customRules/customRules.service.ts@@ -0,0 +1,146 @@+// ERP-only admin CRUD for the Settings → Custom Rules page.+// Cross-app queries (assignment loaders, list fetch for tab data, polymorphic+// assign/unassign) live in `@carbon/ee/custom-rules`.++import type { Database, Json } from "@carbon/database";+import type {+ ConditionAst,+ Severity,+ TargetType,+ TransactionSurface+} from "@carbon/utils";+import { getLocalTimeZone, now } from "@internationalized/date";+import type { SupabaseClient } from "@supabase/supabase-js";+import type { GenericQueryFilters } from "~/utils/query";+import { setGenericQueryFilters } from "~/utils/query";+import { sanitize } from "~/utils/supabase";++type CustomRuleInsert = {+ name: string;+ description?: string | null;+ message: string;+ severity: Severity;+ conditionAst: ConditionAst;+ surfaces: TransactionSurface[];+ targetType: TargetType;+ appliesToAll: boolean;+ active: boolean;+ companyId: string;+ createdBy: string;+ customFields?: Json;+};++type CustomRuleUpdate = {+ id: string;+ name: string;+ description?: string | null;+ message: string;+ severity: Severity;+ conditionAst: ConditionAst;+ surfaces: TransactionSurface[];+ appliesToAll: boolean;+ active: boolean;+ updatedBy: string;+ customFields?: Json;+};++export async function getCustomRules(+ client: SupabaseClient<Database>,+ companyId: string,+ args?: GenericQueryFilters & {+ search: string | null;+ targetType?: TargetType | null;+ }+) {+ let query = client+ .from("customRule")+ .select("*", { count: "exact" })+ .eq("companyId", companyId);++ if (args?.search) {+ query = query.ilike("name", `%${args.search}%`);+ }+ if (args?.targetType) {+ query = query.eq("targetType", args.targetType);+ }++ query = setGenericQueryFilters(query, args ?? {}, [+ { column: "name", ascending: true }+ ]);+ return query;+}++export async function getCustomRule(+ client: SupabaseClient<Database>,+ id: string+) {+ return client.from("customRule").select("*").eq("id", id).single();+}++export async function upsertCustomRule(+ client: SupabaseClient<Database>,+ rule: CustomRuleInsert | CustomRuleUpdate+) {+ if ("createdBy" in rule) {+ return client+ .from("customRule")+ .insert({ ...rule, conditionAst: rule.conditionAst as unknown as Json })+ .select("id")+ .single();+ }+ return client+ .from("customRule")+ .update({+ ...sanitize(rule),+ conditionAst: rule.conditionAst as unknown as Json,+ updatedAt: now(getLocalTimeZone()).toAbsoluteString()+ })+ .eq("id", rule.id)+ .select("id")+ .single();+}++export async function deleteCustomRule(+ client: SupabaseClient<Database>,+ id: string+) {+ return client.from("customRule").delete().eq("id", id);+}++export async function getRuleAssignmentCounts(+ client: SupabaseClient<Database>,+ ruleIds: string[]+) {+ // Counts span all three assignment tables. Each rule lives in exactly one+ // (rule.targetType drives the table); union of single-table counts is correct.+ if (ruleIds.length === 0) return { data: {}, error: null };++ const counts: Record<string, number> = {};+ const tables: Array<+ | "customRuleItemAssignment"+ | "customRuleStorageUnitAssignment"+ | "customRuleWorkCenterAssignment"+ > = [+ "customRuleItemAssignment",+ "customRuleStorageUnitAssignment",+ "customRuleWorkCenterAssignment"+ ];++ const results = await Promise.all(+ tables.map((table) =>+ (client as SupabaseClient<Database>)+ .from(table)+ .select("ruleId")+ .in("ruleId", ruleIds)+ )+ );++ for (const { data, error } of results) {+ if (error) return { data: {}, error };+ for (const row of (data ?? []) as Array<{ ruleId: string }>) {+ counts[row.ruleId] = (counts[row.ruleId] ?? 0) + 1;+ }+ }++ return { data: counts, error: null };+}diff --git a/apps/erp/app/modules/customRules/index.ts b/apps/erp/app/modules/customRules/index.tsnew file mode 100644index 0000000000..a367b5a232--- /dev/null+++ b/apps/erp/app/modules/customRules/index.ts@@ -0,0 +1,13 @@+// ERP-side Custom Rules module. Re-exports cross-app queries from the+// `@carbon/ee/custom-rules` package alongside ERP-only admin CRUD + form+// validators.++export {+ assignCustomRule,+ getActiveRulesForTargets,+ getCustomRulesList,+ getRuleAssignmentsForTarget,+ unassignCustomRule+} from "@carbon/ee/custom-rules";+export * from "./customRules.models";+export * from "./customRules.service";diff --git a/apps/erp/app/modules/customRules/ui/ConditionRow.tsx b/apps/erp/app/modules/customRules/ui/ConditionRow.tsxnew file mode 100644index 0000000000..3bd351fea1--- /dev/null+++ b/apps/erp/app/modules/customRules/ui/ConditionRow.tsx@@ -0,0 +1,199 @@+import { cn, IconButton } from "@carbon/react";+import {+ availableOperators,+ type Condition,+ type FieldDef,+ getFieldDef,+ getFieldSurfaceNotes,+ type Operator,+ SURFACES_BY_TARGET_TYPE,+ type TransactionSurface+} from "@carbon/utils";+import { useLingui } from "@lingui/react/macro";+import { memo, useEffect, useMemo } from "react";+import { LuX } from "react-icons/lu";+import FieldCombobox from "./FieldCombobox";+import OperatorCombobox from "./OperatorCombobox";+import type { ValueOptionsByLoader } from "./useValueOptions";+import ValueInput from "./ValueInput";++// Pretty labels for per-surface notes. Mirrors SURFACE_META in SurfacesField+// but kept lean — only the title is shown.+const SURFACE_LABEL: Record<TransactionSurface, string> = {+ receipt: "Receipts",+ shipment: "Shipments",+ stockTransfer: "Stock transfers",+ warehouseTransfer: "Warehouse transfers",+ inventoryAdjustment: "Inventory adjustments",+ place: "Place",+ pick: "Pick",+ operationStart: "Operation start",+ operationFinish: "Operation finish",+ materialIssue: "Material issue",+ materialReceive: "Material receive"+};++const pickDefaultOp = (ops: Operator[]): Operator =>+ ops.includes("eq") ? "eq" : (ops[0] ?? "eq");++export const CONDITION_GRID_CLASS =+ "grid grid-cols-1 gap-2 sm:grid-cols-[minmax(0,1.2fr)_minmax(0,0.9fr)_minmax(0,1fr)]";++type ConditionRowProps = {+ condition: Condition;+ index: number;+ canRemove: boolean;+ onChange: (index: number, patch: Partial<Condition>) => void;+ onRemove: (index: number) => void;+ optionsByLoader: ValueOptionsByLoader;+ targetType?: "item" | "storageUnit" | "workCenter";+ /**+ * Live list of surfaces the parent rule is configured for. When provided,+ * the per-surface notes panel filters to this set. Falls back to all+ * surfaces valid for the targetType when omitted.+ */+ surfaces?: TransactionSurface[];+};++function ConditionRowImpl({+ condition,+ index,+ canRemove,+ onChange,+ onRemove,+ optionsByLoader,+ targetType,+ surfaces+}: ConditionRowProps) {+ const { t } = useLingui();++ const fieldDef = useMemo<FieldDef | undefined>(+ () => getFieldDef(condition.field),+ [condition.field]+ );++ const availableOps = useMemo<Operator[]>(+ () => (fieldDef ? availableOperators(fieldDef) : []),+ [fieldDef]+ );++ const valueOptions = useMemo(+ () =>+ fieldDef?.valueOptionsLoader+ ? optionsByLoader[fieldDef.valueOptionsLoader]+ : undefined,+ [fieldDef, optionsByLoader]+ );++ // Per-surface semantic notes for ambiguous fields (e.g. transaction.quantity+ // means different things on operationStart vs operationFinish). Filter to+ // surfaces the rule actually fires on when the parent supplies them; fall+ // back to all surfaces valid for the targetType otherwise.+ const surfaceNotes = useMemo<+ { surface: TransactionSurface; note: string }[] | null+ >(() => {+ const all = getFieldSurfaceNotes(condition.field);+ if (!all) return null;+ const scope: readonly TransactionSurface[] =+ surfaces && surfaces.length > 0+ ? surfaces+ : targetType+ ? SURFACES_BY_TARGET_TYPE[targetType]+ : [];+ const rows: { surface: TransactionSurface; note: string }[] = [];+ for (const s of scope) {+ const note = all[s];+ if (note) rows.push({ surface: s, note });+ }+ return rows.length > 0 ? rows : null;+ }, [condition.field, targetType, surfaces]);++ // Self-heal: stored op no longer in the field's allowed set (legacy data,+ // or the field's `nullable` flag flipped post-save). Patch down to a valid+ // op so the user can save the rule back clean.+ useEffect(() => {+ if (!fieldDef) return;+ if (availableOps.includes(condition.op)) return;+ onChange(index, { op: pickDefaultOp(availableOps), value: undefined });+ }, [fieldDef, availableOps, condition.op, index, onChange]);++ return (+ <div className="flex w-full items-center gap-2">+ <div+ className={cn(+ "group flex-1 min-w-0 rounded-lg border border-border bg-card p-3",+ "transition-colors hover:border-border/80"+ )}+ >+ <div className={CONDITION_GRID_CLASS}>+ <FieldCombobox+ value={condition.field}+ targetType={targetType}+ onChange={(path) => {+ const nextDef = getFieldDef(path);+ const nextOps = nextDef ? availableOperators(nextDef) : [];+ onChange(index, {+ field: path,+ op: pickDefaultOp(nextOps),+ value: undefined+ });+ }}+ />++ <OperatorCombobox+ value={condition.op}+ onChange={(op: Operator) =>+ onChange(index, { op, value: undefined })+ }+ available={availableOps}+ disabled={!fieldDef}+ />++ <ValueInput+ fieldDef={fieldDef}+ op={condition.op}+ value={condition.value}+ options={valueOptions}+ onChange={(next) => onChange(index, { value: next })}+ />+ </div>++ {surfaceNotes && (+ <details className="mt-2 group rounded-md border border-dashed border-border/70 bg-muted/30 px-2 py-1.5 text-xs text-muted-foreground">+ <summary className="cursor-pointer select-none text-[11px] font-medium uppercase tracking-wider text-muted-foreground/90 hover:text-foreground">+ {t`Value source by surface`}+ </summary>+ <ul className="mt-1.5 flex flex-col gap-1">+ {surfaceNotes.map(({ surface, note }) => (+ <li+ key={surface}+ className="grid grid-cols-[minmax(0,9rem)_minmax(0,1fr)] gap-2"+ >+ <span className="font-medium text-foreground/80">+ {SURFACE_LABEL[surface]}+ </span>+ <span className="leading-snug">{note}</span>+ </li>+ ))}+ </ul>+ </details>+ )}+ </div>++ <IconButton+ icon={<LuX />}+ aria-label={t`Remove condition`}+ variant="ghost"+ size="sm"+ onClick={() => onRemove(index)}+ isDisabled={!canRemove}+ className={cn(+ "shrink-0",+ !canRemove && "opacity-0 pointer-events-none"+ )}+ />+ </div>+ );+}++export default memo(ConditionRowImpl);diff --git a/apps/erp/app/modules/items/ui/ItemRules/ItemRuleForm.tsx b/apps/erp/app/modules/customRules/ui/CustomRuleForm.tsxsimilarity index 62%rename from apps/erp/app/modules/items/ui/ItemRules/ItemRuleForm.tsxrename to apps/erp/app/modules/customRules/ui/CustomRuleForm.tsxindex 3649bd2b1f..8edd74d72a 100644--- a/apps/erp/app/modules/items/ui/ItemRules/ItemRuleForm.tsx+++ b/apps/erp/app/modules/customRules/ui/CustomRuleForm.tsx@@ -14,11 +14,12 @@ import {import {type Condition,type ConditionAst,- TRANSACTION_SURFACES+ SURFACES_BY_TARGET_TYPE,+ TRANSACTION_SURFACES,+ type TransactionSurface} from "@carbon/utils";import { Trans, useLingui } from "@lingui/react/macro";import { useState } from "react";-import { useFetcher } from "react-router";import type { z } from "zod";import {CustomFormFields,@@ -29,35 +30,34 @@ import {} from "~/components/Form";import { usePermissions } from "~/hooks";import { path } from "~/utils/path";-import { itemRuleValidator } from "../../items.models";+import { customRuleValidator } from "../customRules.models";import MessageWithTokens from "./MessageWithTokens";import RuleBuilder from "./RuleBuilder";import SeveritySelect from "./SeveritySelect";import SurfacesField from "./SurfacesField";-type ItemRuleFormInitial = Partial<z.infer<typeof itemRuleValidator>> & {+type CustomRuleFormInitial = Partial<z.infer<typeof customRuleValidator>> & {conditionAst?: ConditionAst;};-type ItemRuleFormProps = {- initialValues: ItemRuleFormInitial;+type CustomRuleFormProps = {+ initialValues: CustomRuleFormInitial;open?: boolean;onClose: () => void;};-export default function ItemRuleForm({+export default function CustomRuleForm({initialValues,open = true,onClose-}: ItemRuleFormProps) {+}: CustomRuleFormProps) {const { t } = useLingui();const permissions = usePermissions();- const fetcher = useFetcher();const isEditing = !!initialValues.id;const isDisabled = isEditing- ? !permissions.can("update", "parts")- : !permissions.can("create", "parts");+ ? !permissions.can("update", "settings")+ : !permissions.can("create", "settings");const conditionAstInitial: ConditionAst = (initialValues.conditionAst as| ConditionAst@@ -74,6 +74,24 @@ export default function ItemRuleForm({conditionAstInitial.conditions);+ const targetType = (initialValues.targetType ?? "item") as+ | "item"+ | "storageUnit"+ | "workCenter";++ // Default new rules to all surfaces of the chosen targetType. Editing keeps+ // whatever was saved.+ const defaultSurfaces = (initialValues.surfaces ??+ TRANSACTION_SURFACES.filter((s) =>+ SURFACES_BY_TARGET_TYPE[targetType].includes(s as never)+ )) as TransactionSurface[];++ // Live mirror of the rule's selected surfaces. RuleBuilder forwards this to+ // each ConditionRow so the per-surface notes panel filters to only the+ // surfaces this rule actually fires on.+ const [liveSurfaces, setLiveSurfaces] =+ useState<TransactionSurface[]>(defaultSurfaces);+// ValidatedForm wants defaultValues; we hand it the scalar fields.// conditionAst gets driven by RuleBuilder via Hidden field.const defaults = {@@ -82,9 +100,10 @@ export default function ItemRuleForm({description: initialValues.description ?? "",message: initialValues.message ?? "",severity: initialValues.severity ?? "error",+ targetType,+ appliesToAll: initialValues.appliesToAll ?? false,active: initialValues.active ?? true,- // Default new rules to all surfaces (matches DB default).- surfaces: initialValues.surfaces ?? [...TRANSACTION_SURFACES]+ surfaces: defaultSurfaces};return (@@ -97,15 +116,14 @@ export default function ItemRuleForm({><ModalDrawerContent size="lg"><ValidatedForm- validator={itemRuleValidator}+ validator={customRuleValidator}method="post"action={isEditing- ? path.to.itemRule(initialValues.id!)- : path.to.newItemRule+ ? path.to.customRule(initialValues.id!)+ : path.to.newCustomRule}defaultValues={defaults}- fetcher={fetcher}className="flex flex-col h-full"><ModalDrawerHeader>@@ -115,6 +133,7 @@ export default function ItemRuleForm({</ModalDrawerHeader><ModalDrawerBody><Hidden name="id" />+ <Hidden name="targetType" /><VStack spacing={4}><HStack className="w-full gap-x-4"><Input name="name" label={t`Name`} />@@ -129,14 +148,35 @@ export default function ItemRuleForm({placeholder={t`Optional context for this rule`}/><SeveritySelect name="severity" />- <SurfacesField name="surfaces" />+ <Boolean+ name="appliesToAll"+ label={+ targetType === "item"+ ? t`Applies to all items`+ : targetType === "storageUnit"+ ? t`Applies to all storage units`+ : t`Applies to all work centers`+ }+ description={t`When on, this rule fires for every target of its type. Assignment rows are ignored but preserved.`}+ />+ <SurfacesField+ name="surfaces"+ targetType={targetType}+ onSurfacesChange={setLiveSurfaces}+ /><RuleBuildername="conditionAst"initial={conditionAstInitial}onConditionsChange={setLiveConditions}+ targetType={targetType}+ surfaces={liveSurfaces}+ />+ <MessageWithTokens+ name="message"+ conditions={liveConditions}+ targetType={targetType}/>- <MessageWithTokens name="message" conditions={liveConditions} />- <CustomFormFields table="itemRule" />+ <CustomFormFields table="customRule" /></VStack></ModalDrawerBody><ModalDrawerFooter>diff --git a/apps/erp/app/modules/customRules/ui/CustomRulesGroups.tsx b/apps/erp/app/modules/customRules/ui/CustomRulesGroups.tsxnew file mode 100644index 0000000000..2dee81ac86--- /dev/null+++ b/apps/erp/app/modules/customRules/ui/CustomRulesGroups.tsx@@ -0,0 +1,323 @@+import {+ Accordion,+ AccordionContent,+ AccordionItem,+ AccordionTrigger,+ Badge,+ Button,+ Card,+ CardContent,+ CardDescription,+ CardHeader,+ CardTitle,+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuSeparator,+ DropdownMenuTrigger,+ Heading,+ HStack,+ IconButton,+ ScrollArea,+ Status,+ useDisclosure,+ VStack+} from "@carbon/react";+import type { TargetType, TransactionSurface } from "@carbon/utils";+import { memo, useCallback, useMemo } from "react";+import {+ LuEllipsisVertical,+ LuPackage,+ LuPencil,+ LuPlus,+ LuTrash,+ LuWarehouse+} from "react-icons/lu";+import { Link, useNavigate } from "react-router";+import { Empty } from "~/components";+import ConfirmDelete from "~/components/Modals/ConfirmDelete";+import { usePermissions, useUrlParams } from "~/hooks";+import { path } from "~/utils/path";+import SurfaceChips from "./SurfaceChips";++type RuleListItem = {+ id: string;+ name: string;+ targetType: TargetType;+ severity: "error" | "warn";+ active: boolean;+ appliesToAll: boolean;+ surfaces?: TransactionSurface[];+ assignmentCount?: number;+ description?: string | null;+ message?: string;+};++type CustomRulesGroupsProps = {+ rules: RuleListItem[];+};++const TARGET_LABEL: Record<TargetType, string> = {+ item: "Item",+ storageUnit: "Storage unit",+ workCenter: "Work center"+};++type SectionCardProps = {+ title: string;+ description: string;+ icon: JSX.Element;+ newRuleHref: string;+ newRuleLabel: string;+ canCreate: boolean;+ rules: RuleListItem[];+};++const RuleSectionCard = memo(+ ({+ title,+ description,+ icon,+ newRuleHref,+ newRuleLabel,+ canCreate,+ rules+ }: SectionCardProps) => (+ <Card>+ <CardHeader>+ <div className="flex items-start justify-between gap-4">+ <div className="min-w-0">+ <CardTitle className="flex items-center gap-2 text-base font-semibold">+ {icon}+ {title}+ </CardTitle>+ <CardDescription className="mt-1 max-w-[60ch] text-sm text-pretty">+ {description}+ </CardDescription>+ </div>+ {canCreate && (+ <Button variant="primary" leftIcon={<LuPlus />} asChild>+ <Link to={newRuleHref}>{newRuleLabel}</Link>+ </Button>+ )}+ </div>+ </CardHeader>+ <CardContent>+ {rules.length === 0 ? (+ <Empty className="my-4" />+ ) : (+ <VStack spacing={3} className="items-stretch">+ {rules.map((r) => (+ <CustomRuleCard key={r.id} rule={r} />+ ))}+ </VStack>+ )}+ </CardContent>+ </Card>+ )+);+RuleSectionCard.displayName = "RuleSectionCard";++const CustomRulesGroups = memo(({ rules }: CustomRulesGroupsProps) => {+ const permissions = usePermissions();+ const canCreate = permissions.can("create", "settings");++ // Split by targetType. Item + storageUnit shown; workCenter hidden until+ // entry point + MES modal ship.+ const { itemRules, storageUnitRules } = useMemo(() => {+ const itemRules: RuleListItem[] = [];+ const storageUnitRules: RuleListItem[] = [];+ for (const r of rules) {+ if (r.targetType === "item") itemRules.push(r);+ else if (r.targetType === "storageUnit") storageUnitRules.push(r);+ }+ return { itemRules, storageUnitRules };+ }, [rules]);++ return (+ <ScrollArea className="w-full h-[calc(100dvh-49px)]">+ <VStack+ spacing={4}+ className="py-12 px-4 max-w-[60rem] h-full mx-auto gap-4"+ >+ <div className="flex flex-col gap-1 w-full">+ <Heading size="h3" className="tracking-tight text-balance">+ Custom Rules+ </Heading>+ <p className="max-w-[72ch] text-sm text-muted-foreground text-pretty">+ Predicate-driven guards that fire on inventory transactions. Block+ with errors or warn with acknowledge-to-continue.+ </p>+ </div>++ <RuleSectionCard+ title="Item rules"+ description="Fire on receipts, shipments, transfers and inventory adjustments. Target items."+ icon={<LuPackage className="size-4 text-muted-foreground" />}+ newRuleHref={`${path.to.newCustomRule}?targetType=item`}+ newRuleLabel="Item Rule"+ canCreate={canCreate}+ rules={itemRules}+ />++ <RuleSectionCard+ title="Storage unit rules"+ description="Fire on place, pick and transfers. Target storage units."+ icon={<LuWarehouse className="size-4 text-muted-foreground" />}+ newRuleHref={`${path.to.newCustomRule}?targetType=storageUnit`}+ newRuleLabel="Storage Unit Rule"+ canCreate={canCreate}+ rules={storageUnitRules}+ />++ {/*+ Production rules card — hidden until work center rule wiring+ (entry point on the work centers list, drawer/tab to manage+ assignments, MES violation modal) ships. To restore: split+ workCenter rules out of `rules` above and render a third+ RuleSectionCard with `newRuleHref` pointing to targetType=workCenter.+ */}+ </VStack>+ </ScrollArea>+ );+});++CustomRulesGroups.displayName = "CustomRulesGroups";+export default CustomRulesGroups;++const CustomRuleCard = memo(({ rule }: { rule: RuleListItem }) => {+ const [params] = useUrlParams();+ const navigate = useNavigate();+ const permissions = usePermissions();+ const deleteDisclosure = useDisclosure();++ const canEdit = permissions.can("update", "settings");+ const canDelete = permissions.can("delete", "settings");++ const handleEdit = useCallback(() => {+ navigate(`${path.to.customRule(rule.id)}?${params.toString()}`);+ }, [navigate, params, rule.id]);++ return (+ <>+ <Card className="p-0 border">+ <Accordion type="multiple" className="w-full">+ <AccordionItem value={rule.id} className="border-none">+ <div className="relative">+ <AccordionTrigger className="px-6 py-6 hover:no-underline w-full">+ <HStack spacing={4} className="flex-1 justify-between pr-12">+ <div className="flex items-center gap-3 min-w-0">+ <Heading size="h4" as="h3" className="truncate">+ {rule.name}+ </Heading>+ <Badge variant="secondary">+ {TARGET_LABEL[rule.targetType]}+ </Badge>+ {rule.severity === "error" ? (+ <Badge variant="red">Error</Badge>+ ) : (+ <Badge variant="yellow">Warn</Badge>+ )}+ {rule.appliesToAll && (+ <Badge variant="outline">Applies to all</Badge>+ )}+ </div>+ <Status+ color={rule.active ? "green" : "gray"}+ className="text-xs font-medium"+ >+ {rule.active ? "Active" : "Inactive"}+ </Status>+ </HStack>+ </AccordionTrigger>+ <div className="absolute right-12 top-1/2 -translate-y-1/2 z-10">+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <IconButton+ aria-label="More options"+ icon={<LuEllipsisVertical />}+ variant="ghost"+ onClick={(e) => e.stopPropagation()}+ />+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end">+ <DropdownMenuItem+ disabled={!canEdit}+ onClick={(e) => {+ e.stopPropagation();+ handleEdit();+ }}+ >+ <LuPencil className="mr-2 h-4 w-4" />+ Edit Rule+ </DropdownMenuItem>+ <DropdownMenuSeparator />+ <DropdownMenuItem+ destructive+ disabled={!canDelete}+ onClick={(e) => {+ e.stopPropagation();+ deleteDisclosure.onOpen();+ }}+ >+ <LuTrash className="mr-2 h-4 w-4" />+ Delete Rule+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ </div>+ </div>+ <AccordionContent className="px-6 pb-5">+ <VStack spacing={3}>+ {rule.description && (+ <p className="text-sm text-muted-foreground">+ {rule.description}+ </p>+ )}+ {rule.message && (+ <div className="flex flex-col gap-1">+ <span className="text-xs uppercase tracking-wide font-medium text-muted-foreground">+ Message+ </span>+ <p className="text-sm">{rule.message}</p>+ </div>+ )}+ <div className="flex items-center gap-4 text-sm">+ <div className="flex flex-col gap-1">+ <span className="text-xs uppercase tracking-wide font-medium text-muted-foreground">+ Triggers+ </span>+ <SurfaceChips+ surfaces={rule.surfaces}+ targetType={rule.targetType}+ />+ </div>+ {!rule.appliesToAll && (+ <div className="flex flex-col gap-1">+ <span className="text-xs uppercase tracking-wide font-medium text-muted-foreground">+ Assignments+ </span>+ <span className="tabular-nums text-sm">+ {rule.assignmentCount ?? 0}+ </span>+ </div>+ )}+ </div>+ </VStack>+ </AccordionContent>+ </AccordionItem>+ </Accordion>+ </Card>+ <ConfirmDelete+ action={path.to.deleteCustomRule(rule.id)}+ isOpen={deleteDisclosure.isOpen}+ name={`${TARGET_LABEL[rule.targetType]} rule "${rule.name}"`}+ text="Are you sure you want to delete this custom rule? Assignments will also be removed."+ onCancel={deleteDisclosure.onClose}+ onSubmit={deleteDisclosure.onClose}+ />+ </>+ );+});++CustomRuleCard.displayName = "CustomRuleCard";diff --git a/apps/erp/app/modules/items/ui/ItemRules/ItemRulesTable.tsx b/apps/erp/app/modules/customRules/ui/CustomRulesTable.tsxsimilarity index 70%rename from apps/erp/app/modules/items/ui/ItemRules/ItemRulesTable.tsxrename to apps/erp/app/modules/customRules/ui/CustomRulesTable.tsxindex 0b2f771caa..a286684526 100644--- a/apps/erp/app/modules/items/ui/ItemRules/ItemRulesTable.tsx+++ b/apps/erp/app/modules/customRules/ui/CustomRulesTable.tsx@@ -13,11 +13,13 @@ import { useCustomColumns } from "~/hooks/useCustomColumns";import { path } from "~/utils/path";import SurfaceChips from "./SurfaceChips";-type ItemRuleRowView = {+type CustomRuleRowView = {id: string;name: string;+ targetType: "item" | "storageUnit" | "workCenter";severity: "error" | "warn";active: boolean;+ appliesToAll: boolean;description?: string | null;message: string;updatedAt?: string | null;@@ -26,17 +28,23 @@ type ItemRuleRowView = {surfaces?: TransactionSurface[];};-type ItemRulesTableProps = {- data: ItemRuleRowView[];+const TARGET_TYPE_LABELS = {+ item: "Item",+ storageUnit: "Storage unit",+ workCenter: "Work center"+} as const;++type CustomRulesTableProps = {+ data: CustomRuleRowView[];count: number;};-const ItemRulesTable = memo(({ data, count }: ItemRulesTableProps) => {+const CustomRulesTable = memo(({ data, count }: CustomRulesTableProps) => {const { t } = useLingui();const [params] = useUrlParams();const navigate = useNavigate();const permissions = usePermissions();- const customColumns = useCustomColumns<ItemRuleRowView>("itemRule");+ const customColumns = useCustomColumns<CustomRuleRowView>("customRule");const rows = useMemo(() => data, [data]);@@ -47,13 +55,22 @@ const ItemRulesTable = memo(({ data, count }: ItemRulesTableProps) => {header: t`Name`,cell: ({ row }) => (<Hyperlink- to={`${path.to.itemRule(row.original.id)}?${params.toString()}`}+ to={`${path.to.customRule(row.original.id)}?${params.toString()}`}><Enumerable value={row.original.name} /></Hyperlink>),meta: { icon: <LuShieldCheck /> }},+ {+ accessorKey: "targetType",+ header: t`Target`,+ cell: ({ row }) => (+ <Badge variant="secondary">+ {TARGET_TYPE_LABELS[row.original.targetType]}+ </Badge>+ )+ },{accessorKey: "severity",header: t`Severity`,@@ -71,7 +88,12 @@ const ItemRulesTable = memo(({ data, count }: ItemRulesTableProps) => {{accessorKey: "surfaces",header: t`Surfaces`,- cell: ({ row }) => <SurfaceChips surfaces={row.original.surfaces} />+ cell: ({ row }) => (+ <SurfaceChips+ surfaces={row.original.surfaces}+ targetType={row.original.targetType}+ />+ )},{accessorKey: "active",@@ -104,19 +126,21 @@ const ItemRulesTable = memo(({ data, count }: ItemRulesTableProps) => {(row: (typeof rows)[number]) => (<><MenuItem- disabled={!permissions.can("update", "parts")}+ disabled={!permissions.can("update", "settings")}onClick={() => {- navigate(`${path.to.itemRule(row.id)}?${params.toString()}`);+ navigate(`${path.to.customRule(row.id)}?${params.toString()}`);}}><MenuIcon icon={<LuPencil />} /><Trans>Edit Rule</Trans></MenuItem><MenuItem- disabled={!permissions.can("delete", "parts")}+ disabled={!permissions.can("delete", "settings")}destructiveonClick={() => {- navigate(`${path.to.deleteItemRule(row.id)}?${params.toString()}`);+ navigate(+ `${path.to.deleteCustomRule(row.id)}?${params.toString()}`+ );}}><MenuIcon icon={<LuTrash />} />@@ -133,18 +157,18 @@ const ItemRulesTable = memo(({ data, count }: ItemRulesTableProps) => {columns={columns}count={count}primaryAction={- permissions.can("create", "parts") && (+ permissions.can("create", "settings") && (<Newlabel={t`Rule`}- to={`${path.to.newItemRule}?${params.toString()}`}+ to={`${path.to.newCustomRule}?${params.toString()}`}/>)}renderContextMenu={renderContextMenu}- title={t`Item Rules`}+ title={t`Custom Rules`}/>);});-ItemRulesTable.displayName = "ItemRulesTable";-export default ItemRulesTable;+CustomRulesTable.displayName = "CustomRulesTable";+export default CustomRulesTable;diff --git a/apps/erp/app/modules/items/ui/ItemRules/ItemRulesUpgradeOverlay.tsx b/apps/erp/app/modules/customRules/ui/CustomRulesUpgradeOverlay.tsxsimilarity index 85%rename from apps/erp/app/modules/items/ui/ItemRules/ItemRulesUpgradeOverlay.tsxrename to apps/erp/app/modules/customRules/ui/CustomRulesUpgradeOverlay.tsxindex 7c02f760d1..64a2dbf90d 100644--- a/apps/erp/app/modules/items/ui/ItemRules/ItemRulesUpgradeOverlay.tsx+++ b/apps/erp/app/modules/customRules/ui/CustomRulesUpgradeOverlay.tsx@@ -11,14 +11,16 @@ import {UpgradeOverlayTitle,UpgradeOverlayUpgradeButton} from "~/components/UpgradeOverlay";-import ItemRulesTable from "./ItemRulesTable";+import CustomRulesTable from "./CustomRulesTable";const mockRules = [{id: "mock-1",name: "Require lot number on receipt",+ targetType: "item" as const,severity: "error" as const,active: true,+ appliesToAll: false,description: "Block receiving when lot number is missing.",message: "Lot number is required for this item on receipt.",updatedAt: "2026-05-04T10:00:00Z",@@ -29,8 +31,10 @@ const mockRules = [{id: "mock-2",name: "Warn on negative adjustment",+ targetType: "item" as const,severity: "warn" as const,active: true,+ appliesToAll: true,description: "Flag inventory adjustments that take quantity below zero.",message: "Adjustment will result in negative on-hand quantity.",updatedAt: "2026-04-29T14:22:00Z",@@ -41,8 +45,10 @@ const mockRules = [{id: "mock-3",name: "Shipment requires serial",+ targetType: "item" as const,severity: "error" as const,active: true,+ appliesToAll: false,description: "Block shipment when serial number is not captured.",message: "Serial number is required on shipment.",updatedAt: "2026-04-21T09:15:00Z",@@ -53,8 +59,10 @@ const mockRules = [{id: "mock-4",name: "Stock transfer between plants",+ targetType: "item" as const,severity: "warn" as const,active: false,+ appliesToAll: false,description: "Warn when transferring between non-default plants.",message: "Cross-plant transfer requires manager approval.",updatedAt: "2026-03-12T11:45:00Z",@@ -64,11 +72,11 @@ const mockRules = [}];-export default function ItemRulesUpgradeOverlay() {+export default function CustomRulesUpgradeOverlay() {return (<UpgradeOverlay><UpgradeOverlayPreview>- <ItemRulesTable data={mockRules as never} count={mockRules.length} />+ <CustomRulesTable data={mockRules as never} count={mockRules.length} /></UpgradeOverlayPreview><UpgradeOverlayCard><UpgradeOverlayIcon>@@ -76,7 +84,7 @@ export default function ItemRulesUpgradeOverlay() {</UpgradeOverlayIcon><UpgradeOverlayContent><UpgradeOverlayTitle>- <Trans>Item Rules</Trans>+ <Trans>Custom Rules</Trans></UpgradeOverlayTitle><UpgradeOverlayDescription><Trans>diff --git a/apps/erp/app/modules/customRules/ui/FieldCombobox.tsx b/apps/erp/app/modules/customRules/ui/FieldCombobox.tsxnew file mode 100644index 0000000000..68392c7424--- /dev/null+++ b/apps/erp/app/modules/customRules/ui/FieldCombobox.tsx@@ -0,0 +1,244 @@+import {+ Command,+ CommandEmpty,+ CommandGroup,+ CommandInput,+ CommandItem,+ CommandList,+ CommandSeparator,+ CommandTrigger,+ cn,+ Popover,+ PopoverContent,+ PopoverTrigger,+ Tooltip,+ TooltipContent,+ TooltipProvider,+ TooltipTrigger+} from "@carbon/react";+import {+ FIELD_REGISTRY,+ type FieldDef,+ getFieldDef,+ getFieldsForTargetType+} from "@carbon/utils";+import { useLingui } from "@lingui/react/macro";+import { useMemo, useState } from "react";+import {+ LuBox,+ LuCheck,+ LuChevronDown,+ LuInfo,+ LuPackage,+ LuReceipt+} from "react-icons/lu";++const CONTEXT: Record<+ FieldDef["context"],+ { label: string; icon: JSX.Element }+> = {+ item: { label: "Item", icon: <LuPackage className="h-3.5 w-3.5" /> },+ storage: { label: "Storage unit", icon: <LuBox className="h-3.5 w-3.5" /> },+ workCenter: {+ label: "Work center",+ icon: <LuBox className="h-3.5 w-3.5" />+ },+ operation: {+ label: "Operation",+ icon: <LuReceipt className="h-3.5 w-3.5" />+ },+ transaction: {+ label: "Transaction",+ icon: <LuReceipt className="h-3.5 w-3.5" />+ }+};++const CONTEXT_ORDER: FieldDef["context"][] = [+ "item",+ "storage",+ "workCenter",+ "operation",+ "transaction"+];++type FieldComboboxProps = {+ value: string;+ onChange: (path: string) => void;+ placeholder?: string;+ className?: string;+ targetType?: "item" | "storageUnit" | "workCenter";+};++export default function FieldCombobox({+ value,+ onChange,+ placeholder,+ className,+ targetType+}: FieldComboboxProps) {+ const { t } = useLingui();+ const [open, setOpen] = useState(false);++ const grouped = useMemo(() => {+ const map = new Map<FieldDef["context"], FieldDef[]>();+ for (const ctx of CONTEXT_ORDER) map.set(ctx, []);+ const pool = targetType+ ? getFieldsForTargetType(targetType)+ : FIELD_REGISTRY;+ for (const f of pool) map.get(f.context)!.push(f);+ return map;+ }, [targetType]);++ const selected = useMemo(() => getFieldDef(value), [value]);+ const ctx = selected ? CONTEXT[selected.context] : undefined;++ return (+ <Popover open={open} onOpenChange={setOpen}>+ <PopoverTrigger asChild>+ <CommandTrigger+ size="md"+ role="combobox"+ aria-expanded={open}+ icon={<LuChevronDown className="h-4 w-4 shrink-0 opacity-50" />}+ className={cn(+ "min-w-[180px] w-full",+ !selected && "text-muted-foreground",+ className+ )}+ onClick={() => setOpen(true)}+ >+ {selected && ctx ? (+ <div className="flex min-w-0 flex-1 items-center gap-2 text-left">+ <div+ className="flex h-5 w-5 shrink-0 items-center justify-center rounded bg-muted text-muted-foreground"+ title={ctx.label}+ role="img"+ aria-label={ctx.label}+ >+ {ctx.icon}+ </div>+ <div className="truncate text-foreground">{selected.label}</div>+ {selected.description && (+ <TooltipProvider delayDuration={200}>+ <Tooltip>+ <TooltipTrigger asChild>+ <span+ role="button"+ tabIndex={0}+ aria-label={t`Field info`}+ className="ml-0.5 inline-flex shrink-0 cursor-help items-center justify-center rounded text-muted-foreground hover:text-foreground"+ onPointerDown={(e) => e.stopPropagation()}+ onClick={(e) => e.stopPropagation()}+ onKeyDown={(e) => {+ if (e.key === "Enter" || e.key === " ") {+ e.preventDefault();+ e.stopPropagation();+ }+ }}+ >+ <LuInfo className="h-3.5 w-3.5" />+ </span>+ </TooltipTrigger>+ <TooltipContent+ side="top"+ align="start"+ sideOffset={6}+ className="max-w-[32ch] text-xs leading-snug"+ >+ {selected.description}+ </TooltipContent>+ </Tooltip>+ </TooltipProvider>+ )}+ </div>+ ) : (+ <div className="truncate">{placeholder ?? t`Select field`}</div>+ )}+ </CommandTrigger>+ </PopoverTrigger>+ <PopoverContent+ align="start"+ onWheel={(e) => e.stopPropagation()}+ onTouchMove={(e) => e.stopPropagation()}+ className="w-[var(--radix-popover-trigger-width)] min-w-[320px] p-0"+ >+ <Command>+ <CommandInput placeholder={t`Search fields...`} className="h-10" />+ <CommandList+ className="max-h-[320px] overflow-y-auto overscroll-contain"+ onWheel={(e) => e.stopPropagation()}+ >+ <CommandEmpty>{t`No fields found.`}</CommandEmpty>+ {(() => {+ const visibleCtx = CONTEXT_ORDER.filter(+ (k) => (grouped.get(k) ?? []).length > 0+ );+ return visibleCtx.map((ctxKey, gi) => {+ const fields = grouped.get(ctxKey) ?? [];+ const meta = CONTEXT[ctxKey];+ return (+ <div key={ctxKey}>+ {gi > 0 && <CommandSeparator />}+ <CommandGroup+ heading={+ <span className="flex items-center gap-1.5 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground">+ {meta.icon}+ {meta.label}+ </span>+ }+ >+ {fields.map((f) => {+ const item = (+ <CommandItem+ key={f.path}+ value={`${meta.label} ${f.label} ${f.path} ${f.description ?? ""}`}+ onSelect={() => {+ onChange(f.path);+ setOpen(false);+ }}+ className="flex items-center gap-2 px-2 py-2"+ >+ <span className="flex min-w-0 flex-1 flex-col">+ <span className="truncate text-sm font-medium">+ {f.label}+ </span>+ <span className="truncate text-xs text-muted-foreground">+ {f.path}+ </span>+ </span>+ <LuCheck+ className={cn(+ "h-4 w-4 shrink-0",+ value === f.path ? "opacity-100" : "opacity-0"+ )}+ />+ </CommandItem>+ );+ if (!f.description) return item;+ return (+ <TooltipProvider key={f.path} delayDuration={300}>+ <Tooltip>+ <TooltipTrigger asChild>{item}</TooltipTrigger>+ <TooltipContent+ side="right"+ align="start"+ sideOffset={8}+ className="max-w-[28ch] text-xs leading-snug"+ >+ {f.description}+ </TooltipContent>+ </Tooltip>+ </TooltipProvider>+ );+ })}+ </CommandGroup>+ </div>+ );+ });+ })()}+ </CommandList>+ </Command>+ </PopoverContent>+ </Popover>+ );+}diff --git a/apps/erp/app/modules/items/ui/ItemRules/MessageWithTokens.tsx b/apps/erp/app/modules/customRules/ui/MessageWithTokens.tsxsimilarity index 84%rename from apps/erp/app/modules/items/ui/ItemRules/MessageWithTokens.tsxrename to apps/erp/app/modules/customRules/ui/MessageWithTokens.tsxindex b147637d76..7ebd53eb3f 100644--- a/apps/erp/app/modules/items/ui/ItemRules/MessageWithTokens.tsx+++ b/apps/erp/app/modules/customRules/ui/MessageWithTokens.tsx@@ -19,6 +19,7 @@ import {FIELD_REGISTRY,type FieldDef,getFieldDef,+ getFieldsForTargetType,type TransactionSurface} from "@carbon/utils";import { Trans, useLingui } from "@lingui/react/macro";@@ -41,6 +42,11 @@ type MessageWithTokensProps = {* toggles surface scope without prop drilling.*/surfacesFieldName?: string;+ /**+ * Rule's targetType — scopes which fields appear in the token dropdown+ * so e.g. workCenter rules don't list `item.replenishmentSystem`.+ */+ targetType?: "item" | "storageUnit" | "workCenter";};type TokenItem = { token: string; description: string };@@ -56,12 +62,20 @@ const CTX_KEYS_BY_SURFACE: Record<TransactionSurface, FieldDef["context"][]> = {shipment: ["storage", "transaction"],stockTransfer: ["storage", "transaction"],warehouseTransfer: ["storage", "transaction"],- inventoryAdjustment: ["storage", "transaction"]+ inventoryAdjustment: ["storage", "transaction"],+ place: ["storage", "transaction"],+ pick: ["storage", "transaction"],+ operationStart: ["workCenter", "operation", "transaction"],+ operationFinish: ["workCenter", "operation", "transaction"],+ materialIssue: ["workCenter", "operation", "transaction"],+ materialReceive: ["workCenter", "operation", "transaction"]};const CONTEXT_LABELS: Record<FieldDef["context"], string> = {item: "Item",- storage: "Storage",+ storage: "Storage unit",+ workCenter: "Work center",+ operation: "Operation",transaction: "Transaction"};@@ -72,6 +86,8 @@ const CONTEXT_LABELS: Record<FieldDef["context"], string> = {const FIELDS_BY_CTX: Record<FieldDef["context"], FieldDef[]> = {item: [],storage: [],+ workCenter: [],+ operation: [],transaction: []};for (const f of FIELD_REGISTRY) FIELDS_BY_CTX[f.context].push(f);@@ -86,7 +102,7 @@ const ORDERED_CTX: FieldDef["context"][] = ["storage", "transaction"];// reallocate the icon element (rendering-hoist-jsx).const BRACES_ICON = <LuBraces />;-// Mirror of the runtime `TOKEN_RE` in packages/utils/src/itemRules.ts so the+// Mirror of the runtime `TOKEN_RE` in packages/utils/src/customRules.ts so the// editor highlights exactly what `interpolateMessage` will substitute — no// false greens, no missed reds. Inlined rather than re-exported to avoid a// UI → runtime import cycle.@@ -110,7 +126,8 @@ export default function MessageWithTokens({name,label,conditions,- surfacesFieldName = "surfaces"+ surfacesFieldName = "surfaces",+ targetType}: MessageWithTokensProps) {const { t } = useLingui();const textareaRef = useRef<HTMLTextAreaElement | null>(null);@@ -171,6 +188,20 @@ export default function MessageWithTokens({const groups = useMemo<TokenGroup[]>(() => {const out: TokenGroup[] = [];const conds = conditions ?? [];+ // Field pool scoped to the rule's targetType; falls back to full registry+ // when not provided (legacy usage).+ const scopedFieldsByCtx: Partial<Record<FieldDef["context"], FieldDef[]>> =+ {};+ if (targetType) {+ const pool = getFieldsForTargetType(targetType);+ for (const f of pool) {+ const bucket = scopedFieldsByCtx[f.context];+ if (bucket) bucket.push(f);+ else scopedFieldsByCtx[f.context] = [f];+ }+ }+ const fieldsForCtx = (ctx: FieldDef["context"]): FieldDef[] =>+ targetType ? (scopedFieldsByCtx[ctx] ?? []) : FIELDS_BY_CTX[ctx];// 1. Per-condition tokens.conds.forEach((c, i) => {@@ -194,18 +225,20 @@ export default function MessageWithTokens({});});- // 2. Item ctx tokens — always populated regardless of surface.- // Includes display-only tokens (`item.id`, `item.name`) on top of- // the predicate-eligible fields from `FIELD_REGISTRY`.- const itemTokens: TokenItem[] = [- // `item.id` is the readable id (e.g. "PART-001"), not the UUID — see- // `evaluateLinesForSurface` where the ctx is normalised.- { token: "item.id", description: "Readable ID (e.g. PART-001)" },- { token: "item.name", description: "Display name" }- ];- for (const f of FIELDS_BY_CTX.item)- itemTokens.push({ token: f.path, description: f.label });- out.push({ heading: CONTEXT_LABELS.item, tokens: itemTokens });+ // 2. Item ctx tokens — populated when item context is in scope. For+ // workCenter rules the item is only available via `operation.itemId`,+ // so suppress the item header entirely.+ if (!targetType || targetType !== "workCenter") {+ const itemTokens: TokenItem[] = [+ // `item.id` is readable id (e.g. "PART-001"), not UUID — see+ // `evaluateLinesForSurface` where ctx is normalised.+ { token: "item.id", description: "Readable ID (e.g. PART-001)" },+ { token: "item.name", description: "Display name" }+ ];+ for (const f of fieldsForCtx("item"))+ itemTokens.push({ token: f.path, description: f.label });+ out.push({ heading: CONTEXT_LABELS.item, tokens: itemTokens });+ }// 3. Surface-relevant ctx tokens. Compute the union of ctx keys// populated by any selected surface; hide groups no surface uses.@@ -217,7 +250,7 @@ export default function MessageWithTokens({}for (const ctxKey of ORDERED_CTX) {if (!allowedCtx.has(ctxKey)) continue;- const fields = FIELDS_BY_CTX[ctxKey];+ const fields = fieldsForCtx(ctxKey);if (fields.length === 0) continue;const tokens: TokenItem[] = [];for (const f of fields)@@ -226,7 +259,7 @@ export default function MessageWithTokens({}return out;- }, [conditions, surfaces]);+ }, [conditions, surfaces, targetType]);const knownTokens = useMemo(() => {const set = new Set<string>();diff --git a/apps/erp/app/modules/items/ui/ItemRules/MultiValueCombobox.tsx b/apps/erp/app/modules/customRules/ui/MultiValueCombobox.tsxsimilarity index 100%rename from apps/erp/app/modules/items/ui/ItemRules/MultiValueCombobox.tsxrename to apps/erp/app/modules/customRules/ui/MultiValueCombobox.tsxdiff --git a/apps/erp/app/modules/items/ui/ItemRules/OperatorCombobox.tsx b/apps/erp/app/modules/customRules/ui/OperatorCombobox.tsxsimilarity index 100%rename from apps/erp/app/modules/items/ui/ItemRules/OperatorCombobox.tsxrename to apps/erp/app/modules/customRules/ui/OperatorCombobox.tsxdiff --git a/apps/erp/app/modules/customRules/ui/RuleAssignmentsList.tsx b/apps/erp/app/modules/customRules/ui/RuleAssignmentsList.tsxnew file mode 100644index 0000000000..4f21f7666c--- /dev/null+++ b/apps/erp/app/modules/customRules/ui/RuleAssignmentsList.tsx@@ -0,0 +1,469 @@+import {+ Badge,+ Button,+ Card,+ CardContent,+ CardDescription,+ CardHeader,+ CardTitle,+ Combobox,+ HStack,+ IconButton,+ Status,+ Table,+ Tbody,+ Td,+ Th,+ Thead,+ Tr+} from "@carbon/react";+import type { TransactionSurface } from "@carbon/utils";+import { Trans, useLingui } from "@lingui/react/macro";+import { useMemo } from "react";+import { LuLibrary, LuPlus, LuShieldCheck, LuTrash } from "react-icons/lu";+import { Form, Link, useFetcher } from "react-router";+import { Hyperlink } from "~/components";+import {+ UpgradeOverlayActions,+ UpgradeOverlayContent,+ UpgradeOverlayDescription,+ UpgradeOverlayIcon,+ UpgradeOverlayTitle,+ UpgradeOverlayUpgradeButton+} from "~/components/UpgradeOverlay";+import { usePermissions } from "~/hooks";+import { usePlanGate } from "~/hooks/usePlanGate";+import { path } from "~/utils/path";+import SurfaceChips from "./SurfaceChips";++type AssignedRule = {+ ruleId: string;+ rule: {+ id: string;+ name: string;+ severity: "error" | "warn";+ message: string;+ active: boolean;+ surfaces?: TransactionSurface[];+ };+ /**+ * When set, this row was inherited from an ancestor storage unit. UI+ * shows an "Inherited from …" badge and disables the unassign action —+ * the user must go to the parent unit's drawer to remove it.+ */+ inheritedFromId?: string | null;+ inheritedFromName?: string | null;+};++type LibraryRule = {+ id: string;+ name: string;+ severity: "error" | "warn";+ active: boolean;+};++type TargetType = "item" | "storageUnit" | "workCenter";++type RuleAssignmentsListProps = {+ targetType: TargetType;+ targetId: string;+ assignments: AssignedRule[];+ library: LibraryRule[];+ /**+ * `card` (default) — full Card chrome with shadow + border. Use on+ * standalone tab pages (item details, etc).+ * `flat` — no Card wrapper; renders inside a ModalDrawer's body where the+ * drawer already provides the surface.+ */+ variant?: "card" | "flat";+};++// Target-specific copy. Keeps the card description grounded in the right+// nouns and surface list per rule type.+const TARGET_COPY: Record<TargetType, { noun: string; surfaceBlurb: string }> =+ {+ item: {+ noun: "item",+ surfaceBlurb: "receipts, shipments, transfers and inventory adjustments"+ },+ storageUnit: {+ noun: "storage unit",+ surfaceBlurb: "place, pick and transfers"+ },+ workCenter: {+ noun: "work center",+ surfaceBlurb: "operation start/finish and material moves"+ }+ };++const ASSIGN_PATH = {+ item: path.to.customRuleAssignItem,+ storageUnit: path.to.customRuleAssignStorageUnit,+ workCenter: path.to.customRuleAssignWorkCenter+};++const UNASSIGN_PATH = {+ item: path.to.customRuleUnassignItem,+ storageUnit: path.to.customRuleUnassignStorageUnit,+ workCenter: path.to.customRuleUnassignWorkCenter+};++const PERM_MODULE: Record<TargetType, "parts" | "inventory" | "resources"> = {+ item: "parts",+ storageUnit: "inventory",+ workCenter: "resources"+};++export default function RuleAssignmentsList({+ targetType,+ targetId,+ assignments,+ library,+ variant = "card"+}: RuleAssignmentsListProps) {+ const { t } = useLingui();+ const permissions = usePermissions();+ const fetcher = useFetcher();+ const { isGated } = usePlanGate({ feature: "CUSTOM_RULES" });+ const module = PERM_MODULE[targetType];+ const canCreate = permissions.can("create", module);+ const canDelete = permissions.can("delete", module);+ const targetCopy = TARGET_COPY[targetType];+ const description = `Enforce constraints on ${targetCopy.surfaceBlurb} for this ${targetCopy.noun}.`;++ const assignedSet = useMemo(+ () => new Set(assignments.map((a) => a.ruleId)),+ [assignments]+ );++ const available = useMemo(+ () => library.filter((r) => r.active && !assignedSet.has(r.id)),+ [library, assignedSet]+ );++ const availableOptions = useMemo(+ () => available.map((r) => ({ value: r.id, label: r.name })),+ [available]+ );++ const handleAssign = (ruleId: string) => {+ if (!ruleId) return;+ const fd = new FormData();+ fd.set("ruleId", ruleId);+ fetcher.submit(fd, {+ method: "post",+ action: ASSIGN_PATH[targetType](targetId)+ });+ };++ const isEmpty = assignments.length === 0;++ const header = (+ <div className="flex items-start justify-between gap-4">+ <div className="min-w-0 flex-1">+ <div className="flex items-center gap-2">+ <h2 className="text-base font-semibold">+ <Trans>Rules</Trans>+ </h2>+ {!isEmpty && (+ <span className="text-sm font-normal text-muted-foreground tabular-nums">+ {assignments.length}+ </span>+ )}+ </div>+ <p className="mt-1 max-w-[64ch] text-sm text-muted-foreground text-pretty">+ {description}+ </p>+ </div>+ {!isEmpty && canCreate && (+ <div className="flex shrink-0 items-center gap-2">+ {availableOptions.length > 0 && (+ <Combobox+ size="md"+ value=""+ options={availableOptions}+ onChange={handleAssign}+ placeholder={t`Add from library…`}+ className="w-[200px]"+ />+ )}+ <Button variant="primary" leftIcon={<LuPlus />} asChild>+ <Link to={`${path.to.newCustomRule}?targetType=${targetType}`}>+ <Trans>Add rule</Trans>+ </Link>+ </Button>+ </div>+ )}+ </div>+ );++ if (isGated) {+ const gatedBody = (+ <div className="flex flex-col items-center justify-center gap-4 py-10 text-center">+ <UpgradeOverlayIcon>+ <LuShieldCheck className="size-6 text-muted-foreground" />+ </UpgradeOverlayIcon>+ <UpgradeOverlayContent>+ <UpgradeOverlayTitle>+ <Trans>Upgrade to unlock {targetCopy.noun} rules</Trans>+ </UpgradeOverlayTitle>+ <UpgradeOverlayDescription>{description}</UpgradeOverlayDescription>+ </UpgradeOverlayContent>+ <UpgradeOverlayActions>+ <UpgradeOverlayUpgradeButton />+ </UpgradeOverlayActions>+ </div>+ );+ if (variant === "flat") {+ return (+ <div className="flex flex-col gap-4">+ {header}+ {gatedBody}+ </div>+ );+ }+ return (+ <Card className="flex-grow">+ <CardHeader>+ <CardTitle>+ <Trans>Rules</Trans>+ </CardTitle>+ <CardDescription>{description}</CardDescription>+ </CardHeader>+ <CardContent>{gatedBody}</CardContent>+ </Card>+ );+ }++ const body = isEmpty ? (+ <EmptyState+ availableOptions={availableOptions}+ canCreate={canCreate}+ onAssign={handleAssign}+ targetNoun={targetCopy.noun}+ />+ ) : (+ <Table>+ <Thead>+ <Tr>+ <Th>+ <Trans>Name</Trans>+ </Th>+ <Th>+ <Trans>Severity</Trans>+ </Th>+ <Th>+ <Trans>Surfaces</Trans>+ </Th>+ <Th>+ <Trans>Status</Trans>+ </Th>+ {variant === "card" && (+ <Th>+ <Trans>Message</Trans>+ </Th>+ )}+ <Th />+ </Tr>+ </Thead>+ <Tbody>+ {assignments.map((a) => {+ const isBroadcast = a.inheritedFromId === "__all__";+ const isInherited = !!a.inheritedFromId && !isBroadcast;+ const isLocked = isInherited || isBroadcast;+ return (+ <Tr key={a.ruleId}>+ <Td className="whitespace-nowrap">+ <HStack className="gap-2 items-center flex-wrap">+ <Hyperlink to={path.to.customRule(a.ruleId)}>+ <HStack className="gap-2 items-center">+ <LuShieldCheck className="text-muted-foreground shrink-0" />+ <span>{a.rule.name}</span>+ </HStack>+ </Hyperlink>+ {isBroadcast && (+ <Badge+ variant="outline"+ className="text-[10px] uppercase tracking-wide"+ >+ <Trans>Applies to all</Trans>+ </Badge>+ )}+ {isInherited && (+ <Link+ to={path.to.storageUnitRules(a.inheritedFromId!)}+ className="no-underline"+ >+ <Badge+ variant="outline"+ className="cursor-pointer text-[10px] uppercase tracking-wide"+ >+ <Trans>Inherited from</Trans>{" "}+ {a.inheritedFromName ?? "parent"}+ </Badge>+ </Link>+ )}+ </HStack>+ </Td>+ <Td>+ {a.rule.severity === "error" ? (+ <Badge variant="red">+ <Trans>Error</Trans>+ </Badge>+ ) : (+ <Badge variant="yellow">+ <Trans>Warning</Trans>+ </Badge>+ )}+ </Td>+ <Td>+ <SurfaceChips+ surfaces={a.rule.surfaces}+ targetType={targetType}+ />+ </Td>+ <Td>+ {a.rule.active ? (+ <Status color="green">+ <Trans>Active</Trans>+ </Status>+ ) : (+ <Status color="gray">+ <Trans>Inactive</Trans>+ </Status>+ )}+ </Td>+ {variant === "card" && (+ <Td className="w-full max-w-0">+ <p className="text-muted-foreground truncate max-w-xl">+ {a.rule.message}+ </p>+ </Td>+ )}+ <Td className="text-right">+ <Form+ method="post"+ action={UNASSIGN_PATH[targetType](targetId, a.ruleId)}+ >+ <IconButton+ type="submit"+ icon={<LuTrash />}+ aria-label={+ isBroadcast+ ? t`Edit the rule to remove the "Applies to all" flag`+ : isInherited+ ? t`Unassign from parent unit to remove`+ : t`Unassign rule`+ }+ title={+ isBroadcast+ ? t`Edit the rule to remove the "Applies to all" flag`+ : isInherited+ ? t`Unassign from parent unit to remove`+ : undefined+ }+ variant="ghost"+ size="sm"+ isDisabled={!canDelete || isLocked}+ />+ </Form>+ </Td>+ </Tr>+ );+ })}+ </Tbody>+ </Table>+ );++ if (variant === "flat") {+ return (+ <div className="flex flex-col gap-4">+ {header}+ {body}+ </div>+ );+ }++ return (+ <Card className="flex-grow">+ <CardHeader>{header}</CardHeader>+ <CardContent>{body}</CardContent>+ </Card>+ );+}++type EmptyStateProps = {+ availableOptions: { value: string; label: string }[];+ canCreate: boolean;+ onAssign: (ruleId: string) => void;+ targetNoun: string;+};++function EmptyState({+ availableOptions,+ canCreate,+ onAssign,+ targetNoun+}: EmptyStateProps) {+ const { t } = useLingui();+ return (+ <div className="flex flex-col items-center justify-center gap-5 py-10 text-center">+ <div className="flex size-14 items-center justify-center rounded-full bg-muted">+ <LuShieldCheck className="size-6 text-muted-foreground" />+ </div>++ <div className="flex flex-col gap-1.5 max-w-md">+ <p className="text-base font-medium">+ <Trans>No rules assigned</Trans>+ </p>+ <p className="text-sm text-muted-foreground">+ Pick an existing rule from the library or create a new one to start+ enforcing constraints on this {targetNoun}.+ </p>+ </div>++ {canCreate && (+ <HStack className="gap-2 flex-wrap justify-center pt-1">+ {availableOptions.length > 0 ? (+ <>+ <Combobox+ value=""+ options={availableOptions}+ onChange={onAssign}+ placeholder={t`Add from library…`}+ />+ <Button+ asChild+ variant="secondary"+ size="sm"+ leftIcon={<LuPlus />}+ >+ <Link to={path.to.newCustomRule}>+ <Trans>Create new rule</Trans>+ </Link>+ </Button>+ </>+ ) : (+ <>+ <Button+ asChild+ variant="secondary"+ size="sm"+ leftIcon={<LuLibrary />}+ >+ <Link to={path.to.customRules}>+ <Trans>Browse library</Trans>+ </Link>+ </Button>+ <Button asChild size="sm" leftIcon={<LuPlus />}>+ <Link to={path.to.newCustomRule}>+ <Trans>Create new rule</Trans>+ </Link>+ </Button>+ </>+ )}+ </HStack>+ )}+ </div>+ );+}diff --git a/apps/erp/app/modules/items/ui/ItemRules/RuleBuilder.tsx b/apps/erp/app/modules/customRules/ui/RuleBuilder.tsxsimilarity index 82%rename from apps/erp/app/modules/items/ui/ItemRules/RuleBuilder.tsxrename to apps/erp/app/modules/customRules/ui/RuleBuilder.tsxindex a69e650b00..d67e6723d1 100644--- a/apps/erp/app/modules/items/ui/ItemRules/RuleBuilder.tsx+++ b/apps/erp/app/modules/customRules/ui/RuleBuilder.tsx@@ -9,7 +9,10 @@ import {type Condition,type ConditionAst,FIELD_REGISTRY,- type MatchKind+ getFieldsForTargetType,+ type MatchKind,+ type TargetType,+ type TransactionSurface} from "@carbon/utils";import { Trans, useLingui } from "@lingui/react/macro";import { useCallback, useEffect, useMemo, useState } from "react";@@ -21,6 +24,13 @@ import { useValueOptions } from "./useValueOptions";type RuleBuilderProps = {name: string;initial?: ConditionAst;+ targetType?: TargetType;+ /**+ * Surfaces the rule is currently configured to fire on. Forwarded to each+ * ConditionRow so the per-surface notes panel filters to the surfaces this+ * rule actually triggers — not every surface valid for the targetType.+ */+ surfaces?: TransactionSurface[];/*** Notifies the parent of every condition-list change so siblings (e.g.* `MessageWithTokens`) can offer per-condition tokens that resolve to@@ -29,15 +39,16 @@ type RuleBuilderProps = {onConditionsChange?: (conditions: Condition[]) => void;};-const emptyCondition = (): Condition => ({- field: FIELD_REGISTRY[0]?.path ?? "",- op: "eq",- value: undefined-});+const emptyConditionFor = (targetType: TargetType | undefined): Condition => {+ const pool = targetType ? getFieldsForTargetType(targetType) : FIELD_REGISTRY;+ return { field: pool[0]?.path ?? "", op: "eq", value: undefined };+};export default function RuleBuilder({name,initial,+ targetType,+ surfaces,onConditionsChange}: RuleBuilderProps) {const { t } = useLingui();@@ -67,7 +78,9 @@ export default function RuleBuilder({[t]);const [conditions, setConditions] = useState<Condition[]>(- initial?.conditions?.length ? initial.conditions : [emptyCondition()]+ initial?.conditions?.length+ ? initial.conditions+ : [emptyConditionFor(targetType)]);const optionsByLoader = useValueOptions();@@ -94,8 +107,8 @@ export default function RuleBuilder({}, []);const handleAdd = useCallback(() => {- setConditions((prev) => [...prev, emptyCondition()]);- }, []);+ setConditions((prev) => [...prev, emptyConditionFor(targetType)]);+ }, [targetType]);const ast: ConditionAst = { kind, conditions };@@ -141,6 +154,8 @@ export default function RuleBuilder({onChange={handleChange}onRemove={handleRemove}optionsByLoader={optionsByLoader}+ targetType={targetType}+ surfaces={surfaces}/>))}</div>diff --git a/apps/erp/app/modules/items/ui/ItemRules/SeveritySelect.tsx b/apps/erp/app/modules/customRules/ui/SeveritySelect.tsxsimilarity index 100%rename from apps/erp/app/modules/items/ui/ItemRules/SeveritySelect.tsxrename to apps/erp/app/modules/customRules/ui/SeveritySelect.tsxdiff --git a/apps/erp/app/modules/items/ui/ItemRules/SurfaceChips.tsx b/apps/erp/app/modules/customRules/ui/SurfaceChips.tsxsimilarity index 52%rename from apps/erp/app/modules/items/ui/ItemRules/SurfaceChips.tsxrename to apps/erp/app/modules/customRules/ui/SurfaceChips.tsxindex 0c4386b875..32754cbb63 100644--- a/apps/erp/app/modules/items/ui/ItemRules/SurfaceChips.tsx+++ b/apps/erp/app/modules/customRules/ui/SurfaceChips.tsx@@ -1,5 +1,10 @@import { cn } from "@carbon/react";-import { TRANSACTION_SURFACES, type TransactionSurface } from "@carbon/utils";+import {+ SURFACES_BY_TARGET_TYPE,+ type TargetType,+ TRANSACTION_SURFACES,+ type TransactionSurface+} from "@carbon/utils";import {LuArrowRightLeft,LuPackage,@@ -25,36 +30,59 @@ const SURFACE_VISUALS: Record<inventoryAdjustment: {label: "Inventory adjustments",icon: <LuScale className="size-3.5" />+ },+ place: { label: "Place", icon: <LuPackage className="size-3.5" /> },+ pick: { label: "Pick", icon: <LuPackage className="size-3.5" /> },+ operationStart: {+ label: "Operation start",+ icon: <LuArrowRightLeft className="size-3.5" />+ },+ operationFinish: {+ label: "Operation finish",+ icon: <LuArrowRightLeft className="size-3.5" />+ },+ materialIssue: {+ label: "Material issue",+ icon: <LuScale className="size-3.5" />+ },+ materialReceive: {+ label: "Material receive",+ icon: <LuScale className="size-3.5" />}};type SurfaceChipsProps = {surfaces: TransactionSurface[] | null | undefined;+ /**+ * When provided, the chip rail renders only surfaces valid for this+ * targetType (instead of all 11). Inactive surfaces within the target's+ * set are still shown at reduced opacity so the operator can scan+ * subscribed vs. skipped at a glance.+ */+ targetType?: TargetType;className?: string;};-/**- * Compact icon-only chips for the 4 transaction surfaces. Active surfaces- * render at full opacity; inactive ones at 30% — letting an operator scan- * "this rule fires on receipts + shipments" without opening the rule.- *- * Each chip carries a `title` attribute for accessibility/native tooltip.- */export default function SurfaceChips({surfaces,+ targetType,className}: SurfaceChipsProps) {- // Empty / null → treat as "all surfaces" (legacy rules pre-migration).- const active = new Set(- surfaces && surfaces.length > 0 ? surfaces : TRANSACTION_SURFACES- );+ // Scope rendered set to the targetType's valid surfaces; fall back to all+ // when no targetType is supplied (callers that haven't been updated yet).+ const universe = targetType+ ? SURFACES_BY_TARGET_TYPE[targetType]+ : TRANSACTION_SURFACES;++ const active = new Set(surfaces && surfaces.length > 0 ? surfaces : universe);+return (<divclassName={cn("flex items-center gap-1 text-muted-foreground", className)}role="group"aria-label="Transaction surfaces">- {TRANSACTION_SURFACES.map((s) => {+ {universe.map((s) => {const meta = SURFACE_VISUALS[s];const isOn = active.has(s);return (diff --git a/apps/erp/app/modules/items/ui/ItemRules/SurfacesField.tsx b/apps/erp/app/modules/customRules/ui/SurfacesField.tsxsimilarity index 54%rename from apps/erp/app/modules/items/ui/ItemRules/SurfacesField.tsxrename to apps/erp/app/modules/customRules/ui/SurfacesField.tsxindex 115137703a..35f1645c31 100644--- a/apps/erp/app/modules/items/ui/ItemRules/SurfacesField.tsx+++ b/apps/erp/app/modules/customRules/ui/SurfacesField.tsx@@ -6,8 +6,13 @@ import {FormErrorMessage,FormLabel} from "@carbon/react";-import { TRANSACTION_SURFACES, type TransactionSurface } from "@carbon/utils";+import {+ SURFACES_BY_TARGET_TYPE,+ TRANSACTION_SURFACES,+ type TransactionSurface+} from "@carbon/utils";import { useLingui } from "@lingui/react/macro";+import { useEffect } from "react";import {LuArrowRightLeft,LuPackage,@@ -44,12 +49,49 @@ const SURFACE_META: Record<title: "Inventory adjustments",description: "Manual quantity edits at a storage unit",icon: <LuScale />+ },+ place: {+ title: "Place",+ description: "When stock is placed into a storage unit",+ icon: <LuPackage />+ },+ pick: {+ title: "Pick",+ description: "When stock is taken from a storage unit",+ icon: <LuPackage />+ },+ operationStart: {+ title: "Operation start",+ description: "When an operator starts a job operation",+ icon: <LuArrowRightLeft />+ },+ operationFinish: {+ title: "Operation finish",+ description: "When an operator completes a job operation",+ icon: <LuArrowRightLeft />+ },+ materialIssue: {+ title: "Material issue",+ description: "When material is consumed by an operation",+ icon: <LuScale />+ },+ materialReceive: {+ title: "Material receive",+ description: "When material is returned from an operation",+ icon: <LuScale />}};type SurfacesFieldProps = {name: string;label?: string;+ targetType?: "item" | "storageUnit" | "workCenter";+ /**+ * Mirrors the live `value` to the parent so siblings (e.g. ConditionRow's+ * per-surface notes panel) can filter against the rule's actual surfaces+ * rather than every surface valid for the targetType. Identity untracked.+ */+ onSurfacesChange?: (next: TransactionSurface[]) => void;};/**@@ -59,19 +101,39 @@ type SurfacesFieldProps = {* Soft-guards against unchecking the last selected surface (zod `min(1)` is* the server-side backstop).*/-export default function SurfacesField({ name, label }: SurfacesFieldProps) {+export default function SurfacesField({+ name,+ label,+ targetType,+ onSurfacesChange+}: SurfacesFieldProps) {const { t } = useLingui();const { error, isOptional } = useField(name);const [value, setValue] = useControlField<TransactionSurface[]>(name);const selected = value ?? [];- const options: ChoiceSelectOption<TransactionSurface>[] =- TRANSACTION_SURFACES.map((s) => ({+ // Mirror selection up to the form. Identity of `onSurfacesChange` not+ // tracked — parent wraps in `useCallback` if it needs stability.+ // biome-ignore lint/correctness/useExhaustiveDependencies: callback identity intentionally untracked+ useEffect(() => {+ onSurfacesChange?.(selected);+ }, [selected]);++ const allowed = targetType+ ? new Set<TransactionSurface>(SURFACES_BY_TARGET_TYPE[targetType])+ : null;+ const visibleSurfaces = allowed+ ? TRANSACTION_SURFACES.filter((s) => allowed.has(s))+ : TRANSACTION_SURFACES;++ const options: ChoiceSelectOption<TransactionSurface>[] = visibleSurfaces.map(+ (s) => ({value: s,title: SURFACE_META[s].title,description: SURFACE_META[s].description,icon: SURFACE_META[s].icon- }));+ })+ );const handleChange = (next: TransactionSurface[]) => {if (next.length === 0) return; // soft guard — keep at least one@@ -81,7 +143,7 @@ export default function SurfacesField({ name, label }: SurfacesFieldProps) {return (<FormControl isInvalid={!!error}><FormLabel isOptional={isOptional} htmlFor={name}>- {label ?? t`Applies to`}+ {label ?? t`Triggers`}</FormLabel>{selected.map((surface, index) => (diff --git a/apps/erp/app/modules/items/ui/ItemRules/ValueCombobox.tsx b/apps/erp/app/modules/customRules/ui/ValueCombobox.tsxsimilarity index 100%rename from apps/erp/app/modules/items/ui/ItemRules/ValueCombobox.tsxrename to apps/erp/app/modules/customRules/ui/ValueCombobox.tsxdiff --git a/apps/erp/app/modules/customRules/ui/ValueInput.tsx b/apps/erp/app/modules/customRules/ui/ValueInput.tsxnew file mode 100644index 0000000000..c03075351e--- /dev/null+++ b/apps/erp/app/modules/customRules/ui/ValueInput.tsx@@ -0,0 +1,514 @@+import {+ cn,+ Input,+ NumberDecrementStepper,+ NumberField,+ NumberIncrementStepper,+ NumberInput,+ NumberInputGroup,+ NumberInputStepper,+ Popover,+ PopoverContent,+ PopoverTrigger+} from "@carbon/react";+import type { FieldDef, Operator } from "@carbon/utils";+import { useLingui } from "@lingui/react/macro";+import { memo, useCallback, useEffect, useMemo, useState } from "react";+import {+ LuChevronDown,+ LuChevronRight,+ LuChevronUp,+ LuMapPin,+ LuX+} from "react-icons/lu";+import { useLocations } from "~/components/Form/Location";+import {+ type StorageUnitTreeRow,+ useStorageUnitsTree+} from "~/components/Form/StorageUnitDrillSelect";+import MultiValueCombobox from "./MultiValueCombobox";+import type { ValueOption } from "./useValueOptions";+import ValueCombobox from "./ValueCombobox";++type ValueInputProps = {+ fieldDef: FieldDef | undefined;+ op: Operator;+ value: unknown;+ onChange: (next: unknown) => void;+ options: ValueOption[] | undefined;+};++const isMultiOp = (op: Operator) => op === "in" || op === "notIn";+const isPresenceOp = (op: Operator) => op === "isSet" || op === "isNotSet";++function ValueInputImpl({+ fieldDef,+ op,+ value,+ onChange,+ options+}: ValueInputProps) {+ const { t } = useLingui();++ // Presence ops — no value control. Render dashed placeholder pill so the+ // grid column stays the same width (matches existing visual treatment).+ // Height matches CommandTrigger size="md" (h-10) so the row stays aligned.+ if (isPresenceOp(op)) {+ return (+ <div className="flex h-10 items-center rounded-md border border-dashed border-border px-3 text-xs text-muted-foreground">+ {t`No value needed`}+ </div>+ );+ }++ // Render the autocomplete combobox whenever the field declares a loader,+ // even if `options` is currently empty. The fetcher hooks populate+ // asynchronously on mount; an empty array still renders a usable Combobox+ // (showing the "no values" empty state) which then re-renders with options+ // when the fetch resolves. Falling through to a text input on empty was the+ // bug — the input got "stuck" until the user re-selected the field.+ const hasOptions = !!fieldDef?.valueOptionsLoader && !!options;+ const multi = isMultiOp(op);++ // Multi-select with a known options loader — supplies a real string[] array+ // straight to the AST (no comma-split parsing needed).+ if (multi && hasOptions) {+ const arrValue = Array.isArray(value)+ ? value.map(String).filter(Boolean)+ : [];+ return (+ <MultiValueCombobox+ value={arrValue}+ onChange={(next) => onChange(next)}+ options={options!}+ placeholder={t`Select values`}+ />+ );+ }++ // Single-select autocomplete — used for any scalar op on a field with a+ // loader. Local component for visual parity with FieldCombobox /+ // OperatorCombobox (chevron trigger, same height, full-width).+ if (!multi && hasOptions) {+ const strValue =+ typeof value === "string" || typeof value === "number"+ ? String(value)+ : "";+ return (+ <ValueCombobox+ value={strValue}+ onChange={(next) => onChange(next)}+ options={options!}+ placeholder={t`Select value`}+ />+ );+ }++ // Storage-unit drill picker — hierarchical Location → drilldown selector+ // for scalar ops. Multi ops fall through to the text path (paste UUIDs).+ if (!multi && fieldDef?.type === "storageUnit") {+ const strValue =+ typeof value === "string" && value !== "" ? value : undefined;+ return <StorageUnitValuePicker value={strValue} onChange={onChange} />;+ }++ // Numeric input — only valid on scalar ops; multi on a numeric field falls+ // through to the comma-separated text path below.+ if (!multi && fieldDef?.type === "number") {+ const numValue =+ typeof value === "number"+ ? value+ : typeof value === "string" && value !== ""+ ? Number(value)+ : Number.NaN;+ return (+ <NumberField+ value={Number.isNaN(numValue) ? undefined : numValue}+ onChange={(n) =>+ onChange(typeof n === "number" && !Number.isNaN(n) ? n : undefined)+ }+ aria-label={t`Number`}+ >+ <NumberInputGroup className="relative">+ <NumberInput placeholder={t`Number`} />+ <NumberInputStepper>+ <NumberIncrementStepper>+ <LuChevronUp size="1em" strokeWidth="3" />+ </NumberIncrementStepper>+ <NumberDecrementStepper>+ <LuChevronDown size="1em" strokeWidth="3" />+ </NumberDecrementStepper>+ </NumberInputStepper>+ </NumberInputGroup>+ </NumberField>+ );+ }++ // Fallback — string input. Multi-value without a loader stays as+ // comma-separated text so users can still type literal sets (e.g. on custom+ // fields where no option list is known).+ const display =+ value == null+ ? ""+ : Array.isArray(value)+ ? value.join(", ")+ : String(value);++ return (+ <Input+ size="md"+ type="text"+ placeholder={multi ? t`comma-separated values` : t`Value`}+ value={display}+ onChange={(e) => {+ const raw = e.target.value;+ if (multi) {+ onChange(+ raw+ .split(",")+ .map((s) => s.trim())+ .filter(Boolean)+ );+ } else {+ onChange(raw);+ }+ }}+ />+ );+}++export default memo(ValueInputImpl);++// ---------------------------------------------------------------------------+// StorageUnitValuePicker — single trigger, popover with location switch ++// drill-down storage-unit tree.+// ---------------------------------------------------------------------------+//+// Custom rules aren't scoped to a location, so location is selectable+// inside the picker's popover (not a sibling input). Trigger shows only the+// unit name (location is implied by the selection); breadcrumb + search live+// inside the popover.+//+// Subcomponents are co-located rather than exposed as compound API — the+// picker is only used in one place. State stays in the parent+// `StorageUnitValuePicker`, passed down explicitly (no internal context+// needed for this scope).++type LocationOption = { value: string; label: React.ReactNode };++function StorageUnitValuePickerImpl({+ value,+ onChange+}: {+ value: string | undefined;+ onChange: (next: unknown) => void;+}) {+ const locations = useLocations() as LocationOption[];++ const [locationId, setLocationId] = useState<string | null>(null);+ const [open, setOpen] = useState(false);+ const [stack, setStack] = useState<string[]>([]);+ const [search, setSearch] = useState("");++ // Default to first available location.+ useEffect(() => {+ if (locationId) return;+ if (!locations.length) return;+ setLocationId(locations[0]!.value);+ }, [locationId, locations]);++ // Auto-route to the location whose tree contains `value`. Hops through+ // locations one at a time; bails as soon as it finds a match.+ const tree = useStorageUnitsTree(locationId);+ useEffect(() => {+ if (!value || !locationId) return;+ if (tree.some((r) => r.id === value)) return;+ for (const loc of locations) {+ if (loc.value === locationId) continue;+ setLocationId(loc.value);+ return;+ }+ }, [value, locationId, tree, locations]);++ const byId = useMemo(() => {+ const m = new Map<string, StorageUnitTreeRow>();+ tree.forEach((r) => m.set(r.id, r));+ return m;+ }, [tree]);++ const childrenOf = useMemo(() => {+ const m = new Map<string | null, StorageUnitTreeRow[]>();+ tree.forEach((r) => {+ const arr = m.get(r.parentId) ?? [];+ arr.push(r);+ m.set(r.parentId, arr);+ });+ m.forEach((arr) => arr.sort((a, b) => a.name.localeCompare(b.name)));+ return m;+ }, [tree]);++ const currentParentId = stack.length === 0 ? null : stack[stack.length - 1]!;+ const currentChildren = childrenOf.get(currentParentId) ?? [];+ const breadcrumb = stack+ .map((id) => byId.get(id))+ .filter((r): r is StorageUnitTreeRow => Boolean(r));++ const renderPath = useCallback(+ (row: StorageUnitTreeRow) =>+ (row.ancestorPath ?? [])+ .slice(0, -1)+ .map((id) => byId.get(id)?.name)+ .filter(Boolean)+ .join(" / "),+ [byId]+ );++ const searchResults = useMemo(() => {+ const q = search.trim().toLowerCase();+ if (!q) return null;+ return tree.filter((r) => {+ if (r.name?.toLowerCase().includes(q)) return true;+ return (r.ancestorPath ?? []).some((id) =>+ byId.get(id)?.name?.toLowerCase().includes(q)+ );+ });+ }, [search, tree, byId]);++ const selectedRow = value ? byId.get(value) : undefined;+ const selectedLocation = locations.find((l) => l.value === locationId);+ const selectedLocationLabel = selectedLocation+ ? typeof selectedLocation.label === "string"+ ? selectedLocation.label+ : ""+ : "";++ const reset = () => {+ setStack([]);+ setSearch("");+ };++ // On open with an existing value: stack to the selected row's parent so+ // user lands viewing the selected unit highlighted in its sibling list.+ useEffect(() => {+ if (!open) return;+ if (!value) return;+ const row = byId.get(value);+ if (!row) return;+ setStack((row.ancestorPath ?? []).slice(0, -1));+ }, [open, value, byId]);++ const select = (id: string) => {+ onChange(id || undefined);+ setOpen(false);+ reset();+ };++ const [locOpen, setLocOpen] = useState(false);++ return (+ <Popover+ open={open}+ onOpenChange={(o) => {+ setOpen(o);+ if (!o) reset();+ }}+ >+ <PopoverTrigger asChild>+ <button+ type="button"+ className={cn(+ "group flex h-10 w-full items-center justify-between gap-2 rounded-md border border-input bg-background px-3 text-sm text-left",+ "outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 transition-[color,box-shadow]",+ !selectedRow && "text-muted-foreground"+ )}+ >+ <span className="min-w-0 flex-1 truncate">+ {selectedRow?.name ?? "Select storage unit"}+ </span>+ <span className="flex shrink-0 items-center gap-1">+ {value ? (+ <span+ role="button"+ tabIndex={-1}+ aria-label="Clear"+ onClick={(e) => {+ e.stopPropagation();+ onChange(undefined);+ }}+ className="flex h-4 w-4 items-center justify-center rounded opacity-60 hover:bg-muted hover:opacity-100"+ >+ <LuX className="h-3 w-3" />+ </span>+ ) : null}+ <LuChevronDown className="h-4 w-4 opacity-50" />+ </span>+ </button>+ </PopoverTrigger>++ <PopoverContent+ align="end"+ sideOffset={4}+ collisionPadding={12}+ avoidCollisions+ className="w-auto min-w-[220px] max-w-[min(420px,calc(100vw-24px))] p-0"+ onWheel={(e) => e.stopPropagation()}+ onTouchMove={(e) => e.stopPropagation()}+ >+ {/* Breadcrumb — always visible. Root crumb is the location, clickable+ to switch locations via a nested popover. */}+ <div className="flex flex-wrap items-center gap-0.5 border-b px-2 py-1.5">+ <Popover open={locOpen} onOpenChange={setLocOpen}>+ <PopoverTrigger asChild>+ <button+ type="button"+ className={cn(+ "flex items-center gap-1 rounded px-1.5 py-0.5 text-xs hover:bg-muted",+ stack.length === 0+ ? "font-medium text-foreground"+ : "text-muted-foreground hover:text-foreground"+ )}+ >+ <LuMapPin className="h-3 w-3 opacity-70" />+ {selectedLocationLabel || "Location"}+ <LuChevronDown className="h-3 w-3 opacity-60" />+ </button>+ </PopoverTrigger>+ <PopoverContent+ align="start"+ sideOffset={4}+ collisionPadding={12}+ className="w-auto min-w-[200px] max-w-[320px] p-1"+ >+ <ul role="list" className="max-h-[200px] overflow-y-auto">+ {locations.length === 0 && (+ <li className="px-2 py-1.5 text-xs text-muted-foreground">+ Loading…+ </li>+ )}+ {locations.map((l) => {+ const isActive = l.value === locationId;+ return (+ <li key={l.value}>+ <button+ type="button"+ onClick={() => {+ setLocationId(l.value);+ setStack([]);+ setSearch("");+ setLocOpen(false);+ }}+ className={cn(+ "flex w-full items-center justify-between gap-2 rounded px-2 py-1.5 text-left text-sm hover:bg-muted",+ isActive && "font-medium text-foreground"+ )}+ >+ <span className="truncate">{String(l.label)}</span>+ {isActive && (+ <span className="text-xs text-muted-foreground">+ ✓+ </span>+ )}+ </button>+ </li>+ );+ })}+ </ul>+ </PopoverContent>+ </Popover>+ {breadcrumb.map((row, i) => (+ <span key={row.id} className="flex items-center gap-0.5">+ <LuChevronRight className="h-3 w-3 text-muted-foreground/60" />+ <button+ type="button"+ onClick={() => setStack(stack.slice(0, i + 1))}+ className={cn(+ "rounded px-1.5 py-0.5 text-xs hover:bg-muted",+ i === breadcrumb.length - 1+ ? "font-medium text-foreground"+ : "text-muted-foreground hover:text-foreground"+ )}+ >+ {row.name}+ </button>+ </span>+ ))}+ </div>++ {/* Search — flush, no chrome. */}+ <Input+ autoFocus+ value={search}+ onChange={(e) => setSearch(e.target.value)}+ placeholder="Search storage units…"+ className="h-9 rounded-none border-none border-b border-border bg-transparent px-3 text-sm focus-visible:ring-0 focus-visible:ring-offset-0"+ />++ {/* List */}+ <ul role="list" className="max-h-[260px] overflow-y-auto py-1">+ {searchResults ? (+ searchResults.length === 0 ? (+ <li className="px-3 py-6 text-center text-xs text-muted-foreground">+ No matches+ </li>+ ) : (+ searchResults.map((row) => (+ <li key={row.id}>+ <button+ type="button"+ onClick={() => select(row.id)}+ className="flex w-full flex-col items-start gap-0.5 px-3 py-1.5 text-left hover:bg-muted"+ >+ <span className="text-sm">{row.name}</span>+ {renderPath(row) && (+ <span className="text-xs text-muted-foreground">+ {renderPath(row)}+ </span>+ )}+ </button>+ </li>+ ))+ )+ ) : currentChildren.length === 0 ? (+ <li className="px-3 py-6 text-center text-xs text-muted-foreground">+ No storage units+ </li>+ ) : (+ currentChildren.map((row) => {+ const hasChildren = (childrenOf.get(row.id) ?? []).length > 0;+ const isSelected = row.id === value;+ return (+ <li key={row.id} className="flex items-stretch hover:bg-muted">+ <button+ type="button"+ onClick={() => select(row.id)}+ className={cn(+ "flex-1 truncate px-3 py-1.5 text-left text-sm",+ isSelected && "font-medium text-foreground"+ )}+ >+ {row.name}+ </button>+ {hasChildren && (+ <button+ type="button"+ onClick={() => {+ setStack([...stack, row.id]);+ setSearch("");+ }}+ className="flex w-7 shrink-0 items-center justify-center border-l text-muted-foreground hover:text-foreground"+ aria-label={`Open ${row.name}`}+ >+ <LuChevronRight className="h-3.5 w-3.5" />+ </button>+ )}+ </li>+ );+ })+ )}+ </ul>+ </PopoverContent>+ </Popover>+ );+}++const StorageUnitValuePicker = memo(StorageUnitValuePickerImpl);diff --git a/apps/erp/app/modules/items/ui/ItemRules/useValueOptions.ts b/apps/erp/app/modules/customRules/ui/useValueOptions.tssimilarity index 64%rename from apps/erp/app/modules/items/ui/ItemRules/useValueOptions.tsrename to apps/erp/app/modules/customRules/ui/useValueOptions.tsindex db59c6b7a3..dc6b42fffc 100644--- a/apps/erp/app/modules/items/ui/ItemRules/useValueOptions.ts+++ b/apps/erp/app/modules/customRules/ui/useValueOptions.ts@@ -1,6 +1,5 @@import type { ValueOptionsLoader } from "@carbon/utils";import { useMemo } from "react";-import { useItemPostingGroups } from "~/components/Form/ItemPostingGroup";import { useLocations } from "~/components/Form/Location";import { useStorageTypes } from "~/components/Form/StorageTypes";import { itemTypes } from "~/modules/inventory/inventory.models";@@ -20,30 +19,18 @@ const ITEM_TYPES_OPTIONS = enumOptions(itemTypes);const ITEM_TRACKING_TYPES_OPTIONS = enumOptions(itemTrackingTypes);const REPLENISHMENT_SYSTEMS_OPTIONS = enumOptions(itemReplenishmentSystems);-/**- * Aggregates every {@link ValueOptionsLoader} into a single map for the rule- * builder's value picker. DB-backed loaders share the existing `useFetcher`- * hooks already used by the form-component pickers — they fetch once on mount- * and re-use the cached payload across rows. Static enum loaders are mapped- * from module-level constants.- *- * Returned object reference is memoised on the underlying option arrays so- * memoised consumers (`ConditionRow`) skip re-renders when nothing changed.- */export function useValueOptions(): ValueOptionsByLoader {const locations = useLocations();const storageTypes = useStorageTypes();- const itemPostingGroups = useItemPostingGroups();return useMemo<ValueOptionsByLoader>(() => ({locations,storageTypes,- itemPostingGroups,itemTypes: ITEM_TYPES_OPTIONS,itemTrackingTypes: ITEM_TRACKING_TYPES_OPTIONS,replenishmentSystems: REPLENISHMENT_SYSTEMS_OPTIONS}),- [locations, storageTypes, itemPostingGroups]+ [locations, storageTypes]);}diff --git a/apps/erp/app/modules/inventory/ui/Inventory/InventoryStorageUnits.tsx b/apps/erp/app/modules/inventory/ui/Inventory/InventoryStorageUnits.tsxindex 43e46163dd..e7db62ba2d 100644--- a/apps/erp/app/modules/inventory/ui/Inventory/InventoryStorageUnits.tsx+++ b/apps/erp/app/modules/inventory/ui/Inventory/InventoryStorageUnits.tsx@@ -1,3 +1,4 @@+import { useCustomRuleViolations } from "@carbon/ee/custom-rules";import {DatePicker,Hidden,@@ -53,16 +54,10 @@ import {import { Outlet } from "react-router";import type { z } from "zod";import { Enumerable } from "~/components/Enumerable";-import {- Input,- Location,- Select,- StorageUnit,- TextArea-} from "~/components/Form";+import { Input, Location, Select, TextArea } from "~/components/Form";+import { StorageUnitDrillSelectField } from "~/components/Form/StorageUnitDrillSelect";import { useUnitOfMeasure } from "~/components/Form/UnitOfMeasure";import { usePermissions } from "~/hooks";-import { useItemRuleViolations } from "~/hooks/useItemRuleViolations";import type {ItemStorageUnitQuantities,itemTrackingTypes,@@ -96,7 +91,7 @@ const InventoryStorageUnits = ({const permissions = usePermissions();const { t } = useLingui();const adjustmentModal = useDisclosure();- const ruleViolations = useItemRuleViolations({+ const ruleViolations = useCustomRuleViolations({action: path.to.inventoryItemAdjustment(pickMethod.itemId),onSuccess: adjustmentModal.onClose});@@ -350,7 +345,7 @@ const InventoryStorageUnits = ({<VStack spacing={2}><Location name="locationId" label={t`Location`} isReadOnly />- <StorageUnit+ <StorageUnitDrillSelectFieldname="storageUnitId"locationId={pickMethod.locationId}label={t`Storage Unit`}diff --git a/apps/erp/app/modules/inventory/ui/Inventory/InventoryTable.tsx b/apps/erp/app/modules/inventory/ui/Inventory/InventoryTable.tsxindex 56ec9bbb83..55664393fb 100644--- a/apps/erp/app/modules/inventory/ui/Inventory/InventoryTable.tsx+++ b/apps/erp/app/modules/inventory/ui/Inventory/InventoryTable.tsx@@ -47,7 +47,6 @@ import {} from "~/components";import { Enumerable } from "~/components/Enumerable";import { useLocations } from "~/components/Form/Location";-import { useStorageUnits } from "~/components/Form/StorageUnit";import { StorageUnitDrillSelect } from "~/components/Form/StorageUnitDrillSelect";import { useUnitOfMeasure } from "~/components/Form/UnitOfMeasure";import { useFilters } from "~/components/Table/components/Filter/useFilters";@@ -74,6 +73,7 @@ type InventoryTableProps = {substances: ListItem[];tags: string[];storageTypes: { id: string; name: string }[];+ storageUnits: { id: string; name: string }[];};const InventoryTable = memo(@@ -84,7 +84,8 @@ const InventoryTable = memo(forms,substances,tags,- storageTypes+ storageTypes,+ storageUnits}: InventoryTableProps) => {const [params] = useUrlParams();const { t } = useLingui();@@ -97,7 +98,10 @@ const InventoryTable = memo(const locations = useLocations();const unitOfMeasures = useUnitOfMeasure();- const { options: storageUnitOptions } = useStorageUnits(locationId);+ const storageUnitNameById = useMemo(+ () => new Map(storageUnits.map((s) => [s.id, s.name])),+ [storageUnits]+ );const filters = useFilters();const materialSubstanceId = filters.getFilter("materialSubstanceId")?.[0];@@ -517,11 +521,12 @@ const InventoryTable = memo().storageUnitIds ?? [];return (<HStack spacing={0} className="gap-1">- {ids.map((id) => {- const opt = storageUnitOptions.find((o) => o.value === id);- const label = typeof opt?.label === "string" ? opt.label : id;- return <Enumerable key={id} value={label} />;- })}+ {ids.map((id) => (+ <Enumerable+ key={id}+ value={storageUnitNameById.get(id) ?? id}+ />+ ))}</HStack>);},@@ -529,44 +534,47 @@ const InventoryTable = memo(filter: {type: "custom",isArray: true,- getLabel: (v: string) => {- const opt = storageUnitOptions.find((o) => o.value === v);- return typeof opt?.label === "string" ? opt.label : v;- },- render: ({ values, toggle }) => (- <div className="flex flex-col gap-2">- {values.length > 0 && (- <div className="flex flex-wrap gap-1">- {values.map((v) => {- const opt = storageUnitOptions.find(- (o) => o.value === v- );- const label =- typeof opt?.label === "string" ? opt.label : v;- return (- <Badge- key={v}- variant="secondary"- className="cursor-pointer gap-1 max-w-full"- onClick={() => toggle(v)}- >- <span className="truncate">{label}</span>- <LuX className="h-3 w-3 shrink-0" />+ getLabel: (v: string) => storageUnitNameById.get(v) ?? v,+ render: ({ values, toggle }) => {+ const VISIBLE = 3;+ const visible = values.slice(0, VISIBLE);+ const overflow = values.length - visible.length;+ return (+ <div className="flex flex-col gap-2">+ {values.length > 0 && (+ <div className="flex flex-wrap gap-1">+ {visible.map((v) => {+ const label = storageUnitNameById.get(v) ?? v;+ return (+ <Badge+ key={v}+ variant="secondary"+ className="cursor-pointer gap-1 max-w-[160px]"+ onClick={() => toggle(v)}+ >+ <span className="truncate">{label}</span>+ <LuX className="h-3 w-3 shrink-0" />+ </Badge>+ );+ })}+ {overflow > 0 && (+ <Badge variant="secondary" className="gap-1">+ +{overflow} more</Badge>- );- })}- </div>- )}- <StorageUnitDrillSelect- locationId={locationId}- value={null}- onChange={(id) => {- if (id) toggle(id);- }}- allowCreate={false}- />- </div>- )+ )}+ </div>+ )}+ <StorageUnitDrillSelect+ locationId={locationId}+ value={null}+ onChange={(id) => {+ if (id) toggle(id);+ }}+ allowCreate={false}+ />+ </div>+ );+ }},pluralHeader: t`Storage Units`,icon: <LuBoxes />@@ -599,7 +607,7 @@ const InventoryTable = memo(substances,tags,storageTypes,- storageUnitOptions,+ storageUnitNameById,unitOfMeasures,t,translateReplenishmentdiff --git a/apps/erp/app/modules/inventory/ui/Receipts/ReceiptPostModal.tsx b/apps/erp/app/modules/inventory/ui/Receipts/ReceiptPostModal.tsxindex 5166e52d82..c0f7632930 100644--- a/apps/erp/app/modules/inventory/ui/Receipts/ReceiptPostModal.tsx+++ b/apps/erp/app/modules/inventory/ui/Receipts/ReceiptPostModal.tsx@@ -1,4 +1,5 @@import { useCarbon } from "@carbon/auth";+import { useCustomRuleViolations } from "@carbon/ee/custom-rules";import {Alert,AlertDescription,@@ -24,7 +25,6 @@ import { useState } from "react";import { LuTriangleAlert } from "react-icons/lu";import { useNavigation, useParams } from "react-router";import { useUser } from "~/hooks";-import { useItemRuleViolations } from "~/hooks/useItemRuleViolations";import { useItems } from "~/stores";import { path } from "~/utils/path";import { getReceiptTracking } from "../../inventory.service";@@ -139,7 +139,7 @@ const ReceiptPostModal = ({ onClose }: { onClose: () => void }) => {validateReceiptTracking();});- const ruleViolations = useItemRuleViolations({+ const ruleViolations = useCustomRuleViolations({action: path.to.receiptPost(receiptId),onSuccess: onClose});diff --git a/apps/erp/app/modules/inventory/ui/Shipments/ShipmentPostModal.tsx b/apps/erp/app/modules/inventory/ui/Shipments/ShipmentPostModal.tsxindex 70898c25c8..7834a1fafb 100644--- a/apps/erp/app/modules/inventory/ui/Shipments/ShipmentPostModal.tsx+++ b/apps/erp/app/modules/inventory/ui/Shipments/ShipmentPostModal.tsx@@ -1,4 +1,5 @@import { useCarbon } from "@carbon/auth";+import { useCustomRuleViolations } from "@carbon/ee/custom-rules";import {Alert,AlertDescription,@@ -25,7 +26,6 @@ import { useState } from "react";import { LuTriangleAlert } from "react-icons/lu";import { useNavigation, useParams } from "react-router";import { useSettings, useUser } from "~/hooks";-import { useItemRuleViolations } from "~/hooks/useItemRuleViolations";import { useItems } from "~/stores";import { path } from "~/utils/path";import type { ShipmentLine } from "../..";@@ -219,7 +219,7 @@ const ShipmentPostModal = ({ onClose }: { onClose: () => void }) => {validateShipmentTracking();});- const ruleViolations = useItemRuleViolations({+ const ruleViolations = useCustomRuleViolations({action: path.to.shipmentPost(shipmentId),onSuccess: onClose});diff --git a/apps/erp/app/modules/inventory/ui/StockTransfers/StockTransferHeader.tsx b/apps/erp/app/modules/inventory/ui/StockTransfers/StockTransferHeader.tsxindex cb264394e1..66e7669ad1 100644--- a/apps/erp/app/modules/inventory/ui/StockTransfers/StockTransferHeader.tsx+++ b/apps/erp/app/modules/inventory/ui/StockTransfers/StockTransferHeader.tsx@@ -1,4 +1,5 @@import type { Result } from "@carbon/auth";+import { useCustomRuleViolations } from "@carbon/ee/custom-rules";import {Button,Copy,@@ -27,7 +28,6 @@ import Assignee, { useOptimisticAssignment } from "~/components/Assignee";import { useAuditLog } from "~/components/AuditLog";import ConfirmDelete from "~/components/Modals/ConfirmDelete";import { usePermissions, useRouteData, useUser } from "~/hooks";-import { useItemRuleViolations } from "~/hooks/useItemRuleViolations";import {isStockTransferLocked,type StockTransfer,@@ -59,11 +59,11 @@ const StockTransferHeader = () => {// Item rules fire on Release + Complete (the "go" transitions). Each gets// its own fetcher so Release's loading state doesn't disable Complete and// vice versa, and violations surface via a single shared modal.- const releaseRules = useItemRuleViolations({+ const releaseRules = useCustomRuleViolations({action: path.to.stockTransferStatus(id)});const releaseFetcher = releaseRules.fetcher;- const completeRules = useItemRuleViolations({+ const completeRules = useCustomRuleViolations({action: path.to.stockTransferStatus(id)});const completeFetcher = completeRules.fetcher;diff --git a/apps/erp/app/modules/inventory/ui/StockTransfers/StockTransferWizard.tsx b/apps/erp/app/modules/inventory/ui/StockTransfers/StockTransferWizard.tsxindex acbb5e2f4b..025907009a 100644--- a/apps/erp/app/modules/inventory/ui/StockTransfers/StockTransferWizard.tsx+++ b/apps/erp/app/modules/inventory/ui/StockTransfers/StockTransferWizard.tsx@@ -1,5 +1,6 @@import type { Result } from "@carbon/auth";import { useCarbon } from "@carbon/auth";+import { useCustomRuleViolations } from "@carbon/ee/custom-rules";import {Badge,Button,@@ -69,7 +70,6 @@ import {import { ItemThumbnail } from "~/components";import { getAccessorKey } from "~/components/Table/utils";import { useUser } from "~/hooks";-import { useItemRuleViolations } from "~/hooks/useItemRuleViolations";import {addTransferLine,clearSelectedToItemStorageUnits,@@ -1215,7 +1215,7 @@ const StockTransferWizardWidget = ({ locationId }: { locationId: string }) => {// Item Rule pre-flight on Create Transfer (auto-released → stock-commit// gate sits at the wizard click). Modal surfaces violations before the// transfer is created.- const createRules = useItemRuleViolations<Result>({+ const createRules = useCustomRuleViolations<Result>({action: path.to.newStockTransfer,onSuccess: () => clearStockTransferWizard()});diff --git a/apps/erp/app/modules/inventory/ui/StorageUnits/StorageUnitForm.tsx b/apps/erp/app/modules/inventory/ui/StorageUnits/StorageUnitForm.tsxindex 3341ac55e9..1a7c6a6779 100644--- a/apps/erp/app/modules/inventory/ui/StorageUnits/StorageUnitForm.tsx+++ b/apps/erp/app/modules/inventory/ui/StorageUnits/StorageUnitForm.tsx@@ -12,7 +12,8 @@ import {VStack} from "@carbon/react";import { Trans, useLingui } from "@lingui/react/macro";-import { useFetcher } from "react-router";+import { LuShieldCheck } from "react-icons/lu";+import { Link, useFetcher } from "react-router";import type { z } from "zod";import {Hidden,@@ -108,13 +109,28 @@ const StorageUnitForm = ({</VStack></ModalDrawerBody><ModalDrawerFooter>- <HStack>- <Submit isDisabled={isDisabled}>- <Trans>Save</Trans>- </Submit>- <Button size="md" variant="solid" onClick={onClose}>- <Trans>Cancel</Trans>- </Button>+ <HStack className="justify-between w-full">+ {isEditing ? (+ <Button+ asChild+ variant="secondary"+ leftIcon={<LuShieldCheck />}+ >+ <Link to={path.to.storageUnitRules(initialValues.id!)}>+ <Trans>Manage rules</Trans>+ </Link>+ </Button>+ ) : (+ <span />+ )}+ <HStack>+ <Submit isDisabled={isDisabled}>+ <Trans>Save</Trans>+ </Submit>+ <Button size="md" variant="solid" onClick={onClose}>+ <Trans>Cancel</Trans>+ </Button>+ </HStack></HStack></ModalDrawerFooter></ValidatedForm>diff --git a/apps/erp/app/modules/inventory/ui/WarehouseTransfers/WarehouseTransferForm.tsx b/apps/erp/app/modules/inventory/ui/WarehouseTransfers/WarehouseTransferForm.tsxindex 9c61f93d5a..90cad0fdc6 100644--- a/apps/erp/app/modules/inventory/ui/WarehouseTransfers/WarehouseTransferForm.tsx+++ b/apps/erp/app/modules/inventory/ui/WarehouseTransfers/WarehouseTransferForm.tsx@@ -1,4 +1,5 @@import { useCarbon } from "@carbon/auth";+import { useCustomRuleViolations } from "@carbon/ee/custom-rules";import { InputControlled, ValidatedForm } from "@carbon/form";import {Button,@@ -47,7 +48,6 @@ import {} from "~/components/Form";import ConfirmDelete from "~/components/Modals/ConfirmDelete";import { usePermissions, useUser } from "~/hooks";-import { useItemRuleViolations } from "~/hooks/useItemRuleViolations";import type { action as statusAction } from "~/routes/x+/warehouse-transfer+/$transferId.status";import { path } from "~/utils/path";import {@@ -73,7 +73,7 @@ const WarehouseTransferForm = ({// Item rules eval at every "go" status transition (Confirm/Ship/Receive/// Complete). Surface violations through the hook's modal rather than the// plain navigation path.- const statusRules = useItemRuleViolations<typeof statusAction>({+ const statusRules = useCustomRuleViolations<typeof statusAction>({action: warehouseTransfer?.id? path.to.warehouseTransferStatus(warehouseTransfer.id): ""diff --git a/apps/erp/app/modules/items/itemRules.server.ts b/apps/erp/app/modules/items/itemRules.server.tsdeleted file mode 100644index 42125b3969..0000000000--- a/apps/erp/app/modules/items/itemRules.server.ts+++ /dev/null@@ -1,448 +0,0 @@-// Server-side item-rules service. Single entry point for trigger surfaces-// (receipt / shipment / stock-transfer / inventory adjustment), plan gate,-// and the per-item Rules-tab loader.-//-// All functions here are server-only. Never import from a client module.--import { requirePermissions } from "@carbon/auth/auth.server";-import type { Database } from "@carbon/database";-import { companyHasPlan } from "@carbon/ee/plan.server";-import {- type CompiledRule,- type Condition,- type ConditionAst,- compileWithCache,- evaluateRules,- getFieldDef,- type RuleContext,- type Severity,- type TransactionSurface,- type ValueOptionsLoader,- type Violation-} from "@carbon/utils";-import type { SupabaseClient } from "@supabase/supabase-js";-import type { LoaderFunctionArgs } from "react-router";-import { getStorageTypesList } from "~/modules/inventory";-import { getLocationsList } from "~/modules/resources";-import {- getActiveRulesForItems,- getItemPostingGroupsList,- getItemRulesList,- getRuleAssignmentsForItem-} from "./items.service";--type Client = SupabaseClient<Database>;--// ----------------------------------------------------------------------------// Plan gate-// -----------------------------------------------------------------------------export const isItemRulesEnabledForCompany = (- client: Client,- companyId: string-): Promise<boolean> =>- companyHasPlan(client, companyId, { feature: "ITEM_RULES" });--// ----------------------------------------------------------------------------// Block decision-// -----------------------------------------------------------------------------/** Any error blocks unconditionally. Warns block until acknowledged. */-export const isBlocked = (- violations: Violation[],- acknowledged: boolean-): boolean => {- for (let i = 0; i < violations.length; i++) {- if (violations[i]!.severity === "error") return true;- }- return violations.length > 0 && !acknowledged;-};--/**- * Collapse violations by `ruleId + message`. Same rule firing on N lines or- * across N surfaces (e.g. shipment + warehouseTransfer when posting an- * outbound transfer) yields N copies — operator only needs to see one.- * `evaluateLinesForSurface` dedups its own output; use this when a caller- * accumulates results from multiple `evaluateLinesForSurface` invocations.- */-export const dedupeViolations = (violations: Violation[]): Violation[] => {- const seen = new Set<string>();- const out: Violation[] = [];- for (let i = 0; i < violations.length; i++) {- const v = violations[i]!;- const key = `${v.ruleId}\x00${v.message}`;- if (seen.has(key)) continue;- seen.add(key);- out.push(v);- }- return out;-};--// ----------------------------------------------------------------------------// Per-item Rules tab data (loader helper)-// -----------------------------------------------------------------------------type AssignedRuleNode = {- id: string;- name: string;- severity: Severity;- message: string;- active: boolean;- surfaces: TransactionSurface[];-};--export async function getItemRulesDataForItem(- client: Client,- itemId: string,- companyId: string-) {- const [assignmentsRes, libraryRes] = await Promise.all([- getRuleAssignmentsForItem(client, itemId, companyId),- getItemRulesList(client, companyId)- ]);-- const assignments: { ruleId: string; rule: AssignedRuleNode }[] = [];- for (const row of assignmentsRes.data ?? []) {- // Supabase returns joined relation as object or single-element array- // depending on FK shape. Normalise once.- const joined = (- row as { itemRule: AssignedRuleNode | AssignedRuleNode[] | null }- ).itemRule;- const rule = Array.isArray(joined) ? joined[0] : joined;- if (!rule) continue;- assignments.push({ ruleId: row.ruleId as string, rule });- }-- return { assignments, library: libraryRes.data ?? [] };-}--export async function loadRulesTabData({- request,- itemId-}: {- request: LoaderFunctionArgs["request"];- itemId: string;-}) {- const { client, companyId } = await requirePermissions(request, {- view: "parts",- role: "employee"- });- return getItemRulesDataForItem(client, itemId, companyId);-}--// ----------------------------------------------------------------------------// Compile-// -----------------------------------------------------------------------------/**- * Batch-load + compile rules for many items in one round-trip. The compiled- * cache (`compileWithCache`) deduplicates across requests so identical rules- * compile once per process.- */-async function loadCompiledRulesForItems(- client: Client,- itemIds: string[],- companyId: string-): Promise<Map<string, CompiledRule[]>> {- const out = new Map<string, CompiledRule[]>();- if (itemIds.length === 0) return out;-- const { data: byItem } = await getActiveRulesForItems(- client,- itemIds,- companyId- );- for (const [itemId, rows] of byItem) {- const compiled = new Array<CompiledRule>(rows.length);- for (let i = 0; i < rows.length; i++) {- const row = rows[i]!;- compiled[i] = compileWithCache({- ...row,- conditionAst: row.conditionAst as ConditionAst- });- }- out.set(itemId, compiled);- }- return out;-}--// ----------------------------------------------------------------------------// Loader-label resolver — UUID condition values → human labels-// -----------------------------------------------------------------------------type LoaderFn = (- client: Client,- companyId: string-) => Promise<{ id: string; name: string }[]>;--const LOADERS: Record<ValueOptionsLoader, LoaderFn | null> = {- locations: async (c, id) => (await getLocationsList(c, id)).data ?? [],- storageTypes: async (c, id) => (await getStorageTypesList(c, id)).data ?? [],- itemPostingGroups: async (c, id) =>- (await getItemPostingGroupsList(c, id)).data ?? [],- // Static enums — value is already the label.- itemTypes: null,- replenishmentSystems: null,- itemTrackingTypes: null-};--const EMPTY_RESOLVER = (): undefined => undefined;--/**- * Build a synchronous `(cond) => label` resolver. Pre-fetches every distinct- * loader referenced by an `id`-typed condition in one parallel batch, then- * returns a closure that hits memory only.- */-async function buildConditionValueResolver(- client: Client,- companyId: string,- conditions: Iterable<Condition>-): Promise<(cond: Condition) => string | undefined> {- const byLoader = new Map<ValueOptionsLoader, Set<string>>();- for (const cond of conditions) {- const def = getFieldDef(cond.field);- if (!def?.valueOptionsLoader || def.type !== "id") continue;- if (LOADERS[def.valueOptionsLoader] === null) continue;- if (cond.value == null) continue;-- let bucket = byLoader.get(def.valueOptionsLoader);- if (!bucket) {- bucket = new Set<string>();- byLoader.set(def.valueOptionsLoader, bucket);- }- if (Array.isArray(cond.value)) {- for (const v of cond.value) bucket.add(String(v));- } else {- bucket.add(String(cond.value));- }- }-- if (byLoader.size === 0) return EMPTY_RESOLVER;-- const labels = new Map<ValueOptionsLoader, Map<string, string>>();- await Promise.all(- Array.from(byLoader.keys()).map(async (loader) => {- const fn = LOADERS[loader]!;- const rows = await fn(client, companyId);- const map = new Map<string, string>();- for (const r of rows) map.set(r.id, r.name);- labels.set(loader, map);- })- );-- return (cond: Condition): string | undefined => {- if (cond.value == null) return undefined;- const def = getFieldDef(cond.field);- const map = def?.valueOptionsLoader- ? labels.get(def.valueOptionsLoader)- : undefined;-- if (Array.isArray(cond.value)) {- if (cond.value.length === 0) return "—";- const out: string[] = [];- for (const v of cond.value) {- const s = String(v);- out.push(map?.get(s) ?? s);- }- return out.join(", ");- }- const s = String(cond.value);- return map?.get(s) ?? s;- };-}--// ----------------------------------------------------------------------------// Per-line evaluator — the single entry point trigger handlers call-// -----------------------------------------------------------------------------export type RuleLineInput = {- /** Diagnostic identifier — not used in eval. */- lineId: string;- /** Item the line operates on. `null` lines are skipped. */- itemId: string | null;- /** Storage unit being interacted with. `null` → `storageUnit.*` resolves to undefined. */- storageUnitId: string | null;- /** Quantity for `transaction.quantity` predicates. */- quantity: number;- /**- * Location stamped on the transaction. When `null`, the helper derives one- * from the storage unit (if any).- */- locationId?: string | null;-};--export type EvaluateLinesForSurfaceArgs = {- /** Service-role client — `item` / `storageUnit` reads bypass RLS. */- client: Client;- companyId: string;- userId: string;- surface: TransactionSurface;- lines: RuleLineInput[];-};--export type EvaluateLinesForSurfaceResult = {- violations: Violation[];- ruleNames: Record<string, string>;-};--const EMPTY_RESULT: EvaluateLinesForSurfaceResult = {- violations: [],- ruleNames: {}-};--type ItemCtxRow = Record<string, unknown> & {- customFields?: Record<string, unknown>;-};-type StorageUnitCtxRow = Record<string, unknown> & {- locationId?: string | null;-};--export async function evaluateLinesForSurface({- client,- companyId,- userId,- surface,- lines-}: EvaluateLinesForSurfaceArgs): Promise<EvaluateLinesForSurfaceResult> {- if (lines.length === 0) return EMPTY_RESULT;- if (!(await isItemRulesEnabledForCompany(client, companyId)))- return EMPTY_RESULT;-- // Single-pass extraction of unique itemIds + storageUnitIds. Avoids two- // `pluckUnique` calls + intermediate arrays.- const itemIds = new Set<string>();- const storageUnitIds = new Set<string>();- for (const line of lines) {- if (line.itemId) itemIds.add(line.itemId);- if (line.storageUnitId) storageUnitIds.add(line.storageUnitId);- }- if (itemIds.size === 0) return EMPTY_RESULT;-- const [itemsRes, storageUnitsRes, compiledByItem] = await Promise.all([- client- .from("item")- .select(- "id, type, replenishmentSystem, itemTrackingType, name, readableId"- )- .in("id", Array.from(itemIds)),- storageUnitIds.size > 0- ? client- .from("storageUnit")- .select("id, storageTypeIds, warehouseId, name, locationId")- .in("id", Array.from(storageUnitIds))- : Promise.resolve({ data: [], error: null }),- loadCompiledRulesForItems(client, Array.from(itemIds), companyId)- ]);-- // Item ctx exposes `readableId` as `id` so templates can render `{item.id}`- // as "PART-001" (not the UUID). Predicates never reference UUID directly.- const itemsById = new Map<string, ItemCtxRow>();- for (const it of itemsRes.data ?? []) {- const row = it as Record<string, unknown>;- const readable = row.readableId as string | undefined;- itemsById.set(row.id as string, {- ...row,- id: readable ?? (row.id as string)- });- }-- // Expose the full `storageTypeIds[]` under the synthetic `storageTypeId`- // field (FIELD_REGISTRY entry is named singular for legacy reasons). Array- // shape lets the operator helpers do "any of" matching against rule values- // — a unit configured as both Hot + Cool should satisfy `in [Cool]`.- const unitsById = new Map<string, StorageUnitCtxRow>();- for (const u of storageUnitsRes.data ?? []) {- const row = u as Record<string, unknown>;- const ids = row.storageTypeIds as string[] | null | undefined;- unitsById.set(row.id as string, {- ...row,- // Empty/null → undefined so `isNotSet` fires correctly, otherwise the- // full array so the operator helpers handle "any of" semantics.- storageTypeId: ids && ids.length > 0 ? ids : undefined- });- }-- // One eager DB pass for label maps. Build the condition list with a single- // generator so we never allocate an intermediate flat array.- const resolveConditionValue = await buildConditionValueResolver(- client,- companyId,- iterateConditions(compiledByItem)- );-- const violations: Violation[] = [];- for (const line of lines) {- if (!line.itemId) continue;- const compiled = compiledByItem.get(line.itemId);- if (!compiled || compiled.length === 0) continue;-- const storageUnit = line.storageUnitId- ? unitsById.get(line.storageUnitId)- : undefined;-- const ctx: RuleContext = {- item: itemsById.get(line.itemId),- storageUnit,- transaction: {- kind: surface,- locationId: line.locationId ?? storageUnit?.locationId ?? null,- quantity: line.quantity,- userId- }- };-- const ruleViolations = evaluateRules(compiled, ctx, surface, {- resolveConditionValue- });- for (let i = 0; i < ruleViolations.length; i++) {- violations.push(ruleViolations[i]!);- }- }-- // Dedup. Same item + same rule across N lines yields N identical violations- // (e.g. 3 shipment lines of "Frozen peas" all break "Hot only"). Operator- // doesn't need to see the same message thrice — collapse by ruleId+message.- const seen = new Set<string>();- const deduped: Violation[] = [];- for (let i = 0; i < violations.length; i++) {- const v = violations[i]!;- const key = `${v.ruleId}\x00${v.message}`;- if (seen.has(key)) continue;- seen.add(key);- deduped.push(v);- }-- if (deduped.length === 0) {- return { violations: deduped, ruleNames: {} };- }-- // Resolve human-readable rule names for the violations modal.- const violatedIds = new Set<string>();- for (let i = 0; i < violations.length; i++)- violatedIds.add(violations[i]!.ruleId);-- const { data: namedRules } = await client- .from("itemRule")- .select("id, name")- .in("id", Array.from(violatedIds));-- const ruleNames: Record<string, string> = {};- for (const r of namedRules ?? []) {- ruleNames[r.id as string] = r.name as string;- }-- return { violations, ruleNames };-}--/** Lazy-iterate every condition across every compiled rule. No allocations. */-function* iterateConditions(- compiledByItem: Map<string, CompiledRule[]>-): Generator<Condition> {- for (const rules of compiledByItem.values()) {- for (let i = 0; i < rules.length; i++) {- const rule = rules[i]!;- const conds = rule.conditions;- for (let j = 0; j < conds.length; j++) yield conds[j]!;- }- }-}diff --git a/apps/erp/app/modules/items/items.models.ts b/apps/erp/app/modules/items/items.models.tsindex b17bc7e906..8e4be22fe6 100644--- a/apps/erp/app/modules/items/items.models.ts+++ b/apps/erp/app/modules/items/items.models.ts@@ -1,4 +1,3 @@-import { TRANSACTION_SURFACES } from "@carbon/utils";import { z } from "zod";import { zfd } from "zod-form-data";import {@@ -772,71 +771,3 @@ export const unitOfMeasureValidator = z.object({code: z.string().min(1, { message: "Code is required" }).max(10),name: z.string().min(1, { message: "Name is required" }).max(50)});--export const itemRuleSeverities = ["error", "warn"] as const;--export const itemRuleOperators = [- "eq",- "neq",- "in",- "notIn",- "isSet",- "isNotSet",- "gt",- "lt"-] as const;--const itemRuleConditionValueSchema = z.union([- z.string(),- z.number(),- z.boolean(),- z.array(z.union([z.string(), z.number(), z.boolean()])),- z.null()-]);--const itemRuleConditionSchema = z.object({- field: z.string().min(1, { message: "Field is required" }),- op: z.enum(itemRuleOperators),- value: itemRuleConditionValueSchema.optional()-});--export const itemRuleMatchKinds = ["all", "any", "none"] as const;--export const itemRuleConditionAstSchema = z.object({- kind: z.enum(itemRuleMatchKinds),- conditions: z- .array(itemRuleConditionSchema)- .min(1, { message: "At least one condition is required" })-});--// conditionAst arrives as a JSON-encoded string in form data; pre-parse before validating.-const itemRuleConditionAstFormField = z.preprocess((raw) => {- if (typeof raw !== "string") return raw;- try {- return JSON.parse(raw);- } catch {- return raw;- }-}, itemRuleConditionAstSchema);--export const itemRuleValidator = z.object({- id: zfd.text(z.string().optional()),- name: z.string().min(1, { message: "Name is required" }).max(120),- description: zfd.text(z.string().optional()),- message: z.string().min(1, { message: "Message is required" }).max(500),- severity: z.enum(itemRuleSeverities),- active: zfd.checkbox(),- surfaces: zfd- .repeatableOfType(z.enum(TRANSACTION_SURFACES))- .refine((arr) => arr.length >= 1, {- message: "Pick at least one surface"- }),- conditionAst: itemRuleConditionAstFormField-});--export const itemRuleAssignmentValidator = z.object({- itemId: z.string().min(1, { message: "Item ID is required" }),- ruleId: z.string().min(1, { message: "Rule ID is required" })-});--export const itemRuleAcknowledgeValidator = zfd.checkbox();diff --git a/apps/erp/app/modules/items/items.service.ts b/apps/erp/app/modules/items/items.service.tsindex b0501d6e56..44db116015 100644--- a/apps/erp/app/modules/items/items.service.ts+++ b/apps/erp/app/modules/items/items.service.ts@@ -1,12 +1,6 @@import type { Database, Json } from "@carbon/database";import { fetchAllFromTable } from "@carbon/database";import type { Kysely, KyselyDatabase } from "@carbon/database/client";-import type {- ConditionAst,- ItemRuleRow,- Severity,- TransactionSurface-} from "@carbon/utils";import { getLocalTimeZone, now, today } from "@internationalized/date";import type { SupabaseClient } from "@supabase/supabase-js";import { nanoid } from "nanoid";@@ -4152,218 +4146,3 @@ export async function getSupplierPartPriceBreaks(unitPrice: pb.unitPrice}));}--// ----------------------------------------------------------------------------// Item Rules-// -----------------------------------------------------------------------------type ItemRuleInsert = {- name: string;- description?: string | null;- message: string;- severity: Severity;- conditionAst: ConditionAst;- active: boolean;- companyId: string;- createdBy: string;- customFields?: Json;-};--type ItemRuleUpdate = {- id: string;- name: string;- description?: string | null;- message: string;- severity: Severity;- conditionAst: ConditionAst;- active: boolean;- updatedBy: string;- customFields?: Json;-};--export async function getItemRules(- client: SupabaseClient<Database>,- companyId: string,- args?: GenericQueryFilters & { search: string | null }-) {- let query = client- .from("itemRule")- .select("*", { count: "exact" })- .eq("companyId", companyId);-- if (args?.search) {- query = query.ilike("name", `%${args.search}%`);- }-- query = setGenericQueryFilters(query, args ?? {}, [- { column: "name", ascending: true }- ]);- return query;-}--export async function getItemRule(- client: SupabaseClient<Database>,- id: string-) {- return client.from("itemRule").select("*").eq("id", id).single();-}--export async function getItemRulesList(- client: SupabaseClient<Database>,- companyId: string-) {- return fetchAllFromTable<{- id: string;- name: string;- severity: Severity;- active: boolean;- surfaces: TransactionSurface[];- }>(client, "itemRule", "id, name, severity, active, surfaces", (query) =>- query.eq("companyId", companyId).order("name")- );-}--export async function upsertItemRule(- client: SupabaseClient<Database>,- rule: ItemRuleInsert | ItemRuleUpdate-) {- if ("createdBy" in rule) {- return client- .from("itemRule")- .insert({ ...rule, conditionAst: rule.conditionAst as unknown as Json })- .select("id")- .single();- }- return client- .from("itemRule")- .update({- ...sanitize(rule),- conditionAst: rule.conditionAst as unknown as Json,- // Full timestamp (not date-only) so the LRU cache in- // `compileWithCache` invalidates on every edit, not once per day.- updatedAt: now(getLocalTimeZone()).toAbsoluteString()- })- .eq("id", rule.id)- .select("id")- .single();-}--export async function deleteItemRule(- client: SupabaseClient<Database>,- id: string-) {- return client.from("itemRule").delete().eq("id", id);-}--/**- * Returns active rules assigned to a specific item.- * Single JOIN — never per-row lookups.- */-export async function getActiveRulesForItem(- client: SupabaseClient<Database>,- itemId: string,- companyId: string-): Promise<{ data: ItemRuleRow[]; error: unknown }> {- const batched = await getActiveRulesForItems(client, [itemId], companyId);- return { data: batched.data.get(itemId) ?? [], error: batched.error };-}--/**- * Batched variant — single round-trip + JOIN for N items. Use this when- * iterating over multiple items in one request (e.g. evaluating every line- * on a receipt) to avoid the N+1 round-trips you'd get from calling- * `getActiveRulesForItem` per item.- */-export async function getActiveRulesForItems(- client: SupabaseClient<Database>,- itemIds: string[],- companyId: string-): Promise<{ data: Map<string, ItemRuleRow[]>; error: unknown }> {- const out = new Map<string, ItemRuleRow[]>();- if (itemIds.length === 0) return { data: out, error: null };-- const { data, error } = await client- .from("itemRuleAssignment")- .select(- `itemId, itemRule:ruleId(id, severity, message, conditionAst, surfaces, updatedAt, active)`- )- .in("itemId", itemIds)- .eq("companyId", companyId);-- if (error) return { data: out, error };-- for (const r of data ?? []) {- // supabase returns the joined row either as object or array depending on FK shape.- // Cast through `unknown` because the generated `Database` types don't yet- // know about the `surfaces` column (run `bun run db:types` after the- // migration applies to refresh).- const row = r as unknown as {- itemId: string;- itemRule: ItemRuleRow | ItemRuleRow[] | null;- };- const node = Array.isArray(row.itemRule) ? row.itemRule[0] : row.itemRule;- if (!node || node.active === false) continue;- const bucket = out.get(row.itemId);- if (bucket) bucket.push(node);- else out.set(row.itemId, [node]);- }- return { data: out, error: null };-}--export async function getRuleAssignmentsForItem(- client: SupabaseClient<Database>,- itemId: string,- companyId: string-) {- return client- .from("itemRuleAssignment")- .select(- `itemId, ruleId, createdAt, itemRule:ruleId(id, name, severity, message, active, surfaces)`- )- .eq("itemId", itemId)- .eq("companyId", companyId);-}--export async function getRuleAssignmentCounts(- client: SupabaseClient<Database>,- ruleIds: string[]-) {- if (ruleIds.length === 0) return { data: {}, error: null };- const { data, error } = await client- .from("itemRuleAssignment")- .select("ruleId")- .in("ruleId", ruleIds);- if (error) return { data: {}, error };- const counts: Record<string, number> = {};- for (const row of data ?? []) {- counts[row.ruleId] = (counts[row.ruleId] ?? 0) + 1;- }- return { data: counts, error: null };-}--export async function assignItemRule(- client: SupabaseClient<Database>,- args: { itemId: string; ruleId: string; companyId: string; userId: string }-) {- return client- .from("itemRuleAssignment")- .insert({- itemId: args.itemId,- ruleId: args.ruleId,- companyId: args.companyId,- createdBy: args.userId- })- .select("itemId, ruleId")- .single();-}--export async function unassignItemRule(- client: SupabaseClient<Database>,- args: { itemId: string; ruleId: string }-) {- return client- .from("itemRuleAssignment")- .delete()- .eq("itemId", args.itemId)- .eq("ruleId", args.ruleId);-}diff --git a/apps/erp/app/modules/items/ui/ItemRules/ConditionRow.tsx b/apps/erp/app/modules/items/ui/ItemRules/ConditionRow.tsxdeleted file mode 100644index 6d1a5893ac..0000000000--- a/apps/erp/app/modules/items/ui/ItemRules/ConditionRow.tsx+++ /dev/null@@ -1,102 +0,0 @@-import { cn, IconButton } from "@carbon/react";-import {- type Condition,- type FieldDef,- getFieldDef,- type Operator-} from "@carbon/utils";-import { useLingui } from "@lingui/react/macro";-import { memo, useMemo } from "react";-import { LuX } from "react-icons/lu";-import FieldCombobox from "./FieldCombobox";-import OperatorCombobox from "./OperatorCombobox";-import type { ValueOptionsByLoader } from "./useValueOptions";-import ValueInput from "./ValueInput";--export const CONDITION_GRID_CLASS =- "grid grid-cols-1 gap-2 sm:grid-cols-[minmax(0,1.2fr)_minmax(0,0.9fr)_minmax(0,1fr)]";--type ConditionRowProps = {- condition: Condition;- index: number;- canRemove: boolean;- onChange: (index: number, patch: Partial<Condition>) => void;- onRemove: (index: number) => void;- optionsByLoader: ValueOptionsByLoader;-};--function ConditionRowImpl({- condition,- index,- canRemove,- onChange,- onRemove,- optionsByLoader-}: ConditionRowProps) {- const { t } = useLingui();-- const fieldDef = useMemo<FieldDef | undefined>(- () => getFieldDef(condition.field),- [condition.field]- );-- const valueOptions = useMemo(- () =>- fieldDef?.valueOptionsLoader- ? optionsByLoader[fieldDef.valueOptionsLoader]- : undefined,- [fieldDef, optionsByLoader]- );-- return (- <div className="flex w-full items-center gap-2">- <div- className={cn(- "group flex-1 min-w-0 rounded-lg border border-border bg-card p-3",- "transition-colors hover:border-border/80"- )}- >- <div className={CONDITION_GRID_CLASS}>- <FieldCombobox- value={condition.field}- onChange={(path) =>- onChange(index, { field: path, op: "eq", value: undefined })- }- />-- <OperatorCombobox- value={condition.op}- onChange={(op: Operator) =>- onChange(index, { op, value: undefined })- }- available={fieldDef?.operators ?? []}- disabled={!fieldDef}- />-- <ValueInput- fieldDef={fieldDef}- op={condition.op}- value={condition.value}- options={valueOptions}- onChange={(next) => onChange(index, { value: next })}- />- </div>- </div>-- <IconButton- icon={<LuX />}- aria-label={t`Remove condition`}- variant="ghost"- size="sm"- onClick={() => onRemove(index)}- isDisabled={!canRemove}- className={cn(- "shrink-0",- !canRemove && "opacity-0 pointer-events-none"- )}- />- </div>- );-}--export default memo(ConditionRowImpl);diff --git a/apps/erp/app/modules/items/ui/ItemRules/FieldCombobox.tsx b/apps/erp/app/modules/items/ui/ItemRules/FieldCombobox.tsxdeleted file mode 100644index 4a24a818fd..0000000000--- a/apps/erp/app/modules/items/ui/ItemRules/FieldCombobox.tsx+++ /dev/null@@ -1,165 +0,0 @@-import {- Command,- CommandEmpty,- CommandGroup,- CommandInput,- CommandItem,- CommandList,- CommandSeparator,- CommandTrigger,- cn,- Popover,- PopoverContent,- PopoverTrigger-} from "@carbon/react";-import { FIELD_REGISTRY, type FieldDef, getFieldDef } from "@carbon/utils";-import { useLingui } from "@lingui/react/macro";-import { useMemo, useState } from "react";-import {- LuBox,- LuCheck,- LuChevronDown,- LuPackage,- LuReceipt-} from "react-icons/lu";--const CONTEXT: Record<- FieldDef["context"],- { label: string; icon: JSX.Element }-> = {- item: { label: "Item", icon: <LuPackage className="h-3.5 w-3.5" /> },- storage: { label: "Storage", icon: <LuBox className="h-3.5 w-3.5" /> },- transaction: {- label: "Transaction",- icon: <LuReceipt className="h-3.5 w-3.5" />- }-};--const CONTEXT_ORDER: FieldDef["context"][] = ["item", "storage", "transaction"];--type FieldComboboxProps = {- value: string;- onChange: (path: string) => void;- placeholder?: string;- className?: string;-};--export default function FieldCombobox({- value,- onChange,- placeholder,- className-}: FieldComboboxProps) {- const { t } = useLingui();- const [open, setOpen] = useState(false);-- const grouped = useMemo(() => {- const map = new Map<FieldDef["context"], FieldDef[]>();- for (const ctx of CONTEXT_ORDER) map.set(ctx, []);- for (const f of FIELD_REGISTRY) map.get(f.context)!.push(f);- return map;- }, []);-- const selected = useMemo(() => getFieldDef(value), [value]);- const ctx = selected ? CONTEXT[selected.context] : undefined;-- return (- <Popover open={open} onOpenChange={setOpen}>- <PopoverTrigger asChild>- <CommandTrigger- size="md"- role="combobox"- aria-expanded={open}- icon={<LuChevronDown className="h-4 w-4 shrink-0 opacity-50" />}- className={cn(- "min-w-[180px] w-full",- !selected && "text-muted-foreground",- className- )}- onClick={() => setOpen(true)}- >- {selected && ctx ? (- <div className="flex min-w-0 flex-1 items-center gap-2 text-left">- <div- className="flex h-5 w-5 shrink-0 items-center justify-center rounded bg-muted text-muted-foreground"- title={ctx.label}- role="img"- aria-label={ctx.label}- >- {ctx.icon}- </div>- <div className="truncate text-foreground">{selected.label}</div>- </div>- ) : (- <div className="truncate">{placeholder ?? t`Select field`}</div>- )}- </CommandTrigger>- </PopoverTrigger>- <PopoverContent- align="start"- onWheel={(e) => e.stopPropagation()}- onTouchMove={(e) => e.stopPropagation()}- className="w-[var(--radix-popover-trigger-width)] min-w-[320px] p-0"- >- <Command>- <CommandInput placeholder={t`Search fields...`} className="h-10" />- <CommandList- className="max-h-[320px] overflow-y-auto overscroll-contain"- onWheel={(e) => e.stopPropagation()}- >- <CommandEmpty>{t`No fields found.`}</CommandEmpty>- {(() => {- const visibleCtx = CONTEXT_ORDER.filter(- (k) => (grouped.get(k) ?? []).length > 0- );- return visibleCtx.map((ctxKey, gi) => {- const fields = grouped.get(ctxKey) ?? [];- const meta = CONTEXT[ctxKey];- return (- <div key={ctxKey}>- {gi > 0 && <CommandSeparator />}- <CommandGroup- heading={- <span className="flex items-center gap-1.5 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground">- {meta.icon}- {meta.label}- </span>- }- >- {fields.map((f) => (- <CommandItem- key={f.path}- value={`${meta.label} ${f.label} ${f.path}`}- onSelect={() => {- onChange(f.path);- setOpen(false);- }}- className="flex items-center gap-2 px-2 py-2"- >- <span className="flex min-w-0 flex-1 flex-col">- <span className="truncate text-sm font-medium">- {f.label}- </span>- <span className="truncate text-xs text-muted-foreground">- {f.path}- </span>- </span>- <LuCheck- className={cn(- "h-4 w-4 shrink-0",- value === f.path ? "opacity-100" : "opacity-0"- )}- />- </CommandItem>- ))}- </CommandGroup>- </div>- );- });- })()}- </CommandList>- </Command>- </PopoverContent>- </Popover>- );-}diff --git a/apps/erp/app/modules/items/ui/ItemRules/ItemRuleAssignments.tsx b/apps/erp/app/modules/items/ui/ItemRules/ItemRuleAssignments.tsxdeleted file mode 100644index 4ae6ff8132..0000000000--- a/apps/erp/app/modules/items/ui/ItemRules/ItemRuleAssignments.tsx+++ /dev/null@@ -1,346 +0,0 @@-import {- Badge,- Button,- Card,- CardAction,- CardContent,- CardDescription,- CardHeader,- CardTitle,- Combobox,- HStack,- IconButton,- Status,- Table,- Tbody,- Td,- Th,- Thead,- Tr-} from "@carbon/react";-import type { TransactionSurface } from "@carbon/utils";-import { Trans, useLingui } from "@lingui/react/macro";-import { useMemo } from "react";-import { LuLibrary, LuPlus, LuShieldCheck, LuTrash } from "react-icons/lu";-import { Form, Link, useFetcher } from "react-router";-import { Hyperlink } from "~/components";-import {- UpgradeOverlayActions,- UpgradeOverlayContent,- UpgradeOverlayDescription,- UpgradeOverlayIcon,- UpgradeOverlayTitle,- UpgradeOverlayUpgradeButton-} from "~/components/UpgradeOverlay";-import { usePermissions } from "~/hooks";-import { usePlanGate } from "~/hooks/usePlanGate";-import { path } from "~/utils/path";-import SurfaceChips from "./SurfaceChips";--type AssignedRule = {- ruleId: string;- rule: {- id: string;- name: string;- severity: "error" | "warn";- message: string;- active: boolean;- surfaces?: TransactionSurface[];- };-};--type LibraryRule = {- id: string;- name: string;- severity: "error" | "warn";- active: boolean;-};--type ItemRuleAssignmentsProps = {- itemId: string;- assignments: AssignedRule[];- library: LibraryRule[];-};--export default function ItemRuleAssignments({- itemId,- assignments,- library-}: ItemRuleAssignmentsProps) {- const { t } = useLingui();- const permissions = usePermissions();- const fetcher = useFetcher();- const { isGated } = usePlanGate({ feature: "ITEM_RULES" });- const canCreate = permissions.can("create", "parts");- const canDelete = permissions.can("delete", "parts");-- const assignedSet = useMemo(- () => new Set(assignments.map((a) => a.ruleId)),- [assignments]- );-- const available = useMemo(- () => library.filter((r) => r.active && !assignedSet.has(r.id)),- [library, assignedSet]- );-- const availableOptions = useMemo(- () => available.map((r) => ({ value: r.id, label: r.name })),- [available]- );-- const handleAssign = (ruleId: string) => {- if (!ruleId) return;- const fd = new FormData();- fd.set("ruleId", ruleId);- fetcher.submit(fd, {- method: "post",- action: path.to.itemRuleAssign(itemId)- });- };-- const isEmpty = assignments.length === 0;-- if (isGated) {- return (- <Card className="flex-grow">- <CardHeader>- <CardTitle>- <Trans>Rules</Trans>- </CardTitle>- <CardDescription>- <Trans>- Enforce constraints on receipts, shipments, transfers and job- operations for this item.- </Trans>- </CardDescription>- </CardHeader>- <CardContent>- <div className="flex flex-col items-center justify-center gap-4 py-10 text-center">- <UpgradeOverlayIcon>- <LuShieldCheck className="size-6 text-muted-foreground" />- </UpgradeOverlayIcon>- <UpgradeOverlayContent>- <UpgradeOverlayTitle>- <Trans>Upgrade to unlock item rules</Trans>- </UpgradeOverlayTitle>- <UpgradeOverlayDescription>- <Trans>- Enforce per-item validation across receipts, shipments,- transfers and adjustments.- </Trans>- </UpgradeOverlayDescription>- </UpgradeOverlayContent>- <UpgradeOverlayActions>- <UpgradeOverlayUpgradeButton />- </UpgradeOverlayActions>- </div>- </CardContent>- </Card>- );- }-- return (- <Card className="flex-grow">- <HStack className="justify-between items-start">- <CardHeader>- <CardTitle>- <HStack className="gap-2 items-baseline">- <span>- <Trans>Rules</Trans>- </span>- {!isEmpty && (- <span className="text-sm text-muted-foreground tabular-nums">- {assignments.length}- </span>- )}- </HStack>- </CardTitle>- <CardDescription>- <Trans>- Enforce constraints on receipts, shipments, transfers and job- operations for this item.- </Trans>- </CardDescription>- </CardHeader>- {!isEmpty && canCreate && (- <CardAction>- <HStack className="gap-2">- {availableOptions.length > 0 && (- <Combobox- value=""- options={availableOptions}- onChange={handleAssign}- placeholder={t`Add from library…`}- />- )}- <Button asChild>- <Link to={path.to.newItemRule}>- <Trans>Add rule</Trans>- </Link>- </Button>- </HStack>- </CardAction>- )}- </HStack>-- <CardContent>- {isEmpty ? (- <EmptyState- availableOptions={availableOptions}- canCreate={canCreate}- onAssign={handleAssign}- />- ) : (- <Table>- <Thead>- <Tr>- <Th>- <Trans>Name</Trans>- </Th>- <Th>- <Trans>Severity</Trans>- </Th>- <Th>- <Trans>Surfaces</Trans>- </Th>- <Th>- <Trans>Status</Trans>- </Th>- <Th>- <Trans>Message</Trans>- </Th>- <Th />- </Tr>- </Thead>- <Tbody>- {assignments.map((a) => (- <Tr key={a.ruleId}>- <Td className="whitespace-nowrap">- <Hyperlink to={path.to.itemRule(a.ruleId)}>- <HStack className="gap-2 items-center">- <LuShieldCheck className="text-muted-foreground shrink-0" />- <span>{a.rule.name}</span>- </HStack>- </Hyperlink>- </Td>- <Td>- {a.rule.severity === "error" ? (- <Badge variant="red">- <Trans>Error</Trans>- </Badge>- ) : (- <Badge variant="yellow">- <Trans>Warning</Trans>- </Badge>- )}- </Td>- <Td>- <SurfaceChips surfaces={a.rule.surfaces} />- </Td>- <Td>- {a.rule.active ? (- <Status color="green">- <Trans>Active</Trans>- </Status>- ) : (- <Status color="gray">- <Trans>Inactive</Trans>- </Status>- )}- </Td>- <Td className="w-full max-w-0">- <p className="text-muted-foreground truncate max-w-xl">- {a.rule.message}- </p>- </Td>- <Td className="text-right">- <Form- method="post"- action={path.to.itemRuleUnassign(itemId, a.ruleId)}- >- <IconButton- type="submit"- icon={<LuTrash />}- aria-label={t`Unassign rule`}- variant="ghost"- size="sm"- isDisabled={!canDelete}- />- </Form>- </Td>- </Tr>- ))}- </Tbody>- </Table>- )}- </CardContent>- </Card>- );-}--type EmptyStateProps = {- availableOptions: { value: string; label: string }[];- canCreate: boolean;- onAssign: (ruleId: string) => void;-};--function EmptyState({- availableOptions,- canCreate,- onAssign-}: EmptyStateProps) {- const { t } = useLingui();- return (- <div className="flex flex-col items-center justify-center gap-5 py-10 text-center">- <div className="flex size-14 items-center justify-center rounded-full bg-muted">- <LuShieldCheck className="size-6 text-muted-foreground" />- </div>-- <div className="flex flex-col gap-1.5 max-w-md">- <p className="text-base font-medium">- <Trans>No rules assigned</Trans>- </p>- <p className="text-sm text-muted-foreground">- <Trans>- Pick an existing rule from the library or create a new one to start- enforcing constraints on this item.- </Trans>- </p>- </div>-- {canCreate && (- <HStack className="gap-2 flex-wrap justify-center pt-1">- {availableOptions.length > 0 ? (- <>- <Combobox- value=""- options={availableOptions}- onChange={onAssign}- placeholder={t`Add from library…`}- />- <Button asChild variant="secondary" leftIcon={<LuPlus />}>- <Link to={path.to.newItemRule}>- <Trans>Create new rule</Trans>- </Link>- </Button>- </>- ) : (- <>- <Button asChild variant="secondary" leftIcon={<LuLibrary />}>- <Link to={path.to.itemRules}>- <Trans>Browse library</Trans>- </Link>- </Button>- <Button asChild leftIcon={<LuPlus />}>- <Link to={path.to.newItemRule}>- <Trans>Create new rule</Trans>- </Link>- </Button>- </>- )}- </HStack>- )}- </div>- );-}diff --git a/apps/erp/app/modules/items/ui/ItemRules/ValueInput.tsx b/apps/erp/app/modules/items/ui/ItemRules/ValueInput.tsxdeleted file mode 100644index a4b935126d..0000000000--- a/apps/erp/app/modules/items/ui/ItemRules/ValueInput.tsx+++ /dev/null@@ -1,157 +0,0 @@-import {- Input,- NumberDecrementStepper,- NumberField,- NumberIncrementStepper,- NumberInput,- NumberInputGroup,- NumberInputStepper-} from "@carbon/react";-import type { FieldDef, Operator } from "@carbon/utils";-import { useLingui } from "@lingui/react/macro";-import { memo } from "react";-import { LuChevronDown, LuChevronUp } from "react-icons/lu";-import MultiValueCombobox from "./MultiValueCombobox";-import type { ValueOption } from "./useValueOptions";-import ValueCombobox from "./ValueCombobox";--type ValueInputProps = {- fieldDef: FieldDef | undefined;- op: Operator;- value: unknown;- onChange: (next: unknown) => void;- options: ValueOption[] | undefined;-};--const isMultiOp = (op: Operator) => op === "in" || op === "notIn";-const isPresenceOp = (op: Operator) => op === "isSet" || op === "isNotSet";--function ValueInputImpl({- fieldDef,- op,- value,- onChange,- options-}: ValueInputProps) {- const { t } = useLingui();-- // Presence ops — no value control. Render dashed placeholder pill so the- // grid column stays the same width (matches existing visual treatment).- // Height matches CommandTrigger size="md" (h-10) so the row stays aligned.- if (isPresenceOp(op)) {- return (- <div className="flex h-10 items-center rounded-md border border-dashed border-border px-3 text-xs text-muted-foreground">- {t`No value needed`}- </div>- );- }-- // Render the autocomplete combobox whenever the field declares a loader,- // even if `options` is currently empty. The fetcher hooks populate- // asynchronously on mount; an empty array still renders a usable Combobox- // (showing the "no values" empty state) which then re-renders with options- // when the fetch resolves. Falling through to a text input on empty was the- // bug — the input got "stuck" until the user re-selected the field.- const hasOptions = !!fieldDef?.valueOptionsLoader && !!options;- const multi = isMultiOp(op);-- // Multi-select with a known options loader — supplies a real string[] array- // straight to the AST (no comma-split parsing needed).- if (multi && hasOptions) {- const arrValue = Array.isArray(value)- ? value.map(String).filter(Boolean)- : [];- return (- <MultiValueCombobox- value={arrValue}- onChange={(next) => onChange(next)}- options={options!}- placeholder={t`Select values`}- />- );- }-- // Single-select autocomplete — used for any scalar op on a field with a- // loader. Local component for visual parity with FieldCombobox /- // OperatorCombobox (chevron trigger, same height, full-width).- if (!multi && hasOptions) {- const strValue =- typeof value === "string" || typeof value === "number"- ? String(value)- : "";- return (- <ValueCombobox- value={strValue}- onChange={(next) => onChange(next)}- options={options!}- placeholder={t`Select value`}- />- );- }-- // Numeric input — only valid on scalar ops; multi on a numeric field falls- // through to the comma-separated text path below.- if (!multi && fieldDef?.type === "number") {- const numValue =- typeof value === "number"- ? value- : typeof value === "string" && value !== ""- ? Number(value)- : Number.NaN;- return (- <NumberField- value={Number.isNaN(numValue) ? undefined : numValue}- onChange={(n) =>- onChange(typeof n === "number" && !Number.isNaN(n) ? n : undefined)- }- aria-label={t`Number`}- >- <NumberInputGroup className="relative">- <NumberInput placeholder={t`Number`} />- <NumberInputStepper>- <NumberIncrementStepper>- <LuChevronUp size="1em" strokeWidth="3" />- </NumberIncrementStepper>- <NumberDecrementStepper>- <LuChevronDown size="1em" strokeWidth="3" />- </NumberDecrementStepper>- </NumberInputStepper>- </NumberInputGroup>- </NumberField>- );- }-- // Fallback — string input. Multi-value without a loader stays as- // comma-separated text so users can still type literal sets (e.g. on custom- // fields where no option list is known).- const display =- value == null- ? ""- : Array.isArray(value)- ? value.join(", ")- : String(value);-- return (- <Input- size="md"- type="text"- placeholder={multi ? t`comma-separated values` : t`Value`}- value={display}- onChange={(e) => {- const raw = e.target.value;- if (multi) {- onChange(- raw- .split(",")- .map((s) => s.trim())- .filter(Boolean)- );- } else {- onChange(raw);- }- }}- />- );-}--export default memo(ValueInputImpl);diff --git a/apps/erp/app/modules/items/ui/useItemsSubmodules.tsx b/apps/erp/app/modules/items/ui/useItemsSubmodules.tsxindex 87468fa553..b2882635e1 100644--- a/apps/erp/app/modules/items/ui/useItemsSubmodules.tsx+++ b/apps/erp/app/modules/items/ui/useItemsSubmodules.tsx@@ -11,8 +11,7 @@ import {LuPizza,LuPuzzle,LuRuler,- LuShapes,- LuShieldCheck+ LuShapes} from "react-icons/lu";import { usePermissions } from "~/hooks";import { useSavedViews } from "~/hooks/useSavedViews";@@ -103,12 +102,6 @@ export default function useItemsSubmodules() {role: "employee",icon: <LuGroup />},- {- name: t`Rules`,- to: path.to.itemRules,- role: "employee",- icon: <LuShieldCheck />- },{name: t`Units`,to: path.to.uoms,diff --git a/apps/erp/app/modules/settings/ui/AuditLog/AuditLogTable.tsx b/apps/erp/app/modules/settings/ui/AuditLog/AuditLogTable.tsxindex d0f0e0dbee..9797f48960 100644--- a/apps/erp/app/modules/settings/ui/AuditLog/AuditLogTable.tsx+++ b/apps/erp/app/modules/settings/ui/AuditLog/AuditLogTable.tsx@@ -1,4 +1,5 @@import {+ auditConfig,getEntityLabel,getEntityTypes,getTableLabel@@ -108,8 +109,30 @@ const InlineDiff = memo();InlineDiff.displayName = "InlineDiff";+// Hide globally-skipped columns (and any nested suffix) from the rendered+// diff. Defense-in-depth — backend strips skipFields too, but legacy entries+// or newly-added skipFields can slip through.+function isSkippedDiffKey(key: string): boolean {+ console.log(key, "KEY");+ const skip = auditConfig.skipFields as readonly string[];+ for (let i = 0; i < skip.length; i++) {+ const s = skip[i]!;+ if (key === s || key.endsWith(`.${s}`)) return true;+ }+ return false;+}++function visibleDiffEntries(+ diff: AuditDiff | null | undefined+): [string, AuditDiff[string]][] {+ console.log(diff);+ if (!diff) return [];+ return Object.entries(diff).filter(([k]) => !isSkippedDiffKey(k));+}+const ExpandedRowContent = memo(({ entry }: { entry: AuditLogEntry }) => {- const hasDiff = entry.diff && Object.keys(entry.diff).length > 0;+ const visibleEntries = visibleDiffEntries(entry.diff);+ const hasDiff = visibleEntries.length > 0;return (<div className="px-6 py-4">@@ -138,16 +161,14 @@ const ExpandedRowContent = memo(({ entry }: { entry: AuditLogEntry }) => {<h4 className="text-sm font-medium mb-2">Changes</h4>{hasDiff ? (<div className="space-y-1">- {Object.entries(entry.diff as AuditDiff).map(- ([fieldName, change]) => (- <InlineDiff- key={fieldName}- fieldName={fieldName}- oldValue={change.old}- newValue={change.new}- />- )- )}+ {visibleEntries.map(([fieldName, change]) => (+ <InlineDiff+ key={fieldName}+ fieldName={fieldName}+ oldValue={change.old}+ newValue={change.new}+ />+ ))}</div>) : (<p className="text-sm text-muted-foreground italic">@@ -258,13 +279,11 @@ const AuditLogTable = memo(({ entries, count }: AuditLogTableProps) => {header: t`Changes`,cell: ({ row }) => {const entry = row.original;- const hasDiff = entry.diff && Object.keys(entry.diff).length > 0;+ const visibleCount = visibleDiffEntries(entry.diff).length;return (<span className="text-sm text-muted-foreground">- {hasDiff- ? `${Object.keys(entry.diff!).length} change${- Object.keys(entry.diff!).length !== 1 ? "s" : ""- }`+ {visibleCount > 0+ ? `${visibleCount} change${visibleCount !== 1 ? "s" : ""}`: "-"}</span>);diff --git a/apps/erp/app/modules/settings/ui/useSettingsSubmodules.tsx b/apps/erp/app/modules/settings/ui/useSettingsSubmodules.tsxindex 82cd6fa1b4..45347c6382 100644--- a/apps/erp/app/modules/settings/ui/useSettingsSubmodules.tsx+++ b/apps/erp/app/modules/settings/ui/useSettingsSubmodules.tsx@@ -15,6 +15,7 @@ import {LuLayoutDashboard,LuNetwork,LuSheet,+ LuShieldCheck,LuShoppingCart,LuSquareStack,LuUsers,@@ -150,6 +151,12 @@ export default function useSettingsSubmodules() {role: "employee",icon: <LuCircleCheck />},+ {+ name: t`Custom Rules`,+ to: path.to.customRules,+ role: "employee",+ icon: <LuShieldCheck />+ },{name: t`Audit Logs`,to: path.to.auditLog,diff --git a/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json b/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.jsonindex 676271884e..edb0a8026c 100644--- a/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json+++ b/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json@@ -1,5 +1,5 @@{- "generated": "2026-05-18T03:08:48.451Z",+ "generated": "2026-05-25T08:17:47.779Z","totalTools": 1075,"modules": 15,"tools": [diff --git a/apps/erp/app/routes/x+/consumable+/$itemId.inventory.tsx b/apps/erp/app/routes/x+/consumable+/$itemId.inventory.tsxindex 51b0f30b13..16ce5537ba 100644--- a/apps/erp/app/routes/x+/consumable+/$itemId.inventory.tsx+++ b/apps/erp/app/routes/x+/consumable+/$itemId.inventory.tsx@@ -1,6 +1,7 @@import { assertIsPost, error, success } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";+import { getCustomRulesDataForTarget } from "@carbon/ee/custom-rules.server";import { validationError, validator } from "@carbon/form";import { VStack } from "@carbon/react";import { pluckUnique } from "@carbon/utils";@@ -8,11 +9,11 @@ import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";import { redirect, useLoaderData } from "react-router";import { useStorageUnits } from "~/components/Form/StorageUnit";import { useRouteData } from "~/hooks";+import RuleAssignmentsList from "~/modules/customRules/ui/RuleAssignmentsList";import {getTrackedEntityExpirations,InventoryDetails} from "~/modules/inventory";-import type { Consumable, UnitOfMeasureListItem } from "~/modules/items";import {getBomHasShelfLifeManagedInput,@@ -25,9 +26,7 @@ import {upsertPickMethod,upsertPickMethodWithShelfLife} from "~/modules/items";-import { getItemRulesDataForItem } from "~/modules/items/itemRules.server";import { PickMethodForm } from "~/modules/items/ui/Item";-import ItemRuleAssignments from "~/modules/items/ui/ItemRules/ItemRuleAssignments";import { getLocationsList } from "~/modules/resources";import { getUserDefaults } from "~/modules/users/users.server";import { getDatabaseClient } from "~/services/database.server";@@ -166,7 +165,11 @@ export async function loader({ request, params }: LoaderFunctionArgs) {getItemShelfLife(client, itemId),getBomHasShelfLifeManagedInput(client, itemId, companyId),getTrackedEntityExpirations(client, trackedEntityIds),- getItemRulesDataForItem(client, itemId, companyId)+ getCustomRulesDataForTarget(client, {+ targetType: "item",+ targetId: itemId,+ companyId+ })]);return {@@ -305,8 +308,9 @@ export default function ConsumableInventoryRoute() {quantities={quantities}storageUnits={storageUnits.options}/>- <ItemRuleAssignments- itemId={itemId}+ <RuleAssignmentsList+ targetType="item"+ targetId={itemId}assignments={ruleAssignments as never}library={ruleLibrary as never}/>diff --git a/apps/erp/app/routes/x+/inventory+/quantities+/$itemId.adjustment.tsx b/apps/erp/app/routes/x+/inventory+/quantities+/$itemId.adjustment.tsxindex 7a590ebbcd..211b4acac4 100644--- a/apps/erp/app/routes/x+/inventory+/quantities+/$itemId.adjustment.tsx+++ b/apps/erp/app/routes/x+/inventory+/quantities+/$itemId.adjustment.tsx@@ -2,6 +2,11 @@ import { assertIsPost, error } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { getCarbonServiceRole } from "@carbon/auth/client.server";import { flash } from "@carbon/auth/session.server";+import {+ dedupeViolations,+ evaluateLinesForSurface,+ isBlocked+} from "@carbon/ee/custom-rules.server";import { validationError, validator } from "@carbon/form";import type { ActionFunctionArgs } from "react-router";import { redirect } from "react-router";@@ -9,10 +14,6 @@ import {insertManualInventoryAdjustment,inventoryAdjustmentValidator} from "~/modules/inventory";-import {- evaluateLinesForSurface,- isBlocked-} from "~/modules/items/itemRules.server";import { path, requestReferrer } from "~/utils/path";export async function action({ request, params }: ActionFunctionArgs) {@@ -35,30 +36,62 @@ export async function action({ request, params }: ActionFunctionArgs) {const { ...d } = validation.data;const acknowledged = formData.get("acknowledged") === "true";- // Item Rule evaluation. Single synthetic line covering the adjustment.+ // Business rule evaluation. Item-target rules fire on+ // `inventoryAdjustment` surface. Storage-unit-target rules fire on+ // `place` when the adjustment lands stock in a bin (positive delta) and+ // `pick` when it removes from a bin (negative delta) — so warehouse rules+ // tied to those surfaces also kick in for manual adjustments.const serviceRole = getCarbonServiceRole();- const { violations, ruleNames } = await evaluateLinesForSurface({+ const qty = Number(d.quantity ?? 0);+ const evalLine = [+ {+ lineId: itemId,+ itemId,+ storageUnitId: d.storageUnitId ?? null,+ quantity: qty,+ locationId: d.locationId+ }+ ];++ const itemPass = await evaluateLinesForSurface({client: serviceRole,companyId,userId,+ targetType: "item",surface: "inventoryAdjustment",- lines: [- {- lineId: itemId,- itemId,- storageUnitId: d.storageUnitId ?? null,- quantity: Number(d.quantity ?? 0),- locationId: d.locationId- }- ]+ lines: evalLine});- if (violations.length > 0 && isBlocked(violations, acknowledged)) {+ const allViolations = [...itemPass.violations];+ const allRuleNames: Record<string, string> = { ...itemPass.ruleNames };++ if (d.storageUnitId) {+ // Pick storage-unit surface from `adjustmentType` only. `quantity` is a+ // positive magnitude per `inventoryAdjustmentValidator` — sign-based+ // direction detection would misclassify `Negative Adjmt.` as `place`.+ const isNegative = d.adjustmentType === "Negative Adjmt.";+ const storageSurface: "place" | "pick" = isNegative ? "pick" : "place";++ const storagePass = await evaluateLinesForSurface({+ client: serviceRole,+ companyId,+ userId,+ targetType: "storageUnit",+ surface: storageSurface,+ lines: evalLine+ });+ allViolations.push(...storagePass.violations);+ Object.assign(allRuleNames, storagePass.ruleNames);+ }++ const deduped = dedupeViolations(allViolations);++ if (deduped.length > 0 && isBlocked(deduped, acknowledged)) {return {error: null,data: null,- violations,- ruleNames+ violations: deduped,+ ruleNames: allRuleNames};}diff --git a/apps/erp/app/routes/x+/inventory+/quantities.tsx b/apps/erp/app/routes/x+/inventory+/quantities.tsxindex e2baa47e5a..39007ee3b2 100644--- a/apps/erp/app/routes/x+/inventory+/quantities.tsx+++ b/apps/erp/app/routes/x+/inventory+/quantities.tsx@@ -9,7 +9,8 @@ import type { InventoryItem } from "~/modules/inventory";import {expandStorageUnitIdsWithDescendants,getInventoryItems,- getStorageTypesList+ getStorageTypesList,+ getStorageUnitsList} from "~/modules/inventory";import InventoryTable from "~/modules/inventory/ui/Inventory/InventoryTable";import {@@ -75,7 +76,7 @@ export async function loader({ request }: LoaderFunctionArgs) {locationId = locations.data?.[0].id as string;}- const [inventoryItems, forms, substances, tags, storageTypes] =+ const [inventoryItems, forms, substances, tags, storageTypes, storageUnits] =await Promise.all([getInventoryItems(client, locationId, companyId, {search,@@ -87,7 +88,8 @@ export async function loader({ request }: LoaderFunctionArgs) {getMaterialFormsList(client, companyId),getMaterialSubstancesList(client, companyId),getTagsList(client, companyId),- getStorageTypesList(client, companyId)+ getStorageTypesList(client, companyId),+ getStorageUnitsList(client, companyId)]);if (inventoryItems.error) {@@ -109,7 +111,8 @@ export async function loader({ request }: LoaderFunctionArgs) {forms: forms.data ?? [],substances: substances.data ?? [],tags: uniqueTags,- storageTypes: storageTypes.data ?? []+ storageTypes: storageTypes.data ?? [],+ storageUnits: storageUnits.data ?? []};}@@ -121,7 +124,8 @@ export default function QuantitiesRoute() {forms,substances,tags,- storageTypes+ storageTypes,+ storageUnits} = useLoaderData<typeof loader>();return (@@ -141,6 +145,7 @@ export default function QuantitiesRoute() {substances={substances}tags={tags}storageTypes={storageTypes}+ storageUnits={storageUnits}/></ResizablePanel><Outlet />diff --git a/apps/erp/app/routes/x+/inventory+/storage-units.$storageUnitId.rules.tsx b/apps/erp/app/routes/x+/inventory+/storage-units.$storageUnitId.rules.tsxnew file mode 100644index 0000000000..9a5d843013--- /dev/null+++ b/apps/erp/app/routes/x+/inventory+/storage-units.$storageUnitId.rules.tsx@@ -0,0 +1,77 @@+import { notFound } from "@carbon/auth";+import { requirePermissions } from "@carbon/auth/auth.server";+import { getCustomRulesDataForTarget } from "@carbon/ee/custom-rules.server";+import {+ Button,+ HStack,+ ModalDrawer,+ ModalDrawerBody,+ ModalDrawerContent,+ ModalDrawerFooter,+ ModalDrawerHeader,+ ModalDrawerProvider,+ ModalDrawerTitle+} from "@carbon/react";+import { Trans } from "@lingui/react/macro";+import type { LoaderFunctionArgs } from "react-router";+import { useLoaderData, useNavigate } from "react-router";+import RuleAssignmentsList from "~/modules/customRules/ui/RuleAssignmentsList";++export async function loader({ request, params }: LoaderFunctionArgs) {+ const { client, companyId } = await requirePermissions(request, {+ view: "inventory",+ role: "employee"+ });+ const { storageUnitId } = params;+ if (!storageUnitId) throw notFound("storageUnitId required");++ const data = await getCustomRulesDataForTarget(client, {+ targetType: "storageUnit",+ targetId: storageUnitId,+ companyId+ });++ return { storageUnitId, ...data };+}++export default function StorageUnitRulesRoute() {+ const { storageUnitId, assignments, library } =+ useLoaderData<typeof loader>();+ const navigate = useNavigate();+ const onClose = () => navigate(-1);++ return (+ <ModalDrawerProvider type="drawer">+ <ModalDrawer+ open+ onOpenChange={(open) => {+ if (!open) onClose();+ }}+ >+ <ModalDrawerContent size="lg">+ <ModalDrawerHeader>+ <ModalDrawerTitle>+ <Trans>Storage unit rules</Trans>+ </ModalDrawerTitle>+ </ModalDrawerHeader>+ <ModalDrawerBody>+ <RuleAssignmentsList+ targetType="storageUnit"+ targetId={storageUnitId}+ assignments={assignments as never}+ library={library as never}+ variant="flat"+ />+ </ModalDrawerBody>+ <ModalDrawerFooter>+ <HStack>+ <Button variant="solid" onClick={onClose}>+ <Trans>Close</Trans>+ </Button>+ </HStack>+ </ModalDrawerFooter>+ </ModalDrawerContent>+ </ModalDrawer>+ </ModalDrawerProvider>+ );+}diff --git a/apps/erp/app/routes/x+/inventory+/storage-units.$storageUnitId.tsx b/apps/erp/app/routes/x+/inventory+/storage-units.$storageUnitId.tsxindex e07d462b2e..6e40c0451f 100644--- a/apps/erp/app/routes/x+/inventory+/storage-units.$storageUnitId.tsx+++ b/apps/erp/app/routes/x+/inventory+/storage-units.$storageUnitId.tsx@@ -7,7 +7,13 @@ import type {ClientActionFunctionArgs,LoaderFunctionArgs} from "react-router";-import { data, redirect, useLoaderData, useNavigate } from "react-router";+import {+ data,+ Outlet,+ redirect,+ useLoaderData,+ useNavigate+} from "react-router";import {getStorageUnit,StorageUnitForm,@@ -110,11 +116,14 @@ export default function EditStorageUnitRoute() {};return (- <StorageUnitForm- key={initialValues.id}- initialValues={initialValues}- locationId={initialValues.locationId}- onClose={() => navigate(-1)}- />+ <>+ <StorageUnitForm+ key={initialValues.id}+ initialValues={initialValues}+ locationId={initialValues.locationId}+ onClose={() => navigate(-1)}+ />+ <Outlet />+ </>);}diff --git a/apps/erp/app/routes/x+/inventory+/storage-units.rules.assign.$storageUnitId.tsx b/apps/erp/app/routes/x+/inventory+/storage-units.rules.assign.$storageUnitId.tsxnew file mode 100644index 0000000000..2c31cd9ac4--- /dev/null+++ b/apps/erp/app/routes/x+/inventory+/storage-units.rules.assign.$storageUnitId.tsx@@ -0,0 +1,74 @@+import { assertIsPost, error, success } from "@carbon/auth";+import { requirePermissions } from "@carbon/auth/auth.server";+import { flash } from "@carbon/auth/session.server";+import { requirePlan } from "@carbon/ee/plan.server";+import type {+ ActionFunctionArgs,+ ClientActionFunctionArgs+} from "react-router";+import { redirect } from "react-router";+import { assignCustomRule } from "~/modules/customRules";+import { path } from "~/utils/path";+import { customRuleAssignmentsQuery, getCompanyId } from "~/utils/react-query";++export async function action({ request, params }: ActionFunctionArgs) {+ assertIsPost(request);+ const { client, companyId, userId } = await requirePermissions(request, {+ create: "inventory"+ });++ await requirePlan({+ request,+ client,+ companyId,+ feature: "CUSTOM_RULES",+ redirectTo: path.to.customRules+ });++ const { storageUnitId } = params;+ if (!storageUnitId) throw new Error("storageUnitId required");++ const formData = await request.formData();+ const ruleId = String(formData.get("ruleId") ?? "");+ if (!ruleId) {+ throw redirect(+ request.headers.get("Referer") ?? path.to.customRules,+ await flash(request, error(null, "Rule id required"))+ );+ }++ const result = await assignCustomRule(client, {+ targetType: "storageUnit",+ targetId: storageUnitId,+ ruleId,+ companyId,+ userId+ });++ if (result.error) {+ throw redirect(+ request.headers.get("Referer") ?? path.to.customRules,+ await flash(request, error(result.error, "Failed to assign rule"))+ );+ }++ throw redirect(+ request.headers.get("Referer") ?? path.to.customRules,+ await flash(request, success("Rule assigned"))+ );+}++export async function clientAction({+ serverAction,+ params+}: ClientActionFunctionArgs) {+ const { storageUnitId } = params;+ if (storageUnitId) {+ window?.clientCache?.setQueryData(+ customRuleAssignmentsQuery("storageUnit", storageUnitId, getCompanyId())+ .queryKey,+ null+ );+ }+ return await serverAction();+}diff --git a/apps/erp/app/routes/x+/inventory+/storage-units.rules.unassign.$storageUnitId.$ruleId.tsx b/apps/erp/app/routes/x+/inventory+/storage-units.rules.unassign.$storageUnitId.$ruleId.tsxnew file mode 100644index 0000000000..6f726aae10--- /dev/null+++ b/apps/erp/app/routes/x+/inventory+/storage-units.rules.unassign.$storageUnitId.$ruleId.tsx@@ -0,0 +1,63 @@+import { assertIsPost, error, success } from "@carbon/auth";+import { requirePermissions } from "@carbon/auth/auth.server";+import { flash } from "@carbon/auth/session.server";+import { requirePlan } from "@carbon/ee/plan.server";+import type {+ ActionFunctionArgs,+ ClientActionFunctionArgs+} from "react-router";+import { redirect } from "react-router";+import { unassignCustomRule } from "~/modules/customRules";+import { path } from "~/utils/path";+import { customRuleAssignmentsQuery, getCompanyId } from "~/utils/react-query";++export async function action({ request, params }: ActionFunctionArgs) {+ assertIsPost(request);+ const { client, companyId } = await requirePermissions(request, {+ delete: "inventory"+ });++ await requirePlan({+ request,+ client,+ companyId,+ feature: "CUSTOM_RULES",+ redirectTo: path.to.customRules+ });++ const { storageUnitId, ruleId } = params;+ if (!storageUnitId || !ruleId)+ throw new Error("storageUnitId and ruleId required");++ const result = await unassignCustomRule(client, {+ targetType: "storageUnit",+ targetId: storageUnitId,+ ruleId+ });+ if (result.error) {+ throw redirect(+ request.headers.get("Referer") ?? path.to.customRules,+ await flash(request, error(result.error, "Failed to unassign rule"))+ );+ }++ throw redirect(+ request.headers.get("Referer") ?? path.to.customRules,+ await flash(request, success("Rule unassigned"))+ );+}++export async function clientAction({+ serverAction,+ params+}: ClientActionFunctionArgs) {+ const { storageUnitId } = params;+ if (storageUnitId) {+ window?.clientCache?.setQueryData(+ customRuleAssignmentsQuery("storageUnit", storageUnitId, getCompanyId())+ .queryKey,+ null+ );+ }+ return await serverAction();+}diff --git a/apps/erp/app/routes/x+/items+/rules.$id.tsx b/apps/erp/app/routes/x+/items+/rules.$id.tsxdeleted file mode 100644index 3a96d3e5df..0000000000--- a/apps/erp/app/routes/x+/items+/rules.$id.tsx+++ /dev/null@@ -1,122 +0,0 @@-import { assertIsPost, error, notFound, success } from "@carbon/auth";-import { requirePermissions } from "@carbon/auth/auth.server";-import { flash } from "@carbon/auth/session.server";-import { requirePlan } from "@carbon/ee/plan.server";-import { validationError, validator } from "@carbon/form";-import type { ConditionAst } from "@carbon/utils";-import type {- ActionFunctionArgs,- ClientActionFunctionArgs,- LoaderFunctionArgs-} from "react-router";-import { data, redirect, useLoaderData, useNavigate } from "react-router";-import {- getItemRule,- itemRuleValidator,- upsertItemRule-} from "~/modules/items";-import ItemRuleForm from "~/modules/items/ui/ItemRules/ItemRuleForm";-import { getCustomFields, setCustomFields } from "~/utils/form";-import { getParams, path } from "~/utils/path";-import { getCompanyId, itemRulesQuery } from "~/utils/react-query";--export async function loader({ request, params }: LoaderFunctionArgs) {- const { client } = await requirePermissions(request, {- view: "parts",- role: "employee"- });-- const { id } = params;- if (!id) throw notFound("id not found");-- const rule = await getItemRule(client, id);-- return { rule: rule.data ?? null };-}--export async function action({ request, params }: ActionFunctionArgs) {- assertIsPost(request);- const { client, companyId, userId } = await requirePermissions(request, {- update: "parts"- });-- await requirePlan({- request,- client,- companyId,- feature: "ITEM_RULES",- redirectTo: path.to.itemRules- });-- const { id } = params;- if (!id) throw new Error("Could not find id");-- const formData = await request.formData();- const validation = await validator(itemRuleValidator).validate(formData);- if (validation.error) {- return validationError(validation.error);- }-- const update = await upsertItemRule(client, {- id,- ...validation.data,- description: validation.data.description ?? null,- updatedBy: userId,- customFields: setCustomFields(formData)- });-- if (update.error) {- return data(- {},- await flash(request, error(update.error, "Failed to update item rule"))- );- }-- throw redirect(- `${path.to.itemRules}?${getParams(request)}`,- await flash(request, success("Updated item rule"))- );-}--export async function clientAction({ serverAction }: ClientActionFunctionArgs) {- window?.clientCache?.setQueryData(- itemRulesQuery(getCompanyId()).queryKey,- null- );- return await serverAction();-}--export default function EditItemRuleRoute() {- const { rule } = useLoaderData<typeof loader>();- const navigate = useNavigate();-- const initialValues = {- id: rule?.id ?? undefined,- name: rule?.name ?? "",- description: rule?.description ?? "",- message: rule?.message ?? "",- severity: (rule?.severity as "error" | "warn") ?? "error",- active: rule?.active ?? true,- conditionAst: (rule?.conditionAst as ConditionAst | undefined) ?? {- kind: "all" as const,- conditions: []- },- ...getCustomFields(rule?.customFields)- };-- return (- <ItemRuleForm- key={initialValues.id}- // ConditionAst.value is `unknown` to keep the AST permissive at the- // type level, but the validator narrows it to scalars/arrays. Cast- // through `unknown` since the runtime values are produced by the same- // validator on save.- initialValues={- initialValues as unknown as React.ComponentProps<- typeof ItemRuleForm- >["initialValues"]- }- onClose={() => navigate(-1)}- />- );-}diff --git a/apps/erp/app/routes/x+/items+/rules.assign.$itemId.tsx b/apps/erp/app/routes/x+/items+/rules.assign.$itemId.tsxindex 8af08c0140..73521d1bed 100644--- a/apps/erp/app/routes/x+/items+/rules.assign.$itemId.tsx+++ b/apps/erp/app/routes/x+/items+/rules.assign.$itemId.tsx@@ -7,9 +7,9 @@ import type {ClientActionFunctionArgs} from "react-router";import { redirect } from "react-router";-import { assignItemRule } from "~/modules/items";+import { assignCustomRule } from "~/modules/customRules";import { path } from "~/utils/path";-import { getCompanyId, itemRuleAssignmentsQuery } from "~/utils/react-query";+import { customRuleAssignmentsQuery, getCompanyId } from "~/utils/react-query";export async function action({ request, params }: ActionFunctionArgs) {assertIsPost(request);@@ -21,8 +21,8 @@ export async function action({ request, params }: ActionFunctionArgs) {request,client,companyId,- feature: "ITEM_RULES",- redirectTo: path.to.itemRules+ feature: "CUSTOM_RULES",+ redirectTo: path.to.customRules});const { itemId } = params;@@ -32,13 +32,14 @@ export async function action({ request, params }: ActionFunctionArgs) {const ruleId = String(formData.get("ruleId") ?? "");if (!ruleId) {throw redirect(- request.headers.get("Referer") ?? path.to.itemRules,+ request.headers.get("Referer") ?? path.to.customRules,await flash(request, error(null, "Rule id required")));}- const result = await assignItemRule(client, {- itemId,+ const result = await assignCustomRule(client, {+ targetType: "item",+ targetId: itemId,ruleId,companyId,userId@@ -46,13 +47,13 @@ export async function action({ request, params }: ActionFunctionArgs) {if (result.error) {throw redirect(- request.headers.get("Referer") ?? path.to.itemRules,+ request.headers.get("Referer") ?? path.to.customRules,await flash(request, error(result.error, "Failed to assign rule")));}throw redirect(- request.headers.get("Referer") ?? path.to.itemRules,+ request.headers.get("Referer") ?? path.to.customRules,await flash(request, success("Rule assigned")));}@@ -64,7 +65,7 @@ export async function clientAction({const { itemId } = params;if (itemId) {window?.clientCache?.setQueryData(- itemRuleAssignmentsQuery(itemId, getCompanyId()).queryKey,+ customRuleAssignmentsQuery("item", itemId, getCompanyId()).queryKey,null);}diff --git a/apps/erp/app/routes/x+/items+/rules.delete.$id.tsx b/apps/erp/app/routes/x+/items+/rules.delete.$id.tsxdeleted file mode 100644index 2d509a627f..0000000000--- a/apps/erp/app/routes/x+/items+/rules.delete.$id.tsx+++ /dev/null@@ -1,93 +0,0 @@-import { error, notFound, success } from "@carbon/auth";-import { requirePermissions } from "@carbon/auth/auth.server";-import { flash } from "@carbon/auth/session.server";-import { requirePlan } from "@carbon/ee/plan.server";-import type {- ActionFunctionArgs,- ClientActionFunctionArgs,- LoaderFunctionArgs-} from "react-router";-import { redirect, useLoaderData, useNavigate, useParams } from "react-router";-import { ConfirmDelete } from "~/components/Modals";-import { deleteItemRule, getItemRule } from "~/modules/items";-import { path } from "~/utils/path";-import { getCompanyId } from "~/utils/react-query";--export async function loader({ request, params }: LoaderFunctionArgs) {- await requirePermissions(request, { view: "parts" });- const { id } = params;- if (!id) throw notFound("id not found");-- const { client } = await requirePermissions(request, { view: "parts" });- const rule = await getItemRule(client, id);- if (rule.error) {- throw redirect(- path.to.itemRules,- await flash(request, error(rule.error, "Failed to load rule"))- );- }- return { rule: rule.data };-}--export async function action({ request, params }: ActionFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- delete: "parts"- });-- await requirePlan({- request,- client,- companyId,- feature: "ITEM_RULES",- redirectTo: path.to.itemRules- });-- const { id } = params;- if (!id) {- throw redirect(- path.to.itemRules,- await flash(request, error(params, "Failed to find rule id"))- );- }-- const result = await deleteItemRule(client, id);- if (result.error) {- throw redirect(- path.to.itemRules,- await flash(request, error(result.error, "Failed to delete rule"))- );- }-- throw redirect(- path.to.itemRules,- await flash(request, success("Rule deleted"))- );-}--export async function clientAction({ serverAction }: ClientActionFunctionArgs) {- const companyId = getCompanyId();- window.clientCache?.invalidateQueries({- predicate: (query) => {- const key = query.queryKey as string[];- return key[0] === "itemRules" && key[1] === companyId;- }- });- return await serverAction();-}--export default function DeleteItemRuleRoute() {- const { id } = useParams();- if (!id) throw new Error("id not found");- const { rule } = useLoaderData<typeof loader>();- const navigate = useNavigate();- if (!rule) return null;-- return (- <ConfirmDelete- action={path.to.deleteItemRule(id)}- name={rule.name}- text={`Delete rule "${rule.name}"? Any items currently bound to it will become unassigned. This cannot be undone.`}- onCancel={() => navigate(-1)}- />- );-}diff --git a/apps/erp/app/routes/x+/items+/rules.new.tsx b/apps/erp/app/routes/x+/items+/rules.new.tsxdeleted file mode 100644index 511e2cee5b..0000000000--- a/apps/erp/app/routes/x+/items+/rules.new.tsx+++ /dev/null@@ -1,89 +0,0 @@-import { assertIsPost, error, success } from "@carbon/auth";-import { requirePermissions } from "@carbon/auth/auth.server";-import { flash } from "@carbon/auth/session.server";-import { requirePlan } from "@carbon/ee/plan.server";-import { validationError, validator } from "@carbon/form";-import type {- ActionFunctionArgs,- ClientActionFunctionArgs,- LoaderFunctionArgs-} from "react-router";-import { data, redirect, useNavigate } from "react-router";-import { itemRuleValidator, upsertItemRule } from "~/modules/items";-import ItemRuleForm from "~/modules/items/ui/ItemRules/ItemRuleForm";-import { setCustomFields } from "~/utils/form";-import { getParams, path } from "~/utils/path";-import { getCompanyId, itemRulesQuery } from "~/utils/react-query";--export async function loader({ request }: LoaderFunctionArgs) {- await requirePermissions(request, { create: "parts" });- return null;-}--export async function action({ request }: ActionFunctionArgs) {- assertIsPost(request);- const { client, companyId, userId } = await requirePermissions(request, {- create: "parts"- });-- await requirePlan({- request,- client,- companyId,- feature: "ITEM_RULES",- redirectTo: path.to.itemRules- });-- const formData = await request.formData();- const validation = await validator(itemRuleValidator).validate(formData);- if (validation.error) {- return validationError(validation.error);- }-- // biome-ignore lint/correctness/noUnusedVariables: id excluded on insert- const { id, ...rest } = validation.data;-- const insert = await upsertItemRule(client, {- ...rest,- description: rest.description ?? null,- companyId,- createdBy: userId,- customFields: setCustomFields(formData)- });-- if (insert.error) {- return data(- {},- await flash(request, error(insert.error, "Failed to create item rule"))- );- }-- return redirect(- `${path.to.itemRules}?${getParams(request)}`,- await flash(request, success("Item rule created"))- );-}--export async function clientAction({ serverAction }: ClientActionFunctionArgs) {- window?.clientCache?.setQueryData(- itemRulesQuery(getCompanyId()).queryKey,- null- );- return await serverAction();-}--export default function NewItemRuleRoute() {- const navigate = useNavigate();- return (- <ItemRuleForm- onClose={() => navigate(-1)}- initialValues={{- name: "",- description: "",- message: "",- severity: "error",- active: true- }}- />- );-}diff --git a/apps/erp/app/routes/x+/items+/rules.tsx b/apps/erp/app/routes/x+/items+/rules.tsxdeleted file mode 100644index b39dcf6f6d..0000000000--- a/apps/erp/app/routes/x+/items+/rules.tsx+++ /dev/null@@ -1,76 +0,0 @@-import { error } from "@carbon/auth";-import { requirePermissions } from "@carbon/auth/auth.server";-import { flash } from "@carbon/auth/session.server";-import { VStack } from "@carbon/react";-import { msg } from "@lingui/core/macro";-import type { LoaderFunctionArgs } from "react-router";-import { Outlet, redirect, useLoaderData } from "react-router";-import { usePlanGate } from "~/hooks/usePlanGate";-import { getItemRules, getRuleAssignmentCounts } from "~/modules/items";-import ItemRulesTable from "~/modules/items/ui/ItemRules/ItemRulesTable";-import ItemRulesUpgradeOverlay from "~/modules/items/ui/ItemRules/ItemRulesUpgradeOverlay";-import type { Handle } from "~/utils/handle";-import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";--export const handle: Handle = {- breadcrumb: msg`Item Rules`,- to: path.to.itemRules-};--export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- view: "parts",- role: "employee"- });-- const url = new URL(request.url);- const searchParams = new URLSearchParams(url.search);- const search = searchParams.get("search");- const { limit, offset, sorts, filters } =- getGenericQueryFilters(searchParams);-- const rules = await getItemRules(client, companyId, {- limit,- offset,- sorts,- search,- filters- });-- if (rules.error) {- console.error(rules.error);- throw redirect(- path.to.parts,- await flash(request, error(null, "Failed to load item rules"))- );- }-- const ids = (rules.data ?? []).map((r) => r.id);- const counts = await getRuleAssignmentCounts(client, ids);- const countMap = (counts.data ?? {}) as Record<string, number>;-- return {- rules: (rules.data ?? []).map((r) => ({- ...r,- assignmentCount: countMap[r.id] ?? 0- })),- count: rules.count ?? 0- };-}--export default function ItemRulesRoute() {- const { rules, count } = useLoaderData<typeof loader>();- const { isGated } = usePlanGate({ feature: "ITEM_RULES" });-- if (isGated) {- return <ItemRulesUpgradeOverlay />;- }-- return (- <VStack spacing={0} className="h-full">- <ItemRulesTable data={rules as never} count={count ?? 0} />- <Outlet />- </VStack>- );-}diff --git a/apps/erp/app/routes/x+/items+/rules.unassign.$itemId.$ruleId.tsx b/apps/erp/app/routes/x+/items+/rules.unassign.$itemId.$ruleId.tsxindex 94e8a1198b..43d9c01491 100644--- a/apps/erp/app/routes/x+/items+/rules.unassign.$itemId.$ruleId.tsx+++ b/apps/erp/app/routes/x+/items+/rules.unassign.$itemId.$ruleId.tsx@@ -7,9 +7,9 @@ import type {ClientActionFunctionArgs} from "react-router";import { redirect } from "react-router";-import { unassignItemRule } from "~/modules/items";+import { unassignCustomRule } from "~/modules/customRules";import { path } from "~/utils/path";-import { getCompanyId, itemRuleAssignmentsQuery } from "~/utils/react-query";+import { customRuleAssignmentsQuery, getCompanyId } from "~/utils/react-query";export async function action({ request, params }: ActionFunctionArgs) {assertIsPost(request);@@ -21,23 +21,27 @@ export async function action({ request, params }: ActionFunctionArgs) {request,client,companyId,- feature: "ITEM_RULES",- redirectTo: path.to.itemRules+ feature: "CUSTOM_RULES",+ redirectTo: path.to.customRules});const { itemId, ruleId } = params;if (!itemId || !ruleId) throw new Error("itemId and ruleId required");- const result = await unassignItemRule(client, { itemId, ruleId });+ const result = await unassignCustomRule(client, {+ targetType: "item",+ targetId: itemId,+ ruleId+ });if (result.error) {throw redirect(- request.headers.get("Referer") ?? path.to.itemRules,+ request.headers.get("Referer") ?? path.to.customRules,await flash(request, error(result.error, "Failed to unassign rule")));}throw redirect(- request.headers.get("Referer") ?? path.to.itemRules,+ request.headers.get("Referer") ?? path.to.customRules,await flash(request, success("Rule unassigned")));}@@ -49,7 +53,7 @@ export async function clientAction({const { itemId } = params;if (itemId) {window?.clientCache?.setQueryData(- itemRuleAssignmentsQuery(itemId, getCompanyId()).queryKey,+ customRuleAssignmentsQuery("item", itemId, getCompanyId()).queryKey,null);}diff --git a/apps/erp/app/routes/x+/material+/$itemId.inventory.tsx b/apps/erp/app/routes/x+/material+/$itemId.inventory.tsxindex 4e5a0614be..9b10300626 100644--- a/apps/erp/app/routes/x+/material+/$itemId.inventory.tsx+++ b/apps/erp/app/routes/x+/material+/$itemId.inventory.tsx@@ -1,6 +1,7 @@import { assertIsPost, error, success } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";+import { getCustomRulesDataForTarget } from "@carbon/ee/custom-rules.server";import { validationError, validator } from "@carbon/form";import { VStack } from "@carbon/react";import { pluckUnique } from "@carbon/utils";@@ -8,6 +9,7 @@ import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";import { redirect, useLoaderData } from "react-router";import { useStorageUnits } from "~/components/Form/StorageUnit";import { useRouteData } from "~/hooks";+import RuleAssignmentsList from "~/modules/customRules/ui/RuleAssignmentsList";import {getTrackedEntityExpirations,InventoryDetails@@ -24,9 +26,7 @@ import {upsertPickMethod,upsertPickMethodWithShelfLife} from "~/modules/items";-import { getItemRulesDataForItem } from "~/modules/items/itemRules.server";import { PickMethodForm } from "~/modules/items/ui/Item";-import ItemRuleAssignments from "~/modules/items/ui/ItemRules/ItemRuleAssignments";import { getLocationsList } from "~/modules/resources";import { getUserDefaults } from "~/modules/users/users.server";import { getDatabaseClient } from "~/services/database.server";@@ -162,7 +162,11 @@ export async function loader({ request, params }: LoaderFunctionArgs) {getItemShelfLife(client, itemId),getBomHasShelfLifeManagedInput(client, itemId, companyId),getTrackedEntityExpirations(client, trackedEntityIds),- getItemRulesDataForItem(client, itemId, companyId)+ getCustomRulesDataForTarget(client, {+ targetType: "item",+ targetId: itemId,+ companyId+ })]);return {@@ -301,8 +305,9 @@ export default function MaterialInventoryRoute() {quantities={quantities}storageUnits={storageUnits.options}/>- <ItemRuleAssignments- itemId={itemId}+ <RuleAssignmentsList+ targetType="item"+ targetId={itemId}assignments={ruleAssignments as never}library={ruleLibrary as never}/>diff --git a/apps/erp/app/routes/x+/part+/$itemId.inventory.tsx b/apps/erp/app/routes/x+/part+/$itemId.inventory.tsxindex 31fc8623ab..f45fc57a23 100644--- a/apps/erp/app/routes/x+/part+/$itemId.inventory.tsx+++ b/apps/erp/app/routes/x+/part+/$itemId.inventory.tsx@@ -1,6 +1,7 @@import { assertIsPost, error, success } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";+import { getCustomRulesDataForTarget } from "@carbon/ee/custom-rules.server";import { validationError, validator } from "@carbon/form";import { VStack } from "@carbon/react";import { pluckUnique } from "@carbon/utils";@@ -8,6 +9,7 @@ import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";import { redirect, useLoaderData } from "react-router";import { useStorageUnits } from "~/components/Form/StorageUnit";import { useRouteData } from "~/hooks";+import RuleAssignmentsList from "~/modules/customRules/ui/RuleAssignmentsList";import {getTrackedEntityExpirations,InventoryDetails@@ -24,9 +26,7 @@ import {upsertPickMethod,upsertPickMethodWithShelfLife} from "~/modules/items";-import { getItemRulesDataForItem } from "~/modules/items/itemRules.server";import { PickMethodForm } from "~/modules/items/ui/Item";-import ItemRuleAssignments from "~/modules/items/ui/ItemRules/ItemRuleAssignments";import { getLocationsList } from "~/modules/resources";import { getUserDefaults } from "~/modules/users/users.server";import { getDatabaseClient } from "~/services/database.server";@@ -122,7 +122,11 @@ export async function loader({ request, params }: LoaderFunctionArgs) {getItemStorageUnitQuantities(client, itemId, companyId, locationId),getItemShelfLife(client, itemId),getBomHasShelfLifeManagedInput(client, itemId, companyId),- getItemRulesDataForItem(client, itemId, companyId)+ getCustomRulesDataForTarget(client, {+ targetType: "item",+ targetId: itemId,+ companyId+ })]);if (quantities.error) {throw redirect(@@ -285,8 +289,9 @@ export default function PartInventoryRoute() {quantities={quantities}storageUnits={storageUnits.options}/>- <ItemRuleAssignments- itemId={itemId}+ <RuleAssignmentsList+ targetType="item"+ targetId={itemId}assignments={ruleAssignments as never}library={ruleLibrary as never}/>diff --git a/apps/erp/app/routes/x+/receipt+/$receiptId.post.tsx b/apps/erp/app/routes/x+/receipt+/$receiptId.post.tsxindex bec3dbdeeb..d66c730561 100644--- a/apps/erp/app/routes/x+/receipt+/$receiptId.post.tsx+++ b/apps/erp/app/routes/x+/receipt+/$receiptId.post.tsx@@ -2,13 +2,13 @@ import { error } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { getCarbonServiceRole } from "@carbon/auth/client.server";import { flash } from "@carbon/auth/session.server";-import type { ActionFunctionArgs } from "react-router";-import { redirect } from "react-router";import {dedupeViolations,evaluateLinesForSurface,isBlocked-} from "~/modules/items/itemRules.server";+} from "@carbon/ee/custom-rules.server";+import type { ActionFunctionArgs } from "react-router";+import { redirect } from "react-router";import { path } from "~/utils/path";export async function action({ request, params }: ActionFunctionArgs) {@@ -63,6 +63,26 @@ export async function action({ request, params }: ActionFunctionArgs) {client: serviceRole,companyId,userId,+ targetType: "item",+ surface,+ lines: evalLines+ });+ allViolations.push(...violations);+ Object.assign(allRuleNames, ruleNames);+ }++ // Storage-unit pass — place side of the receipt. Same lines, different+ // target. Transfers double-up via the warehouseTransfer surface.+ const storageUnitSurfaces: ("place" | "warehouseTransfer")[] = ["place"];+ if (receiptForSurface?.sourceDocument === "Inbound Transfer") {+ storageUnitSurfaces.push("warehouseTransfer");+ }+ for (const surface of storageUnitSurfaces) {+ const { violations, ruleNames } = await evaluateLinesForSurface({+ client: serviceRole,+ companyId,+ userId,+ targetType: "storageUnit",surface,lines: evalLines});diff --git a/apps/erp/app/routes/x+/resources+/work-centers.$workCenterId.rules.tsx b/apps/erp/app/routes/x+/resources+/work-centers.$workCenterId.rules.tsxnew file mode 100644index 0000000000..9f888cf36b--- /dev/null+++ b/apps/erp/app/routes/x+/resources+/work-centers.$workCenterId.rules.tsx@@ -0,0 +1,36 @@+import { notFound } from "@carbon/auth";+import { requirePermissions } from "@carbon/auth/auth.server";+import { getCustomRulesDataForTarget } from "@carbon/ee/custom-rules.server";+import type { LoaderFunctionArgs } from "react-router";+import { useLoaderData } from "react-router";+import RuleAssignmentsList from "~/modules/customRules/ui/RuleAssignmentsList";++export async function loader({ request, params }: LoaderFunctionArgs) {+ const { client, companyId } = await requirePermissions(request, {+ view: "resources",+ role: "employee"+ });+ const { workCenterId } = params;+ if (!workCenterId) throw notFound("workCenterId required");++ const data = await getCustomRulesDataForTarget(client, {+ targetType: "workCenter",+ targetId: workCenterId,+ companyId+ });++ return { workCenterId, ...data };+}++export default function WorkCenterRulesRoute() {+ const { workCenterId, assignments, library } = useLoaderData<typeof loader>();+ return (+ <RuleAssignmentsList+ targetType="workCenter"+ targetId={workCenterId}+ assignments={assignments as never}+ library={library as never}+ variant="flat"+ />+ );+}diff --git a/apps/erp/app/routes/x+/resources+/work-centers.rules.assign.$workCenterId.tsx b/apps/erp/app/routes/x+/resources+/work-centers.rules.assign.$workCenterId.tsxnew file mode 100644index 0000000000..9f3c6a687e--- /dev/null+++ b/apps/erp/app/routes/x+/resources+/work-centers.rules.assign.$workCenterId.tsx@@ -0,0 +1,74 @@+import { assertIsPost, error, success } from "@carbon/auth";+import { requirePermissions } from "@carbon/auth/auth.server";+import { flash } from "@carbon/auth/session.server";+import { requirePlan } from "@carbon/ee/plan.server";+import type {+ ActionFunctionArgs,+ ClientActionFunctionArgs+} from "react-router";+import { redirect } from "react-router";+import { assignCustomRule } from "~/modules/customRules";+import { path } from "~/utils/path";+import { customRuleAssignmentsQuery, getCompanyId } from "~/utils/react-query";++export async function action({ request, params }: ActionFunctionArgs) {+ assertIsPost(request);+ const { client, companyId, userId } = await requirePermissions(request, {+ create: "resources"+ });++ await requirePlan({+ request,+ client,+ companyId,+ feature: "CUSTOM_RULES",+ redirectTo: path.to.customRules+ });++ const { workCenterId } = params;+ if (!workCenterId) throw new Error("workCenterId required");++ const formData = await request.formData();+ const ruleId = String(formData.get("ruleId") ?? "");+ if (!ruleId) {+ throw redirect(+ request.headers.get("Referer") ?? path.to.customRules,+ await flash(request, error(null, "Rule id required"))+ );+ }++ const result = await assignCustomRule(client, {+ targetType: "workCenter",+ targetId: workCenterId,+ ruleId,+ companyId,+ userId+ });++ if (result.error) {+ throw redirect(+ request.headers.get("Referer") ?? path.to.customRules,+ await flash(request, error(result.error, "Failed to assign rule"))+ );+ }++ throw redirect(+ request.headers.get("Referer") ?? path.to.customRules,+ await flash(request, success("Rule assigned"))+ );+}++export async function clientAction({+ serverAction,+ params+}: ClientActionFunctionArgs) {+ const { workCenterId } = params;+ if (workCenterId) {+ window?.clientCache?.setQueryData(+ customRuleAssignmentsQuery("workCenter", workCenterId, getCompanyId())+ .queryKey,+ null+ );+ }+ return await serverAction();+}diff --git a/apps/erp/app/routes/x+/resources+/work-centers.rules.unassign.$workCenterId.$ruleId.tsx b/apps/erp/app/routes/x+/resources+/work-centers.rules.unassign.$workCenterId.$ruleId.tsxnew file mode 100644index 0000000000..f3ca091162--- /dev/null+++ b/apps/erp/app/routes/x+/resources+/work-centers.rules.unassign.$workCenterId.$ruleId.tsx@@ -0,0 +1,63 @@+import { assertIsPost, error, success } from "@carbon/auth";+import { requirePermissions } from "@carbon/auth/auth.server";+import { flash } from "@carbon/auth/session.server";+import { requirePlan } from "@carbon/ee/plan.server";+import type {+ ActionFunctionArgs,+ ClientActionFunctionArgs+} from "react-router";+import { redirect } from "react-router";+import { unassignCustomRule } from "~/modules/customRules";+import { path } from "~/utils/path";+import { customRuleAssignmentsQuery, getCompanyId } from "~/utils/react-query";++export async function action({ request, params }: ActionFunctionArgs) {+ assertIsPost(request);+ const { client, companyId } = await requirePermissions(request, {+ delete: "resources"+ });++ await requirePlan({+ request,+ client,+ companyId,+ feature: "CUSTOM_RULES",+ redirectTo: path.to.customRules+ });++ const { workCenterId, ruleId } = params;+ if (!workCenterId || !ruleId)+ throw new Error("workCenterId and ruleId required");++ const result = await unassignCustomRule(client, {+ targetType: "workCenter",+ targetId: workCenterId,+ ruleId+ });+ if (result.error) {+ throw redirect(+ request.headers.get("Referer") ?? path.to.customRules,+ await flash(request, error(result.error, "Failed to unassign rule"))+ );+ }++ throw redirect(+ request.headers.get("Referer") ?? path.to.customRules,+ await flash(request, success("Rule unassigned"))+ );+}++export async function clientAction({+ serverAction,+ params+}: ClientActionFunctionArgs) {+ const { workCenterId } = params;+ if (workCenterId) {+ window?.clientCache?.setQueryData(+ customRuleAssignmentsQuery("workCenter", workCenterId, getCompanyId())+ .queryKey,+ null+ );+ }+ return await serverAction();+}diff --git a/apps/erp/app/routes/x+/settings+/custom-rules.$id.delete.tsx b/apps/erp/app/routes/x+/settings+/custom-rules.$id.delete.tsxnew file mode 100644index 0000000000..36dbc72589--- /dev/null+++ b/apps/erp/app/routes/x+/settings+/custom-rules.$id.delete.tsx@@ -0,0 +1,81 @@+import { assertIsPost, error, notFound, success } from "@carbon/auth";+import { requirePermissions } from "@carbon/auth/auth.server";+import { flash } from "@carbon/auth/session.server";+import { requirePlan } from "@carbon/ee/plan.server";+import type {+ ActionFunctionArgs,+ ClientActionFunctionArgs,+ LoaderFunctionArgs+} from "react-router";+import { redirect, useLoaderData, useNavigate } from "react-router";+import { ConfirmDelete } from "~/components/Modals";+import { deleteCustomRule, getCustomRule } from "~/modules/customRules";+import { getParams, path } from "~/utils/path";+import { customRulesQuery, getCompanyId } from "~/utils/react-query";++export async function loader({ request, params }: LoaderFunctionArgs) {+ const { client } = await requirePermissions(request, { delete: "settings" });+ const { id } = params;+ if (!id) throw notFound("id required");+ const rule = await getCustomRule(client, id);+ if (rule.error || !rule.data) {+ throw redirect(+ path.to.customRules,+ await flash(request, error(rule.error, "Rule not found"))+ );+ }+ return { rule: rule.data };+}++export async function action({ request, params }: ActionFunctionArgs) {+ assertIsPost(request);+ const { client, companyId } = await requirePermissions(request, {+ delete: "settings"+ });++ await requirePlan({+ request,+ client,+ companyId,+ feature: "CUSTOM_RULES",+ redirectTo: path.to.customRules+ });++ const { id } = params;+ if (!id) throw new Error("id required");++ const result = await deleteCustomRule(client, id);+ if (result.error) {+ throw redirect(+ `${path.to.customRules}?${getParams(request)}`,+ await flash(request, error(result.error, "Failed to delete rule"))+ );+ }++ throw redirect(+ `${path.to.customRules}?${getParams(request)}`,+ await flash(request, success("Rule deleted"))+ );+}++export async function clientAction({ serverAction }: ClientActionFunctionArgs) {+ window?.clientCache?.setQueryData(+ customRulesQuery(getCompanyId()).queryKey,+ null+ );+ return await serverAction();+}++export default function DeleteCustomRuleRoute() {+ const { rule } = useLoaderData<typeof loader>();+ const { id } = (rule as { id: string }) ?? { id: "" };+ const navigate = useNavigate();+ return (+ <ConfirmDelete+ action={path.to.deleteCustomRule(id)}+ name={(rule as { name?: string })?.name ?? "this rule"}+ text="Are you sure you want to delete this rule? Assignments will also be removed."+ onCancel={() => navigate(path.to.customRules)}+ />+ );+}diff --git a/apps/erp/app/routes/x+/settings+/custom-rules.$id.tsx b/apps/erp/app/routes/x+/settings+/custom-rules.$id.tsxnew file mode 100644index 0000000000..fb094b10a1--- /dev/null+++ b/apps/erp/app/routes/x+/settings+/custom-rules.$id.tsx@@ -0,0 +1,92 @@+import { assertIsPost, error, notFound } from "@carbon/auth";+import { requirePermissions } from "@carbon/auth/auth.server";+import { flash } from "@carbon/auth/session.server";+import { requirePlan } from "@carbon/ee/plan.server";+import { validator } from "@carbon/form";+import type { ConditionAst } from "@carbon/utils";+import type {+ ActionFunctionArgs,+ ClientActionFunctionArgs,+ LoaderFunctionArgs+} from "react-router";+import { redirect, useLoaderData, useNavigate } from "react-router";+import {+ customRuleValidator,+ getCustomRule,+ upsertCustomRule+} from "~/modules/customRules";+import CustomRuleForm from "~/modules/customRules/ui/CustomRuleForm";+import { getParams, path } from "~/utils/path";+import { customRulesQuery, getCompanyId } from "~/utils/react-query";++export async function loader({ request, params }: LoaderFunctionArgs) {+ const { client } = await requirePermissions(request, { view: "settings" });+ const { id } = params;+ if (!id) throw notFound("id required");+ const rule = await getCustomRule(client, id);+ if (rule.error || !rule.data) throw notFound("Rule not found");+ return { rule: rule.data };+}++export async function action({ request, params }: ActionFunctionArgs) {+ assertIsPost(request);+ const { client, companyId, userId } = await requirePermissions(request, {+ update: "settings"+ });++ await requirePlan({+ request,+ client,+ companyId,+ feature: "CUSTOM_RULES",+ redirectTo: path.to.customRules+ });++ const { id } = params;+ if (!id) throw new Error("id required");++ const formData = await request.formData();+ const validation = await validator(customRuleValidator).validate(formData);+ if (validation.error) return validation.error;++ const update = await upsertCustomRule(client, {+ ...validation.data,+ id,+ description: validation.data.description ?? null,+ updatedBy: userId+ });++ if (update.error) {+ return await flash(+ request,+ error(update.error, "Failed to update rule")+ ).then(() => null);+ }++ throw redirect(`${path.to.customRules}?${getParams(request)}`);+}++export async function clientAction({ serverAction }: ClientActionFunctionArgs) {+ window?.clientCache?.setQueryData(+ customRulesQuery(getCompanyId()).queryKey,+ null+ );+ return await serverAction();+}++export default function EditCustomRuleRoute() {+ const { rule } = useLoaderData<typeof loader>();+ const navigate = useNavigate();+ return (+ <CustomRuleForm+ initialValues={+ {+ ...((rule ?? {}) as Record<string, unknown>),+ conditionAst: (rule as { conditionAst: unknown })+ .conditionAst as unknown as ConditionAst+ } as never+ }+ onClose={() => navigate(path.to.customRules)}+ />+ );+}diff --git a/apps/erp/app/routes/x+/settings+/custom-rules.new.tsx b/apps/erp/app/routes/x+/settings+/custom-rules.new.tsxnew file mode 100644index 0000000000..7ad0e5da7e--- /dev/null+++ b/apps/erp/app/routes/x+/settings+/custom-rules.new.tsx@@ -0,0 +1,83 @@+import { assertIsPost, error } from "@carbon/auth";+import { requirePermissions } from "@carbon/auth/auth.server";+import { flash } from "@carbon/auth/session.server";+import { requirePlan } from "@carbon/ee/plan.server";+import { validator } from "@carbon/form";+import type { TargetType } from "@carbon/utils";+import type {+ ActionFunctionArgs,+ ClientActionFunctionArgs,+ LoaderFunctionArgs+} from "react-router";+import { redirect, useLoaderData, useNavigate } from "react-router";+import { customRuleValidator, upsertCustomRule } from "~/modules/customRules";+import CustomRuleForm from "~/modules/customRules/ui/CustomRuleForm";+import { getParams, path } from "~/utils/path";+import { customRulesQuery, getCompanyId } from "~/utils/react-query";++const isTargetType = (value: string | null): value is TargetType =>+ value === "item" || value === "storageUnit" || value === "workCenter";++export async function loader({ request }: LoaderFunctionArgs) {+ await requirePermissions(request, { create: "settings" });+ const url = new URL(request.url);+ const raw = url.searchParams.get("targetType");+ return { targetType: isTargetType(raw) ? raw : ("item" as TargetType) };+}++export async function action({ request }: ActionFunctionArgs) {+ assertIsPost(request);+ const { client, companyId, userId } = await requirePermissions(request, {+ create: "settings"+ });++ await requirePlan({+ request,+ client,+ companyId,+ feature: "CUSTOM_RULES",+ redirectTo: path.to.customRules+ });++ const formData = await request.formData();+ const validation = await validator(customRuleValidator).validate(formData);+ if (validation.error) return validation.error;++ const insert = await upsertCustomRule(client, {+ ...validation.data,+ description: validation.data.description ?? null,+ companyId,+ createdBy: userId+ });++ if (insert.error) {+ return await flash(+ request,+ error(insert.error, "Failed to create rule")+ ).then(() => null);+ }++ throw redirect(`${path.to.customRules}?${getParams(request)}`);+}++export async function clientAction({ serverAction }: ClientActionFunctionArgs) {+ window?.clientCache?.setQueryData(+ customRulesQuery(getCompanyId()).queryKey,+ null+ );+ return await serverAction();+}++export default function NewCustomRuleRoute() {+ const { targetType } = useLoaderData<typeof loader>();+ const navigate = useNavigate();+ // navigate(-1) breaks when the page was opened directly (no history entry+ // to pop). Always navigate forward to the parent list route — closes the+ // drawer regardless of how the user got here.+ return (+ <CustomRuleForm+ initialValues={{ targetType }}+ onClose={() => navigate(path.to.customRules)}+ />+ );+}diff --git a/apps/erp/app/routes/x+/settings+/custom-rules.tsx b/apps/erp/app/routes/x+/settings+/custom-rules.tsxnew file mode 100644index 0000000000..9bf04f98b4--- /dev/null+++ b/apps/erp/app/routes/x+/settings+/custom-rules.tsx@@ -0,0 +1,65 @@+import { error } from "@carbon/auth";+import { requirePermissions } from "@carbon/auth/auth.server";+import { flash } from "@carbon/auth/session.server";+import { msg } from "@lingui/core/macro";+import type { LoaderFunctionArgs } from "react-router";+import { Outlet, redirect, useLoaderData } from "react-router";+import { usePlanGate } from "~/hooks/usePlanGate";+import { getCustomRules, getRuleAssignmentCounts } from "~/modules/customRules";+import CustomRulesGroups from "~/modules/customRules/ui/CustomRulesGroups";+import CustomRulesUpgradeOverlay from "~/modules/customRules/ui/CustomRulesUpgradeOverlay";+import type { Handle } from "~/utils/handle";+import { path } from "~/utils/path";++export const handle: Handle = {+ breadcrumb: msg`Custom Rules`,+ to: path.to.customRules+};++export async function loader({ request }: LoaderFunctionArgs) {+ const { client, companyId } = await requirePermissions(request, {+ view: "settings",+ role: "employee"+ });++ const rules = await getCustomRules(client, companyId, {+ search: null,+ limit: 1000,+ offset: 0,+ sorts: []+ });++ if (rules.error) {+ throw redirect(+ path.to.settings,+ await flash(request, error(rules.error, "Failed to load custom rules"))+ );+ }++ const ids = (rules.data ?? []).map((r) => r.id);+ const counts = await getRuleAssignmentCounts(client, ids);++ const countsData = (counts.data ?? {}) as Record<string, number>;+ const rows = (rules.data ?? []).map((r) => ({+ ...r,+ assignmentCount: countsData[r.id] ?? 0+ }));++ return { rows };+}++export default function CustomRulesSettingsRoute() {+ const { rows } = useLoaderData<typeof loader>();+ const { isGated } = usePlanGate({ feature: "CUSTOM_RULES" });++ if (isGated) {+ return <CustomRulesUpgradeOverlay />;+ }++ return (+ <>+ <CustomRulesGroups rules={rows as never} />+ <Outlet />+ </>+ );+}diff --git a/apps/erp/app/routes/x+/shipment+/$shipmentId.post.tsx b/apps/erp/app/routes/x+/shipment+/$shipmentId.post.tsxindex c1f7702c82..b3c11ca9b5 100644--- a/apps/erp/app/routes/x+/shipment+/$shipmentId.post.tsx+++ b/apps/erp/app/routes/x+/shipment+/$shipmentId.post.tsx@@ -2,15 +2,15 @@ import { error, success } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { getCarbonServiceRole } from "@carbon/auth/client.server";import { flash } from "@carbon/auth/session.server";-import { getLocalTimeZone, parseDate, today } from "@internationalized/date";-import type { ActionFunctionArgs } from "react-router";-import { redirect } from "react-router";-import { upsertDocument } from "~/modules/documents";import {dedupeViolations,evaluateLinesForSurface,isBlocked-} from "~/modules/items/itemRules.server";+} from "@carbon/ee/custom-rules.server";+import { getLocalTimeZone, parseDate, today } from "@internationalized/date";+import type { ActionFunctionArgs } from "react-router";+import { redirect } from "react-router";+import { upsertDocument } from "~/modules/documents";import { loader as pdfLoader } from "~/routes/file+/shipment+/$id[.]pdf";import { path } from "~/utils/path";import { stripSpecialCharacters } from "~/utils/string";@@ -67,6 +67,25 @@ export async function action({ request, params }: ActionFunctionArgs) {client: serviceRole,companyId,userId,+ targetType: "item",+ surface,+ lines: evalLines+ });+ allViolations.push(...violations);+ Object.assign(allRuleNames, ruleNames);+ }++ // Storage-unit pass — pick side of the shipment.+ const storageUnitSurfaces: ("pick" | "warehouseTransfer")[] = ["pick"];+ if (shipmentForSurface?.sourceDocument === "Outbound Transfer") {+ storageUnitSurfaces.push("warehouseTransfer");+ }+ for (const surface of storageUnitSurfaces) {+ const { violations, ruleNames } = await evaluateLinesForSurface({+ client: serviceRole,+ companyId,+ userId,+ targetType: "storageUnit",surface,lines: evalLines});diff --git a/apps/erp/app/routes/x+/stock-transfer+/$id.status.tsx b/apps/erp/app/routes/x+/stock-transfer+/$id.status.tsxindex 9f5ba9d426..108980d528 100644--- a/apps/erp/app/routes/x+/stock-transfer+/$id.status.tsx+++ b/apps/erp/app/routes/x+/stock-transfer+/$id.status.tsx@@ -2,16 +2,17 @@ import { assertIsPost, error, success } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { getCarbonServiceRole } from "@carbon/auth/client.server";import { flash } from "@carbon/auth/session.server";+import {+ dedupeViolations,+ evaluateLinesForSurface,+ isBlocked+} from "@carbon/ee/custom-rules.server";import type { ActionFunctionArgs } from "react-router";import { redirect } from "react-router";import {stockTransferStatusType,updateStockTransferStatus} from "~/modules/inventory";-import {- evaluateLinesForSurface,- isBlocked-} from "~/modules/items/itemRules.server";import { path, requestReferrer } from "~/utils/path";export async function action({ request, params }: ActionFunctionArgs) {@@ -50,26 +51,43 @@ export async function action({ request, params }: ActionFunctionArgs) {.eq("stockTransferId", id).eq("companyId", companyId);- const { violations, ruleNames } = await evaluateLinesForSurface({+ const evalLines = (lines ?? []).map((l) => ({+ lineId: l.id as string,+ itemId: l.itemId as string | null,+ storageUnitId: l.toStorageUnitId as string | null,+ quantity: Number(l.quantity ?? 0),+ locationId: null+ }));++ const itemPass = await evaluateLinesForSurface({client: serviceRole,companyId,userId,+ targetType: "item",surface: "stockTransfer",// Evaluate against the destination side — that's where stock is landing.- lines: (lines ?? []).map((l) => ({- lineId: l.id as string,- itemId: l.itemId as string | null,- storageUnitId: l.toStorageUnitId as string | null,- quantity: Number(l.quantity ?? 0),- locationId: null- }))+ lines: evalLines});+ const storagePass = await evaluateLinesForSurface({+ client: serviceRole,+ companyId,+ userId,+ targetType: "storageUnit",+ surface: "stockTransfer",+ lines: evalLines+ });++ const combined = dedupeViolations([+ ...itemPass.violations,+ ...storagePass.violations+ ]);+ const ruleNames = { ...itemPass.ruleNames, ...storagePass.ruleNames };- if (violations.length > 0 && isBlocked(violations, acknowledged)) {+ if (combined.length > 0 && isBlocked(combined, acknowledged)) {return {error: null,data: null,- violations,+ violations: combined,ruleNames};}diff --git a/apps/erp/app/routes/x+/stock-transfer+/new.tsx b/apps/erp/app/routes/x+/stock-transfer+/new.tsxindex ca01a5c4dd..49c37caf33 100644--- a/apps/erp/app/routes/x+/stock-transfer+/new.tsx+++ b/apps/erp/app/routes/x+/stock-transfer+/new.tsx@@ -2,6 +2,11 @@ import { error } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { getCarbonServiceRole } from "@carbon/auth/client.server";import { flash } from "@carbon/auth/session.server";+import {+ dedupeViolations,+ evaluateLinesForSurface,+ isBlocked+} from "@carbon/ee/custom-rules.server";import { validationError, validator } from "@carbon/form";import { msg } from "@lingui/core/macro";import type { ActionFunctionArgs } from "react-router";@@ -12,10 +17,6 @@ import {upsertStockTransfer,upsertStockTransferLines} from "~/modules/inventory";-import {- evaluateLinesForSurface,- isBlocked-} from "~/modules/items/itemRules.server";import { getNextSequence } from "~/modules/settings";import { setCustomFields } from "~/utils/form";import type { Handle } from "~/utils/handle";@@ -61,25 +62,42 @@ export async function action({ request }: ActionFunctionArgs) {// any stock-moving is started. Evaluate against the destination side// (`toStorageUnitId`) — that's where stock will land.const serviceRole = getCarbonServiceRole();- const { violations, ruleNames } = await evaluateLinesForSurface({+ const evalLines = lines.map((l, i) => ({+ lineId: `pending-${i}`,+ itemId: l.itemId,+ storageUnitId: l.toStorageUnitId ?? null,+ quantity: Number(l.quantity ?? 0),+ locationId+ }));++ const itemPass = await evaluateLinesForSurface({client: serviceRole,companyId,userId,+ targetType: "item",surface: "stockTransfer",- lines: lines.map((l, i) => ({- lineId: `pending-${i}`,- itemId: l.itemId,- storageUnitId: l.toStorageUnitId ?? null,- quantity: Number(l.quantity ?? 0),- locationId- }))+ lines: evalLines});+ const storagePass = await evaluateLinesForSurface({+ client: serviceRole,+ companyId,+ userId,+ targetType: "storageUnit",+ surface: "stockTransfer",+ lines: evalLines+ });++ const combined = dedupeViolations([+ ...itemPass.violations,+ ...storagePass.violations+ ]);+ const ruleNames = { ...itemPass.ruleNames, ...storagePass.ruleNames };- if (violations.length > 0 && isBlocked(violations, acknowledged)) {+ if (combined.length > 0 && isBlocked(combined, acknowledged)) {return {error: null,data: null,- violations,+ violations: combined,ruleNames};}diff --git a/apps/erp/app/routes/x+/tool+/$itemId.inventory.tsx b/apps/erp/app/routes/x+/tool+/$itemId.inventory.tsxindex d4a115b38b..31de38940d 100644--- a/apps/erp/app/routes/x+/tool+/$itemId.inventory.tsx+++ b/apps/erp/app/routes/x+/tool+/$itemId.inventory.tsx@@ -1,6 +1,7 @@import { assertIsPost, error, success } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";+import { getCustomRulesDataForTarget } from "@carbon/ee/custom-rules.server";import { validationError, validator } from "@carbon/form";import { VStack } from "@carbon/react";import { pluckUnique } from "@carbon/utils";@@ -8,6 +9,7 @@ import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";import { redirect, useLoaderData } from "react-router";import { useStorageUnits } from "~/components/Form/StorageUnit";import { useRouteData } from "~/hooks";+import RuleAssignmentsList from "~/modules/customRules/ui/RuleAssignmentsList";import {getTrackedEntityExpirations,InventoryDetails@@ -24,9 +26,7 @@ import {upsertPickMethod,upsertPickMethodWithShelfLife} from "~/modules/items";-import { getItemRulesDataForItem } from "~/modules/items/itemRules.server";import { PickMethodForm } from "~/modules/items/ui/Item";-import ItemRuleAssignments from "~/modules/items/ui/ItemRules/ItemRuleAssignments";import { getLocationsList } from "~/modules/resources";import { getUserDefaults } from "~/modules/users/users.server";import { getDatabaseClient } from "~/services/database.server";@@ -154,7 +154,11 @@ export async function loader({ request, params }: LoaderFunctionArgs) {getItemShelfLife(client, itemId),getBomHasShelfLifeManagedInput(client, itemId, companyId),getTrackedEntityExpirations(client, trackedEntityIds),- getItemRulesDataForItem(client, itemId, companyId)+ getCustomRulesDataForTarget(client, {+ targetType: "item",+ targetId: itemId,+ companyId+ })]);return {@@ -292,8 +296,9 @@ export default function ToolInventoryRoute() {quantities={quantities}storageUnits={storageUnits.options}/>- <ItemRuleAssignments- itemId={itemId}+ <RuleAssignmentsList+ targetType="item"+ targetId={itemId}assignments={ruleAssignments as never}library={ruleLibrary as never}/>diff --git a/apps/erp/app/routes/x+/warehouse-transfer+/$transferId.status.tsx b/apps/erp/app/routes/x+/warehouse-transfer+/$transferId.status.tsxindex e1b5945efd..b6f457abe2 100644--- a/apps/erp/app/routes/x+/warehouse-transfer+/$transferId.status.tsx+++ b/apps/erp/app/routes/x+/warehouse-transfer+/$transferId.status.tsx@@ -2,16 +2,17 @@ import { assertIsPost, error, success } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { getCarbonServiceRole } from "@carbon/auth/client.server";import { flash } from "@carbon/auth/session.server";+import {+ dedupeViolations,+ evaluateLinesForSurface,+ isBlocked+} from "@carbon/ee/custom-rules.server";import type { ActionFunctionArgs } from "react-router";import { redirect } from "react-router";import {updateWarehouseTransferStatus,warehouseTransferStatusType} from "~/modules/inventory";-import {- evaluateLinesForSurface,- isBlocked-} from "~/modules/items/itemRules.server";import { path } from "~/utils/path";export async function action({ request, params }: ActionFunctionArgs) {@@ -56,26 +57,44 @@ export async function action({ request, params }: ActionFunctionArgs) {.eq("transferId", id).eq("companyId", companyId);- const { violations, ruleNames } = await evaluateLinesForSurface({+ const evalLines = (lines ?? []).map((l) => ({+ lineId: l.id as string,+ itemId: l.itemId as string | null,+ storageUnitId: l.toStorageUnitId as string | null,+ quantity: Number(l.quantity ?? 0),+ locationId: l.toLocationId as string | null+ }));++ const itemPass = await evaluateLinesForSurface({client: serviceRole,companyId,userId,+ targetType: "item",surface: "warehouseTransfer",// Evaluate against the destination side — that's where stock is landing.- lines: (lines ?? []).map((l) => ({- lineId: l.id as string,- itemId: l.itemId as string | null,- storageUnitId: l.toStorageUnitId as string | null,- quantity: Number(l.quantity ?? 0),- locationId: l.toLocationId as string | null- }))+ lines: evalLines});- if (violations.length > 0 && isBlocked(violations, acknowledged)) {+ const storagePass = await evaluateLinesForSurface({+ client: serviceRole,+ companyId,+ userId,+ targetType: "storageUnit",+ surface: "warehouseTransfer",+ lines: evalLines+ });++ const combined = dedupeViolations([+ ...itemPass.violations,+ ...storagePass.violations+ ]);+ const ruleNames = { ...itemPass.ruleNames, ...storagePass.ruleNames };++ if (combined.length > 0 && isBlocked(combined, acknowledged)) {return {error: null,data: null,- violations,+ violations: combined,ruleNames};}diff --git a/apps/erp/app/utils/path.ts b/apps/erp/app/utils/path.tsindex 5f50d0e337..cd3470d824 100644--- a/apps/erp/app/utils/path.ts+++ b/apps/erp/app/utils/path.ts@@ -777,8 +777,6 @@ export const path = {deleteShipment: (id: string) => generatePath(`${x}/shipment/${id}/delete`),deleteStorageUnit: (id: string) =>generatePath(`${x}/inventory/storage-units/delete/${id}`),- deleteItemRule: (id: string) =>- generatePath(`${x}/items/rules/delete/${id}`),deleteStorageType: (id: string) =>generatePath(`${x}/inventory/storage-types/delete/${id}`),deleteShippingMethod: (id: string) =>@@ -1191,7 +1189,6 @@ export const path = {newSalesRFQLine: (id: string) => generatePath(`${x}/sales-rfq/${id}/new`),newScrapReason: `${x}/production/scrap-reasons/new`,newStorageUnit: `${x}/inventory/storage-units/new`,- newItemRule: `${x}/items/rules/new`,newStorageType: `${x}/inventory/storage-types/new`,newShipment: `${x}/shipment/new`,newShift: `${x}/people/shifts/new`,@@ -1249,12 +1246,28 @@ export const path = {consumableRules: (id: string) =>generatePath(`${x}/consumable/${id}/rules`),toolRules: (id: string) => generatePath(`${x}/tool/${id}/rules`),- itemRules: `${x}/items/rules`,- itemRule: (id: string) => generatePath(`${x}/items/rules/${id}`),- itemRuleAssign: (itemId: string) =>+ customRules: `${x}/settings/custom-rules`,+ customRule: (id: string) =>+ generatePath(`${x}/settings/custom-rules/${id}`),+ newCustomRule: `${x}/settings/custom-rules/new`,+ deleteCustomRule: (id: string) =>+ generatePath(`${x}/settings/custom-rules/${id}/delete`),+ customRuleAssignItem: (itemId: string) =>generatePath(`${x}/items/rules/assign/${itemId}`),- itemRuleUnassign: (itemId: string, ruleId: string) =>+ customRuleUnassignItem: (itemId: string, ruleId: string) =>generatePath(`${x}/items/rules/unassign/${itemId}/${ruleId}`),+ customRuleAssignStorageUnit: (id: string) =>+ generatePath(`${x}/inventory/storage-units/rules/assign/${id}`),+ customRuleUnassignStorageUnit: (id: string, ruleId: string) =>+ generatePath(+ `${x}/inventory/storage-units/rules/unassign/${id}/${ruleId}`+ ),+ customRuleAssignWorkCenter: (id: string) =>+ generatePath(`${x}/resources/work-centers/rules/assign/${id}`),+ customRuleUnassignWorkCenter: (id: string, ruleId: string) =>+ generatePath(+ `${x}/resources/work-centers/rules/unassign/${id}/${ruleId}`+ ),partSales: (id: string) => generatePath(`${x}/part/${id}/sales`),partSupplier: (itemId: string, id: string) =>generatePath(`${x}/part/${itemId}/purchasing/${id}`),@@ -1584,6 +1597,8 @@ export const path = {sequences: `${x}/settings/sequences`,storageUnit: (id: string) =>generatePath(`${x}/inventory/storage-units/${id}`),+ storageUnitRules: (id: string) =>+ generatePath(`${x}/inventory/storage-units/${id}/rules`),storageUnits: `${x}/inventory/storage-units`,storageType: (id: string) =>generatePath(`${x}/inventory/storage-types/${id}`),diff --git a/apps/erp/app/utils/react-query.ts b/apps/erp/app/utils/react-query.tsindex 7af6884cd6..2d104bb407 100644--- a/apps/erp/app/utils/react-query.ts+++ b/apps/erp/app/utils/react-query.ts@@ -149,16 +149,25 @@ export const uomsQuery = (companyId: string | null) => ({staleTime: RefreshRate.Medium});-export const itemRulesQuery = (companyId: string | null) => ({- queryKey: ["itemRules", companyId ?? "null"],+export const customRulesQuery = (+ companyId: string | null,+ targetType?: "item" | "storageUnit" | "workCenter" | null+) => ({+ queryKey: ["customRules", targetType ?? "all", companyId ?? "null"],staleTime: RefreshRate.Low});-export const itemRuleAssignmentsQuery = (- itemId: string,+export const customRuleAssignmentsQuery = (+ targetType: "item" | "storageUnit" | "workCenter",+ targetId: string,companyId: string | null) => ({- queryKey: ["itemRuleAssignments", itemId, companyId ?? "null"],+ queryKey: [+ "customRuleAssignments",+ targetType,+ targetId,+ companyId ?? "null"+ ],staleTime: RefreshRate.Low});diff --git a/apps/mes/app/routes/x+/end.$operationId.tsx b/apps/mes/app/routes/x+/end.$operationId.tsxindex 2736872939..ad0ba5c728 100644--- a/apps/mes/app/routes/x+/end.$operationId.tsx+++ b/apps/mes/app/routes/x+/end.$operationId.tsx@@ -2,6 +2,10 @@ import { error, success } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { getCarbonServiceRole } from "@carbon/auth/client.server";import { flash } from "@carbon/auth/session.server";+import {+ evaluateLinesForSurface,+ isBlocked+} from "@carbon/ee/custom-rules.server";import type { LoaderFunctionArgs } from "react-router";import { redirect } from "react-router";import {@@ -98,6 +102,51 @@ export async function loader({ request, params }: LoaderFunctionArgs) {jobMakeMethod.data.requiresSerialTracking ||jobMakeMethod.data.requiresBatchTracking;+ // Business-rule pre-flight on operationFinish. Only fires when this scan+ // actually closes the operation (`willBeFinished`); transient quantity+ // events don't trigger finish rules.+ if (willBeFinished && jobOperation.data.workCenterId) {+ const acknowledged = url.searchParams.get("acknowledged") === "true";+ const ruleEval = await evaluateLinesForSurface({+ client: serviceRole,+ companyId,+ userId,+ targetType: "workCenter",+ surface: "operationFinish",+ lines: [+ {+ lineId: operationId,+ itemId: jobMakeMethod.data.itemId as string | null,+ workCenterId: jobOperation.data.workCenterId,+ operation: {+ id: operationId,+ itemId: jobMakeMethod.data.itemId as string | null,+ quantity: jobOperation.data.operationQuantity ?? null,+ workInstructionId:+ (jobOperation.data as { workInstructionId?: string | null })+ .workInstructionId ?? null+ },+ quantity: quantityToComplete+ }+ ]+ });+ if (+ ruleEval.violations.length > 0 &&+ isBlocked(ruleEval.violations, acknowledged)+ ) {+ return redirect(+ path.to.operation(operationId),+ await flash(+ request,+ error(+ ruleEval.violations[0]?.message ?? "Rule violation",+ "Cannot finish operation"+ )+ )+ );+ }+ }+if (quantityToComplete > 0) {if (isTrackedEntity) {if (!trackedEntityId) {diff --git a/apps/mes/app/routes/x+/issue.tsx b/apps/mes/app/routes/x+/issue.tsxindex 61c76d7354..2212247e60 100644--- a/apps/mes/app/routes/x+/issue.tsx+++ b/apps/mes/app/routes/x+/issue.tsx@@ -2,6 +2,10 @@ import { assertIsPost, error } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { getCarbonServiceRole } from "@carbon/auth/client.server";import { flash } from "@carbon/auth/session.server";+import {+ evaluateLinesForSurface,+ isBlocked+} from "@carbon/ee/custom-rules.server";import { validationError, validator } from "@carbon/form";import type { ActionFunctionArgs } from "react-router";import { redirect } from "react-router";@@ -15,9 +19,6 @@ export async function action({ request }: ActionFunctionArgs) {const formData = await request.formData();const validation = await validator(issueValidator).validate(formData);- // `validationError` is the shape `<ValidatedForm>` recognises — without it- // a failed submission returns an opaque `{error}` blob the modal silently- // discards, which is exactly the "Issue button does nothing" symptom.if (validation.error) {return validationError(validation.error);}@@ -26,6 +27,56 @@ export async function action({ request }: ActionFunctionArgs) {validation.data;const serviceRole = await getCarbonServiceRole();+ const acknowledged = formData.get("acknowledged") === "true";++ // Resolve workCenter context off the operation so workCenter-scoped rules+ // can evaluate against this materialIssue.+ // `workInstructionId` is in the runtime row but absent from the generated+ // DB types (stale until next regen). Select * and let the manual cast+ // below resolve the field; type only `workCenterId` directly off the row.+ const { data: jobOpRow } = await serviceRole+ .from("jobOperation")+ .select("workCenterId")+ .eq("id", jobOperationId)+ .maybeSingle();++ if (jobOpRow?.workCenterId) {+ const ruleEval = await evaluateLinesForSurface({+ client: serviceRole,+ companyId,+ userId,+ targetType: "workCenter",+ surface: "materialIssue",+ lines: [+ {+ lineId: jobOperationId,+ itemId,+ workCenterId: jobOpRow.workCenterId,+ operation: {+ id: jobOperationId,+ itemId,+ quantity,+ workInstructionId:+ (jobOpRow as { workInstructionId?: string | null })+ .workInstructionId ?? null+ },+ quantity+ }+ ]+ });+ if (+ ruleEval.violations.length > 0 &&+ isBlocked(ruleEval.violations, acknowledged)+ ) {+ return {+ error: null,+ data: null,+ violations: ruleEval.violations,+ ruleNames: ruleEval.ruleNames+ };+ }+ }+const issue = await serviceRole.functions.invoke("issue", {body: {id: jobOperationId,diff --git a/apps/mes/app/routes/x+/start.$operationId.tsx b/apps/mes/app/routes/x+/start.$operationId.tsxindex c888560c3d..c016322886 100644--- a/apps/mes/app/routes/x+/start.$operationId.tsx+++ b/apps/mes/app/routes/x+/start.$operationId.tsx@@ -2,6 +2,10 @@ import { error } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { getCarbonServiceRole } from "@carbon/auth/client.server";import { flash } from "@carbon/auth/session.server";+import {+ evaluateLinesForSurface,+ isBlocked+} from "@carbon/ee/custom-rules.server";import { getLocalTimeZone, now } from "@internationalized/date";import type { LoaderFunctionArgs } from "react-router";import { redirect } from "react-router";@@ -100,6 +104,51 @@ export async function loader({ request, params }: LoaderFunctionArgs) {}}+ // Business-rule pre-flight (workCenter target, operationStart surface).+ // Hard errors abort; warnings flash but allow (loader-only flow has no+ // modal to ack against).+ if (jobOperation.data.workCenterId) {+ const acknowledged = url.searchParams.get("acknowledged") === "true";+ const ruleEval = await evaluateLinesForSurface({+ client: serviceRole,+ companyId,+ userId,+ targetType: "workCenter",+ surface: "operationStart",+ lines: [+ {+ lineId: operationId,+ itemId: null,+ workCenterId: jobOperation.data.workCenterId,+ operation: {+ id: operationId,+ itemId: null,+ quantity: jobOperation.data.operationQuantity ?? null,+ workInstructionId:+ (jobOperation.data as { workInstructionId?: string | null })+ .workInstructionId ?? null+ },+ quantity: jobOperation.data.operationQuantity ?? 0+ }+ ]+ });+ if (+ ruleEval.violations.length > 0 &&+ isBlocked(ruleEval.violations, acknowledged)+ ) {+ throw redirect(+ path.to.operation(operationId),+ await flash(+ request,+ error(+ ruleEval.violations[0]?.message ?? "Rule violation",+ "Cannot start operation"+ )+ )+ );+ }+ }+// If type is Machine, cancel all setup and labor production events for this operationif (type === "Machine") {const currentTime = now(getLocalTimeZone()).toAbsoluteString();diff --git a/apps/mes/app/routes/x+/unconsume.tsx b/apps/mes/app/routes/x+/unconsume.tsxindex 1f6026a7dc..fd92133b26 100644--- a/apps/mes/app/routes/x+/unconsume.tsx+++ b/apps/mes/app/routes/x+/unconsume.tsx@@ -1,6 +1,10 @@import { assertIsPost } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { getCarbonServiceRole } from "@carbon/auth/client.server";+import {+ evaluateLinesForSurface,+ isBlocked+} from "@carbon/ee/custom-rules.server";import type { ActionFunctionArgs } from "react-router";import { data } from "react-router";import { issueTrackedEntityValidator } from "~/services/models";@@ -20,8 +24,81 @@ export async function action({ request }: ActionFunctionArgs) {}const { materialId, parentTrackedEntityId, children } = validation.data;+ if (!materialId) {+ return data(+ { success: false, message: "materialId required" },+ { status: 400 }+ );+ }+ const acknowledged = Boolean(+ (payload as { acknowledged?: boolean }).acknowledged+ );const serviceRole = await getCarbonServiceRole();++ // materialReceive surface — return-to-stock from a job operation. Resolve+ // workCenter via jobMaterial → jobOperation. Skip rule eval if material's+ // operation is unresolvable (consistent with permissive-fallback elsewhere).+ const { data: matRow } = await serviceRole+ .from("jobMaterial")+ .select("jobOperationId, itemId, quantity")+ .eq("id", materialId)+ .maybeSingle();++ if (matRow?.jobOperationId) {+ // `workInstructionId` is in the runtime row but absent from the generated+ // DB types (stale until next regen). Select only the typed column;+ // pick up `workInstructionId` via cast below.+ const { data: jobOpRow } = await serviceRole+ .from("jobOperation")+ .select("workCenterId")+ .eq("id", matRow.jobOperationId)+ .maybeSingle();++ if (jobOpRow?.workCenterId) {+ const workInstructionId =+ (jobOpRow as { workInstructionId?: string | null }).workInstructionId ??+ null;+ const ruleEval = await evaluateLinesForSurface({+ client: serviceRole,+ companyId,+ userId,+ targetType: "workCenter",+ surface: "materialReceive",+ lines: [+ {+ lineId: materialId,+ itemId: (matRow.itemId as string | null) ?? null,+ workCenterId: jobOpRow.workCenterId,+ operation: {+ id: matRow.jobOperationId,+ itemId: (matRow.itemId as string | null) ?? null,+ quantity: matRow.quantity ?? null,+ workInstructionId+ },+ quantity: matRow.quantity ?? 0+ }+ ]+ });+ if (+ ruleEval.violations.length > 0 &&+ isBlocked(ruleEval.violations, acknowledged)+ ) {+ return data(+ {+ success: false,+ message:+ ruleEval.violations[0]?.message ??+ "Rule violation prevented material return",+ violations: ruleEval.violations,+ ruleNames: ruleEval.ruleNames+ },+ { status: 400 }+ );+ }+ }+ }+const issue = await serviceRole.functions.invoke("issue", {body: {type: "unconsumeTrackedEntities",diff --git a/apps/mes/package.json b/apps/mes/package.jsonindex 438e71b741..34d7045be2 100644--- a/apps/mes/package.json+++ b/apps/mes/package.json@@ -5,6 +5,7 @@"@carbon/auth": "workspace:*","@carbon/database": "workspace:*","@carbon/documents": "workspace:*",+ "@carbon/ee": "workspace:*","@carbon/form": "workspace:*","@carbon/jobs": "workspace:*","@carbon/kv": "workspace:*",diff --git a/docker-compose.dev.yml b/docker-compose.dev.ymlindex 114cc01447..345b772329 100644--- a/docker-compose.dev.yml+++ b/docker-compose.dev.yml@@ -239,7 +239,7 @@ services:# Each worktree gets its own logical DB index (0-15) via REDIS_URL.inngest:- image: inngest/inngest:v1.18.0+ image: inngest/inngest:v1.19.4restart: unless-stoppedports:- "${PORT_INNGEST}:8288"diff --git a/packages/database/src/audit.ts b/packages/database/src/audit.tsindex 515ed8b40c..c8346bc220 100644--- a/packages/database/src/audit.ts+++ b/packages/database/src/audit.ts@@ -73,6 +73,44 @@ type AuditRpcClient = {): Promise<{ data: number | null; error: any }>;};+/**+ * Whether an audit-diff key should be hidden from consumers (top-level+ * column or any nested suffix). Mirrors the writer-side filter so legacy+ * rows written before the writer enforced `skipFields` still get scrubbed+ * at read time.+ */+function isSkippedAuditKey(key: string): boolean {+ const skip = auditConfig.skipFields as readonly string[];+ for (let i = 0; i < skip.length; i++) {+ const s = skip[i]!;+ if (key === s || key.endsWith(`.${s}`)) return true;+ }+ return false;+}++/**+ * Strip globally-skipped diff keys from each entry. Keeps the entry itself+ * even when every change was filtered — the entry header (timestamp, actor,+ * operation) is still meaningful history; only the noisy column rows+ * (e.g. `embedding` vectors) get suppressed from the diff payload.+ */+function sanitizeAuditEntries(entries: AuditLogEntry[]): AuditLogEntry[] {+ const out: AuditLogEntry[] = [];+ for (const entry of entries) {+ if (!entry.diff) {+ out.push(entry);+ continue;+ }+ const next: Record<string, unknown> = {};+ for (const [key, value] of Object.entries(entry.diff)) {+ if (isSkippedAuditKey(key)) continue;+ next[key] = value;+ }+ out.push({ ...entry, diff: next as AuditLogEntry["diff"] });+ }+ return out;+}+/*** Get audit log entries for a specific entity.* Queries by entityType (semantic grouping) so that child table changes@@ -104,7 +142,7 @@ export async function getEntityAuditLog(throw new Error(`Failed to fetch audit log: ${error.message}`);}- return data ?? [];+ return sanitizeAuditEntries(data ?? []);}/**@@ -156,7 +194,7 @@ export async function getGlobalAuditLog(}return {- data: data ?? [],+ data: sanitizeAuditEntries(data ?? []),count: count ?? 0};}diff --git a/packages/database/src/types.ts b/packages/database/src/types.tsindex 9fb8a4104b..cad198068f 100644--- a/packages/database/src/types.ts+++ b/packages/database/src/types.ts@@ -6392,6 +6392,524 @@ export type Database = {}Relationships: []}+ customRule: {+ Row: {+ active: boolean+ appliesToAll: boolean+ companyId: string+ conditionAst: Json+ createdAt: string+ createdBy: string+ customFields: Json | null+ description: string | null+ id: string+ message: string+ name: string+ severity: string+ surfaces: Database["public"]["Enums"]["transactionSurface"][]+ targetType: Database["public"]["Enums"]["customRuleTargetType"]+ updatedAt: string | null+ updatedBy: string | null+ }+ Insert: {+ active?: boolean+ appliesToAll?: boolean+ companyId: string+ conditionAst: Json+ createdAt?: string+ createdBy: string+ customFields?: Json | null+ description?: string | null+ id?: string+ message: string+ name: string+ severity: string+ surfaces?: Database["public"]["Enums"]["transactionSurface"][]+ targetType?: Database["public"]["Enums"]["customRuleTargetType"]+ updatedAt?: string | null+ updatedBy?: string | null+ }+ Update: {+ active?: boolean+ appliesToAll?: boolean+ companyId?: string+ conditionAst?: Json+ createdAt?: string+ createdBy?: string+ customFields?: Json | null+ description?: string | null+ id?: string+ message?: string+ name?: string+ severity?: string+ surfaces?: Database["public"]["Enums"]["transactionSurface"][]+ targetType?: Database["public"]["Enums"]["customRuleTargetType"]+ updatedAt?: string | null+ updatedBy?: string | null+ }+ Relationships: [+ {+ foreignKeyName: "customRule_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "companies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "customRule_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "company"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "customRule_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "customFieldTables"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "customRule_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "integrations"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "customRule_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "customRule_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "customRule_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "customRule_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "customRule_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ {+ foreignKeyName: "customRule_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "customRule_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "customRule_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "customRule_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "customRule_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ ]+ }+ customRuleItemAssignment: {+ Row: {+ companyId: string+ createdAt: string+ createdBy: string+ itemId: string+ ruleId: string+ }+ Insert: {+ companyId: string+ createdAt?: string+ createdBy: string+ itemId: string+ ruleId: string+ }+ Update: {+ companyId?: string+ createdAt?: string+ createdBy?: string+ itemId?: string+ ruleId?: string+ }+ Relationships: [+ {+ foreignKeyName: "customRuleItemAssignment_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "companies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "customRuleItemAssignment_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "company"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "customRuleItemAssignment_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "customFieldTables"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "customRuleItemAssignment_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "integrations"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "customRuleItemAssignment_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "customRuleItemAssignment_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "customRuleItemAssignment_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "customRuleItemAssignment_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "customRuleItemAssignment_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ {+ foreignKeyName: "customRuleItemAssignment_itemId_fkey"+ columns: ["itemId"]+ isOneToOne: false+ referencedRelation: "consumables"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "customRuleItemAssignment_itemId_fkey"+ columns: ["itemId"]+ isOneToOne: false+ referencedRelation: "item"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "customRuleItemAssignment_itemId_fkey"+ columns: ["itemId"]+ isOneToOne: false+ referencedRelation: "materials"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "customRuleItemAssignment_itemId_fkey"+ columns: ["itemId"]+ isOneToOne: false+ referencedRelation: "parts"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "customRuleItemAssignment_itemId_fkey"+ columns: ["itemId"]+ isOneToOne: false+ referencedRelation: "services"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "customRuleItemAssignment_itemId_fkey"+ columns: ["itemId"]+ isOneToOne: false+ referencedRelation: "tools"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "customRuleItemAssignment_ruleId_fkey"+ columns: ["ruleId"]+ isOneToOne: false+ referencedRelation: "customRule"+ referencedColumns: ["id"]+ },+ ]+ }+ customRuleStorageUnitAssignment: {+ Row: {+ companyId: string+ createdAt: string+ createdBy: string+ ruleId: string+ storageUnitId: string+ }+ Insert: {+ companyId: string+ createdAt?: string+ createdBy: string+ ruleId: string+ storageUnitId: string+ }+ Update: {+ companyId?: string+ createdAt?: string+ createdBy?: string+ ruleId?: string+ storageUnitId?: string+ }+ Relationships: [+ {+ foreignKeyName: "customRuleStorageUnitAssignment_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "companies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "customRuleStorageUnitAssignment_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "company"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "customRuleStorageUnitAssignment_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "customFieldTables"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "customRuleStorageUnitAssignment_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "integrations"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "customRuleStorageUnitAssignment_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "customRuleStorageUnitAssignment_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "customRuleStorageUnitAssignment_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "customRuleStorageUnitAssignment_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "customRuleStorageUnitAssignment_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ {+ foreignKeyName: "customRuleStorageUnitAssignment_ruleId_fkey"+ columns: ["ruleId"]+ isOneToOne: false+ referencedRelation: "customRule"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "customRuleStorageUnitAssignment_storageUnitId_fkey"+ columns: ["storageUnitId"]+ isOneToOne: false+ referencedRelation: "storageUnit"+ referencedColumns: ["id"]+ },+ ]+ }+ customRuleWorkCenterAssignment: {+ Row: {+ companyId: string+ createdAt: string+ createdBy: string+ ruleId: string+ workCenterId: string+ }+ Insert: {+ companyId: string+ createdAt?: string+ createdBy: string+ ruleId: string+ workCenterId: string+ }+ Update: {+ companyId?: string+ createdAt?: string+ createdBy?: string+ ruleId?: string+ workCenterId?: string+ }+ Relationships: [+ {+ foreignKeyName: "customRuleWorkCenterAssignment_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "companies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "customRuleWorkCenterAssignment_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "company"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "customRuleWorkCenterAssignment_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "customFieldTables"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "customRuleWorkCenterAssignment_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "integrations"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "customRuleWorkCenterAssignment_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "customRuleWorkCenterAssignment_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "customRuleWorkCenterAssignment_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "customRuleWorkCenterAssignment_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "customRuleWorkCenterAssignment_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ {+ foreignKeyName: "customRuleWorkCenterAssignment_ruleId_fkey"+ columns: ["ruleId"]+ isOneToOne: false+ referencedRelation: "customRule"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "customRuleWorkCenterAssignment_workCenterId_fkey"+ columns: ["workCenterId"]+ isOneToOne: false+ referencedRelation: "riskRegisters"+ referencedColumns: ["workCenterId"]+ },+ {+ foreignKeyName: "customRuleWorkCenterAssignment_workCenterId_fkey"+ columns: ["workCenterId"]+ isOneToOne: false+ referencedRelation: "workCenter"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "customRuleWorkCenterAssignment_workCenterId_fkey"+ columns: ["workCenterId"]+ isOneToOne: false+ referencedRelation: "workCenters"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "customRuleWorkCenterAssignment_workCenterId_fkey"+ columns: ["workCenterId"]+ isOneToOne: false+ referencedRelation: "workCentersWithBlockingStatus"+ referencedColumns: ["id"]+ },+ ]+ }demandActual: {Row: {actualQuantity: number@@ -12140,293 +12658,6 @@ export type Database = {},]}- itemRule: {- Row: {- active: boolean- companyId: string- conditionAst: Json- createdAt: string- createdBy: string- customFields: Json | null- description: string | null- id: string- message: string- name: string- severity: string- surfaces: Database["public"]["Enums"]["transactionSurface"][]- updatedAt: string | null- updatedBy: string | null- }- Insert: {- active?: boolean- companyId: string- conditionAst: Json- createdAt?: string- createdBy: string- customFields?: Json | null- description?: string | null- id?: string- message: string- name: string- severity: string- surfaces?: Database["public"]["Enums"]["transactionSurface"][]- updatedAt?: string | null- updatedBy?: string | null- }- Update: {- active?: boolean- companyId?: string- conditionAst?: Json- createdAt?: string- createdBy?: string- customFields?: Json | null- description?: string | null- id?: string- message?: string- name?: string- severity?: string- surfaces?: Database["public"]["Enums"]["transactionSurface"][]- updatedAt?: string | null- updatedBy?: string | null- }- Relationships: [- {- foreignKeyName: "itemRule_companyId_fkey"- columns: ["companyId"]- isOneToOne: false- referencedRelation: "companies"- referencedColumns: ["id"]- },- {- foreignKeyName: "itemRule_companyId_fkey"- columns: ["companyId"]- isOneToOne: false- referencedRelation: "company"- referencedColumns: ["id"]- },- {- foreignKeyName: "itemRule_companyId_fkey"- columns: ["companyId"]- isOneToOne: false- referencedRelation: "customFieldTables"- referencedColumns: ["companyId"]- },- {- foreignKeyName: "itemRule_companyId_fkey"- columns: ["companyId"]- isOneToOne: false- referencedRelation: "integrations"- referencedColumns: ["companyId"]- },- {- foreignKeyName: "itemRule_createdBy_fkey"- columns: ["createdBy"]- isOneToOne: false- referencedRelation: "employees"- referencedColumns: ["id"]- },- {- foreignKeyName: "itemRule_createdBy_fkey"- columns: ["createdBy"]- isOneToOne: false- referencedRelation: "employeesAcrossCompanies"- referencedColumns: ["id"]- },- {- foreignKeyName: "itemRule_createdBy_fkey"- columns: ["createdBy"]- isOneToOne: false- referencedRelation: "employeeSummary"- referencedColumns: ["id"]- },- {- foreignKeyName: "itemRule_createdBy_fkey"- columns: ["createdBy"]- isOneToOne: false- referencedRelation: "user"- referencedColumns: ["id"]- },- {- foreignKeyName: "itemRule_createdBy_fkey"- columns: ["createdBy"]- isOneToOne: false- referencedRelation: "userDefaults"- referencedColumns: ["userId"]- },- {- foreignKeyName: "itemRule_updatedBy_fkey"- columns: ["updatedBy"]- isOneToOne: false- referencedRelation: "employees"- referencedColumns: ["id"]- },- {- foreignKeyName: "itemRule_updatedBy_fkey"- columns: ["updatedBy"]- isOneToOne: false- referencedRelation: "employeesAcrossCompanies"- referencedColumns: ["id"]- },- {- foreignKeyName: "itemRule_updatedBy_fkey"- columns: ["updatedBy"]- isOneToOne: false- referencedRelation: "employeeSummary"- referencedColumns: ["id"]- },- {- foreignKeyName: "itemRule_updatedBy_fkey"- columns: ["updatedBy"]- isOneToOne: false- referencedRelation: "user"- referencedColumns: ["id"]- },- {- foreignKeyName: "itemRule_updatedBy_fkey"- columns: ["updatedBy"]- isOneToOne: false- referencedRelation: "userDefaults"- referencedColumns: ["userId"]- },- ]- }- itemRuleAssignment: {- Row: {- companyId: string- createdAt: string- createdBy: string- itemId: string- ruleId: string- }- Insert: {- companyId: string- createdAt?: string- createdBy: string- itemId: string- ruleId: string- }- Update: {- companyId?: string- createdAt?: string- createdBy?: string- itemId?: string- ruleId?: string- }- Relationships: [- {- foreignKeyName: "itemRuleAssignment_companyId_fkey"- columns: ["companyId"]- isOneToOne: false- referencedRelation: "companies"- referencedColumns: ["id"]- },- {- foreignKeyName: "itemRuleAssignment_companyId_fkey"- columns: ["companyId"]- isOneToOne: false- referencedRelation: "company"- referencedColumns: ["id"]- },- {- foreignKeyName: "itemRuleAssignment_companyId_fkey"- columns: ["companyId"]- isOneToOne: false- referencedRelation: "customFieldTables"- referencedColumns: ["companyId"]- },- {- foreignKeyName: "itemRuleAssignment_companyId_fkey"- columns: ["companyId"]- isOneToOne: false- referencedRelation: "integrations"- referencedColumns: ["companyId"]- },- {- foreignKeyName: "itemRuleAssignment_createdBy_fkey"- columns: ["createdBy"]- isOneToOne: false- referencedRelation: "employees"- referencedColumns: ["id"]- },- {- foreignKeyName: "itemRuleAssignment_createdBy_fkey"- columns: ["createdBy"]- isOneToOne: false- referencedRelation: "employeesAcrossCompanies"- referencedColumns: ["id"]- },- {- foreignKeyName: "itemRuleAssignment_createdBy_fkey"- columns: ["createdBy"]- isOneToOne: false- referencedRelation: "employeeSummary"- referencedColumns: ["id"]- },- {- foreignKeyName: "itemRuleAssignment_createdBy_fkey"- columns: ["createdBy"]- isOneToOne: false- referencedRelation: "user"- referencedColumns: ["id"]- },- {- foreignKeyName: "itemRuleAssignment_createdBy_fkey"- columns: ["createdBy"]- isOneToOne: false- referencedRelation: "userDefaults"- referencedColumns: ["userId"]- },- {- foreignKeyName: "itemRuleAssignment_itemId_fkey"- columns: ["itemId"]- isOneToOne: false- referencedRelation: "consumables"- referencedColumns: ["id"]- },- {- foreignKeyName: "itemRuleAssignment_itemId_fkey"- columns: ["itemId"]- isOneToOne: false- referencedRelation: "item"- referencedColumns: ["id"]- },- {- foreignKeyName: "itemRuleAssignment_itemId_fkey"- columns: ["itemId"]- isOneToOne: false- referencedRelation: "materials"- referencedColumns: ["id"]- },- {- foreignKeyName: "itemRuleAssignment_itemId_fkey"- columns: ["itemId"]- isOneToOne: false- referencedRelation: "parts"- referencedColumns: ["id"]- },- {- foreignKeyName: "itemRuleAssignment_itemId_fkey"- columns: ["itemId"]- isOneToOne: false- referencedRelation: "services"- referencedColumns: ["id"]- },- {- foreignKeyName: "itemRuleAssignment_itemId_fkey"- columns: ["itemId"]- isOneToOne: false- referencedRelation: "tools"- referencedColumns: ["id"]- },- {- foreignKeyName: "itemRuleAssignment_ruleId_fkey"- columns: ["ruleId"]- isOneToOne: false- referencedRelation: "itemRule"- referencedColumns: ["id"]- },- ]- }itemSamplingPlan: {Row: {aql: number | null@@ -36107,7 +36338,7 @@ export type Database = {},]}- searchIndex_CYj9v111oXXm6PX9ZD6Yn2: {+ searchIndex_EUh423aA7ugzjHTPJvVfvL: {Row: {createdAt: stringdescription: string | null@@ -51382,14 +51613,14 @@ export type Database = {},{foreignKeyName: "partner_id_fkey"- columns: ["supplierLocationId"]+ columns: ["id"]isOneToOne: falsereferencedRelation: "supplierLocation"referencedColumns: ["id"]},{foreignKeyName: "partner_id_fkey"- columns: ["id"]+ columns: ["supplierLocationId"]isOneToOne: falsereferencedRelation: "supplierLocation"referencedColumns: ["id"]@@ -52873,14 +53104,14 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey"- columns: ["supplierCountryCode"]+ columns: ["customerCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["customerCountryCode"]+ columns: ["supplierCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]@@ -56863,14 +57094,14 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey"- columns: ["customerCountryCode"]+ columns: ["paymentCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["paymentCountryCode"]+ columns: ["customerCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]@@ -62335,6 +62566,7 @@ export type Database = {| "Indirect Cost"| "Variance"| "Total"+ customRuleTargetType: "item" | "storageUnit" | "workCenter"deadlineType: "No Deadline" | "ASAP" | "Soft Deadline" | "Hard Deadline"demandSourceType: "Sales Order" | "Job Material"dimensionEntityType:@@ -62858,6 +63090,12 @@ export type Database = {| "stockTransfer"| "warehouseTransfer"| "inventoryAdjustment"+ | "place"+ | "pick"+ | "operationStart"+ | "operationFinish"+ | "materialIssue"+ | "materialReceive"warehouseTransferStatus:| "Draft"| "To Ship and Receive"@@ -63582,6 +63820,7 @@ export const Constants = {"Variance","Total",],+ customRuleTargetType: ["item", "storageUnit", "workCenter"],deadlineType: ["No Deadline", "ASAP", "Soft Deadline", "Hard Deadline"],demandSourceType: ["Sales Order", "Job Material"],dimensionEntityType: [@@ -64154,6 +64393,12 @@ export const Constants = {"stockTransfer","warehouseTransfer","inventoryAdjustment",+ "place",+ "pick",+ "operationStart",+ "operationFinish",+ "materialIssue",+ "materialReceive",],warehouseTransferStatus: ["Draft",diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.tsindex 9fb8a4104b..cad198068f 100644--- a/packages/database/supabase/functions/lib/types.ts+++ b/packages/database/supabase/functions/lib/types.ts@@ -6392,6 +6392,524 @@ export type Database = {}Relationships: []}+ customRule: {+ Row: {+ active: boolean+ appliesToAll: boolean+ companyId: string+ conditionAst: Json+ createdAt: string+ createdBy: string+ customFields: Json | null+ description: string | null+ id: string+ message: string+ name: string+ severity: string+ surfaces: Database["public"]["Enums"]["transactionSurface"][]+ targetType: Database["public"]["Enums"]["customRuleTargetType"]+ updatedAt: string | null+ updatedBy: string | null+ }+ Insert: {+ active?: boolean+ appliesToAll?: boolean+ companyId: string+ conditionAst: Json+ createdAt?: string+ createdBy: string+ customFields?: Json | null+ description?: string | null+ id?: string+ message: string+ name: string+ severity: string+ surfaces?: Database["public"]["Enums"]["transactionSurface"][]+ targetType?: Database["public"]["Enums"]["customRuleTargetType"]+ updatedAt?: string | null+ updatedBy?: string | null+ }+ Update: {+ active?: boolean+ appliesToAll?: boolean+ companyId?: string+ conditionAst?: Json+ createdAt?: string+ createdBy?: string+ customFields?: Json | null+ description?: string | null+ id?: string+ message?: string+ name?: string+ severity?: string+ surfaces?: Database["public"]["Enums"]["transactionSurface"][]+ targetType?: Database["public"]["Enums"]["customRuleTargetType"]+ updatedAt?: string | null+ updatedBy?: string | null+ }+ Relationships: [+ {+ foreignKeyName: "customRule_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "companies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "customRule_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "company"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "customRule_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "customFieldTables"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "customRule_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "integrations"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "customRule_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "customRule_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "customRule_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "customRule_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "customRule_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ {+ foreignKeyName: "customRule_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "customRule_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "customRule_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "customRule_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "customRule_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ ]+ }+ customRuleItemAssignment: {+ Row: {+ companyId: string+ createdAt: string+ createdBy: string+ itemId: string+ ruleId: string+ }+ Insert: {+ companyId: string+ createdAt?: string+ createdBy: string+ itemId: string+ ruleId: string+ }+ Update: {+ companyId?: string+ createdAt?: string+ createdBy?: string+ itemId?: string+ ruleId?: string+ }+ Relationships: [+ {+ foreignKeyName: "customRuleItemAssignment_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "companies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "customRuleItemAssignment_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "company"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "customRuleItemAssignment_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "customFieldTables"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "customRuleItemAssignment_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "integrations"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "customRuleItemAssignment_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "customRuleItemAssignment_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "customRuleItemAssignment_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "customRuleItemAssignment_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "customRuleItemAssignment_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ {+ foreignKeyName: "customRuleItemAssignment_itemId_fkey"+ columns: ["itemId"]+ isOneToOne: false+ referencedRelation: "consumables"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "customRuleItemAssignment_itemId_fkey"+ columns: ["itemId"]+ isOneToOne: false+ referencedRelation: "item"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "customRuleItemAssignment_itemId_fkey"+ columns: ["itemId"]+ isOneToOne: false+ referencedRelation: "materials"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "customRuleItemAssignment_itemId_fkey"+ columns: ["itemId"]+ isOneToOne: false+ referencedRelation: "parts"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "customRuleItemAssignment_itemId_fkey"+ columns: ["itemId"]+ isOneToOne: false+ referencedRelation: "services"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "customRuleItemAssignment_itemId_fkey"+ columns: ["itemId"]+ isOneToOne: false+ referencedRelation: "tools"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "customRuleItemAssignment_ruleId_fkey"+ columns: ["ruleId"]+ isOneToOne: false+ referencedRelation: "customRule"+ referencedColumns: ["id"]+ },+ ]+ }+ customRuleStorageUnitAssignment: {+ Row: {+ companyId: string+ createdAt: string+ createdBy: string+ ruleId: string+ storageUnitId: string+ }+ Insert: {+ companyId: string+ createdAt?: string+ createdBy: string+ ruleId: string+ storageUnitId: string+ }+ Update: {+ companyId?: string+ createdAt?: string+ createdBy?: string+ ruleId?: string+ storageUnitId?: string+ }+ Relationships: [+ {+ foreignKeyName: "customRuleStorageUnitAssignment_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "companies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "customRuleStorageUnitAssignment_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "company"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "customRuleStorageUnitAssignment_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "customFieldTables"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "customRuleStorageUnitAssignment_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "integrations"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "customRuleStorageUnitAssignment_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "customRuleStorageUnitAssignment_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "customRuleStorageUnitAssignment_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "customRuleStorageUnitAssignment_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "customRuleStorageUnitAssignment_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ {+ foreignKeyName: "customRuleStorageUnitAssignment_ruleId_fkey"+ columns: ["ruleId"]+ isOneToOne: false+ referencedRelation: "customRule"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "customRuleStorageUnitAssignment_storageUnitId_fkey"+ columns: ["storageUnitId"]+ isOneToOne: false+ referencedRelation: "storageUnit"+ referencedColumns: ["id"]+ },+ ]+ }+ customRuleWorkCenterAssignment: {+ Row: {+ companyId: string+ createdAt: string+ createdBy: string+ ruleId: string+ workCenterId: string+ }+ Insert: {+ companyId: string+ createdAt?: string+ createdBy: string+ ruleId: string+ workCenterId: string+ }+ Update: {+ companyId?: string+ createdAt?: string+ createdBy?: string+ ruleId?: string+ workCenterId?: string+ }+ Relationships: [+ {+ foreignKeyName: "customRuleWorkCenterAssignment_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "companies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "customRuleWorkCenterAssignment_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "company"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "customRuleWorkCenterAssignment_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "customFieldTables"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "customRuleWorkCenterAssignment_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "integrations"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "customRuleWorkCenterAssignment_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "customRuleWorkCenterAssignment_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "customRuleWorkCenterAssignment_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "customRuleWorkCenterAssignment_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "customRuleWorkCenterAssignment_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ {+ foreignKeyName: "customRuleWorkCenterAssignment_ruleId_fkey"+ columns: ["ruleId"]+ isOneToOne: false+ referencedRelation: "customRule"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "customRuleWorkCenterAssignment_workCenterId_fkey"+ columns: ["workCenterId"]+ isOneToOne: false+ referencedRelation: "riskRegisters"+ referencedColumns: ["workCenterId"]+ },+ {+ foreignKeyName: "customRuleWorkCenterAssignment_workCenterId_fkey"+ columns: ["workCenterId"]+ isOneToOne: false+ referencedRelation: "workCenter"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "customRuleWorkCenterAssignment_workCenterId_fkey"+ columns: ["workCenterId"]+ isOneToOne: false+ referencedRelation: "workCenters"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "customRuleWorkCenterAssignment_workCenterId_fkey"+ columns: ["workCenterId"]+ isOneToOne: false+ referencedRelation: "workCentersWithBlockingStatus"+ referencedColumns: ["id"]+ },+ ]+ }demandActual: {Row: {actualQuantity: number@@ -12140,293 +12658,6 @@ export type Database = {},]}- itemRule: {- Row: {- active: boolean- companyId: string- conditionAst: Json- createdAt: string- createdBy: string- customFields: Json | null- description: string | null- id: string- message: string- name: string- severity: string- surfaces: Database["public"]["Enums"]["transactionSurface"][]- updatedAt: string | null- updatedBy: string | null- }- Insert: {- active?: boolean- companyId: string- conditionAst: Json- createdAt?: string- createdBy: string- customFields?: Json | null- description?: string | null- id?: string- message: string- name: string- severity: string- surfaces?: Database["public"]["Enums"]["transactionSurface"][]- updatedAt?: string | null- updatedBy?: string | null- }- Update: {- active?: boolean- companyId?: string- conditionAst?: Json- createdAt?: string- createdBy?: string- customFields?: Json | null- description?: string | null- id?: string- message?: string- name?: string- severity?: string- surfaces?: Database["public"]["Enums"]["transactionSurface"][]- updatedAt?: string | null- updatedBy?: string | null- }- Relationships: [- {- foreignKeyName: "itemRule_companyId_fkey"- columns: ["companyId"]- isOneToOne: false- referencedRelation: "companies"- referencedColumns: ["id"]- },- {- foreignKeyName: "itemRule_companyId_fkey"- columns: ["companyId"]- isOneToOne: false- referencedRelation: "company"- referencedColumns: ["id"]- },- {- foreignKeyName: "itemRule_companyId_fkey"- columns: ["companyId"]- isOneToOne: false- referencedRelation: "customFieldTables"- referencedColumns: ["companyId"]- },- {- foreignKeyName: "itemRule_companyId_fkey"- columns: ["companyId"]- isOneToOne: false- referencedRelation: "integrations"- referencedColumns: ["companyId"]- },- {- foreignKeyName: "itemRule_createdBy_fkey"- columns: ["createdBy"]- isOneToOne: false- referencedRelation: "employees"- referencedColumns: ["id"]- },- {- foreignKeyName: "itemRule_createdBy_fkey"- columns: ["createdBy"]- isOneToOne: false- referencedRelation: "employeesAcrossCompanies"- referencedColumns: ["id"]- },- {- foreignKeyName: "itemRule_createdBy_fkey"- columns: ["createdBy"]- isOneToOne: false- referencedRelation: "employeeSummary"- referencedColumns: ["id"]- },- {- foreignKeyName: "itemRule_createdBy_fkey"- columns: ["createdBy"]- isOneToOne: false- referencedRelation: "user"- referencedColumns: ["id"]- },- {- foreignKeyName: "itemRule_createdBy_fkey"- columns: ["createdBy"]- isOneToOne: false- referencedRelation: "userDefaults"- referencedColumns: ["userId"]- },- {- foreignKeyName: "itemRule_updatedBy_fkey"- columns: ["updatedBy"]- isOneToOne: false- referencedRelation: "employees"- referencedColumns: ["id"]- },- {- foreignKeyName: "itemRule_updatedBy_fkey"- columns: ["updatedBy"]- isOneToOne: false- referencedRelation: "employeesAcrossCompanies"- referencedColumns: ["id"]- },- {- foreignKeyName: "itemRule_updatedBy_fkey"- columns: ["updatedBy"]- isOneToOne: false- referencedRelation: "employeeSummary"- referencedColumns: ["id"]- },- {- foreignKeyName: "itemRule_updatedBy_fkey"- columns: ["updatedBy"]- isOneToOne: false- referencedRelation: "user"- referencedColumns: ["id"]- },- {- foreignKeyName: "itemRule_updatedBy_fkey"- columns: ["updatedBy"]- isOneToOne: false- referencedRelation: "userDefaults"- referencedColumns: ["userId"]- },- ]- }- itemRuleAssignment: {- Row: {- companyId: string- createdAt: string- createdBy: string- itemId: string- ruleId: string- }- Insert: {- companyId: string- createdAt?: string- createdBy: string- itemId: string- ruleId: string- }- Update: {- companyId?: string- createdAt?: string- createdBy?: string- itemId?: string- ruleId?: string- }- Relationships: [- {- foreignKeyName: "itemRuleAssignment_companyId_fkey"- columns: ["companyId"]- isOneToOne: false- referencedRelation: "companies"- referencedColumns: ["id"]- },- {- foreignKeyName: "itemRuleAssignment_companyId_fkey"- columns: ["companyId"]- isOneToOne: false- referencedRelation: "company"- referencedColumns: ["id"]- },- {- foreignKeyName: "itemRuleAssignment_companyId_fkey"- columns: ["companyId"]- isOneToOne: false- referencedRelation: "customFieldTables"- referencedColumns: ["companyId"]- },- {- foreignKeyName: "itemRuleAssignment_companyId_fkey"- columns: ["companyId"]- isOneToOne: false- referencedRelation: "integrations"- referencedColumns: ["companyId"]- },- {- foreignKeyName: "itemRuleAssignment_createdBy_fkey"- columns: ["createdBy"]- isOneToOne: false- referencedRelation: "employees"- referencedColumns: ["id"]- },- {- foreignKeyName: "itemRuleAssignment_createdBy_fkey"- columns: ["createdBy"]- isOneToOne: false- referencedRelation: "employeesAcrossCompanies"- referencedColumns: ["id"]- },- {- foreignKeyName: "itemRuleAssignment_createdBy_fkey"- columns: ["createdBy"]- isOneToOne: false- referencedRelation: "employeeSummary"- referencedColumns: ["id"]- },- {- foreignKeyName: "itemRuleAssignment_createdBy_fkey"- columns: ["createdBy"]- isOneToOne: false- referencedRelation: "user"- referencedColumns: ["id"]- },- {- foreignKeyName: "itemRuleAssignment_createdBy_fkey"- columns: ["createdBy"]- isOneToOne: false- referencedRelation: "userDefaults"- referencedColumns: ["userId"]- },- {- foreignKeyName: "itemRuleAssignment_itemId_fkey"- columns: ["itemId"]- isOneToOne: false- referencedRelation: "consumables"- referencedColumns: ["id"]- },- {- foreignKeyName: "itemRuleAssignment_itemId_fkey"- columns: ["itemId"]- isOneToOne: false- referencedRelation: "item"- referencedColumns: ["id"]- },- {- foreignKeyName: "itemRuleAssignment_itemId_fkey"- columns: ["itemId"]- isOneToOne: false- referencedRelation: "materials"- referencedColumns: ["id"]- },- {- foreignKeyName: "itemRuleAssignment_itemId_fkey"- columns: ["itemId"]- isOneToOne: false- referencedRelation: "parts"- referencedColumns: ["id"]- },- {- foreignKeyName: "itemRuleAssignment_itemId_fkey"- columns: ["itemId"]- isOneToOne: false- referencedRelation: "services"- referencedColumns: ["id"]- },- {- foreignKeyName: "itemRuleAssignment_itemId_fkey"- columns: ["itemId"]- isOneToOne: false- referencedRelation: "tools"- referencedColumns: ["id"]- },- {- foreignKeyName: "itemRuleAssignment_ruleId_fkey"- columns: ["ruleId"]- isOneToOne: false- referencedRelation: "itemRule"- referencedColumns: ["id"]- },- ]- }itemSamplingPlan: {Row: {aql: number | null@@ -36107,7 +36338,7 @@ export type Database = {},]}- searchIndex_CYj9v111oXXm6PX9ZD6Yn2: {+ searchIndex_EUh423aA7ugzjHTPJvVfvL: {Row: {createdAt: stringdescription: string | null@@ -51382,14 +51613,14 @@ export type Database = {},{foreignKeyName: "partner_id_fkey"- columns: ["supplierLocationId"]+ columns: ["id"]isOneToOne: falsereferencedRelation: "supplierLocation"referencedColumns: ["id"]},{foreignKeyName: "partner_id_fkey"- columns: ["id"]+ columns: ["supplierLocationId"]isOneToOne: falsereferencedRelation: "supplierLocation"referencedColumns: ["id"]@@ -52873,14 +53104,14 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey"- columns: ["supplierCountryCode"]+ columns: ["customerCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["customerCountryCode"]+ columns: ["supplierCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]@@ -56863,14 +57094,14 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey"- columns: ["customerCountryCode"]+ columns: ["paymentCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["paymentCountryCode"]+ columns: ["customerCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]@@ -62335,6 +62566,7 @@ export type Database = {| "Indirect Cost"| "Variance"| "Total"+ customRuleTargetType: "item" | "storageUnit" | "workCenter"deadlineType: "No Deadline" | "ASAP" | "Soft Deadline" | "Hard Deadline"demandSourceType: "Sales Order" | "Job Material"dimensionEntityType:@@ -62858,6 +63090,12 @@ export type Database = {| "stockTransfer"| "warehouseTransfer"| "inventoryAdjustment"+ | "place"+ | "pick"+ | "operationStart"+ | "operationFinish"+ | "materialIssue"+ | "materialReceive"warehouseTransferStatus:| "Draft"| "To Ship and Receive"@@ -63582,6 +63820,7 @@ export const Constants = {"Variance","Total",],+ customRuleTargetType: ["item", "storageUnit", "workCenter"],deadlineType: ["No Deadline", "ASAP", "Soft Deadline", "Hard Deadline"],demandSourceType: ["Sales Order", "Job Material"],dimensionEntityType: [@@ -64154,6 +64393,12 @@ export const Constants = {"stockTransfer","warehouseTransfer","inventoryAdjustment",+ "place",+ "pick",+ "operationStart",+ "operationFinish",+ "materialIssue",+ "materialReceive",],warehouseTransferStatus: ["Draft",diff --git a/packages/database/supabase/migrations/20260514120000_custom-rules-enum.sql b/packages/database/supabase/migrations/20260514120000_custom-rules-enum.sqlnew file mode 100644index 0000000000..6c7aa38c82--- /dev/null+++ b/packages/database/supabase/migrations/20260514120000_custom-rules-enum.sql@@ -0,0 +1,15 @@+-- Custom Rules refactor — enum additions only.+-- Split from the table migration so ALTER TYPE ADD VALUE statements+-- run outside the surrounding DDL transaction (Postgres requirement+-- prior to enum value being visible to subsequent statements).++-- Add storageUnit + workCenter surfaces to the existing enum.+ALTER TYPE "transactionSurface" ADD VALUE IF NOT EXISTS 'place';+ALTER TYPE "transactionSurface" ADD VALUE IF NOT EXISTS 'pick';+ALTER TYPE "transactionSurface" ADD VALUE IF NOT EXISTS 'operationStart';+ALTER TYPE "transactionSurface" ADD VALUE IF NOT EXISTS 'operationFinish';+ALTER TYPE "transactionSurface" ADD VALUE IF NOT EXISTS 'materialIssue';+ALTER TYPE "transactionSurface" ADD VALUE IF NOT EXISTS 'materialReceive';++-- New enum identifying which entity a customRule applies to.+CREATE TYPE "customRuleTargetType" AS ENUM ('item', 'storageUnit', 'workCenter');diff --git a/packages/database/supabase/migrations/20260514120001_custom-rules-tables.sql b/packages/database/supabase/migrations/20260514120001_custom-rules-tables.sqlnew file mode 100644index 0000000000..6d5df911d1--- /dev/null+++ b/packages/database/supabase/migrations/20260514120001_custom-rules-tables.sql@@ -0,0 +1,222 @@+-- Custom Rules refactor — rename existing item-rule tables and add+-- support for storageUnit + workCenter target types.++----------------------------------------------------------------------+-- 1. Rename core rule table + constraints/indexes/policies+----------------------------------------------------------------------++ALTER TABLE "itemRule" RENAME TO "customRule";++ALTER TABLE "customRule" RENAME CONSTRAINT "itemRule_companyId_fkey" TO "customRule_companyId_fkey";+ALTER TABLE "customRule" RENAME CONSTRAINT "itemRule_createdBy_fkey" TO "customRule_createdBy_fkey";+ALTER TABLE "customRule" RENAME CONSTRAINT "itemRule_updatedBy_fkey" TO "customRule_updatedBy_fkey";+ALTER TABLE "customRule" RENAME CONSTRAINT "itemRule_companyId_name_key" TO "customRule_companyId_name_key";+ALTER TABLE "customRule" RENAME CONSTRAINT "itemRule_surfaces_nonempty" TO "customRule_surfaces_nonempty";++ALTER INDEX IF EXISTS "itemRule_companyId_idx" RENAME TO "customRule_companyId_idx";+ALTER INDEX IF EXISTS "itemRule_companyId_active_partial_idx" RENAME TO "customRule_companyId_active_partial_idx";++----------------------------------------------------------------------+-- 2. Add new columns to customRule+----------------------------------------------------------------------++ALTER TABLE "customRule"+ ADD COLUMN "targetType" "customRuleTargetType" NOT NULL DEFAULT 'item',+ ADD COLUMN "appliesToAll" BOOLEAN NOT NULL DEFAULT FALSE;++-- Common filter: rules for a given company + targetType + active flag.+CREATE INDEX "customRule_companyId_targetType_active_idx"+ ON "customRule" ("companyId", "targetType")+ WHERE "active" = TRUE;++----------------------------------------------------------------------+-- 3. Move customRule RLS off parts_* permissions onto settings_*+----------------------------------------------------------------------++DROP POLICY IF EXISTS "SELECT" ON "public"."customRule";+DROP POLICY IF EXISTS "INSERT" ON "public"."customRule";+DROP POLICY IF EXISTS "UPDATE" ON "public"."customRule";+DROP POLICY IF EXISTS "DELETE" ON "public"."customRule";++CREATE POLICY "SELECT" ON "public"."customRule"+FOR SELECT USING (+ "companyId" = ANY (+ (SELECT get_companies_with_employee_permission('settings_view'))::text[]+ )+);++CREATE POLICY "INSERT" ON "public"."customRule"+FOR INSERT WITH CHECK (+ "companyId" = ANY (+ (SELECT get_companies_with_employee_permission('settings_create'))::text[]+ )+);++CREATE POLICY "UPDATE" ON "public"."customRule"+FOR UPDATE USING (+ "companyId" = ANY (+ (SELECT get_companies_with_employee_permission('settings_update'))::text[]+ )+);++CREATE POLICY "DELETE" ON "public"."customRule"+FOR DELETE USING (+ "companyId" = ANY (+ (SELECT get_companies_with_employee_permission('settings_delete'))::text[]+ )+);++----------------------------------------------------------------------+-- 4. Rename item assignment table+----------------------------------------------------------------------++ALTER TABLE "itemRuleAssignment" RENAME TO "customRuleItemAssignment";++ALTER TABLE "customRuleItemAssignment"+ RENAME CONSTRAINT "itemRuleAssignment_pkey" TO "customRuleItemAssignment_pkey";+ALTER TABLE "customRuleItemAssignment"+ RENAME CONSTRAINT "itemRuleAssignment_itemId_fkey" TO "customRuleItemAssignment_itemId_fkey";+ALTER TABLE "customRuleItemAssignment"+ RENAME CONSTRAINT "itemRuleAssignment_ruleId_fkey" TO "customRuleItemAssignment_ruleId_fkey";+ALTER TABLE "customRuleItemAssignment"+ RENAME CONSTRAINT "itemRuleAssignment_companyId_fkey" TO "customRuleItemAssignment_companyId_fkey";+ALTER TABLE "customRuleItemAssignment"+ RENAME CONSTRAINT "itemRuleAssignment_createdBy_fkey" TO "customRuleItemAssignment_createdBy_fkey";++ALTER INDEX IF EXISTS "itemRuleAssignment_itemId_idx" RENAME TO "customRuleItemAssignment_itemId_idx";+ALTER INDEX IF EXISTS "itemRuleAssignment_ruleId_idx" RENAME TO "customRuleItemAssignment_ruleId_idx";+ALTER INDEX IF EXISTS "itemRuleAssignment_companyId_idx" RENAME TO "customRuleItemAssignment_companyId_idx";+ALTER INDEX IF EXISTS "itemRuleAssignment_itemId_companyId_idx" RENAME TO "customRuleItemAssignment_itemId_companyId_idx";++----------------------------------------------------------------------+-- 5. Storage unit assignment table+----------------------------------------------------------------------++CREATE TABLE "customRuleStorageUnitAssignment" (+ "storageUnitId" TEXT NOT NULL,+ "ruleId" TEXT NOT NULL,+ "companyId" TEXT NOT NULL,+ "createdBy" TEXT NOT NULL,+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),++ CONSTRAINT "customRuleStorageUnitAssignment_pkey"+ PRIMARY KEY ("storageUnitId", "ruleId"),+ CONSTRAINT "customRuleStorageUnitAssignment_storageUnitId_fkey"+ FOREIGN KEY ("storageUnitId") REFERENCES "storageUnit"("id") ON DELETE CASCADE,+ CONSTRAINT "customRuleStorageUnitAssignment_ruleId_fkey"+ FOREIGN KEY ("ruleId") REFERENCES "customRule"("id") ON DELETE CASCADE,+ CONSTRAINT "customRuleStorageUnitAssignment_companyId_fkey"+ FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE,+ CONSTRAINT "customRuleStorageUnitAssignment_createdBy_fkey"+ FOREIGN KEY ("createdBy") REFERENCES "user"("id")+);++CREATE INDEX "customRuleStorageUnitAssignment_storageUnitId_idx"+ ON "customRuleStorageUnitAssignment" ("storageUnitId");+CREATE INDEX "customRuleStorageUnitAssignment_ruleId_idx"+ ON "customRuleStorageUnitAssignment" ("ruleId");+CREATE INDEX "customRuleStorageUnitAssignment_companyId_idx"+ ON "customRuleStorageUnitAssignment" ("companyId");+CREATE INDEX "customRuleStorageUnitAssignment_storageUnitId_companyId_idx"+ ON "customRuleStorageUnitAssignment" ("storageUnitId", "companyId");++ALTER TABLE "customRuleStorageUnitAssignment" ENABLE ROW LEVEL SECURITY;++CREATE POLICY "SELECT" ON "public"."customRuleStorageUnitAssignment"+FOR SELECT USING (+ "companyId" = ANY (+ (SELECT get_companies_with_employee_role())::text[]+ )+);++CREATE POLICY "INSERT" ON "public"."customRuleStorageUnitAssignment"+FOR INSERT WITH CHECK (+ "companyId" = ANY (+ (SELECT get_companies_with_employee_permission('inventory_create'))::text[]+ )+);++CREATE POLICY "UPDATE" ON "public"."customRuleStorageUnitAssignment"+FOR UPDATE USING (+ "companyId" = ANY (+ (SELECT get_companies_with_employee_permission('inventory_update'))::text[]+ )+);++CREATE POLICY "DELETE" ON "public"."customRuleStorageUnitAssignment"+FOR DELETE USING (+ "companyId" = ANY (+ (SELECT get_companies_with_employee_permission('inventory_delete'))::text[]+ )+);++----------------------------------------------------------------------+-- 6. Work center assignment table+----------------------------------------------------------------------++CREATE TABLE "customRuleWorkCenterAssignment" (+ "workCenterId" TEXT NOT NULL,+ "ruleId" TEXT NOT NULL,+ "companyId" TEXT NOT NULL,+ "createdBy" TEXT NOT NULL,+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),++ CONSTRAINT "customRuleWorkCenterAssignment_pkey"+ PRIMARY KEY ("workCenterId", "ruleId"),+ CONSTRAINT "customRuleWorkCenterAssignment_workCenterId_fkey"+ FOREIGN KEY ("workCenterId") REFERENCES "workCenter"("id") ON DELETE CASCADE,+ CONSTRAINT "customRuleWorkCenterAssignment_ruleId_fkey"+ FOREIGN KEY ("ruleId") REFERENCES "customRule"("id") ON DELETE CASCADE,+ CONSTRAINT "customRuleWorkCenterAssignment_companyId_fkey"+ FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE,+ CONSTRAINT "customRuleWorkCenterAssignment_createdBy_fkey"+ FOREIGN KEY ("createdBy") REFERENCES "user"("id")+);++CREATE INDEX "customRuleWorkCenterAssignment_workCenterId_idx"+ ON "customRuleWorkCenterAssignment" ("workCenterId");+CREATE INDEX "customRuleWorkCenterAssignment_ruleId_idx"+ ON "customRuleWorkCenterAssignment" ("ruleId");+CREATE INDEX "customRuleWorkCenterAssignment_companyId_idx"+ ON "customRuleWorkCenterAssignment" ("companyId");+CREATE INDEX "customRuleWorkCenterAssignment_workCenterId_companyId_idx"+ ON "customRuleWorkCenterAssignment" ("workCenterId", "companyId");++ALTER TABLE "customRuleWorkCenterAssignment" ENABLE ROW LEVEL SECURITY;++CREATE POLICY "SELECT" ON "public"."customRuleWorkCenterAssignment"+FOR SELECT USING (+ "companyId" = ANY (+ (SELECT get_companies_with_employee_role())::text[]+ )+);++CREATE POLICY "INSERT" ON "public"."customRuleWorkCenterAssignment"+FOR INSERT WITH CHECK (+ "companyId" = ANY (+ (SELECT get_companies_with_employee_permission('resources_create'))::text[]+ )+);++CREATE POLICY "UPDATE" ON "public"."customRuleWorkCenterAssignment"+FOR UPDATE USING (+ "companyId" = ANY (+ (SELECT get_companies_with_employee_permission('resources_update'))::text[]+ )+);++CREATE POLICY "DELETE" ON "public"."customRuleWorkCenterAssignment"+FOR DELETE USING (+ "companyId" = ANY (+ (SELECT get_companies_with_employee_permission('resources_delete'))::text[]+ )+);++----------------------------------------------------------------------+-- 7. customFieldTable rename+----------------------------------------------------------------------++UPDATE "customFieldTable"+ SET "table" = 'customRule',+ "name" = 'Custom Rule'+ WHERE "table" = 'itemRule';diff --git a/packages/ee/package.json b/packages/ee/package.jsonindex 12d0583c04..da4414b1ca 100644--- a/packages/ee/package.json+++ b/packages/ee/package.json@@ -5,6 +5,8 @@"exports": {".": "./src/index.ts","./accounting": "./src/accounting/index.ts",+ "./custom-rules": "./src/customRules/index.ts",+ "./custom-rules.server": "./src/customRules/server.ts","./exchange-rates.server": "./src/exchange-rates/exchange-rates.server.ts","./jira": "./src/jira/lib/index.ts","./jira.server": "./src/jira/lib/index.server.ts",diff --git a/packages/ee/src/customRules/index.ts b/packages/ee/src/customRules/index.tsnew file mode 100644index 0000000000..90b4de21e2--- /dev/null+++ b/packages/ee/src/customRules/index.ts@@ -0,0 +1,7 @@+// Public exports for cross-app consumers (ERP + MES).+export * from "./service";+export {+ type CustomRuleViolationPayload,+ useCustomRuleViolations+} from "./use-violations";+export { default as CustomRuleViolationModal } from "./violation-modal";diff --git a/packages/ee/src/customRules/server.ts b/packages/ee/src/customRules/server.tsnew file mode 100644index 0000000000..de9e9519a0--- /dev/null+++ b/packages/ee/src/customRules/server.ts@@ -0,0 +1,628 @@+// Server-side custom-rules evaluator. Cross-app entry point — ERP+// (item/storageUnit surfaces) and MES (workCenter surfaces) both call+// `evaluateLinesForSurface`.+//+// All functions here are server-only. Never import from a client module.++import type { Database } from "@carbon/database";+import {+ type CompiledRule,+ type Condition,+ type ConditionAst,+ compileWithCache,+ evaluateRules,+ getFieldDef,+ type RuleContext,+ type Severity,+ type TargetType,+ type TransactionSurface,+ type ValueOptionsLoader,+ type Violation+} from "@carbon/utils";+import type { SupabaseClient } from "@supabase/supabase-js";+import { companyHasPlan } from "../plan.server";+import {+ getActiveRulesForTargets,+ getCustomRulesList,+ getRuleAssignmentsForTarget+} from "./service";++type Client = SupabaseClient<Database>;++// ---------------------------------------------------------------------------+// Plan gate+// ---------------------------------------------------------------------------++export const isCustomRulesEnabledForCompany = (+ client: Client,+ companyId: string+): Promise<boolean> =>+ companyHasPlan(client, companyId, { feature: "CUSTOM_RULES" });++// ---------------------------------------------------------------------------+// Block decision+// ---------------------------------------------------------------------------++/** Any error blocks unconditionally. Warns block until acknowledged. */+export const isBlocked = (+ violations: Violation[],+ acknowledged: boolean+): boolean => {+ for (let i = 0; i < violations.length; i++) {+ if (violations[i]!.severity === "error") return true;+ }+ return violations.length > 0 && !acknowledged;+};++/**+ * Collapse violations by `ruleId + message`. Call when accumulating results+ * from multiple `evaluateLinesForSurface` invocations (e.g. item pass ++ * storageUnit pass on the same receipt).+ */+export const dedupeViolations = (violations: Violation[]): Violation[] => {+ const seen = new Set<string>();+ const out: Violation[] = [];+ for (let i = 0; i < violations.length; i++) {+ const v = violations[i]!;+ const key = `${v.ruleId}\x00${v.message}`;+ if (seen.has(key)) continue;+ seen.add(key);+ out.push(v);+ }+ return out;+};++// ---------------------------------------------------------------------------+// Per-target Rules tab data (loader helper)+// ---------------------------------------------------------------------------++type AssignedRuleNode = {+ id: string;+ name: string;+ targetType: TargetType;+ severity: Severity;+ message: string;+ active: boolean;+ surfaces: TransactionSurface[];+ appliesToAll: boolean;+};++export async function getCustomRulesDataForTarget(+ client: Client,+ args: { targetType: TargetType; targetId: string; companyId: string }+) {+ const [assignmentsRes, libraryRes] = await Promise.all([+ getRuleAssignmentsForTarget(client, args),+ getCustomRulesList(client, args.companyId, args.targetType)+ ]);++ // Forward inheritance metadata so the drawer can tag inherited rows.+ const assignments: {+ ruleId: string;+ rule: AssignedRuleNode;+ inheritedFromId: string | null;+ inheritedFromName: string | null;+ }[] = [];+ for (const row of assignmentsRes.data ?? []) {+ const joined = row.customRule as+ | AssignedRuleNode+ | AssignedRuleNode[]+ | null;+ const rule = Array.isArray(joined) ? joined[0] : joined;+ if (!rule) continue;+ assignments.push({+ ruleId: row.ruleId,+ rule,+ inheritedFromId: row.inheritedFromId,+ inheritedFromName: row.inheritedFromName+ });+ }++ return { assignments, library: libraryRes.data ?? [] };+}++// ---------------------------------------------------------------------------+// Compile+// ---------------------------------------------------------------------------++async function loadCompiledRulesForTargets(+ client: Client,+ args: { targetType: TargetType; targetIds: string[]; companyId: string }+): Promise<{+ byTarget: Map<string, CompiledRule[]>;+ broadcasts: CompiledRule[];+}> {+ const byTarget = new Map<string, CompiledRule[]>();++ const { data, broadcasts } = await getActiveRulesForTargets(client, args);+ for (const [targetId, rows] of data) {+ const compiled = new Array<CompiledRule>(rows.length);+ for (let i = 0; i < rows.length; i++) {+ const row = rows[i]!;+ compiled[i] = compileWithCache({+ ...row,+ conditionAst: row.conditionAst as ConditionAst+ });+ }+ byTarget.set(targetId, compiled);+ }++ const compiledBroadcasts = new Array<CompiledRule>(broadcasts.length);+ for (let i = 0; i < broadcasts.length; i++) {+ const row = broadcasts[i]!;+ compiledBroadcasts[i] = compileWithCache({+ ...row,+ conditionAst: row.conditionAst as ConditionAst+ });+ }++ return { byTarget, broadcasts: compiledBroadcasts };+}++// ---------------------------------------------------------------------------+// Loader-label resolver — UUID condition values → human labels+// ---------------------------------------------------------------------------++type LoaderFn = (+ client: Client,+ companyId: string+) => Promise<{ id: string; name: string }[]>;++// Inline-table loaders. Each pulls (id, name) for one entity type scoped by+// company. No ERP-app-utils dependency — keeps this file portable across apps.+const LOADERS: Record<ValueOptionsLoader, LoaderFn | null> = {+ locations: async (c, id) => {+ const { data } = await c+ .from("location")+ .select("id, name")+ .eq("companyId", id);+ return (data ?? []) as { id: string; name: string }[];+ },+ storageTypes: async (c, id) => {+ const { data } = await c+ .from("storageType")+ .select("id, name")+ .eq("companyId", id);+ return (data ?? []) as { id: string; name: string }[];+ },+ // Static enums — value is already the label.+ itemTypes: null,+ replenishmentSystems: null,+ itemTrackingTypes: null+};++const EMPTY_RESOLVER = (): undefined => undefined;++async function buildConditionValueResolver(+ client: Client,+ companyId: string,+ conditions: Iterable<Condition>+): Promise<(cond: Condition) => string | undefined> {+ const byLoader = new Map<ValueOptionsLoader, Set<string>>();+ for (const cond of conditions) {+ const def = getFieldDef(cond.field);+ if (!def?.valueOptionsLoader || def.type !== "id") continue;+ if (LOADERS[def.valueOptionsLoader] === null) continue;+ if (cond.value == null) continue;++ let bucket = byLoader.get(def.valueOptionsLoader);+ if (!bucket) {+ bucket = new Set<string>();+ byLoader.set(def.valueOptionsLoader, bucket);+ }+ if (Array.isArray(cond.value)) {+ for (const v of cond.value) bucket.add(String(v));+ } else {+ bucket.add(String(cond.value));+ }+ }++ if (byLoader.size === 0) return EMPTY_RESOLVER;++ const labels = new Map<ValueOptionsLoader, Map<string, string>>();+ await Promise.all(+ Array.from(byLoader.keys()).map(async (loader) => {+ const fn = LOADERS[loader]!;+ const rows = await fn(client, companyId);+ const map = new Map<string, string>();+ for (const r of rows) map.set(r.id, r.name);+ labels.set(loader, map);+ })+ );++ return (cond: Condition): string | undefined => {+ if (cond.value == null) return undefined;+ const def = getFieldDef(cond.field);+ const map = def?.valueOptionsLoader+ ? labels.get(def.valueOptionsLoader)+ : undefined;++ if (Array.isArray(cond.value)) {+ if (cond.value.length === 0) return "—";+ const out: string[] = [];+ for (const v of cond.value) {+ const s = String(v);+ out.push(map?.get(s) ?? s);+ }+ return out.join(", ");+ }+ const s = String(cond.value);+ return map?.get(s) ?? s;+ };+}++// ---------------------------------------------------------------------------+// Per-line evaluator — single entry point trigger handlers call+// ---------------------------------------------------------------------------++export type RuleLineInput = {+ /** Diagnostic identifier — not used in eval. */+ lineId: string;+ /**+ * Item the line operates on. Required when `targetType === "item"`.+ * Available for context in storageUnit/workCenter passes too.+ */+ itemId?: string | null;+ /** Storage unit being interacted with. */+ storageUnitId?: string | null;+ /** Work center being operated. Required when `targetType === "workCenter"`. */+ workCenterId?: string | null;+ /** Operation context for workCenter passes. */+ operation?: {+ id?: string | null;+ itemId?: string | null;+ quantity?: number | null;+ workInstructionId?: string | null;+ };+ /** Quantity for `transaction.quantity` predicates. */+ quantity: number;+ locationId?: string | null;+};++export type EvaluateLinesForSurfaceArgs = {+ client: Client;+ companyId: string;+ userId: string;+ /**+ * Which targetType the call is evaluating. Surfaces that apply to multiple+ * targetTypes (e.g. `stockTransfer`) require one call per targetType — the+ * caller concatenates and `dedupeViolations`-es results.+ */+ targetType: TargetType;+ surface: TransactionSurface;+ lines: RuleLineInput[];+};++export type EvaluateLinesForSurfaceResult = {+ violations: Violation[];+ ruleNames: Record<string, string>;+};++const EMPTY_RESULT: EvaluateLinesForSurfaceResult = {+ violations: [],+ ruleNames: {}+};++type ItemCtxRow = Record<string, unknown> & {+ customFields?: Record<string, unknown>;+};+type StorageUnitCtxRow = Record<string, unknown> & {+ locationId?: string | null;+};+type WorkCenterCtxRow = Record<string, unknown>;++const lineTargetIdFor = (+ line: RuleLineInput,+ targetType: TargetType+): string | null => {+ switch (targetType) {+ case "item":+ return line.itemId ?? null;+ case "storageUnit":+ return line.storageUnitId ?? null;+ case "workCenter":+ return line.workCenterId ?? null;+ }+};++export async function evaluateLinesForSurface({+ client,+ companyId,+ userId,+ targetType,+ surface,+ lines+}: EvaluateLinesForSurfaceArgs): Promise<EvaluateLinesForSurfaceResult> {+ if (lines.length === 0) return EMPTY_RESULT;+ if (!(await isCustomRulesEnabledForCompany(client, companyId)))+ return EMPTY_RESULT;++ const targetIds = new Set<string>();+ const itemIds = new Set<string>();+ const storageUnitIds = new Set<string>();+ const workCenterIds = new Set<string>();+ for (const line of lines) {+ const tid = lineTargetIdFor(line, targetType);+ if (tid) targetIds.add(tid);+ if (line.itemId) itemIds.add(line.itemId);+ if (line.storageUnitId) storageUnitIds.add(line.storageUnitId);+ if (line.workCenterId) workCenterIds.add(line.workCenterId);+ if (line.operation?.itemId) itemIds.add(line.operation.itemId);+ }+ // No early-return on empty targetIds — `appliesToAll` broadcasts must still+ // fire against every line. Explicit-assignment lookup short-circuits inside+ // `getActiveRulesForTargets` when targetIds is empty.++ // Walk the storage-unit tree for every line that carries a bin id. Two+ // inheritance behaviours hang off this fetch:+ // 1. Rules assigned to a parent bin (e.g. "Grow Room") fire on every+ // descendant — expand the rule-assignment lookup set with each line+ // bin's ancestorPath.+ // 2. Storage types cascade: a child bin implicitly carries every+ // `storageTypeIds` declared on itself OR any ancestor. The evaluator+ // unions them when populating `ctx.storageUnit.storageTypeId` below.+ // One round-trip; selects `storageTypeIds` so the union doesn't need a+ // second fetch.+ const ancestorsByBin = new Map<string, string[]>();+ const storageTypesByBin = new Map<string, string[]>();+ let expandedTargetIds: string[] = Array.from(targetIds);+ if (storageUnitIds.size > 0) {+ const ids = Array.from(storageUnitIds);+ const ancestorsRes = await (client as Client)+ .from("storageUnits_recursive")+ .select("id, ancestorPath, storageTypeIds")+ .in("id", ids)+ .eq("companyId", companyId);++ const expanded = new Set<string>(ids);+ const ancestorIds = new Set<string>();+ for (const row of (ancestorsRes.data ?? []) as Array<{+ id: string;+ ancestorPath: string[] | null;+ storageTypeIds: string[] | null;+ }>) {+ const chain =+ row.ancestorPath && row.ancestorPath.length > 0+ ? row.ancestorPath+ : [row.id];+ ancestorsByBin.set(row.id, chain);+ if (row.storageTypeIds) storageTypesByBin.set(row.id, row.storageTypeIds);+ for (const a of chain) {+ expanded.add(a);+ ancestorIds.add(a);+ }+ }+ for (const id of ids) {+ if (!ancestorsByBin.has(id)) ancestorsByBin.set(id, [id]);+ }++ // Second fetch: storageTypeIds for ancestor bins not in the line-bin set+ // (the first query only returned rows for the bins we asked about, not+ // their ancestors). Skip if every ancestor was already in the line set.+ const missing = Array.from(ancestorIds).filter(+ (id) => !storageTypesByBin.has(id) && !ids.includes(id)+ );+ if (missing.length > 0) {+ const ancestorRowsRes = await (client as Client)+ .from("storageUnits_recursive")+ .select("id, storageTypeIds")+ .in("id", missing)+ .eq("companyId", companyId);+ for (const row of (ancestorRowsRes.data ?? []) as Array<{+ id: string;+ storageTypeIds: string[] | null;+ }>) {+ if (row.storageTypeIds)+ storageTypesByBin.set(row.id, row.storageTypeIds);+ }+ }++ // Only the storageUnit-target rule lookup uses the expanded set; item /+ // workCenter rule queries still scope to their own target ids.+ if (targetType === "storageUnit") {+ expandedTargetIds = Array.from(expanded);+ }+ }++ const [itemsRes, storageUnitsRes, workCentersRes, compiled] =+ await Promise.all([+ itemIds.size > 0+ ? client+ .from("item")+ .select(+ "id, type, replenishmentSystem, itemTrackingType, name, readableId, customFields"+ )+ .in("id", Array.from(itemIds))+ : Promise.resolve({ data: [], error: null }),+ storageUnitIds.size > 0+ ? client+ .from("storageUnit")+ .select("id, storageTypeIds, warehouseId, name, locationId")+ .in("id", Array.from(storageUnitIds))+ : Promise.resolve({ data: [], error: null }),+ workCenterIds.size > 0+ ? client+ .from("workCenter")+ .select("id, locationId, active, name")+ .in("id", Array.from(workCenterIds))+ : Promise.resolve({ data: [], error: null }),+ loadCompiledRulesForTargets(client, {+ targetType,+ targetIds: expandedTargetIds,+ companyId+ })+ ]);++ const compiledByTarget = compiled.byTarget;+ const broadcastCompiled = compiled.broadcasts;++ // If neither explicit assignments nor broadcasts exist, nothing can fire.+ if (compiledByTarget.size === 0 && broadcastCompiled.length === 0)+ return EMPTY_RESULT;++ const itemsById = new Map<string, ItemCtxRow>();+ for (const it of itemsRes.data ?? []) {+ const row = it as unknown as Record<string, unknown>;+ const readable = row.readableId as string | undefined;+ itemsById.set(row.id as string, {+ ...row,+ id: readable ?? (row.id as string)+ });+ }++ const unitsById = new Map<string, StorageUnitCtxRow>();+ for (const u of storageUnitsRes.data ?? []) {+ const row = u as Record<string, unknown>;+ const binId = row.id as string;+ // Union storage types across the ancestor chain so a child bin inherits+ // every type declared on itself + every parent. Predicates like+ // `storageUnit.storageTypeId eq frozen` then match when ANY ancestor+ // (incl. self) carries "frozen".+ const chain = ancestorsByBin.get(binId) ?? [binId];+ const unionedTypes = new Set<string>();+ for (const ancestorId of chain) {+ const ownTypes =+ ancestorId === binId+ ? (row.storageTypeIds as string[] | null | undefined)+ : storageTypesByBin.get(ancestorId);+ if (ownTypes) for (const t of ownTypes) unionedTypes.add(t);+ }+ unitsById.set(binId, {+ ...row,+ storageTypeId:+ unionedTypes.size > 0 ? Array.from(unionedTypes) : undefined+ });+ }++ const wcById = new Map<string, WorkCenterCtxRow>();+ for (const w of workCentersRes.data ?? []) {+ const row = w as Record<string, unknown>;+ wcById.set(row.id as string, { ...row });+ }++ const resolveConditionValue = await buildConditionValueResolver(+ client,+ companyId,+ iterateConditions(compiledByTarget, broadcastCompiled)+ );++ const violations: Violation[] = [];+ for (const line of lines) {+ const targetId = lineTargetIdFor(line, targetType);++ // Per-line compiled rule set: explicit assignments (target-keyed, with+ // ancestor inheritance for storageUnit) + broadcasts. Lines without a+ // targetId of this targetType still match broadcasts.+ const seen = new Set<string>();+ const compiledForLine: CompiledRule[] = [];++ if (targetId) {+ if (targetType === "storageUnit") {+ const chain = ancestorsByBin.get(targetId) ?? [targetId];+ for (const ancestorId of chain) {+ const rules = compiledByTarget.get(ancestorId);+ if (!rules) continue;+ for (const r of rules) {+ if (seen.has(r.id)) continue;+ seen.add(r.id);+ compiledForLine.push(r);+ }+ }+ } else {+ const rules = compiledByTarget.get(targetId);+ if (rules) {+ for (const r of rules) {+ if (seen.has(r.id)) continue;+ seen.add(r.id);+ compiledForLine.push(r);+ }+ }+ }+ }++ for (const r of broadcastCompiled) {+ if (seen.has(r.id)) continue;+ seen.add(r.id);+ compiledForLine.push(r);+ }++ if (compiledForLine.length === 0) continue;++ // Fallback id-only ctx objects when the DB lookup misses the row (RLS,+ // missing record, late insert). Keeps `{item.id}` / `{storageUnit.id}` /+ // `{workCenter.id}` token interpolation working — the violation modal+ // shouldn't render "—" just because the join didn't materialize.+ const storageUnit = line.storageUnitId+ ? (unitsById.get(line.storageUnitId) ?? { id: line.storageUnitId })+ : undefined;++ const ctx: RuleContext = {+ item: line.itemId+ ? (itemsById.get(line.itemId) ?? { id: line.itemId })+ : undefined,+ storageUnit,+ workCenter: line.workCenterId+ ? (wcById.get(line.workCenterId) ?? { id: line.workCenterId })+ : undefined,+ operation: line.operation+ ? {+ id: line.operation.id ?? undefined,+ itemId: line.operation.itemId ?? undefined,+ quantity: line.operation.quantity ?? undefined,+ workInstructionId: line.operation.workInstructionId ?? undefined+ }+ : undefined,+ transaction: {+ kind: surface,+ locationId: line.locationId ?? storageUnit?.locationId ?? null,+ quantity: line.quantity,+ userId+ }+ };++ const ruleViolations = evaluateRules(compiledForLine, ctx, surface, {+ resolveConditionValue+ });+ for (let i = 0; i < ruleViolations.length; i++) {+ violations.push(ruleViolations[i]!);+ }+ }++ const deduped = dedupeViolations(violations);+ if (deduped.length === 0) {+ return { violations: deduped, ruleNames: {} };+ }++ const violatedIds = new Set<string>();+ for (let i = 0; i < deduped.length; i++) violatedIds.add(deduped[i]!.ruleId);++ const { data: namedRules } = await client+ .from("customRule")+ .select("id, name")+ .in("id", Array.from(violatedIds))+ .eq("companyId", companyId);++ const ruleNames: Record<string, string> = {};+ for (const r of namedRules ?? []) {+ ruleNames[r.id as string] = r.name as string;+ }++ return { violations: deduped, ruleNames };+}++function* iterateConditions(+ compiledByTarget: Map<string, CompiledRule[]>,+ broadcasts: CompiledRule[]+): Generator<Condition> {+ for (const rules of compiledByTarget.values()) {+ for (let i = 0; i < rules.length; i++) {+ const rule = rules[i]!;+ const conds = rule.conditions;+ for (let j = 0; j < conds.length; j++) yield conds[j]!;+ }+ }+ for (let i = 0; i < broadcasts.length; i++) {+ const conds = broadcasts[i]!.conditions;+ for (let j = 0; j < conds.length; j++) yield conds[j]!;+ }+}diff --git a/packages/ee/src/customRules/service.ts b/packages/ee/src/customRules/service.tsnew file mode 100644index 0000000000..89c4d6e76a--- /dev/null+++ b/packages/ee/src/customRules/service.ts@@ -0,0 +1,410 @@+// Cross-app DB queries for Custom Rules. Both ERP (admin UI, item/storage+// surfaces) and MES (workCenter surfaces) import from here.+//+// ERP-only admin CRUD (list/upsert/delete) stays in the ERP module — it+// depends on ERP request-utils (GenericQueryFilters, sanitize) that don't+// belong in the EE package.++import type { Database } from "@carbon/database";+import { fetchAllFromTable } from "@carbon/database";+import type {+ CustomRuleRow,+ Severity,+ TargetType,+ TransactionSurface+} from "@carbon/utils";+import type { SupabaseClient } from "@supabase/supabase-js";++const assignmentTableFor = (+ targetType: TargetType+):+ | "customRuleItemAssignment"+ | "customRuleStorageUnitAssignment"+ | "customRuleWorkCenterAssignment" => {+ switch (targetType) {+ case "item":+ return "customRuleItemAssignment";+ case "storageUnit":+ return "customRuleStorageUnitAssignment";+ case "workCenter":+ return "customRuleWorkCenterAssignment";+ }+};++const targetIdColumnFor = (+ targetType: TargetType+): "itemId" | "storageUnitId" | "workCenterId" => {+ switch (targetType) {+ case "item":+ return "itemId";+ case "storageUnit":+ return "storageUnitId";+ case "workCenter":+ return "workCenterId";+ }+};++type RuleRowSelect = Pick<+ CustomRuleRow,+ | "id"+ | "targetType"+ | "severity"+ | "message"+ | "conditionAst"+ | "surfaces"+ | "updatedAt"+ | "active"+>;++/**+ * Loads active rules applicable to a set of targets of one targetType.+ *+ * `data` keys are targetIds (explicit-assignment rules only).+ * `broadcasts` carries rules with `appliesToAll = TRUE` — caller merges them+ * into every line, including lines that carry no targetId of this targetType.+ *+ * Two round-trips: explicit-assignments + appliesToAll-broadcast. Broadcast+ * fetch always runs, even when `targetIds` is empty, so a request with no+ * explicit target still sees broadcasts.+ */+export async function getActiveRulesForTargets(+ client: SupabaseClient<Database>,+ args: {+ targetType: TargetType;+ targetIds: string[];+ companyId: string;+ }+): Promise<{+ data: Map<string, CustomRuleRow[]>;+ broadcasts: CustomRuleRow[];+ error: unknown;+}> {+ const out = new Map<string, CustomRuleRow[]>();++ const ruleCols =+ "id, targetType, severity, message, conditionAst, surfaces, updatedAt, active";++ const table = assignmentTableFor(args.targetType);+ const idCol = targetIdColumnFor(args.targetType);++ const [explicit, broadcast] = await Promise.all([+ args.targetIds.length > 0+ ? (client as SupabaseClient<Database>)+ .from(table)+ .select(`${idCol}, customRule:ruleId(${ruleCols})`)+ .in(idCol, args.targetIds)+ .eq("companyId", args.companyId)+ : Promise.resolve({ data: [], error: null }),+ client+ .from("customRule")+ .select(ruleCols)+ .eq("companyId", args.companyId)+ .eq("targetType", args.targetType)+ .eq("appliesToAll", true)+ .eq("active", true)+ ]);++ if (explicit.error)+ return { data: out, broadcasts: [], error: explicit.error };+ if (broadcast.error)+ return { data: out, broadcasts: [], error: broadcast.error };++ for (const r of explicit.data ?? []) {+ const row = r as unknown as {+ [k: string]: unknown;+ customRule: RuleRowSelect | RuleRowSelect[] | null;+ };+ const targetId = row[idCol] as string;+ const node = Array.isArray(row.customRule)+ ? row.customRule[0]+ : row.customRule;+ if (!node || node.active === false) continue;+ if (node.targetType !== args.targetType) continue;+ const bucket = out.get(targetId);+ if (bucket) bucket.push(node as CustomRuleRow);+ else out.set(targetId, [node as CustomRuleRow]);+ }++ const broadcasts = (broadcast.data ?? []) as unknown as CustomRuleRow[];++ return { data: out, broadcasts, error: null };+}++/**+ * Loader-style row returned from `getRuleAssignmentsForTarget`. Adds+ * `inheritedFromId` / `inheritedFromName` so the UI can label rules that+ * came from an ancestor unit (storageUnit hierarchy only) and disable+ * unassign on those rows.+ */+export type RuleAssignmentRow = {+ /** Owner of the assignment row (this target id, or an ancestor unit id). */+ ownerId: string;+ ruleId: string;+ createdAt: string | null;+ customRule: {+ id: string;+ name: string;+ targetType: TargetType;+ severity: Severity;+ message: string;+ active: boolean;+ surfaces?: TransactionSurface[];+ appliesToAll?: boolean;+ };+ /** null when the assignment is direct on `args.targetId`. */+ inheritedFromId: string | null;+ inheritedFromName: string | null;+};++export async function getRuleAssignmentsForTarget(+ client: SupabaseClient<Database>,+ args: { targetType: TargetType; targetId: string; companyId: string }+): Promise<{ data: RuleAssignmentRow[]; error: unknown }> {+ const table = assignmentTableFor(args.targetType);+ const idCol = targetIdColumnFor(args.targetType);++ // Storage units inherit assignments from every ancestor in the tree.+ // Item / workCenter targets are flat — keep the simple direct query.+ const lookupIds = await resolveLookupIds(client, args);++ // Broadcast (`appliesToAll`) rules govern every target of this targetType.+ // Surface them alongside explicit + inherited rows so the drawer shows the+ // full set the evaluator will fire (was previously hidden — drawer showed+ // "0 assignments" while broadcasts still triggered).+ const [res, broadcastsRes] = await Promise.all([+ (client as SupabaseClient<Database>)+ .from(table)+ .select(+ `${idCol}, ruleId, createdAt, customRule:ruleId(id, name, targetType, severity, message, active, surfaces, appliesToAll)`+ )+ .in(idCol, lookupIds)+ .eq("companyId", args.companyId),+ client+ .from("customRule")+ .select(+ "id, name, targetType, severity, message, active, surfaces, appliesToAll, createdAt"+ )+ .eq("companyId", args.companyId)+ .eq("targetType", args.targetType)+ .eq("appliesToAll", true)+ ]);++ if (res.error) return { data: [], error: res.error };+ if (broadcastsRes.error) return { data: [], error: broadcastsRes.error };++ // Resolve ancestor names in one extra query so the UI doesn't need to+ // re-fetch. Only the storageUnit case can yield non-self owner ids.+ const inheritedOwnerIds = new Set<string>();+ for (const r of res.data ?? []) {+ const ownerId = (r as unknown as Record<string, unknown>)[idCol] as string;+ if (ownerId && ownerId !== args.targetId) inheritedOwnerIds.add(ownerId);+ }++ const ancestorNameById = new Map<string, string>();+ if (args.targetType === "storageUnit" && inheritedOwnerIds.size > 0) {+ const namesRes = await client+ .from("storageUnit")+ .select("id, name")+ .in("id", Array.from(inheritedOwnerIds))+ .eq("companyId", args.companyId);+ for (const row of (namesRes.data ?? []) as Array<{+ id: string;+ name: string;+ }>) {+ ancestorNameById.set(row.id, row.name);+ }+ }++ // Dedupe: if the same rule is assigned to both self and an ancestor,+ // keep the direct row (so unassign UI operates on what the user owns).+ const byRuleId = new Map<string, RuleAssignmentRow>();+ for (const r of res.data ?? []) {+ const row = r as unknown as {+ [k: string]: unknown;+ customRule:+ | RuleAssignmentRow["customRule"]+ | RuleAssignmentRow["customRule"][]+ | null;+ };+ const ownerId = row[idCol] as string;+ const node = Array.isArray(row.customRule)+ ? row.customRule[0]+ : row.customRule;+ if (!node) continue;++ const isDirect = ownerId === args.targetId;+ const inheritedFromId = isDirect ? null : ownerId;+ const inheritedFromName = inheritedFromId+ ? (ancestorNameById.get(inheritedFromId) ?? null)+ : null;++ const candidate: RuleAssignmentRow = {+ ownerId,+ ruleId: row.ruleId as string,+ createdAt: (row.createdAt as string | null) ?? null,+ customRule: node,+ inheritedFromId,+ inheritedFromName+ };++ const existing = byRuleId.get(candidate.ruleId);+ // Prefer direct over inherited when both exist for the same rule.+ if (!existing || (existing.inheritedFromId && !candidate.inheritedFromId)) {+ byRuleId.set(candidate.ruleId, candidate);+ }+ }++ // Append broadcasts as synthetic rows. Sentinel `__all__` ownerId distinguishes+ // them from real assignment rows; UI keys off `inheritedFromId === "__all__"`+ // or the rule's `appliesToAll` flag to render the "Applies to all" badge and+ // suppress unassign. Skip when already present as an explicit row (shouldn't+ // happen in practice — broadcast rules can't be assigned — but be defensive).+ for (const b of (broadcastsRes.data ?? []) as Array<{+ id: string;+ name: string;+ targetType: TargetType;+ severity: Severity;+ message: string;+ active: boolean;+ surfaces: TransactionSurface[];+ appliesToAll: boolean;+ createdAt: string | null;+ }>) {+ if (b.active === false) continue;+ if (byRuleId.has(b.id)) continue;+ byRuleId.set(b.id, {+ ownerId: "__all__",+ ruleId: b.id,+ createdAt: b.createdAt,+ customRule: {+ id: b.id,+ name: b.name,+ targetType: b.targetType,+ severity: b.severity,+ message: b.message,+ active: b.active,+ surfaces: b.surfaces,+ appliesToAll: b.appliesToAll+ },+ inheritedFromId: "__all__",+ inheritedFromName: "Applies to all"+ });+ }++ return { data: Array.from(byRuleId.values()), error: null };+}++/**+ * Returns the set of unit ids to query assignments under. For storageUnit+ * targets this is the unit + every ancestor (so child drawer sees inherited+ * rules). For other targets it's just the target id.+ */+async function resolveLookupIds(+ client: SupabaseClient<Database>,+ args: { targetType: TargetType; targetId: string; companyId: string }+): Promise<string[]> {+ if (args.targetType !== "storageUnit") return [args.targetId];++ const { data } = await (client as SupabaseClient<Database>)+ .from("storageUnits_recursive")+ .select("ancestorPath")+ .eq("id", args.targetId)+ .eq("companyId", args.companyId)+ .maybeSingle();++ const row = data as { ancestorPath: string[] | null } | null;+ const chain =+ row?.ancestorPath && row.ancestorPath.length > 0+ ? row.ancestorPath+ : [args.targetId];+ return chain;+}++export async function getCustomRulesList(+ client: SupabaseClient<Database>,+ companyId: string,+ targetType?: TargetType+) {+ return fetchAllFromTable<{+ id: string;+ name: string;+ targetType: TargetType;+ severity: Severity;+ active: boolean;+ appliesToAll: boolean;+ surfaces: TransactionSurface[];+ }>(+ client,+ "customRule",+ "id, name, targetType, severity, active, appliesToAll, surfaces",+ (query) => {+ let q = query.eq("companyId", companyId).order("name");+ if (targetType) q = q.eq("targetType", targetType);+ return q;+ }+ );+}++export async function assignCustomRule(+ client: SupabaseClient<Database>,+ args: {+ targetType: TargetType;+ targetId: string;+ ruleId: string;+ companyId: string;+ userId: string;+ }+) {+ const table = assignmentTableFor(args.targetType);+ const idCol = targetIdColumnFor(args.targetType);++ // Preflight: rule must exist in this company and its targetType must match+ // the assignment table. Without this, callers could insert a storageUnit-rule+ // id into customRuleItemAssignment; the evaluator filters defensively but+ // the orphan row still inflates getRuleAssignmentCounts.+ const ruleRes = await client+ .from("customRule")+ .select("id, targetType")+ .eq("id", args.ruleId)+ .eq("companyId", args.companyId)+ .single();+ if (ruleRes.error || !ruleRes.data) {+ return {+ data: null,+ error: ruleRes.error ?? new Error("Rule not found")+ };+ }+ if (ruleRes.data.targetType !== args.targetType) {+ return {+ data: null,+ error: new Error(+ `Rule targetType "${ruleRes.data.targetType}" does not match "${args.targetType}"`+ )+ };+ }++ return (client as SupabaseClient<Database>)+ .from(table)+ .insert({+ [idCol]: args.targetId,+ ruleId: args.ruleId,+ companyId: args.companyId,+ createdBy: args.userId+ } as never)+ .select(`${idCol}, ruleId`)+ .single();+}++export async function unassignCustomRule(+ client: SupabaseClient<Database>,+ args: { targetType: TargetType; targetId: string; ruleId: string }+) {+ const table = assignmentTableFor(args.targetType);+ const idCol = targetIdColumnFor(args.targetType);++ return (client as SupabaseClient<Database>)+ .from(table)+ .delete()+ .eq(idCol, args.targetId)+ .eq("ruleId", args.ruleId);+}diff --git a/apps/erp/app/hooks/useItemRuleViolations.tsx b/packages/ee/src/customRules/use-violations.tsxsimilarity index 91%rename from apps/erp/app/hooks/useItemRuleViolations.tsxrename to packages/ee/src/customRules/use-violations.tsxindex 6ced99d7ba..2b310f6553 100644--- a/apps/erp/app/hooks/useItemRuleViolations.tsx+++ b/packages/ee/src/customRules/use-violations.tsx@@ -2,21 +2,21 @@ import { toast } from "@carbon/react";import type { Violation } from "@carbon/utils";import { useCallback, useEffect, useRef, useState } from "react";import { useFetcher } from "react-router";-import ItemRuleViolationModal from "~/components/ItemRuleViolationModal";+import CustomRuleViolationModal from "./violation-modal";/*** Shape every item-rule-aware server action must return when it wants the* client to surface violations. Mirrors the payload produced by* `evaluateForItem` + the per-action wrapper that resolves rule names.*/-export type ItemRuleViolationPayload = {+export type CustomRuleViolationPayload = {error?: { message?: string } | null;data?: unknown;violations?: Violation[];ruleNames?: Record<string, string>;};-type UseItemRuleViolationsOptions = {+type UseCustomRuleViolationsOptions = {/** Server action endpoint that the form is posted to. */action: string;/**@@ -26,7 +26,7 @@ type UseItemRuleViolationsOptions = {onSuccess?: () => void;};-type UseItemRuleViolationsResult<T> = {+type UseCustomRuleViolationsResult<T> = {// `useFetcher<T>` actually returns `FetcherWithComponents<SerializeFrom<T>>`;// mirror that here so callers see the serialised payload type without us// having to import the React Router internal `SerializeFrom` helper.@@ -45,7 +45,7 @@ type UseItemRuleViolationsResult<T> = {** Wraps a `useFetcher` and:* - toasts any `error.message` returned by the action- * - opens `<ItemRuleViolationModal>` when the action returns `violations`+ * - opens `<CustomRuleViolationModal>` when the action returns `violations`* - re-posts the last form data with `acknowledged=true` when the user* clicks "Acknowledge & continue"* - resets the dismissed/ack flags on every fresh submission@@ -53,10 +53,10 @@ type UseItemRuleViolationsResult<T> = {* Call sites only have to swap `fetcher.submit(...)` for `rules.submit(...)`* and render `<rules.ViolationModal />`. Everything else is wired internally.*/-export function useItemRuleViolations<T = unknown>({+export function useCustomRuleViolations<T = unknown>({action,onSuccess-}: UseItemRuleViolationsOptions): UseItemRuleViolationsResult<T> {+}: UseCustomRuleViolationsOptions): UseCustomRuleViolationsResult<T> {const fetcher = useFetcher<T>();const lastSubmissionRef = useRef<FormData | null>(null);// Tracks whether a submission was issued but onSuccess hasn't fired yet.@@ -71,7 +71,7 @@ export function useItemRuleViolations<T = unknown>({// forever (page reload was the only way out). Instead, we clear `staged`// when a new submission starts and only re-stage if `fetcher.data` is a// *different* reference than what we last consumed.- const [staged, setStaged] = useState<ItemRuleViolationPayload | undefined>(+ const [staged, setStaged] = useState<CustomRuleViolationPayload | undefined>(undefined);const lastSeenDataRef = useRef<unknown>(undefined);@@ -79,7 +79,7 @@ export function useItemRuleViolations<T = unknown>({// the form submits via `fetcher={...}` prop directly (bypassing `submit()`).const prevIdleRef = useRef(true);- const data = fetcher.data as ItemRuleViolationPayload | undefined;+ const data = fetcher.data as CustomRuleViolationPayload | undefined;const idle = fetcher.state === "idle";const violations = staged?.violations ?? [];const ruleNames = staged?.ruleNames;@@ -164,7 +164,7 @@ export function useItemRuleViolations<T = unknown>({const ViolationModal = useCallback(() => {if (!hasViolations) return null;return (- <ItemRuleViolationModal+ <CustomRuleViolationModalviolations={violations}ruleNames={ruleNames}isSubmitting={!idle}diff --git a/apps/erp/app/components/ItemRuleViolationModal.tsx b/packages/ee/src/customRules/violation-modal.tsxsimilarity index 87%rename from apps/erp/app/components/ItemRuleViolationModal.tsxrename to packages/ee/src/customRules/violation-modal.tsxindex df3d6d57ed..d1f65dad59 100644--- a/apps/erp/app/components/ItemRuleViolationModal.tsx+++ b/packages/ee/src/customRules/violation-modal.tsx@@ -9,13 +9,12 @@ import {ModalTitle} from "@carbon/react";import type { Violation } from "@carbon/utils";-import { Trans, useLingui } from "@lingui/react/macro";import { useMemo } from "react";import { LuOctagonAlert, LuTriangleAlert } from "react-icons/lu";type RuleNameMap = Record<string, string>;-type ItemRuleViolationModalProps = {+type CustomRuleViolationModalProps = {violations: Violation[];ruleNames?: RuleNameMap;onCancel: () => void;@@ -23,15 +22,13 @@ type ItemRuleViolationModalProps = {isSubmitting?: boolean;};-export default function ItemRuleViolationModal({+export default function CustomRuleViolationModal({violations,ruleNames,onCancel,onAcknowledge,isSubmitting-}: ItemRuleViolationModalProps) {- const { t } = useLingui();-+}: CustomRuleViolationModalProps) {const { errors, warns, hasError, onlyWarns } = useMemo(() => {const errs: Violation[] = [];const wrns: Violation[] = [];@@ -65,7 +62,7 @@ export default function ItemRuleViolationModal({) : (<LuTriangleAlert className="text-amber-500 h-5 w-5" />)}- <Trans>Rule Violation</Trans>+ Rule Violation</span></ModalTitle></ModalHeader>@@ -74,7 +71,7 @@ export default function ItemRuleViolationModal({<div className="flex flex-col gap-4 text-sm">{errors.length > 0 && (<ViolationGroup- title={t`Errors`}+ title="Errors"violations={errors}ruleNames={ruleNames}tone="error"@@ -82,7 +79,7 @@ export default function ItemRuleViolationModal({)}{warns.length > 0 && (<ViolationGroup- title={t`Warnings`}+ title="Warnings"violations={warns}ruleNames={ruleNames}tone="warn"@@ -93,7 +90,7 @@ export default function ItemRuleViolationModal({<ModalFooter><Button variant="secondary" onClick={onCancel}>- <Trans>Cancel</Trans>+ Cancel</Button><Buttonvariant={hasError ? "destructive" : "solid"}@@ -101,11 +98,7 @@ export default function ItemRuleViolationModal({isDisabled={hasError || isSubmitting}isLoading={isSubmitting}>- {onlyWarns ? (- <Trans>Acknowledge & continue</Trans>- ) : (- <Trans>Confirm</Trans>- )}+ {onlyWarns ? "Acknowledge & continue" : "Confirm"}</Button></ModalFooter></ModalContent>diff --git a/packages/ee/src/plan.ts b/packages/ee/src/plan.tsindex 6326c63923..f2e806231a 100644--- a/packages/ee/src/plan.ts+++ b/packages/ee/src/plan.ts@@ -9,7 +9,7 @@ export const FEATURE_PLANS = {API_KEYS: [Plan.Business, Plan.Partner],WEBHOOKS: [Plan.Business, Plan.Partner],INTEGRATIONS: [Plan.Business, Plan.Partner],- ITEM_RULES: [Plan.Business],+ CUSTOM_RULES: [Plan.Business],AUDIT_LOG: [Plan.Business]} as const satisfies Record<string, Plan[]>;diff --git a/packages/jobs/src/inngest/functions/events/audit.ts b/packages/jobs/src/inngest/functions/events/audit.tsindex 1f75d90fda..0629099916 100644--- a/packages/jobs/src/inngest/functions/events/audit.ts+++ b/packages/jobs/src/inngest/functions/events/audit.ts@@ -39,6 +39,21 @@ const AuditPayloadSchema = z.object({export type AuditPayload = z.infer<typeof AuditPayloadSchema>;+/**+ * Whether a diff key should be excluded from the audit log. Matches both+ * top-level columns (`"embedding"`) and any nested suffix (`"foo.embedding"`)+ * so vector / metadata columns don't leak when they appear inside JSON+ * containers or under createField allowlists.+ */+function isSkippedAuditKey(key: string): boolean {+ const skip = auditConfig.skipFields as readonly string[];+ for (let i = 0; i < skip.length; i++) {+ const s = skip[i]!;+ if (key === s || key.endsWith(`.${s}`)) return true;+ }+ return false;+}+/*** Compute the diff between old and new record values.*/@@ -47,12 +62,11 @@ function computeDiff(newRecord: Record<string, unknown>): AuditDiff | null {const diff: AuditDiff = {};- const skipFields = auditConfig.skipFields;const allKeys = new Set([...Object.keys(old), ...Object.keys(newRecord)]);for (const key of allKeys) {- if ((skipFields as readonly string[]).includes(key)) continue;+ if (isSkippedAuditKey(key)) continue;const oldValue = old[key];const newValue = newRecord[key];@@ -84,6 +98,8 @@ function computeDiff(/*** Build a diff for INSERT events from an allowlist of columns.* Returns null when no fields are configured or none are present on the record.+ * Globally-skipped fields (e.g. `embedding`) are dropped even if listed in+ * `createFields` so vector / metadata noise can't leak into CREATE diffs.*/function computeCreateDiff(newRecord: Record<string, unknown>,@@ -93,6 +109,7 @@ function computeCreateDiff(const diff: AuditDiff = {};for (const field of createFields) {+ if (isSkippedAuditKey(field)) continue;if (field in newRecord) {diff[field] = { new: newRecord[field] };}@@ -111,11 +128,14 @@ function computeNestedDiff(const allKeys = new Set([...Object.keys(old), ...Object.keys(newRecord)]);for (const key of allKeys) {+ const fullKey = `${prefix}.${key}`;+ if (isSkippedAuditKey(fullKey)) continue;+const oldValue = old[key];const newValue = newRecord[key];if (JSON.stringify(oldValue) !== JSON.stringify(newValue)) {- diff[`${prefix}.${key}`] = { old: oldValue, new: newValue };+ diff[fullKey] = { old: oldValue, new: newValue };}}diff --git a/packages/locale/locales/de/erp.po b/packages/locale/locales/de/erp.poindex 109432f69f..a0bd45d9ed 100644--- a/packages/locale/locales/de/erp.po+++ b/packages/locale/locales/de/erp.po@@ -200,9 +200,6 @@ msgstr "Akkumulationszeitraum (Wochen)"msgid "Accumulation Period:"msgstr "Akkumulationszeitraum:"-msgid "Acknowledge & continue"-msgstr "Bestätigen & fortfahren"-msgid "Action Items"msgstr "Aktionselemente"@@ -488,6 +485,18 @@ msgstr "API-Schlüssel für programmgesteuerten Zugriff auf Ihre Carbon-Daten."msgid "Applies to"msgstr "Gilt für"+msgid "Applies to all"+msgstr ""++msgid "Applies to all items"+msgstr ""++msgid "Applies to all storage units"+msgstr ""++msgid "Applies to all work centers"+msgstr ""+msgid "Apply pricing rules"msgstr "Preisregeln anwenden"@@ -1922,6 +1931,9 @@ msgstr "Benutzerdefiniertes Feld"msgid "Custom Fields"msgstr "Benutzerdefinierte Felder"+msgid "Custom Rules"+msgstr ""+msgid "Customer"msgstr "Kunde"@@ -2776,6 +2788,9 @@ msgstr "Lieferantenprozess bearbeiten"msgid "Edit Supplier Type"msgstr "Lieferantentyp bearbeiten"+msgid "Edit the rule to remove the \"Applies to all\" flag"+msgstr ""+msgid "Edit Timecard"msgstr "Zeitkarte bearbeiten"@@ -2896,12 +2911,6 @@ msgstr "Enddatum"msgid "End Time"msgstr "Endzeit"-msgid "Enforce constraints on receipts, shipments, transfers and job operations for this item."-msgstr "Erzwingen Sie Einschränkungen bei Eingängen, Lieferungen, Transfers und Arbeitsvorgängen für diesen Artikel."--msgid "Enforce per-item validation across receipts, shipments, transfers and adjustments."-msgstr "Erzwinge artikelspezifische Validierung über Eingänge, Lieferungen, Transfers und Anpassungen hinweg."-msgid "Enforce per-item validation and guidelines across receipts, shipments, transfers, and adjustments."msgstr "Erzwingen Sie eine Validierung und Richtlinien pro Artikel über Eingänge, Lieferungen, Transfers und Anpassungen hinweg."@@ -2998,9 +3007,6 @@ msgstr "Fehler beim Entfernen des Modells aus der Bestellzeile"msgid "Error validating serial number"msgstr "Fehler beim Validieren der Seriennummer"-msgid "Errors"-msgstr "Fehler"-msgid "Escalation"msgstr "Eskalation"@@ -3432,6 +3438,9 @@ msgstr "Abrufen"msgid "Field"msgstr "Feld"+msgid "Field info"+msgstr ""+msgid "Field Mapping"msgstr "Feldzuordnung"@@ -3758,6 +3767,9 @@ msgstr "Infrastruktur"msgid "Inherit From Materials"msgstr "Von Materialien erben"+msgid "Inherited from"+msgstr ""+msgid "Insert rows"msgstr "Zeilen einfügen"@@ -3959,9 +3971,6 @@ msgstr "Artikel-ID"msgid "Item Master"msgstr "Artikelstamm"-msgid "Item Rules"-msgstr "Artikelregeln"-msgid "Item Scope"msgstr "Artikelbereich"@@ -4321,6 +4330,9 @@ msgstr "Verwalten Sie, wie die Haltbarkeit in Ihrem Bestand verfolgt, berechnetmsgid "Manage Ownership"msgstr "Eigentümerschaft verwalten"+msgid "Manage rules"+msgstr ""+msgid "Manage Subscription"msgstr "Abonnement verwalten"@@ -5489,9 +5501,6 @@ msgstr "Wählen Sie einen Kunden oder einen Kundentyp aus, um demsgid "Pick a date or leave blank to clear it."msgstr "Wählen Sie ein Datum oder lassen Sie es leer, um es zu löschen."-msgid "Pick an existing rule from the library or create a new one to start enforcing constraints on this item."-msgstr "Wählen Sie eine vorhandene Regel aus der Bibliothek aus oder erstellen Sie eine neue, um Einschränkungen für diesen Artikel durchzusetzen."-msgid "Pick List"msgstr "Pickliste"@@ -6335,9 +6344,6 @@ msgstr "Regel gilt für jeden Artikel."msgid "Rule Type"msgstr "Regeltyp"-msgid "Rule Violation"-msgstr "Regelverstoß"-msgid "Rules"msgstr "Regeln"@@ -7122,6 +7128,9 @@ msgstr "Speichertypen"msgid "Storage Unit"msgstr "Lagereinheit"+msgid "Storage unit rules"+msgstr ""+msgid "Storage Units"msgstr "Lagereinheiten"@@ -7750,6 +7759,9 @@ msgstr "Papierkorb"msgid "Trial Balance"msgstr "Rohbilanz"+msgid "Triggers"+msgstr ""+msgid "Tuesday"msgstr "Dienstag"@@ -7777,6 +7789,9 @@ msgstr "Nicht beprobte Entitäten bleiben in Warteschleife, damimsgid "Unapproved Supplier"msgstr "Nicht genehmigter Lieferant"+msgid "Unassign from parent unit to remove"+msgstr ""+msgid "Unassign rule"msgstr "Regel entfernen"@@ -7897,12 +7912,13 @@ msgstr "Upgrade"msgid "Upgrade to Business"msgstr "Upgrade to Business"+#. placeholder {0}: targetCopy.noun+msgid "Upgrade to unlock {0} rules"+msgstr ""+msgid "Upgrade to unlock audit history"msgstr "Upgrade freischalten, um Audit-Verlauf zu entsperren"-msgid "Upgrade to unlock item rules"-msgstr "Upgrade to unlock item rules"-msgid "Upload"msgstr "Hochladen"@@ -8001,6 +8017,9 @@ msgstr "Auftrag wird validiert..."msgid "Value"msgstr "Wert"+msgid "Value source by surface"+msgstr ""+msgid "VAT Number"msgstr "Umsatzsteuer-Identifikationsnummer"@@ -8190,9 +8209,6 @@ msgstr "Warnen Sie, wenn die Person, die einen eingegangenen Artikel prÃmsgid "Warning"msgstr "Warnung"-msgid "Warnings"-msgstr "Warnungen"-msgid "Watch full video"msgstr "Video vollständig ansehen"@@ -8253,6 +8269,9 @@ msgstr "Wenn die Haltbarkeit eines Fertigprodukts auf â€Ãmsgid "When expired stock is used"msgstr "Wenn abgelaufene Bestände verwendet werden"+msgid "When on, this rule fires for every target of its type. Assignment rows are ignored but preserved."+msgstr ""+msgid "Who Can Approve"msgstr "Wer kann genehmigen"diff --git a/packages/locale/locales/en/erp.po b/packages/locale/locales/en/erp.poindex f982bedc4c..6dd7d40f9f 100644--- a/packages/locale/locales/en/erp.po+++ b/packages/locale/locales/en/erp.po@@ -200,9 +200,6 @@ msgstr "Accumulation Period (Weeks)"msgid "Accumulation Period:"msgstr "Accumulation Period:"-msgid "Acknowledge & continue"-msgstr "Acknowledge & continue"-msgid "Action Items"msgstr "Action Items"@@ -488,6 +485,18 @@ msgstr "API keys for programmatic access to your Carbon data."msgid "Applies to"msgstr "Applies to"+msgid "Applies to all"+msgstr "Applies to all"++msgid "Applies to all items"+msgstr "Applies to all items"++msgid "Applies to all storage units"+msgstr "Applies to all storage units"++msgid "Applies to all work centers"+msgstr "Applies to all work centers"+msgid "Apply pricing rules"msgstr "Apply pricing rules"@@ -1922,6 +1931,9 @@ msgstr "Custom Field"msgid "Custom Fields"msgstr "Custom Fields"+msgid "Custom Rules"+msgstr "Custom Rules"+msgid "Customer"msgstr "Customer"@@ -2776,6 +2788,9 @@ msgstr "Edit supplier process"msgid "Edit Supplier Type"msgstr "Edit Supplier Type"+msgid "Edit the rule to remove the \"Applies to all\" flag"+msgstr "Edit the rule to remove the \"Applies to all\" flag"+msgid "Edit Timecard"msgstr "Edit Timecard"@@ -2896,12 +2911,6 @@ msgstr "End Date"msgid "End Time"msgstr "End Time"-msgid "Enforce constraints on receipts, shipments, transfers and job operations for this item."-msgstr "Enforce constraints on receipts, shipments, transfers and job operations for this item."--msgid "Enforce per-item validation across receipts, shipments, transfers and adjustments."-msgstr "Enforce per-item validation across receipts, shipments, transfers and adjustments."-msgid "Enforce per-item validation and guidelines across receipts, shipments, transfers, and adjustments."msgstr "Enforce per-item validation and guidelines across receipts, shipments, transfers, and adjustments."@@ -2998,9 +3007,6 @@ msgstr "Error removing model from sales order line"msgid "Error validating serial number"msgstr "Error validating serial number"-msgid "Errors"-msgstr "Errors"-msgid "Escalation"msgstr "Escalation"@@ -3432,6 +3438,9 @@ msgstr "Fetch"msgid "Field"msgstr "Field"+msgid "Field info"+msgstr "Field info"+msgid "Field Mapping"msgstr "Field Mapping"@@ -3758,6 +3767,9 @@ msgstr "Infrastructure"msgid "Inherit From Materials"msgstr "Inherit From Materials"+msgid "Inherited from"+msgstr "Inherited from"+msgid "Insert rows"msgstr "Insert rows"@@ -3959,9 +3971,6 @@ msgstr "Item ID"msgid "Item Master"msgstr "Item Master"-msgid "Item Rules"-msgstr "Item Rules"-msgid "Item Scope"msgstr "Item Scope"@@ -4321,6 +4330,9 @@ msgstr "Manage how shelf life is tracked, computed, and enforced across inventormsgid "Manage Ownership"msgstr "Manage Ownership"+msgid "Manage rules"+msgstr "Manage rules"+msgid "Manage Subscription"msgstr "Manage Subscription"@@ -5489,9 +5501,6 @@ msgstr "Pick a customer or customer type to view their pricing."msgid "Pick a date or leave blank to clear it."msgstr "Pick a date or leave blank to clear it."-msgid "Pick an existing rule from the library or create a new one to start enforcing constraints on this item."-msgstr "Pick an existing rule from the library or create a new one to start enforcing constraints on this item."-msgid "Pick List"msgstr "Pick List"@@ -6335,9 +6344,6 @@ msgstr "Rule applies to every item."msgid "Rule Type"msgstr "Rule Type"-msgid "Rule Violation"-msgstr "Rule Violation"-msgid "Rules"msgstr "Rules"@@ -7122,6 +7128,9 @@ msgstr "Storage Types"msgid "Storage Unit"msgstr "Storage Unit"+msgid "Storage unit rules"+msgstr "Storage unit rules"+msgid "Storage Units"msgstr "Storage Units"@@ -7750,6 +7759,9 @@ msgstr "Trash"msgid "Trial Balance"msgstr "Trial Balance"+msgid "Triggers"+msgstr "Triggers"+msgid "Tuesday"msgstr "Tuesday"@@ -7777,6 +7789,9 @@ msgstr "Un-sampled entities will remain On Hold so you can keep inspecting and dmsgid "Unapproved Supplier"msgstr "Unapproved Supplier"+msgid "Unassign from parent unit to remove"+msgstr "Unassign from parent unit to remove"+msgid "Unassign rule"msgstr "Unassign rule"@@ -7897,12 +7912,13 @@ msgstr "Upgrade"msgid "Upgrade to Business"msgstr "Upgrade to Business"+#. placeholder {0}: targetCopy.noun+msgid "Upgrade to unlock {0} rules"+msgstr "Upgrade to unlock {0} rules"+msgid "Upgrade to unlock audit history"msgstr "Upgrade to unlock audit history"-msgid "Upgrade to unlock item rules"-msgstr "Upgrade to unlock item rules"-msgid "Upload"msgstr "Upload"@@ -8001,6 +8017,9 @@ msgstr "Validating job..."msgid "Value"msgstr "Value"+msgid "Value source by surface"+msgstr "Value source by surface"+msgid "VAT Number"msgstr "VAT Number"@@ -8190,9 +8209,6 @@ msgstr "Warn when the person inspecting an inbound item is the same person who rmsgid "Warning"msgstr "Warning"-msgid "Warnings"-msgstr "Warnings"-msgid "Watch full video"msgstr "Watch full video"@@ -8253,6 +8269,9 @@ msgstr "When a finished product's shelf life is set to Calculated, pick which comsgid "When expired stock is used"msgstr "When expired stock is used"+msgid "When on, this rule fires for every target of its type. Assignment rows are ignored but preserved."+msgstr "When on, this rule fires for every target of its type. Assignment rows are ignored but preserved."+msgid "Who Can Approve"msgstr "Who Can Approve"diff --git a/packages/locale/locales/es/erp.po b/packages/locale/locales/es/erp.poindex 673e20a113..1c9a87a63a 100644--- a/packages/locale/locales/es/erp.po+++ b/packages/locale/locales/es/erp.po@@ -200,9 +200,6 @@ msgstr "PerÃÂÂodo de Acumulación (Semanas)"msgid "Accumulation Period:"msgstr "PerÃÂÂodo de Acumulación:"-msgid "Acknowledge & continue"-msgstr "Reconocer y continuar"-msgid "Action Items"msgstr "Elementos de Acción"@@ -488,6 +485,18 @@ msgstr "Claves API para acceso programático a tus datos de Carbon."msgid "Applies to"msgstr "Se aplica a"+msgid "Applies to all"+msgstr ""++msgid "Applies to all items"+msgstr ""++msgid "Applies to all storage units"+msgstr ""++msgid "Applies to all work centers"+msgstr ""+msgid "Apply pricing rules"msgstr "Aplicar reglas de precios"@@ -1922,6 +1931,9 @@ msgstr "Campo Personalizado"msgid "Custom Fields"msgstr "Campos Personalizados"+msgid "Custom Rules"+msgstr ""+msgid "Customer"msgstr "Cliente"@@ -2776,6 +2788,9 @@ msgstr "Editar proceso del proveedor"msgid "Edit Supplier Type"msgstr "Editar Tipo de Proveedor"+msgid "Edit the rule to remove the \"Applies to all\" flag"+msgstr ""+msgid "Edit Timecard"msgstr "Editar Tarjeta de Tiempo"@@ -2896,12 +2911,6 @@ msgstr "Fecha de Fin"msgid "End Time"msgstr "Hora de Finalización"-msgid "Enforce constraints on receipts, shipments, transfers and job operations for this item."-msgstr "Aplicar restricciones en recibos, envÃÂÂos, transferencias y operaciones de trabajo para este artÃÂÂculo."--msgid "Enforce per-item validation across receipts, shipments, transfers and adjustments."-msgstr "Aplicar validación por artÃÂÂculo en recibos, envÃÂÂos, transferencias y ajustes."-msgid "Enforce per-item validation and guidelines across receipts, shipments, transfers, and adjustments."msgstr "Aplicar validación y directrices por artÃÂÂculo en recibos, envÃÂÂos, transferencias y ajustes."@@ -2998,9 +3007,6 @@ msgstr "Error al eliminar el modelo de la lÃÂÂnea de orden de venmsgid "Error validating serial number"msgstr "Error validando número de serie"-msgid "Errors"-msgstr "Errores"-msgid "Escalation"msgstr "Escalada"@@ -3432,6 +3438,9 @@ msgstr "Obtener"msgid "Field"msgstr "Campo"+msgid "Field info"+msgstr ""+msgid "Field Mapping"msgstr "Mapeo de campos"@@ -3758,6 +3767,9 @@ msgstr "Infraestructura"msgid "Inherit From Materials"msgstr "Heredar de Materiales"+msgid "Inherited from"+msgstr ""+msgid "Insert rows"msgstr "Insertar filas"@@ -3959,9 +3971,6 @@ msgstr "ID de ArtÃÂÂculo"msgid "Item Master"msgstr "Maestro de ArtÃÂÂculos"-msgid "Item Rules"-msgstr "Reglas de ArtÃÂÂculos"-msgid "Item Scope"msgstr "Alcance de ArtÃÂÂculos"@@ -4321,6 +4330,9 @@ msgstr "Administra cómo se rastrea, calcula y aplica la vida Ãmsgid "Manage Ownership"msgstr "Gestionar Propiedad"+msgid "Manage rules"+msgstr ""+msgid "Manage Subscription"msgstr "Administrar Suscripción"@@ -5489,9 +5501,6 @@ msgstr "Selecciona un cliente o tipo de cliente para ver sus precios."msgid "Pick a date or leave blank to clear it."msgstr "Elige una fecha o déjala en blanco para borrarla."-msgid "Pick an existing rule from the library or create a new one to start enforcing constraints on this item."-msgstr "Elige una regla existente de la biblioteca o crea una nueva para comenzar a aplicar restricciones en este artÃÂÂculo."-msgid "Pick List"msgstr "Lista de Picking"@@ -6335,9 +6344,6 @@ msgstr "La regla se aplica a todos los artÃÂÂculos."msgid "Rule Type"msgstr "Tipo de Regla"-msgid "Rule Violation"-msgstr "Violación de regla"-msgid "Rules"msgstr "Reglas"@@ -7122,6 +7128,9 @@ msgstr "Tipos de Almacenamiento"msgid "Storage Unit"msgstr "Unidad de Almacenamiento"+msgid "Storage unit rules"+msgstr ""+msgid "Storage Units"msgstr "Unidades de Almacenamiento"@@ -7750,6 +7759,9 @@ msgstr "Papelera"msgid "Trial Balance"msgstr "Balance de Comprobación"+msgid "Triggers"+msgstr ""+msgid "Tuesday"msgstr "Martes"@@ -7777,6 +7789,9 @@ msgstr "Las entidades no muestreadas permanecerán En Espera parmsgid "Unapproved Supplier"msgstr "Proveedor No Aprobado"+msgid "Unassign from parent unit to remove"+msgstr ""+msgid "Unassign rule"msgstr "Desasignar regla"@@ -7897,12 +7912,13 @@ msgstr "Actualizar"msgid "Upgrade to Business"msgstr "Actualizar a Business"+#. placeholder {0}: targetCopy.noun+msgid "Upgrade to unlock {0} rules"+msgstr ""+msgid "Upgrade to unlock audit history"msgstr "Actualizar para desbloquear el historial de auditorÃÂÂa"-msgid "Upgrade to unlock item rules"-msgstr "Actualizar para desbloquear reglas de artÃÂÂculos"-msgid "Upload"msgstr "Cargar"@@ -8001,6 +8017,9 @@ msgstr "Validando trabajo..."msgid "Value"msgstr "Valor"+msgid "Value source by surface"+msgstr ""+msgid "VAT Number"msgstr "Número de IVA"@@ -8190,9 +8209,6 @@ msgstr "Advertir cuando la persona que inspecciona un artÃÂÂculomsgid "Warning"msgstr "Advertencia"-msgid "Warnings"-msgstr "Advertencias"-msgid "Watch full video"msgstr "Ver video completo"@@ -8253,6 +8269,9 @@ msgstr "Cuando la vida útil de un producto terminado se establemsgid "When expired stock is used"msgstr "Cuando se utiliza stock vencido"+msgid "When on, this rule fires for every target of its type. Assignment rows are ignored but preserved."+msgstr ""+msgid "Who Can Approve"msgstr "Quién Puede Aprobar"diff --git a/packages/locale/locales/fr/erp.po b/packages/locale/locales/fr/erp.poindex a675133e56..e0451f9c76 100644--- a/packages/locale/locales/fr/erp.po+++ b/packages/locale/locales/fr/erp.po@@ -200,9 +200,6 @@ msgstr "Période d'accumulation (semaines)"msgid "Accumulation Period:"msgstr "Période d'accumulation :"-msgid "Acknowledge & continue"-msgstr "Reconnaître et continuer"-msgid "Action Items"msgstr "Éléments d'action"@@ -488,6 +485,18 @@ msgstr "Clés API pour un accès programmatique à vos données Carbon."msgid "Applies to"msgstr "S'applique à"+msgid "Applies to all"+msgstr ""++msgid "Applies to all items"+msgstr ""++msgid "Applies to all storage units"+msgstr ""++msgid "Applies to all work centers"+msgstr ""+msgid "Apply pricing rules"msgstr "Appliquer les règles de tarification"@@ -1922,6 +1931,9 @@ msgstr "Champ personnalisé"msgid "Custom Fields"msgstr "Champs personnalisés"+msgid "Custom Rules"+msgstr ""+msgid "Customer"msgstr "Client"@@ -2776,6 +2788,9 @@ msgstr "Modifier le processus du fournisseur"msgid "Edit Supplier Type"msgstr "Modifier le type de fournisseur"+msgid "Edit the rule to remove the \"Applies to all\" flag"+msgstr ""+msgid "Edit Timecard"msgstr "Modifier la feuille de temps"@@ -2896,12 +2911,6 @@ msgstr "Date de fin"msgid "End Time"msgstr "Heure de fin"-msgid "Enforce constraints on receipts, shipments, transfers and job operations for this item."-msgstr "Appliquer des contraintes sur les reçus, les expéditions, les transferts et les opérations de travail pour cet article."--msgid "Enforce per-item validation across receipts, shipments, transfers and adjustments."-msgstr "Appliquer la validation par article sur les reçus, les expéditions, les transferts et les ajustements."-msgid "Enforce per-item validation and guidelines across receipts, shipments, transfers, and adjustments."msgstr "Appliquer la validation et les directives par article dans les reçus, les expéditions, les transferts et les ajustements."@@ -2998,9 +3007,6 @@ msgstr "Erreur lors de la suppression du modèle de la ligne demsgid "Error validating serial number"msgstr "Erreur lors de la validation du numéro de série"-msgid "Errors"-msgstr "Erreurs"-msgid "Escalation"msgstr "Escalade"@@ -3432,6 +3438,9 @@ msgstr "Récupérer"msgid "Field"msgstr "Champ"+msgid "Field info"+msgstr ""+msgid "Field Mapping"msgstr "Mappage des champs"@@ -3758,6 +3767,9 @@ msgstr "Infrastructure"msgid "Inherit From Materials"msgstr "Hériter des matériaux"+msgid "Inherited from"+msgstr ""+msgid "Insert rows"msgstr "Insérer des lignes"@@ -3959,9 +3971,6 @@ msgstr "ID Article"msgid "Item Master"msgstr "Maître d'article"-msgid "Item Rules"-msgstr "Règles d'articles"-msgid "Item Scope"msgstr "Portée des articles"@@ -4321,6 +4330,9 @@ msgstr "Gérez le suivi, le calcul et l'application de la durÃmsgid "Manage Ownership"msgstr "Gérer la propriété"+msgid "Manage rules"+msgstr ""+msgid "Manage Subscription"msgstr "Gérer l'abonnement"@@ -5489,9 +5501,6 @@ msgstr "Sélectionnez un client ou un type de client pour affichmsgid "Pick a date or leave blank to clear it."msgstr "Choisissez une date ou laissez vide pour l'effacer."-msgid "Pick an existing rule from the library or create a new one to start enforcing constraints on this item."-msgstr "Choisissez une règle existante dans la bibliothèque ou créez-en une nouvelle pour commencer àappliquer des contraintes sur cet article."-msgid "Pick List"msgstr "Liste de prélèvement"@@ -6335,9 +6344,6 @@ msgstr "La règle s'applique àchaque article."msgid "Rule Type"msgstr "Type de règle"-msgid "Rule Violation"-msgstr "Violation de règle"-msgid "Rules"msgstr "Règles"@@ -7122,6 +7128,9 @@ msgstr "Types de stockage"msgid "Storage Unit"msgstr "Unité de stockage"+msgid "Storage unit rules"+msgstr ""+msgid "Storage Units"msgstr "Unités de stockage"@@ -7750,6 +7759,9 @@ msgstr "Corbeille"msgid "Trial Balance"msgstr "Balance de vérification"+msgid "Triggers"+msgstr ""+msgid "Tuesday"msgstr "Mardi"@@ -7777,6 +7789,9 @@ msgstr "Les entités non échantillonnÃmsgid "Unapproved Supplier"msgstr "Fournisseur non approuvé"+msgid "Unassign from parent unit to remove"+msgstr ""+msgid "Unassign rule"msgstr "Retirer la règle"@@ -7897,12 +7912,13 @@ msgstr "Mettre àniveau"msgid "Upgrade to Business"msgstr "Passer àBusiness"+#. placeholder {0}: targetCopy.noun+msgid "Upgrade to unlock {0} rules"+msgstr ""+msgid "Upgrade to unlock audit history"msgstr "Passez àla version supérieure pour déverrouiller l'historique d'audit"-msgid "Upgrade to unlock item rules"-msgstr "Passer àla version supérieure pour déverrouiller les règles d'article"-msgid "Upload"msgstr "Télécharger"@@ -8001,6 +8017,9 @@ msgstr "Validation du travail en cours..."msgid "Value"msgstr "Valeur"+msgid "Value source by surface"+msgstr ""+msgid "VAT Number"msgstr "Numéro de TVA"@@ -8190,9 +8209,6 @@ msgstr "Avertir lorsque la personne inspectant un article entrant est la mÃÆmsgid "Warning"msgstr "Avertissement"-msgid "Warnings"-msgstr "Avertissements"-msgid "Watch full video"msgstr "Regarder la vidéo complète"@@ -8253,6 +8269,9 @@ msgstr "Lorsque la durée de vie d'un produit fini est dÃÆmsgid "When expired stock is used"msgstr "Lorsque du stock expiré est utilisé"+msgid "When on, this rule fires for every target of its type. Assignment rows are ignored but preserved."+msgstr ""+msgid "Who Can Approve"msgstr "Qui peut approuver"diff --git a/packages/locale/locales/hi/erp.po b/packages/locale/locales/hi/erp.poindex 548955622c..e45c348623 100644--- a/packages/locale/locales/hi/erp.po+++ b/packages/locale/locales/hi/erp.po@@ -200,9 +200,6 @@ msgstr "संàÂmsgid "Accumulation Period:"msgstr "संचय अवधि:"-msgid "Acknowledge & continue"-msgstr "सà¥ÂÂवीकार करें à¤â€Âर जारी रखें"-msgid "Action Items"msgstr "कारà¥ÂÂय आइटम"@@ -488,6 +485,18 @@ msgstr "आपके Carbon डेटा के लिए प्रोग्रmsgid "Applies to"msgstr "लाà¤â€â€ÃƒÂ ¥‚ होता है"+msgid "Applies to all"+msgstr ""++msgid "Applies to all items"+msgstr ""++msgid "Applies to all storage units"+msgstr ""++msgid "Applies to all work centers"+msgstr ""+msgid "Apply pricing rules"msgstr "मूलà¥ÂÂय निरà¥ÂÂधारण नियम लाà¤â€â€ÃƒÂ ¥‚ करें"@@ -1922,6 +1931,9 @@ msgstr "कसàÂmsgid "Custom Fields"msgstr "कसà¥ÂÂटम फीलà¥ÂÂडà¥ÂÂस"+msgid "Custom Rules"+msgstr ""+msgid "Customer"msgstr "à¤â€â€ÃƒÂ Â¥ÂÂराहक"@@ -2776,6 +2788,9 @@ msgstr "आपàÂmsgid "Edit Supplier Type"msgstr "आपूरà¥ÂÂतिकरà¥ÂÂता पà¥ÂÂरकार संपादित करें"+msgid "Edit the rule to remove the \"Applies to all\" flag"+msgstr ""+msgid "Edit Timecard"msgstr "टाइमकारà¥ÂÂड संपादित करें"@@ -2896,12 +2911,6 @@ msgstr "अंÃÂmsgid "End Time"msgstr "समापà¥ÂÂति समय"-msgid "Enforce constraints on receipts, shipments, transfers and job operations for this item."-msgstr "इस आइटम के लिठरसीदों, शिपमेंट, टà¥ÂÂरांसफर à¤â€Âर जॉब ऑपरेशन पर बाधाà¤ÂÂं लाà¤â€â€ÃƒÂ ¥‚ करें।"--msgid "Enforce per-item validation across receipts, shipments, transfers and adjustments."-msgstr "पà¥ÂÂरतà¥ÂÂयेक आइटम के लिठरसीदों, शिपमेंट, सà¥ÂÂथानांतरण à¤â€Âर समायोजनों में सतà¥ÂÂयापन लाà¤â€â€ÃƒÂ ¥‚ करें।"-msgid "Enforce per-item validation and guidelines across receipts, shipments, transfers, and adjustments."msgstr "रसीदों, शिपमेंट, टà¥ÂÂरांसफर à¤â€Âर समायोजन में पà¥ÂÂरति-आइटम सतà¥ÂÂयापन à¤â€Âर दिशानिरà¥ÂÂदेश लाà¤â€â€ÃƒÂ ¥‚ करें।"@@ -2998,9 +3007,6 @@ msgstr "बिà¤Ãmsgid "Error validating serial number"msgstr "सीरियल नंबर को मानà¥ÂÂय करने में तà¥ÂÂरà¥ÂÂटि"-msgid "Errors"-msgstr "तà¥ÂÂरà¥ÂÂटियाà¤ÂÂ"-msgid "Escalation"msgstr "संवरà¥ÂÂधन"@@ -3432,6 +3438,9 @@ msgstr "लाà¤Ãmsgid "Field"msgstr "कà¥ÂÂषेतà¥ÂÂर"+msgid "Field info"+msgstr ""+msgid "Field Mapping"msgstr "फीलà¥ÂÂड मैपिंà¤â€â€"@@ -3758,6 +3767,9 @@ msgstr "बà¥ÂÂà¤Ãmsgid "Inherit From Materials"msgstr "सामà¤â€â€ÃƒÂ Â¥ÂÂरी से विरासत में पà¥ÂÂरापà¥ÂÂत करें"+msgid "Inherited from"+msgstr ""+msgid "Insert rows"msgstr "पंकà¥ÂÂतियाठसमà¥ÂÂमिलित करें"@@ -3959,9 +3971,6 @@ msgstr "आइÃÂmsgid "Item Master"msgstr "आइटम मासà¥ÂÂटर"-msgid "Item Rules"-msgstr "आइटम नियम"-msgid "Item Scope"msgstr "आइटम सà¥ÂÂकोप"@@ -4321,6 +4330,9 @@ msgstr "शेàÂmsgid "Manage Ownership"msgstr "सà¥ÂÂवामितà¥ÂÂव पà¥ÂÂरबंधित करें"+msgid "Manage rules"+msgstr ""+msgid "Manage Subscription"msgstr "सदसà¥ÂÂयता पà¥ÂÂरबंधित करें"@@ -5489,9 +5501,6 @@ msgstr "उनàÂmsgid "Pick a date or leave blank to clear it."msgstr "à¤ÂÂक तारीख चà¥ÂÂनें या इसे साफ करने के लिठखाली छोड़ें।"-msgid "Pick an existing rule from the library or create a new one to start enforcing constraints on this item."-msgstr "लाइबà¥ÂÂरेरी से à¤ÂÂक मौजूदा नियम चà¥ÂÂनें या इस आइटम पर बाधाà¤ÂÂं लाà¤â€â€ÃƒÂ ¥‚ करना शà¥ÂÂरू करने के लिठà¤ÂÂक नया नियम बनाà¤ÂÂं।"-msgid "Pick List"msgstr "पिक लिसà¥ÂÂट"@@ -6335,9 +6344,6 @@ msgstr "निà¤Ãmsgid "Rule Type"msgstr "नियम पà¥ÂÂरकार"-msgid "Rule Violation"-msgstr "नियम उलà¥ÂÂलंघन"-msgid "Rules"msgstr "नियम"@@ -7122,6 +7128,9 @@ msgstr "सà¥ÂÂà¤Ãmsgid "Storage Unit"msgstr "à¤ÂÂंडारण इकाई"+msgid "Storage unit rules"+msgstr ""+msgid "Storage Units"msgstr "à¤ÂÂंडारण इकाइयाà¤ÂÂ"@@ -7750,6 +7759,9 @@ msgstr "टà¥ÂÂà¤Ãmsgid "Trial Balance"msgstr "टà¥ÂÂरायल बैलेंस"+msgid "Triggers"+msgstr ""+msgid "Tuesday"msgstr "मंà¤â€â€ÃƒÂ ¤²à¤µà¤¾à¤°"@@ -7777,6 +7789,9 @@ msgstr "नमà¥Ãmsgid "Unapproved Supplier"msgstr "अनà¥ÂÂमोदित नहीं आपूरà¥ÂÂतिकरà¥ÂÂता"+msgid "Unassign from parent unit to remove"+msgstr ""+msgid "Unassign rule"msgstr "नियम को अनअसाइन करें"@@ -7897,12 +7912,13 @@ msgstr "अपàÂmsgid "Upgrade to Business"msgstr "बिजनेस में अपà¤â€â€ÃƒÂ Â¥ÂÂरेड करें"+#. placeholder {0}: targetCopy.noun+msgid "Upgrade to unlock {0} rules"+msgstr ""+msgid "Upgrade to unlock audit history"msgstr "ऑडिट इतिहास को अनलॉक करने के लिठअपà¤â€â€ÃƒÂ Â¥ÂÂरेड करें"-msgid "Upgrade to unlock item rules"-msgstr "आइटम नियमों को अनलॉक करने के लिठअपà¤â€â€ÃƒÂ Â¥ÂÂरेड करें"-msgid "Upload"msgstr "अपलोड करें"@@ -8001,6 +8017,9 @@ msgstr "नौàÂÂmsgid "Value"msgstr "मान"+msgid "Value source by surface"+msgstr ""+msgid "VAT Number"msgstr "VAT संखà¥ÂÂया"@@ -8190,9 +8209,6 @@ msgstr "चेàÂmsgid "Warning"msgstr "चेतावनी"-msgid "Warnings"-msgstr "चेतावनियाà¤ÂÂ"-msgid "Watch full video"msgstr "पूरा वीडियो देखें"@@ -8253,6 +8269,9 @@ msgstr "जब àÂÂmsgid "When expired stock is used"msgstr "जब समापà¥ÂÂत हो चà¥ÂÂका सà¥ÂÂटॉक उपयोà¤ किया जाता है"+msgid "When on, this rule fires for every target of its type. Assignment rows are ignored but preserved."+msgstr ""+msgid "Who Can Approve"msgstr "कौन अनà¥ÂÂमोदन कर सकता है"diff --git a/packages/locale/locales/it/erp.po b/packages/locale/locales/it/erp.poindex 595b45d801..47d907798b 100644--- a/packages/locale/locales/it/erp.po+++ b/packages/locale/locales/it/erp.po@@ -200,9 +200,6 @@ msgstr "Periodo di Accumulo (Settimane)"msgid "Accumulation Period:"msgstr "Periodo di Accumulo:"-msgid "Acknowledge & continue"-msgstr "Riconosci e continua"-msgid "Action Items"msgstr "Elementi di azione"@@ -488,6 +485,18 @@ msgstr "Chiavi API per l'accesso programmatico ai tuoi dati Carbon."msgid "Applies to"msgstr "Si applica a"+msgid "Applies to all"+msgstr ""++msgid "Applies to all items"+msgstr ""++msgid "Applies to all storage units"+msgstr ""++msgid "Applies to all work centers"+msgstr ""+msgid "Apply pricing rules"msgstr "Applica regole di prezzo"@@ -1922,6 +1931,9 @@ msgstr "Campo Personalizzato"msgid "Custom Fields"msgstr "Campi Personalizzati"+msgid "Custom Rules"+msgstr ""+msgid "Customer"msgstr "Cliente"@@ -2776,6 +2788,9 @@ msgstr "Modifica processo fornitore"msgid "Edit Supplier Type"msgstr "Modifica Tipo Fornitore"+msgid "Edit the rule to remove the \"Applies to all\" flag"+msgstr ""+msgid "Edit Timecard"msgstr "Modifica Scheda Orario"@@ -2896,12 +2911,6 @@ msgstr "Data di fine"msgid "End Time"msgstr "Ora di fine"-msgid "Enforce constraints on receipts, shipments, transfers and job operations for this item."-msgstr "Applica vincoli su ricevute, spedizioni, trasferimenti e operazioni di lavoro per questo articolo."--msgid "Enforce per-item validation across receipts, shipments, transfers and adjustments."-msgstr "Applica la convalida per articolo su ricevute, spedizioni, trasferimenti e rettifiche."-msgid "Enforce per-item validation and guidelines across receipts, shipments, transfers, and adjustments."msgstr "Applica la convalida per articolo e le linee guida su ricevute, spedizioni, trasferimenti e rettifiche."@@ -2998,9 +3007,6 @@ msgstr "Errore nella rimozione del modello dalla riga dell'ordine di vendita"msgid "Error validating serial number"msgstr "Errore durante la convalida del numero di serie"-msgid "Errors"-msgstr "Errori"-msgid "Escalation"msgstr "Escalation"@@ -3432,6 +3438,9 @@ msgstr "Recupera"msgid "Field"msgstr "Campo"+msgid "Field info"+msgstr ""+msgid "Field Mapping"msgstr "Mappatura campi"@@ -3758,6 +3767,9 @@ msgstr "Infrastruttura"msgid "Inherit From Materials"msgstr "Eredita dai Materiali"+msgid "Inherited from"+msgstr ""+msgid "Insert rows"msgstr "Inserisci righe"@@ -3959,9 +3971,6 @@ msgstr "ID Articolo"msgid "Item Master"msgstr "Anagrafica Articolo"-msgid "Item Rules"-msgstr "Regole Articolo"-msgid "Item Scope"msgstr "Ambito Articolo"@@ -4321,6 +4330,9 @@ msgstr "Gestisci come la durata di conservazione viene tracciata, calcolata e apmsgid "Manage Ownership"msgstr "Gestisci Proprietà"+msgid "Manage rules"+msgstr ""+msgid "Manage Subscription"msgstr "Gestisci Abbonamento"@@ -5489,9 +5501,6 @@ msgstr "Seleziona un cliente o un tipo di cliente per visualizzare i loro prezzimsgid "Pick a date or leave blank to clear it."msgstr "Scegli una data o lascia vuoto per cancellarla."-msgid "Pick an existing rule from the library or create a new one to start enforcing constraints on this item."-msgstr "Seleziona una regola esistente dalla libreria o creane una nuova per iniziare a applicare vincoli su questo articolo."-msgid "Pick List"msgstr "Elenco di prelievo"@@ -6335,9 +6344,6 @@ msgstr "La regola si applica a ogni articolo."msgid "Rule Type"msgstr "Tipo di Regola"-msgid "Rule Violation"-msgstr "Violazione della regola"-msgid "Rules"msgstr "Regole"@@ -7122,6 +7128,9 @@ msgstr "Tipi di Archiviazione"msgid "Storage Unit"msgstr "Unitàdi Stoccaggio"+msgid "Storage unit rules"+msgstr ""+msgid "Storage Units"msgstr "Unitàdi Stoccaggio"@@ -7750,6 +7759,9 @@ msgstr "Cestino"msgid "Trial Balance"msgstr "Bilancia di Verifica"+msgid "Triggers"+msgstr ""+msgid "Tuesday"msgstr "Martedì"@@ -7777,6 +7789,9 @@ msgstr "Le entitànon campionate rimarranno In Sospeso in modomsgid "Unapproved Supplier"msgstr "Fornitore non approvato"+msgid "Unassign from parent unit to remove"+msgstr ""+msgid "Unassign rule"msgstr "Annulla assegnazione regola"@@ -7897,12 +7912,13 @@ msgstr "Aggiorna"msgid "Upgrade to Business"msgstr "Passa a Business"+#. placeholder {0}: targetCopy.noun+msgid "Upgrade to unlock {0} rules"+msgstr ""+msgid "Upgrade to unlock audit history"msgstr "Aggiorna per sbloccare la cronologia di audit"-msgid "Upgrade to unlock item rules"-msgstr "Esegui l'upgrade per sbloccare le regole degli articoli"-msgid "Upload"msgstr "Carica"@@ -8001,6 +8017,9 @@ msgstr "Convalida processo..."msgid "Value"msgstr "Valore"+msgid "Value source by surface"+msgstr ""+msgid "VAT Number"msgstr "Numero IVA"@@ -8190,9 +8209,6 @@ msgstr "Avvisa quando la persona che ispeziona un articolo in entrata Ãmsgid "Warning"msgstr "Avvertenza"-msgid "Warnings"-msgstr "Avvisi"-msgid "Watch full video"msgstr "Guarda il video completo"@@ -8253,6 +8269,9 @@ msgstr "Quando la durata di conservazione di un prodotto finito ÃÂÂmsgid "When expired stock is used"msgstr "Quando viene utilizzato stock scaduto"+msgid "When on, this rule fires for every target of its type. Assignment rows are ignored but preserved."+msgstr ""+msgid "Who Can Approve"msgstr "Chi Può Approvare"diff --git a/packages/locale/locales/ja/erp.po b/packages/locale/locales/ja/erp.poindex 331c2578b0..e08f373587 100644--- a/packages/locale/locales/ja/erp.po+++ b/packages/locale/locales/ja/erp.po@@ -200,9 +200,6 @@ msgstr "è“„ç©ÂÂÃÂmsgid "Accumulation Period:"msgstr "è“„ç©ÂÂ期間:"-msgid "Acknowledge & continue"-msgstr "確èªÂÂãÂÂâ€â€ÃƒÂ£Ã‚¦続行"-msgid "Action Items"msgstr "アクション項目"@@ -488,6 +485,18 @@ msgstr "Carbonデータへのプログラマティックアクセス用のAPIキmsgid "Applies to"msgstr "é©çâ€Â¨å¯¾è±¡"+msgid "Applies to all"+msgstr ""++msgid "Applies to all items"+msgstr ""++msgid "Applies to all storage units"+msgstr ""++msgid "Applies to all work centers"+msgstr ""+msgid "Apply pricing rules"msgstr "価格è¨ÂÂ定ルールをé©çâ€Â¨"@@ -1922,6 +1931,9 @@ msgstr "カスãmsgid "Custom Fields"msgstr "カスタムフィールド"+msgid "Custom Rules"+msgstr ""+msgid "Customer"msgstr "顧客"@@ -2776,6 +2788,9 @@ msgstr "サãƒâ€â€msgid "Edit Supplier Type"msgstr "サãƒâ€â€ÃƒÂ£Ã†â€™Ã‚©Ã£â€šÂ¤Ã£Æ’¤ãƒ¼ã‚¿ã‚¤ãƒâ€â€ÃƒÂ£Ã¢â‚¬Å¡Ã¢â‚¬â„¢ÃƒÂ§Ã‚·Â¨Ã©â€ºâ€ "+msgid "Edit the rule to remove the \"Applies to all\" flag"+msgstr ""+msgid "Edit Timecard"msgstr "タイムカードを編集"@@ -2896,12 +2911,6 @@ msgstr "終了æmsgid "End Time"msgstr "終了時刻"-msgid "Enforce constraints on receipts, shipments, transfers and job operations for this item."-msgstr "ã“ã®アイテムã®領åÂŽ書ã€ÂÂ出è·ã€ÂÂ転é€ÂÂã€ÂÂジョブæ“ÂÂ作ã«対ã™る制約をé©çâ€Â¨ãÂÂâ€â€ÃƒÂ£Ã‚¾ã™。"--msgid "Enforce per-item validation across receipts, shipments, transfers and adjustments."-msgstr "å“ÂÂç›®ãÂÂâ€Âã¨ã®検証を領åÂŽ書ã€ÂÂ出è·ã€ÂÂ転é€ÂÂã€ÂÂãŠよã³調整全体ã«é©çâ€Â¨ãÂÂâ€â€ÃƒÂ£Ã‚¾ã™。"-msgid "Enforce per-item validation and guidelines across receipts, shipments, transfers, and adjustments."msgstr "é ˜åÂŽ書ã€ÂÂ出è·ã€ÂÂ転é€ÂÂã€ÂÂãŠよã³調整全体ã«ã‚ÂÂãŸã£ã¦ã€ÂÂå“ÂÂç›®ãÂÂâ€Âã¨ã®検証ã¨ガイドラインを実施ãÂÂâ€â€ÃƒÂ£Ã‚¾ã™。"@@ -2998,9 +3007,6 @@ msgstr "販売æ³Ãmsgid "Error validating serial number"msgstr "シリアル番å·ã®検証エラー"-msgid "Errors"-msgstr "エラー"-msgid "Escalation"msgstr "エスカレーション"@@ -3432,6 +3438,9 @@ msgstr "å–å¾â€â€"msgid "Field"msgstr "フィールド"+msgid "Field info"+msgstr ""+msgid "Field Mapping"msgstr "フィールドマッãƒâ€Âング"@@ -3758,6 +3767,9 @@ msgstr "インãÃmsgid "Inherit From Materials"msgstr "æÂÂÂÂæ–™ã‹ら継承"+msgid "Inherited from"+msgstr ""+msgid "Insert rows"msgstr "行を挿入"@@ -3959,9 +3971,6 @@ msgstr "アイãmsgid "Item Master"msgstr "アイテムマスター"-msgid "Item Rules"-msgstr "アイテムルール"-msgid "Item Scope"msgstr "アイテムスコーãƒâ€â€"@@ -4321,6 +4330,9 @@ msgstr "棚å¸è³Ãmsgid "Manage Ownership"msgstr "所有権を管ç†"+msgid "Manage rules"+msgstr ""+msgid "Manage Subscription"msgstr "サブスクリãƒâ€â€ÃƒÂ£Ã¢â‚¬Å¡Ã‚·Ã£Æ’§ãƒ³ã‚’管ç†"@@ -5489,9 +5501,6 @@ msgstr "顧客ãÂÂÃmsgid "Pick a date or leave blank to clear it."msgstr "æâ€â€Ã‚¥Ã¤Â»ËœÃ£â€šâ€™Ã©Â¸択ã™るã‹ã€ÂÂ空白ã®ã¾ã¾ã«ãÂÂâ€â€ÃƒÂ£Ã‚¦クリアãÂÂâ€â€ÃƒÂ£Ã‚¦ãÂÂÂÂã ã•ã„。"-msgid "Pick an existing rule from the library or create a new one to start enforcing constraints on this item."-msgstr "ライブラリã‹らæâ€â€Ã‚¢Ã¥Â˜ã®ルールをé¸択ã™るã‹ã€ÂÂæ–°ãÂÂâ€â€ÃƒÂ£Ã‚„ルールを作æˆÂÂãÂÂâ€â€ÃƒÂ£Ã‚¦ã€ÂÂã“ã®アイテムã«対ã™る制約ã®é©çâ€Â¨ã‚’é–‹å§‹ãÂÂâ€â€ÃƒÂ£Ã‚¾ã™。"-msgid "Pick List"msgstr "ãƒâ€Âッã‚ÂÂングリスト"@@ -6335,9 +6344,6 @@ msgstr "ルーãÃmsgid "Rule Type"msgstr "ルールタイãƒâ€â€"-msgid "Rule Violation"-msgstr "ルールé•åÂÂÂÂ"-msgid "Rules"msgstr "ルール"@@ -7122,6 +7128,9 @@ msgstr "ストÃÂmsgid "Storage Unit"msgstr "ä¿ÂÂ管å˜ä½ÂÂ"+msgid "Storage unit rules"+msgstr ""+msgid "Storage Units"msgstr "ä¿ÂÂ管å˜ä½ÂÂ"@@ -7750,6 +7759,9 @@ msgstr "ゴミçÃmsgid "Trial Balance"msgstr "試ç®â€â€ÃƒÂ¨Ã‚¡Â¨"+msgid "Triggers"+msgstr ""+msgid "Tuesday"msgstr "ç«曜æâ€â€Ã‚Â¥"@@ -7777,6 +7789,9 @@ msgstr "未サãÃmsgid "Unapproved Supplier"msgstr "未承èªÂÂサãƒâ€â€ÃƒÂ£Ã†â€™Ã‚©Ã£â€šÂ¤Ã£Æ’¤ãƒ¼"+msgid "Unassign from parent unit to remove"+msgstr ""+msgid "Unassign rule"msgstr "ルールã®割り当ã¦を解除"@@ -7897,12 +7912,13 @@ msgstr "アッÃÂmsgid "Upgrade to Business"msgstr "ビジãƒÂÂスãƒâ€â€ÃƒÂ£Ã†â€™Ã‚©Ã£Æ’³ã«アッãƒâ€â€ÃƒÂ£Ã¢â‚¬Å¡Ã‚°Ã£Æ’¬ãƒ¼ãƒ‰"+#. placeholder {0}: targetCopy.noun+msgid "Upgrade to unlock {0} rules"+msgstr ""+msgid "Upgrade to unlock audit history"msgstr "監査履æÂ´ã®ãƒÂÂックを解除ã™るã«ã¯アッãƒâ€â€ÃƒÂ£Ã¢â‚¬Å¡Ã‚°Ã£Æ’¬ãƒ¼ãƒ‰ãÂÂâ€â€ÃƒÂ£Ã‚¦ãÂÂÂÂã ã•ã„"-msgid "Upgrade to unlock item rules"-msgstr "アイテムルールã®ãƒÂÂックを解除ã™るã«ã¯アッãƒâ€â€ÃƒÂ£Ã¢â‚¬Å¡Ã‚°Ã£Æ’¬ãƒ¼ãƒ‰ãÂÂâ€â€ÃƒÂ£Ã‚¦ãÂÂÂÂã ã•ã„"-msgid "Upload"msgstr "アッãƒâ€â€ÃƒÂ£Ã†â€™Ã‚Âード"@@ -8001,6 +8017,9 @@ msgstr "ジョãÃmsgid "Value"msgstr "値"+msgid "Value source by surface"+msgstr ""+msgid "VAT Number"msgstr "VAT番å·"@@ -8190,9 +8209,6 @@ msgstr "Ã¥ÂÂâ€â€ÃƒÂ£Ã‚‘Ãmsgid "Warning"msgstr "è¦告"-msgid "Warnings"-msgstr "è¦告"-msgid "Watch full video"msgstr "フル動çâ€Â»ã‚’視è´"@@ -8253,6 +8269,9 @@ msgstr "完æˆÂÂÃ¥âmsgid "When expired stock is used"msgstr "期é™ÂÂ切れã®在庫ãÂŒ使çâ€Â¨ã•れる場åˆ"+msgid "When on, this rule fires for every target of its type. Assignment rows are ignored but preserved."+msgstr ""+msgid "Who Can Approve"msgstr "誰ãÂŒ承èªÂÂã§ãÂÂÂÂã‚‹ã‹"diff --git a/packages/locale/locales/pl/erp.po b/packages/locale/locales/pl/erp.poindex b8da1bd0c0..80bceece0f 100644--- a/packages/locale/locales/pl/erp.po+++ b/packages/locale/locales/pl/erp.po@@ -200,9 +200,6 @@ msgstr "Okres akumulacji (tygodnie)"msgid "Accumulation Period:"msgstr "Okres akumulacji:"-msgid "Acknowledge & continue"-msgstr "Potwierdź i kontynuuj"-msgid "Action Items"msgstr "Elementy akcji"@@ -488,6 +485,18 @@ msgstr "Klucze API do programowego dostępu do danych Carbon."msgid "Applies to"msgstr "Dotyczy"+msgid "Applies to all"+msgstr ""++msgid "Applies to all items"+msgstr ""++msgid "Applies to all storage units"+msgstr ""++msgid "Applies to all work centers"+msgstr ""+msgid "Apply pricing rules"msgstr "Zastosuj reguÅ‚y cenowe"@@ -1922,6 +1931,9 @@ msgstr "Pole niestandardowe"msgid "Custom Fields"msgstr "Pola niestandardowe"+msgid "Custom Rules"+msgstr ""+msgid "Customer"msgstr "Klient"@@ -2776,6 +2788,9 @@ msgstr "Edytuj proces dostawcy"msgid "Edit Supplier Type"msgstr "Edytuj typ dostawcy"+msgid "Edit the rule to remove the \"Applies to all\" flag"+msgstr ""+msgid "Edit Timecard"msgstr "Edytuj KartÄ™ Czasu Pracy"@@ -2896,12 +2911,6 @@ msgstr "Data koÅ„cowa"msgid "End Time"msgstr "Czas zakoÅ„czenia"-msgid "Enforce constraints on receipts, shipments, transfers and job operations for this item."-msgstr "Wymuszaj ograniczenia na paragonach, wysyÅ‚kach, transferach i operacjach zadaÅ„ dla tego artykuÅ‚u."--msgid "Enforce per-item validation across receipts, shipments, transfers and adjustments."-msgstr "Wymuszaj walidacjÄ™ dla każdego artykuÅ‚u na paragonach, wysyÅ‚kach, transferach i korektach."-msgid "Enforce per-item validation and guidelines across receipts, shipments, transfers, and adjustments."msgstr "Wymuszaj walidacjÄ™ i wytyczne dla każdej pozycji w paragonach, wysyÅ‚kach, transferach i korektach."@@ -2998,9 +3007,6 @@ msgstr "Błąd podczas usuwaniamsgid "Error validating serial number"msgstr "Błąd podczas walidacji numeru seryjnego"-msgid "Errors"-msgstr "Błędy"-msgid "Escalation"msgstr "Eskalacja"@@ -3432,6 +3438,9 @@ msgstr "Pobierz"msgid "Field"msgstr "Pole"+msgid "Field info"+msgstr ""+msgid "Field Mapping"msgstr "Mapowanie pól"@@ -3758,6 +3767,9 @@ msgstr "Infrastruktura"msgid "Inherit From Materials"msgstr "Dziedzicz z Materiałów"+msgid "Inherited from"+msgstr ""+msgid "Insert rows"msgstr "Wstaw wiersze"@@ -3959,9 +3971,6 @@ msgstr "ID Przedmiotu"msgid "Item Master"msgstr "Główny element"-msgid "Item Rules"-msgstr "ReguÅ‚y pozycji"-msgid "Item Scope"msgstr "Zakres Pozycji"@@ -4321,6 +4330,9 @@ msgstr "ZarzÄ…dzaj sposobem Å›lemsgid "Manage Ownership"msgstr "ZarzÄ…dzaj wÅ‚asnoÅ›ciÄ…"+msgid "Manage rules"+msgstr ""+msgid "Manage Subscription"msgstr "Zarzadzaj subskrypcja"@@ -5489,9 +5501,6 @@ msgstr "Wybierz klienta lub typ klienta, aby wyÅ›wietlimsgid "Pick a date or leave blank to clear it."msgstr "Wybierz datÄ™ lub pozostaw puste pole, aby je wyczyÅ›cić."-msgid "Pick an existing rule from the library or create a new one to start enforcing constraints on this item."-msgstr "Wybierz istniejÄ…cÄ… regułę z biblioteki lub utwórz nowÄ…, aby rozpocząć wymuszanie ograniczeÅ„ na tym elemencie."-msgid "Pick List"msgstr "Lista pobrania"@@ -6335,9 +6344,6 @@ msgstr "ReguÅ‚a dotyczy każdego artykmsgid "Rule Type"msgstr "Typ reguÅ‚y"-msgid "Rule Violation"-msgstr "Naruszenie reguÅ‚y"-msgid "Rules"msgstr "ReguÅ‚y"@@ -7122,6 +7128,9 @@ msgstr "Typy magazynowania"msgid "Storage Unit"msgstr "Jednostka magazynowa"+msgid "Storage unit rules"+msgstr ""+msgid "Storage Units"msgstr "Jednostki magazynowe"@@ -7750,6 +7759,9 @@ msgstr "Kosz"msgid "Trial Balance"msgstr "Bilans Próbny"+msgid "Triggers"+msgstr ""+msgid "Tuesday"msgstr "Wtorek"@@ -7777,6 +7789,9 @@ msgstr "Nieprzetestowane jednostki pozostanÄ… w stanie Wmsgid "Unapproved Supplier"msgstr "Niezatwierdzony dostawca"+msgid "Unassign from parent unit to remove"+msgstr ""+msgid "Unassign rule"msgstr "UsuÅ„ przypisanie reguÅ‚y"@@ -7897,12 +7912,13 @@ msgstr "Uaktualnij"msgid "Upgrade to Business"msgstr "Uaktualnij do Business"+#. placeholder {0}: targetCopy.noun+msgid "Upgrade to unlock {0} rules"+msgstr ""+msgid "Upgrade to unlock audit history"msgstr "Uaktualnij, aby odblokować historiÄ™ audytu"-msgid "Upgrade to unlock item rules"-msgstr "Uaktualnij, aby odblokować reguÅ‚y elementów"-msgid "Upload"msgstr "PrzeÅ›lij"@@ -8001,6 +8017,9 @@ msgstr "Walidacja zadania..."msgid "Value"msgstr "Wartość"+msgid "Value source by surface"+msgstr ""+msgid "VAT Number"msgstr "Numer VAT"@@ -8190,9 +8209,6 @@ msgstr "Ostrzegaj, gdy osoba sprawdzajÄ…ca przychodzÃmsgid "Warning"msgstr "Ostrzeżenie"-msgid "Warnings"-msgstr "Ostrzeżenia"-msgid "Watch full video"msgstr "Obejrzyj peÅ‚ne wideo"@@ -8253,6 +8269,9 @@ msgstr "Gdy okres przydatnoÅ›ci gotowego produktu jest umsgid "When expired stock is used"msgstr "Gdy używany jest wygasÅ‚y zapas"+msgid "When on, this rule fires for every target of its type. Assignment rows are ignored but preserved."+msgstr ""+msgid "Who Can Approve"msgstr "Kto może zatwierdzić"diff --git a/packages/locale/locales/pt/erp.po b/packages/locale/locales/pt/erp.poindex 2ff94b83a4..cdccaf09e5 100644--- a/packages/locale/locales/pt/erp.po+++ b/packages/locale/locales/pt/erp.po@@ -200,9 +200,6 @@ msgstr "PerÃÂÂodo de Acumulaçãomsgid "Accumulation Period:"msgstr "PerÃÂÂodo de Acumulação:"-msgid "Acknowledge & continue"-msgstr "Reconhecer e continuar"-msgid "Action Items"msgstr "Itens de Ação"@@ -488,6 +485,18 @@ msgstr "Chaves de API para acesso programático aos seus dados do Carbon."msgid "Applies to"msgstr "Aplica-se a"+msgid "Applies to all"+msgstr ""++msgid "Applies to all items"+msgstr ""++msgid "Applies to all storage units"+msgstr ""++msgid "Applies to all work centers"+msgstr ""+msgid "Apply pricing rules"msgstr "Aplicar regras de preços"@@ -1922,6 +1931,9 @@ msgstr "Campo Personalizado"msgid "Custom Fields"msgstr "Campos Personalizados"+msgid "Custom Rules"+msgstr ""+msgid "Customer"msgstr "Cliente"@@ -2776,6 +2788,9 @@ msgstr "Editar processo do fornecedor"msgid "Edit Supplier Type"msgstr "Editar Tipo de Fornecedor"+msgid "Edit the rule to remove the \"Applies to all\" flag"+msgstr ""+msgid "Edit Timecard"msgstr "Editar Cartão de Ponto"@@ -2896,12 +2911,6 @@ msgstr "Data Final"msgid "End Time"msgstr "Hora de Término"-msgid "Enforce constraints on receipts, shipments, transfers and job operations for this item."-msgstr "Aplicar restrições em recebimentos, remessas, transferências e operações de trabalho para este item."--msgid "Enforce per-item validation across receipts, shipments, transfers and adjustments."-msgstr "Aplicar validação por item em recebimentos, remessas, transferências e ajustes."-msgid "Enforce per-item validation and guidelines across receipts, shipments, transfers, and adjustments."msgstr "Aplicar validação e diretrizes por item em recebimentos, remessas, transferências e ajustes."@@ -2998,9 +3007,6 @@ msgstr "Erro ao remover modelo da linha de pedido de venda"msgid "Error validating serial number"msgstr "Erro ao validar número de série"-msgid "Errors"-msgstr "Erros"-msgid "Escalation"msgstr "Escalação"@@ -3432,6 +3438,9 @@ msgstr "Buscar"msgid "Field"msgstr "Campo"+msgid "Field info"+msgstr ""+msgid "Field Mapping"msgstr "Mapeamento de Campos"@@ -3758,6 +3767,9 @@ msgstr "Infraestrutura"msgid "Inherit From Materials"msgstr "Herdar de Materiais"+msgid "Inherited from"+msgstr ""+msgid "Insert rows"msgstr "Inserir linhas"@@ -3959,9 +3971,6 @@ msgstr "ID do Item"msgid "Item Master"msgstr "Mestre de Item"-msgid "Item Rules"-msgstr "Regras de Item"-msgid "Item Scope"msgstr "Escopo do Item"@@ -4321,6 +4330,9 @@ msgstr "Gerir como a vida útil é rastreada, camsgid "Manage Ownership"msgstr "Gerenciar Propriedade"+msgid "Manage rules"+msgstr ""+msgid "Manage Subscription"msgstr "Gerenciar Assinatura"@@ -5489,9 +5501,6 @@ msgstr "Selecione um cliente ou tipo de cliente para visualizar seus preÃÆmsgid "Pick a date or leave blank to clear it."msgstr "Escolha uma data ou deixe em branco para limpar."-msgid "Pick an existing rule from the library or create a new one to start enforcing constraints on this item."-msgstr "Escolha uma regra existente da biblioteca ou crie uma nova para começar a aplicar restrições neste item."-msgid "Pick List"msgstr "Lista de Coleta"@@ -6335,9 +6344,6 @@ msgstr "A regra se aplica a todos os itens."msgid "Rule Type"msgstr "Tipo de Regra"-msgid "Rule Violation"-msgstr "Violação de Regra"-msgid "Rules"msgstr "Regras"@@ -7122,6 +7128,9 @@ msgstr "Tipos de Armazenamento"msgid "Storage Unit"msgstr "Unidade de Armazenamento"+msgid "Storage unit rules"+msgstr ""+msgid "Storage Units"msgstr "Unidades de Armazenamento"@@ -7750,6 +7759,9 @@ msgstr "Lixo"msgid "Trial Balance"msgstr "Balancete de Verificação"+msgid "Triggers"+msgstr ""+msgid "Tuesday"msgstr "Terça-feira"@@ -7777,6 +7789,9 @@ msgstr "Entidades não amostradas permanecerãomsgid "Unapproved Supplier"msgstr "Fornecedor Não Aprovado"+msgid "Unassign from parent unit to remove"+msgstr ""+msgid "Unassign rule"msgstr "Desatribuir regra"@@ -7897,12 +7912,13 @@ msgstr "Atualizar"msgid "Upgrade to Business"msgstr "Atualizar para Business"+#. placeholder {0}: targetCopy.noun+msgid "Upgrade to unlock {0} rules"+msgstr ""+msgid "Upgrade to unlock audit history"msgstr "Atualize para desbloquear histórico de auditoria"-msgid "Upgrade to unlock item rules"-msgstr "Atualize para desbloquear regras de item"-msgid "Upload"msgstr "Carregar"@@ -8001,6 +8017,9 @@ msgstr "Validando trabalho..."msgid "Value"msgstr "Valor"+msgid "Value source by surface"+msgstr ""+msgid "VAT Number"msgstr "Número de IVA"@@ -8190,9 +8209,6 @@ msgstr "Avisar quando a pessoa que inspeciona um item de entrada ÃÂmsgid "Warning"msgstr "Aviso"-msgid "Warnings"-msgstr "Avisos"-msgid "Watch full video"msgstr "Assistir vÃÂÂdeo completo"@@ -8253,6 +8269,9 @@ msgstr "Quando a vida útil de um produto acabado ÃÂmsgid "When expired stock is used"msgstr "Quando estoque expirado é utilizado"+msgid "When on, this rule fires for every target of its type. Assignment rows are ignored but preserved."+msgstr ""+msgid "Who Can Approve"msgstr "Quem Pode Aprovar"diff --git a/packages/locale/locales/ru/erp.po b/packages/locale/locales/ru/erp.poindex 5af99a39d8..b605e0934c 100644--- a/packages/locale/locales/ru/erp.po+++ b/packages/locale/locales/ru/erp.po@@ -200,9 +200,6 @@ msgstr "ßõрÃÂÃmsgid "Accumulation Period:"msgstr "ßõрøþô ýðúþÿûõýøÑÂÂ:"-msgid "Acknowledge & continue"-msgstr "ßþôтòõрôøть ø ÿрþôþûöøть"-msgid "Action Items"msgstr "ÃÂÂÂûõüõýты ôõùÑÂÂтòøÑÂÂ"@@ -488,6 +485,18 @@ msgstr "API ключи для программного доступа к вашmsgid "Applies to"msgstr "ßрøüõýÑÂÂõтÑÂÂѠú"+msgid "Applies to all"+msgstr ""++msgid "Applies to all items"+msgstr ""++msgid "Applies to all storage units"+msgstr ""++msgid "Applies to all work centers"+msgstr ""+msgid "Apply pricing rules"msgstr "ßрøüõýÑÂÂть ÿрðòøûð цõýþþñрð÷þòðýøÑÂÂ"@@ -1922,6 +1931,9 @@ msgstr "ßþÃÂȄÅâ€msgid "Custom Fields"msgstr "ßþûь÷þòðтõÃÂȄ΄ÂÂúøõ ÿþÃÂȄÂÂ"+msgid "Custom Rules"+msgstr ""+msgid "Customer"msgstr "Úûøõýт"@@ -2776,6 +2788,9 @@ msgstr "àõôðÃmsgid "Edit Supplier Type"msgstr "àõôðúтøрþòðть тøÿ ÿþÑÂÂтðòщøúð"+msgid "Edit the rule to remove the \"Applies to all\" flag"+msgstr ""+msgid "Edit Timecard"msgstr "àõôðúтøрþòðть тðñõûь учõтð рðñþчõóþ òрõüõýø"@@ -2896,12 +2911,6 @@ msgstr "ÃÂâ€ÂðтÃÂmsgid "End Time"msgstr "Ã’рõüѠþúþýчðýøÑÂÂ"-msgid "Enforce constraints on receipts, shipments, transfers and job operations for this item."-msgstr "ßрøüõýÑÂÂùтõ þóрðýøчõýøѠýð ÿрøхþôы, þтÿрðòúø, ÿõрõôðчø ø þÿõрðцøø ÷ðôðýøù ôÃÂȄʄÂÂтþóþ тþòðрð."--msgid "Enforce per-item validation across receipts, shipments, transfers and adjustments."-msgstr "ÞñõÑÂÂÿõчьтõ òðûøôðцøю ôûѠúðöôþóþ тþòðрð ÿрø ÿþûучõýøø, þтÿрðòúõ, ÿõрõôðчõ ø úþррõúтøрþòúõ."-msgid "Enforce per-item validation and guidelines across receipts, shipments, transfers, and adjustments."msgstr "ÞñõÑÂÂÿõчьтõ òðûøôðцøю ø рõúþüõýôðцøø ôûѠúðöôþóþ тþòðрð ò úòøтðýцøÑÂÂÑ…, þтÿрðòúðх, ÿõрõôðчðх ø úþррõúтøрþòúðх."@@ -2998,9 +3007,6 @@ msgstr "ÞшøÃÂÂÂmsgid "Error validating serial number"msgstr "Þшøñúð ÿрø ÿрþòõрúõ ÑÂÂõрøùýþóþ ýþüõрð"-msgid "Errors"-msgstr "Þшøñúø"-msgid "Escalation"msgstr "ÃÂÂÂÑÂÂúðûðцøÑÂÂ"@@ -3432,6 +3438,9 @@ msgstr "ßþÃÂȄÆâ€msgid "Field"msgstr "ßþûõ"+msgid "Field info"+msgstr ""+msgid "Field Mapping"msgstr "áþÿþÑÂÂтðòûõýøõ ÿþûõù"@@ -3758,6 +3767,9 @@ msgstr "ØýфÑmsgid "Inherit From Materials"msgstr "ÃÂÂÂðÑÂÂûõôþòðть þт üðтõрøðûþò"+msgid "Inherited from"+msgstr ""+msgid "Insert rows"msgstr "ÃÂ’ÑÂÂтðòøть ÑÂÂтрþúø"@@ -3959,9 +3971,6 @@ msgstr "ID тþòÃÂmsgid "Item Master"msgstr "ÜðÑÂÂтõр ÑÂÂûõüõýтð"-msgid "Item Rules"-msgstr "ßрðòøûð тþòðрþò"-msgid "Item Scope"msgstr "ÞñûðÑÂÂть ÿрøüõýõýøѠтþòðрð"@@ -4321,6 +4330,9 @@ msgstr "ãÿрÃÂÃmsgid "Manage Ownership"msgstr "ãÿрðòûõýøõ ÿрðòðüø ÑÂÂþñÑÂÂтòõýýþÑÂÂтø"+msgid "Manage rules"+msgstr ""+msgid "Manage Subscription"msgstr "ãÿрðòûõýøõ ÿþôÿøÑÂÂúþù"@@ -5489,9 +5501,6 @@ msgstr "Ã’ыñÃmsgid "Pick a date or leave blank to clear it."msgstr "Ã’ыñõрøтõ ôðту øûø þÑÂÂтðòьтõ ÿуÑÂÂтыü, чтþñы þчøÑÂÂтøть."-msgid "Pick an existing rule from the library or create a new one to start enforcing constraints on this item."-msgstr "Ã’ыñõрøтõ ÑÂÂущõÑÂÂтòующõõ ÿрðòøûþ ø÷ ñøñûøþтõúø øûø ÑÂÂþ÷ôðùтõ ýþòþõ, чтþñы ýðчðть ÿрøüõýÑÂÂть þóрðýøчõýøѠôÃÂȄʄÂÂтþóþ тþòðрð."-msgid "Pick List"msgstr "áÿøÑÂÂþú ÿþôñþрð"@@ -6335,9 +6344,6 @@ msgstr "ßрðÃÂÃmsgid "Rule Type"msgstr "âøÿ ÿрðòøûð"-msgid "Rule Violation"-msgstr "ÃÂÂÂðрушõýøõ ÿрðòøûð"-msgid "Rules"msgstr "ßрðòøûð"@@ -7122,6 +7128,9 @@ msgstr "âøÿÑââ‚msgid "Storage Unit"msgstr "Õôøýøцð хрðýõýøÑÂÂ"+msgid "Storage unit rules"+msgstr ""+msgid "Storage Units"msgstr "Õôøýøцы хрðýõýøÑÂÂ"@@ -7750,6 +7759,9 @@ msgstr "ÚþрÃÂÃmsgid "Trial Balance"msgstr "ßрþñýыù ñðûðýÑÂÂ"+msgid "Triggers"+msgstr ""+msgid "Tuesday"msgstr "Ã’тþрýøú"@@ -7777,6 +7789,9 @@ msgstr "ÃÂÂÂõþñÃmsgid "Unapproved Supplier"msgstr "ÃÂÂÂõþôþñрõýýыù ÿþÑÂÂтðòщøú"+msgid "Unassign from parent unit to remove"+msgstr ""+msgid "Unassign rule"msgstr "Þтüõýøть ýð÷ýðчõýøõ ÿрðòøûð"@@ -7897,12 +7912,13 @@ msgstr "ÞñýþÃmsgid "Upgrade to Business"msgstr "ßõрõùтø ýð Business"+#. placeholder {0}: targetCopy.noun+msgid "Upgrade to unlock {0} rules"+msgstr ""+msgid "Upgrade to unlock audit history"msgstr "ÞñýþòøтõÑÂÂÑŒ, чтþñы рð÷ñûþúøрþòðть øÑÂÂтþрøю ðуôøтð"-msgid "Upgrade to unlock item rules"-msgstr "ÞñýþòøтõÑÂÂÑŒ, чтþñы рð÷ñûþúøрþòðть ÿрðòøûð ÑÂÂûõüõýтþò"-msgid "Upload"msgstr "ÃÂâ€â€ÃƒÂ°Ã³ру÷øть"@@ -8001,6 +8017,9 @@ msgstr "ßрþÃÂÃmsgid "Value"msgstr "ÃÂâ€â€ÃƒÂ½Ã°чõýøõ"+msgid "Value source by surface"+msgstr ""+msgid "VAT Number"msgstr "ÃÂÂÂþüõр ÃÂÂÂÃÂâ€Âá"@@ -8190,9 +8209,6 @@ msgstr "ßрõÃÂÃmsgid "Warning"msgstr "ßрõôуÿрõöôõýøõ"-msgid "Warnings"-msgstr "ßрõôуÿрõöôõýøÑÂÂ"-msgid "Watch full video"msgstr "áüþтрõть ÿþûýþõ òøôõþ"@@ -8253,6 +8269,9 @@ msgstr "ÚþóôÃmsgid "When expired stock is used"msgstr "Úþóôð øÑÂÂÿþûь÷уõтÑÂÂѠøÑÂÂтõúшøù тþòðр"+msgid "When on, this rule fires for every target of its type. Assignment rows are ignored but preserved."+msgstr ""+msgid "Who Can Approve"msgstr "Úтþ üþöõт þôþñрøть"diff --git a/packages/locale/locales/zh/erp.po b/packages/locale/locales/zh/erp.poindex 5139ba9900..37d582fc33 100644--- a/packages/locale/locales/zh/erp.po+++ b/packages/locale/locales/zh/erp.po@@ -200,9 +200,6 @@ msgstr "累积æœmsgid "Accumulation Period:"msgstr "累积期éâ€â€Ã‚´Ã¯Â¼Å¡"-msgid "Acknowledge & continue"-msgstr "确认并继ç»ÂÂ"-msgid "Action Items"msgstr "æ“ÂÂ作项"@@ -488,6 +485,18 @@ msgstr "用于以编程方式访问您的 Carbon 数据的 API 密钥。"msgid "Applies to"msgstr "适çâ€Â¨äºŽ"+msgid "Applies to all"+msgstr ""++msgid "Applies to all items"+msgstr ""++msgid "Applies to all storage units"+msgstr ""++msgid "Applies to all work centers"+msgstr ""+msgid "Apply pricing rules"msgstr "åºâ€Âçâ€Â¨å®šä»·è§„则"@@ -1922,6 +1931,9 @@ msgstr "自定äÂmsgid "Custom Fields"msgstr "自定义åÂÂâ€â€ÃƒÂ¦Ã‚®Âµ"+msgid "Custom Rules"+msgstr ""+msgid "Customer"msgstr "客户"@@ -2776,6 +2788,9 @@ msgstr "编辑Ãmsgid "Edit Supplier Type"msgstr "编辑供åºâ€Â商类型"+msgid "Edit the rule to remove the \"Applies to all\" flag"+msgstr ""+msgid "Edit Timecard"msgstr "编辑æâ€â€Ã‚¶Ã©â€â€Ã‚´Ã¥Â¡"@@ -2896,12 +2911,6 @@ msgstr "结æÂŸæâmsgid "End Time"msgstr "结æÂŸæâ€â€Ã‚¶Ã©â€â€Ã‚´"-msgid "Enforce constraints on receipts, shipments, transfers and job operations for this item."-msgstr "对æÂ¤项目的æâ€Â¶æÂ®ã€ÂÂå‘货ã€ÂÂ转移和工作æ“ÂÂ作强制执行约æÂŸ。"--msgid "Enforce per-item validation across receipts, shipments, transfers and adjustments."-msgstr "在æâ€Â¶æÂ®ã€ÂÂå‘货ã€ÂÂ转移和调整ä¸ÂÂ强制执行按项目验è¯ÂÂ。"-msgid "Enforce per-item validation and guidelines across receipts, shipments, transfers, and adjustments."msgstr "在æâ€Â¶æÂ®ã€ÂÂå‘货ã€ÂÂ转移和调整ä¸ÂÂ强制执行按项目验è¯ÂÂ和指åÂÂâ€â€ÃƒÂ£Ã¢â€šÂ¬Ã¢â‚¬Å¡"@@ -2998,9 +3007,6 @@ msgstr "从éâ€Âیmsgid "Error validating serial number"msgstr "验è¯ÂÂåºÂÂåˆâ€â€ÃƒÂ¥Ã‚·æâ€â€Ã‚¶Ã¥â€¡ÂºÃ©â€Ââ„¢"-msgid "Errors"-msgstr "éâ€Â™è¯¯"-msgid "Escalation"msgstr "å‡级"@@ -3432,6 +3438,9 @@ msgstr "获å–"msgid "Field"msgstr "Ã¥ÂÂâ€â€ÃƒÂ¦Ã‚®Âµ"+msgid "Field info"+msgstr ""+msgid "Field Mapping"msgstr "Ã¥ÂÂâ€â€ÃƒÂ¦Ã‚®ÂµÃ¦ËœÂ Ã¥Â°â€ž"@@ -3758,6 +3767,9 @@ msgstr "基础èÂmsgid "Inherit From Materials"msgstr "从æÂÂÂÂ料继承"+msgid "Inherited from"+msgstr ""+msgid "Insert rows"msgstr "æÂÂ’入行"@@ -3959,9 +3971,6 @@ msgstr "物å“ÂÂID"msgid "Item Master"msgstr "物料主数æÂ®"-msgid "Item Rules"-msgstr "项目规则"-msgid "Item Scope"msgstr "物å“ÂÂ范围"@@ -4321,6 +4330,9 @@ msgstr "管ç†åÂmsgid "Manage Ownership"msgstr "管ç†所有æÂÂÆ’"+msgid "Manage rules"+msgstr ""+msgid "Manage Subscription"msgstr "管ç†订阅"@@ -5489,9 +5501,6 @@ msgstr "选择Ãmsgid "Pick a date or leave blank to clear it."msgstr "选择æâ€â€Ã‚¥Ã¦Å“Ÿæˆ–留空以清除。"-msgid "Pick an existing rule from the library or create a new one to start enforcing constraints on this item."-msgstr "从库ä¸ÂÂ选择现有规则或创建新规则以开始对æÂ¤项目强制执行约æÂŸ。"-msgid "Pick List"msgstr "拣货å•"@@ -6335,9 +6344,6 @@ msgstr "规则Ãmsgid "Rule Type"msgstr "规则类型"-msgid "Rule Violation"-msgstr "规则è¿ÂÂÃ¥ÂÂÂÂ"-msgid "Rules"msgstr "规则"@@ -7122,6 +7128,9 @@ msgstr "å˜储çÂmsgid "Storage Unit"msgstr "å˜储å•ä½ÂÂ"+msgid "Storage unit rules"+msgstr ""+msgid "Storage Units"msgstr "å˜储å•ä½ÂÂ"@@ -7750,6 +7759,9 @@ msgstr "垃圾æÂmsgid "Trial Balance"msgstr "试ç®â€â€ÃƒÂ¥Ã‚¹Â³Ã¨Â¡Â¡Ã¨Â¡Â¨"+msgid "Triggers"+msgstr ""+msgid "Tuesday"msgstr "星期二"@@ -7777,6 +7789,9 @@ msgstr "未采Ãmsgid "Unapproved Supplier"msgstr "未批准的供åºâ€Â商"+msgid "Unassign from parent unit to remove"+msgstr ""+msgid "Unassign rule"msgstr "å–消分é…ÂÂ规则"@@ -7897,12 +7912,13 @@ msgstr "å‡级"msgid "Upgrade to Business"msgstr "å‡级到商业版"+#. placeholder {0}: targetCopy.noun+msgid "Upgrade to unlock {0} rules"+msgstr ""+msgid "Upgrade to unlock audit history"msgstr "å‡级以解éâ€ÂÂÂ审计历å²"-msgid "Upgrade to unlock item rules"-msgstr "å‡级以解éâ€ÂÂÂ项目规则"-msgid "Upload"msgstr "上传"@@ -8001,6 +8017,9 @@ msgstr "æÂ£在éªmsgid "Value"msgstr "值"+msgid "Value source by surface"+msgstr ""+msgid "VAT Number"msgstr "增值税å·"@@ -8190,9 +8209,6 @@ msgstr "当检ÃÂmsgid "Warning"msgstr "è¦告"-msgid "Warnings"-msgstr "è¦告"-msgid "Watch full video"msgstr "观看完整视频"@@ -8253,6 +8269,9 @@ msgstr "当æˆÂÂÃ¥Ãmsgid "When expired stock is used"msgstr "当使çâ€Â¨è¿‡æœŸåº“å˜æâ€â€Ã‚¶"+msgid "When on, this rule fires for every target of its type. Assignment rows are ignored but preserved."+msgstr ""+msgid "Who Can Approve"msgstr "è°ÂÂå¯以批准"diff --git a/packages/react/src/hooks/useRealtimeChannel.ts b/packages/react/src/hooks/useRealtimeChannel.tsindex 6b83f9fb6e..394d6e0c78 100644--- a/packages/react/src/hooks/useRealtimeChannel.ts+++ b/packages/react/src/hooks/useRealtimeChannel.ts@@ -46,9 +46,10 @@ export const useRealtimeChannel = <TDeps extends any[]>(const channelRef = useRef<RealtimeChannel | null>(null);const isTearingDownRef = useRef(false);const lastErrorToastAtRef = useRef<number>(0);+ const lastErrorToastIdRef = useRef<string | number | null>(null);const retryCountRef = useRef(0);const retryTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);- const isVisibilityReconnectRef = useRef(false);+ const isSilentReconnectRef = useRef(false);// Updated each effect run so the retry timer always calls the latest subscribe closure.const doSubscribeRef = useRef<() => Promise<void>>(() => Promise.resolve());const { carbon, isRealtimeAuthSet } = useCarbon();@@ -112,6 +113,11 @@ export const useRealtimeChannel = <TDeps extends any[]>(configuredChannel.subscribe(async (status, err) => {if (status === REALTIME_SUBSCRIBE_STATES.SUBSCRIBED) {retryCountRef.current = 0;+ // Dismiss any lingering disconnect toast — reconnect succeeded.+ if (lastErrorToastIdRef.current != null) {+ toast.dismiss(lastErrorToastIdRef.current);+ lastErrorToastIdRef.current = null;+ }return;}@@ -122,22 +128,37 @@ export const useRealtimeChannel = <TDeps extends any[]>(if (isRetriableError &¬ifyOnSubscribeError &&- !isVisibilityReconnectRef.current+ !isSilentReconnectRef.current) {- const now = Date.now();- if (now - lastErrorToastAtRef.current > 12_000) {- lastErrorToastAtRef.current = now;- toast.error(`Realtime disconnected (${topic})`, {- description: `${status}: ${formatSubscribeErr(err)}`,- duration: 10_000- });+ // Persistent loading toast — sticks with a spinner until reconnect+ // succeeds. Reuses the same id so repeated CHANNEL_ERRORs don't+ // stack. Underlying error stored in console only; users see a+ // calm "reconnecting" indicator, not an alarming red toast.+ if (err) {+ console.warn(+ `Realtime ${topic} ${status}: ${formatSubscribeErr(err)}`+ );}+ const opts = {+ id: lastErrorToastIdRef.current ?? undefined,+ description: "Trying to reconnect…",+ duration: Number.POSITIVE_INFINITY,+ dismissible: false+ } as const;+ lastErrorToastIdRef.current = toast.loading(+ `Realtime disconnected`,+ opts+ );+ lastErrorToastAtRef.current = Date.now();}if (isRetriableError) {await teardown();- // Exponential backoff: 5s, 10s, 20s, 40s, 60s max- const delay = Math.min(5_000 * 2 ** retryCountRef.current, 60_000);+ // Exponential backoff: 1s, 2s, 5s, 10s, 30s, 60s max — faster+ // recovery on transient blips, still polite at steady state.+ const schedule = [1_000, 2_000, 5_000, 10_000, 30_000, 60_000];+ const delay =+ schedule[Math.min(retryCountRef.current, schedule.length - 1)]!;retryCountRef.current++;retryTimerRef.current = setTimeout(() => {retryTimerRef.current = null;@@ -165,31 +186,39 @@ export const useRealtimeChannel = <TDeps extends any[]>(doSubscribeRef.current = doSubscribe;void doSubscribe();- const handleVisibilityChange = () => {- if (document.visibilityState === "visible") {- // Cancel pending retry and reconnect immediately- if (retryTimerRef.current) {- clearTimeout(retryTimerRef.current);- retryTimerRef.current = null;- }- retryCountRef.current = 0;- isVisibilityReconnectRef.current = true;- void doSubscribeRef.current().finally(() => {- isVisibilityReconnectRef.current = false;- });+ const forceReconnect = (silent: boolean) => {+ if (retryTimerRef.current) {+ clearTimeout(retryTimerRef.current);+ retryTimerRef.current = null;}+ retryCountRef.current = 0;+ isSilentReconnectRef.current = silent;+ void doSubscribeRef.current().finally(() => {+ isSilentReconnectRef.current = false;+ });+ };++ const handleVisibilityChange = () => {+ if (document.visibilityState === "visible") forceReconnect(true);};+ const handleOnline = () => forceReconnect(true);document.addEventListener("visibilitychange", handleVisibilityChange);+ window.addEventListener("online", handleOnline);// Cleanup on unmount or dependency changereturn () => {document.removeEventListener("visibilitychange", handleVisibilityChange);+ window.removeEventListener("online", handleOnline);if (retryTimerRef.current) {clearTimeout(retryTimerRef.current);retryTimerRef.current = null;}retryCountRef.current = 0;+ if (lastErrorToastIdRef.current != null) {+ toast.dismiss(lastErrorToastIdRef.current);+ lastErrorToastIdRef.current = null;+ }void teardown();};}, [diff --git a/packages/utils/src/itemRules.test.ts b/packages/utils/src/customRules.test.tssimilarity index 76%rename from packages/utils/src/itemRules.test.tsrename to packages/utils/src/customRules.test.tsindex e737d3c3f8..87bb3ca32c 100644--- a/packages/utils/src/itemRules.test.ts+++ b/packages/utils/src/customRules.test.ts@@ -1,24 +1,27 @@import { beforeEach, describe, expect, it } from "vitest";import {- __itemRulesCacheSize,- __resetItemRulesCache,+ __customRulesCacheSize,+ __resetCustomRulesCache,+ type CustomRuleRow,compileRule,compileWithCache,evaluateRules,getFieldDef,- type ItemRuleRow,+ getFieldsForTargetType,interpolateMessage,type RuleContext-} from "./itemRules";+} from "./customRules";const ruleOf = (conditions: Array<{ field: string; op: string; value?: unknown }>,- overrides: Partial<ItemRuleRow> = {}-): ItemRuleRow => ({+ overrides: Partial<CustomRuleRow> = {}+): CustomRuleRow => ({id: overrides.id ?? "rule_1",+ targetType: overrides.targetType ?? "item",severity: overrides.severity ?? "error",message: overrides.message ?? "violated",conditionAst: { kind: "all", conditions: conditions as never },+ surfaces: overrides.surfaces,updatedAt: overrides.updatedAt ?? "2026-05-04T00:00:00Z",active: true});@@ -174,7 +177,6 @@ describe("operators", () => {);expect(gt.predicate({ transaction: { quantity: 200 } })).toBe(true);expect(gt.predicate({ transaction: { quantity: 50 } })).toBe(false);- // Non-numeric input: returns false instead of coercingexpect(gt.predicate({ transaction: { quantity: "300" } })).toBe(false);const lt = compileRule(@@ -194,15 +196,13 @@ describe("compilePredicate", () => {{ field: "transaction.kind", op: "eq", value: "receipt" }]));- // Wrap with our own counter — we can't directly observe, but we can assert behavior:- // when first condition false, second is irrelevant.expect(compiled.predicate({item: { type: "Material" },transaction: { kind: "receipt" }})).toBe(false);- secondCondCalls++; // sanity: this assertion runs without invoking second condition due to short-circuit+ secondCondCalls++;expect(secondCondCalls).toBe(1);});@@ -214,6 +214,7 @@ describe("compilePredicate", () => {it("malformed AST → predicate false (defensive)", () => {const compiled = compileRule({id: "x",+ targetType: "item",severity: "error",message: "m",// @ts-expect-error intentionally malformed@@ -246,6 +247,30 @@ describe("compilePredicate", () => {compiled.predicate({ item: { customFields: { frozen: false } } })).toBe(false);});++ it("workCenter + operation root segments resolve", () => {+ const compiled = compileRule(+ ruleOf(+ [+ { field: "workCenter.locationId", op: "eq", value: "loc_a" },+ { field: "operation.itemId", op: "isSet" }+ ],+ { targetType: "workCenter" }+ )+ );+ expect(+ compiled.predicate({+ workCenter: { locationId: "loc_a" },+ operation: { itemId: "item_1" }+ })+ ).toBe(true);+ expect(+ compiled.predicate({+ workCenter: { locationId: "loc_a" },+ operation: { itemId: null }+ })+ ).toBe(false);+ });});describe("interpolateMessage", () => {@@ -298,8 +323,8 @@ describe("evaluateRules", () => {[r1, r2],{item: { name: "Vanilla" },- storageUnit: { storageTypeId: "ambient" }, // fails r1- transaction: { quantity: 2000 } // fails r2 (not less than 1000)+ storageUnit: { storageTypeId: "ambient" },+ transaction: { quantity: 2000 }},"receipt");@@ -330,10 +355,25 @@ describe("evaluateRules", () => {);expect(violations).toEqual([]);});++ it("rule subscribed to surfaces it doesn't include is skipped", () => {+ const r = compileRule(+ ruleOf([{ field: "operation.itemId", op: "isSet" }], {+ targetType: "workCenter",+ surfaces: ["operationStart"]+ })+ );+ const violations = evaluateRules(+ [r],+ { operation: { itemId: null } },+ "operationFinish"+ );+ expect(violations).toEqual([]);+ });});describe("compileWithCache", () => {- beforeEach(() => __resetItemRulesCache());+ beforeEach(() => __resetCustomRulesCache());it("returns same compiled instance on cache hit", () => {const row = ruleOf([{ field: "item.type", op: "eq", value: "Part" }]);@@ -352,11 +392,29 @@ describe("compileWithCache", () => {const a = compileWithCache(row1);const b = compileWithCache(row2);expect(a).not.toBe(b);- expect(__itemRulesCacheSize()).toBe(2);+ expect(__customRulesCacheSize()).toBe(2);+ });++ it("does not collide across targetTypes with identical content", () => {+ // Same id, same AST, same message — different targetType must produce+ // distinct compiled rules. Catches a stale cache key that omits+ // targetType.+ const itemRow = ruleOf([{ field: "item.type", op: "eq", value: "Part" }], {+ id: "shared_id",+ targetType: "item"+ });+ const wcRow = ruleOf([{ field: "item.type", op: "eq", value: "Part" }], {+ id: "shared_id",+ targetType: "workCenter"+ });+ const a = compileWithCache(itemRow);+ const b = compileWithCache(wcRow);+ expect(a).not.toBe(b);+ expect(a.targetType).toBe("item");+ expect(b.targetType).toBe("workCenter");});it("evicts oldest when over cap", () => {- // Fill past CACHE_CAP (256) — assert size never exceeds cap.for (let i = 0; i < 300; i++) {compileWithCache(ruleOf([{ field: "item.type", op: "eq", value: `v${i}` }], {@@ -365,7 +423,7 @@ describe("compileWithCache", () => {}));}- expect(__itemRulesCacheSize()).toBeLessThanOrEqual(256);+ expect(__customRulesCacheSize()).toBeLessThanOrEqual(256);});});@@ -386,6 +444,45 @@ describe("FIELD_REGISTRY", () => {});});+describe("getFieldsForTargetType", () => {+ it("item target sees item + storage + shared fields, not workCenter fields", () => {+ const fields = getFieldsForTargetType("item");+ const paths = fields.map((f) => f.path);+ expect(paths).toContain("item.type");+ expect(paths).toContain("transaction.quantity");+ // storageUnit ctx is loaded for item-target surfaces when the line carries+ // a storageUnitId — these fields are now visible (with nullable: true so+ // authors can guard with isSet/isNotSet).+ expect(paths).toContain("storageUnit.id");+ expect(paths).toContain("storageUnit.locationId");+ expect(paths).toContain("storageUnit.storageTypeId");+ expect(paths.some((p) => p.startsWith("workCenter."))).toBe(false);+ expect(paths.some((p) => p.startsWith("operation."))).toBe(false);+ });++ it("workCenter target sees workCenter + shared, not item.* or storageUnit.*", () => {+ const fields = getFieldsForTargetType("workCenter");+ const paths = fields.map((f) => f.path);+ expect(paths).toContain("workCenter.locationId");+ expect(paths).toContain("workCenter.active");+ expect(paths).toContain("transaction.quantity");+ expect(paths).not.toContain("item.type");+ expect(paths.some((p) => p.startsWith("storageUnit."))).toBe(false);+ });++ it("storageUnit target sees storage + item fields (item ctx loads on every storageUnit-target surface)", () => {+ const fields = getFieldsForTargetType("storageUnit");+ const paths = fields.map((f) => f.path);+ expect(paths).toContain("storageUnit.id");+ expect(paths).toContain("storageUnit.storageTypeId");+ expect(paths).toContain("storageUnit.locationId");+ expect(paths).toContain("transaction.quantity");+ expect(paths).toContain("item.type");+ expect(paths).toContain("item.replenishmentSystem");+ expect(paths).toContain("item.itemTrackingType");+ });+});+describe("required-field pre-check", () => {const coldRule = ruleOf([{ field: "storageUnit.storageTypeId", op: "eq", value: "cold-id" }],@@ -394,10 +491,7 @@ describe("required-field pre-check", () => {it("null field → hard violation, predicate skipped", () => {const compiled = compileRule(coldRule);- // Predicate would PASS if it ran (undefined === "cold-id" is false, so- // normally a violation fires for wrong value — but here storageUnit is- // entirely absent, so required-field check must fire first).- const ctx: RuleContext = {}; // storageUnit undefined+ const ctx: RuleContext = {};const violations = evaluateRules([compiled], ctx, "inventoryAdjustment");expect(violations).toHaveLength(1);expect(violations[0]?.ruleId).toBe("rule_cold");@@ -421,10 +515,9 @@ describe("required-field pre-check", () => {message: "storage type must be set"}));- const ctx: RuleContext = {}; // storageUnit undefined+ const ctx: RuleContext = {};const violations = evaluateRules([rule], ctx, "inventoryAdjustment");expect(violations).toHaveLength(1);- // Must be the rule's own message, not "is required"expect(violations[0]?.message).toBe("storage type must be set");expect(violations[0]?.message).not.toContain("required");});diff --git a/packages/utils/src/itemRules.ts b/packages/utils/src/customRules.tssimilarity index 56%rename from packages/utils/src/itemRules.tsrename to packages/utils/src/customRules.tsindex 55272774f2..12b49e9fc2 100644--- a/packages/utils/src/itemRules.ts+++ b/packages/utils/src/customRules.ts@@ -1,6 +1,11 @@-// Item Rules evaluator. AST → JIT-compiled closure with LRU cache.+// Custom Rules evaluator. AST → JIT-compiled closure with LRU cache.// Used server-side on transactions (receipt, shipment, stock transfer,-// inventory adjustment) to enforce per-item validation/guideline rules.+// inventory adjustment, place, pick, operation start/finish, material+// issue/receive) to enforce per-entity validation/guideline rules.+//+// Each rule binds to a single `TargetType` (`item`, `storageUnit`, or+// `workCenter`). The field registry is partitioned by `targetType` so the+// builder UI only surfaces fields valid for the chosen target.export type Operator =| "eq"@@ -14,6 +19,14 @@ export type Operator =export type Severity = "error" | "warn";+/**+ * Which entity a rule applies to. Drives the field registry slice the+ * builder shows the author, and the assignment table the loader joins.+ * Mirrors the Postgres ENUM `customRuleTargetType`.+ */+export const TARGET_TYPES = ["item", "storageUnit", "workCenter"] as const;+export type TargetType = (typeof TARGET_TYPES)[number];+/*** Transaction surfaces a rule may opt into. Mirrors the Postgres ENUM* `transactionSurface`. After `bun run db:types` regenerates the database@@ -29,10 +42,45 @@ export const TRANSACTION_SURFACES = ["shipment","stockTransfer","warehouseTransfer",- "inventoryAdjustment"+ "inventoryAdjustment",+ "place",+ "pick",+ "operationStart",+ "operationFinish",+ "materialIssue",+ "materialReceive"] as const;export type TransactionSurface = (typeof TRANSACTION_SURFACES)[number];+/**+ * Which surfaces are valid for each target type. The form validator narrows+ * a rule's `surfaces` array against this map; the evaluator skips surfaces+ * a rule didn't subscribe to.+ *+ * Transfer surfaces (`stockTransfer`, `warehouseTransfer`) apply to both+ * `item` and `storageUnit` targets — the integration call sites pass each+ * targetType separately, the engine filters by surface intersection.+ */+export const SURFACES_BY_TARGET_TYPE: Record<+ TargetType,+ readonly TransactionSurface[]+> = {+ item: [+ "receipt",+ "shipment",+ "stockTransfer",+ "warehouseTransfer",+ "inventoryAdjustment"+ ],+ storageUnit: ["place", "pick", "stockTransfer", "warehouseTransfer"],+ workCenter: [+ "operationStart",+ "operationFinish",+ "materialIssue",+ "materialReceive"+ ]+};+export type Condition = {field: string;op: Operator;@@ -61,18 +109,22 @@ export type RuleContext = {item?: Record<string, unknown> & { customFields?: Record<string, unknown> };shelf?: Record<string, unknown>;storageUnit?: Record<string, unknown>;+ workCenter?: Record<string, unknown>;+ operation?: Record<string, unknown>;transaction?: Record<string, unknown>;};-export type ItemRuleRow = {+export type CustomRuleRow = {id: string;+ targetType: TargetType;severity: Severity;message: string;conditionAst: ConditionAst;/*** Surfaces this rule applies to. Empty arrays are not allowed at the DB* level (CHECK constraint); treat missing/empty client-side as "all- * surfaces" for forward-compat with rules created before the migration.+ * surfaces for this targetType" for forward-compat with rules created+ * before the migration.*/surfaces?: TransactionSurface[];updatedAt?: string | null;@@ -81,22 +133,11 @@ export type ItemRuleRow = {export type CompiledRule = {id: string;+ targetType: TargetType;severity: Severity;rawMessage: string;surfaces: TransactionSurface[];- /**- * Raw condition list — kept on the compiled rule so message templates can- * reference `{condition[N].field|operator|value}` at eval time without- * round-tripping back to the AST row.- */conditions: Condition[];- /**- * Pre-bound resolvers for every condition whose op is NOT a presence-aware- * operator (`isSet`/`isNotSet`). Evaluator runs these BEFORE the predicate;- * any null / undefined / empty-string field hit short-circuits the rule- * to a "field is required" violation. Lets authors declare contracts at- * the condition level — referencing a field implies it must be set.- */requiredFieldChecks: {field: string;resolve: (ctx: RuleContext) => unknown;@@ -110,7 +151,14 @@ export type CompiledRule = {type Resolver = (ctx: RuleContext) => unknown;-const ROOT_KEYS = new Set(["item", "shelf", "storageUnit", "transaction"]);+const ROOT_KEYS = new Set([+ "item",+ "shelf",+ "storageUnit",+ "workCenter",+ "operation",+ "transaction"+]);const buildResolver = (path: string): Resolver => {const segments = path.split(".");@@ -133,10 +181,6 @@ const buildResolver = (path: string): Resolver => {const isNullish = (v: unknown): boolean => v === null || v === undefined;-// Array-left helpers: treat the field's resolved array as "any of these-// elements". Lets storage-unit fields with multiple types (e.g.-// `storageUnit.storageTypeId` flattened from `storageTypeIds[]`) participate-// in `eq` / `in` semantics naturally.const eqAnyArrayLeft = (l: unknown[], r: unknown): boolean => {for (let i = 0; i < l.length; i++) if (l[i] === r) return true;return false;@@ -174,8 +218,6 @@ const compileCondition = (cond: Condition): ((ctx: RuleContext) => boolean) => {const op = operatorFns[cond.op];if (!op) return () => false;const value = cond.value;- // Bind everything at compile time. Closure shape is monomorphic per Operator- // (single property access pattern, single equality check), keeping V8 happy.return (ctx) => op(resolve(ctx), value);};@@ -185,7 +227,6 @@ const compilePredicate = (if (!ast || !Array.isArray(ast.conditions)) return () => false;const kind = ast.kind;if (kind !== "all" && kind !== "any" && kind !== "none") return () => false;- // Vacuous-truth handling: empty `all` = true, empty `any`/`none` = false/true.if (ast.conditions.length === 0) {return kind === "all" || kind === "none" ? () => true : () => false;}@@ -206,7 +247,6 @@ const compilePredicate = (return false;};}- // none — no condition may be truereturn (ctx) => {for (let i = 0; i < fns.length; i++) {if (fns[i]!(ctx)) return false;@@ -215,16 +255,19 @@ const compilePredicate = (};};-export const compileRule = (row: ItemRuleRow): CompiledRule => ({+const defaultSurfacesFor = (+ targetType: TargetType+): readonly TransactionSurface[] => SURFACES_BY_TARGET_TYPE[targetType];++export const compileRule = (row: CustomRuleRow): CompiledRule => ({id: row.id,+ targetType: row.targetType,severity: row.severity,rawMessage: row.message,- // Empty / missing → treat as "all surfaces" (backward-compat for rules- // created before the surfaces column existed).surfaces:row.surfaces && row.surfaces.length > 0? row.surfaces- : [...TRANSACTION_SURFACES],+ : [...defaultSurfacesFor(row.targetType)],conditions:row.conditionAst && Array.isArray(row.conditionAst.conditions)? row.conditionAst.conditions@@ -246,9 +289,6 @@ export const compileRule = (row: ItemRuleRow): CompiledRule => ({const CACHE_CAP = 256;const cache = new Map<string, CompiledRule>();-// FNV-1a 32-bit. Cheap, deterministic, no deps. Used to cache-bust on-// content changes even if `updatedAt` is missing/stale (e.g. callers that-// forget to refresh the column on edit).const fnv1a = (s: string): string => {let h = 0x811c9dc5;for (let i = 0; i < s.length; i++) {@@ -258,20 +298,19 @@ const fnv1a = (s: string): string => {return h.toString(36);};-const cacheKey = (row: ItemRuleRow): string => {- // Hash the bits that drive compilation output. If any change, the cached- // CompiledRule (with its baked-in rawMessage + predicate) is stale.+const cacheKey = (row: CustomRuleRow): string => {+ // Hash bits that drive compilation output, including targetType so two+ // rules with identical AST but different targets cannot collide.const contentHash = fnv1a(- `${row.message}|${JSON.stringify(row.conditionAst)}|${(row.surfaces ?? []).join(",")}`+ `${row.targetType}|${row.message}|${JSON.stringify(row.conditionAst)}|${(row.surfaces ?? []).join(",")}`);return `${row.id}:${row.updatedAt ?? ""}:${contentHash}`;};-export const compileWithCache = (row: ItemRuleRow): CompiledRule => {+export const compileWithCache = (row: CustomRuleRow): CompiledRule => {const key = cacheKey(row);const hit = cache.get(key);if (hit) {- // Refresh recency: delete + re-insert so the most-recently-used floats to the end.cache.delete(key);cache.set(key, hit);return hit;@@ -285,24 +324,16 @@ export const compileWithCache = (row: ItemRuleRow): CompiledRule => {return compiled;};-export const __resetItemRulesCache = (): void => {+export const __resetCustomRulesCache = (): void => {cache.clear();};-export const __itemRulesCacheSize = (): number => cache.size;+export const __customRulesCacheSize = (): number => cache.size;// ---------------------------------------------------------------------------// Message interpolation// ----------------------------------------------------------------------------/**- * Token grammar:- * {ctx.dotted.path} — resolved against `RuleContext`- * {condition[N].field|operator|value} — resolved against the rule's AST- *- * Missing/null tokens render as an em-dash so the message stays readable- * when the rule fires precisely because the field is empty.- */const TOKEN_RE =/\{(condition\[\d+\]\.(?:field|operator|value)|[a-zA-Z_][\w.]*)\}/g;@@ -320,14 +351,7 @@ const OPERATOR_LABELS: Record<Operator, string> = {};export type InterpolateMessageOptions = {- /** AST conditions for `{condition[N].…}` tokens. Pass `rule.conditions`. */conditions?: Condition[];- /**- * Optional resolver that turns a condition's stored `value` into a- * human-friendly string (e.g. UUID → display label for `id`-typed- * loaders). Returning `undefined` falls back to a default formatter that- * stringifies scalars and joins arrays with `", "`.- */resolveConditionValue?: (cond: Condition,index: number@@ -358,9 +382,6 @@ export const interpolateMessage = (if (!cond) return "—";switch (prop) {case "field":- // Read the registry at call time — declarations are hoisted by- // the module's eval order, so `getFieldDef` exists by the time- // any rule actually fires.return getFieldDef(cond.field)?.label ?? cond.field;case "operator":return OPERATOR_LABELS[cond.op] ?? cond.op;@@ -385,22 +406,12 @@ export const interpolateMessage = (// ---------------------------------------------------------------------------export type EvaluateRulesOptions = {- /**- * Resolver for `{condition[N].value}` tokens — typically an async-prefilled- * lookup map of `id` → label for loader-backed condition values.- */resolveConditionValue?: (cond: Condition,index: number) => string | undefined;};-/**- * Walk a rule's required-field checks. Returns a label of the FIRST field- * that resolved to null / undefined / empty string, or `null` if every- * required field is populated. Indexed loop, monomorphic resolver call- * site — predicate-style hot path that V8 keeps in IC.- */const findFirstMissingRequiredField = (rule: CompiledRule,ctx: RuleContext@@ -409,8 +420,6 @@ const findFirstMissingRequiredField = (for (let i = 0; i < checks.length; i++) {const c = checks[i]!;const value = c.resolve(ctx);- // Empty array counts as missing — synthetic fields like- // `storageUnit.storageTypeId` resolve to `string[]` from `storageTypeIds[]`.if (value === null ||value === undefined ||@@ -424,7 +433,7 @@ const findFirstMissingRequiredField = (};const buildRequiredFieldMessage = (- rule: CompiledRule,+ _rule: CompiledRule,fieldPath: string): string => {const label = getFieldDef(fieldPath)?.label ?? fieldPath;@@ -441,13 +450,8 @@ export const evaluateRules = (const resolveConditionValue = opts?.resolveConditionValue;for (let i = 0; i < rules.length; i++) {const rule = rules[i]!;- // Surface gate — skip rules that don't opt into this surface before- // touching the predicate. Cheap: 1–4 element array, O(1) in practice.if (!rule.surfaces.includes(surface)) continue;- // Required-field pre-check — referencing a field in a condition implies- // that field is part of the rule's contract. Null → hard violation,- // skip predicate.const missing = findFirstMissingRequiredField(rule, ctx);if (missing !== null) {out.push({@@ -458,7 +462,7 @@ export const evaluateRules = (continue;}- if (rule.predicate(ctx)) continue; // condition satisfied — no violation+ if (rule.predicate(ctx)) continue;out.push({ruleId: rule.id,severity: rule.severity,@@ -475,16 +479,10 @@ export const evaluateRules = (// Field resolver registry — single source of truth for builder UI + evaluator// ----------------------------------------------------------------------------// Pull DB row shapes from the generated Supabase types so the registry stays-// in sync with the schema. Type-only import — no runtime dependency.import type { Database } from "@carbon/database";type Tables = Database["public"]["Tables"];-/**- * Compile-time check: returns `true` if the column type accepts `null`,- * else `false`. Used to verify each `dbField` declares the correct nullability.- */type IsNullable<T> = null extends T ? true : false;type ExpectedNullable<@@ -492,22 +490,47 @@ type ExpectedNullable<C extends keyof Tables[T]["Row"]> = IsNullable<Tables[T]["Row"][C]>;-export type FieldType = "string" | "number" | "enum" | "id";+export type FieldType =+ | "string"+ | "number"+ | "enum"+ | "id"+ /**+ * Special-cased id picker: the rule builder renders a hierarchical+ * (location → drill-down) storage-unit selector instead of a flat combobox.+ * Values stored as the chosen storage unit's UUID.+ */+ | "storageUnit";export type ValueOptionsLoader =| "locations"| "storageTypes"| "itemTypes"| "replenishmentSystems"- | "itemTrackingTypes"- | "itemPostingGroups";+ | "itemTrackingTypes";++export type FieldContext =+ | "item"+ | "storage"+ | "workCenter"+ | "operation"+ | "transaction";export type FieldDef = {path: string;label: string;type: FieldType;operators: Operator[];- context: "item" | "storage" | "transaction";+ context: FieldContext;+ /**+ * Which rule `targetType`(s) may reference this field.+ * - `"shared"` → visible to every targetType (e.g. `transaction.*`)+ * - `TargetType` → visible only to that one targetType+ * - `readonly TargetType[]` → visible to each targetType in the list (e.g.+ * `["item", "storageUnit"]` for storage-unit fields that make sense on+ * both item-target and storageUnit-target rules)+ */+ targetType: TargetType | "shared" | readonly TargetType[];valueOptionsLoader?: ValueOptionsLoader;/*** `true` (default) — column is nullable; `isSet`/`isNotSet` are valid.@@ -515,6 +538,13 @@ export type FieldDef = {* stripped from the available operator list.*/nullable?: boolean;+ /**+ * Human-readable note on where this field's value originates. Surfaced in+ * the rule-builder UI under the field selector so authors understand what+ * they're testing against. Synthetic fields receive their `derivedFrom`+ * string here automatically.+ */+ description?: string;};const PRESENCE_OPS = new Set<Operator>(["isSet", "isNotSet"]);@@ -523,12 +553,8 @@ const SCALAR_OPS: Operator[] = ["eq", "neq", "isSet", "isNotSet"];const ENUM_OPS: Operator[] = ["eq", "neq", "in", "notIn", "isSet", "isNotSet"];const ID_OPS: Operator[] = ["eq", "neq", "in", "notIn", "isSet", "isNotSet"];const NUMBER_OPS: Operator[] = ["eq", "neq", "gt", "lt", "isSet", "isNotSet"];+const BOOL_OPS: Operator[] = ["eq", "neq"];-/**- * Returns the operator subset valid for a field given its DB nullability.- * Strips `isSet`/`isNotSet` when the field is non-nullable — those ops are- * meaningless on a NOT NULL column and would always evaluate to a constant.- */export const availableOperators = (def: FieldDef): Operator[] =>def.nullable === false? def.operators.filter((op) => !PRESENCE_OPS.has(op))@@ -537,19 +563,6 @@ export const availableOperators = (def: FieldDef): Operator[] =>export const isOperatorAllowed = (def: FieldDef, op: Operator): boolean =>availableOperators(def).includes(op);-/**- * Field declaration helpers. Two flavors:- *- * - `fields.database({ table, column, nullable, ... })` — maps 1:1 to a real- * DB column. Nullability is **enforced at compile time** against- * `Database["public"]["Tables"][T]["Row"][C]`. Schema drift = TS error.- * Path is derived as `${ctxKey ?? table}.${column}`.- *- * - `fields.synthetic({ path, derivedFrom, nullable, ... })` — no direct DB- * column (e.g. `transaction.*` is built per-trigger; `item.itemPostingGroupId`- * is denormalised from a join). Nullability is asserted by hand; document- * the runtime source in `derivedFrom`.- */const fields = {database: <T extends keyof Tables,@@ -558,21 +571,25 @@ const fields = {>(args: {table: T;column: C;- nullable: N; // ← must equal ExpectedNullable<T, C> or TS errors+ nullable: N;label: string;type: FieldType;operators: Operator[];- context: FieldDef["context"];+ context: FieldContext;+ targetType: FieldDef["targetType"];ctxKey?: string;valueOptionsLoader?: ValueOptionsLoader;+ description?: string;}): FieldDef => ({path: `${args.ctxKey ?? args.table}.${args.column}`,label: args.label,type: args.type,operators: args.operators,context: args.context,+ targetType: args.targetType,valueOptionsLoader: args.valueOptionsLoader,- nullable: args.nullable+ nullable: args.nullable,+ description: args.description}),synthetic: (args: {@@ -582,7 +599,8 @@ const fields = {label: string;type: FieldType;operators: Operator[];- context: FieldDef["context"];+ context: FieldContext;+ targetType: FieldDef["targetType"];valueOptionsLoader?: ValueOptionsLoader;}): FieldDef => ({path: args.path,@@ -590,13 +608,37 @@ const fields = {type: args.type,operators: args.operators,context: args.context,+ targetType: args.targetType,valueOptionsLoader: args.valueOptionsLoader,- nullable: args.nullable+ nullable: args.nullable,+ description: args.derivedFrom})};+// FIELD_REGISTRY holds ONLY fields the evaluator guarantees in ctx for every+// surface within a given targetType. Fields that may be null or are only+// populated for a subset of surfaces are intentionally excluded — rule+// authors should never write a predicate that silently no-ops on some surface.+//+// Cross-target fields (e.g. storageUnit.* visible to both item + storageUnit+// rules) use the array form of `targetType`. For item-target surfaces the+// storageUnit ctx may be undefined when `line.storageUnitId` is null+// (inventoryAdjustment without a bin, warehouseTransfer with no destination+// yet); we mark such fields `nullable: true` so `availableOperators` exposes+// `isSet`/`isNotSet` and authors can guard explicitly.+//+// Dropped vs. earlier drafts (kept here as audit trail):+// - item.itemPostingGroupId → evaluator SELECT doesn't include the join+// - shelf.locationId → `shelf` is not a RuleContext root key+// - transaction.locationId → sometimes null per surface+// - operation.itemId → null at operationStart (no item bound yet)+// - operation.workInstructionId → may be null on operationsexport const FIELD_REGISTRY: FieldDef[] = [- // ── Item ──────────────────────────────────────────────────────────────────+ // ── Item context (item + storageUnit targets) ─────────────────────────────+ // All storageUnit-target surfaces (place, pick, stockTransfer,+ // warehouseTransfer) carry a `line.itemId`, so the evaluator loads item+ // ctx and these fields resolve. Item DB columns are NOT NULL so no+ // nullable change.fields.database({table: "item",column: "type",@@ -605,6 +647,7 @@ export const FIELD_REGISTRY: FieldDef[] = [type: "enum",operators: ENUM_OPS,context: "item",+ targetType: ["item", "storageUnit"],valueOptionsLoader: "itemTypes"}),fields.database({@@ -615,6 +658,7 @@ export const FIELD_REGISTRY: FieldDef[] = [type: "enum",operators: ENUM_OPS,context: "item",+ targetType: ["item", "storageUnit"],valueOptionsLoader: "replenishmentSystems"}),fields.database({@@ -625,64 +669,110 @@ export const FIELD_REGISTRY: FieldDef[] = [type: "enum",operators: ENUM_OPS,context: "item",+ targetType: ["item", "storageUnit"],valueOptionsLoader: "itemTrackingTypes"}),- fields.synthetic({- path: "item.itemPostingGroupId",- derivedFrom: "itemCost.itemPostingGroupId (denormalised into ctx.item)",- nullable: true,- label: "Item posting group",- type: "id",- operators: ID_OPS,- context: "item",- valueOptionsLoader: "itemPostingGroups"- }),- // ── Storage ───────────────────────────────────────────────────────────────+ // ── StorageUnit context (item + storageUnit targets) ──────────────────────+ // Always loaded by the evaluator for storageUnit-target rules; loaded when+ // `line.storageUnitId` is set for item-target rules. `nullable: true` on+ // every entry so item rules can guard with `isSet`/`isNotSet`.fields.synthetic({- path: "shelf.locationId",- derivedFrom: "storageUnit.locationId via shelfId join (no `shelf` table)",- nullable: false,- label: "Shelf location",- type: "id",- operators: ID_OPS,+ path: "storageUnit.id",+ derivedFrom: "The bin chosen on this transaction line.",+ nullable: true,+ label: "Storage unit",+ // `"storageUnit"` triggers the hierarchical drill-down picker in the+ // rule-builder UI (Location → drilldown). No flat loader needed.+ type: "storageUnit",+ // Drill picker selects a single bin — `in`/`notIn` would require a+ // multi-select UI that doesn't exist. Restrict to scalar ops.+ operators: SCALAR_OPS,context: "storage",- valueOptionsLoader: "locations"+ targetType: ["item", "storageUnit"]}),fields.synthetic({path: "storageUnit.storageTypeId",- derivedFrom: "first element of storageUnit.storageTypeIds[]",+ derivedFrom: "The bin's primary storage type (e.g. cold, hazmat, dry).",nullable: true,label: "Storage type",type: "id",operators: ID_OPS,context: "storage",+ targetType: ["item", "storageUnit"],valueOptionsLoader: "storageTypes"}),- // ── Transaction ───────────────────────────────────────────────────────────- // `transaction` is a synthetic ctx assembled per-trigger (receipt/shipment/- // stock-transfer/job op). No corresponding table — all paths synthetic.+ // Useful for `appliesToAll` rules that want to scope by physical location —+ // e.g. "block pick from any unit in the quarantine warehouse". Declared as+ // synthetic (not database) so `nullable: true` overrides the DB NOT NULL —+ // ctx itself can be undefined for item-target rules when `line.storageUnitId`+ // is null.fields.synthetic({- path: "transaction.locationId",- derivedFrom: "trigger handler — varies by surface",+ path: "storageUnit.locationId",+ derivedFrom:+ "Physical location (warehouse or site) holding the chosen bin.",nullable: true,- label: "Transaction location",+ label: "Storage unit location",type: "id",operators: ID_OPS,- context: "transaction",+ context: "storage",+ targetType: ["item", "storageUnit"],valueOptionsLoader: "locations"}),++ // ── WorkCenter target ─────────────────────────────────────────────────────+ // workCenter is the target — always loaded by the evaluator.+ fields.database({+ table: "workCenter",+ column: "locationId",+ nullable: true,+ label: "Work center location",+ type: "id",+ operators: ID_OPS,+ context: "workCenter",+ targetType: "workCenter",+ valueOptionsLoader: "locations"+ }),+ fields.database({+ table: "workCenter",+ column: "active",+ nullable: false,+ label: "Work center active",+ type: "enum",+ operators: BOOL_OPS,+ context: "workCenter",+ targetType: "workCenter"+ }),++ // ── Transaction (shared across all targets) ───────────────────────────────+ // transaction.quantity is set by every trigger handler. No other transaction+ // field is guaranteed across all surfaces.fields.synthetic({path: "transaction.quantity",- derivedFrom: "line.quantity from receipt/shipment/transfer consumption",+ derivedFrom:+ "Quantity moved or applied by this transaction. Meaning shifts per surface — see per-surface notes below.",nullable: false,label: "Transaction quantity",type: "number",operators: NUMBER_OPS,- context: "transaction"+ context: "transaction",+ targetType: "shared"})];+/**+ * Subset of the registry visible to a rule of a given `targetType`. Includes+ * all fields explicitly declared for that target plus the `shared` set, plus+ * any field whose `targetType` is an array containing the requested target.+ * Builder UI filters its field dropdown through this helper.+ */+export const getFieldsForTargetType = (targetType: TargetType): FieldDef[] =>+ FIELD_REGISTRY.filter((f) => {+ if (f.targetType === "shared") return true;+ if (Array.isArray(f.targetType)) return f.targetType.includes(targetType);+ return f.targetType === targetType;+ });+export const getFieldDef = (path: string): FieldDef | undefined => {// Custom fields are dynamic — accept any item.customFields.* path.if (path.startsWith("item.customFields.")) {@@ -691,8 +781,75 @@ export const getFieldDef = (path: string): FieldDef | undefined => {label: path.slice("item.customFields.".length),type: "string",operators: SCALAR_OPS,- context: "item"+ context: "item",+ targetType: "item",+ description: "Custom field on the item record."};}return FIELD_REGISTRY.find((f) => f.path === path);};++// ---------------------------------------------------------------------------+// Per-surface field semantics+// ---------------------------------------------------------------------------+//+// Some fields carry different meaning depending on which surface fires the+// rule. `transaction.quantity` is the prime example — it's the line qty on a+// receipt, the planned op qty on `operationStart`, the scan delta on+// `operationFinish`, etc. Surface this so rule authors don't write predicates+// that work on one surface and silently misfire on another.++const TRANSACTION_QUANTITY_NOTES: Record<TransactionSurface, string> = {+ receipt: "Quantity received on this receipt line.",+ shipment: "Quantity shipped on this shipment line.",+ stockTransfer: "Quantity moved on this stock-transfer line.",+ warehouseTransfer: "Quantity moved on this warehouse-transfer line.",+ inventoryAdjustment: "Signed delta applied by this adjustment.",+ place: "Quantity placed into the storage unit (= receipt line qty).",+ pick: "Quantity taken from the storage unit (= shipment line qty).",+ operationStart:+ "Planned operation quantity (full target, not a delta this scan).",+ operationFinish: "Quantity completed by this scan (a delta, not cumulative).",+ materialIssue: "Material quantity consumed by this issue.",+ materialReceive: "Material quantity returned to stock."+};++// StorageUnit fields shift meaning between source bin (pick / shipment) and+// destination bin (place / receipt / transfer). On operation surfaces they+// aren't populated at all.+const STORAGE_UNIT_NOTES: Record<TransactionSurface, string> = {+ receipt: "Destination bin (where receiving line lands).",+ shipment: "Source bin (where shipped line was picked from).",+ stockTransfer: "Destination bin (TO storage unit).",+ warehouseTransfer: "Destination bin (TO storage unit).",+ inventoryAdjustment: "Bin the adjustment applies to (may be unset).",+ place: "Destination bin (mirrors receipt).",+ pick: "Source bin (mirrors shipment).",+ operationStart: "Not populated.",+ operationFinish: "Not populated.",+ materialIssue: "Not populated.",+ materialReceive: "Not populated."+};++const SURFACE_FIELD_NOTES: Record<+ string,+ Partial<Record<TransactionSurface, string>>+> = {+ "transaction.quantity": TRANSACTION_QUANTITY_NOTES,+ "storageUnit.id": STORAGE_UNIT_NOTES,+ "storageUnit.locationId": STORAGE_UNIT_NOTES,+ "storageUnit.storageTypeId": STORAGE_UNIT_NOTES+};++/**+ * Per-surface note for a given field path. Returns `undefined` when the field+ * carries the same meaning across every surface it applies to (no clarification+ * needed). Returns a partial map keyed by surface otherwise.+ *+ * Builder UI renders these under the field selector when the user picks a+ * field whose semantics shift between surfaces.+ */+export const getFieldSurfaceNotes = (+ path: string+): Partial<Record<TransactionSurface, string>> | undefined =>+ SURFACE_FIELD_NOTES[path];diff --git a/packages/utils/src/index.ts b/packages/utils/src/index.tsindex 7ee7a2c625..febf7b440a 100644--- a/packages/utils/src/index.ts+++ b/packages/utils/src/index.ts@@ -6,11 +6,11 @@ export * from "./bom";export * from "./color";export * from "./const";export * from "./country";+export * from "./customRules";export * from "./date";export * from "./duration";export * from "./file";export * from "./geo";-export * from "./itemRules";export * from "./items";export * from "./keyboard";export * from "./labels";diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex ed746ae2b4..39b0df770e 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -992,6 +992,9 @@ importers:'@carbon/documents':specifier: workspace:*version: link:../../packages/documents+ '@carbon/ee':+ specifier: workspace:*+ version: link:../../packages/ee'@carbon/form':specifier: workspace:*version: link:../../packages/form